deepspace 0.8.0 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/cli.js +496 -408
- package/dist/cli.js.map +1 -1
- package/package.json +2 -2
- package/dist/testing.d.ts +0 -115
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/cli.ts","../src/cli/lib/spinner.ts","../src/cli/lib/output.ts","../src/cli/lib/cli-format.ts","../src/cli/lib/api.ts","../src/cli/lib/cli-errors.ts","../src/cli/env.ts","../src/cli/auth.ts","../src/cli/jwt.ts","../src/cli/session.ts","../src/cli/lib/command.ts","../src/cli/commands/login.ts","../src/cli/lib/open-browser.ts","../src/cli/commands/logout.ts","../src/cli/lib/app-identity.ts","../src/server/utils/registry-client.ts","../src/cli/commands/dev.ts","../src/cli/lib/app-context.ts","../src/cli/lib/launch-config.ts","../src/cli/lib/dev-vars.ts","../src/cli/lib/app-tokens.ts","../src/server/rooms/binding-manifest.ts","../src/cli/lib/secrets.ts","../src/cli/lib/secure-file.ts","../src/cli/lib/wrangler-env.ts","../src/server/rooms/app-name.ts","../src/cli/lib/install-status.ts","../src/cli/lib/package-manager.ts","../src/cli/lib/preflight.ts","../src/cli/lib/macos-junk.ts","../src/cli/lib/schema-lint.ts","../src/server/schemas/registry.ts","../src/cli/lib/port.ts","../src/cli/commands/kill.ts","../src/cli/commands/test.ts","../src/cli/lib/playwright.ts","../src/cli/commands/screenshot.ts","../src/cli/commands/test-accounts.ts","../src/cli/commands/deploy.ts","../src/cli/commands/deploy/build.ts","../src/cli/commands/deploy/commerce.ts","../src/cli/commands/deploy/output.ts","../src/cli/commands/deploy/request.ts","../src/cli/commands/deploy/repository.ts","../src/cli/lib/git/repository.ts","../src/cli/lib/git/process.ts","../src/cli/lib/git/safety.ts","../src/cli/lib/repo-api.ts","../src/cli/lib/vc-remote.ts","../src/cli/lib/vc-push.ts","../src/cli/lib/workspace-id.ts","../src/cli/commands/deploy/secrets.ts","../src/cli/commands/undeploy.ts","../src/cli/lib/app-target.ts","../src/cli/commands/whoami.ts","../src/cli/commands/apps.ts","../src/cli/commands/logs.ts","../src/shared/log-events.ts","../src/cli/commands/usage.ts","../src/cli/commands/add.ts","../src/cli/commands/feature-installer.ts","../src/cli/commands/domain.ts","../src/cli/commands/collaborators.ts","../src/server/auth/testAccounts.ts","../src/cli/commands/transfer.ts","../src/cli/commands/integrations.ts","../src/cli/commands/_invoke-impl.ts","../src/cli/commands/library.ts","../src/cli/commands/feedback.ts","../src/cli/commands/secrets.ts","../src/cli/lib/citty-args.ts","../src/cli/commands/init.ts","../src/cli/commands/status.ts","../src/cli/commands/push.ts","../src/cli/commands/pull.ts","../src/cli/commands/clone.ts","../src/cli/commands/releases.ts","../src/cli/commands/rollback.ts","../src/cli/commands/workspace.ts","../src/cli/commands/workspace/new.ts","../src/cli/commands/workspace/analysis.ts","../src/cli/commands/workspace/local.ts","../src/cli/commands/workspace/runtime.ts","../src/cli/commands/workspace/attach.ts","../src/cli/commands/workspace/sync.ts","../src/cli/commands/workspace/list.ts","../src/cli/lib/actor-labels.ts","../src/cli/commands/workspace/status.ts","../src/cli/commands/workspace/land.ts","../src/cli/lib/validation.ts","../src/cli/commands/workspace/drop.ts","../src/cli/commands/activity.ts","../src/cli/commands/git-credential.ts"],"sourcesContent":["/**\n * DeepSpace CLI\n *\n * Commands:\n * login — authenticate with your DeepSpace account\n * deploy — build and deploy your app to *.app.space\n * undeploy — remove a deployed app\n * create — redirects to `npm create deepspace`\n */\n\nimport { defineCommand, runMain, runCommand } from 'citty'\n// cross-spawn, not node:child_process: on Windows `npx` is `npx.cmd`, and since\n// Node's CVE-2024-27980 hardening a plain spawn/spawnSync refuses to exec a\n// .cmd (ENOENT / EINVAL) unless shell:true is set — which we won't do (rawArgs\n// would become a shell-injection surface). cross-spawn resolves the shim safely.\nimport { sync as spawnSync } from 'cross-spawn'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { wrapCommandErrors, errorCode } from './lib/cli-errors'\nimport { stopActiveSpinner } from './lib/spinner'\nimport { printAction } from './lib/output'\nimport { DEEPSPACE_ENV } from './env'\nimport login from './commands/login'\nimport logout from './commands/logout'\nimport dev from './commands/dev'\nimport kill from './commands/kill'\nimport test from './commands/test'\nimport screenshot from './commands/screenshot'\nimport testAccounts from './commands/test-accounts'\nimport deploy from './commands/deploy'\nimport undeploy from './commands/undeploy'\nimport whoami from './commands/whoami'\nimport apps from './commands/apps'\nimport logs from './commands/logs'\nimport usage from './commands/usage'\nimport add from './commands/add'\nimport domain from './commands/domain'\nimport collaborators from './commands/collaborators'\nimport transfer from './commands/transfer'\nimport integrations from './commands/integrations'\nimport library from './commands/library'\nimport feedback from './commands/feedback'\nimport secrets from './commands/secrets'\nimport init from './commands/init'\nimport status from './commands/status'\nimport push from './commands/push'\nimport pull from './commands/pull'\nimport clone from './commands/clone'\nimport releases from './commands/releases'\nimport rollback from './commands/rollback'\nimport workspace from './commands/workspace'\nimport activity from './commands/activity'\nimport gitCredential from './commands/git-credential'\n\n// Read own version from package.json so the CLI banner stays in sync with publishes.\n// __dirname of the bundled output is <pkg>/dist; package.json sits one level up.\nconst __dirname = dirname(fileURLToPath(import.meta.url))\nconst pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'))\n\n// workerd doesn't auto-discover system CAs in containers — outbound HTTPS to the\n// auth/api workers fails with \"TLS peer's certificate is not trusted\" until we\n// point it at the standard Debian/Ubuntu cert bundle. Harmless on macOS (path\n// doesn't exist, env var not set).\nif (\n process.platform === 'linux' &&\n !process.env.SSL_CERT_FILE &&\n existsSync('/etc/ssl/certs/ca-certificates.crt')\n) {\n process.env.SSL_CERT_FILE = '/etc/ssl/certs/ca-certificates.crt'\n}\n\nconst create = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a new DeepSpace app (runs create-deepspace; all flags are forwarded)',\n },\n args: {\n name: {\n type: 'positional',\n description: 'App name',\n required: false,\n },\n interactive: {\n type: 'boolean',\n description: 'Prompt for options instead of using defaults',\n },\n template: {\n type: 'string',\n description: 'Starter template (default: starter)',\n },\n local: {\n type: 'string',\n description: 'Use a local SDK monorepo checkout instead of the published package',\n },\n },\n run({ rawArgs }) {\n // Forward EVERY argument verbatim and pin the scaffolder to this CLI's own\n // version — `npm create deepspace@latest` used to drop all flags and could\n // fetch a create-deepspace newer than the running CLI.\n const scaffolder = `create-deepspace@${pkg.version}`\n console.log(`Running: npx ${scaffolder} ${rawArgs.join(' ')}`.trimEnd() + '\\n')\n const res = spawnSync('npx', ['-y', scaffolder, ...rawArgs], { stdio: 'inherit' })\n // Surface a spawn failure instead of exiting silently: with stdio:'inherit'\n // and a spawn error, res.status is null and `?? 1` would swallow the real\n // cause (npx missing from PATH, etc.) behind a bare exit 1.\n if (res.error) {\n const err = res.error as NodeJS.ErrnoException\n console.error(\n `Failed to run \\`npx ${scaffolder}\\`: ${err.message}` +\n (err.code === 'ENOENT' ? '\\nIs Node.js (which provides npx) installed and on PATH?' : ''),\n )\n process.exit(1)\n }\n process.exit(res.status ?? 1)\n },\n})\n\n// ── command groups ──────────────────────────────────────────────────────────\n// Command implementations keep their files; the key is the public name, and\n// the spread re-stamps meta.name so group help renders the full tree.\n\nconst rename = <T extends { meta?: unknown }>(cmd: T, name: string): T =>\n ({ ...cmd, meta: { ...((cmd.meta ?? {}) as Record<string, unknown>), name } }) as T\n\nconst auth = defineCommand({\n meta: { name: 'auth', description: 'Session: login, logout, whoami' },\n subCommands: { login, logout, whoami },\n})\n\nconst app = defineCommand({\n meta: {\n name: 'app',\n description:\n 'The app itself: create, init, list, undeploy, transfer, collaborators, domain, library, usage',\n },\n subCommands: {\n create,\n init,\n list: rename(apps, 'list'),\n undeploy,\n transfer,\n collaborators,\n domain,\n library,\n usage,\n },\n})\n\nconst devGroup = defineCommand({\n meta: { name: 'dev', description: 'Local development' },\n subCommands: { start: rename(dev, 'start'), kill },\n})\nconst testGroup = defineCommand({\n meta: { name: 'test', description: 'App tests and test tooling' },\n subCommands: {\n run: rename(test, 'run'),\n screenshot,\n accounts: rename(testAccounts, 'accounts'),\n },\n})\n\nconst main = defineCommand({\n meta: {\n name: 'deepspace',\n version: pkg.version,\n description: 'DeepSpace SDK CLI',\n },\n subCommands: {\n status,\n activity,\n // Production log tail (arrived from main after the re-tree; a top-level\n // observability verb alongside `activity`, not an `app` subcommand — it\n // is a daily agent verb, and its --follow NDJSON stream is the same\n // documented exception `activity --follow` holds).\n logs,\n push,\n pull,\n clone,\n workspace,\n releases,\n rollback,\n deploy,\n dev: devGroup,\n test: testGroup,\n add,\n secrets,\n integrations,\n auth,\n app,\n feedback,\n 'git-credential': gitCredential,\n },\n // No `run()` here — citty cascades parent run() AFTER subcommand finishes,\n // which corrupts agent-friendly output (`--json`) and prints noise on every\n // command. Citty's default behavior when no subcommand matches is to print\n // help, which is what we want for `deepspace` with no args.\n})\n\n// Escaped errors (API failures, network hiccups) render as one clean line\n// instead of citty's default Error-object dump with a stack trace.\n//\n// For `--json` callers, drive runCommand ourselves: citty validates the argv and\n// throws its own CLIError BEFORE run() executes, so a parse failure (missing\n// required positional like `workspace attach` with no id, unknown command) never\n// reaches a command's own --json catch — runMain would print the human usage\n// page, which a machine consumer can't parse. Convert it into a coded JSON\n// refusal. `--help`/`-h` still goes through runMain so help stays read-only and\n// exits 0 regardless of --json (runCommand would ignore the flag and could run a\n// mutating command); everything else keeps runMain's behavior untouched.\n/** Levenshtein distance, for the did-you-mean hint below. Inputs are command\n * names (short), so the O(n·m) DP is trivially cheap. */\nfunction editDistance(a: string, b: string): number {\n const dp = Array.from({ length: a.length + 1 }, (_, i) => [\n i,\n ...new Array<number>(b.length).fill(0),\n ])\n for (let j = 1; j <= b.length; j++) dp[0][j] = j\n for (let i = 1; i <= a.length; i++) {\n for (let j = 1; j <= b.length; j++) {\n dp[i][j] = Math.min(\n dp[i - 1][j] + 1,\n dp[i][j - 1] + 1,\n dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),\n )\n }\n }\n return dp[a.length][b.length]\n}\n\nfunction closestCommand(input: string, candidates: string[]): string | null {\n let best: string | null = null\n let bestDist = 4 // farther than 3 edits is a different word, not a typo\n for (const c of candidates) {\n const d = editDistance(input.toLowerCase(), c)\n if (d < bestDist) {\n best = c\n bestDist = d\n }\n }\n return best\n}\n\n/**\n * Fail-fast unknown-command guard for the HUMAN path. citty's default for an\n * unknown (sub)command is to print usage and exit 0 — which lets a script or\n * agent driving a stale command surface read a typo as success. The --json\n * path already converts citty's E_UNKNOWN_COMMAND into a coded exit-1\n * refusal; this makes the exit-code contract uniform for everyone else.\n *\n * Walks the static subcommand tables only while tokens look like command\n * names: the first flag ends the walk (citty may still resolve a subcommand\n * placed after flags — that arrangement just isn't pre-checked), and a\n * command without subCommands consumes the rest of argv as its own args.\n */\nfunction assertKnownCommandPath(argv: string[]): void {\n let table: Record<string, unknown> | undefined = main.subCommands as Record<string, unknown>\n let path = 'deepspace'\n for (const tok of argv) {\n if (!table || tok.startsWith('-')) return\n const entry: unknown = table[tok]\n if (!entry) {\n const hint = closestCommand(tok, Object.keys(table))\n console.error(\n `Unknown command: ${path} ${tok}${hint ? ` — did you mean \\`${path} ${hint}\\`?` : ''}\\n` +\n `Run \\`${path} --help\\` for the command list.`,\n )\n if (hint) {\n printAction({ cwd: process.cwd(), argv: [...path.split(' '), hint] })\n }\n process.exit(1)\n }\n path += ` ${tok}`\n table = (entry as { subCommands?: Record<string, unknown> }).subCommands\n }\n}\n\nconst rawArgs = process.argv.slice(2)\nconst wantsHelp = rawArgs.some((arg) => arg === '--help' || arg === '-h')\nif (DEEPSPACE_ENV === 'invalid') {\n const error =\n `Invalid DEEPSPACE_ENV=${JSON.stringify(process.env.DEEPSPACE_ENV)}. ` +\n 'Use `staging`, `production`, or unset it; refusing to default to production.'\n if (rawArgs.includes('--json') && !wantsHelp) {\n console.log(JSON.stringify({ ok: false, code: 'invalid_environment', error }))\n } else {\n console.error(error)\n }\n process.exit(1)\n}\nif (rawArgs.includes('--json') && !wantsHelp) {\n const first = rawArgs.find((a) => !a.startsWith('-'))\n // Unknown top-level command: give the MACHINE caller the same did-you-mean\n // the human path gets — the consumer that most needs it. (Deeper paths fall\n // through to citty's E_UNKNOWN_COMMAND mapping below.)\n if (first && !Object.prototype.hasOwnProperty.call(main.subCommands ?? {}, first)) {\n const hint = closestCommand(first, Object.keys(main.subCommands ?? {}))\n console.log(\n JSON.stringify({\n ok: false,\n code: 'unknown_command',\n error: `Unknown command: deepspace ${first}${hint ? ` — did you mean \\`deepspace ${hint}\\`?` : ''}`,\n ...(hint ? { action: { cwd: process.cwd(), argv: ['deepspace', hint] } } : {}),\n }),\n )\n process.exit(1)\n }\n runCommand(wrapCommandErrors(main), { rawArgs }).catch((err) => {\n stopActiveSpinner()\n // citty's CLIError carries a `.code` per condition; map each to its own\n // stable slug (EARG = a missing/invalid positional or flag). A genuinely\n // escaped run() error is already handled by wrapCommandErrors → renderCliError\n // and exits before this catch, so the errorCode() branch only guards the\n // rare non-citty throw that reaches here.\n const cittyCode =\n err instanceof Error && err.name === 'CLIError' ? (err as { code?: string }).code : undefined\n const code =\n cittyCode === 'EARG'\n ? 'missing_argument'\n : cittyCode === 'E_UNKNOWN_COMMAND'\n ? 'unknown_command'\n : cittyCode === 'E_NO_COMMAND'\n ? 'no_command'\n : errorCode(err)\n // citty colorizes some messages (cyan) and its no-color check ignores a\n // non-TTY stdout, so strip ANSI before it lands in the machine-read string.\n const message = (err instanceof Error ? err.message : String(err)).replace(\n // eslint-disable-next-line no-control-regex\n /\\u001b\\[[0-9;]*m/g,\n '',\n )\n console.log(JSON.stringify({ ok: false, error: message, ...(code ? { code } : {}) }))\n process.exit(1)\n })\n} else {\n // `--help` stays exempt so help probes remain read-only.\n if (!wantsHelp) assertKnownCommandPath(rawArgs)\n runMain(wrapCommandErrors(main))\n}\n","import * as p from '@clack/prompts'\n\nexport interface Spinner {\n start: (msg?: string) => void\n stop: (msg?: string) => void\n message: (msg?: string) => void\n}\n\n// The spinner currently painting the terminal, if any. On Windows a live\n// @clack/prompts spinner registers a `process.on('exit')` handler that writes\n// a final frame to the TTY; calling process.exit() while it is still running\n// makes that write land as libuv tears the TTY handle down —\n// `Assertion failed: !(handle->flags & UV_HANDLE_CLOSING)` — turning a clean\n// exit(1) into an abort. Tracking the active spinner lets error helpers stop it\n// (which clears the interval and neuters that exit handler) before they exit.\nlet activeSpinner: Spinner | null = null\n\n// In a real terminal, @clack/prompts repaints the spinner by writing `\\r`\n// to overwrite the previous frame. In non-TTY contexts (agents, CI logs,\n// pipes, `tee`-ed output) `\\r` does nothing and every frame becomes a new\n// line — a single long phase floods the log with thousands of repeats.\n// When stdout is not a TTY we fall back to one static line per phase.\nexport function createSpinner(): Spinner {\n const impl: Spinner = process.stdout.isTTY\n ? p.spinner()\n : {\n start: (msg?: string) => { if (msg) console.log(msg) },\n stop: (msg?: string) => { if (msg) console.log(msg) },\n message: (msg?: string) => { if (msg) console.log(msg) },\n }\n const wrapper: Spinner = {\n start: (msg?: string) => {\n activeSpinner = wrapper\n impl.start(msg)\n },\n stop: (msg?: string) => {\n impl.stop(msg)\n if (activeSpinner === wrapper) activeSpinner = null\n },\n message: (msg?: string) => impl.message(msg),\n }\n return wrapper\n}\n\n/**\n * Stop whatever spinner is currently painting, if any. Call before\n * process.exit() on an error path so a live spinner never tears down mid-write\n * (see activeSpinner above). Idempotent and safe when nothing is active.\n */\nexport function stopActiveSpinner(): void {\n activeSpinner?.stop()\n}\n","/**\n * The output contract (docs: agent-experience standard).\n *\n * Agents read text: the human output is the interface and must be complete.\n * These helpers standardize its two optional machine anchors —\n *\n * 1. a refusal's final line carries its slug: `…message. [non_fast_forward]`\n * 2. when a command owns one safe follow-up, its final line names it:\n * `Next: deepspace pull`\n *\n * `--json` mirrors them (`code`, `action: { cwd, argv }`) but is never the primary\n * surface. Exit codes stay load-bearing: 0 done, 1 failed, 2 succeeded with\n * a local step remaining.\n */\n\nimport * as p from '@clack/prompts'\nimport { isAbsolute } from 'node:path'\nimport { shQuote } from './cli-format'\n\n/** One executable recovery step. Commands decide which action is appropriate;\n * the runtime only transports and renders it. */\nexport interface CliAction {\n cwd: string\n argv: string[]\n}\n\n/** Construct an action without turning argv back into a shell program. */\nexport function cliAction(...argv: string[]): CliAction {\n const action = { cwd: process.cwd(), argv }\n assertExecutableAction(action)\n return action\n}\n\n/** Reject action-shaped hints that an agent cannot execute verbatim. */\nexport function assertExecutableAction(action: CliAction): void {\n if (!isAbsolute(action.cwd)) throw new TypeError('CLI action cwd must be absolute')\n if (action.argv.length === 0 || action.argv[0].trim() === '') {\n throw new TypeError('CLI action argv must name an executable')\n }\n if (action.argv.some((arg) => /^<[^<>]+>$/.test(arg))) {\n throw new TypeError('CLI action argv must not contain placeholder tokens')\n }\n}\n\n/** Suffix a refusal message with its machine slug, last line only. Idempotent\n * (a message already carrying `[slug]` at the end is left alone) so wrapper\n * layers can apply it without double-tagging. */\nexport function withSlug(msg: string, code: string): string {\n const tag = `[${code}]`\n return msg.trimEnd().endsWith(tag) ? msg : `${msg.trimEnd()} ${tag}`\n}\n\nfunction displayArg(arg: string): string {\n return /^[A-Za-z0-9_./:@%+=,-]+$/.test(arg) ? arg : shQuote(arg)\n}\n\n/** Render the same structured action exposed to agents as a copy-pasteable\n * human command. The shell string is presentation only, never machine data. */\nexport function printAction(action: CliAction): void {\n assertExecutableAction(action)\n const command = action.argv.map(displayArg).join(' ')\n const prefix = action.cwd === process.cwd() ? '' : `cd ${displayArg(action.cwd)} && `\n p.log.message(`Next: ${prefix}${command}`)\n}\n","/** POSIX single-quote a string for safe interpolation into a human-facing\n * \"run this\" command. Never use the result as a machine contract — that's\n * what structured {cwd, argv} is for. */\nexport function shQuote(s: string): string {\n return `'${s.replace(/'/g, \"'\\\\''\")}'`\n}\n\n/** Render argv as a copy-pasteable human command. */\nexport function humanCommand(argv: readonly string[]): string {\n return argv.map((arg) => (/^[A-Za-z0-9_./=:@-]+$/.test(arg) ? arg : shQuote(arg))).join(' ')\n}\n","/**\n * Authenticated JSON fetch against a platform worker.\n *\n * Shared by the CLI commands that call the platform as the logged-in user\n * (`domain`, `feedback`, `collaborators`, `transfer`, …). Sends a Bearer\n * token, parses the JSON body, and on a non-2xx response throws an ApiError\n * carrying the worker's `{ error, code }` — message for display, code for\n * branching — so callers never string-sniff error text.\n */\nexport class ApiError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly code?: string,\n /** Internal REST path — kept off the message (DEBUG-only rendering). */\n readonly apiPath?: string,\n ) {\n super(message)\n }\n}\n\n/**\n * Registered by auth.ts at load: force-mint a fresh JWT from the stored\n * session, bypassing the cached token file. Lets apiFetch heal a 401 whose\n * cause is a token that is locally \"valid\" but rejected server-side (signing-\n * key rotation, revocation) with one silent refresh + retry instead of a hard\n * error an agent has to reason about. Null ⇒ the session itself is dead and\n * the original 401 stands. A callback (not an import) so this low-level\n * module stays dependency-free of auth.ts.\n */\nlet refreshAuthToken: (() => Promise<string | null>) | null = null\nexport function registerAuthRefresh(fn: () => Promise<string | null>): void {\n refreshAuthToken = fn\n}\n\nexport async function apiFetch<T>(\n baseUrl: string,\n token: string,\n path: string,\n init?: RequestInit,\n isRetry = false,\n): Promise<T> {\n let res: Response\n let text: string\n try {\n res = await fetch(`${baseUrl}${path}`, {\n ...init,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n ...(init?.headers ?? {}),\n },\n })\n // One transparent recovery per request. Safe for mutations too: every\n // repo-API mutation is idempotency-keyed, and the 401 means the server\n // never acted. Requires a NEW token — retrying the same rejected bearer\n // would just double the failure latency.\n if (res.status === 401 && !isRetry && refreshAuthToken) {\n const fresh = await refreshAuthToken()\n if (fresh && fresh !== token) return apiFetch<T>(baseUrl, fresh, path, init, true)\n }\n text = await res.text()\n } catch (err) {\n // A network-level failure (connection refused, DNS, TLS, offline) throws a\n // TypeError('fetch failed'), not an HTTP status — give it a stable code so a\n // --json caller can classify the transport outage instead of scraping prose.\n throw new ApiError(\n `Could not reach the deploy service at ${baseUrl}: ${err instanceof Error ? err.message : String(err)}. Check your connection (and DEEPSPACE_DEPLOY_URL), then retry.`,\n 0,\n 'network_error',\n path,\n )\n }\n if (!res.ok) {\n let msg = text\n let code: string | undefined\n try {\n const body = JSON.parse(text) as { error?: string; code?: string }\n msg = body.error ?? text\n code = body.code\n } catch {\n // not JSON\n }\n // A bare router 404 (\"Not found\", no server code) means DEEPSPACE_DEPLOY_URL\n // points at a service that doesn't host the repo API (wrong/old URL). Give it\n // an actionable message + code UNIFORMLY for every caller (incl. rollback's\n // direct endpoint), so a --json agent gets one stable slug for this case.\n if (!code && res.status === 404 && text.trim() === 'Not found') {\n code = 'unrecognized_service'\n msg = `The deploy service at ${baseUrl} doesn't recognize this request — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?); if it is, the server may be older than this CLI.`\n }\n // Any other server error that supplied no `code` of its own (a non-conforming\n // 5xx, an HTML error page) still needs a stable slug to classify.\n code = code ?? (res.status >= 500 ? 'server_error' : 'http_error')\n // Message = the server's sentence only. The internal REST path and raw\n // status read like a stack trace to users (same treatment as secretsApi);\n // they stay on the error's fields for DEBUG rendering and branching.\n throw new ApiError(msg || `Request failed (${res.status})`, res.status, code, path)\n }\n if (!text) return {} as T\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n // A 2xx with a non-JSON body isn't the repo API — code it so a --json caller\n // doesn't get a bare SyntaxError.\n throw new ApiError(\n `The deploy service at ${baseUrl} returned a malformed (non-JSON) response — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n res.status,\n 'invalid_response',\n path,\n )\n }\n // Every repo-API response is a JSON object; a null/array/primitive 2xx body is a\n // wrong/broken service — reject it with a code instead of letting a caller\n // destructure null and crash uncoded.\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new ApiError(\n `The deploy service at ${baseUrl} returned an unexpected response shape — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n res.status,\n 'invalid_response',\n path,\n )\n }\n return parsed as T\n}\n","/**\n * Friendly rendering for errors that escape a command's run().\n *\n * citty's runMain catches escaped errors and console.errors the full Error\n * object — stack trace and all. For expected operational failures (an API\n * 403, a network hiccup) that reads like a crash. wrapCommandErrors()\n * recursively wraps every command's run() so escaped errors render as a\n * single clean message (with known API error slugs translated), while\n * citty's own help/version/usage handling stays untouched. Set DEBUG=1 to\n * get the full stack back.\n */\n\nimport type { CommandDef } from 'citty'\nimport { stopActiveSpinner } from './spinner'\nimport { withSlug } from './output'\nimport { ApiError } from './api'\n\n/**\n * A client-side or precondition failure that carries a machine `code`, so a\n * thrown error (a blank `--app`, \"not logged in\", an empty repo) reads in\n * `--json` exactly like a server ApiError — `{ ok:false, code, error }` — rather\n * than a bare message. Reuses no HTTP semantics (unlike ApiError). Most instances\n * are pure client-side validation that never touch the network; a few are\n * preconditions checked before the real work (e.g. an expired session, detected\n * after a refresh attempt) — the shared contract is only \"carries a stable code\".\n */\nexport class InputError extends Error {\n constructor(\n message: string,\n readonly code: string,\n ) {\n super(message)\n }\n}\n\n/**\n * The machine `code` slug an error carries, if any — an {@link ApiError} (server\n * failure) or an {@link InputError} (client-side validation). Lets a command's\n * `--json` catch surface `code` uniformly without knowing the concrete type.\n * Deliberately narrow: it does NOT read arbitrary `.code` properties (a Node\n * `ENOENT` fs error must not leak into the machine contract as a `code`).\n */\nexport function errorCode(err: unknown): string | undefined {\n if (err instanceof ApiError || err instanceof InputError) return err.code\n // GitError (raw git operation/transport failure) — duck-typed by `name` to\n // avoid a cli-errors↔git import cycle. Give it a generic `git_error` (or its\n // own slug, if set) so a --json caller can branch on \"a git op failed\"\n // instead of scraping the fatal-… prose.\n if (err instanceof Error && err.name === 'GitError') return (err as { code?: string }).code ?? 'git_error'\n return undefined\n}\n\n/**\n * API error slugs that genuinely confuse people → what to tell them. Slugs\n * whose meaning is obvious from the name (invalid_email, ...) stay unmapped\n * and render as-is; don't grow this into a mirror of the server's errors.\n */\nconst API_ERROR_HINTS: Record<string, string> = {\n not_app_owner: 'Only the app owner can do this.',\n app_not_found:\n 'App not found on the service this command asked. Check the app id — the DEEPSPACE_APP_ID ' +\n 'value in wrangler.toml, usually `app_…` (a legacy app\\'s id is its name); list your apps ' +\n 'with `deepspace app list`. If you are overriding DEEPSPACE_DEPLOY_URL (staging), note that ' +\n 'account/collaborator commands go to the PLATFORM API — an app registered only on a staging ' +\n 'deploy service is unknown there. (`domain` commands take the deployed app *name* instead.)',\n not_app_owner_or_collaborator: 'You must be the app owner or a collaborator to do this.',\n test_account_cannot_be_collaborator:\n 'Test accounts cannot be added as collaborators. Use a real DeepSpace account.',\n user_not_found:\n 'No DeepSpace user with that email. They need to log in to DeepSpace at least once ' +\n '(`deepspace auth login`, or sign in to any app) before they can be referenced by email.',\n insufficient_credits:\n 'Out of credits. Inviting a new collaborator by email sends them a transactional ' +\n 'email billed to your account — top up your credits and try again.',\n invite_email_failed:\n 'The invite email could not be sent. You were not charged — please try again in a moment.',\n}\n\n/** Exported for tests. One clean message for an escaped error. */\nexport function formatCliError(err: unknown): string {\n const message = err instanceof Error ? err.message : String(err)\n // The platform returns { error: <sentence>, code: <slug> }, and apiFetch\n // preserves that code on a typed error. Never infer machine state from prose.\n const slug = errorCode(err)\n const hint = slug ? API_ERROR_HINTS[slug] : undefined\n // The server sentence and the hint can say the same thing — don't stutter.\n return hint && !message.includes(hint) ? `${message}\\n${hint}` : message\n}\n\nexport function renderCliError(err: unknown): never {\n // A command may throw with its progress spinner still live; stop it before\n // the process.exit below so the exit can't abort on Windows (see spinner.ts).\n stopActiveSpinner()\n const message = formatCliError(err)\n const slug = errorCode(err)\n // `--json` callers get the envelope every other refusal path emits. Without\n // this, an error that ESCAPES a command's own try/catch printed prose to\n // stderr and left stdout EMPTY — a machine consumer saw a non-zero exit with\n // nothing to parse. Commands that catch their own errors are unaffected;\n // this is the fallback for the ~15 that don't.\n if (process.argv.includes('--json')) {\n console.log(JSON.stringify({ ok: false, ...(slug ? { code: slug } : {}), error: message }))\n process.exit(1)\n }\n // Human path: the last line carries the machine slug, per the output\n // contract (lib/output.ts).\n console.error(slug ? withSlug(message, slug) : message)\n if (process.env.DEBUG) {\n // ApiError/secretsApi keep the internal REST path off the message; show it here.\n const { apiPath, status } = err as { apiPath?: string; status?: number }\n if (apiPath) console.error(`\\nAPI ${apiPath}${status ? ` (${status})` : ''}`)\n if (err instanceof Error && err.stack) console.error('\\n' + err.stack)\n }\n process.exit(1)\n}\n\ntype RunFn = NonNullable<CommandDef['run']>\n\n/**\n * Recursively wrap a concrete command tree's run() handlers. Only plain\n * object subcommands are wrapped — every command in this CLI is one; lazy\n * (function/promise) subcommand definitions would pass through unwrapped.\n */\nexport function wrapCommandErrors<T extends CommandDef>(cmd: T): T {\n const run = cmd.run\n if (run) {\n cmd.run = (async (ctx: Parameters<RunFn>[0]) => {\n try {\n await run(ctx)\n } catch (err) {\n renderCliError(err)\n }\n }) as RunFn\n }\n if (cmd.subCommands && typeof cmd.subCommands === 'object') {\n for (const sub of Object.values(cmd.subCommands)) {\n if (sub && typeof sub === 'object') wrapCommandErrors(sub as CommandDef)\n }\n }\n return cmd\n}\n","/** Stable platform-environment selection shared by every CLI command. */\n\n/**\n * `staging` targets the isolated constellation on spacestest.com. Unknown\n * explicit values are invalid and receive inert URLs, never production URLs.\n */\nexport type DeepSpaceEnvironment = 'production' | 'staging' | 'invalid'\n\nexport function resolveDeepSpaceEnvironment(value: string | undefined): DeepSpaceEnvironment {\n if (value === undefined || value === 'production') return 'production'\n if (value === 'staging') return 'staging'\n return 'invalid'\n}\n\nexport const DEEPSPACE_ENV = resolveDeepSpaceEnvironment(process.env.DEEPSPACE_ENV)\n\nconst PROD_URLS = {\n auth: 'https://auth.deep.space',\n api: 'https://api-worker.deep.space',\n platform: 'https://platform-worker.deep.space',\n deploy: 'https://deploy-worker.deep.space',\n} as const\n\nconst STAGING_URLS = {\n // Services live on deepspacesites.com, apps on spacestest.com. This mirrors\n // prod's two-zone split because a Worker cannot fetch one in its own zone.\n auth: 'https://auth.deepspacesites.com',\n api: 'https://api.deepspacesites.com',\n platform: 'https://platform.deepspacesites.com',\n deploy: 'https://deploy.deepspacesites.com',\n} as const\n\n// Defense in depth for callers imported without cli.ts's validation.\nconst INVALID_URLS = {\n auth: 'http://127.0.0.1:9',\n api: 'http://127.0.0.1:9',\n platform: 'http://127.0.0.1:9',\n deploy: 'http://127.0.0.1:9',\n} as const\n\nexport const PLATFORM_URLS =\n DEEPSPACE_ENV === 'production'\n ? PROD_URLS\n : DEEPSPACE_ENV === 'staging'\n ? STAGING_URLS\n : INVALID_URLS\n\n/** Report per-service process overrides without changing the stable presets. */\nexport function effectivePlatformUrls(env: NodeJS.ProcessEnv = process.env) {\n return {\n auth: env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth,\n api: env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api,\n platform: env.DEEPSPACE_PLATFORM_URL ?? PLATFORM_URLS.platform,\n deploy: env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy,\n }\n}\n\nexport const DASHBOARD_URL =\n DEEPSPACE_ENV === 'production'\n ? 'https://dashboard.deep.space'\n : DEEPSPACE_ENV === 'staging'\n ? 'https://dashboard.deepspacesites.com'\n : 'http://127.0.0.1:9'\n","/**\n * CLI auth utilities — shared across all commands.\n *\n * Reads the session token from ~/.deepspace/session and ensures\n * a fresh JWT is available at ~/.deepspace/token.\n */\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nimport { PLATFORM_URLS } from './env'\nimport { decodeJwtPayload } from './jwt'\nimport { exchangeSession } from './session'\nimport { registerAuthRefresh } from './lib/api'\nimport { cliAction, Refusal } from './lib/command'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth\n/** The plane whose credentials keep the historical un-suffixed filenames. */\nconst PROD_AUTH_URL = 'https://auth.deep.space'\n\nconst DIR = join(homedir(), '.deepspace')\n\n/**\n * Credentials are stored PER AUTH PLANE.\n *\n * They used to be one global pair (`~/.deepspace/{session,token}`), so a\n * single `DEEPSPACE_ENV=staging` login silently clobbered the production\n * session — and the next prod command exchanged a staging cookie against the\n * prod auth worker and reported \"Session expired. Run `deepspace auth\n * login`\", which reads like a token-refresh failure but is actually a\n * different account plane. Auto-refresh was working the whole time.\n *\n * Keyed by the effective auth URL, because that (not DEEPSPACE_ENV alone) is\n * what decides who issued the cookie — a bare `DEEPSPACE_AUTH_URL` override\n * gets its own slot too. Production keeps the historical filenames, so\n * upgrading does not log anyone out.\n */\nfunction credentialSuffix(authUrl: string): string {\n if (authUrl === PROD_AUTH_URL) return ''\n const host = (() => {\n try {\n return new URL(authUrl).host\n } catch {\n return authUrl\n }\n })()\n return `.${host.replace(/[^a-zA-Z0-9]+/g, '-')}`\n}\n\n/** The {session,token} file pair for a given auth plane. */\nexport function credentialPaths(authUrl: string = AUTH_URL): {\n sessionPath: string\n tokenPath: string\n} {\n const suffix = credentialSuffix(authUrl)\n return { sessionPath: join(DIR, `session${suffix}`), tokenPath: join(DIR, `token${suffix}`) }\n}\n\nexport const { sessionPath: SESSION_PATH, tokenPath: TOKEN_PATH } = credentialPaths()\n\n/**\n * Ensure a valid JWT exists. Refreshes from the session token if expired.\n * Returns the JWT string or throws if not logged in / session expired.\n */\nexport async function ensureToken(): Promise<string> {\n // Try existing token first — if it's still valid, skip the refresh\n if (existsSync(TOKEN_PATH)) {\n const existing = readFileSync(TOKEN_PATH, 'utf-8').trim()\n if (isTokenValid(existing)) {\n return existing\n }\n }\n\n if (!existsSync(SESSION_PATH)) {\n throw new Refusal('Not logged in. Run `deepspace auth login` first.', 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const sessionToken = readFileSync(SESSION_PATH, 'utf-8').trim()\n\n // Refresh from session\n const token = await exchangeSession(AUTH_URL, sessionToken)\n if (!token) {\n throw new Refusal(\n 'Session expired. Run `deepspace auth login` to re-authenticate.',\n 'not_authenticated',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n\n mkdirSync(DIR, { recursive: true, mode: 0o700 })\n writeFileSync(TOKEN_PATH, token, { mode: 0o600 })\n\n return token\n}\n\n/** Check if a JWT has at least 30 seconds of validity remaining. */\nfunction isTokenValid(jwt: string): boolean {\n try {\n const payload = decodeJwtPayload<{ exp?: number }>(jwt)\n return typeof payload.exp === 'number' && payload.exp * 1000 > Date.now() + 30_000\n } catch {\n return false\n }\n}\n\n/**\n * Force-mint a fresh JWT from the stored session, ignoring the cached token\n * file — apiFetch's 401 recovery (see registerAuthRefresh). Never throws:\n * null means the session is gone/expired, and the caller's original 401\n * (with its own actionable message) is the right error to surface.\n */\nregisterAuthRefresh(async (): Promise<string | null> => {\n try {\n if (!existsSync(SESSION_PATH)) return null\n const sessionToken = readFileSync(SESSION_PATH, 'utf-8').trim()\n const token = await exchangeSession(AUTH_URL, sessionToken)\n if (!token) return null\n mkdirSync(DIR, { recursive: true, mode: 0o700 })\n writeFileSync(TOKEN_PATH, token, { mode: 0o600 })\n return token\n } catch {\n return null\n }\n})\n","export function decodeJwtPayload<T = Record<string, unknown>>(token: string): T {\n const payloadSegment = token.split('.')[1]\n if (!payloadSegment) {\n throw new Error('JWT payload is missing')\n }\n return JSON.parse(Buffer.from(payloadSegment, 'base64url').toString('utf8')) as T\n}\n","/**\n * CLI session helpers — exchange a Better Auth session cookie for a short-lived\n * JWT against the auth worker. Shared by `auth.ts` (token refresh for all\n * authenticated commands) and `login.ts` (email/password flow).\n */\n\nexport const SESSION_COOKIE = '__Secure-better-auth.session_token'\n\n/**\n * Exchange a Better Auth session token for a fresh JWT.\n * Returns null if the session is invalid or expired.\n */\nexport async function exchangeSession(\n authUrl: string,\n sessionToken: string,\n): Promise<string | null> {\n const res = await fetch(`${authUrl}/api/auth/token`, {\n method: 'POST',\n headers: {\n Cookie: `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}`,\n Origin: authUrl,\n },\n })\n if (!res.ok) return null\n const data = (await res.json()) as { token?: string | null }\n return data.token ?? null\n}\n","/**\n * The shared command-output boundary. Command bodies return content or throw\n * a {@link Refusal}; this runtime owns JSON envelopes, human slugs and optional\n * actions, plus the 0/1/2 exit convention.\n */\n\nimport { defineCommand, type ArgsDef, type CommandDef } from 'citty'\nimport * as p from '@clack/prompts'\nimport { stopActiveSpinner } from './spinner'\nimport { assertExecutableAction, printAction, withSlug, type CliAction } from './output'\nimport { errorCode } from './cli-errors'\n\nexport { cliAction } from './output'\n\n/**\n * A refusal the caller can act on: carries the machine slug that appears both\n * in `--json` as `code` and at the end of the human line, plus at most one\n * executable action that resolves it.\n *\n * `actionRequired` marks the third exit state — the operation did what it\n * could and a LOCAL step remains (merge the tip, commit the tree). It exits 2,\n * which is the difference between \"this failed\" and \"your turn\", and is the\n * single most useful signal an agent gets from this CLI.\n */\nexport class Refusal extends Error {\n readonly code: string\n readonly action: CliAction | undefined\n readonly actionRequired: boolean\n readonly extra: Record<string, unknown>\n\n constructor(\n message: string,\n code: string,\n opts: { action?: CliAction; actionRequired?: boolean; extra?: Record<string, unknown> } = {},\n ) {\n super(message)\n this.name = 'Refusal'\n this.code = code\n if (opts.action) assertExecutableAction(opts.action)\n this.action = opts.action\n this.actionRequired = opts.actionRequired ?? false\n this.extra = opts.extra ?? {}\n }\n}\n\n/** What a command body returns: the machine payload plus its follow-ups. */\nexport interface CommandResult {\n /** Merged into the `--json` envelope. Omit for commands with no payload. */\n data?: Record<string, unknown>\n /** One executable follow-up: the `Next:` line and envelope's `action`. */\n action?: CliAction\n}\n\n/**\n * Strip the envelope's reserved keys from a payload before it is spread into\n * the envelope. `data`/`extra` can carry raw server JSON (`integrations\n * invoke` forwards the response body verbatim), and a payload containing\n * `ok`, `action`, or `actionRequired` must not be able to flip a failure to\n * success or hand an agent an unvalidated recovery action.\n */\nfunction withoutReservedKeys(payload: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(payload).filter(\n ([key]) =>\n ![\n 'ok',\n 'code',\n 'error',\n 'action',\n 'actionRequired',\n 'next',\n 'nextAction',\n 'resume',\n ].includes(key),\n ),\n )\n}\n\n/**\n * Exit only once stdout has drained. `console.log` on a PIPE is asynchronous\n * past the OS buffer (64 KiB on Linux/macOS), so exiting immediately truncates\n * a large payload mid-write — `integrations list --json` is already ~29 KB and\n * the catalog grows. The empty write's callback fires after the queue flushes.\n */\nfunction exitWhenFlushed(code: number): never {\n // Nothing queued (a TTY, a small payload, or a test harness capturing\n // console.log) — exit synchronously. Deferring unconditionally would break\n // any caller that mocks process.exit and asserts synchronously, and would\n // let execution continue past a `never` return.\n if (process.stdout.writableLength === 0) process.exit(code)\n process.stdout.write('', () => process.exit(code))\n return undefined as never\n}\n\nexport interface DeepspaceCommandDef<A extends ArgsDef> {\n meta: { name: string; description: string }\n args?: A\n /** Print human output yourself; return the machine payload. Throw a\n * {@link Refusal} for an actionable failure. */\n run: (ctx: { args: Record<string, unknown> & { json: boolean } }) => Promise<CommandResult | void>\n}\n\n/**\n * Wrap a command body in the contract. Injects `--json`, renders both output\n * paths, and owns the exit codes — a body never calls process.exit itself.\n */\nexport function defineDeepspaceCommand<A extends ArgsDef>(def: DeepspaceCommandDef<A>): CommandDef {\n // The injected `json` arg widens citty's inferred ArgsDef generic, which no\n // longer matches the bare `CommandDef` the registry holds. The runtime reads\n // args dynamically, so the erasure is safe and keeps every command in the\n // tree one uniform type.\n return defineCommand({\n meta: def.meta,\n args: {\n ...(def.args ?? ({} as A)),\n json: {\n type: 'boolean',\n description: 'Emit a single-line JSON result for scripts/agents',\n default: false,\n },\n },\n async run({ args }) {\n const json = Boolean((args as { json?: boolean }).json)\n let succeeded = false\n try {\n const out =\n (await def.run({ args: args as Record<string, unknown> & { json: boolean } })) ?? {}\n if (out.action) assertExecutableAction(out.action)\n if (json) {\n console.log(\n JSON.stringify({\n ok: true,\n ...withoutReservedKeys(out.data ?? {}),\n ...(out.action ? { action: out.action } : {}),\n }),\n )\n } else if (out.action) {\n printAction(out.action)\n }\n succeeded = true\n } catch (err) {\n stopActiveSpinner()\n const refusal = err instanceof Refusal ? err : null\n const code = refusal?.code ?? errorCode(err)\n const message = err instanceof Error ? err.message : String(err)\n if (json) {\n console.log(\n JSON.stringify({\n ok: false,\n ...(code ? { code } : {}),\n ...(refusal?.actionRequired ? { actionRequired: true } : {}),\n error: message,\n ...(refusal?.action ? { action: refusal.action } : {}),\n ...withoutReservedKeys(refusal?.extra ?? {}),\n }),\n )\n } else {\n const line = code ? withSlug(message, code) : message\n if (refusal?.actionRequired) p.log.warn(line)\n else p.log.error(line)\n if (refusal?.action) printAction(refusal.action)\n }\n // 2 = \"it worked, but a local step remains\"; 1 = it failed.\n exitWhenFlushed(refusal?.actionRequired ? 2 : 1)\n }\n // OUTSIDE the try on purpose: a test that mocks process.exit to throw\n // would otherwise have the success path land in the catch above and be\n // re-rendered as a failure.\n if (succeeded) exitWhenFlushed(0)\n },\n }) as CommandDef\n}\n","/**\n * deepspace auth login\n *\n * Opens the browser to sign in with GitHub or Google.\n * CLI polls the auth worker until login is complete.\n *\n * deepspace auth login # browser-based OAuth\n * deepspace auth login --email x --password y # non-interactive (discouraged: argv leaks)\n * echo \"$PW\" | deepspace auth login --email x --password-stdin # password via stdin\n * DEEPSPACE_EMAIL=x DEEPSPACE_PASSWORD=y deepspace auth login # via env\n *\n * `--json` (from the command runtime, lib/command.ts) matters more here than\n * anywhere else: login is the FIRST command an agent runs, and until now it\n * had no machine surface at all. Two rules keep it usable:\n *\n * 1. `--json` is an explicit machine signal, so it also means \"non-\n * interactive\" for credential resolution — $DEEPSPACE_EMAIL/$DEEPSPACE_\n * PASSWORD are consulted even from a pty. (The guard against ambient\n * DEEPSPACE_* hijacking a HUMAN `deepspace auth login` is untouched: a\n * human doesn't pass --json.)\n * 2. The browser flow polls for up to TEN MINUTES. Entering it from a\n * machine caller with nowhere to click is a silent hang, so `--json`\n * without credentials and without a TTY refuses immediately\n * (`interactive_required`) instead.\n */\n\nimport { credentialPaths } from '../auth'\nimport { writeFileSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\nimport { randomBytes, createHash } from 'node:crypto'\nimport * as p from '@clack/prompts'\n\nimport { createSpinner } from '../lib/spinner'\nimport { DASHBOARD_URL, PLATFORM_URLS } from '../env'\nimport { exchangeSession, SESSION_COOKIE } from '../session'\nimport { decodeJwtPayload } from '../jwt'\nimport { openBrowser } from '../lib/open-browser'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'login',\n description: 'Log in to your DeepSpace account',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email address (non-interactive mode; or $DEEPSPACE_EMAIL)',\n required: false,\n },\n password: {\n type: 'string',\n description: 'Password (discouraged — visible in ps/history; prefer --password-stdin or $DEEPSPACE_PASSWORD)',\n required: false,\n },\n 'password-stdin': {\n type: 'boolean',\n description: 'Read the password from stdin instead of --password',\n default: false,\n },\n },\n async run({ args }) {\n const json = args.json\n // Non-interactive mode for CI/agents. Password from --password-stdin\n // (safest), $DEEPSPACE_PASSWORD, or --password (discouraged — visible in\n // `ps`/shell history); email from --email or $DEEPSPACE_EMAIL. The env vars\n // are consulted ONLY when stdin is non-interactive (or --json was asked\n // for), so ambient DEEPSPACE_* in a dev shell can't hijack an interactive\n // `deepspace auth login` into a password login as a different identity.\n const interactive = Boolean(process.stdin.isTTY) && !json\n const { email, password } = resolveLoginCredentials({\n emailArg: args.email as string | undefined,\n passwordArg: args.password as string | undefined,\n envEmail: interactive ? undefined : process.env.DEEPSPACE_EMAIL,\n envPassword: interactive ? undefined : process.env.DEEPSPACE_PASSWORD,\n passwordStdin: args['password-stdin'] ? readPasswordFromStdin() : undefined,\n })\n const passwordIntent =\n Boolean(args['password-stdin']) || args.password !== undefined || password !== undefined\n\n const decision = loginModeDecision({ email, password, passwordIntent })\n if (decision.mode === 'error') {\n throw new Refusal(decision.message, decision.code)\n }\n if (decision.mode === 'password') {\n if (!json) console.log(`Signing in as ${email}...`)\n const who = await doEmailLogin(email as string, password as string)\n if (!json) {\n console.log(`Logged in as ${who.email} (${who.userId})`)\n console.log(`Dashboard: ${DASHBOARD_URL}`)\n }\n return { data: { email: who.email, userId: who.userId } }\n }\n // decision.mode === 'oauth' → fall through to the browser flow below.\n\n // The browser flow polls for up to ten minutes. --json is the machine\n // signal on its own — a caller running under a pty (stdout IS a TTY) would\n // otherwise fall through and hang for ten minutes. Refuse for ANY --json\n // caller, or any non-TTY, with the flags that actually work.\n if (json || !process.stdout.isTTY) {\n throw new Refusal(\n 'Browser login needs an interactive terminal. Use --email with --password-stdin (or $DEEPSPACE_EMAIL/$DEEPSPACE_PASSWORD).',\n 'interactive_required',\n )\n }\n\n // Browser-based OAuth flow\n if (!json) p.intro('DeepSpace Login')\n\n const s = createSpinner()\n if (!json) s.start('Creating login session...')\n\n // PKCE: generate a random verifier and send only its SHA-256 hash to the\n // server. The verifier never leaves this process, so the loginUrl alone\n // can't be used to drain credentials at /status — only this CLI can.\n const codeVerifier = base64url(randomBytes(32))\n const codeChallenge = base64url(createHash('sha256').update(codeVerifier).digest())\n\n // 1. Create a CLI session\n const sessionRes = await fetch(`${AUTH_URL}/api/auth/cli/session`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code_challenge: codeChallenge }),\n })\n // The runtime stops any live spinner before it renders a refusal, so these\n // throws don't need to unwind the spinner themselves.\n if (!sessionRes.ok) {\n throw new Refusal(\n `Could not create login session (${sessionRes.status})`,\n 'login_session_failed',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n const sessionData = (await sessionRes.json()) as {\n sessionId?: string\n loginUrl?: string\n }\n if (!sessionData.sessionId || !sessionData.loginUrl) {\n throw new Refusal(\n 'Could not create login session — the auth server returned no session id or login url.',\n 'login_session_failed',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n\n const { sessionId, loginUrl } = sessionData as {\n sessionId: string\n loginUrl: string\n }\n\n if (!json) {\n s.stop('Opening browser...')\n p.log.info(`If the browser doesn't open, visit:\\n ${loginUrl}`)\n }\n\n // 2. Open browser\n openBrowser(loginUrl)\n\n // 3. Poll for completion\n if (!json) s.start('Waiting for authentication...')\n const result = await pollForCompletion(sessionId, codeVerifier)\n\n if (!result) {\n throw new Refusal('Login timed out. Run `deepspace auth login` to try again.', 'login_timeout', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n // 4. Store credentials + provision the billing profile (see provisionProfile)\n storeCredentials(result.sessionToken, result.jwt)\n await provisionProfile(result.jwt)\n\n // Report the same identity fields the password path does, so an agent\n // never has to follow login with `whoami` to learn who it became.\n let userId = '(unknown)'\n try {\n userId = decodeJwtPayload<{ sub?: string }>(result.jwt).sub ?? userId\n } catch {\n // A malformed JWT is the session's problem, not login's — keep going.\n }\n\n if (!json) {\n s.stop('Authenticated')\n p.log.success(`Logged in as ${result.name ?? result.email}`)\n p.note(\n `Manage your account, deployed apps, billing, and subscription\\nplans on the web dashboard:\\n\\n ${DASHBOARD_URL}`,\n 'Dashboard',\n )\n p.outro('Done')\n }\n return { data: { email: result.email, userId } }\n },\n})\n\n/**\n * Resolve non-interactive login credentials with a clear precedence (ONB-4):\n * email = --email > $DEEPSPACE_EMAIL; password = --password-stdin (when the flag\n * is set, its already-read value wins) > --password > $DEEPSPACE_PASSWORD.\n * Pure for testing.\n */\nexport function resolveLoginCredentials(opts: {\n emailArg?: string\n passwordArg?: string\n envEmail?: string\n envPassword?: string\n passwordStdin?: string\n}): { email?: string; password?: string } {\n const email = opts.emailArg || opts.envEmail || undefined\n const password =\n opts.passwordStdin !== undefined\n ? opts.passwordStdin\n : opts.passwordArg || opts.envPassword || undefined\n return { email, password }\n}\n\n/**\n * Decide how `login` should proceed given the resolved credentials (ONB-4).\n * `passwordIntent` is true when the user asked for a password login (a\n * credential flag/stdin or a resolved password). Crucially, a supplied-but-\n * incomplete credential set (missing email, or an EMPTY password — e.g. an\n * empty `--password-stdin` in CI) becomes an `error`, not a silent fall-through\n * to the browser OAuth flow (which would hang ~10 min in a headless pipeline).\n * `code` is the machine slug the refusal carries. Pure for testing.\n */\nexport function loginModeDecision(opts: {\n email?: string\n password?: string\n passwordIntent: boolean\n}): { mode: 'password' } | { mode: 'oauth' } | { mode: 'error'; message: string; code: string } {\n if (opts.email && opts.password) return { mode: 'password' }\n if (!opts.passwordIntent) return { mode: 'oauth' }\n if (!opts.email) {\n return {\n mode: 'error',\n code: 'missing_email',\n message: 'Non-interactive login needs an email: --email <you@example.com> (or $DEEPSPACE_EMAIL).',\n }\n }\n return {\n mode: 'error',\n code: 'missing_password',\n message:\n 'Non-interactive login needs a non-empty password: --password-stdin, $DEEPSPACE_PASSWORD, or --password.',\n }\n}\n\n/**\n * Read a password piped on stdin (one trailing newline stripped). Refuses on a\n * TTY, where reading stdin would block forever waiting for EOF.\n */\nfunction readPasswordFromStdin(): string {\n if (process.stdin.isTTY) {\n throw new Refusal(\n '--password-stdin expects the password piped on stdin, e.g. `printf %s \"$PW\" | deepspace auth login --email you@x.com --password-stdin`.',\n 'password_stdin_needs_pipe',\n )\n }\n return readFileSync(0, 'utf-8').replace(/\\r?\\n$/, '')\n}\n\ninterface LoginResult {\n sessionToken: string\n jwt: string\n email: string\n name: string | null\n}\n\nasync function pollForCompletion(\n sessionId: string,\n codeVerifier: string,\n): Promise<LoginResult | null> {\n const maxAttempts = 120 // 10 minutes at 5s intervals\n const interval = 5000\n\n for (let i = 0; i < maxAttempts; i++) {\n await sleep(interval)\n\n try {\n const res = await fetch(`${AUTH_URL}/api/auth/cli/status/${sessionId}`, {\n headers: { 'x-code-verifier': codeVerifier },\n })\n\n if (res.status === 410 || res.status === 404) return null // expired / not found\n if (!res.ok) continue\n\n const data = (await res.json()) as {\n state?: string\n sessionToken?: string\n jwt?: string\n email?: string\n name?: string\n }\n\n if (data.state === 'complete' && data.sessionToken && data.jwt) {\n return {\n sessionToken: data.sessionToken,\n jwt: data.jwt,\n email: data.email ?? '',\n name: data.name ?? null,\n }\n }\n } catch {\n // Network error, keep polling\n }\n }\n\n return null\n}\n\nfunction storeCredentials(sessionToken: string, jwt: string) {\n const dir = join(homedir(), '.deepspace')\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n // Per-plane paths: a staging login must not overwrite the production\n // session (that clobber surfaced as a bogus \"Session expired\" on the next\n // prod command).\n const { sessionPath, tokenPath } = credentialPaths(AUTH_URL)\n writeFileSync(sessionPath, sessionToken, { mode: 0o600 })\n writeFileSync(tokenPath, jwt, { mode: 0o600 })\n}\n\n/**\n * Provision the user's billing profile so they can be referenced by email\n * immediately after logging in — e.g. added as a collaborator on someone\n * else's app. The api-worker's auth middleware upserts the `userProfiles`\n * row on any authenticated call, but login/whoami only ever touch the auth\n * worker, so a fresh CLI-only account otherwise has no profile and\n * `collaborators add <their-email>` 404s until their first deploy. One GET\n * to /api/users/me creates it. Best-effort: the same upsert happens on any\n * later api-worker call, so a transient failure here must not fail login.\n */\nasync function provisionProfile(jwt: string): Promise<void> {\n try {\n await fetch(`${API_URL}/api/users/me`, { headers: { Authorization: `Bearer ${jwt}` } })\n } catch {\n // non-fatal — the profile is upserted on the next api-worker request\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction base64url(bytes: Buffer): string {\n return bytes.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n// ── Email/password login (for test accounts and CI) ────────────────\n\nasync function doEmailLogin(\n email: string,\n password: string,\n): Promise<{ email: string; userId: string }> {\n const res = await fetch(`${AUTH_URL}/api/auth/sign-in/email`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Origin: AUTH_URL },\n body: JSON.stringify({ email, password }),\n redirect: 'manual',\n })\n\n if (!res.ok) {\n const body = (await res.json().catch(() => ({}))) as { message?: string }\n throw new Error(body.message ?? `Authentication failed (${res.status})`)\n }\n\n const setCookie = res.headers.get('set-cookie') ?? ''\n const cookieMatch = setCookie.match(new RegExp(`${SESSION_COOKIE}=([^;]+)`))\n if (!cookieMatch) {\n throw new Error('No session cookie returned')\n }\n const sessionToken = decodeURIComponent(cookieMatch[1])\n\n const jwt = await exchangeSession(AUTH_URL, sessionToken)\n if (!jwt) {\n throw new Error('JWT issuance failed')\n }\n\n storeCredentials(sessionToken, jwt)\n await provisionProfile(jwt)\n // The user id is the fact `whoami --json` reports as `userId`; surface it at\n // login too so an agent never has to re-run whoami to learn who it became.\n let userId = '(unknown)'\n try {\n userId = decodeJwtPayload<{ sub?: string }>(jwt).sub ?? userId\n } catch {\n // A malformed JWT is the session's problem, not login's — keep going.\n }\n return { email, userId }\n}\n","/**\n * Best-effort \"open this URL in the default browser\".\n *\n * Non-blocking and never throws: every caller has already printed the URL, so\n * a failure to launch the browser is harmless — the user opens it manually.\n * `JSON.stringify` quotes the URL so query strings / special chars can't break\n * out of the shell command.\n */\nimport { exec } from 'node:child_process'\n\nexport function openBrowser(url: string): void {\n const quoted = JSON.stringify(url)\n const cmd =\n process.platform === 'darwin'\n ? `open ${quoted}`\n : process.platform === 'win32'\n ? `start \"\" ${quoted}`\n : `xdg-open ${quoted}`\n\n // Swallow errors — the URL was already shown, so launching is optional.\n exec(cmd, () => {})\n}\n","/**\n * deepspace auth logout\n *\n * Revokes the session on the auth worker, then removes the cached session\n * token and JWT from ~/.deepspace/. Test accounts (managed by `deepspace\n * test-accounts`) are not touched.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope\n * and the exit code come from there. Logging out is TERMINAL — there is no\n * follow-up worth naming, so this command emits no `next` (the contract\n * forbids filler).\n */\n\nimport { existsSync, readFileSync, rmSync } from 'node:fs'\n\nimport { PLATFORM_URLS } from '../env'\nimport { SESSION_COOKIE } from '../session'\nimport { credentialPaths } from '../auth'\nimport { defineDeepspaceCommand } from '../lib/command'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth\n\n// Per-plane paths from the shared helper — logging out of staging must not\n// delete the production session (and vice versa).\nconst { sessionPath: SESSION_PATH, tokenPath: TOKEN_PATH } = credentialPaths(AUTH_URL)\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'logout',\n description: 'Sign out and remove cached credentials',\n },\n async run({ args }) {\n // Read the session token before deleting it so we can revoke server-side.\n const sessionToken = existsSync(SESSION_PATH)\n ? readFileSync(SESSION_PATH, 'utf-8').trim()\n : null\n\n if (sessionToken) {\n try {\n await fetch(`${AUTH_URL}/api/auth/sign-out`, {\n method: 'POST',\n headers: {\n Cookie: `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}`,\n Origin: AUTH_URL,\n },\n })\n } catch {\n // Network failure — still wipe local credentials so the user can\n // re-authenticate. Server-side session will expire on its own.\n }\n }\n\n let removed = 0\n for (const path of [SESSION_PATH, TOKEN_PATH]) {\n if (existsSync(path)) {\n rmSync(path)\n removed++\n }\n }\n\n // Already-logged-out is a SUCCESS, not a refusal: the requested end state\n // (no cached credentials) holds either way, so an agent retrying logout\n // must not read exit 1.\n if (!args.json) console.log(removed === 0 ? 'Already logged out.' : 'Logged out.')\n return { data: { loggedOut: true, removed, alreadyLoggedOut: removed === 0 } }\n },\n})\n","/**\n * App identity (docs/proposals/app-identity-registry.md).\n *\n * Every app carries an immutable id in wrangler.toml:\n *\n * [vars]\n * DEEPSPACE_APP_ID = \"app_01JG8QK…\" # minted at scaffold/init\n *\n * [env.staging.vars]\n * DEEPSPACE_APP_ID = \"app_01JG8QM…\" # each env is its own app\n *\n * The wrangler `name` field is just the subdomain label the next deploy\n * claims; identity is the id. Minting is local (a ULID — 80 random bits\n * need no server round-trip to be unique); registration happens at first\n * deploy.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport { InputError } from './cli-errors'\n\n// Single source: the shared registry client owns the id shape. Import-then-\n// re-export (not a bare `export from`) because line ~151 uses it locally too.\nimport { APP_ID_RE } from '../../server/utils/registry-client'\nexport { APP_ID_RE }\n\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\n/** A 26-char ULID (48-bit ms timestamp + 80 random bits, Crockford base32) —\n * the id shape shared by app ids (`app_…`) and workspace ids (`ws_…`). */\nexport function mintUlid(now = Date.now()): string {\n let ts = ''\n let t = now\n for (let i = 0; i < 10; i++) {\n ts = CROCKFORD[t % 32] + ts\n t = Math.floor(t / 32)\n }\n const rand = new Uint8Array(10)\n crypto.getRandomValues(rand)\n let rs = ''\n let acc = 0\n let bits = 0\n for (const byte of rand) {\n acc = (acc << 8) | byte\n bits += 8\n while (bits >= 5) {\n bits -= 5\n rs += CROCKFORD[(acc >> bits) & 31]\n }\n }\n return `${ts}${rs}`.slice(0, 26)\n}\n\n/** Mint a fresh app id: `app_` + 26-char ULID. */\nexport function mintAppId(now = Date.now()): string {\n return `app_${mintUlid(now)}`\n}\n\n/** Outcome of looking for an app already registered at this name. */\nexport type ExistingAppResolution =\n /** A registered app the caller can deploy — reuse its id. `owned` is false\n * when access comes from the on-behalf matrix (collaborator/admin) rather\n * than ownership; callers must confirm before deploying those. */\n | { kind: 'adopted'; appId: string; owned: boolean }\n /** A registered app the caller CANNOT deploy — abort before minting. */\n | { kind: 'taken' }\n /** Nothing registered here → mint a fresh id. */\n | { kind: 'none' }\n\n/**\n * Resolve the app already registered at this subdomain, if any. A repo with no\n * `DEEPSPACE_APP_ID` must NOT blindly mint a fresh id: an app the platform\n * already registered — e.g. one backfilled during the app-identity cutover —\n * owns its route, so a fresh id would collide (\"name … is taken by another\n * app\"). Two probes:\n *\n * 1. The caller's own apps (`/api/apps`), matched by subdomain — the owner\n * redeploying a legacy repo.\n * 2. The name itself as a legacy id: backfilled apps use their name as their\n * appId, so a gated per-app read (`/api/apps/:appId/analytics`, the same\n * owner / collaborator / admin matrix deploy grants) answers in one call\n * whether the app exists and whether the caller may deploy it. 200 → adopt\n * (deploy runs on-behalf when the caller isn't the owner); 403 → the name\n * belongs to an app the caller can't deploy, so minting would only defer\n * the failure to a confusing route-claim collision — report `taken` so\n * deploy can fail with the real reason; 404 → nothing there.\n *\n * Best-effort otherwise: network errors and unexpected responses resolve to\n * `none` so the deploy still proceeds and mints, exactly as before.\n */\nexport async function resolveExistingAppId(\n deployUrl: string,\n token: string,\n appName: string,\n): Promise<ExistingAppResolution> {\n const headers = { Authorization: `Bearer ${token}` }\n\n try {\n const res = await fetch(`${deployUrl}/api/apps`, { headers })\n if (res.ok) {\n const body = (await res.json()) as {\n apps?: Array<{ appId?: string; name?: string | null }>\n }\n const match = body.apps?.find((a) => a.name === appName)\n if (match?.appId) return { kind: 'adopted', appId: match.appId, owned: true }\n }\n } catch {\n // fall through to the legacy-id probe\n }\n\n try {\n const res = await fetch(\n `${deployUrl}/api/apps/${encodeURIComponent(appName)}/analytics?period=1h`,\n { headers },\n )\n // Not in the owned list but the gated read authorizes → on-behalf access\n // (collaborator or admin). NOT ownership: for an admin this is true of\n // EVERY registered app, so the caller must confirm before deploying.\n if (res.ok) return { kind: 'adopted', appId: appName, owned: false }\n if (res.status === 403) return { kind: 'taken' }\n } catch {\n // best-effort: fall through\n }\n\n return { kind: 'none' }\n}\n\ninterface WranglerVars {\n vars?: Record<string, unknown>\n env?: Record<string, { vars?: Record<string, unknown> }>\n}\n\n/** Read DEEPSPACE_APP_ID for the given wrangler env (top-level when omitted).\n * Env blocks do NOT inherit the top-level id — each env is its own app. */\nexport function readAppId(cwd: string = process.cwd(), wranglerEnv?: string): string | null {\n const wranglerPath = join(resolve(cwd), 'wrangler.toml')\n if (!existsSync(wranglerPath)) return null\n let cfg: WranglerVars\n try {\n cfg = parseToml(readFileSync(wranglerPath, 'utf-8')) as WranglerVars\n } catch (err) {\n // A corrupt wrangler.toml must NOT read as \"no id yet\" — callers would\n // tell the user to run `deepspace app init` (a lie) or mint a SECOND id\n // into the broken file. Surface the real problem.\n throw new InputError(\n `Could not parse ${wranglerPath}: ${err instanceof Error ? err.message : String(err)}`,\n 'invalid_config',\n )\n }\n const vars = wranglerEnv ? cfg.env?.[wranglerEnv]?.vars : cfg.vars\n const id = vars?.DEEPSPACE_APP_ID\n return typeof id === 'string' && APP_ID_RE.test(id) ? id : null\n}\n\n/**\n * Write DEEPSPACE_APP_ID into wrangler.toml, text-preserving: appended to the\n * existing `[vars]` / `[env.<name>.vars]` block, or the block is created.\n * Refuses to overwrite an existing id unless `force` — identity is immutable;\n * a new id means a new app (`deepspace app init --new-id`).\n */\nexport function writeAppId(\n cwd: string,\n appId: string,\n opts: { wranglerEnv?: string; force?: boolean } = {},\n): void {\n const wranglerPath = join(resolve(cwd), 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n throw new Error(`No wrangler.toml in ${resolve(cwd)}`)\n }\n const existing = readAppId(cwd, opts.wranglerEnv)\n if (existing && !opts.force) {\n if (existing === appId) return\n throw new Error(\n `wrangler.toml already carries ${existing}. The app id is immutable — use --new-id only to fork this repo as a separate app.`,\n )\n }\n\n let src = readFileSync(wranglerPath, 'utf-8')\n const header = opts.wranglerEnv ? `[env.${opts.wranglerEnv}.vars]` : '[vars]'\n const line = `DEEPSPACE_APP_ID = \"${appId}\"`\n const headerRe = new RegExp(`^\\\\${header.replace(/\\./g, '\\\\.')}[ \\\\t]*$`, 'm')\n const idLineRe = /^DEEPSPACE_APP_ID\\s*=.*$/m\n\n const match = headerRe.exec(src)\n if (match) {\n // Insert (or replace) inside the existing block: from the header to the\n // next section header or EOF.\n const blockStart = match.index + match[0].length\n const rest = src.slice(blockStart)\n const nextSection = rest.search(/^\\s*\\[/m)\n const blockEnd = nextSection === -1 ? src.length : blockStart + nextSection\n const block = src.slice(blockStart, blockEnd)\n const newBlock = idLineRe.test(block)\n ? block.replace(idLineRe, line)\n : `\\n${line}${block}`\n src = src.slice(0, blockStart) + newBlock + src.slice(blockEnd)\n } else {\n src = src.trimEnd() + `\\n\\n${header}\\n${line}\\n`\n }\n writeFileSync(wranglerPath, src)\n}\n","/**\n * The ONE registry client. Every platform worker reaches the app-registry\n * Durable Object (hosted by the deploy worker, singleton `v1:global`) through\n * a cross-script REGISTRY binding — and before this module, each of the five\n * workers hand-rolled its own copy of the same mechanics: the instance name\n * appeared in 6 places, the `https://registry/` URL in 6, `APP_ID_RE` in 5,\n * and `RegistryClientError` + `registryErrorJson` existed byte-identical in\n * two workers. Copies that must agree and nothing enforcing it.\n *\n * This module owns the MECHANICS: instance name, stub lookup, the wire call,\n * the error type, and the standard route mapping. Each worker still declares\n * its own typed convenience wrapper listing only the actions it uses — that\n * subset is genuinely per-worker; the plumbing is not.\n */\n\n/** The singleton registry instance — one DO holds every app/route/collaborator. */\nexport const REGISTRY_INSTANCE = 'v1:global'\n\n/** App id shape: a ULID-minted `app_…` id, or a legacy name-as-id. */\nexport const APP_ID_RE = /^(app_[0-9A-HJKMNP-TV-Z]{26}|[a-z0-9][a-z0-9_-]{0,63})$/\n\n/** ONLY a ULID-minted id — surfaces that must not accept a legacy name. */\nexport const STRICT_APP_ID_RE = /^app_[0-9A-HJKMNP-TV-Z]{26}$/\n\nexport class RegistryClientError extends Error {\n constructor(\n message: string,\n readonly code: string,\n readonly status: number,\n ) {\n super(message)\n this.name = 'RegistryClientError'\n }\n}\n\nexport function registryStub(ns: DurableObjectNamespace): DurableObjectStub {\n return ns.get(ns.idFromName(REGISTRY_INSTANCE))\n}\n\n/**\n * One registry action over the wire. Non-2xx answers throw\n * {@link RegistryClientError} carrying the DO's structured `code` (or\n * `'error'` for a transport-shaped body) — callers distinguish a registry-\n * REPORTED miss (`code === 'not_found'`) from an outage by that code, never\n * by treating every throw as \"not found\".\n */\nexport async function callRegistry<T>(\n stub: DurableObjectStub,\n body: { action: string } & Record<string, unknown>,\n): Promise<T> {\n const res = await stub.fetch('https://registry/', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n const json = (await res.json().catch(() => ({}))) as { error?: string; code?: string }\n if (!res.ok) {\n throw new RegistryClientError(\n json.error ?? `Registry error (${res.status})`,\n json.code ?? 'error',\n res.status,\n )\n }\n return json as T\n}\n\n/** Standard mapping of a registry failure onto a route response. */\nexport function registryErrorJson(\n c: { json: (body: unknown, status?: number) => Response },\n err: unknown,\n): Response {\n if (err instanceof RegistryClientError) {\n return c.json({ error: err.message, code: err.code }, err.status as 400)\n }\n throw err\n}\n","/**\n * deepspace dev start [--port N]\n *\n * Starts local development:\n * 1. Ensures you're logged in\n * 2. Writes .dev.vars pointing to the production platform workers\n * 3. Starts vite dev (Cloudflare Vite plugin runs the worker in-process)\n *\n * deepspace dev start # port 5173 (strict)\n * deepspace dev start --port 5180 # bind to a different port (multi-app dev)\n *\n * Port is `--port` > $DEEPSPACE_PORT > 5173 — except inside a Claude Code\n * worktree, where (unless --port was passed) a stable per-worktree port in\n * 5180–5199 is derived instead, so the preview server never collides with a\n * main-repo dev server. We always pass --strictPort to vite so a busy port\n * fails loudly instead of silently jumping to 5174 (which would diverge from\n * anything Playwright/test config is expecting).\n *\n * Defined with the command runtime (lib/command.ts) so every PREFLIGHT failure\n * (no app dir, logged out, port busy, secrets refresh) carries a slug and a\n * `--json` envelope. The server itself is long-running: the body awaits vite's\n * exit and the envelope lands after it, since there is no earlier moment that\n * means \"done\". Vite's own output streams through inherited stdio and is never\n * buffered or suppressed — under `--json` the envelope is the LAST line, not\n * the only one.\n */\n\nimport { readAppId } from '../lib/app-identity'\nimport { resolve, basename, join } from 'node:path'\nimport spawn from 'cross-spawn'\nimport { ensureToken } from '../auth'\nimport { detectAppName, findAppDir, findChildApps } from '../lib/app-context'\nimport {\n detectClaudeWorktree,\n deriveWorktreePort,\n upsertWorktreeLaunchConfig,\n writeLaunchConfigIfMissing,\n} from '../lib/launch-config'\nimport { PLATFORM_URLS } from '../env'\nimport { writeDevVars } from '../lib/dev-vars'\nimport { decodeJwtPayload } from '../jwt'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { preflightNodeVersion, preflightWindowsWorkerd } from '../lib/preflight'\nimport { removeMacosJunk } from '../lib/macos-junk'\nimport { refreshSecretsCache } from '../lib/secrets'\nimport { lintProjectSchemas, formatSchemaLintFindings } from '../lib/schema-lint'\nimport { DEFAULT_PORT, resolvePort, checkPortAvailable } from '../lib/port'\nimport {\n prepareWranglerEnvConfig,\n wranglerViteEnv,\n type PreparedWranglerEnvConfig,\n} from '../lib/wrangler-env'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\n/**\n * The \"no wrangler.toml here\" refusal, shared verbatim by `dev` and `test`.\n * Multi-line on purpose: the sibling-app suggestions are the whole point of\n * the message, and the runtime appends the slug to its last line.\n */\nexport function noAppDirMessage(start: string, children: string[]): string {\n const lines = [`No wrangler.toml found at or above ${start}.`]\n if (children.length > 0) {\n lines.push('Did you mean to run inside one of these app directories?')\n for (const c of children) lines.push(` cd ${c}`)\n } else {\n lines.push('Run from a DeepSpace app directory (one containing wrangler.toml).')\n }\n return lines.join('\\n')\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'dev',\n description: 'Start local development server',\n },\n args: {\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description:\n 'wrangler.toml [env.<name>] block to run (e.g. --env staging). ' +\n \"Applies the env's overrides at build time.\",\n required: false,\n },\n port: {\n type: 'string',\n description: `Port to bind (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n },\n async run({ args }) {\n const say = (line: string) => {\n if (!args.json) console.log(line)\n }\n preflightNodeVersion('dev start')\n const wranglerEnv =\n typeof args.env === 'string' && args.env.trim() ? args.env.trim() : undefined\n\n // Resolve the app root by walking up from the requested dir (default cwd),\n // so running from a subdirectory still works instead of hard-failing.\n const start = resolve((args.dir as string | undefined) ?? '.')\n const appDir = findAppDir(start)\n if (!appDir) {\n throw new Refusal(noAppDirMessage(start, findChildApps(start)), 'no_app_dir')\n }\n\n const junk = removeMacosJunk(appDir)\n if (junk > 0) say(`Removed ${junk} macOS metadata file(s) (._*, .DS_Store)`)\n\n // Inside a Claude Code worktree the desktop preview tool reads only the\n // MAIN repo's launch.json and would serve the main repo's stale code\n // (anthropics/claude-code#56688) — so upsert a cwd-pinned entry there.\n // Only a literal --port counts as explicit and is honored verbatim: an\n // ambient $DEEPSPACE_PORT (e.g. exported in a shell profile) must not pin\n // the worktree to the main repo's port — the port is resolved AFTER\n // worktree detection so a malformed ambient value can't kill dev either.\n // Otherwise a stable per-worktree port (bumped past other entries' ports)\n // avoids colliding with a main-repo server. This run binds the same port\n // the entry advertises, so the preview tool can attach to an\n // already-running worktree server instead of spawning a duplicate.\n const worktree = detectClaudeWorktree(appDir)\n const explicitPort = Boolean(args.port)\n let port =\n worktree && !explicitPort\n ? deriveWorktreePort(worktree.worktreeName)\n : resolvePort(args.port as string | undefined)\n if (worktree) {\n const upserted = upsertWorktreeLaunchConfig(\n worktree.mainRepoRoot,\n worktree.worktreeName,\n appDir,\n {\n port,\n probePort: !explicitPort,\n extraArgs: [...(wranglerEnv ? ['--env', wranglerEnv] : [])],\n },\n )\n if (upserted) {\n port = upserted.port\n say(\n `Claude worktree detected — preview tool: use preview_start with name \"${upserted.entryName}\" (port ${upserted.port})`,\n )\n } else if (!args.json) {\n console.warn(\n `Warning: could not update ${join(worktree.mainRepoRoot, '.claude', 'launch.json')} ` +\n `(malformed or unwritable) — the Claude preview tool may serve the main repo's code ` +\n `instead of this worktree.`,\n )\n }\n if (!explicitPort && process.env.DEEPSPACE_PORT) {\n say(\n `Ignoring DEEPSPACE_PORT=${process.env.DEEPSPACE_PORT} inside a worktree — ` +\n `using per-worktree port ${port}. Pass --port to override.`,\n )\n }\n }\n\n // Seed an app-local .claude/launch.json (only if absent) so the Claude Code\n // preview tool launches this app on the resolved port, instead of walking\n // up and latching onto an ancestor repo's config. With an explicit --port,\n // also update the existing entry so `kill` and the preview tool track the\n // port we actually bind (DEV-3).\n writeLaunchConfigIfMissing(appDir, detectAppName(appDir) ?? basename(appDir), port, {\n updatePort: explicitPort,\n })\n\n ensureInstallReady(appDir)\n\n // Surface schema-lint findings in the terminal the developer is watching.\n // The worker also warns at runtime, but only in the DO's console after a\n // client connects — easy to miss, and these are shipping privacy bugs.\n const lintFindings = await lintProjectSchemas(appDir)\n if (lintFindings && lintFindings.length > 0 && !args.json) {\n for (const line of formatSchemaLintFindings(lintFindings)) console.warn(line)\n }\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err: unknown) {\n // Keep ensureToken's canonical wording (\"Not logged in…\" / \"Session\n // expired…\") and add the slug + the command that fixes it.\n throw new Refusal(err instanceof Error ? err.message : String(err), 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n let payload: { sub: string; name?: string; email?: string }\n try {\n payload = decodeJwtPayload<{ sub: string; name?: string; email?: string }>(token)\n } catch {\n throw new Refusal(\n 'Malformed session token. Run `npx deepspace auth login`.',\n 'not_authenticated',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n // `--env` selects which `[env.<name>]` block of wrangler.toml we apply\n // (renames the app, swaps vars, etc.). Surface it in the startup log so\n // it's obvious which app slot a session is hitting when it's set.\n say(`Logged in as ${payload.name ?? payload.email}`)\n if (wranglerEnv) say(`Wrangler env: ${wranglerEnv}`)\n say(`Port: ${port}`)\n\n // Refresh the app-store secrets cache (config = wrangler env, or 'prd').\n // A repo without a DEEPSPACE_APP_ID hasn't been initialized — writeDevVars\n // below throws with the `deepspace app init` pointer, so skip the pull.\n let generatedSecretsCache: string | undefined\n const appIdForSecrets = readAppId(appDir, wranglerEnv)\n if (appIdForSecrets) {\n try {\n const refreshed = await refreshSecretsCache(DEPLOY_URL, token, appIdForSecrets, wranglerEnv)\n if (refreshed) {\n generatedSecretsCache = refreshed.rendered\n say(refreshed.summary)\n }\n } catch (err: unknown) {\n throw new Refusal(\n `Failed to refresh app secrets: ${err instanceof Error ? err.message : String(err)}`,\n 'secrets_refresh_failed',\n )\n }\n }\n\n const sharedDevVarsCache = generatedSecretsCache !== undefined\n await writeDevVars(appDir, payload.sub, token, wranglerEnv, {\n generatedSecretsCache,\n sharedDevVarsCache,\n })\n // prepareWranglerEnvConfig throws typed errors that already carry slugs;\n // let them through untouched rather than flattening them to a message.\n const wranglerConfig: PreparedWranglerEnvConfig = prepareWranglerEnvConfig(\n appDir,\n wranglerEnv,\n { sharedDevVarsCache },\n )\n preflightWindowsWorkerd(appDir)\n\n // Pre-probe the port so a collision gets a friendly remedy instead of\n // vite's raw --strictPort EADDRINUSE stack trace (DEV-5).\n if (!(await checkPortAvailable(port))) {\n const killArgv =\n port === DEFAULT_PORT\n ? ['deepspace', 'dev', 'kill']\n : ['deepspace', 'dev', 'kill', '--port', String(port)]\n const killCmd = killArgv.join(' ')\n wranglerConfig.cleanup()\n throw new Refusal(\n `Port ${port} is already in use.\\n` +\n `Free it with \\`${killCmd}\\`, or start on another port: \\`deepspace dev start --port <other>\\`.`,\n 'port_in_use',\n { extra: { port } },\n )\n }\n\n say('Starting dev server...\\n')\n\n const vite = spawn('npx', ['vite', '--port', String(port), '--strictPort', '--host'], {\n cwd: appDir,\n stdio: 'inherit',\n env: wranglerViteEnv(process.env, wranglerConfig, { DEEPSPACE_PORT: String(port) }),\n })\n const stop = () => {\n wranglerConfig.cleanup()\n vite.kill()\n }\n process.on('SIGINT', stop)\n process.on('SIGTERM', stop)\n\n // `dev` runs until vite exits (Ctrl-C, or a crash). Await that instead of\n // exiting from the close handler: the runtime owns exit codes now, and a\n // body that called process.exit would skip the envelope entirely.\n const code = await new Promise<number | null>((res) => {\n vite.on('close', (c) => {\n wranglerConfig.cleanup()\n res(c)\n })\n })\n // A signal-terminated vite reports code null — that's Ctrl-C, i.e. the\n // normal way this command ends, so it stays a success.\n if (code !== null && code !== 0) {\n throw new Refusal(`Dev server exited with code ${code}.`, 'dev_server_failed', {\n extra: { port, appDir, exitCode: code },\n })\n }\n return { data: { port, appDir, wranglerEnv: wranglerEnv ?? null } }\n },\n})\n","/** Discover the local DeepSpace app surrounding a working directory. */\n\nimport { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport { InputError } from './cli-errors'\n\n/** Read the app name from the local wrangler.toml, when present. */\nexport function detectAppName(cwd: string = process.cwd()): string | null {\n const wranglerPath = join(resolve(cwd), 'wrangler.toml')\n if (!existsSync(wranglerPath)) return null\n try {\n const config = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n return typeof config.name === 'string' && config.name.length > 0 ? config.name : null\n } catch (error) {\n throw new InputError(\n `Could not parse ${wranglerPath}: ${error instanceof Error ? error.message : String(error)}`,\n 'invalid_config',\n )\n }\n}\n\n/** Walk upward to the nearest directory containing wrangler.toml. */\nexport function findAppDir(start: string = process.cwd()): string | null {\n let dir = resolve(start)\n for (;;) {\n if (existsSync(join(dir, 'wrangler.toml'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/** Immediate child directories that contain wrangler.toml. */\nexport function findChildApps(dir: string): string[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && existsSync(join(dir, entry.name, 'wrangler.toml')))\n .map((entry) => entry.name)\n .sort()\n } catch {\n return []\n }\n}\n","/** Claude preview launch configuration for local apps and worktrees. */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, unlinkSync } from 'node:fs'\nimport { join, resolve, dirname, basename, isAbsolute, sep } from 'node:path'\nimport { detectAppName } from './app-context'\n\n/**\n * Atomic launch.json write: temp file + rename, so an interrupted write can\n * never leave torn (permanently unparseable) JSON behind.\n */\nfunction writeLaunchFile(launchPath: string, config: unknown): void {\n mkdirSync(dirname(launchPath), { recursive: true })\n const tmpPath = `${launchPath}.${process.pid}.tmp`\n writeFileSync(tmpPath, JSON.stringify(config, null, 2) + '\\n')\n try {\n renameSync(tmpPath, launchPath)\n } catch (err) {\n // Don't leave an orphan tmp file behind (e.g. Windows EPERM while the\n // preview tool holds launch.json open).\n try {\n unlinkSync(tmpPath)\n } catch {\n // best-effort cleanup\n }\n throw err\n }\n}\n\n/**\n * Read + validate a launch.json. Returns the parsed config, an empty skeleton\n * when the file is absent or empty (interrupted write, `touch` — nothing to\n * preserve), or null when it exists but is malformed / wrong-shaped (leave it\n * alone rather than clobber a hand-edited file). Trimmed before parsing so a\n * UTF-8 BOM from Windows editors doesn't read as \"malformed\".\n */\nfunction readLaunchFile(\n launchPath: string,\n): { version?: string; configurations: Array<Record<string, unknown>> } | null {\n const empty = { version: '0.0.1', configurations: [] }\n if (!existsSync(launchPath)) return empty\n const raw = readFileSync(launchPath, 'utf-8').trim()\n if (!raw) return empty\n const parsed = JSON.parse(raw)\n if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.configurations)) return null\n return parsed\n}\n\n/**\n * Seed the app's own entry in `<appDir>/.claude/launch.json` so the Claude\n * Code preview tool launches THIS app. Without an app-local launch.json the\n * tool walks up the directory tree and can latch onto an ancestor repo's\n * config — pointing at a different app and port — which is a real failure\n * when a DeepSpace app lives inside another repo.\n *\n * Entry-level, not file-level: if the file already has an entry named\n * `appName` (possibly user-customized) it is left untouched by default, but a\n * file that exists without it — e.g. created by a worktree run's upsert before\n * the main app ever ran `dev` — still gets the app's entry appended.\n *\n * `opts.updatePort` (DEV-3): when the user passed an explicit `--port`, update\n * the existing entry's `port` and the `--port` value inside its `runtimeArgs`\n * (other args like `--env` are preserved) so `kill` and the preview tool track\n * the port `dev` actually bound. Without it, a scaffold pinned to 5173 would\n * stay stale after `dev --port 5180`. Best-effort: a failure must never block\n * `dev` from starting.\n */\nexport function writeLaunchConfigIfMissing(\n appDir: string,\n appName: string,\n port: number,\n opts: { updatePort?: boolean } = {},\n): void {\n const launchPath = join(appDir, '.claude', 'launch.json')\n try {\n const config = readLaunchFile(launchPath)\n if (!config) return\n const existing = config.configurations.find((c) => c?.name === appName)\n if (existing) {\n if (!opts.updatePort) return\n // Resync BOTH the `port` field and the `--port` value in runtimeArgs — a\n // stale runtimeArgs (even when the port field matches) makes the preview\n // tool launch on the wrong port. Only write when something actually changed.\n let changed = false\n if (Number(existing.port) !== port) {\n existing.port = port\n changed = true\n }\n if (Array.isArray(existing.runtimeArgs)) {\n const ra = existing.runtimeArgs.map(String)\n const pi = ra.indexOf('--port')\n if (pi >= 0 && pi + 1 < ra.length) {\n if (ra[pi + 1] !== String(port)) {\n ra[pi + 1] = String(port)\n changed = true\n }\n } else {\n ra.push('--port', String(port))\n changed = true\n }\n if (changed) existing.runtimeArgs = ra\n }\n if (changed) writeLaunchFile(launchPath, config)\n return\n }\n config.configurations.push({\n name: appName,\n runtimeExecutable: 'npx',\n runtimeArgs: ['deepspace', 'dev', 'start', '--port', String(port)],\n port,\n })\n writeLaunchFile(launchPath, config)\n } catch {\n // best-effort only\n }\n}\n\n/**\n * The port `kill` should target for the app at `appDir` when no `--port` was\n * given and we're not in a worktree (DEV-2): the port recorded in the app's own\n * `.claude/launch.json` entry, which `dev --port` keeps in sync (see above).\n * Falls back to null (caller uses the default) when there's no launch.json,\n * no matching entry, or a malformed file.\n */\nexport function resolveAppLaunchPort(appDir: string): number | null {\n try {\n const config = readLaunchFile(join(appDir, '.claude', 'launch.json'))\n if (!config) return null\n const appName = detectAppName(appDir) ?? basename(appDir)\n const entry =\n config.configurations.find((c) => c?.name === appName) ??\n (config.configurations.length === 1 ? config.configurations[0] : undefined)\n const port = Number(entry?.port)\n return Number.isInteger(port) && port > 0 ? port : null\n } catch {\n return null\n }\n}\n\n/**\n * Detect whether `appDir` lives inside a Claude Code worktree\n * (`<root>/.claude/worktrees/<name>/...`). Returns the main repo root (the\n * directory containing `.claude`) and the worktree name, or null.\n *\n * The Claude desktop preview tool starts dev servers from the session's\n * primary working directory and reads only the MAIN repo's\n * `.claude/launch.json` — a worktree's own launch.json is never read\n * (anthropics/claude-code#56688). Detecting this lets `dev` seed a\n * `cwd`-pinned entry where the tool will actually look.\n */\nexport function detectClaudeWorktree(\n appDir: string,\n): { mainRepoRoot: string; worktreeName: string } | null {\n const segments = resolve(appDir).split(sep)\n // Innermost match wins: worktrees are created under the *session root's*\n // .claude/worktrees, so a nested worktree implies the session is rooted at\n // the outer worktree — that outer root's launch.json is the one the\n // session's preview tool reads.\n for (let i = segments.length - 3; i >= 1; i--) {\n if (segments[i] === '.claude' && segments[i + 1] === 'worktrees' && segments[i + 2]) {\n return {\n mainRepoRoot: segments.slice(0, i).join(sep) || sep,\n worktreeName: segments[i + 2],\n }\n }\n }\n return null\n}\n\nconst WORKTREE_ENTRY_PREFIX = 'wt-'\nconst WORKTREE_PORT_MIN = 5180\nconst WORKTREE_PORT_RANGE = 20\n\n/**\n * Deterministic per-worktree preview port in the worktree band\n * (5180–5199), distinct from the default 5173 so a preview server for the\n * worktree never collides with a main-repo dev server. Stable across runs\n * for the same worktree name. Hash collisions between worktree names are\n * resolved at write time by `upsertWorktreeLaunchConfig`, which probes past\n * ports already claimed by other launch.json entries.\n */\nexport function deriveWorktreePort(worktreeName: string): number {\n let hash = 0\n for (const ch of worktreeName) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0\n return WORKTREE_PORT_MIN + (hash % WORKTREE_PORT_RANGE)\n}\n\nexport interface WorktreeLaunchOptions {\n /** Desired port for the entry (and for the current dev run). */\n port: number\n /**\n * When true, bump the port past any port already claimed by another\n * launch.json entry (wrapping within 5180–5199). Off for an explicit\n * --port, which is honored verbatim.\n */\n probePort?: boolean\n /** Extra `deepspace dev start` args to preserve in the entry (e.g. --prod, --env). */\n extraArgs?: string[]\n}\n\n/**\n * Upsert a `cwd`-pinned entry named `wt-<worktreeName>` into the MAIN repo's\n * `.claude/launch.json`, so the Claude desktop preview tool (which only reads\n * that file) starts the dev server inside the worktree instead of serving the\n * main repo's stale code. Also prunes `wt-*` entries whose absolute `cwd` no\n * longer exists (deleted worktrees) — relative `cwd`s are left alone, since\n * `existsSync` would resolve them against this process's cwd, not the\n * preview tool's. All other entries are preserved verbatim.\n *\n * Returns the entry name and the (possibly probed) port on success, or null\n * if the file was malformed or unwritable — best-effort: must never block\n * `dev` from starting, but the caller should warn, since a missing entry\n * means the preview tool will serve the main repo's code.\n */\nexport function upsertWorktreeLaunchConfig(\n mainRepoRoot: string,\n worktreeName: string,\n appDir: string,\n opts: WorktreeLaunchOptions,\n): { entryName: string; port: number } | null {\n const launchPath = join(mainRepoRoot, '.claude', 'launch.json')\n const entryName = WORKTREE_ENTRY_PREFIX + worktreeName\n try {\n const config = readLaunchFile(launchPath)\n if (!config) return null\n // Ownership check for pruning: only entries whose cwd lives under this\n // repo's .claude/worktrees/ could have been written by us. A hand-authored\n // wt-* entry pointing elsewhere (or at an unmounted volume) is never ours\n // to delete.\n const worktreesRoot = join(mainRepoRoot, '.claude', 'worktrees') + sep\n config.configurations = config.configurations.filter((c) => {\n if (c?.name === entryName) return false // replaced below\n const isStaleWorktreeEntry =\n typeof c?.name === 'string' &&\n c.name.startsWith(WORKTREE_ENTRY_PREFIX) &&\n typeof c.cwd === 'string' &&\n isAbsolute(c.cwd) &&\n c.cwd.startsWith(worktreesRoot) &&\n !existsSync(c.cwd)\n return !isStaleWorktreeEntry\n })\n\n let port = opts.port\n if (opts.probePort) {\n // Number() coercion so a hand-edited string port (\"5186\") still counts\n // as claimed.\n const taken = new Set(\n config.configurations\n .map((c) => Number(c?.port))\n .filter((p) => Number.isInteger(p) && p > 0),\n )\n for (let i = 0; i < WORKTREE_PORT_RANGE && taken.has(port); i++) {\n port = WORKTREE_PORT_MIN + ((port - WORKTREE_PORT_MIN + 1) % WORKTREE_PORT_RANGE)\n }\n }\n\n config.configurations.push({\n name: entryName,\n runtimeExecutable: 'npx',\n runtimeArgs: ['deepspace', 'dev', 'start', '--port', String(port), ...(opts.extraArgs ?? [])],\n port,\n // `cwd` is honored verbatim by the desktop preview tool (documented in\n // the Claude Code desktop launch.json reference alongside `port`) and\n // verified end-to-end: with it set, the preview server builds from the\n // worktree instead of the session's main repo.\n cwd: resolve(appDir),\n })\n writeLaunchFile(launchPath, config)\n return { entryName, port }\n } catch {\n return null\n }\n}\n\n/**\n * The port dev/test/kill should default to inside a Claude Code worktree, so\n * all three commands target the same server (`test` against a different port\n * silently exercises the main repo's code via Playwright's\n * reuseExistingServer). The `wt-<name>` entry in the main repo's launch.json\n * is the source of truth — it includes any probing `dev` applied; fall back\n * to the derived port when it doesn't exist yet. Returns null outside a\n * worktree.\n */\nexport function resolveWorktreePort(appDir: string): number | null {\n const worktree = detectClaudeWorktree(appDir)\n if (!worktree) return null\n try {\n const config = readLaunchFile(join(worktree.mainRepoRoot, '.claude', 'launch.json'))\n const entry = config?.configurations.find(\n (c) => c?.name === WORKTREE_ENTRY_PREFIX + worktree.worktreeName,\n )\n const port = Number(entry?.port)\n if (Number.isInteger(port) && port > 0) return port\n } catch {\n // malformed launch.json — fall through to the derived port\n }\n return deriveWorktreePort(worktree.worktreeName)\n}\n","/** Local `.dev.vars` parsing, preservation, and SDK-managed writes. */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { PLATFORM_URLS } from '../env'\nimport { readAppId } from './app-identity'\nimport { fetchAppIdentityToken, fetchPublicKey, mintAppOwnerJwt } from './app-tokens'\nimport { stripGeneratedSecretsCache } from './secrets'\nimport { writeSecretFileSync } from './secure-file'\nimport { devVarsPathFor } from './wrangler-env'\n\n/** Keys rewritten from platform truth on every dev, test, and deploy run. */\nconst SDK_MANAGED_KEYS = new Set([\n 'AUTH_JWT_PUBLIC_KEY',\n 'AUTH_JWT_ISSUER',\n 'AUTH_WORKER_URL',\n 'API_WORKER_URL',\n 'PLATFORM_WORKER_URL',\n 'OWNER_USER_ID',\n 'APP_OWNER_JWT',\n 'APP_IDENTITY_TOKEN',\n 'ALLOW_DEBUG_ROUTES',\n])\n\nexport const DEV_VARS_DIVIDER = '# --- not managed by the SDK; preserved across dev/test runs ---'\n\ninterface WriteDevVarsOptions {\n appId?: string\n /** Rendered remote secrets cache, which replaces legacy preserved values. */\n generatedSecretsCache?: string\n /** Linked configs share `.dev.vars`; unlinked apps use `.dev.vars.<env>`. */\n sharedDevVarsCache?: boolean\n}\n\n/**\n * Strip SDK-managed lines above the divider while preserving all other content\n * verbatim, including comments and multi-line quoted values.\n */\nexport function extractCustomDevVars(content: string): string {\n const lines = content.split('\\n')\n const out: string[] = []\n let belowDivider = false\n let i = 0\n while (i < lines.length) {\n const line = lines[i]\n if (line.trim() === DEV_VARS_DIVIDER.trim()) {\n belowDivider = true\n i++\n continue\n }\n const eq = line.indexOf('=')\n const keyMatch = eq >= 0 ? line.slice(0, eq).match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*$/) : null\n if (!keyMatch) {\n out.push(line)\n i++\n continue\n }\n const key = keyMatch[1]\n const valueStart = line.slice(eq + 1)\n const block: string[] = [line]\n if (valueStart.startsWith('\"') && !hasUnescapedQuote(valueStart.slice(1))) {\n i++\n while (i < lines.length) {\n block.push(lines[i])\n const closed = hasUnescapedQuote(lines[i])\n i++\n if (closed) break\n }\n } else {\n i++\n }\n if (belowDivider || !SDK_MANAGED_KEYS.has(key)) out.push(...block)\n }\n while (out.length && out[out.length - 1].trim() === '') out.pop()\n return out.join('\\n')\n}\n\nfunction hasUnescapedQuote(value: string): boolean {\n let escaped = false\n for (const char of value) {\n if (escaped) {\n escaped = false\n continue\n }\n if (char === '\\\\') {\n escaped = true\n continue\n }\n if (char === '\"') return true\n }\n return false\n}\n\n/** Parse values used by deploy safety checks from a dotenv-formatted string. */\nexport function parseDevVars(content: string): Record<string, string> {\n const result: Record<string, string> = {}\n const lines = content.split('\\n')\n let i = 0\n while (i < lines.length) {\n const line = lines[i]\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith('#')) {\n i++\n continue\n }\n const eq = line.indexOf('=')\n if (eq < 0) {\n i++\n continue\n }\n const keyMatch = line.slice(0, eq).match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*$/)\n if (!keyMatch) {\n i++\n continue\n }\n const key = keyMatch[1]\n let value = line.slice(eq + 1)\n\n let closed = !value.startsWith('\"') || hasUnescapedQuote(value.slice(1))\n if (!closed) {\n i++\n while (i < lines.length) {\n value += '\\n' + lines[i]\n if (hasUnescapedQuote(lines[i])) {\n closed = true\n i++\n break\n }\n i++\n }\n } else {\n i++\n }\n\n if (value.startsWith('\"') && !closed) {\n throw new Error(\n `parseDevVars: unterminated quoted value for key \"${key}\" — check your .dev.vars file for a missing closing quote.`,\n )\n }\n if (value.startsWith('\"') && value.endsWith('\"') && value.length >= 2) {\n value = unescapeQuotedDevVar(value.slice(1, -1))\n }\n result[key] = value\n }\n return result\n}\n\nfunction unescapeQuotedDevVar(value: string): string {\n let out = ''\n for (let i = 0; i < value.length; i++) {\n const char = value[i]\n if (char !== '\\\\' || i === value.length - 1) {\n out += char\n continue\n }\n const next = value[i + 1]\n if (next === '\\\\' || next === '\"') {\n out += next\n i++\n continue\n }\n out += char\n }\n return out\n}\n\nfunction requireAppIdFor(appDir: string, wranglerEnv?: string): string {\n const id = readAppId(appDir, wranglerEnv)\n if (id) return id\n throw new Error(\n 'wrangler.toml has no DEEPSPACE_APP_ID' +\n (wranglerEnv ? ` for [env.${wranglerEnv}]` : '') +\n '. Run `deepspace app init` (or `deepspace app init --env <name>`) and retry.',\n )\n}\n\n/** Rewrite the SDK section and preserve user-owned values below it. */\nexport async function writeDevVars(\n appDir: string,\n ownerId: string,\n callerJwt: string,\n wranglerEnv?: string,\n opts: WriteDevVarsOptions = {},\n): Promise<void> {\n const urls = PLATFORM_URLS\n const publicKey = await fetchPublicKey(urls.auth)\n const appId = opts.appId ?? requireAppIdFor(appDir, wranglerEnv)\n const appOwnerJwt = await mintAppOwnerJwt(urls.auth, callerJwt, appId)\n const appIdentityToken = await fetchAppIdentityToken(urls.deploy, callerJwt, appId)\n\n // Wrangler requires quotes around multi-line PEM values.\n const sdkVars = [\n `AUTH_JWT_PUBLIC_KEY=\"${publicKey}\"`,\n `AUTH_JWT_ISSUER=${urls.auth}/api/auth`,\n `AUTH_WORKER_URL=${urls.auth}`,\n `API_WORKER_URL=${urls.api}`,\n `PLATFORM_WORKER_URL=${urls.platform}`,\n `OWNER_USER_ID=${ownerId}`,\n `APP_OWNER_JWT=${appOwnerJwt}`,\n ...(appIdentityToken ? [`APP_IDENTITY_TOKEN=${appIdentityToken}`] : []),\n `ALLOW_DEBUG_ROUTES=true`,\n ].join('\\n')\n\n const useSharedDevVarsCache = opts.sharedDevVarsCache ?? opts.generatedSecretsCache !== undefined\n const devVarsPath = devVarsPathFor(appDir, wranglerEnv, {\n sharedDevVarsCache: useSharedDevVarsCache,\n })\n const existing = existsSync(devVarsPath) ? readFileSync(devVarsPath, 'utf-8') : ''\n const custom =\n opts.generatedSecretsCache ??\n extractCustomDevVars(stripGeneratedSecretsCache(existing).trimEnd())\n let body: string\n if (!custom) {\n body = `${sdkVars}\\n`\n } else if (opts.generatedSecretsCache) {\n body = `${sdkVars}\\n\\n${custom}\\n`\n } else {\n body = `${sdkVars}\\n\\n${DEV_VARS_DIVIDER}\\n${custom}\\n`\n }\n\n writeSecretFileSync(devVarsPath, body)\n}\n","/** Platform calls that obtain app-scoped credentials for local execution. */\n\n/** Fetch the JWT public key from an auth worker's JWKS endpoint. */\nexport async function fetchPublicKey(authUrl: string): Promise<string> {\n const response = await fetch(`${authUrl}/api/auth/jwks`)\n if (!response.ok) {\n throw new Error(`Failed to fetch JWT public key (${response.status})`)\n }\n const body = (await response.json()) as { publicKey?: string }\n if (!body.publicKey) throw new Error('JWKS response missing publicKey')\n return body.publicKey\n}\n\n/** Mint a long-lived owner token bound to the app's immutable id. */\nexport async function mintAppOwnerJwt(\n authUrl: string,\n callerJwt: string,\n appId: string,\n): Promise<string> {\n const response = await fetch(`${authUrl}/api/auth/mint-app-token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${callerJwt}`,\n },\n body: JSON.stringify({ appId }),\n })\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n throw new Error(`Failed to mint APP_OWNER_JWT (${response.status}): ${detail}`)\n }\n const body = (await response.json()) as { token?: string; error?: string }\n if (!body.token) {\n throw new Error(`Auth worker returned no token: ${body.error ?? 'unknown error'}`)\n }\n return body.token\n}\n\n/**\n * Fetch the app-origin identity token. A missing app is expected before its\n * first deployment and therefore returns null.\n */\nexport async function fetchAppIdentityToken(\n deployUrl: string,\n callerJwt: string,\n appId: string,\n): Promise<string | null> {\n const response = await fetch(\n `${deployUrl}/api/apps/${encodeURIComponent(appId)}/identity-token`,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${callerJwt}` },\n },\n )\n if (response.status === 404) return null\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n throw new Error(`Failed to fetch APP_IDENTITY_TOKEN (${response.status}): ${detail}`)\n }\n const body = (await response.json()) as { token?: string; error?: string }\n if (!body.token) {\n throw new Error(`Deploy worker returned no token: ${body.error ?? 'unknown error'}`)\n }\n return body.token\n}\n","/**\n * Binding Manifest — non-DO bindings declared by an app's wrangler.toml that\n * the deploy-worker should pass through to Cloudflare's WfP upload API.\n *\n * Apps don't export a `__BINDING_MANIFEST__`; the CLI extracts these from the\n * normalized vite/wrangler output config at deploy time. This file just owns\n * the types + validation so both sides (CLI client and deploy-worker server)\n * agree on the shape.\n */\n/// <reference types=\"@cloudflare/workers-types\" />\n\n/**\n * A single non-DO binding the app declares. Mirrors CF's WfP binding API.\n *\n * Provisionable resources (d1, kv_namespace, vectorize, r2_bucket, queue) accept\n * the literal string `\"auto\"` in their ID field to request platform-side\n * provisioning at deploy time. When `\"auto\"` is used, the deploy-worker creates\n * the resource on the platform CF account, persists the resulting CF ID in the\n * app registry, and substitutes the real ID before forwarding to WfP. The\n * sentinel sticks around in this type because:\n * 1. `wrangler` parsing requires a non-empty string in the id field\n * 2. The CLI passes the unresolved manifest through to the deploy-worker\n * 3. The deploy-worker is the only side with CF API credentials\n *\n * Companion fields (`database_name`, `title`, `dimensions`, `metric`) are only\n * used when `\"auto\"` is set — they tell the provisioner how to create the\n * resource. After provisioning these fields are still present on the wire but\n * ignored by WfP.\n */\nexport type CustomBinding =\n | {\n type: 'vectorize'\n name: string\n /** Either a pre-existing index name or the literal `\"auto\"`. */\n index_name: string\n /** Required when `index_name === \"auto\"`. */\n dimensions?: number\n /** Required when `index_name === \"auto\"`. */\n metric?: 'cosine' | 'euclidean' | 'dot-product'\n }\n | { type: 'ai'; name: string }\n | {\n type: 'r2_bucket'\n name: string\n /** Either a pre-existing bucket name or the literal `\"auto\"`. */\n bucket_name: string\n }\n | {\n type: 'kv_namespace'\n name: string\n /** Either a pre-existing KV namespace ID or the literal `\"auto\"`. */\n namespace_id: string\n /** Required when `namespace_id === \"auto\"`. Human-readable namespace title. */\n title?: string\n }\n | {\n type: 'd1'\n name: string\n /** Either a pre-existing D1 database UUID or the literal `\"auto\"`. */\n id: string\n /** Required when `id === \"auto\"`. Human-readable database name. */\n database_name?: string\n }\n | {\n type: 'queue'\n name: string\n /** Either a pre-existing queue name or the literal `\"auto\"`. */\n queue_name: string\n }\n | { type: 'browser_rendering'; name: string }\n | { type: 'analytics_engine'; name: string; dataset?: string }\n | { type: 'hyperdrive'; name: string; id: string }\n\nexport type CustomBindingManifest = CustomBinding[]\n\n/** Sentinel string in an ID field that requests platform-side provisioning. */\nexport const AUTO_PROVISION_SENTINEL = 'auto'\n\n/** Binding types whose ID field accepts the `\"auto\"` sentinel for provisioning. */\nexport const AUTO_PROVISIONABLE_TYPES = new Set([\n 'd1',\n 'kv_namespace',\n 'vectorize',\n 'r2_bucket',\n 'queue',\n])\n\n/** Vectorize metric values accepted by CF when creating an index. */\nconst VECTORIZE_METRICS = new Set(['cosine', 'euclidean', 'dot-product'])\n\n/**\n * True if a binding has the `\"auto\"` sentinel in its primary ID field. Used by\n * the deploy-worker to decide which entries need provisioning and by the\n * validator to enforce companion-field requirements.\n */\nexport function isAutoProvision(b: CustomBinding): boolean {\n switch (b.type) {\n case 'd1':\n return b.id === AUTO_PROVISION_SENTINEL\n case 'kv_namespace':\n return b.namespace_id === AUTO_PROVISION_SENTINEL\n case 'vectorize':\n return b.index_name === AUTO_PROVISION_SENTINEL\n case 'r2_bucket':\n return b.bucket_name === AUTO_PROVISION_SENTINEL\n case 'queue':\n return b.queue_name === AUTO_PROVISION_SENTINEL\n default:\n return false\n }\n}\n\n/** Binding `type` values an app is allowed to declare. */\nexport const ALLOWED_BINDING_TYPES = new Set([\n 'vectorize',\n 'ai',\n 'r2_bucket',\n 'kv_namespace',\n 'd1',\n 'queue',\n 'browser_rendering',\n 'analytics_engine',\n 'hyperdrive',\n])\n\n/**\n * Binding NAMES the SDK reserves on every app — apps may not redeclare them.\n *\n * Includes:\n * - Static-asset + service bindings the platform sets up automatically.\n * - SDK-managed env (auth, identity, owner JWT).\n * - The auto-attached cost-tracking AE dataset (`USAGE_EVENTS`).\n *\n * DO binding names (RECORD_ROOMS, YJS_ROOMS, etc.) are NOT in this set\n * because they live in a separate manifest (`__DO_MANIFEST__`).\n */\nexport const RESERVED_BINDING_NAMES = new Set([\n 'ASSETS',\n 'PLATFORM_WORKER',\n 'API_WORKER',\n 'APP_NAME',\n 'OWNER_USER_ID',\n 'AUTH_JWT_PUBLIC_KEY',\n 'AUTH_JWT_ISSUER',\n 'AUTH_WORKER_URL',\n 'APP_IDENTITY_TOKEN',\n 'APP_OWNER_JWT',\n 'USAGE_EVENTS',\n])\n\n/**\n * Per-binding validation error. `binding` is undefined for top-level\n * shape failures (e.g. manifest is not an array).\n */\nexport interface ValidationError {\n binding?: CustomBinding\n reason: string\n}\n\n/**\n * Validate a binding manifest. Returns errors; an empty array means valid.\n *\n * Used both client-side (CLI) for friendly fail-fast and server-side\n * (deploy-worker) as a security boundary — apps can't sneak in reserved\n * binding names by editing the wire format.\n */\nexport function validateBindingManifest(\n manifest: unknown,\n): { valid: true; bindings: CustomBindingManifest } | { valid: false; errors: ValidationError[] } {\n if (!Array.isArray(manifest)) {\n return { valid: false, errors: [{ reason: 'Manifest must be an array' }] }\n }\n const errors: ValidationError[] = []\n const seenNames = new Set<string>()\n for (const entry of manifest) {\n if (!entry || typeof entry !== 'object') {\n errors.push({ reason: `Entry must be an object (got ${entry === null ? 'null' : typeof entry})` })\n continue\n }\n const e = entry as Record<string, unknown>\n const type = e.type\n const name = e.name\n if (typeof type !== 'string' || !ALLOWED_BINDING_TYPES.has(type)) {\n errors.push({\n reason: `Disallowed binding type: ${typeof type === 'string' ? type : `(${typeof type})`}. Allowed: ${[...ALLOWED_BINDING_TYPES].sort().join(', ')}`,\n })\n continue\n }\n if (typeof name !== 'string' || !name) {\n errors.push({ reason: `Binding of type \"${type}\" missing 'name' (string)` })\n continue\n }\n if (RESERVED_BINDING_NAMES.has(name)) {\n errors.push({ reason: `Binding name \"${name}\" is reserved by the SDK` })\n continue\n }\n if (seenNames.has(name)) {\n errors.push({ reason: `Duplicate binding name \"${name}\"` })\n continue\n }\n seenNames.add(name)\n // Now safely typed: type is in ALLOWED_BINDING_TYPES + name is a string.\n const binding = entry as CustomBinding\n const fieldErr = requiredFieldError(binding)\n if (fieldErr) errors.push({ binding, reason: fieldErr })\n }\n if (errors.length) return { valid: false, errors }\n return { valid: true, bindings: manifest as CustomBindingManifest }\n}\n\nfunction requiredFieldError(b: CustomBinding): string | null {\n switch (b.type) {\n case 'vectorize': {\n if (!b.index_name) return `vectorize binding \"${b.name}\" missing index_name (or \"auto\")`\n if (b.index_name === AUTO_PROVISION_SENTINEL) {\n // Auto-provisioning needs the index shape upfront — CF requires both\n // dimensions and metric at index-create time.\n if (typeof b.dimensions !== 'number' || b.dimensions <= 0) {\n return `vectorize binding \"${b.name}\" with index_name=\"auto\" requires \"dimensions\" (positive number)`\n }\n if (!b.metric || !VECTORIZE_METRICS.has(b.metric)) {\n return `vectorize binding \"${b.name}\" with index_name=\"auto\" requires \"metric\" (one of: ${[...VECTORIZE_METRICS].join(', ')})`\n }\n }\n return null\n }\n case 'r2_bucket':\n return b.bucket_name ? null : `r2_bucket binding \"${b.name}\" missing bucket_name (or \"auto\")`\n case 'kv_namespace': {\n if (!b.namespace_id) return `kv_namespace binding \"${b.name}\" missing namespace_id (or \"auto\")`\n if (b.namespace_id === AUTO_PROVISION_SENTINEL && !b.title) {\n return `kv_namespace binding \"${b.name}\" with namespace_id=\"auto\" requires \"title\"`\n }\n return null\n }\n case 'd1': {\n if (!b.id) return `d1 binding \"${b.name}\" missing id (or \"auto\")`\n if (b.id === AUTO_PROVISION_SENTINEL && !b.database_name) {\n return `d1 binding \"${b.name}\" with id=\"auto\" requires \"database_name\"`\n }\n return null\n }\n case 'queue':\n return b.queue_name ? null : `queue binding \"${b.name}\" missing queue_name (or \"auto\")`\n case 'hyperdrive':\n // Hyperdrive auto-provisioning is out of scope for v1 (needs upstream\n // connection-string management). Only pre-existing IDs accepted.\n if (!b.id) return `hyperdrive binding \"${b.name}\" missing id`\n if (b.id === AUTO_PROVISION_SENTINEL) {\n return `hyperdrive binding \"${b.name}\": auto-provisioning not yet supported (provide a real id)`\n }\n return null\n case 'ai':\n case 'browser_rendering':\n case 'analytics_engine':\n return null // no required fields beyond `name`\n default: {\n // Exhaustiveness guard — adding a new variant without a case fails here.\n const _exhaustive: never = b\n void _exhaustive\n return null\n }\n }\n}\n\n/**\n * Convert vite/wrangler's normalized config (from `.wrangler/deploy/config.json`)\n * into a CustomBindingManifest.\n *\n * Vite normalizes wrangler.toml into object/array structures with shapes like\n * `{ ai: { binding: 'AI' } }`, `{ vectorize: [{ binding, index_name }] }`,\n * etc. We extract each known shape with explicit field plucks (no broad\n * `as` casts) and return a flat array.\n */\nexport function bindingManifestFromOutputConfig(\n outputConfig: Record<string, unknown>,\n): CustomBindingManifest {\n const out: CustomBindingManifest = []\n\n // ai: single object\n const aiBinding = pluckString(outputConfig.ai, 'binding')\n if (aiBinding) out.push({ type: 'ai', name: aiBinding })\n\n // vectorize: array of { binding, index_name, dimensions?, metric? }\n // `dimensions` and `metric` are only required when index_name === \"auto\"\n // (auto-provisioning); the validator enforces that, so we just pluck both\n // here and let it decide.\n for (const v of asObjectArray(outputConfig.vectorize)) {\n const name = pluckString(v, 'binding')\n const index_name = pluckString(v, 'index_name')\n if (!name || !index_name) continue\n const dimensions = pluckNumber(v, 'dimensions')\n const metric = pluckString(v, 'metric')\n out.push({\n type: 'vectorize',\n name,\n index_name,\n ...(dimensions != null && { dimensions }),\n ...(metric && (metric === 'cosine' || metric === 'euclidean' || metric === 'dot-product') && { metric }),\n })\n }\n\n // r2_buckets: array of { binding, bucket_name }\n for (const r of asObjectArray(outputConfig.r2_buckets)) {\n const name = pluckString(r, 'binding')\n const bucket_name = pluckString(r, 'bucket_name')\n if (name && bucket_name) out.push({ type: 'r2_bucket', name, bucket_name })\n }\n\n // kv_namespaces: array of { binding, id, title? }\n // `title` is only required when id === \"auto\"; pluck both here and let\n // the validator enforce the dependency.\n for (const k of asObjectArray(outputConfig.kv_namespaces)) {\n const name = pluckString(k, 'binding')\n const namespace_id = pluckString(k, 'id')\n if (!name || !namespace_id) continue\n const title = pluckString(k, 'title')\n out.push({\n type: 'kv_namespace',\n name,\n namespace_id,\n ...(title && { title }),\n })\n }\n\n // d1_databases: array of { binding, database_id, database_name? }\n // `database_name` is only required when database_id === \"auto\"; pluck both\n // and let the validator enforce.\n for (const d of asObjectArray(outputConfig.d1_databases)) {\n const name = pluckString(d, 'binding')\n const id = pluckString(d, 'database_id')\n if (!name || !id) continue\n const database_name = pluckString(d, 'database_name')\n out.push({\n type: 'd1',\n name,\n id,\n ...(database_name && { database_name }),\n })\n }\n\n // queues.producers: array of { binding, queue }\n const queues = isObject(outputConfig.queues) ? outputConfig.queues : null\n for (const q of asObjectArray(queues?.producers)) {\n const name = pluckString(q, 'binding')\n const queue_name = pluckString(q, 'queue')\n if (name && queue_name) out.push({ type: 'queue', name, queue_name })\n }\n\n // browser: { binding } (Cloudflare names this `browser` not `browser_rendering`)\n const browserBinding = pluckString(outputConfig.browser, 'binding')\n if (browserBinding) out.push({ type: 'browser_rendering', name: browserBinding })\n\n // analytics_engine_datasets: array of { binding, dataset? }\n for (const a of asObjectArray(outputConfig.analytics_engine_datasets)) {\n const name = pluckString(a, 'binding')\n const dataset = pluckString(a, 'dataset')\n if (name) out.push({ type: 'analytics_engine', name, dataset: dataset ?? undefined })\n }\n\n // hyperdrive: array of { binding, id }\n for (const h of asObjectArray(outputConfig.hyperdrive)) {\n const name = pluckString(h, 'binding')\n const id = pluckString(h, 'id')\n if (name && id) out.push({ type: 'hyperdrive', name, id })\n }\n\n return out\n}\n\n// ---- internal helpers (no broad `as` casts) ----\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\nfunction pluckString(v: unknown, key: string): string | null {\n if (!isObject(v)) return null\n const val = v[key]\n return typeof val === 'string' && val.length > 0 ? val : null\n}\n\nfunction pluckNumber(v: unknown, key: string): number | null {\n if (!isObject(v)) return null\n const val = v[key]\n return typeof val === 'number' && Number.isFinite(val) ? val : null\n}\n\nfunction asObjectArray(v: unknown): Record<string, unknown>[] {\n if (!Array.isArray(v)) return []\n return v.filter(isObject)\n}\n","/**\n * App secrets — client helpers for the app-anchored store\n * (docs/proposals/app-identity-registry.md §4.3).\n *\n * Every app has exactly one store, addressed by its immutable id:\n * `/api/secrets/:appId/configs/:config/...` on the deploy worker. Configs\n * follow the wrangler-env convention: the top-level config is `prd`, an\n * `--env staging` deploy ships the `staging` config. There are no per-user\n * projects and no app↔project links — those concepts are gone.\n */\n\nimport { RESERVED_BINDING_NAMES } from '../../server/rooms/binding-manifest'\nimport { ApiError } from './api'\n\nexport const GENERATED_SECRETS_DIVIDER =\n '# --- DeepSpace secrets cache: generated by `npx deepspace secrets`; do not edit manually ---'\n\n/**\n * Names a user may not set as an app secret. `RESERVED_BINDING_NAMES` covers\n * runtime bindings the platform injects; `API_WORKER_URL`/`PLATFORM_WORKER_URL`\n * are SDK-managed env that isn't a binding (so absent from that set) but is\n * still platform-owned. `ALLOW_DEBUG_ROUTES` is deliberately NOT here — it's a\n * normal, user-settable flag. Rejecting these client-side gives a clear message\n * instead of a raw server `(400)` that leaks the API path.\n */\nconst RESERVED_SECRET_NAMES = new Set([\n ...RESERVED_BINDING_NAMES,\n 'API_WORKER_URL',\n 'PLATFORM_WORKER_URL',\n])\n\nexport const SECRET_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/\nexport const CONFIG_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/\nconst MAX_SECRET_VALUE_BYTES = 32 * 1024\n\nexport interface SecretListItem {\n key: string\n version: number\n updatedAt: string\n updatedBy: string\n}\n\nexport interface SecretsConfigInfo {\n name: string\n createdAt: string\n updatedAt: string\n secretCount?: number\n}\n\nexport interface PulledSecretsCache {\n appId: string\n configName: string\n values: Record<string, string>\n}\n\nexport type SecretsDownloadFormat = 'dotenv' | 'json' | 'shell'\n\nexport function validateConfigName(configName: string): string {\n if (!CONFIG_NAME_RE.test(configName)) {\n throw new Error(\n `Invalid config \"${configName}\". Use letters, numbers, underscores, or hyphens; start with a letter or number.`,\n )\n }\n return configName\n}\n\nexport function validateSecretName(name: string): string {\n if (!SECRET_NAME_RE.test(name)) {\n throw new Error(\n `Invalid secret name \"${name}\". Use letters, numbers, and underscores; start with a letter or underscore.`,\n )\n }\n if (RESERVED_SECRET_NAMES.has(name)) {\n throw new Error(\n `\"${name}\" is managed by the DeepSpace SDK and can't be set as an app secret — ` +\n 'the platform injects it at deploy time.',\n )\n }\n return name\n}\n\nexport function validateSecretValue(key: string, value: string): void {\n if (new TextEncoder().encode(value).byteLength > MAX_SECRET_VALUE_BYTES) {\n throw new Error(`Secret \"${key}\" exceeds ${MAX_SECRET_VALUE_BYTES} bytes`)\n }\n}\n\n/** Config convention: top-level deploys/dev use `prd`; a wrangler env uses\n * its own name. */\nexport function defaultConfigNameForEnv(wranglerEnv?: string): string {\n return wranglerEnv ?? 'prd'\n}\n\n// ── HTTP plumbing ────────────────────────────────────────────────────────────\n\nexport async function secretsApi<T>(\n deployUrl: string,\n token: string,\n path: string,\n init: RequestInit = {},\n): Promise<T> {\n const res = await fetch(`${deployUrl}/api/secrets${path}`, {\n ...init,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n ...(init.headers ?? {}),\n },\n })\n const body = (await res.json().catch(() => ({}))) as T & { error?: string }\n if (!res.ok) {\n // Surface the server's sentence, not the internal `/api/secrets/app_…/…`\n // slug — that path is an implementation detail and reads like a bug to\n // users. `status` carries the code for programmatic branches; set DEBUG=1\n // (via cli-errors) for the full error. `apiPath` is kept for debugging.\n const err = new Error(body.error ?? `Secrets request failed (${res.status})`) as Error & {\n status?: number\n apiPath?: string\n }\n err.status = res.status\n err.apiPath = path\n throw err\n }\n return body\n}\n\nexport function listSecrets(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n): Promise<{ secrets: SecretListItem[] }> {\n return secretsApi(deployUrl, token, `/${appId}/configs/${encodeURIComponent(configName)}`)\n}\n\nexport function fetchSecretsValues(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n): Promise<{ secrets: Record<string, string> }> {\n return secretsApi(deployUrl, token, `/${appId}/configs/${encodeURIComponent(configName)}/values`)\n}\n\nexport function getSecretPlain(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n key: string,\n): Promise<{ key: string; value: string }> {\n return secretsApi(\n deployUrl,\n token,\n `/${appId}/configs/${encodeURIComponent(configName)}/secrets/${encodeURIComponent(key)}?plain=true`,\n )\n}\n\nexport function setSecret(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n key: string,\n value: string,\n): Promise<{ ok: boolean }> {\n return secretsApi(\n deployUrl,\n token,\n `/${appId}/configs/${encodeURIComponent(configName)}/secrets/${encodeURIComponent(key)}`,\n { method: 'PUT', body: JSON.stringify({ value }) },\n )\n}\n\nexport function deleteSecret(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n key: string,\n): Promise<{ ok: boolean }> {\n return secretsApi(\n deployUrl,\n token,\n `/${appId}/configs/${encodeURIComponent(configName)}/secrets/${encodeURIComponent(key)}`,\n { method: 'DELETE' },\n )\n}\n\nexport function uploadSecrets(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n secrets: Record<string, string>,\n replace: boolean,\n): Promise<{ ok: boolean }> {\n return secretsApi(\n deployUrl,\n token,\n `/${appId}/configs/${encodeURIComponent(configName)}/secrets`,\n { method: 'PUT', body: JSON.stringify({ secrets, replace }) },\n )\n}\n\nexport function listConfigs(\n deployUrl: string,\n token: string,\n appId: string,\n): Promise<{ configs: SecretsConfigInfo[] }> {\n return secretsApi(deployUrl, token, `/${appId}/configs`)\n}\n\nexport function createConfig(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n copyFrom?: string,\n): Promise<{ ok: boolean }> {\n return secretsApi(deployUrl, token, `/${appId}/configs`, {\n method: 'POST',\n body: JSON.stringify({ name: configName, ...(copyFrom ? { copyFrom } : {}) }),\n })\n}\n\nexport function deleteConfig(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n): Promise<{ ok: boolean }> {\n return secretsApi(deployUrl, token, `/${appId}/configs/${encodeURIComponent(configName)}`, {\n method: 'DELETE',\n })\n}\n\n/**\n * Pull the app's config values for dev/test/deploy caches. Missing store or\n * config is NOT an error — a fresh app simply has no secrets yet.\n */\nexport async function pullAppSecretsCache(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n): Promise<PulledSecretsCache | null> {\n try {\n const { secrets } = await fetchSecretsValues(deployUrl, token, appId, configName)\n // A wrong/broken service can answer 200 without the documented `secrets`\n // object (or with null); left unchecked `Object.keys(values)` downstream throws\n // a raw, uncoded `Cannot convert undefined or null to object` on the deploy\n // path. Code it invalid_response — the same slug the repo-API guard uses — so\n // the refresh fails closed with a real message instead of a leaked TypeError.\n if (secrets === null || typeof secrets !== 'object' || Array.isArray(secrets)) {\n throw new ApiError(\n `The secrets service at ${deployUrl} returned an unexpected response shape — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n 200,\n 'invalid_response',\n `/${appId}/configs/${configName}/values`,\n )\n }\n return { appId, configName, values: secrets }\n } catch (err) {\n // 404: no store yet, or no such config. Both mean \"nothing to ship\". Match\n // on the status field, not the message (which no longer carries the code).\n if ((err as { status?: number })?.status === 404) return null\n throw err\n }\n}\n\n// ── Cache rendering / parsing ────────────────────────────────────────────────\n\nexport function quoteDotenvValue(value: string): string {\n if (/^[A-Za-z0-9_./:@+-]*$/.test(value) && value !== '') return value\n // Newlines must be escaped or the value's tail parses as extra env vars;\n // dotenv expands \\n / \\r inside double-quoted values.\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n return `\"${escaped}\"`\n}\n\n/** Render pulled values as the generated `.dev.vars` cache section. */\nexport function renderSecretsCache(\n secrets: Record<string, string>,\n source: { appId: string; configName: string },\n): string {\n const keys = Object.keys(secrets).sort()\n const lines = [\n GENERATED_SECRETS_DIVIDER,\n `# app ${source.appId} · config ${source.configName}`,\n '# Use `npx deepspace secrets` to change these values.',\n ]\n for (const key of keys) {\n validateSecretValue(key, secrets[key])\n lines.push(`${key}=${quoteDotenvValue(secrets[key])}`)\n }\n return lines.join('\\n')\n}\n\n/** Strip a previously generated cache section from a `.dev.vars` body. */\nexport function stripGeneratedSecretsCache(content: string): string {\n const idx = content.indexOf(GENERATED_SECRETS_DIVIDER)\n if (idx === -1) return content\n return content.slice(0, idx).trimEnd() + '\\n'\n}\n\n// ── Upload/download formats (Doppler-compatible) ─────────────────────────────\n\nexport function parseSecretsUpload(content: string): Record<string, string> {\n const trimmed = content.trim()\n if (!trimmed) return {}\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n const parsed = JSON.parse(trimmed) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('JSON upload must be an object of KEY=value strings.')\n }\n const out: Record<string, string> = {}\n for (const [key, value] of Object.entries(parsed)) {\n validateSecretName(key)\n if (typeof value !== 'string') throw new Error(`Secret \"${key}\" must be a string`)\n validateSecretValue(key, value)\n out[key] = value\n }\n return out\n }\n // dotenv — supports multiline quoted values (dotenv ≥15 semantics): a value\n // whose opening quote isn't closed on its own line continues, verbatim,\n // until a line ending with the closing quote. Without this, uploading a\n // .env holding a real PEM silently stored one byte and minted phantom keys\n // from the base64 continuation lines.\n const out: Record<string, string> = {}\n const lines = trimmed.split(/\\r?\\n/)\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim()\n if (!line || line.startsWith('#')) continue\n const eq = line.indexOf('=')\n if (eq <= 0) continue // junk line — tolerated, like comments\n const key = line.slice(0, eq).trim()\n if (!SECRET_NAME_RE.test(key)) continue\n validateSecretName(key) // reject reserved/SDK-managed names with a clear message, same as `set`\n const raw = line.slice(eq + 1).trim()\n const quote = raw[0] === '\"' || raw[0] === \"'\" ? raw[0] : null\n let value: string\n if (!quote) {\n value = raw\n } else if (endsWithUnescapedQuote(raw.slice(1), quote)) {\n const inner = raw.slice(1, -1)\n value = quote === '\"' ? unescapeDotenv(inner) : inner\n } else {\n // Multiline: consume raw (untrimmed) lines until one closes the quote.\n const startLine = i + 1\n const parts = [raw.slice(1)]\n let closed = false\n while (++i < lines.length) {\n const cont = lines[i].trimEnd()\n if (endsWithUnescapedQuote(cont, quote)) {\n parts.push(cont.slice(0, -1))\n closed = true\n break\n }\n parts.push(lines[i])\n }\n if (!closed) {\n throw new Error(\n `Unterminated quoted value for \"${key}\" (opens on line ${startLine}). ` +\n `Close the ${quote === '\"' ? 'double' : 'single'} quote, or escape newlines as \\\\n on one line.`,\n )\n }\n value = parts.join('\\n')\n if (quote === '\"') value = unescapeDotenv(value)\n }\n validateSecretValue(key, value)\n out[key] = value\n }\n return out\n}\n\n/** True when `s` is non-empty and ends with `q` not preceded by an odd run of\n * backslashes (only `\"` values support escapes; `'` closes unconditionally). */\nfunction endsWithUnescapedQuote(s: string, q: string): boolean {\n if (!s.endsWith(q)) return false\n if (q === \"'\") return true\n let backslashes = 0\n for (let j = s.length - 2; j >= 0 && s[j] === '\\\\'; j--) backslashes++\n return backslashes % 2 === 0\n}\n\n/** Left-to-right so `\\\\n` (escaped backslash + n) isn't confused with `\\n`. */\nfunction unescapeDotenv(v: string): string {\n let out = ''\n for (let i = 0; i < v.length; i++) {\n if (v[i] === '\\\\' && i + 1 < v.length) {\n const c = v[++i]\n out += c === 'n' ? '\\n' : c === 'r' ? '\\r' : c\n } else {\n out += v[i]\n }\n }\n return out\n}\n\n/**\n * POSIX single-quote: wrap in `'…'`, closing/reopening around any embedded\n * single quote (`'\\''`). Unlike dotenv double-quoting, this preserves real\n * newlines literally, so `eval \"$(… download --format shell)\"` restores a\n * multiline value (e.g. a PEM key) byte-for-byte instead of a one-line `\\n`.\n */\nexport function shellSingleQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`\n}\n\nexport function formatSecretsDownload(\n secrets: Record<string, string>,\n format: SecretsDownloadFormat,\n): string {\n const entries = Object.entries(secrets).sort(([a], [b]) => a.localeCompare(b))\n if (format === 'json') {\n return JSON.stringify(Object.fromEntries(entries), null, 2) + '\\n'\n }\n if (format === 'shell') {\n return entries.map(([k, v]) => `export ${k}=${shellSingleQuote(v)}`).join('\\n') + '\\n'\n }\n return entries.map(([k, v]) => `${k}=${quoteDotenvValue(v)}`).join('\\n') + '\\n'\n}\n\n/**\n * The pull-and-render step every command shares (deploy/dev/test): fetch the\n * app's config values and render the generated `.dev.vars` cache section.\n * Returns null when the store/config doesn't exist yet (\"nothing to ship\").\n * Real failures (auth, 5xx) throw — callers cancel loudly.\n */\nexport async function refreshSecretsCache(\n deployUrl: string,\n token: string,\n appId: string,\n wranglerEnv: string | undefined,\n): Promise<{ pulled: PulledSecretsCache; rendered: string; summary: string } | null> {\n const configName = defaultConfigNameForEnv(wranglerEnv)\n const pulled = await pullAppSecretsCache(deployUrl, token, appId, configName)\n if (!pulled) return null\n const count = Object.keys(pulled.values).length\n return {\n pulled,\n rendered: renderSecretsCache(pulled.values, pulled),\n summary: `Secrets: ${pulled.configName} (${count} secret${count === 1 ? '' : 's'})`,\n }\n}\n","import { chmodSync, writeFileSync } from 'node:fs'\n\n/**\n * Write a file that holds plaintext secret values (`.dev.vars` caches,\n * `secrets download` output) readable by the owner only. `writeFileSync`'s\n * `mode` applies only when the file is created, so chmod separately to\n * tighten files that already exist with a wider mode.\n */\nexport function writeSecretFileSync(path: string, content: string): void {\n writeFileSync(path, content, { mode: 0o600 })\n try {\n chmodSync(path, 0o600)\n } catch {\n // POSIX modes are best-effort on Windows; the write itself succeeded.\n }\n}\n","/**\n * Wrangler env resolution for DeepSpace's multi-environment deploys.\n *\n * Lets a single repo deploy to `<app>.app.space` and `<app>-staging.app.space`\n * (or any other named environment) from one `wrangler.toml`:\n *\n * name = \"hopkins\"\n * [vars]\n * APP_NAME = \"hopkins\"\n *\n * [env.staging]\n * name = \"hopkins-staging\"\n * [env.staging.vars]\n * APP_NAME = \"hopkins-staging\"\n *\n * Then `npx deepspace deploy --env staging` reads the override and ships to\n * `hopkins-staging.app.space`. The platform treats it as a fully separate\n * app — its own DO state, OAuth tokens, Stripe products, cron schedule.\n * No platform-side change needed beyond letting the CLI register a second\n * app under the same owner.\n *\n * When an app links a remote secrets project, DeepSpace keeps generated\n * dev/test/deploy credentials in a single `.dev.vars` cache so named\n * environments do not leave extra local files. In that linked-secrets mode,\n * `--env` flattens the selected Wrangler env into a generated config for the\n * Cloudflare Vite plugin instead of passing `CLOUDFLARE_ENV`; otherwise\n * Wrangler would prefer legacy `.dev.vars.<env>` files over the shared cache.\n * Unlinked apps keep Wrangler's legacy env-file behavior.\n */\n\nimport { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { parse as parseToml, stringify as stringifyToml } from 'smol-toml'\nimport { resolveAppName } from '../../server/rooms/app-name'\n\n/** Shape of the bits of wrangler.toml that DeepSpace CLI commands read.\n * Add an optional field here whenever a new command starts consulting\n * the config — avoids one-off `WranglerConfig & { … }` casts at\n * call sites and keeps the canonical type in one place. */\nexport interface WranglerConfig {\n name?: string\n env?: Record<\n string,\n ({ name?: string; vars?: Record<string, unknown> } & Record<string, unknown>) | undefined\n >\n /** `[assets]` block (`directory`, `binding`, `not_found_handling`,\n * `run_worker_first`). Consumed by deploy.ts to merge extra\n * worker-first routes into the deployed metadata. */\n assets?: {\n directory?: string\n binding?: string\n not_found_handling?: string\n run_worker_first?: unknown\n }\n /** `[vars]` block — string-valued environment variables baked into\n * the worker at deploy time. */\n vars?: Record<string, unknown>\n}\n\nexport interface PreparedWranglerEnvConfig {\n configPath?: string\n wranglerEnv?: string\n cleanup(): void\n}\n\nexport interface WranglerEnvModeOptions {\n sharedDevVarsCache?: boolean\n}\n\ntype TomlRecord = Record<string, unknown>\n\nconst NON_INHERITABLE_ENV_KEYS = new Set([\n 'define',\n 'vars',\n 'durable_objects',\n 'kv_namespaces',\n 'r2_buckets',\n 'ai_search_namespaces',\n 'ai_search',\n 'vectorize',\n 'services',\n 'queues',\n 'workflows',\n 'tail_consumers',\n 'secrets',\n 'secrets_store_secrets',\n])\n\nlet generatedConfigSeq = 0\n\n/**\n * Resolve the appName that this CLI invocation should target.\n *\n * Without `envName`: returns the top-level `name`.\n * With `envName`: returns `[env.<envName>].name` and requires that the\n * env block exists and declares a name. We refuse to\n * fall back to the top-level name because that would\n * silently deploy staging code to production.\n *\n * Returns a discriminated union so callers can surface a precise error\n * (matches the existing `resolveAppName` contract).\n */\nexport function resolveAppNameForEnv(\n config: WranglerConfig,\n envName: string | undefined,\n): { ok: true; name: string; warning?: string } | { ok: false; reason: string } {\n if (!envName) {\n return resolveAppName(config.name)\n }\n const envBlock = config.env?.[envName]\n if (!envBlock) {\n return {\n ok: false,\n reason:\n `wrangler.toml: no [env.${envName}] block found. ` +\n `Add one with a distinct \\`name\\` to deploy this environment.`,\n }\n }\n if (typeof envBlock.name !== 'string' || envBlock.name.trim() === '') {\n return {\n ok: false,\n reason:\n `wrangler.toml: [env.${envName}].name is missing. ` +\n `Set a distinct app name (e.g. \"${typeof config.name === 'string' ? config.name : 'myapp'}-${envName}\") so this environment doesn't overwrite the default.`,\n }\n }\n if (envBlock.name === config.name) {\n return {\n ok: false,\n reason:\n `wrangler.toml: [env.${envName}].name \"${envBlock.name}\" is the same as the top-level name. ` +\n `Pick a distinct name (e.g. \"${config.name}-${envName}\") so deploys don't collide.`,\n }\n }\n return resolveAppName(envBlock.name)\n}\n\n/** The .dev.vars path for the selected mode. Linked secrets use a shared cache. */\nexport function devVarsPathFor(\n appDir: string,\n envName: string | undefined,\n opts: WranglerEnvModeOptions = {},\n): string {\n if (opts.sharedDevVarsCache || !envName) return join(appDir, '.dev.vars')\n return join(appDir, `.dev.vars.${envName}`)\n}\n\nexport function legacyEnvDevVarsPathFor(\n appDir: string,\n envName: string | undefined,\n): string | undefined {\n return envName ? join(appDir, `.dev.vars.${envName}`) : undefined\n}\n\nexport function warnIfLegacyEnvDevVarsExists(\n appDir: string,\n envName: string | undefined,\n warn: (message: string) => void = console.warn,\n): void {\n const legacyPath = legacyEnvDevVarsPathFor(appDir, envName)\n if (!legacyPath || !existsSync(legacyPath)) return\n warn(\n `Warning: ${legacyPath} exists, but DeepSpace now uses ${devVarsPathFor(appDir, envName, { sharedDevVarsCache: true })} ` +\n `for every environment. This run will ignore ${legacyPath}; move any secrets you still ` +\n `need into .dev.vars, then remove the env-specific file when you're ready.`,\n )\n}\n\nexport function prepareWranglerEnvConfig(\n appDir: string,\n envName: string | undefined,\n opts: { warn?: (message: string) => void } & WranglerEnvModeOptions = {},\n): PreparedWranglerEnvConfig {\n if (!envName) return { cleanup() {} }\n if (!opts.sharedDevVarsCache) return { wranglerEnv: envName, cleanup() {} }\n\n warnIfLegacyEnvDevVarsExists(appDir, envName, opts.warn)\n\n const config = readWranglerConfig(appDir)\n const resolved = resolveAppNameForEnv(config, envName)\n if (!resolved.ok) throw new Error(resolved.reason)\n const flattened = flattenWranglerEnvConfig(config as TomlRecord, envName)\n const configPath = join(\n appDir,\n `.wrangler.deepspace.${safeGeneratedConfigSegment(envName)}.${process.pid}.${++generatedConfigSeq}.toml`,\n )\n writeFileSync(\n configPath,\n [\n '# Generated by DeepSpace for this CLI run.',\n '# Do not edit; wrangler.toml remains the source of truth.',\n stringifyToml(flattened),\n ]\n .join('\\n')\n .replace(/\\s*$/u, '\\n'),\n )\n return {\n configPath,\n cleanup() {\n rmSync(configPath, { force: true })\n },\n }\n}\n\nexport function wranglerViteEnv(\n baseEnv: NodeJS.ProcessEnv,\n prepared: PreparedWranglerEnvConfig,\n extraEnv: NodeJS.ProcessEnv = {},\n): NodeJS.ProcessEnv {\n const env = { ...baseEnv, ...extraEnv }\n if (prepared.configPath) {\n delete env.CLOUDFLARE_ENV\n env.CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH = prepared.configPath\n } else if (prepared.wranglerEnv) {\n env.CLOUDFLARE_ENV = prepared.wranglerEnv\n }\n return env\n}\n\nfunction flattenWranglerEnvConfig(config: TomlRecord, envName: string): TomlRecord {\n const envRoot = asTomlRecord(config.env)\n const envBlock = asTomlRecord(envRoot?.[envName])\n if (!envBlock) {\n throw new Error(`wrangler.toml: no [env.${envName}] block found.`)\n }\n\n const flattened: TomlRecord = {}\n for (const [key, value] of Object.entries(config)) {\n if (key === 'env' || NON_INHERITABLE_ENV_KEYS.has(key)) continue\n flattened[key] = value\n }\n for (const [key, value] of Object.entries(envBlock)) {\n flattened[key] = value\n }\n return flattened\n}\n\nfunction asTomlRecord(value: unknown): TomlRecord | undefined {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as TomlRecord)\n : undefined\n}\n\nfunction safeGeneratedConfigSegment(value: string): string {\n return value.replace(/[^A-Za-z0-9._-]/gu, '_')\n}\n\n/**\n * Read + parse wrangler.toml. Caller checks existence first via\n * `hasWranglerConfig`. Throws a `WranglerConfigError` with the absolute\n * path embedded on a malformed file — saves the user from staring at\n * a raw smol-toml parser stack trace when they have one stray\n * unquoted character in their config.\n */\nexport class WranglerConfigError extends Error {\n constructor(\n public readonly path: string,\n public readonly cause: unknown,\n ) {\n const detail = cause instanceof Error ? cause.message : String(cause)\n super(`wrangler.toml: malformed TOML at ${path}: ${detail}`)\n this.name = 'WranglerConfigError'\n }\n}\n\nexport function readWranglerConfig(appDir: string): WranglerConfig {\n const path = join(appDir, 'wrangler.toml')\n const raw = readFileSync(path, 'utf-8')\n try {\n return parseToml(raw) as WranglerConfig\n } catch (err) {\n throw new WranglerConfigError(path, err)\n }\n}\n\n/** Convenience: true when wrangler.toml exists at the standard path. */\nexport function hasWranglerConfig(appDir: string): boolean {\n return existsSync(join(appDir, 'wrangler.toml'))\n}\n","/**\n * App-name validation + sanitization helpers.\n *\n * Strategy: validate strictly so we have a precise definition of \"valid\",\n * but DON'T reject non-conforming names — sanitize them, warn the user, and\n * proceed. Hard rejection would break apps whose `wrangler.toml name` was\n * something like `My_App` (previously deployed as `my-app` via silent\n * server-side sanitization). The new behavior preserves \"still deploys,\"\n * but the CLI now surfaces a warning so the user can fix the name when\n * convenient instead of being silently surprised by their hostname.\n *\n * Rules track Cloudflare's WfP script-name constraints (RFC 1035 host label,\n * no consecutive dashes) plus our 2-char minimum so subdomains read sensibly.\n */\n\nexport const APP_NAME_RULES = {\n /** ^[a-z0-9](-?[a-z0-9])+$ — RFC 1035 host label, no consecutive dashes. */\n pattern: /^[a-z0-9](?:-?[a-z0-9])+$/,\n minLength: 2,\n maxLength: 63,\n} as const\n\nexport type AppNameValidation =\n | { valid: true; name: string }\n | { valid: false; reason: string }\n\n/**\n * Strict validation: returns valid only if the name already conforms.\n * Useful as a precondition test or for CI lints.\n */\nexport function validateAppName(raw: unknown): AppNameValidation {\n if (typeof raw !== 'string') {\n return { valid: false, reason: 'App name must be a string' }\n }\n const name = raw.trim()\n if (!name) {\n return { valid: false, reason: 'App name is required' }\n }\n if (name.length < APP_NAME_RULES.minLength) {\n return { valid: false, reason: `App name \"${name}\" is too short (min ${APP_NAME_RULES.minLength} chars)` }\n }\n if (name.length > APP_NAME_RULES.maxLength) {\n return { valid: false, reason: `App name \"${name}\" is too long (max ${APP_NAME_RULES.maxLength} chars)` }\n }\n if (!APP_NAME_RULES.pattern.test(name)) {\n return {\n valid: false,\n reason:\n `App name \"${name}\" is invalid. Use lowercase letters, digits, and single hyphens only ` +\n `(must start + end with alphanumeric). Examples: my-app, search-v2, unison-search.`,\n }\n }\n return { valid: true, name }\n}\n\nexport type AppNameResolution =\n | { ok: true; name: string; warning?: string }\n | { ok: false; reason: string }\n\n/**\n * Resolve an app name for deploy: prefer the input as-is if valid, otherwise\n * sanitize and warn. Hard-fail only if even sanitization can't produce a\n * valid name (empty, all-non-alphanumeric, too short, too long).\n *\n * The intent is \"what previously worked still works, with a friendly warning\n * about non-conforming names.\"\n */\nexport function resolveAppName(raw: unknown): AppNameResolution {\n const strict = validateAppName(raw)\n if (strict.valid) return { ok: true, name: strict.name }\n\n if (typeof raw !== 'string') return { ok: false, reason: strict.reason }\n const trimmed = raw.trim()\n if (!trimmed) return { ok: false, reason: 'App name is required' }\n\n const sanitized = sanitizeAppName(trimmed)\n const sanitizedStrict = validateAppName(sanitized)\n if (!sanitizedStrict.valid) {\n return {\n ok: false,\n reason: `App name \"${trimmed}\" can't be sanitized into a valid name (${sanitizedStrict.reason}). Pick something matching: lowercase letters, digits, single hyphens, ${APP_NAME_RULES.minLength}-${APP_NAME_RULES.maxLength} chars.`,\n }\n }\n return {\n ok: true,\n name: sanitized,\n warning:\n `App name \"${trimmed}\" doesn't conform to deploy rules — using \"${sanitized}\" instead. ` +\n `Update wrangler.toml's \\`name\\` to silence this warning.`,\n }\n}\n\n/**\n * Lossy normalization that mirrors what the deploy-worker historically did\n * server-side. Keep only [a-z0-9-], collapse consecutive dashes, trim leading\n * and trailing dashes.\n */\nfunction sanitizeAppName(raw: string): string {\n return raw\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n","import { Refusal } from './command'\n/**\n * Verifies the app's dependencies are installed before running a command that\n * needs them (dev, test, deploy, add).\n *\n * `create-deepspace` runs `npm install` (and the agent-skill installer) in a\n * detached background process so the user gets their prompt back immediately.\n * The background worker writes three sentinels under `<appDir>/.deepspace/`:\n *\n * install.started — created before the worker is spawned\n * install.pid — the worker's pid (liveness check for a killed install)\n * install.done — written on successful completion\n * install.err — written on failure (contains the error message)\n * install.log — combined stdout/stderr of the install\n *\n * The presence of `node_modules/deepspace/package.json` is the ground truth\n * for \"ready\"; the sentinels only shape the error message.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { detectPackageManager } from './package-manager'\n\nexport type InstallState = 'ready' | 'installing' | 'failed' | 'missing'\n\n/** Non-throwing install state for informational surfaces such as status. */\nexport function installState(appDir: string): InstallState {\n if (resolvesDeepspace(appDir)) return 'ready'\n const sentinelDir = join(appDir, '.deepspace')\n if (existsSync(join(sentinelDir, 'install.err'))) return 'failed'\n if (existsSync(join(sentinelDir, 'install.started'))) {\n if (!existsSync(join(sentinelDir, 'install.done')) && installWorkerAlive(sentinelDir)) {\n return 'installing'\n }\n return 'failed'\n }\n return 'missing'\n}\n\n/** How to watch the install log live, per platform: `tail -f` isn't on Windows\n * (PowerShell's `Get-Content -Wait` is the equivalent). */\nexport function tailHint(logPath: string, platform: NodeJS.Platform = process.platform): string {\n return platform === 'win32' ? `Get-Content -Wait ${logPath}` : `tail -f ${logPath}`\n}\n\nexport function ensureInstallReady(appDir: string): void {\n if (resolvesDeepspace(appDir)) return\n\n const sentinelDir = join(appDir, '.deepspace')\n const errPath = join(sentinelDir, 'install.err')\n const startedPath = join(sentinelDir, 'install.started')\n const donePath = join(sentinelDir, 'install.done')\n const logPath = join(sentinelDir, 'install.log')\n\n if (existsSync(errPath)) {\n const detail = readFileSync(errPath, 'utf-8').trimEnd()\n const log = existsSync(logPath) ? ` Full log: ${logPath}.` : ''\n throw new Refusal(\n `Background install failed: ${detail}.${log} Run \\`npm install\\` (or \\`bun install\\`) manually, then retry.`,\n 'install_failed',\n { action: { cwd: appDir, argv: [detectPackageManager(appDir), 'install'] } },\n )\n }\n\n if (existsSync(startedPath) && !existsSync(donePath)) {\n // A worker that died without writing done/err (OOM, docker stop, laptop\n // shutdown) must not read as \"still installing\" forever. Every current\n // scaffolder writes a valid install.pid before doing background work.\n if (!installWorkerAlive(sentinelDir)) {\n const log = existsSync(logPath) ? ` See what happened: ${logPath}.` : ''\n throw new Refusal(\n `The background install is no longer running and never finished.${log} Run \\`npm install\\` (or \\`bun install\\`) manually, then retry.`,\n 'install_failed',\n { action: { cwd: appDir, argv: [detectPackageManager(appDir), 'install'] } },\n )\n }\n // `tail -f` isn't a Windows command — tailHint points PowerShell users at its equivalent.\n const tail = existsSync(logPath) ? ` Tail progress: ${tailHint(logPath)}.` : ''\n throw new Refusal(\n `Dependencies are still installing in the background.${tail} Retry once it finishes.`,\n 'install_in_progress',\n )\n }\n\n throw new Refusal(\n 'Dependencies not installed. Run `npm install` (or `bun install`) first.',\n 'deps_missing',\n {\n action: { cwd: appDir, argv: [detectPackageManager(appDir), 'install'] },\n },\n )\n}\n\n/**\n * Ground truth for \"dependencies ready\", matching Node's resolver: walk up\n * from `fromDir` looking for node_modules/deepspace. A linked worktree inside\n * the app (e.g. `.deepspace/ws/<id>`) has no node_modules of its own, but its\n * imports resolve against the app checkout's — so the gate must walk up too,\n * or dev/deploy refuse in exactly the places tsc/vitest work.\n */\nexport function resolvesDeepspace(fromDir: string): boolean {\n let dir = fromDir\n for (;;) {\n if (existsSync(join(dir, 'node_modules', 'deepspace', 'package.json'))) return true\n const parent = dirname(dir)\n if (parent === dir) return false\n dir = parent\n }\n}\n\n/**\n * Is the detached install worker still running? Missing or malformed identity\n * fails closed; a valid pid is alive when signal 0 succeeds. EPERM means\n * \"alive, not ours\".\n */\nfunction installWorkerAlive(sentinelDir: string): boolean {\n const pidPath = join(sentinelDir, 'install.pid')\n if (!existsSync(pidPath)) return false\n const pid = Number(readFileSync(pidPath, 'utf-8').trim())\n if (!Number.isSafeInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/** Resolve the repository's package manager from its explicit packageManager\n * field first, then its lockfile. npm is the conservative fallback. */\nexport function detectPackageManager(appDir: string): PackageManager {\n try {\n const pkg = JSON.parse(readFileSync(join(appDir, 'package.json'), 'utf-8')) as {\n packageManager?: unknown\n }\n const name = typeof pkg.packageManager === 'string' ? pkg.packageManager.split('@')[0] : ''\n if (name === 'npm' || name === 'pnpm' || name === 'yarn' || name === 'bun') return name\n } catch {\n // Missing/malformed package.json falls through to lockfile detection.\n }\n if (existsSync(join(appDir, 'pnpm-lock.yaml'))) return 'pnpm'\n if (existsSync(join(appDir, 'yarn.lock'))) return 'yarn'\n if (existsSync(join(appDir, 'bun.lock')) || existsSync(join(appDir, 'bun.lockb'))) return 'bun'\n return 'npm'\n}\n\nexport function installCommand(appDir: string): string {\n return `${detectPackageManager(appDir)} install`\n}\n","import { Refusal } from './command'\nimport { execFileSync } from 'node:child_process'\nimport { existsSync } from 'node:fs'\n// Namespace import on purpose: a named `import { registerHooks }` would itself\n// crash at load time on the very Nodes this preflight exists to catch.\nimport * as nodeModule from 'node:module'\nimport { resolve } from 'node:path'\n\n/**\n * The Cloudflare Vite plugin uses `module.registerHooks` (Node 22.15+ /\n * 23.5+). On older Nodes, `vite build` and the dev server die with a cryptic\n * ESM error from deep inside the plugin:\n *\n * SyntaxError: The requested module 'node:module' does not provide an\n * export named 'registerHooks'\n *\n * Catch it before spawning Vite and print the actual fix instead. Feature-\n * detected rather than version-pinned so the check can't go stale; the\n * `hasRegisterHooks` parameter exists only for tests.\n */\nexport function preflightNodeVersion(\n command: string,\n hasRegisterHooks: boolean = typeof (nodeModule as { registerHooks?: unknown }).registerHooks ===\n 'function',\n): void {\n if (hasRegisterHooks) return\n // Throw, never process.exit — see resolvePort: an exit inside a runtime\n // command body skips the --json envelope entirely.\n throw new Refusal(\n `deepspace ${command} requires Node 22.15 or newer (found v${process.versions.node}). ` +\n 'Install the current LTS from https://nodejs.org and re-run.',\n 'node_too_old',\n )\n}\n\n// 0xC0000135 = STATUS_DLL_NOT_FOUND on Windows. Node reports it as a signed int.\nconst DLL_NOT_FOUND = -1073741515\n\n/**\n * On Windows, the Cloudflare Workers runtime (`workerd.exe`) is built with\n * MSVC and links against `vcruntime140.dll`. A bare Windows install (Server\n * 2022, Server Core, minimal Windows 11) does not ship those DLLs, so workerd\n * exits immediately with STATUS_DLL_NOT_FOUND. Miniflare then surfaces this as\n * \"Error: write EOF\" because workerd closed the stdin pipe before reading its\n * config — an error with no JS stack trace and no hint at the cause.\n *\n * This preflight catches the case and prints the actual fix (install VC++\n * Redistributable). Skip silently if workerd isn't installed yet or runs fine.\n */\nexport function preflightWindowsWorkerd(appDir: string): void {\n if (process.platform !== 'win32') return\n\n const workerdExe = resolve(\n appDir,\n 'node_modules',\n '@cloudflare',\n 'workerd-windows-64',\n 'bin',\n 'workerd.exe',\n )\n if (!existsSync(workerdExe)) return\n\n try {\n execFileSync(workerdExe, ['--help'], { stdio: 'pipe', timeout: 10_000 })\n return\n } catch (err: unknown) {\n const status = (err as { status?: number }).status\n if (status !== DLL_NOT_FOUND) return\n\n throw new Refusal(\n 'workerd (Cloudflare Workers runtime) cannot start on this system: it needs the ' +\n 'Microsoft Visual C++ Redistributable, which is not installed. Install it with ' +\n '`winget install Microsoft.VCRedist.2015+.x64` (or choco install -y vcredist140, or ' +\n 'https://aka.ms/vs/17/release/vc_redist.x64.exe), then restart this terminal and re-run.',\n 'vcredist_missing',\n )\n }\n}\n","import { readdirSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.wrangler', '.vite'])\n\n/**\n * Delete macOS metadata files (AppleDouble `._*` and `.DS_Store`) under an\n * app directory. They appear when a project is copied from macOS through\n * tar/zip/SMB onto another system, and they poison the toolchain: ESLint\n * hard-fails on their binary content (\"Parsing error: Invalid character\",\n * failing the deploy lint), and generouted can pick up `._index.tsx` in\n * src/pages as a phantom route. Returns the number of files removed.\n */\nexport function removeMacosJunk(dir: string): number {\n let removed = 0\n // Best-effort throughout: an unreadable subdir or undeletable file must\n // never abort a build that would otherwise have worked.\n let entries\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return removed\n }\n for (const entry of entries) {\n const path = join(dir, entry.name)\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) removed += removeMacosJunk(path)\n continue\n }\n if (entry.name === '.DS_Store' || entry.name.startsWith('._')) {\n try {\n rmSync(path, { force: true })\n removed++\n } catch {\n // Leave it — the lint may still trip on it, but we didn't make\n // anything worse.\n }\n }\n }\n return removed\n}\n","/**\n * CLI surface for schema lint.\n *\n * `lintSchema` findings otherwise print only from the worker console when a\n * RecordRoom DO constructs — after a client connects, interleaved with the\n * rest of the runtime log, and never at deploy time. These are exactly the\n * warnings that ship as privacy/permission bugs (e.g. a declared\n * visibilityField that no role actually enforces), so `dev` and `deploy`\n * also run them up front where the developer is already looking.\n *\n * Bundles the app's `src/schemas.ts` with esbuild and imports the resulting\n * ESM — the same approach `deploy` uses for `src/subscriptions.ts`. Lint is\n * advisory: any failure to load or parse returns null and the command\n * proceeds (the worker still warns at runtime).\n */\n\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { lintSchema, type CollectionSchema } from '../../server/schemas/registry'\n\n/**\n * Lint every schema exported from `<appDir>/src/schemas.ts`.\n * Returns the warning messages (empty = clean), or null when the file is\n * absent or couldn't be loaded — callers should stay quiet on null.\n */\nexport async function lintProjectSchemas(appDir: string): Promise<string[] | null> {\n const schemasPath = join(appDir, 'src', 'schemas.ts')\n if (!existsSync(schemasPath)) return null\n\n let schemas: unknown\n try {\n const esbuild = await import('esbuild')\n const outFile = join(appDir, '.wrangler', 'deploy', 'schemas.lint.bundle.mjs')\n await esbuild.build({\n entryPoints: [schemasPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: outFile,\n logLevel: 'silent',\n write: true,\n })\n // Cache-bust the import so repeat runs in the same Node process don't\n // reuse a stale module from the loader cache.\n const mod = (await import(`${pathToFileURL(outFile).href}?t=${Date.now()}`)) as {\n schemas?: unknown\n }\n schemas = mod.schemas\n } catch {\n // Say why lint is being skipped — a schema graph esbuild can't bundle\n // (e.g. a transitive `cloudflare:workers` import) would otherwise read\n // as \"schemas are clean\".\n console.warn(\n 'Schema lint skipped: could not bundle src/schemas.ts (the worker still lints at runtime).',\n )\n return null\n }\n\n if (!Array.isArray(schemas)) return null\n\n const findings: string[] = []\n for (const schema of schemas) {\n if (!schema || typeof schema !== 'object') continue\n try {\n findings.push(...lintSchema(schema as CollectionSchema))\n } catch {\n // A malformed schema entry fails loudly at runtime anyway — skip here.\n }\n }\n return findings\n}\n\n/** Max findings printed in full — the rest collapse to a count so a\n * pathological schema file can't flood the terminal (or an agent's context). */\nconst MAX_PRINTED_FINDINGS = 5\n\n/**\n * Format findings as printable lines. Empty input → empty output (print\n * nothing when clean — lint earns attention by being rare).\n */\nexport function formatSchemaLintFindings(findings: string[]): string[] {\n if (findings.length === 0) return []\n const n = findings.length\n const shown = findings.slice(0, MAX_PRINTED_FINDINGS)\n const hidden = n - shown.length\n return [\n `Schema lint: ${n} warning${n === 1 ? '' : 's'} in src/schemas.ts — ${n === 1 ? 'this ships' : 'these ship'} as permission/privacy bugs:`,\n ...shown.map((f) => ` • ${f}`),\n ...(hidden > 0 ? [` …and ${hidden} more — fix the above and re-run to see the rest.`] : []),\n ]\n}\n","/**\n * Collection Schema Definitions & Validation\n *\n * All collections use typed SQL columns. No document-mode / fields-based storage.\n */\n\nimport type {\n CollectionSchema,\n ColumnDefinition,\n ColumnInterpretation,\n PermissionLevel,\n RolePermissions,\n} from '../../shared/types'\n\nexport type {\n CollectionSchema,\n ColumnDefinition,\n ColumnInterpretation,\n PermissionLevel,\n RolePermissions,\n} from '../../shared/types'\n\n// ============================================================================\n// Column Definitions\n// ============================================================================\n\nexport interface ResolvedColumn {\n id: string\n name: string\n storage: 'number' | 'text'\n interpretation: ColumnInterpretation\n expression?: string\n readonly: boolean\n userBound?: boolean\n immutable?: boolean\n required?: boolean\n default?: unknown\n timestampTrigger?: { field: string; value?: unknown }\n}\n\n// ============================================================================\n// Column Helpers\n// ============================================================================\n\nexport function collectionTableName(name: string): string {\n return `c_${name.replace(/[^a-zA-Z0-9_]/g, '_')}`\n}\n\nexport function columnId(name: string): string {\n return `col_${name.toLowerCase().replace(/[^a-z0-9]/g, '_')}`\n}\n\nexport function resolveColumn(col: ColumnDefinition): ResolvedColumn {\n const interp: ColumnInterpretation =\n typeof col.interpretation === 'string'\n ? ({ kind: col.interpretation } as ColumnInterpretation)\n : col.interpretation\n return {\n id: col.id ?? columnId(col.name),\n name: col.name,\n storage: col.storage,\n interpretation: interp,\n expression: col.expression,\n readonly: !!col.expression,\n userBound: col.userBound,\n immutable: col.immutable,\n required: col.required,\n default: col.default,\n timestampTrigger: col.timestampTrigger,\n }\n}\n\nexport function rowToData(\n row: Record<string, unknown>,\n columns: ResolvedColumn[],\n): Record<string, unknown> {\n const data: Record<string, unknown> = {}\n for (const col of columns) {\n if (row[col.id] !== undefined && row[col.id] !== null) {\n let val = row[col.id]\n if (col.interpretation.kind === 'json' && typeof val === 'string') {\n try {\n val = JSON.parse(val as string)\n } catch {\n /* keep as string */\n }\n }\n data[col.name] = val\n }\n }\n return data\n}\n\nexport function dataToColumnValues(\n data: Record<string, unknown>,\n columns: ResolvedColumn[],\n): Record<string, unknown> {\n const values: Record<string, unknown> = {}\n for (const col of columns) {\n if (col.expression || col.readonly) continue\n const val = data[col.id] ?? data[col.name]\n if (val !== undefined) {\n values[col.id] = coerceValue(val, col.storage, col.interpretation)\n }\n }\n return values\n}\n\nexport function coerceValue(\n value: unknown,\n storage: 'number' | 'text',\n interpretation: ColumnInterpretation,\n): unknown {\n if (value === null || value === undefined || value === '') return null\n\n if (storage === 'text') {\n if (interpretation.kind === 'json') {\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value)\n } catch {\n return null\n }\n }\n return typeof value === 'string' ? value : String(value)\n }\n\n if (typeof value === 'number') return isFinite(value) ? value : null\n if (typeof value === 'boolean') return value ? 1 : 0\n if (typeof value !== 'string') return String(value)\n\n const s = value.trim()\n\n if (interpretation.kind === 'boolean') {\n const lower = s.toLowerCase()\n if (lower === 'true' || lower === '1' || lower === 'yes') return 1\n if (lower === 'false' || lower === '0' || lower === 'no') return 0\n return s\n }\n\n if (interpretation.kind === 'percent') {\n const m = s.match(/^(-?\\d+(?:\\.\\d+)?)\\s*%$/)\n if (m) return parseFloat(m[1]) / 100\n }\n\n if (interpretation.kind === 'currency') {\n const cleaned = s.replace(/[^0-9.-]/g, '')\n const n = parseFloat(cleaned)\n if (!isNaN(n)) return n\n return s\n }\n\n if (interpretation.kind === 'date' || interpretation.kind === 'datetime') {\n const d = new Date(s)\n if (!isNaN(d.getTime())) return Math.floor(d.getTime() / 1000)\n return s\n }\n\n const cleaned = s.replace(/[$€£¥,\\s]/g, '')\n const n = parseFloat(cleaned)\n if (!isNaN(n) && isFinite(n)) return n\n\n return s\n}\n\nexport function buildTableSelect(collectionName: string, columns: ResolvedColumn[]): string {\n const tbl = collectionTableName(collectionName)\n const parts: string[] = ['_row_id', '_created_by', '_created_at', '_updated_at']\n for (const col of columns) {\n if (col.expression) {\n parts.push(`(${col.expression}) AS \"${col.id}\"`)\n } else {\n parts.push(`\"${col.id}\"`)\n }\n }\n return `SELECT ${parts.join(', ')} FROM \"${tbl}\"`\n}\n\nexport interface User {\n id: string\n email: string\n name: string\n imageUrl?: string\n role: string\n createdAt: string\n lastSeenAt: string\n}\n\nexport interface StoredRecord {\n collection: string\n recordId: string\n data: Record<string, unknown>\n createdBy: string\n createdAt: string\n updatedAt: string\n}\n\n// ============================================================================\n// Permission Checking\n// ============================================================================\n\nexport interface PermissionContext {\n isTeamMember: (teamId: string, userId: string) => boolean\n}\n\nexport const noopPermissionContext: PermissionContext = {\n isTeamMember: () => false,\n}\n\nexport function getRolePermissions(schema: CollectionSchema, role: string): RolePermissions {\n if (schema.permissions[role]) return schema.permissions[role]\n if (schema.permissions['*']) return schema.permissions['*']\n return { read: false, create: false, update: false, delete: false }\n}\n\nexport function isOwner(\n schema: CollectionSchema,\n record: { data: Record<string, unknown>; createdBy: string },\n userId: string,\n): boolean {\n if (schema.ownerField) return record.data[schema.ownerField] === userId\n return record.createdBy === userId\n}\n\nfunction isCollaborator(\n schema: CollectionSchema,\n record: { data: Record<string, unknown> },\n userId: string,\n): boolean {\n if (!schema.collaboratorsField) return false\n const collab = record.data[schema.collaboratorsField]\n if (typeof collab === 'string') {\n try {\n return (JSON.parse(collab) as string[]).includes(userId)\n } catch {\n return false\n }\n }\n if (Array.isArray(collab)) return collab.includes(userId)\n return false\n}\n\nfunction passesVisibilityCheck(\n schema: CollectionSchema,\n record: { data: Record<string, unknown> },\n): boolean {\n if (!schema.visibilityField) return false\n if (typeof schema.visibilityField === 'string') {\n return record.data[schema.visibilityField] === 'public'\n }\n return record.data[schema.visibilityField.field] === schema.visibilityField.value\n}\n\nfunction checkPermissionLevel(\n level: PermissionLevel,\n schema: CollectionSchema,\n record: { data: Record<string, unknown>; createdBy: string; recordId?: string },\n userId: string,\n ctx: PermissionContext = noopPermissionContext,\n): boolean {\n if (level === true) return true\n if (level === false) return false\n if (level === 'own') return isOwner(schema, record, userId)\n if (level === 'unclaimed-or-own') {\n if (schema.ownerField) {\n const ownerVal = record.data[schema.ownerField]\n if (!ownerVal || ownerVal === '') return true\n }\n return isOwner(schema, record, userId)\n }\n if (level === 'collaborator') {\n return isOwner(schema, record, userId) || isCollaborator(schema, record, userId)\n }\n if (level === 'team' || level === 'access') {\n if (isOwner(schema, record, userId)) return true\n if (isCollaborator(schema, record, userId)) return true\n if (schema.teamField) {\n const teamId = record.data[schema.teamField]\n if (typeof teamId === 'string' && ctx.isTeamMember(teamId, userId)) return true\n }\n return false\n }\n if (level === 'published') {\n return isOwner(schema, record, userId) || passesVisibilityCheck(schema, record)\n }\n if (level === 'shared') {\n return (\n isOwner(schema, record, userId) ||\n isCollaborator(schema, record, userId) ||\n passesVisibilityCheck(schema, record)\n )\n }\n return false\n}\n\nexport function canRead(\n schema: CollectionSchema,\n role: string,\n record: { data: Record<string, unknown>; createdBy: string; recordId?: string },\n userId: string,\n ctx: PermissionContext = noopPermissionContext,\n): boolean {\n return checkPermissionLevel(getRolePermissions(schema, role).read, schema, record, userId, ctx)\n}\n\nexport function canCreate(schema: CollectionSchema, role: string): boolean {\n return getRolePermissions(schema, role).create === true\n}\n\nexport function canUpdate(\n schema: CollectionSchema,\n role: string,\n record: { data: Record<string, unknown>; createdBy: string; recordId?: string },\n userId: string,\n ctx: PermissionContext = noopPermissionContext,\n): boolean {\n return checkPermissionLevel(getRolePermissions(schema, role).update, schema, record, userId, ctx)\n}\n\nexport function canDelete(\n schema: CollectionSchema,\n role: string,\n record: { data: Record<string, unknown>; createdBy: string; recordId?: string },\n userId: string,\n ctx: PermissionContext = noopPermissionContext,\n): boolean {\n return checkPermissionLevel(getRolePermissions(schema, role).delete, schema, record, userId, ctx)\n}\n\n/** Check if a field update violates writableFields restrictions. */\nexport function checkFieldPermissions(\n schema: CollectionSchema,\n role: string,\n newData: Record<string, unknown>,\n existingData?: Record<string, unknown>,\n): string | null {\n const perms = getRolePermissions(schema, role)\n if (!perms.writableFields) return null // no restrictions\n\n const allowedFields = new Set(perms.writableFields)\n for (const key of Object.keys(newData)) {\n if (existingData && newData[key] === existingData[key]) continue\n if (!allowedFields.has(key)) {\n return `Role '${role}' cannot modify field '${key}'`\n }\n }\n return null\n}\n\n// ============================================================================\n// System-Managed Columns (users collection)\n// ============================================================================\n\n/** Names of columns managed by the system (registerUser), not client mutations. */\nexport const SYSTEM_MANAGED_COLUMNS = new Set([\n 'email',\n 'name',\n 'imageUrl',\n 'role',\n 'createdAt',\n 'lastSeenAt',\n])\n\n/** Standard user columns. Apps spread these into their users schema. */\nexport const USERS_COLUMNS: ColumnDefinition[] = [\n { name: 'email', storage: 'text', interpretation: 'plain' },\n { name: 'name', storage: 'text', interpretation: 'plain' },\n { name: 'imageUrl', storage: 'text', interpretation: 'plain' },\n { name: 'role', storage: 'text', interpretation: 'plain' },\n { name: 'createdAt', storage: 'text', interpretation: { kind: 'datetime' } },\n { name: 'lastSeenAt', storage: 'text', interpretation: { kind: 'datetime' } },\n]\n\nexport const BASE_USERS_SCHEMA: CollectionSchema = {\n name: 'users',\n columns: [...USERS_COLUMNS],\n permissions: {\n '*': { read: 'own', create: false, update: false, delete: false },\n admin: { read: true, create: false, update: true, delete: true },\n },\n}\n\n// ============================================================================\n// Schema Registry\n// ============================================================================\n\n/**\n * Lint a CollectionSchema for declarations that look like they should\n * enforce something but don't, due to interactions between top-level\n * fields (visibilityField, ownerField) and per-role permission levels.\n *\n * The SDK has historically silently accepted schemas that imply more\n * enforcement than they actually deliver — e.g., `visibilityField` set\n * but every role's `read: true` means \"anyone can read everything\"\n * regardless of `visibility`. Warn loudly at registration so app\n * authors notice before shipping a privacy bug.\n *\n * Returns an array of warning messages. Empty = clean.\n */\nexport function lintSchema(schema: CollectionSchema): string[] {\n const warnings: string[] = []\n const VISIBILITY_AWARE: ReadonlyArray<PermissionLevel> = ['published', 'shared']\n\n // Roles that grant unconditional read despite visibilityField being declared.\n if (schema.visibilityField) {\n const offendingRoles = Object.entries(schema.permissions)\n .filter(([, perms]) => perms.read === true)\n .map(([role]) => role)\n if (offendingRoles.length > 0) {\n const usesAware = Object.values(schema.permissions).some(\n (p) => typeof p.read === 'string' && VISIBILITY_AWARE.includes(p.read as PermissionLevel),\n )\n if (!usesAware) {\n warnings.push(\n `[${schema.name}] visibilityField is declared but no role uses read: 'published' or 'shared'. ` +\n `Roles with read: true (${offendingRoles.join(', ')}) will see every row regardless of visibility. ` +\n `Change those to read: 'published' (owner OR public) or 'shared' (owner OR collaborator OR public) ` +\n `to actually enforce the filter, or remove visibilityField if you don't intend to gate reads by it.`,\n )\n }\n }\n }\n\n // ownerField declared but the named column isn't userBound — easy to\n // create a row claiming someone else's ownership.\n if (schema.ownerField) {\n const col = schema.columns.find((c) => c.name === schema.ownerField)\n if (col && !col.userBound) {\n warnings.push(\n `[${schema.name}] ownerField is '${schema.ownerField}' but that column is not marked userBound: true. ` +\n `A client can create a row with someone else's id in this field, bypassing 'own' permission checks. ` +\n `Add userBound: true (and ideally immutable: true) to the column.`,\n )\n }\n }\n\n // userBound columns that aren't text storage — userBound sets the\n // field to the caller's userId (a string), so non-text storage is a\n // schema mistake that will surface as a coercion error at write time.\n for (const col of schema.columns) {\n if (col.userBound && col.storage !== 'text') {\n warnings.push(\n `[${schema.name}] column '${col.name}' is userBound but storage is '${col.storage}'. ` +\n `userBound stamps the user id (a string); use storage: 'text'.`,\n )\n }\n }\n\n return warnings\n}\n\nexport class SchemaRegistry {\n private trusted: Map<string, CollectionSchema> = new Map()\n\n constructor(schemas: CollectionSchema[] = []) {\n for (const schema of schemas) {\n this.registerTrusted(schema)\n }\n }\n\n registerTrusted(schema: CollectionSchema): void {\n for (const w of lintSchema(schema)) {\n console.warn(`[schema-lint] ${w}`)\n }\n this.trusted.set(schema.name, schema)\n }\n\n get(name: string): CollectionSchema | undefined {\n return this.trusted.get(name)\n }\n\n has(name: string): boolean {\n return this.trusted.has(name)\n }\n\n all(): CollectionSchema[] {\n return Array.from(this.trusted.values())\n }\n\n names(): string[] {\n return Array.from(this.trusted.keys())\n }\n}\n\n// ============================================================================\n// Permission Analysis\n// ============================================================================\n\nexport type PermissionSource = 'explicit' | 'wildcard' | 'default-deny'\n\nexport interface ResolvedPermission {\n level: PermissionLevel | boolean\n source: PermissionSource\n}\n\nexport interface CollectionPermissionSummary {\n collection: string\n ownerField?: string\n collaboratorsField?: string\n teamField?: string\n columns: ColumnDefinition[]\n permissions: Record<\n string,\n {\n read: ResolvedPermission\n create: ResolvedPermission\n update: ResolvedPermission\n delete: ResolvedPermission\n writableFields?: string[]\n }\n >\n}\n\nexport interface PermissionAnalysis {\n roles: string[]\n collections: CollectionPermissionSummary[]\n}\n\nexport function analyzePermissions(schemas: CollectionSchema[]): PermissionAnalysis {\n const roleSet = new Set<string>()\n for (const schema of schemas) {\n for (const role of Object.keys(schema.permissions)) roleSet.add(role)\n }\n roleSet.delete('*')\n const roles = Array.from(roleSet)\n\n const collections: CollectionPermissionSummary[] = schemas.map((schema) => {\n const permissions: CollectionPermissionSummary['permissions'] = {}\n for (const role of roles) {\n let source: PermissionSource\n let perms: RolePermissions\n if (schema.permissions[role]) {\n source = 'explicit'\n perms = schema.permissions[role]\n } else if (schema.permissions['*']) {\n source = 'wildcard'\n perms = schema.permissions['*']\n } else {\n source = 'default-deny'\n perms = { read: false, create: false, update: false, delete: false }\n }\n permissions[role] = {\n read: { level: perms.read, source },\n create: { level: perms.create, source },\n update: { level: perms.update, source },\n delete: { level: perms.delete, source },\n writableFields: perms.writableFields,\n }\n }\n return {\n collection: schema.name,\n ownerField: schema.ownerField,\n collaboratorsField: schema.collaboratorsField,\n teamField: schema.teamField,\n columns: schema.columns,\n permissions,\n }\n })\n\n return { roles, collections }\n}\n","import { Refusal } from './command'\n/**\n * Shared dev-server port resolution for `dev`, `test`, and `kill`.\n *\n * Precedence: explicit `--port` arg > $DEEPSPACE_PORT > DEFAULT_PORT. An\n * out-of-range value is a hard error (exit 1) rather than a silent fallback,\n * so a typo doesn't quietly bind the wrong port.\n */\n\nimport { createServer } from 'node:net'\n\nexport const DEFAULT_PORT = 5173\n\n/**\n * Whether `port` is free to bind on `host`. Used by `dev` to pre-probe before\n * spawning vite (which binds with `--host`, i.e. 0.0.0.0), so a busy port gets\n * a friendly `deepspace dev kill` / `--port` remedy instead of vite's raw\n * EADDRINUSE stack (DEV-5). Best-effort: a bind race after the probe still\n * surfaces vite's own error, but the common \"server already running\" case is\n * caught cleanly.\n */\nexport function checkPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {\n return new Promise((resolve) => {\n const srv = createServer()\n srv.once('error', () => resolve(false))\n srv.once('listening', () => srv.close(() => resolve(true)))\n srv.listen(port, host)\n })\n}\n\nexport function resolvePort(arg?: string): number {\n const raw = arg ?? process.env.DEEPSPACE_PORT\n if (!raw) return DEFAULT_PORT\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n // Throw, never process.exit: these helpers run inside runtime command\n // bodies, and an exit skips the runtime's envelope — a --json caller\n // would get code 1 with an EMPTY stdout, the exact hole the runtime\n // exists to close.\n throw new Refusal(`Invalid port: ${raw}. Must be an integer between 1 and 65535.`, 'invalid_port')\n }\n return n\n}\n","/**\n * deepspace dev kill [--port N] [--all]\n *\n * Stops a local dev server bound to the given port, plus the workerd\n * child processes that wrangler/Vite would normally clean up but\n * sometimes leak when the parent dies ungracefully (Ctrl-C in a\n * detached terminal, IDE close, sandbox deny on signal, etc).\n *\n * deepspace dev kill # kill listener on 5173 + its workerd children\n * deepspace dev kill --port 5180 # kill listener on a different port\n * deepspace dev kill --all # also sweep ALL stray workerd/wrangler procs on the machine\n *\n * Cross-platform: uses lsof/pgrep on macOS and Linux, and PowerShell\n * (Get-NetTCPConnection / Get-CimInstance) on Windows. PowerShell ships\n * with every supported Windows version since 7; no extra install required.\n *\n * Always sends SIGTERM first, waits briefly, then SIGKILL anything\n * still alive — same shape as `vite`'s own shutdown handler so we\n * don't trample DO state mid-write. (On Windows, SIGTERM is best-effort:\n * Win32 has no real signals, so node maps both to TerminateProcess. We\n * still issue them in the same order for consistent log output.)\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { readFileSync, readdirSync, readlinkSync } from 'node:fs'\nimport { setTimeout as wait } from 'node:timers/promises'\nimport { findAppDir } from '../lib/app-context'\nimport { resolveWorktreePort, resolveAppLaunchPort } from '../lib/launch-config'\nimport { DEFAULT_PORT, resolvePort } from '../lib/port'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst SIGTERM_GRACE_MS = 1500\nconst IS_WIN = process.platform === 'win32'\n\n/**\n * Pick the port `kill` targets, mirroring `dev`'s binding precedence so the two\n * always agree (DEV-2). Pure for testing.\n * 1. explicit --port\n * 2. worktree port (dev ignores $DEEPSPACE_PORT inside a worktree, so we do too)\n * 3. $DEEPSPACE_PORT (dev binds it outside a worktree, over a launch.json that\n * dev only rewrites for an explicit --port)\n * 4. the app's launch.json port (kept in sync by `dev --port`)\n * 5. the default\n */\nexport function pickKillPort(opts: {\n explicit: number | null\n worktree: number | null\n env: number | null\n appLaunch: number | null\n}): number {\n if (opts.explicit != null) return opts.explicit\n if (opts.worktree != null) return opts.worktree\n if (opts.env != null) return opts.env\n return opts.appLaunch ?? DEFAULT_PORT\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'kill',\n description: 'Kill the local dev server and any orphaned workerd processes',\n },\n args: {\n port: {\n type: 'string',\n description: `Port the dev server is bound to (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n all: {\n type: 'boolean',\n description: 'Also kill stray workerd/wrangler processes across all ports',\n default: false,\n },\n },\n async run({ args }) {\n const portArg = args.port as string | undefined\n const all = Boolean(args.all)\n const say = (line: string) => {\n if (!args.json) console.log(line)\n }\n // Resolve which port to target, mirroring `dev`'s own precedence so `kill`\n // always targets the server `dev` bound (DEV-2). Without this, no-arg `kill`\n // hit :5173 even when `dev --port 8790` was running elsewhere.\n const cwd = process.cwd()\n const port = pickKillPort({\n explicit: portArg ? resolvePort(portArg) : null,\n worktree: resolveWorktreePort(cwd),\n // resolvePort() reads + validates $DEEPSPACE_PORT; only consult it when set.\n env: process.env.DEEPSPACE_PORT ? resolvePort() : null,\n appLaunch: resolveAppLaunchPort(findAppDir(cwd) ?? cwd),\n })\n const targets = new Set<number>()\n\n // 1. Anything LISTENing on the dev port (vite + the workerd child it\n // publishes through, occasionally a stray inspector). `enumerated`\n // tells us whether we could actually inspect the port at all.\n const listeners = enumerateListeners(port)\n for (const pid of listeners.pids) targets.add(pid)\n\n // 2. Children of those listeners — wrangler/vite tend to spawn workerd\n // as a sibling, but in some shells it ends up as a child instead.\n for (const pid of [...targets]) {\n for (const child of childPids(pid)) targets.add(child)\n }\n\n // 3. With --all, sweep workerd / wrangler / vite anywhere on the box.\n // Useful when port 5173 is \"free\" but a leftover workerd from a\n // previous run is still holding D1 / DO state in .wrangler/.\n let swept = false\n if (all) {\n const sweep = sweepByName(['workerd', 'wrangler', 'vite'])\n swept = sweep.swept\n for (const pid of sweep.pids) targets.add(pid)\n }\n\n if (targets.size === 0) {\n // DEV-1: distinguish \"inspected, found nothing\" from \"couldn't inspect\".\n // The latter must NOT report the port free (exit 0) while a leaked\n // workerd keeps holding DO/D1 state — that was the original silent no-op.\n const outcome = noTargetsMessage({\n enumerated: listeners.enumerated,\n swept,\n all,\n port,\n })\n if (!outcome.ok) {\n throw new Refusal(outcome.message, 'inspect_unavailable')\n }\n say(outcome.message)\n return { data: { port, all, killed: [], portFree: true } }\n }\n\n // SIGTERM pass.\n for (const pid of targets) {\n if (sendSignal(pid, 'SIGTERM')) {\n say(`SIGTERM → pid ${pid}`)\n }\n }\n await wait(SIGTERM_GRACE_MS)\n\n const stillAlive: number[] = []\n for (const pid of targets) {\n if (isAlive(pid)) stillAlive.push(pid)\n }\n\n // SIGKILL holdouts.\n const killed: number[] = []\n for (const pid of stillAlive) {\n if (sendSignal(pid, 'SIGKILL')) {\n killed.push(pid)\n say(`SIGKILL → pid ${pid} (did not exit on SIGTERM)`)\n }\n }\n\n // Re-verify the port is free.\n await wait(200)\n const remaining = listenerPids(port)\n if (remaining.length > 0) {\n throw new Refusal(\n `Port ${port} is still held by pid(s) ${remaining.join(', ')} — try \\`deepspace dev kill --port ${port}\\` again, or kill manually.`,\n 'port_still_held',\n {\n action: cliAction('deepspace', 'dev', 'kill', '--port', String(port)),\n extra: { port, holders: remaining },\n },\n )\n }\n\n // Report what actually happened. Under --all we may have swept processes on\n // ports other than `port` (matched by name), so a bare \"Port 5173 is free\"\n // would misrepresent the sweep (DEV-6).\n say(\n all\n ? `Killed ${targets.size} process(es) (workerd/wrangler/vite sweep). :${port} is free.`\n : `Port ${port} is free.`,\n )\n return {\n data: { port, all, killed: [...targets], sigkilled: killed, portFree: true },\n }\n },\n})\n\n// ── Platform-specific helpers ─────────────────────────────────────────────\n\n/**\n * Decide what to print when no kill targets were found. Pure so the DEV-1\n * rule — never claim the port is free when we couldn't actually inspect it —\n * is unit-testable. `ok:false` means we lacked any way to observe the system\n * (no lsof/pgrep AND no /proc) and must exit non-zero rather than lie.\n */\nexport function noTargetsMessage(opts: {\n enumerated: boolean\n swept: boolean\n all: boolean\n port: number\n}): { ok: boolean; message: string } {\n const { enumerated, swept, all, port } = opts\n const couldObserve = enumerated || (all && swept)\n if (!couldObserve) {\n return {\n ok: false,\n message:\n `Couldn't determine what's running on :${port}: no lsof/pgrep and /proc ` +\n `is unavailable, so nothing was inspected or killed. Install lsof (or ` +\n `procps for pgrep), or find and kill the process manually.`,\n }\n }\n return {\n ok: true,\n message: all\n ? `Nothing listening on :${port} and no stray workerd/wrangler/vite processes found.`\n : `Nothing listening on :${port}. (Pass --all to sweep stray workerd/wrangler.)`,\n }\n}\n\n/**\n * PIDs listening on `port`, plus whether we could inspect the port at all.\n * `enumerated:false` means every available method (lsof / PowerShell / /proc)\n * was missing — a genuine \"don't know\", not \"nothing there\".\n */\nfunction enumerateListeners(port: number): { pids: number[]; enumerated: boolean } {\n if (IS_WIN) {\n // Get-NetTCPConnection is the modern replacement for netstat -ano.\n // -ErrorAction SilentlyContinue swallows \"No matching connection\" so\n // the command exits 0 with empty stdout instead of a noisy red error.\n const r = runPowershellChecked(\n `Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess`,\n )\n return { pids: r.pids, enumerated: r.ran }\n }\n // lsof is authoritative when present. It exits 1 (not an error, for us) when\n // nothing matches, so \"ran but empty\" is a real \"nothing listening\".\n const lsof = runLsof(port)\n if (lsof.ran) return { pids: lsof.pids, enumerated: true }\n // lsof is absent on many container/CI images — `node:22-bookworm` ships none\n // of lsof/ss/fuser/netstat. /proc needs no external binary and covers Linux;\n // if it's also unavailable we truly can't tell (enumerated:false).\n const proc = listenerPidsViaProc(port)\n return { pids: proc.pids, enumerated: proc.available }\n}\n\n/** Thin wrapper for the post-kill re-verify, where capability is irrelevant. */\nfunction listenerPids(port: number): number[] {\n return enumerateListeners(port).pids\n}\n\n/** Run lsof for a port. `ran` distinguishes \"lsof absent\" from \"found nothing\". */\nfunction runLsof(port: number): { pids: number[]; ran: boolean } {\n try {\n // -t prints PIDs only, one per line; -nP avoids DNS / service lookups.\n const r = spawnSync('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'], {\n encoding: 'utf-8',\n })\n if (r.error) return { pids: [], ran: false } // ENOENT: lsof not installed\n // 0 = matches printed; 1 = no matches. Both mean lsof ran successfully.\n return { pids: r.status === 0 ? parsePidLines(r.stdout) : [], ran: true }\n } catch {\n return { pids: [], ran: false }\n }\n}\n\n/** Port → listening PIDs via /proc alone (no lsof/ss). Finds the LISTEN\n * socket's inode in /proc/net/tcp{,6}, then the process holding that fd.\n * `available` is false when /proc itself couldn't be read. */\nfunction listenerPidsViaProc(port: number): { pids: number[]; available: boolean } {\n let available = false\n try {\n const hexPort = port.toString(16).toUpperCase().padStart(4, '0')\n const inodes = new Set<string>()\n for (const f of ['/proc/net/tcp', '/proc/net/tcp6']) {\n let data: string\n try {\n data = readFileSync(f, 'utf-8')\n } catch {\n continue\n }\n available = true\n for (const line of data.split('\\n').slice(1)) {\n const cols = line.trim().split(/\\s+/)\n // sl local_address(1) rem_address(2) st(3) … inode(9); st 0A = LISTEN.\n if (cols[3] !== '0A') continue\n if (cols[1]?.split(':')[1] === hexPort && cols[9]) inodes.add(cols[9])\n }\n }\n if (!available) return { pids: [], available: false }\n if (!inodes.size) return { pids: [], available: true }\n const pids = new Set<number>()\n for (const pidDir of readdirSync('/proc')) {\n if (!/^\\d+$/.test(pidDir)) continue\n let fds: string[]\n try {\n fds = readdirSync(`/proc/${pidDir}/fd`)\n } catch {\n continue // not ours / gone\n }\n for (const fd of fds) {\n let link: string\n try {\n link = readlinkSync(`/proc/${pidDir}/fd/${fd}`)\n } catch {\n continue\n }\n const m = link.match(/^socket:\\[(\\d+)\\]$/)\n if (m && inodes.has(m[1])) {\n pids.add(Number(pidDir))\n break\n }\n }\n }\n return { pids: [...pids], available: true }\n } catch {\n return { pids: [], available }\n }\n}\n\nfunction childPids(parentPid: number): number[] {\n if (IS_WIN) {\n return runPowershell(\n `Get-CimInstance Win32_Process -Filter \"ParentProcessId=${parentPid}\" | Select-Object -ExpandProperty ProcessId`,\n )\n }\n return run(['pgrep', '-P', String(parentPid)])\n}\n\n/**\n * Sweep processes by name/commandline. `swept` reports whether the enumerator\n * (pgrep / PowerShell) actually ran — so `--all` doesn't falsely claim \"no\n * stray processes\" when it never got to look.\n */\nfunction sweepByName(names: string[]): { pids: number[]; swept: boolean } {\n const all = new Set<number>()\n if (IS_WIN) {\n // Match against process Name (e.g. \"workerd\") AND CommandLine (catches\n // npx-launched scripts like \"vite\" that show up as node.exe with vite\n // in the args).\n const orClauses = names\n .map((n) => `($_.Name -like '*${n}*') -or ($_.CommandLine -like '*${n}*')`)\n .join(' -or ')\n const script = `Get-CimInstance Win32_Process | Where-Object { ${orClauses} } | Select-Object -ExpandProperty ProcessId`\n const r = runPowershellChecked(script)\n for (const pid of r.pids) if (pid !== process.pid) all.add(pid)\n return { pids: [...all], swept: r.ran }\n }\n let swept = false\n for (const name of names) {\n const r = runPgrep(['-f', name])\n if (r.ran) swept = true\n for (const pid of r.pids) if (pid !== process.pid) all.add(pid)\n }\n return { pids: [...all], swept }\n}\n\n/** Run pgrep. `ran` distinguishes \"pgrep absent\" from \"matched nothing\" (exit 1). */\nfunction runPgrep(pgrepArgs: string[]): { pids: number[]; ran: boolean } {\n try {\n const r = spawnSync('pgrep', pgrepArgs, { encoding: 'utf-8' })\n if (r.error) return { pids: [], ran: false } // ENOENT: pgrep not installed\n // 0 = matches; 1 = no matches. Both mean pgrep ran.\n return { pids: r.status === 0 ? parsePidLines(r.stdout) : [], ran: r.status === 0 || r.status === 1 }\n } catch {\n return { pids: [], ran: false }\n }\n}\n\n// ── Process primitives ────────────────────────────────────────────────────\n\n/** Run a command and return whitespace-separated PIDs (empty array on failure). */\nfunction run(cmd: string[]): number[] {\n try {\n const r = spawnSync(cmd[0], cmd.slice(1), { encoding: 'utf-8' })\n if (r.status !== 0) return []\n return parsePidLines(r.stdout)\n } catch {\n return []\n }\n}\n\n/**\n * Run a PowerShell snippet. Prefers `pwsh` (PowerShell 7+) when available\n * and falls back to `powershell.exe` (Windows PowerShell 5.1, ships with\n * every Windows version we care about).\n */\nfunction runPowershell(script: string): number[] {\n return runPowershellChecked(script).pids\n}\n\n/** Like runPowershell but reports whether PowerShell actually ran (`ran`),\n * so callers can tell \"no matches\" (exit 0, empty) from \"PowerShell absent\". */\nfunction runPowershellChecked(script: string): { pids: number[]; ran: boolean } {\n const exe = pwshOrPowershell()\n try {\n const r = spawnSync(exe, ['-NoProfile', '-NonInteractive', '-Command', script], {\n encoding: 'utf-8',\n })\n if (r.error) return { pids: [], ran: false }\n // With -ErrorAction SilentlyContinue the query exits 0 even with no matches.\n return { pids: r.status === 0 ? parsePidLines(r.stdout) : [], ran: r.status === 0 }\n } catch {\n return { pids: [], ran: false }\n }\n}\n\nfunction pwshOrPowershell(): string {\n // `pwsh` is the modern cross-platform binary; `powershell.exe` is the\n // legacy Windows-only one. Try modern first, fall back if missing.\n const probe = spawnSync('pwsh', ['-NoProfile', '-Command', '$PSVersionTable.PSVersion.Major'], {\n encoding: 'utf-8',\n })\n if (probe.status === 0) return 'pwsh'\n return 'powershell.exe'\n}\n\nfunction parsePidLines(stdout: string): number[] {\n return stdout\n .split(/\\s+/)\n .map((s) => Number.parseInt(s, 10))\n .filter((n) => Number.isFinite(n) && n > 0)\n}\n\nfunction sendSignal(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(pid, signal)\n return true\n } catch {\n return false\n }\n}\n\nfunction isAlive(pid: number): boolean {\n try {\n // signal 0 = \"do nothing, just check\"\n process.kill(pid, 0)\n return true\n } catch {\n return false\n }\n}\n","/**\n * deepspace test run [suite] [--port N]\n *\n * Runs tests for a DeepSpace app. Always uses dev workers.\n *\n * deepspace test run # smoke + api (quick check)\n * deepspace test run smoke # smoke tests only\n * deepspace test run api # API tests only\n * deepspace test run e2e # all Playwright tests\n * deepspace test run unit # vitest unit tests\n * deepspace test run all # everything\n * deepspace test run <file> # run specific test file\n *\n * Port is `--port` > $DEEPSPACE_PORT > 5173 — except inside a Claude Code\n * worktree, where (unless --port was passed) the worktree's own port is used\n * so tests hit the worktree's server, not the main repo's. The chosen port is\n * exported as DEEPSPACE_PORT to the Playwright child so the config +\n * webServer both bind to the same address. Pass a different port per app to\n * run multiple apps\n * (and test suites) in parallel.\n *\n * Defined with the command runtime (lib/command.ts). The suite runner streams\n * playwright/vitest output through inherited stdio, so under `--json` that\n * text still scrolls past and the envelope is the LAST line rather than the\n * only one — buffering a test run to keep stdout pristine would cost the live\n * feedback the command exists for. The suite's own exit code collapses to the\n * contract's 0/1.\n */\n\nimport { readAppId } from '../lib/app-identity'\nimport { resolve } from 'node:path'\nimport { sync as spawnSync } from 'cross-spawn'\nimport { ensureToken } from '../auth'\nimport { findAppDir, findChildApps } from '../lib/app-context'\nimport { resolveWorktreePort } from '../lib/launch-config'\nimport { PLATFORM_URLS } from '../env'\nimport { writeDevVars } from '../lib/dev-vars'\nimport { decodeJwtPayload } from '../jwt'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { ensurePlaywright } from '../lib/playwright'\nimport { preflightNodeVersion, preflightWindowsWorkerd } from '../lib/preflight'\nimport { refreshSecretsCache } from '../lib/secrets'\nimport { DEFAULT_PORT, resolvePort } from '../lib/port'\nimport {\n prepareWranglerEnvConfig,\n wranglerViteEnv,\n type PreparedWranglerEnvConfig,\n} from '../lib/wrangler-env'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n// Same refusal text `dev` uses — one source so the two can't drift.\nimport { noAppDirMessage } from './dev'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'test',\n description: 'Run tests for your DeepSpace app',\n },\n args: {\n suite: {\n type: 'positional',\n description: 'Test suite: smoke, api, e2e, unit, all (default: smoke+api)',\n required: false,\n },\n port: {\n type: 'string',\n description: `Port for vite/webServer (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description:\n 'wrangler.toml [env.<name>] block to test (uses secrets config <name> by default).',\n required: false,\n },\n },\n async run({ args }) {\n const say = (line: string) => {\n if (!args.json) console.log(line)\n }\n preflightNodeVersion('test run')\n const suite = (args.suite as string | undefined) ?? 'default'\n const wranglerEnv =\n typeof args.env === 'string' && args.env.trim() ? args.env.trim() : undefined\n\n // Resolve the app root by walking up from cwd, matching `deepspace dev start`.\n const start = resolve('.')\n const appDir = findAppDir(start)\n if (!appDir) {\n throw new Refusal(noAppDirMessage(start, findChildApps(start)), 'no_app_dir')\n }\n\n // Inside a Claude Code worktree the default port must match the\n // worktree's dev server (not 5173): Playwright's reuseExistingServer\n // would otherwise attach to the MAIN repo's server and silently test\n // stale code. Explicit --port still wins.\n const worktreePort = args.port ? null : resolveWorktreePort(appDir)\n const port = worktreePort ?? resolvePort(args.port as string | undefined)\n if (worktreePort && process.env.DEEPSPACE_PORT) {\n say(\n `Ignoring DEEPSPACE_PORT=${process.env.DEEPSPACE_PORT} inside a worktree — ` +\n `targeting per-worktree port ${port}. Pass --port to override.`,\n )\n }\n\n ensureInstallReady(appDir)\n\n // Always write .dev.vars pointing to dev workers. A logged-in user is\n // required so writeDevVars can mint APP_OWNER_JWT via the auth-worker.\n let token: string\n let ownerId: string\n try {\n token = await ensureToken()\n const payload = decodeJwtPayload<{ sub: string }>(token)\n ownerId = payload.sub\n } catch (err) {\n // Surface ensureToken's canonical message (\"Not logged in. Run `deepspace\n // login` first.\" / \"Session expired…\") instead of a bespoke one (ONB-5).\n throw new Refusal(\n err instanceof Error ? err.message : 'Not logged in. Run `deepspace auth login` first.',\n 'not_authenticated',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n\n // Refresh the app-store secrets cache (config = wrangler env, or 'prd').\n // A repo without a DEEPSPACE_APP_ID hasn't been initialized — writeDevVars\n // below throws with the `deepspace app init` pointer, so skip the pull.\n let generatedSecretsCache: string | undefined\n const appIdForSecrets = readAppId(appDir, wranglerEnv)\n if (appIdForSecrets) {\n try {\n const refreshed = await refreshSecretsCache(DEPLOY_URL, token, appIdForSecrets, wranglerEnv)\n if (refreshed) {\n generatedSecretsCache = refreshed.rendered\n say(refreshed.summary)\n }\n } catch (err: unknown) {\n throw new Refusal(\n `Failed to refresh app secrets: ${err instanceof Error ? err.message : String(err)}`,\n 'secrets_refresh_failed',\n )\n }\n }\n\n const sharedDevVarsCache = generatedSecretsCache !== undefined\n await writeDevVars(appDir, ownerId, token, wranglerEnv, {\n generatedSecretsCache,\n sharedDevVarsCache,\n })\n\n if (suite !== 'unit') {\n preflightWindowsWorkerd(appDir)\n ensurePlaywright(appDir)\n }\n\n let exitCode = 0\n\n switch (suite) {\n case 'smoke':\n exitCode = runPlaywright(\n appDir,\n ['tests/smoke.spec.ts'],\n port,\n wranglerEnv,\n sharedDevVarsCache,\n )\n break\n case 'api':\n exitCode = runPlaywright(\n appDir,\n ['tests/api.spec.ts'],\n port,\n wranglerEnv,\n sharedDevVarsCache,\n )\n break\n case 'e2e':\n exitCode = runPlaywright(appDir, [], port, wranglerEnv, sharedDevVarsCache)\n break\n case 'unit':\n exitCode = runVitest(appDir)\n break\n case 'all':\n exitCode = runVitest(appDir)\n if (exitCode === 0)\n exitCode = runPlaywright(appDir, [], port, wranglerEnv, sharedDevVarsCache)\n break\n case 'default':\n exitCode = runPlaywright(\n appDir,\n ['tests/smoke.spec.ts', 'tests/api.spec.ts'],\n port,\n wranglerEnv,\n sharedDevVarsCache,\n )\n break\n default:\n if (suite.endsWith('.spec.ts')) {\n exitCode = runPlaywright(appDir, [suite], port, wranglerEnv, sharedDevVarsCache)\n } else {\n throw new Refusal(\n `Unknown test suite: ${suite}\\nAvailable: smoke, api, e2e, unit, all`,\n 'unknown_suite',\n )\n }\n }\n\n // The runner already printed every failure in detail; the refusal adds the\n // slug and the non-zero exit. Playwright's own code collapses to 1 — the\n // contract reserves 0/1/2 and every non-zero code here means \"tests failed\".\n if (exitCode !== 0) {\n throw new Refusal(`Test suite '${suite}' failed (exit ${exitCode}).`, 'tests_failed', {\n extra: { suite, port, exitCode },\n })\n }\n return { data: { suite, port, appDir, wranglerEnv: wranglerEnv ?? null } }\n },\n})\n\nfunction runPlaywright(\n appDir: string,\n testFiles: string[],\n port: number,\n wranglerEnv?: string,\n sharedDevVarsCache = false,\n): number {\n let wranglerConfig: PreparedWranglerEnvConfig\n try {\n wranglerConfig = prepareWranglerEnvConfig(appDir, wranglerEnv, { sharedDevVarsCache })\n } catch (err: unknown) {\n console.error(err instanceof Error ? err.message : String(err))\n return 1\n }\n try {\n const result = spawnSync(\n 'npx',\n ['playwright', 'test', '--config', 'tests/playwright.config.ts', ...testFiles],\n {\n cwd: appDir,\n stdio: 'inherit',\n env: wranglerViteEnv(process.env, wranglerConfig, { DEEPSPACE_PORT: String(port) }),\n },\n )\n return result.status ?? 1\n } finally {\n wranglerConfig.cleanup()\n }\n}\n\nfunction runVitest(appDir: string): number {\n const result = spawnSync('npx', ['vitest', 'run', '--passWithNoTests'], {\n cwd: appDir,\n stdio: 'inherit',\n })\n return result.status ?? 1\n}\n","import { Refusal } from './command'\nimport { execSync } from 'node:child_process'\nimport { sync as spawnSync } from 'cross-spawn'\n\nexport function ensurePlaywright(appDir: string) {\n try {\n // execSync interprets the command via shell, so it handles npx/npx.cmd\n // resolution on its own. Only spawn()/spawnSync() need cross-spawn.\n execSync('npx playwright --version', { cwd: appDir, stdio: 'pipe' })\n } catch {\n console.log('Installing Playwright...')\n execSync('npm install -D @playwright/test', { cwd: appDir, stdio: 'pipe' })\n }\n\n // `playwright install` is idempotent: a fast no-op when Chromium already\n // exists, and the first real browser download only when a browser command\n // actually needs it.\n const isLinux = process.platform === 'linux'\n const isRoot = isLinux && typeof process.getuid === 'function' && process.getuid() === 0\n const args = isRoot ? ['install', '--with-deps', 'chromium'] : ['install', 'chromium']\n const result = spawnSync('npx', ['playwright', ...args], {\n cwd: appDir,\n stdio: 'inherit',\n })\n\n if (result.status !== 0) {\n throw new Refusal(\n 'Playwright install failed. On Linux, system libs may be missing. Try: sudo npx playwright install --with-deps chromium',\n 'playwright_install_failed',\n )\n }\n}\n","/**\n * deepspace test screenshot <url> <output> [--full-page] [--wait-for-timeout ms]\n *\n * Takes a Playwright Chromium screenshot, installing the browser on demand.\n *\n * Playwright is spawned with inherited stdio, so its progress streams straight\n * through — under `--json` that streamed text precedes the envelope, which is\n * still the last line on stdout.\n */\n\nimport { sync as spawnSync } from 'cross-spawn'\nimport { resolve } from 'node:path'\nimport { ensurePlaywright } from '../lib/playwright'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'screenshot',\n description: 'Take a Playwright screenshot, installing Chromium on demand',\n },\n args: {\n url: {\n type: 'positional',\n description: 'URL to capture, for example http://localhost:5173/',\n required: true,\n },\n output: {\n type: 'positional',\n description: 'Output image path, for example screenshot.png',\n required: true,\n },\n 'full-page': {\n type: 'boolean',\n description: 'Capture the full scrollable page',\n required: false,\n },\n 'wait-for-timeout': {\n type: 'string',\n description: 'Milliseconds to wait before capture',\n required: false,\n },\n },\n async run({ args }) {\n const appDir = resolve('.')\n ensurePlaywright(appDir)\n\n const url = String(args.url)\n const output = String(args.output)\n const playwrightArgs = ['playwright', 'screenshot', url, output]\n if (args['full-page']) playwrightArgs.push('--full-page')\n if (args['wait-for-timeout']) {\n playwrightArgs.push('--wait-for-timeout', String(args['wait-for-timeout']))\n }\n\n const result = spawnSync('npx', playwrightArgs, {\n cwd: appDir,\n stdio: 'inherit',\n })\n\n // Playwright already printed the reason; the refusal adds the slug an\n // agent branches on. Its own exit code collapses to 1 — the contract\n // reserves 0/1/2, and playwright only ever means \"failed\" here.\n if (result.status !== 0) {\n throw new Refusal(\n `Screenshot failed: playwright exited ${result.status ?? 'without a status'}.`,\n 'screenshot_failed',\n )\n }\n\n return { data: { url, output, fullPage: Boolean(args['full-page']) } }\n },\n})\n","/**\n * deepspace test accounts\n *\n * Manage test accounts for local development and CI.\n * Test accounts use @deepspace.test emails and are clearly\n * demarcated in the database. Max 10 per developer.\n *\n * Credentials are saved to ~/.deepspace/test-accounts.json (0600)\n * so they persist across projects and sessions.\n *\n * deepspace test accounts create --email bot@deepspace.test --password Pass123!\n * deepspace test accounts list\n * deepspace test accounts delete --email bot@deepspace.test\n * deepspace test accounts delete --id <id>\n * deepspace test accounts clear # delete all (with confirm)\n * deepspace test accounts clear --label e2e # delete only label=e2e\n * deepspace test accounts clear --yes # skip confirm (CI)\n */\n\nimport { defineCommand } from 'citty'\nimport * as p from '@clack/prompts'\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\nimport { ensureToken, SESSION_PATH } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst SESSION_COOKIE = '__Secure-better-auth.session_token'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth\nconst DIR = join(homedir(), '.deepspace')\nconst ACCOUNTS_PATH = join(DIR, 'test-accounts.json')\n\n// ── Local credential store ─────────────────────────────────────────\n\ninterface StoredAccount {\n id: string\n email: string\n password: string\n userId: string\n name?: string\n label?: string | null\n createdAt: number\n}\n\nfunction loadAccounts(): StoredAccount[] {\n if (!existsSync(ACCOUNTS_PATH)) return []\n try {\n return JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'))\n } catch {\n return []\n }\n}\n\nfunction saveAccounts(accounts: StoredAccount[]) {\n mkdirSync(DIR, { recursive: true })\n writeFileSync(ACCOUNTS_PATH, JSON.stringify(accounts, null, 2), { mode: 0o600 })\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction sessionCookie(): string {\n const token = readFileSync(SESSION_PATH, 'utf-8').trim()\n return `${SESSION_COOKIE}=${encodeURIComponent(token)}`\n}\n\ninterface RemoteAccount {\n id: string\n email: string\n userId: string\n label: string | null\n createdAt: number\n}\n\nasync function fetchRemoteAccounts(): Promise<RemoteAccount[]> {\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts`, {\n headers: { Cookie: sessionCookie(), Origin: AUTH_URL },\n })\n const data = (await res.json().catch(() => ({}))) as {\n accounts?: RemoteAccount[]\n error?: string\n }\n if (!res.ok || !data.accounts) {\n throw new Error(data.error ?? 'Failed to list test accounts')\n }\n return data.accounts\n}\n\nasync function deleteRemote(id: string): Promise<void> {\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts/${id}`, {\n method: 'DELETE',\n headers: { Cookie: sessionCookie(), Origin: AUTH_URL },\n })\n if (!res.ok) {\n const data = (await res.json().catch(() => ({}))) as { error?: string }\n throw new Error(data.error ?? `DELETE returned ${res.status}`)\n }\n}\n\n// ── Subcommands ────────────────────────────────────────────────────\n\nconst create = defineDeepspaceCommand({\n meta: {\n name: 'create',\n description: 'Create a test account',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email (must end with @deepspace.test)',\n required: true,\n },\n password: {\n type: 'string',\n description: 'Password (min 8 characters)',\n required: true,\n },\n name: {\n type: 'string',\n description: 'Display name',\n required: false,\n },\n label: {\n type: 'string',\n description: 'Label for this test account',\n required: false,\n },\n },\n async run({ args }) {\n await ensureToken()\n\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Cookie: sessionCookie(),\n Origin: AUTH_URL,\n },\n body: JSON.stringify({\n email: args.email,\n password: args.password,\n name: args.name,\n label: args.label,\n }),\n })\n\n const data = (await res.json().catch(() => ({}))) as {\n id?: string\n email?: string\n userId?: string\n label?: string | null\n createdAt?: number\n error?: string\n }\n\n if (!res.ok || !data.id) {\n throw new Refusal(`Failed: ${data.error ?? 'Unknown error'}`, 'test_account_create_failed')\n }\n\n const account = data as {\n id: string\n email: string\n userId: string\n label: string | null\n createdAt: number\n }\n\n // Save credentials locally\n const accounts = loadAccounts()\n accounts.push({\n id: account.id,\n email: args.email as string,\n password: args.password as string,\n userId: account.userId,\n name: args.name as string | undefined,\n label: account.label,\n createdAt: account.createdAt,\n })\n saveAccounts(accounts)\n\n if (!args.json) {\n console.log(`Created test account:`)\n console.log(` ID: ${account.id}`)\n console.log(` Email: ${account.email}`)\n console.log(` Password: ${args.password}`)\n console.log(` UserID: ${account.userId}`)\n if (account.label) console.log(` Label: ${account.label}`)\n console.log(`\\nSaved to ${ACCOUNTS_PATH}`)\n }\n\n return {\n data: {\n id: account.id,\n email: account.email,\n // The password is already echoed on the human path and stored 0600 in\n // ACCOUNTS_PATH — withholding it from --json would only force scripts\n // to parse the file themselves.\n password: args.password,\n userId: account.userId,\n label: account.label ?? null,\n createdAt: account.createdAt,\n savedTo: ACCOUNTS_PATH,\n },\n }\n },\n})\n\nconst list = defineDeepspaceCommand({\n meta: {\n name: 'list',\n description: 'List your test accounts',\n },\n async run({ args }) {\n await ensureToken()\n\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n throw new Refusal(`Failed: ${(err as Error).message}`, 'test_accounts_list_failed')\n }\n\n // Merge with local credentials (passwords are only stored locally)\n const local = loadAccounts()\n const localByEmail = new Map(local.map((a) => [a.email, a]))\n\n if (remote.length === 0) {\n if (!args.json) {\n console.log(\n 'No test accounts. Create one with: deepspace test accounts create --email <email> --password <password>',\n )\n }\n return { data: { accounts: [], count: 0, limit: 10 } }\n }\n\n if (!args.json) {\n console.log(`Test accounts (${remote.length}/10):\\n`)\n for (const a of remote) {\n const stored = localByEmail.get(a.email)\n const date = new Date(a.createdAt).toLocaleDateString()\n console.log(` ${a.email}${a.label ? ` (${a.label})` : ''}`)\n console.log(` ID: ${a.id} UserID: ${a.userId} Created: ${date}`)\n if (stored?.password) {\n console.log(` Password: ${stored.password}`)\n } else {\n console.log(` Password: (not saved locally)`)\n }\n }\n }\n\n return {\n data: {\n accounts: remote.map((a) => ({\n id: a.id,\n email: a.email,\n userId: a.userId,\n label: a.label,\n createdAt: a.createdAt,\n password: localByEmail.get(a.email)?.password ?? null,\n })),\n count: remote.length,\n limit: 10,\n },\n }\n },\n})\n\nconst del = defineDeepspaceCommand({\n meta: {\n name: 'delete',\n description: 'Delete a test account by --email or --id',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email of the test account to delete',\n required: false,\n },\n id: {\n type: 'string',\n description: 'ID of the test account to delete',\n required: false,\n },\n },\n async run({ args }) {\n if (!args.email && !args.id) {\n throw new Refusal('Provide --email <email> or --id <id>.', 'missing_argument')\n }\n if (args.email && args.id) {\n throw new Refusal('Provide either --email or --id, not both.', 'conflicting_arguments')\n }\n\n await ensureToken()\n\n let targetId = args.id as string | undefined\n const targetEmail = args.email as string | undefined\n\n if (targetEmail && !targetId) {\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n throw new Refusal(`Failed: ${(err as Error).message}`, 'test_accounts_list_failed')\n }\n const match = remote.find((a) => a.email === targetEmail)\n if (!match) {\n throw new Refusal(`No test account with email ${targetEmail}.`, 'test_account_not_found', {\n action: cliAction('deepspace', 'test', 'accounts', 'list'),\n })\n }\n targetId = match.id\n }\n\n try {\n await deleteRemote(targetId!)\n } catch (err) {\n throw new Refusal(`Failed: ${(err as Error).message}`, 'test_account_delete_failed')\n }\n\n // Remove from local store\n const accounts = loadAccounts().filter(\n (a) => a.id !== targetId && (!targetEmail || a.email !== targetEmail),\n )\n saveAccounts(accounts)\n\n if (!args.json) {\n console.log(`Test account deleted${targetEmail ? `: ${targetEmail}` : `: ${targetId}`}`)\n }\n return { data: { deleted: true, id: targetId ?? null, email: targetEmail ?? null } }\n },\n})\n\nconst clear = defineDeepspaceCommand({\n meta: {\n name: 'clear',\n description: 'Delete all your test accounts (or those matching --label)',\n },\n args: {\n label: {\n type: 'string',\n description: 'Only delete accounts with this label (e.g. e2e, slack-clone)',\n required: false,\n },\n yes: {\n type: 'boolean',\n description: 'Skip confirmation prompt (for CI scripts)',\n default: false,\n },\n },\n async run({ args }) {\n const label = args.label as string | undefined\n await ensureToken()\n\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n throw new Refusal(`Failed: ${(err as Error).message}`, 'test_accounts_list_failed')\n }\n\n const targets = label ? remote.filter((a) => a.label === label) : remote\n\n if (targets.length === 0) {\n const suffix = label ? ` with label '${label}'` : ''\n if (!args.json) console.log(`No test accounts${suffix} to delete.`)\n return { data: { deleted: 0, requested: 0, failures: [] } }\n }\n\n if (!args.yes) {\n // p.confirm needs a TTY it can prompt on. A `--json` caller is a script by\n // definition, so prompting would block forever with nothing on stdout —\n // refuse with the flag that resolves it instead of hanging.\n if (args.json) {\n throw new Refusal(\n 'Deleting test accounts needs confirmation. Pass --yes to confirm non-interactively.',\n 'confirmation_required',\n )\n }\n const subject = label\n ? `${targets.length} test account(s) labeled '${label}'`\n : `all ${targets.length} test account(s)`\n const confirmed = await p.confirm({\n message: `Delete ${subject}? This is not reversible.`,\n initialValue: false,\n })\n if (p.isCancel(confirmed) || !confirmed) {\n console.log('Cancelled.')\n return { data: { deleted: 0, requested: targets.length, cancelled: true, failures: [] } }\n }\n }\n\n let ok = 0\n const failures: Array<{ email: string; error: string }> = []\n for (const a of targets) {\n try {\n await deleteRemote(a.id)\n ok++\n } catch (err) {\n failures.push({ email: a.email, error: (err as Error).message })\n }\n }\n\n // Sync local store with what's actually deleted.\n const deletedIds = new Set(\n targets.filter((t) => !failures.find((f) => f.email === t.email)).map((t) => t.id),\n )\n saveAccounts(loadAccounts().filter((a) => !deletedIds.has(a.id)))\n\n if (failures.length > 0) {\n // A partial delete still failed overall — carry the per-account reasons\n // in the refusal so --json reports them instead of only the count.\n throw new Refusal(\n `Deleted ${ok}/${targets.length} test account(s).\\nFailed:\\n` +\n failures.map((f) => ` ${f.email}: ${f.error}`).join('\\n'),\n 'test_account_delete_failed',\n { extra: { deleted: ok, requested: targets.length, failures } },\n )\n }\n if (!args.json) console.log(`Deleted ${ok}/${targets.length} test account(s).`)\n return { data: { deleted: ok, requested: targets.length, failures: [] } }\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'test-accounts',\n description: 'Manage test accounts for development',\n },\n subCommands: {\n create,\n list,\n delete: del,\n clear,\n },\n})\n","/** Build and deploy a DeepSpace app through the platform deploy worker. */\n\nimport * as p from '@clack/prompts'\nimport { defineCommand } from 'citty'\nimport { resolve } from 'node:path'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { mintAppId, readAppId, resolveExistingAppId, writeAppId } from '../lib/app-identity'\nimport { ensureInstallReady } from '../lib/install-status'\nimport type { CliAction } from '../lib/output'\nimport { preflightNodeVersion } from '../lib/preflight'\nimport { createSpinner } from '../lib/spinner'\nimport {\n hasWranglerConfig,\n readWranglerConfig,\n resolveAppNameForEnv,\n type WranglerConfig,\n} from '../lib/wrangler-env'\nimport { buildDeployBundle } from './deploy/build'\nimport { syncOneTimeProducts, syncSubscriptionPlans } from './deploy/commerce'\nimport { createDeployOutput, type DeployOutput } from './deploy/output'\nimport { deployBuiltBundle } from './deploy/request'\nimport { syncDeployRepository } from './deploy/repository'\nimport { loadDeploySecrets, prepareDeploySecrets } from './deploy/secrets'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nexport default defineCommand({\n meta: {\n name: 'deploy',\n description: 'Build and deploy your DeepSpace app',\n },\n args: {\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description:\n 'wrangler.toml [env.<name>] block to deploy (e.g. --env staging). ' +\n 'Omit to deploy the top-level config.',\n required: false,\n },\n rename: {\n type: 'boolean',\n description:\n 'Confirm that a changed wrangler `name` renames this app (its URL moves; data, secrets, and collaborators travel). Without this flag an interactive prompt asks.',\n default: false,\n },\n 'allow-missing-secrets': {\n type: 'boolean',\n description:\n 'Deploy even though hand-edited .dev.vars secrets are absent from the store (they will NOT be deployed, and any a previous deploy set are dropped).',\n default: false,\n },\n adopt: {\n type: 'boolean',\n description:\n 'Confirm adopting an existing app you can deploy but do not own (collaborator/admin ' +\n 'on-behalf) when wrangler.toml has no DEEPSPACE_APP_ID. Without this flag an ' +\n 'interactive prompt asks.',\n default: false,\n },\n // Citty maps --no-push to the negation of an argument named `push`.\n push: {\n type: 'boolean',\n description:\n \"Sync the branch to the app's cloud repo before deploying (--no-push to skip; the \" +\n 'release then may point at source the platform cannot recover).',\n default: true,\n },\n 'ignore-stale': {\n type: 'boolean',\n description:\n 'Deploy even if someone released a newer version since you last synced (skips the ' +\n 'stale-base guard).',\n default: false,\n },\n json: {\n type: 'boolean',\n description:\n 'Emit a single-line JSON result for scripts/agents (human output goes to stderr)',\n default: false,\n },\n },\n async run({ args }) {\n const output = createDeployOutput(args.json === true)\n preflightNodeVersion('deploy')\n const appDir = resolve(args.dir ?? '.')\n\n const selectorRefusal = blankSelectorRefusal(args)\n if (selectorRefusal) output.die(selectorRefusal.error, selectorRefusal.code)\n const envName = typeof args.env === 'string' && args.env.trim() ? args.env.trim() : undefined\n\n if (!hasWranglerConfig(appDir)) {\n output.die('No wrangler.toml found. Are you in a DeepSpace app directory?', 'not_in_app_repo')\n }\n try {\n ensureInstallReady(appDir)\n } catch (error: unknown) {\n const refusal = error as { message?: string; code?: string; action?: CliAction }\n output.die(refusal.message ?? String(error), refusal.code ?? 'deps_missing', {\n action: refusal.action,\n })\n }\n\n p.intro('Deploying DeepSpace app')\n output.showIntro()\n\n const wranglerConfig: WranglerConfig = readWranglerConfig(appDir)\n const nameResult = resolveAppNameForEnv(wranglerConfig, envName)\n if (!nameResult.ok) return output.die(nameResult.reason, 'invalid_app_name')\n const declaredName = envName ? wranglerConfig.env?.[envName]?.name : wranglerConfig.name\n if (declaredName !== nameResult.name) {\n const location = envName ? `[env.${envName}].name` : '`name`'\n output.die(\n `wrangler.toml: ${location} \"${declaredName}\" is not in canonical form. ` +\n `Update it to \"${nameResult.name}\" and re-run.`,\n 'invalid_app_name',\n )\n }\n const appName = nameResult.name\n let appId = readAppId(appDir, envName)\n p.log.info(envName ? `App: ${appName} (env: ${envName})` : `App: ${appName}`)\n\n const { token, ownerId } = await authenticate(appDir, output)\n\n if (!appId) {\n const existing = await resolveExistingAppId(DEPLOY_URL, token, appName)\n if (existing.kind === 'taken') {\n output.die(\n `\"${appName}\" is taken by an app you don't have deploy access to. ` +\n 'Ask the owner to add you as a collaborator (`deepspace app collaborators add`), ' +\n 'or pick a different `name` in wrangler.toml.',\n 'name_taken',\n )\n }\n if (existing.kind === 'adopted' && !existing.owned && !args.adopt) {\n if (output.nonInteractive) {\n output.die(\n `\"${appName}\" is an existing app owned by another account that you can deploy ` +\n 'on-behalf (collaborator/admin). Confirmation needs --adopt here — ' +\n 're-run with --adopt to deploy it, or pick a different `name` in wrangler.toml ' +\n 'if you meant a new app.',\n 'confirmation_required',\n )\n }\n const confirmed = await p.confirm({\n message:\n `\"${appName}\" is an existing app owned by another account that you can deploy ` +\n 'on-behalf (you are a collaborator or admin). Deploy it? ' +\n '(Meant a new app? Pick a different `name` in wrangler.toml.)',\n })\n if (p.isCancel(confirmed) || !confirmed) {\n output.die('Deploy cancelled.', 'cancelled')\n }\n }\n appId = existing.kind === 'adopted' ? existing.appId : mintAppId()\n writeAppId(appDir, appId, { wranglerEnv: envName })\n p.log.info(\n existing.kind === 'adopted'\n ? `Adopted existing app id ${appId} for ${appName} — commit wrangler.toml.`\n : `Minted app id ${appId} — commit wrangler.toml.`,\n )\n }\n p.log.info(`Id: ${appId}`)\n\n const secretsCache = await loadDeploySecrets({\n deployUrl: DEPLOY_URL,\n appDir,\n appId,\n envName,\n ownerId,\n token,\n output,\n })\n const repository = await syncDeployRepository({\n deployUrl: DEPLOY_URL,\n appDir,\n appId,\n token,\n push: args.push !== false,\n ignoreStale: Boolean(args['ignore-stale']),\n output,\n })\n\n const spinner = createSpinner()\n const bundle = await buildDeployBundle({\n appDir,\n appName,\n envName,\n sharedDevVarsCache: secretsCache.linked !== null,\n wranglerConfig,\n output,\n spinner,\n })\n const secrets = prepareDeploySecrets({\n appDir,\n envName,\n cache: secretsCache,\n allowMissing: Boolean(args['allow-missing-secrets']),\n customBindings: bundle.customBindings,\n doManifest: bundle.doManifest,\n output,\n })\n const body = await deployBuiltBundle({\n deployUrl: DEPLOY_URL,\n appDir,\n appId,\n appName,\n token,\n rename: args.rename === true,\n ignoreStale: Boolean(args['ignore-stale']),\n bundle,\n secrets,\n repository,\n output,\n spinner,\n })\n\n if (body.url) {\n spinner.message('Waiting for edge propagation...')\n const ready = await waitForAssetsReady(body.url, 90_000)\n if (!ready) {\n spinner.stop('Deployed (edge propagation still in progress after 90s)')\n p.log.warn(\n 'First requests may briefly hit the assets transitional page; retry in a minute.',\n )\n p.log.info(`URL: ${body.url} (deploy accepted; serving not yet verified from here)`)\n await syncCommerce(appDir, appId, token, output.nonInteractive)\n if (output.json) {\n return output.emitJson({\n ok: true,\n appId,\n appName,\n url: body.url,\n releaseId: body.releaseId ?? null,\n bundleRetained: body.bundleRetained ?? null,\n edgePropagating: true,\n recoverable: repository.recoverable,\n ...staleBaseGuardFields(body),\n })\n }\n p.outro('Done')\n return\n }\n }\n\n spinner.stop('Deployed!')\n p.log.success(`Live at: ${body.url}`)\n await syncCommerce(appDir, appId, token, output.nonInteractive)\n if (output.json) {\n return output.emitJson({\n ok: true,\n appId,\n appName,\n url: body.url ?? null,\n releaseId: body.releaseId ?? null,\n bundleRetained: body.bundleRetained ?? null,\n recoverable: repository.recoverable,\n ...staleBaseGuardFields(body),\n })\n }\n p.outro('Done')\n },\n})\n\nasync function syncCommerce(\n appDir: string,\n appId: string,\n token: string,\n nonInteractive: boolean,\n): Promise<void> {\n await syncSubscriptionPlans(appDir, appId, token, nonInteractive)\n await syncOneTimeProducts(appDir, appId, token)\n}\n\n/** Refuse explicit blank selectors before auth so they cannot fall back to production/cwd. */\nexport function blankSelectorRefusal(args: {\n dir?: unknown\n env?: unknown\n}): { code: string; error: string } | null {\n if (args.env !== undefined && !String(args.env).trim()) {\n return {\n code: 'invalid_env',\n error:\n '--env was given an empty environment name — pass an env (e.g. --env staging), or omit --env to deploy the top-level config.',\n }\n }\n if (args.dir !== undefined && !String(args.dir).trim()) {\n return {\n code: 'invalid_dir',\n error:\n 'The app directory argument was empty — pass a directory, or omit it to deploy the current directory.',\n }\n }\n return null\n}\n\nexport function staleBaseGuardFields(body: {\n staleBaseGuard?: unknown\n}): { staleBaseGuard: 'skipped' } | Record<string, never> {\n return body.staleBaseGuard === 'skipped' ? { staleBaseGuard: 'skipped' } : {}\n}\n\n/** Wait until the new deployment is consistently serving across edge isolates. */\nasync function waitForAssetsReady(url: string, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs\n let attempt = 0\n let streak = 0\n\n while (Date.now() < deadline) {\n attempt++\n try {\n const response = await fetch(url, { redirect: 'manual' })\n const body = await response.text()\n if (!body.includes('Assets have not yet deployed') && !body.includes('No app configured')) {\n streak++\n if (streak >= 3) return true\n await new Promise((resolve) => setTimeout(resolve, 1_500))\n continue\n }\n streak = 0\n } catch {\n streak = 0\n }\n\n const waitMs = Math.min(8_000, 1_000 * 2 ** (attempt - 1))\n await new Promise((resolve) => setTimeout(resolve, waitMs))\n }\n return false\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nasync function authenticate(\n appDir: string,\n output: DeployOutput,\n): Promise<{ token: string; ownerId: string }> {\n try {\n const token = await ensureToken()\n return { token, ownerId: decodeJwtPayload<{ sub: string }>(token).sub }\n } catch (error: unknown) {\n output.die(errorMessage(error), 'not_authenticated', {\n action: { cwd: appDir, argv: ['deepspace', 'auth', 'login'] },\n })\n }\n}\n","import * as p from '@clack/prompts'\nimport { execSync } from 'node:child_process'\nimport { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport {\n bindingManifestFromOutputConfig,\n validateBindingManifest,\n type CustomBindingManifest,\n} from '../../../server/rooms/binding-manifest'\nimport { removeMacosJunk } from '../../lib/macos-junk'\nimport { formatSchemaLintFindings, lintProjectSchemas } from '../../lib/schema-lint'\nimport type { Spinner } from '../../lib/spinner'\nimport {\n prepareWranglerEnvConfig,\n wranglerViteEnv,\n type PreparedWranglerEnvConfig,\n type WranglerConfig,\n} from '../../lib/wrangler-env'\nimport type { DeployOutput } from './output'\n\nconst RESERVED_RUN_WORKER_FIRST = new Set([\n '/api/*',\n '/ws/*',\n '/internal/*',\n '/v1/*',\n '/_deepspace/*',\n])\n\nexport interface DeployAsset {\n path: string\n contentBase64: string\n}\n\nexport interface DurableObjectManifestEntry {\n binding: string\n className: string\n sqlite: boolean\n}\n\nexport interface DeployBundle {\n assets: DeployAsset[]\n workerJs: string\n doManifest: DurableObjectManifestEntry[] | undefined\n customBindings: CustomBindingManifest\n extraRoutes: string[]\n}\n\ninterface OutputWranglerConfig extends Record<string, unknown> {\n name?: string\n main: string\n assets?: { directory: string }\n durable_objects?: { bindings: Array<{ name: string; class_name: string }> }\n migrations?: Array<{ new_sqlite_classes?: string[] }>\n}\n\nexport async function buildDeployBundle(options: {\n appDir: string\n appName: string\n envName: string | undefined\n sharedDevVarsCache: boolean\n wranglerConfig: WranglerConfig\n output: DeployOutput\n spinner: Spinner\n}): Promise<DeployBundle> {\n const { appDir, appName, envName, sharedDevVarsCache, wranglerConfig, output, spinner } = options\n const junk = removeMacosJunk(appDir)\n if (junk > 0) p.log.info(`Removed ${junk} macOS metadata file(s) (._*, .DS_Store)`)\n\n const lintFindings = await lintProjectSchemas(appDir)\n if (lintFindings && lintFindings.length > 0) {\n p.log.warn(formatSchemaLintFindings(lintFindings).join('\\n'))\n }\n\n spinner.start('Building...')\n let preparedWranglerConfig: PreparedWranglerEnvConfig | undefined\n try {\n preparedWranglerConfig = prepareWranglerEnvConfig(appDir, envName, {\n sharedDevVarsCache,\n })\n execSync('npx vite build', {\n cwd: appDir,\n stdio: 'pipe',\n env: wranglerViteEnv(process.env, preparedWranglerConfig),\n })\n } catch (error: unknown) {\n spinner.stop('Build failed')\n const execError = error as {\n stdout?: { toString(): string }\n stderr?: { toString(): string }\n }\n const detail = [execError.stdout?.toString(), execError.stderr?.toString()]\n .filter(Boolean)\n .join('\\n')\n .trim()\n output.die(detail || errorMessage(error), 'build_failed')\n } finally {\n preparedWranglerConfig?.cleanup()\n }\n spinner.stop('Built')\n\n const deployConfigPath = join(appDir, '.wrangler', 'deploy', 'config.json')\n if (!existsSync(deployConfigPath)) {\n output.die(\n 'Build output config not found at .wrangler/deploy/config.json',\n 'build_output_missing',\n )\n }\n\n const deployConfig = JSON.parse(readFileSync(deployConfigPath, 'utf-8')) as {\n configPath: string\n }\n const outputWranglerPath = resolve(dirname(deployConfigPath), deployConfig.configPath)\n if (!existsSync(outputWranglerPath)) {\n output.die(`Output wrangler.json not found at ${outputWranglerPath}`, 'build_output_missing')\n }\n\n const outputConfig = JSON.parse(readFileSync(outputWranglerPath, 'utf-8')) as OutputWranglerConfig\n if (outputConfig.name && outputConfig.name !== appName) {\n const envHint = envName ? ` (--env ${envName})` : ''\n output.die(\n `Build output mismatch: expected name \"${appName}\"${envHint}, ` +\n `but the built wrangler.json declares \"${outputConfig.name}\". ` +\n `This usually means the Cloudflare Vite plugin didn't apply ` +\n `DeepSpace's generated env config. Check the plugin version and re-run.`,\n 'build_output_mismatch',\n )\n }\n\n const workerDir = dirname(outputWranglerPath)\n const workerBundlePath = join(workerDir, outputConfig.main)\n const clientDir = outputConfig.assets?.directory\n ? resolve(workerDir, outputConfig.assets.directory)\n : null\n if (!existsSync(workerBundlePath)) {\n output.die(`Worker bundle not found at ${workerBundlePath}`, 'build_output_missing')\n }\n if (!clientDir || !existsSync(clientDir)) {\n return output.die(`Client assets not found at ${clientDir}`, 'build_output_missing')\n }\n\n spinner.start('Collecting assets...')\n const assets = collectAssets(clientDir)\n spinner.stop(`Collected ${assets.length} assets`)\n const workerJs = readFileSync(workerBundlePath, 'utf-8')\n\n const doBindings = outputConfig.durable_objects?.bindings\n const sqliteClasses = new Set(\n outputConfig.migrations?.flatMap((migration) => migration.new_sqlite_classes ?? []) ?? [],\n )\n const doManifest = doBindings?.map((binding) => ({\n binding: binding.name,\n className: binding.class_name,\n sqlite: sqliteClasses.has(binding.class_name),\n }))\n if (doManifest?.length) p.log.info(`DO manifest: ${doManifest.length} binding(s)`)\n\n const customBindings = bindingManifestFromOutputConfig(outputConfig)\n const validation = validateBindingManifest(customBindings)\n if (!validation.valid) {\n output.die(\n `Invalid binding(s) in wrangler.toml:\\n` +\n validation.errors.map((error) => ` • ${error.reason}`).join('\\n'),\n 'invalid_bindings',\n )\n }\n if (customBindings.length) {\n p.log.info(\n `Custom bindings: ${customBindings.map((binding) => `${binding.name} (${binding.type})`).join(', ')}`,\n )\n }\n\n const extraRoutes = extractRunWorkerFirst(wranglerConfig)\n\n return {\n assets,\n workerJs,\n doManifest,\n customBindings,\n extraRoutes,\n }\n}\n\nfunction extractRunWorkerFirst(config: WranglerConfig): string[] {\n const raw = config.assets?.run_worker_first\n if (!Array.isArray(raw)) return []\n\n const routes: string[] = []\n const seen = new Set<string>()\n for (const entry of raw) {\n if (typeof entry !== 'string') continue\n const route = entry.trim()\n if (!route.startsWith('/') || RESERVED_RUN_WORKER_FIRST.has(route) || seen.has(route)) continue\n seen.add(route)\n routes.push(route)\n }\n return routes\n}\n\nfunction collectAssets(dir: string): DeployAsset[] {\n const assets: DeployAsset[] = []\n const walk = (currentDir: string, prefix: string): void => {\n for (const entry of readdirSync(currentDir, { withFileTypes: true })) {\n if (entry.name === '.assetsignore') continue\n const fullPath = join(currentDir, entry.name)\n const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n walk(fullPath, relativePath)\n } else {\n assets.push({\n path: `/${relativePath}`,\n contentBase64: readFileSync(fullPath).toString('base64'),\n })\n }\n }\n }\n walk(dir, '')\n return assets\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import * as p from '@clack/prompts'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { PLATFORM_URLS } from '../../env'\nimport { createSpinner } from '../../lib/spinner'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\ninterface PlanChange {\n slug: string\n reason: 'removed' | 'repriced'\n affectedSubscribers: number\n intervals?: Array<{ interval: 'month' | 'year'; oldCents: number; newCents: number }>\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nasync function loadDeclaration(\n appDir: string,\n sourceFile: string,\n outputFile: string,\n exportName: string,\n): Promise<unknown> {\n const sourcePath = join(appDir, 'src', sourceFile)\n if (!existsSync(sourcePath)) return undefined\n const esbuild = await import('esbuild')\n const outputPath = join(appDir, '.wrangler', 'deploy', outputFile)\n await esbuild.build({\n entryPoints: [sourcePath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: outputPath,\n logLevel: 'silent',\n write: true,\n })\n const module = (await import(`${pathToFileURL(outputPath).href}?t=${Date.now()}`)) as Record<\n string,\n unknown\n >\n return module[exportName]\n}\n\nfunction formatCents(cents: number): string {\n return cents === 0 ? 'free' : `$${(cents / 100).toFixed(2)}`\n}\n\nfunction planChangeSummary(change: PlanChange): string {\n const count = `${change.affectedSubscribers} subscriber${change.affectedSubscribers === 1 ? '' : 's'}`\n if (change.reason === 'removed') return ` • ${change.slug} — removed (${count} still on it)`\n const diffs = (change.intervals ?? [])\n .map(\n (interval) =>\n `${interval.interval}: ${formatCents(interval.oldCents)} → ${formatCents(interval.newCents)}`,\n )\n .join('; ')\n return ` • ${change.slug} — repriced (${diffs}; ${count} grandfathered on old price)`\n}\n\nasync function cancelChangedPlans(appName: string, token: string, changes: PlanChange[]) {\n p.log.warn(\n `Plan change${changes.length === 1 ? '' : 's'} from this deploy left subscribers stranded:\\n` +\n `${changes.map(planChangeSummary).join('\\n')}\\n\\n` +\n 'Stripe will keep charging them until you cancel. Cancel at the end of their current billing period?',\n )\n const confirmed = await p.confirm({\n message: `Cancel ${changes.length === 1 ? 'these subscribers' : 'all of them'} at period end?`,\n initialValue: false,\n })\n if (p.isCancel(confirmed) || !confirmed) {\n p.log.info('Skipped — existing subscribers stay on their current plan/price.')\n return\n }\n\n const maxIterations = 100\n for (const change of changes) {\n const spinner = createSpinner()\n spinner.start(\n `Canceling ${change.affectedSubscribers} subscriber${change.affectedSubscribers === 1 ? '' : 's'} on ${change.slug}...`,\n )\n let canceled = 0\n let failed = 0\n let iteration = 0\n let lastError: string | null = null\n let stopped = false\n try {\n while (iteration < maxIterations) {\n const response = await fetch(`${API_URL}/api/subscriptions/admin-cancel`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n appName,\n planSlug: change.slug,\n atPeriodEnd: true,\n reason: `plan ${change.reason} via deploy`,\n }),\n })\n const body = (await response.json().catch(() => ({}))) as {\n success?: boolean\n canceled?: number\n failures?: unknown[]\n hasMore?: boolean\n error?: string\n }\n if (!response.ok || !body.success) {\n lastError = body.error ?? `HTTP ${response.status}`\n spinner.stop(`Cancel failed for ${change.slug}: ${lastError}`)\n stopped = true\n break\n }\n const batchCanceled = body.canceled ?? 0\n canceled += batchCanceled\n failed += body.failures?.length ?? 0\n if (!body.hasMore) break\n if (batchCanceled === 0) {\n lastError = 'no progress (all rows failed this batch)'\n break\n }\n iteration++\n }\n if (!stopped) {\n const failureSuffix = failed ? `; ${failed} failed (see Stripe)` : ''\n const capSuffix = iteration >= maxIterations ? ' (batch cap reached — re-run deploy)' : ''\n spinner.stop(\n `Canceled ${canceled} on ${change.slug}${failureSuffix}${capSuffix}${lastError ? ` — ${lastError}` : ''}`,\n )\n }\n } catch (error) {\n spinner.stop(`Cancel failed for ${change.slug}: ${errorMessage(error)}`)\n }\n }\n}\n\nexport async function syncSubscriptionPlans(\n appDir: string,\n appName: string,\n token: string,\n nonInteractive: boolean,\n): Promise<void> {\n if (!existsSync(join(appDir, 'src', 'subscriptions.ts'))) return\n let plans: unknown\n try {\n plans = await loadDeclaration(\n appDir,\n 'subscriptions.ts',\n 'subscriptions.bundle.mjs',\n 'subscriptionPlans',\n )\n } catch (error) {\n p.log.warn(`Could not load src/subscriptions.ts: ${errorMessage(error)}`)\n return\n }\n if (!Array.isArray(plans)) {\n p.log.warn('src/subscriptions.ts must `export const subscriptionPlans = [...] as const`')\n return\n }\n if (!plans.length) return\n\n const spinner = createSpinner()\n spinner.start('Syncing subscription plans...')\n try {\n const response = await fetch(`${API_URL}/api/subscriptions/sync`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify({ appId: appName, plans }),\n })\n const body = (await response.json().catch(() => ({}))) as {\n ok?: boolean\n error?: string\n hint?: string\n planChanges?: PlanChange[]\n connectMissing?: boolean\n }\n if (!response.ok || !body.ok) {\n spinner.stop('Plan sync skipped')\n p.log.warn(\n `Plan sync failed: ${body.error ?? `HTTP ${response.status}`}${body.hint ? ` — ${body.hint}` : ''}`,\n )\n return\n }\n spinner.stop(`Synced ${plans.length} plan${plans.length === 1 ? '' : 's'} to Stripe`)\n if (body.connectMissing) {\n p.log.warn(\n 'Stripe Connect not yet set up. Customers can subscribe and earnings ' +\n 'will queue in your platform balance until you finish onboarding at ' +\n '/earnings on the dashboard. The first payout after you connect ' +\n 'will sweep everything that accumulated in the meantime.',\n )\n }\n const changes = (body.planChanges ?? []).filter((change) => change.affectedSubscribers > 0)\n if (!changes.length) return\n if (nonInteractive) {\n p.log.warn(\n `${changes.length} plan change${changes.length === 1 ? '' : 's'} left subscribers stranded; ` +\n 'grandfathered (non-interactive deploy). Cancel later via the subscriptions admin helper if intended.',\n )\n return\n }\n await cancelChangedPlans(appName, token, changes)\n } catch (error) {\n spinner.stop('Plan sync skipped')\n p.log.warn(`Plan sync request failed: ${errorMessage(error)}`)\n }\n}\n\nexport async function syncOneTimeProducts(\n appDir: string,\n appName: string,\n token: string,\n): Promise<void> {\n if (!existsSync(join(appDir, 'src', 'products.ts'))) return\n let products: unknown\n try {\n products = await loadDeclaration(\n appDir,\n 'products.ts',\n 'products.bundle.mjs',\n 'oneTimeProducts',\n )\n } catch (error) {\n p.log.warn(`Could not load src/products.ts: ${errorMessage(error)}`)\n return\n }\n if (!Array.isArray(products)) {\n p.log.warn('src/products.ts must `export const oneTimeProducts = [...] as const`')\n return\n }\n\n const spinner = products.length ? createSpinner() : null\n spinner?.start('Syncing one-time products...')\n try {\n const response = await fetch(`${API_URL}/api/charges/products/sync`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify({ appId: appName, products }),\n })\n const body = (await response.json().catch(() => ({}))) as {\n ok?: boolean\n count?: number\n error?: string\n details?: unknown\n }\n if (response.ok && body.ok) {\n const count = body.count ?? products.length\n spinner?.stop(`Synced ${count} one-time product${count === 1 ? '' : 's'}`)\n return\n }\n spinner?.stop('Product sync skipped')\n p.log.warn(\n `Product sync failed: ${body.error ?? `HTTP ${response.status}`}${body.details ? ` — ${JSON.stringify(body.details)}` : ''}`,\n )\n } catch (error) {\n spinner?.stop('Product sync skipped')\n p.log.warn(`Product sync request failed: ${errorMessage(error)}`)\n }\n}\n","import * as p from '@clack/prompts'\nimport { printAction, withSlug, type CliAction } from '../../lib/output'\n\nexport interface DeployOutput {\n readonly json: boolean\n readonly nonInteractive: boolean\n emitJson(value: unknown): void\n showIntro(): void\n die(message: string, code: string, opts?: { action?: CliAction; actionRequired?: boolean }): never\n}\n\n/** Owns deploy's human/JSON output contract and its single pre-upload exit door. */\nexport function createDeployOutput(json: boolean): DeployOutput {\n const nonInteractive = json || !process.stdin.isTTY\n const realStdoutWrite = process.stdout.write.bind(process.stdout)\n let emitted = false\n let introShown = false\n let lastHuman = ''\n\n if (json) {\n process.stdout.write = ((chunk: unknown, ...rest: unknown[]): boolean => {\n const text = typeof chunk === 'string' ? chunk : String(chunk ?? '')\n const ansiSgr = new RegExp(`${String.fromCodePoint(27)}\\\\[[0-9;]*m`, 'g')\n const line = text\n .replace(ansiSgr, '')\n .replace(/[│◇◆■└┌]/g, '')\n .trim()\n if (line) lastHuman = line\n return (process.stderr.write as (...args: unknown[]) => boolean)(chunk, ...rest)\n }) as typeof process.stdout.write\n\n process.on('exit', (code) => {\n if (emitted || code === 0) return\n process.stdout.write = realStdoutWrite\n realStdoutWrite(\n `${JSON.stringify({ ok: false, code: 'deploy_failed', error: lastHuman || 'deploy failed' })}\\n`,\n )\n })\n }\n\n const emitJson = (value: unknown): void => {\n emitted = true\n process.stdout.write = realStdoutWrite\n realStdoutWrite(`${JSON.stringify(value)}\\n`)\n }\n\n return {\n json,\n nonInteractive,\n emitJson,\n showIntro() {\n introShown = true\n },\n die(message, code, opts = {}) {\n if (json) {\n emitJson({\n ok: false,\n code,\n error: message,\n ...(opts.actionRequired ? { actionRequired: true } : {}),\n ...(opts.action ? { action: opts.action } : {}),\n })\n } else {\n if (introShown && opts.actionRequired) p.log.warn(withSlug(message, code))\n else if (introShown) p.cancel(withSlug(message, code))\n else console.error(withSlug(message, code))\n if (opts.action) printAction(opts.action)\n }\n process.exit(opts.actionRequired ? 2 : 1)\n },\n }\n}\n","import * as p from '@clack/prompts'\nimport { randomUUID } from 'node:crypto'\nimport { printAction, withSlug, type CliAction } from '../../lib/output'\nimport type { Spinner } from '../../lib/spinner'\nimport type { DeployBundle } from './build'\nimport type { DeployOutput } from './output'\nimport { shouldSendLineage, type DeployRepositoryState } from './repository'\nimport type { DeploySecretsPayload } from './secrets'\n\nconst CLOUDFLARE_DEPLOY_ERROR_HINT =\n \"Deployment reached the DeepSpace deploy worker, but Cloudflare's deployment \" +\n 'control-plane API failed. This is often caused by a Cloudflare Dashboard/API ' +\n 'incident or Workers for Platforms entitlement outage. Already deployed apps ' +\n 'should keep serving; wait for Cloudflare to recover and retry.'\n\nconst MAX_GROUP_BYTES = 40 * 1024 * 1024\nconst GROUP_BYTES = (() => {\n const configured = Number(process.env.DEEPSPACE_DEPLOY_GROUP_BYTES)\n const bytes = Number.isInteger(configured) && configured > 0 ? configured : 3 * 1024 * 1024\n return Math.min(bytes, MAX_GROUP_BYTES)\n})()\n\nexport interface DeployCommitResponse {\n success?: boolean\n url?: string\n error?: string\n code?: string\n fromHost?: string\n toHost?: string\n onBehalfOfOwner?: string\n staleBaseGuard?: string\n releaseId?: string\n bundleRetained?: boolean\n}\n\nexport async function deployBuiltBundle(options: {\n deployUrl: string\n appDir: string\n appId: string\n appName: string\n token: string\n rename: boolean\n ignoreStale: boolean\n bundle: DeployBundle\n secrets: DeploySecretsPayload\n repository: DeployRepositoryState\n output: DeployOutput\n spinner: Spinner\n}): Promise<DeployCommitResponse> {\n const {\n deployUrl,\n appDir,\n appId,\n appName,\n token,\n ignoreStale,\n bundle,\n secrets,\n repository,\n output,\n spinner,\n } = options\n\n spinner.start(`Deploying ${appName}...`)\n if (bundle.extraRoutes.length) {\n p.log.info(`Custom worker-first routes: ${bundle.extraRoutes.join(', ')}`)\n }\n const assetGroups = packAssetGroups(bundle.assets, GROUP_BYTES)\n if (assetGroups.length === 0) assetGroups.push([])\n const uploadId = randomUUID()\n const totalGroups = assetGroups.length\n try {\n for (let index = 0; index < totalGroups; index++) {\n const groupJson = JSON.stringify(assetGroups[index])\n spinner.message(`Uploading assets — group ${index + 1}/${totalGroups}...`)\n const groupResponse = await postWithRetry(\n `${deployUrl}/api/deploy/${appId}/assets` +\n `?uploadId=${uploadId}&groupIndex=${index}&totalGroups=${totalGroups}`,\n () => ({\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: groupJson,\n }),\n )\n if (!groupResponse.ok) {\n const errorBody = (await groupResponse.json().catch(() => ({}))) as { error?: string }\n await abortStagedUpload(deployUrl, appId, uploadId, totalGroups, token)\n spinner.stop('Deploy failed')\n output.die(\n `Asset upload failed on group ${index + 1}/${totalGroups}: ` +\n `${errorBody.error ?? `HTTP ${groupResponse.status}`}`,\n 'upload_failed',\n )\n }\n }\n } catch (error: unknown) {\n await abortStagedUpload(deployUrl, appId, uploadId, totalGroups, token)\n spinner.stop('Deploy failed')\n output.die(`Asset upload failed (network): ${errorMessage(error)}`, 'upload_failed')\n }\n spinner.message(`Deploying ${appName}...`)\n\n let confirmRename = options.rename\n const bail = async (\n message: string,\n stopLabel: string | null = 'Deploy failed',\n code?: string,\n actionRequired = false,\n action?: CliAction,\n ): Promise<never> => {\n await abortStagedUpload(deployUrl, appId, uploadId, totalGroups, token)\n if (stopLabel !== null) spinner.stop(stopLabel)\n p.cancel(code ? withSlug(message, code) : message)\n if (action) printAction(action)\n if (output.json) {\n output.emitJson({\n ok: false,\n ...(actionRequired ? { actionRequired: true } : {}),\n error: message,\n ...(code ? { code } : {}),\n ...(action ? { action } : {}),\n })\n }\n process.exit(actionRequired ? 2 : 1)\n }\n\n const makeForm = (): FormData => {\n const form = new FormData()\n form.append(\n 'worker',\n new Blob([bundle.workerJs], { type: 'application/javascript' }),\n 'worker.js',\n )\n form.append('uploadId', uploadId)\n form.append('totalGroups', String(totalGroups))\n if (bundle.doManifest) form.append('doManifest', JSON.stringify(bundle.doManifest))\n if (bundle.customBindings.length) {\n form.append('bindingManifest', JSON.stringify(bundle.customBindings))\n }\n if (secrets.names.length) form.append('userSecrets', JSON.stringify(secrets.values))\n if (bundle.extraRoutes.length) {\n form.append('extraRunWorkerFirst', JSON.stringify(bundle.extraRoutes))\n }\n form.append('name', appName)\n if (confirmRename) form.append('confirmRename', 'true')\n if (shouldSendLineage(repository.commitOid, repository.recoverable)) {\n form.append('commitOid', repository.commitOid as string)\n }\n if (ignoreStale) form.append('ignoreStale', 'true')\n form.append('deployKey', repository.deployKey)\n return form\n }\n\n const postCommit = async (): Promise<Response> =>\n postWithRetry(\n `${deployUrl}/api/deploy/${appId}`,\n () => ({\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: makeForm(),\n }),\n { retryServerErrors: false },\n )\n\n let response: Response\n try {\n response = await postCommit()\n } catch (error: unknown) {\n await bail(\n `Deploy request failed: ${errorMessage(error)}`,\n 'Deploy failed',\n 'deploy_request_failed',\n )\n throw error\n }\n\n let body = (await response.json().catch(() => ({}))) as DeployCommitResponse\n for (\n let attempt = 0;\n response.status === 503 && body.code === 'release_finalization_pending' && attempt < 3;\n attempt++\n ) {\n await new Promise((resolve) => setTimeout(resolve, 250 * 2 ** attempt))\n response = await postCommit()\n body = (await response.json().catch(() => ({}))) as DeployCommitResponse\n }\n\n if (response.status === 409 && body.code === 'rename_required' && !confirmRename) {\n spinner.stop('Rename confirmation needed')\n if (output.nonInteractive) {\n await bail(\n `This deploy renames the app: ${body.fromHost} → ${body.toHost}. ` +\n 'Confirmation needs an interactive terminal — re-run with --rename to approve the ' +\n 'rename, or `deepspace app init --new-id` if you meant a separate app.',\n null,\n 'rename_required',\n )\n }\n const confirmed = await p.confirm({\n message:\n `This deploy renames the app: ${body.fromHost} → ${body.toHost}. ` +\n `The URL changes and the old one stops serving right away; data, secrets, and collaborators travel with it. ` +\n '(Meant a separate app? Run `deepspace app init --new-id` instead.) Rename?',\n })\n if (p.isCancel(confirmed) || !confirmed) await bail('Deploy cancelled.', null)\n\n confirmRename = true\n spinner.start(`Deploying ${appName}...`)\n response = await postCommit()\n body = (await response.json().catch(() => ({}))) as DeployCommitResponse\n }\n\n if (response.status === 409 && body.code === 'stale_base') {\n await bail(\n body.error ??\n 'A newer release landed while you worked — pull, integrate, and redeploy (or --ignore-stale).',\n 'Deploy failed',\n 'stale_base',\n true,\n { cwd: appDir, argv: ['deepspace', 'pull'] },\n )\n }\n if (!response.ok || !body.success) {\n await bail(formatDeployWorkerError(response.status, body.error), 'Deploy failed', body.code)\n }\n\n if (body.onBehalfOfOwner) {\n p.log.warn(`Deployed on behalf of owner ${body.onBehalfOfOwner}`)\n }\n if (body.staleBaseGuard === 'skipped') {\n p.log.warn(\n 'The stale-base guard was skipped (repo store unavailable) — this deploy was NOT ' +\n \"checked against the live release. Verify you're not clobbering newer work.\",\n )\n }\n if (body.bundleRetained === false) {\n p.log.warn(\n 'This deploy is live, but its rollback bundle was not retained because the app storage quota is full.',\n )\n }\n return body\n}\n\nasync function abortStagedUpload(\n deployUrl: string,\n appId: string,\n uploadId: string,\n totalGroups: number,\n token: string,\n): Promise<void> {\n try {\n await fetch(\n `${deployUrl}/api/deploy/${appId}/assets` +\n `?uploadId=${uploadId}&totalGroups=${totalGroups}`,\n { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } },\n )\n } catch {\n // Staged groups are also covered by the R2 lifecycle rule.\n }\n}\n\nfunction formatDeployWorkerError(status: number, error: string | undefined): string {\n const detail = error ?? `Deployment error (${status})`\n if (\n status < 500 &&\n ![\n 'Upload session failed',\n 'Asset upload failed',\n 'Worker deploy failed',\n 'entitlements.not_available',\n 'Internal Server Error',\n ].some((needle) => error?.includes(needle))\n ) {\n return detail\n }\n return `${CLOUDFLARE_DEPLOY_ERROR_HINT}\\n\\nUnderlying error: ${detail}`\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Pack whole asset entries into request groups under the serialized byte cap. */\nexport function packAssetGroups<T>(assets: T[], maxBytes: number): T[][] {\n const groups: T[][] = []\n let current: T[] = []\n let currentBytes = 2\n for (const asset of assets) {\n const entryBytes = Buffer.byteLength(JSON.stringify(asset), 'utf-8') + 1\n if (current.length > 0 && currentBytes + entryBytes > maxBytes) {\n groups.push(current)\n current = []\n currentBytes = 2\n }\n current.push(asset)\n currentBytes += entryBytes\n }\n if (current.length > 0) groups.push(current)\n return groups\n}\n\n/** Retry rebuilt request bodies on network failures and eligible transient responses. */\nexport async function postWithRetry(\n url: string,\n makeInit: () => RequestInit,\n {\n attempts = 4,\n retryServerErrors = true,\n }: { attempts?: number; retryServerErrors?: boolean } = {},\n): Promise<Response> {\n let lastResponse: Response | undefined\n let lastError: unknown\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n const response = await fetch(url, makeInit())\n const transient =\n retryServerErrors &&\n (response.status >= 500 || response.status === 408 || response.status === 429)\n if (!transient) return response\n lastResponse = response\n } catch (error) {\n lastError = error\n }\n if (attempt < attempts) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(8_000, 500 * 2 ** (attempt - 1))))\n }\n }\n if (lastResponse) return lastResponse\n throw lastError instanceof Error ? lastError : new Error(String(lastError))\n}\n","import * as p from '@clack/prompts'\nimport {\n assertSyncableRepo,\n currentBranch,\n isAncestor,\n isWorkTreeClean,\n resolveCommit,\n revListCount,\n} from '../../lib/git/repository'\nimport { trackedSecretFiles } from '../../lib/git/safety'\nimport { mintIdempotencyKey, repoApi, type RemoteWorkspace } from '../../lib/repo-api'\nimport { classifyPushTransportFailure, pushToSpace, type PushRefResult } from '../../lib/vc-push'\nimport { ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../../lib/vc-remote'\nimport { workspaceIdFromBranch } from '../../lib/workspace-id'\nimport { errorCode } from '../../lib/cli-errors'\nimport type { DeployOutput } from './output'\n\nexport interface DeployRepositoryState {\n commitOid: string | null\n recoverable: boolean\n deployKey: string\n}\n\nexport async function syncDeployRepository(options: {\n deployUrl: string\n appDir: string\n appId: string\n token: string\n push: boolean\n ignoreStale: boolean\n output: DeployOutput\n}): Promise<DeployRepositoryState> {\n const { deployUrl, appDir, appId, token, push, ignoreStale, output } = options\n let commitOid: string | null = null\n let recoverable = false\n const deployKey = mintIdempotencyKey()\n\n if (!push) {\n try {\n assertSyncableRepo(appDir)\n commitOid = resolveCommit(appDir, 'HEAD')\n } catch {\n // A non-repository app can still deploy; it simply has no source lineage.\n }\n return { commitOid, recoverable, deployKey }\n }\n\n try {\n assertSyncableRepo(appDir)\n ensureSpaceRemote(appDir, appId)\n const branch = currentBranch(appDir)\n const workspaceBranchId = workspaceIdFromBranch(branch)\n\n if (!isWorkTreeClean(appDir)) {\n const refusal = dirtyWorktreeRefusal(branch)\n output.die(refusal.error, refusal.code)\n }\n\n if (!branch) {\n commitOid = resolveCommit(appDir, 'HEAD')\n return { commitOid, recoverable, deployKey }\n }\n\n const tip = resolveCommit(appDir, `refs/heads/${branch}`)\n if (!tip) return { commitOid, recoverable, deployKey }\n\n const secretFiles = workspaceBranchId ? [] : trackedSecretFiles(appDir, tip)\n if (workspaceBranchId) {\n const { view } = await repoApi(deployUrl, token, appId).getWorkspace(workspaceBranchId)\n const lineage = workspaceDeployLineage(view.workspace.status, view.tipOid, tip)\n if (lineage === 'inactive') {\n output.die(\n `Workspace ${workspaceBranchId} is ${view.workspace.status}; deploy from trunk or create a new workspace.`,\n 'workspace_not_active',\n )\n }\n if (lineage === 'unsynced') {\n output.die(\n `Workspace ${workspaceBranchId} has unsynced commits. Publish this exact HEAD before deploying so the release keeps recoverable source lineage.`,\n 'workspace_unsynced',\n {\n action: { cwd: appDir, argv: ['deepspace', 'workspace', 'sync'] },\n actionRequired: true,\n },\n )\n }\n recoverable = true\n p.log.info(`Workspace ${workspaceBranchId} is synced at ${tip.slice(0, 10)}.`)\n } else if (secretFiles.length > 0) {\n p.log.warn(\n `Skipping cloud-repo push — the branch tracks secret file(s): ${secretFiles.join(', ')}. ` +\n `Untrack with \\`git rm --cached ${secretFiles[0]}\\` (add to .gitignore), re-commit, then ` +\n `\\`deepspace push\\`. Deploy continues; this release's source isn't recoverable until then.`,\n )\n } else {\n const pushResult = await pushWithTransientRetry(() =>\n pushToSpace(appDir, token, `refs/heads/${branch}:refs/heads/${branch}`),\n )\n if (pushResult.status === 'committed' || pushResult.status === 'up_to_date') {\n recoverable = true\n if (pushResult.status === 'committed') {\n p.log.info(`Pushed ${branch} → ${tip.slice(0, 10)}.`)\n }\n } else if (pushResult.status === 'rejected') {\n output.die(\n `Cloud repo rejected ${branch}${pushResult.reason ? `: ${pushResult.reason}` : ''}. Resolve the rejection and publish the commit before deploying.`,\n 'vc_push_rejected',\n )\n } else {\n const remoteState = classifyRemoteState(appDir, token, branch, tip)\n if (remoteState.strictlyBehind && !ignoreStale) {\n let behind = 'several'\n try {\n behind = String(revListCount(appDir, tip, remoteState.remoteTip as string))\n } catch {\n // The count is decoration; the refusal remains valid without it.\n }\n const message =\n `Your ${branch} is ${behind} commit(s) behind the cloud repo — deploying would take ` +\n `already-landed work off the live app. Run \\`deepspace pull\\`, then redeploy ` +\n `(or pass --ignore-stale to ship this older tree anyway).`\n output.die(message, 'behind_trunk', {\n action: {\n cwd: appDir,\n argv: ['deepspace', 'pull'],\n },\n actionRequired: true,\n })\n }\n if (remoteState.strictlyBehind) {\n recoverable = true\n p.log.warn(\n `Deploying a tree behind the cloud repo (--ignore-stale) — the live app reverts to ` +\n `${tip.slice(0, 10)} until the next deploy from an up-to-date checkout.`,\n )\n } else {\n output.die(\n `Cloud repo's ${branch} diverged (${pushResult.status}). Integrate the cloud tip, or explicitly publish an intentional history rewrite, before deploying.`,\n 'vc_diverged',\n {\n action: { cwd: appDir, argv: ['deepspace', 'pull'] },\n actionRequired: true,\n },\n )\n }\n }\n }\n commitOid = tip\n } catch (error: unknown) {\n const failure = deployRepositoryFailure(error)\n output.die(failure.error, failure.code)\n }\n\n return { commitOid, recoverable, deployKey }\n}\n\nfunction classifyRemoteState(\n appDir: string,\n token: string,\n branch: string,\n localTip: string,\n): { remoteTip: string | null; strictlyBehind: boolean } {\n let remoteTip: string | null = null\n try {\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+refs/heads/${branch}:refs/remotes/space/${branch}`,\n ])\n remoteTip = resolveCommit(appDir, `refs/remotes/space/${branch}`)\n return {\n remoteTip,\n strictlyBehind:\n remoteTip !== null && remoteTip !== localTip && isAncestor(appDir, localTip, remoteTip),\n }\n } catch {\n return { remoteTip, strictlyBehind: false }\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nexport function deployRepositoryFailure(error: unknown): { code: string; error: string } {\n const transportFailure = classifyPushTransportFailure(error)\n if (transportFailure) return transportFailure\n\n const code = errorCode(error)\n const message = errorMessage(error)\n if (code && code !== 'git_error') return { code, error: message }\n return {\n code: code ?? 'vc_sync_failed',\n error: `Version-control sync failed: ${message}`,\n }\n}\n\nexport async function pushWithTransientRetry(push: () => PushRefResult): Promise<PushRefResult> {\n const backoffMs = [500, 1500, 3500]\n for (let attempt = 0; ; attempt++) {\n try {\n return push()\n } catch (error) {\n const message = errorMessage(error)\n if (/(?:HTTP |error: )(?:429|503)\\b/i.test(message) && attempt < backoffMs.length) {\n await new Promise((resolve) => setTimeout(resolve, backoffMs[attempt]))\n continue\n }\n throw error\n }\n }\n}\n\nexport function shouldSendLineage(commitOid: string | null, recoverable: boolean): boolean {\n return commitOid !== null && recoverable\n}\n\nexport function workspaceDeployLineage(\n status: RemoteWorkspace['status'],\n publishedTip: string | null,\n localTip: string,\n): 'recoverable' | 'inactive' | 'unsynced' {\n if (status !== 'active') return 'inactive'\n return publishedTip === localTip ? 'recoverable' : 'unsynced'\n}\n\nexport function dirtyWorktreeRefusal(branch: string | null): {\n code: 'dirty_worktree'\n error: string\n} {\n const workspaceId = workspaceIdFromBranch(branch)\n return {\n code: 'dirty_worktree',\n error:\n 'The worktree has uncommitted changes, and a deploy records the commit it ships. ' +\n (workspaceId\n ? `Commit them to this workspace branch (${branch}) — WIP commits are fine — then redeploy. `\n : 'Commit them (to a workspace branch if this is work in progress: `deepspace workspace new -t \"…\"`), then redeploy. ') +\n 'Or pass --no-push to deploy without version-control sync — the release then records no source lineage.',\n }\n}\n","import { appendFileSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { InputError } from '../cli-errors'\nimport { gitLine, gitMeetsFloor, parseGitVersion, runGit, splitNulFields } from './process'\n\n/** Conservative client-side approximation of `git check-ref-format --branch`. */\nexport function isPlausibleBranchName(name: string): boolean {\n if (!name || name === 'HEAD' || name === '@') return false\n if (name.startsWith('/') || name.startsWith('-') || name.startsWith('.')) return false\n if (name.endsWith('/') || name.endsWith('.') || name.endsWith('.lock')) return false\n if (name.includes('/.') || name.includes('.lock/')) return false\n // eslint-disable-next-line no-control-regex\n return !/(\\.\\.|\\/\\/|@\\{|[\\x00-\\x20\\x7f~^:?*[\\\\])/.test(name)\n}\n\n/** Require a full, SHA-1 Git repository supported by the cloud repo protocol. */\nexport function assertSyncableRepo(cwd: string): void {\n const inside = runGit(cwd, ['rev-parse', '--is-inside-work-tree'], { allowFail: true })\n if (inside.status !== 0 || inside.stdout.toString().trim() !== 'true') {\n throw new InputError(\n `${cwd} is not a git repository. DeepSpace apps are scaffolded as git repos — run \\`git init\\` first.`,\n 'not_git_repo',\n )\n }\n\n const versionOutput = runGit(cwd, ['--version'], { allowFail: true })\n .stdout.toString('utf-8')\n .trim()\n if (!gitMeetsFloor(parseGitVersion(versionOutput))) {\n throw gitTooOld(versionOutput)\n }\n\n const formatResult = runGit(cwd, ['rev-parse', '--show-object-format'], { allowFail: true })\n const format = formatResult.stdout.toString('utf-8').trim()\n if (formatResult.status !== 0 || format.startsWith('--')) throw gitTooOld(versionOutput)\n if (format !== 'sha1') {\n throw new InputError(\n `This repo uses object format \"${format}\" — DeepSpace version control supports sha1 repos only (git's default) for now.`,\n 'unsupported_object_format',\n )\n }\n if (gitLine(cwd, ['rev-parse', '--is-shallow-repository']) === 'true') {\n throw new InputError(\n 'This is a shallow clone. Run `git fetch --unshallow` before pushing to DeepSpace.',\n 'shallow_repo',\n )\n }\n}\n\nfunction gitTooOld(versionOutput: string): InputError {\n return new InputError(\n `DeepSpace version control needs git ≥ 2.29 — found ${versionOutput || 'an unknown git version'}. Upgrade git and retry.`,\n 'git_too_old',\n )\n}\n\n/** The repository's top-level worktree directory. */\nexport function repoToplevel(cwd: string): string {\n return gitLine(cwd, ['rev-parse', '--show-toplevel'])\n}\n\n/** Current branch short name, or null when HEAD is detached. */\nexport function currentBranch(cwd: string): string | null {\n const result = runGit(cwd, ['symbolic-ref', '--short', '-q', 'HEAD'], { allowFail: true })\n const name = result.stdout.toString('utf-8').trim()\n return result.status === 0 && name ? name : null\n}\n\n/** Resolve a ref or oid to a commit oid. */\nexport function resolveCommit(cwd: string, ref: string): string | null {\n const result = runGit(cwd, ['rev-parse', '-q', '--verify', `${ref}^{commit}`], {\n allowFail: true,\n })\n const oid = result.stdout.toString('utf-8').trim()\n return result.status === 0 && /^[0-9a-f]{40}$/.test(oid) ? oid : null\n}\n\nexport function isWorkTreeClean(cwd: string): boolean {\n return gitLine(cwd, ['status', '--porcelain']) === ''\n}\n\nexport function updateRef(cwd: string, ref: string, oid: string): void {\n runGit(cwd, ['update-ref', ref, oid])\n}\n\nexport function isAncestor(cwd: string, ancestor: string, descendant: string): boolean {\n return (\n runGit(cwd, ['merge-base', '--is-ancestor', ancestor, descendant], { allowFail: true })\n .status === 0\n )\n}\n\nexport function mergeBase(cwd: string, left: string, right: string): string | null {\n const result = runGit(cwd, ['merge-base', left, right], { allowFail: true })\n if (result.status !== 0) return null\n const oid = result.stdout.toString('utf-8').trim()\n return /^[0-9a-f]{40}$/.test(oid) ? oid : null\n}\n\nexport function fastForwardCurrentBranch(cwd: string, oid: string): void {\n runGit(cwd, ['merge', '--ff-only', oid])\n}\n\nexport function initRepo(dir: string, branch: string): void {\n runGit(dir, ['init', '--quiet', '-b', branch])\n}\n\nexport function checkoutHead(cwd: string): void {\n runGit(cwd, ['reset', '--hard', '--quiet'])\n}\n\nexport function switchToNewBranch(cwd: string, name: string, oid: string): void {\n runGit(cwd, ['switch', '--quiet', '-c', name, oid])\n}\n\n/** Changed paths between commits, with rename detection disabled so both sides remain visible. */\nexport function diffNameOnly(cwd: string, base: string, head: string): string[] {\n return splitNulFields(\n runGit(cwd, [\n '-c',\n 'core.quotePath=false',\n 'diff',\n '--name-only',\n '--no-renames',\n '-z',\n base,\n head,\n ]).stdout,\n )\n}\n\nexport function revListCount(cwd: string, exclude: string, include: string): number {\n const count = Number(gitLine(cwd, ['rev-list', '--count', `${exclude}..${include}`]))\n return Number.isFinite(count) ? count : 0\n}\n\nexport function addWorktreeNewBranch(cwd: string, dir: string, branch: string, oid: string): void {\n runGit(cwd, ['worktree', 'add', '--quiet', '-b', branch, dir, oid])\n}\n\nexport interface GitWorktree {\n path: string\n branch: string | null\n}\n\nexport function listWorktrees(cwd: string): GitWorktree[] {\n const result = runGit(cwd, ['worktree', 'list', '--porcelain'], { allowFail: true })\n if (result.status !== 0) return []\n const worktrees: GitWorktree[] = []\n let current: GitWorktree | null = null\n for (const line of result.stdout.toString('utf-8').split('\\n')) {\n if (line.startsWith('worktree ')) {\n current = { path: line.slice('worktree '.length), branch: null }\n worktrees.push(current)\n } else if (line.startsWith('branch ') && current) {\n const ref = line.slice('branch '.length)\n current.branch = ref.startsWith('refs/heads/') ? ref.slice('refs/heads/'.length) : ref\n }\n }\n return worktrees\n}\n\n/** Add a pattern to the repository's shared, local-only info/exclude file. */\nexport function ensureLocalExclude(cwd: string, pattern: string): void {\n const commonDir = resolve(cwd, gitLine(cwd, ['rev-parse', '--git-common-dir']))\n const excludePath = join(commonDir, 'info', 'exclude')\n let current = ''\n try {\n current = readFileSync(excludePath, 'utf-8')\n } catch {\n // The append below creates an absent file.\n }\n if (current.split('\\n').some((line) => line.trim() === pattern)) return\n try {\n mkdirSync(dirname(excludePath), { recursive: true })\n appendFileSync(\n excludePath,\n `${current.endsWith('\\n') || current === '' ? '' : '\\n'}${pattern}\\n`,\n )\n } catch {\n // Best-effort: a failed exclude makes status noisy but does not break the worktree.\n }\n}\n","import { sync as spawnSync } from 'cross-spawn'\n\nconst MAX_GIT_BUFFER = 512 * 1024 * 1024\n\nexport class GitError extends Error {\n constructor(\n message: string,\n /** Optional machine slug; generic Git errors fall back to `git_error`. */\n readonly code?: string,\n ) {\n super(message)\n this.name = 'GitError'\n }\n}\n\n/** Execute git without terminal prompts, localized output, or shell interpolation. */\nexport function runGit(\n cwd: string,\n args: string[],\n opts: { input?: string | Buffer; allowFail?: boolean; env?: Record<string, string> } = {},\n): { stdout: Buffer; stderr: Buffer; status: number } {\n const result = spawnSync('git', args, {\n cwd,\n input: opts.input,\n maxBuffer: MAX_GIT_BUFFER,\n stdio: ['pipe', 'pipe', 'pipe'],\n env: {\n ...process.env,\n GIT_TERMINAL_PROMPT: '0',\n LC_ALL: 'C',\n ...(opts.env ?? {}),\n },\n })\n if (result.error) {\n const code = (result.error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new GitError(\n 'git is not installed or not on PATH — install git and retry.',\n 'git_not_installed',\n )\n }\n throw new GitError(`git ${args[0]} failed: ${result.error.message}`)\n }\n const status = result.status ?? 1\n if (status !== 0 && !opts.allowFail) {\n const stderr = result.stderr?.toString('utf-8').trim() ?? ''\n throw new GitError(`git ${args.join(' ')} exited ${status}${stderr ? `: ${stderr}` : ''}`)\n }\n return {\n stdout: result.stdout ?? Buffer.alloc(0),\n stderr: result.stderr ?? Buffer.alloc(0),\n status,\n }\n}\n\nexport function gitLine(cwd: string, args: string[]): string {\n return runGit(cwd, args).stdout.toString('utf-8').trim()\n}\n\n/** Decode a NUL-delimited git result without corrupting control characters in paths. */\nexport function splitNulFields(buffer: Buffer): string[] {\n const fields: string[] = []\n let start = 0\n for (let index = 0; index < buffer.length; index++) {\n if (buffer[index] === 0) {\n fields.push(buffer.toString('utf-8', start, index))\n start = index + 1\n }\n }\n if (start < buffer.length) fields.push(buffer.toString('utf-8', start))\n return fields\n}\n\n/** Parse `git --version` into the major/minor pair used by the compatibility floor. */\nexport function parseGitVersion(output: string): [number, number] | null {\n const match = /(\\d+)\\.(\\d+)/.exec(output)\n return match ? [Number(match[1]), Number(match[2])] : null\n}\n\n/** Git 2.29 is the minimum version that exposes the required object-format probe. */\nexport function gitMeetsFloor(version: [number, number] | null): boolean {\n if (!version) return true\n const [major, minor] = version\n return major > 2 || (major === 2 && minor >= 29)\n}\n","import { shQuote } from '../cli-format'\nimport { runGit, splitNulFields } from './process'\nimport { repoToplevel } from './repository'\n\nconst SECRET_FILE_RE = /(^|\\/)(\\.dev\\.vars(\\.[^/]*)?|\\.env(\\.[^/]*)?|\\.npmrc|\\.envrc|\\.mcp\\.json)$/i\nconst SECRET_TEMPLATE_RE = /\\.(example|sample|template)$/i\n\n/** Best-effort oversized-blob diagnostics for a rejected push. */\nexport function findOversizedObjects(\n cwd: string,\n capBytes: number,\n limit = 3,\n): { path: string; bytes: number }[] {\n try {\n const revisionObjects = runGit(cwd, ['rev-list', '--objects', '--all'], { allowFail: true })\n if (revisionObjects.status !== 0) return []\n const pathByOid = new Map<string, string>()\n for (const line of revisionObjects.stdout.toString('utf-8').split('\\n')) {\n const separator = line.indexOf(' ')\n if (separator > 0) pathByOid.set(line.slice(0, separator), line.slice(separator + 1))\n }\n\n const sizedObjects = runGit(\n cwd,\n [\n 'cat-file',\n '--batch-all-objects',\n '--batch-check=%(objectname) %(objecttype) %(objectsize)',\n ],\n { allowFail: true },\n )\n if (sizedObjects.status !== 0) return []\n const oversized: { path: string; bytes: number }[] = []\n for (const line of sizedObjects.stdout.toString('utf-8').split('\\n')) {\n const [oid, type, size] = line.split(' ')\n if (type !== 'blob') continue\n const bytes = Number(size)\n const path = pathByOid.get(oid)\n if (path && Number.isFinite(bytes) && bytes > capBytes) oversized.push({ path, bytes })\n }\n return oversized.sort((left, right) => right.bytes - left.bytes).slice(0, limit)\n } catch {\n return []\n }\n}\n\n/** Dirty paths safe to expose in logs; local secret filenames are redacted. */\nexport function statusFiles(cwd: string): string[] {\n const records = splitNulFields(\n runGit(cwd, [\n '-c',\n 'core.quotePath=false',\n 'status',\n '--porcelain',\n '--untracked-files=all',\n '-z',\n ]).stdout,\n )\n const files: string[] = []\n for (let index = 0; index < records.length; index++) {\n const record = records[index]\n files.push(record.slice(3))\n if (/[RC]/.test(record.slice(0, 2))) {\n index++\n if (/R/.test(record.slice(0, 2)) && index < records.length) files.push(records[index])\n }\n }\n return [\n ...new Set(\n files.filter((path) => !(SECRET_FILE_RE.test(path) && !SECRET_TEMPLATE_RE.test(path))),\n ),\n ]\n}\n\n/** Secret-bearing files in a committed tree, scanned from the repository root. */\nexport function trackedSecretFiles(cwd: string, ref: string): string[] {\n const result = runGit(\n repoToplevel(cwd),\n ['-c', 'core.quotePath=false', 'ls-tree', '-r', '--name-only', '-z', ref],\n { allowFail: true },\n )\n if (result.status !== 0) return []\n return splitNulFields(result.stdout).filter(\n (path) => SECRET_FILE_RE.test(path) && !SECRET_TEMPLATE_RE.test(path),\n )\n}\n\nexport const SECRET_IN_HISTORY_CODE = 'secret_in_history'\n\nexport function committedSecretRefusal(\n cwd: string,\n commitOid: string | null,\n options: { action: string; then: string },\n): { files: string[]; message: string; code: string } | null {\n if (!commitOid) return null\n const files = trackedSecretFiles(cwd, commitOid)\n if (files.length === 0) return null\n return {\n files,\n code: SECRET_IN_HISTORY_CODE,\n message:\n `Refusing to ${options.action}: the commit being published carries secret file(s) — ` +\n `${files.join(', ')}. These hold local secrets and must not reach the cloud repo, ` +\n `but pushing this commit would upload them through its history. ` +\n `Untrack with \\`git rm --cached ${shQuote(files[0])}\\`, ensure it's .gitignored, commit, ` +\n `then ${options.then}.`,\n }\n}\n","/**\n * Typed client for the deploy-worker's /api/repo JSON surface — the DeepSpace\n * layer on top of the git remote: refs for scripting, workspaces, the activity\n * feed, and the release history. Object transfer itself never goes through\n * here; that's real git against the smart-HTTP endpoint (lib/vc-remote.ts).\n *\n * Idempotency: `createWorkspace` carries a client-minted key, so a retried\n * create replays the recorded outcome instead of double-writing. sync, land\n * and drop are idempotent by CONSTRUCTION instead — each is a state\n * transition whose replay is a no-op (same tip, already-landed, already-\n * dropped all return the current view) — so they send no key.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { apiFetch, ApiError } from './api'\n\nexport interface RemoteRef {\n name: string\n oid: string\n updatedAt: string\n updatedBy: string\n}\n\nexport interface RemoteRefsResult {\n refs: RemoteRef[]\n head: string | null\n}\n\nexport interface RemoteRelease {\n id: string\n seq: number\n commitOid: string | null\n cfVersionId: string | null\n rollbackAvailable: boolean\n config: unknown\n actor: string\n url: string | null\n kind: 'deploy' | 'rollback'\n createdAt: string\n}\n\nexport interface RemoteWorkspace {\n id: string\n task: string\n baseOid: string\n ref: string\n status: 'active' | 'landed' | 'dropped'\n createdBy: string\n createdAt: string\n updatedAt: string\n landedOid: string | null\n}\n\nexport interface RemoteCommitCount {\n count: number\n capped: boolean\n}\n\n/** Commit-graph facts the repo DO owns. Path-level coordination (which other\n * workspaces touch the same files) is computed client-side from local diffs —\n * see `workspace.ts`. */\nexport interface RemoteWorkspaceView {\n workspace: RemoteWorkspace\n tipOid: string | null\n aheadOfBase: RemoteCommitCount | null\n behindTrunk: RemoteCommitCount | null\n}\n\nexport interface RemoteActivityEvent {\n seq: number\n kind: string\n subjectId: string | null\n summary: unknown\n actor: string\n createdAt: string\n}\n\nexport function mintIdempotencyKey(): string {\n return randomUUID()\n}\n\n/**\n * Resolve a live subdomain name to its app id via the deploy worker's\n * access-gated resolver (`GET /api/repo/resolve-name/:name`). Unlike the\n * owner-only `/api/apps` list, this also finds apps the caller merely\n * COLLABORATES on. Returns null when the name is unknown, malformed, or the\n * caller has no access — the server deliberately doesn't distinguish the\n * first from the last (no existence oracle).\n */\nexport async function resolveAppIdByName(\n deployUrl: string,\n token: string,\n name: string,\n): Promise<string | null> {\n try {\n const { appId } = await apiFetch<{ appId: string }>(\n deployUrl,\n token,\n `/api/repo/resolve-name/${encodeURIComponent(name)}`,\n )\n return appId ?? null\n } catch (err) {\n if (err instanceof ApiError && (err.status === 404 || err.status === 400)) return null\n throw err\n }\n}\n\nexport function repoApi(deployUrl: string, token: string, appId: string) {\n const base = `/api/repo/${encodeURIComponent(appId)}`\n const call = async <T>(path: string, init?: RequestInit): Promise<T> => {\n // The bare-404 \"wrong/old service\" case (→ unrecognized_service) is handled\n // uniformly in apiFetch now, for every caller incl. rollback's direct endpoint.\n return await apiFetch<T>(deployUrl, token, `${base}${path}`, init)\n }\n const post = <T>(path: string, body: unknown) =>\n call<T>(path, { method: 'POST', body: JSON.stringify(body) })\n\n // A well-formed repo-API 2xx body carries the endpoint's documented fields with\n // the right shape. A wrong/broken service can answer 200 with `{}` (or an empty\n // body, which apiFetch reads as `{}`), a null-valued field, or the wrong type;\n // left unchecked those destructure to `undefined`/`null` downstream and surface\n // as a false `ok:true` or an uncoded `reading '…' of null|undefined` crash. Code\n // such a body as invalid_response — the same slug apiFetch uses for a\n // null/array/non-JSON 2xx. This enforces every SCHEMA-FREE degeneracy check —\n // present, correct JSON type, non-null, arrays carry no null entries, objects\n // are non-empty — and stops exactly where a check would need the per-endpoint\n // field schema (a populated-but-wrong-fielded entity like `{view:{wrong:1}}` or\n // `[{}]` is left to the caller's TS types + happy-path tests, NOT re-validated\n // here). Kinds: `array` (a list, never null, no null entries), `object` (a\n // non-empty, non-null, non-array object — a real entity is never `{}`, and no\n // top-level field is a legitimately-empty map; do NOT tag such a field `object`\n // if one is ever added), `present` (key exists; value may be null — e.g. a\n // nullable ref like getRefs' `head`).\n const KIND = {\n array: (v: unknown) => Array.isArray(v) && v.every((e) => e !== null),\n object: (v: unknown) =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length > 0,\n present: (v: unknown) => v !== undefined,\n }\n type Kind = keyof typeof KIND\n const shapeError = (path: string) =>\n new ApiError(\n `The deploy service at ${deployUrl} returned an unexpected response shape — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n 200,\n 'invalid_response',\n `${base}${path}`,\n )\n // Each `spec` key must name a documented top-level field of the response (a\n // typo'd key rejects every valid 2xx as invalid_response — fail-loud, caught by\n // the per-endpoint happy-path tests). Keys stay strings (not `keyof T`) so T\n // still infers from each method's return annotation rather than from the spec.\n const assertShape = <T>(r: T, spec: Record<string, Kind>, path: string): T => {\n if (r === null || typeof r !== 'object') throw shapeError(path)\n const obj = r as Record<string, unknown>\n for (const [key, kind] of Object.entries(spec)) {\n if (!KIND[kind](obj[key])) throw shapeError(path)\n }\n return r\n }\n const getShape = async <T>(path: string, spec: Record<string, Kind>): Promise<T> =>\n assertShape(await call<T>(path), spec, path)\n const postShape = async <T>(\n path: string,\n body: unknown,\n spec: Record<string, Kind>,\n ): Promise<T> => assertShape(await post<T>(path, body), spec, path)\n\n return {\n /** null ⇒ the app has never been registered (fresh repo, no history). */\n async getRefs(): Promise<RemoteRefsResult | null> {\n try {\n return await getShape<RemoteRefsResult>('/refs', { refs: 'array', head: 'present' })\n } catch (err) {\n if (err instanceof ApiError && err.code === 'app_not_found') return null\n throw err\n }\n },\n\n createWorkspace(args: {\n workspaceId: string\n task: string\n baseOid: string\n idempotencyKey: string\n }): Promise<{ view: RemoteWorkspaceView }> {\n return postShape('/workspaces', args, { view: 'object' })\n },\n\n listWorkspaces(opts?: {\n all?: boolean\n limit?: number\n }): Promise<{ views: RemoteWorkspaceView[] }> {\n const params = new URLSearchParams()\n if (opts?.all) params.set('all', '1')\n if (opts?.limit) params.set('limit', String(opts.limit))\n const qs = params.toString()\n return getShape(`/workspaces${qs ? `?${qs}` : ''}`, { views: 'array' })\n },\n\n getWorkspace(id: string): Promise<{ view: RemoteWorkspaceView }> {\n return getShape(`/workspaces/${encodeURIComponent(id)}`, { view: 'object' })\n },\n\n syncWorkspace(id: string, args: { headOid: string }): Promise<{ view: RemoteWorkspaceView }> {\n return postShape(`/workspaces/${encodeURIComponent(id)}/sync`, args, { view: 'object' })\n },\n\n landWorkspace(\n id: string,\n args: { landedOid: string; intoRef?: string },\n ): Promise<{ view: RemoteWorkspaceView }> {\n return postShape(`/workspaces/${encodeURIComponent(id)}/land`, args, { view: 'object' })\n },\n\n dropWorkspace(id: string): Promise<{ view: RemoteWorkspaceView }> {\n return postShape(`/workspaces/${encodeURIComponent(id)}/drop`, {}, { view: 'object' })\n },\n\n listActivity(opts?: {\n since?: number\n limit?: number\n tail?: boolean\n }): Promise<{ events: RemoteActivityEvent[]; cursor: number; hasMore: boolean }> {\n const params = new URLSearchParams()\n if (opts?.since) params.set('since', String(opts.since))\n if (opts?.limit) params.set('limit', String(opts.limit))\n if (opts?.tail) params.set('tail', '1')\n const qs = params.toString()\n return getShape(`/activity${qs ? `?${qs}` : ''}`, {\n events: 'array',\n cursor: 'present',\n hasMore: 'present',\n })\n },\n\n listReleases(limit?: number): Promise<{ releases: RemoteRelease[] }> {\n return getShape(`/releases${limit ? `?limit=${limit}` : ''}`, { releases: 'array' })\n },\n\n latestRelease(): Promise<{ release: RemoteRelease | null }> {\n // `release` is nullable (no releases yet) — presence-only, not `object`.\n return getShape('/releases/latest', { release: 'present' })\n },\n\n getRelease(id: string): Promise<{ release: RemoteRelease }> {\n return getShape(`/releases/${encodeURIComponent(id)}`, { release: 'object' })\n },\n }\n}\n\nexport type RepoApi = ReturnType<typeof repoApi>\n","/**\n * Remote URL, bearer auth, and credential-helper setup for the `space` remote.\n * The transfer itself is real Git; push protocol parsing lives in `vc-push.ts`.\n */\n\nimport { existsSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, relative, resolve } from 'node:path'\nimport { PLATFORM_URLS } from '../env'\nimport { shQuote } from './cli-format'\nimport { runGit } from './git/process'\n\n/** The remote name the platform repo lives under in every synced clone. */\nexport const SPACE_REMOTE = 'space'\n\n/** The deploy worker base URL, honoring the per-command override convention. */\nexport function deployBaseUrl(): string {\n return process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n}\n\n/** The app's smart-HTTP remote URL — clonable/pushable by real Git. */\nexport function repoUrl(appId: string, base: string = deployBaseUrl()): string {\n return `${base.replace(/\\/+$/, '')}/api/repo/${encodeURIComponent(appId)}`\n}\n\n/**\n * Auth env for CLI-driven Git invocations. The bearer header is scoped to the\n * platform base URL and travels only in the child environment, never argv or\n * disk. Existing `GIT_CONFIG_*` entries are preserved.\n */\nexport function gitAuthEnv(token: string, base: string = deployBaseUrl()): Record<string, string> {\n const existing = Number(process.env.GIT_CONFIG_COUNT ?? '0')\n const index = Number.isInteger(existing) && existing > 0 ? existing : 0\n return {\n GIT_CONFIG_COUNT: String(index + 1),\n [`GIT_CONFIG_KEY_${index}`]: `http.${base.replace(/\\/+$/, '')}.extraHeader`,\n [`GIT_CONFIG_VALUE_${index}`]: `Authorization: Bearer ${token}`,\n }\n}\n\n/** Run Git with bearer-auth configuration injected via its environment. */\nexport function runGitRemote(\n cwd: string,\n token: string,\n args: string[],\n opts: { input?: string | Buffer; allowFail?: boolean; env?: Record<string, string> } = {},\n): { stdout: Buffer; stderr: Buffer; status: number } {\n return runGit(cwd, args, { ...opts, env: { ...gitAuthEnv(token), ...(opts.env ?? {}) } })\n}\n\n/**\n * Whether the running CLI entry is ephemeral. A credential helper pinned into\n * global Git config must not point at an npm cache or app-local install that\n * can disappear.\n */\nfunction entryIsTransient(cwd: string): boolean {\n const entry = process.argv[1]\n if (!entry) return true\n if (/[\\\\/]_npx[\\\\/]/.test(entry) || entry.startsWith(tmpdir())) return true\n const rel = relative(resolve(cwd), resolve(entry))\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))\n}\n\n/** Does an existing pinned helper entry still point at usable files? */\nfunction helperEntryUsable(command: string): boolean {\n // Quoted paths containing a single quote deliberately fall through to false;\n // re-aiming that rare form is simpler and safer than partially parsing shell.\n const match = /^!'([^']*)' '([^']*)' git-credential$/.exec(command)\n return match !== null && existsSync(match[1]) && existsSync(match[2])\n}\n\n/**\n * Pin the exact node binary and CLI entry, avoiding PATH and stale global CLI\n * shadowing. `shQuote` neutralizes every shell metacharacter in those paths.\n */\nexport function credentialHelperCommand(): string {\n const entry = process.argv[1]\n if (!entry) throw new Error('CLI entry path is unavailable')\n return `!${shQuote(process.execPath)} ${shQuote(entry)} git-credential`\n}\n\n/**\n * Best-effort host-scoped credential-helper installation. Wrapped commands\n * inject auth themselves; this setup exists so plain `git push space` and\n * `git clone <app-url>` work afterward.\n */\nfunction installCredentialHelper(cwd: string, url: string): void {\n try {\n const origin = new URL(url)\n const key = `credential.${origin.protocol}//${origin.host}.helper`\n const helper = credentialHelperCommand()\n // The empty first value resets inherited helpers. Otherwise Git's approve\n // step could persist the short-lived DeepSpace bearer in an OS keychain.\n const wanted = ['', helper]\n const scope = entryIsTransient(cwd) ? '--local' : '--global'\n const current = runGit(cwd, ['config', scope, '--get-all', key], { allowFail: true })\n if (current.status === 0) {\n const existing = current.stdout\n .toString('utf-8')\n .split('\\n')\n .filter((_, index, lines) => index < lines.length - 1)\n if (existing.length === wanted.length && existing.every((value, i) => value === wanted[i])) {\n return\n }\n // Leave another usable checkout's helper alone so parallel checkouts do\n // not ping-pong global config. Rewrite only malformed or stale entries.\n if (\n existing.length === wanted.length &&\n existing[0] === '' &&\n helperEntryUsable(existing[1])\n ) {\n return\n }\n runGit(cwd, ['config', scope, '--unset-all', key], { allowFail: true })\n }\n runGit(cwd, ['config', scope, '--add', key, ''])\n runGit(cwd, ['config', scope, '--add', key, helper])\n if (scope === '--global' && !process.argv.includes('--json')) {\n process.stderr.write(\n `note: added a git credential helper for ${origin.host} to your global git config so ` +\n `plain \\`git clone\\`/\\`git push\\` to DeepSpace authenticate. ` +\n `Undo with: git config --global --unset-all ${key}\\n`,\n )\n }\n } catch {\n // Best effort: wrapped transfers remain authenticated without the helper.\n }\n}\n\n/** Point `space` at this app and install the host-scoped credential helper. */\nexport function ensureSpaceRemote(cwd: string, appId: string): string {\n const url = repoUrl(appId)\n const current = runGit(cwd, ['remote', 'get-url', SPACE_REMOTE], { allowFail: true })\n if (current.status !== 0) {\n runGit(cwd, ['remote', 'add', SPACE_REMOTE, url])\n } else {\n const existing = current.stdout.toString('utf-8').trim()\n if (existing !== url) {\n const priorApp = appIdFromRepoUrl(existing)\n if (priorApp && priorApp !== appId && !process.argv.includes('--json')) {\n process.stderr.write(\n `warning: remote '${SPACE_REMOTE}' was pointed at app ${priorApp}; re-aiming it at ${appId}.\\n`,\n )\n }\n runGit(cwd, ['remote', 'set-url', SPACE_REMOTE, url])\n }\n }\n installCredentialHelper(cwd, url)\n return url\n}\n\n/** Extract the app id from a DeepSpace repository URL. */\nfunction appIdFromRepoUrl(url: string): string | null {\n const match = /\\/api\\/repo\\/([^/]+)\\/?$/.exec(url)\n return match ? decodeURIComponent(match[1]) : null\n}\n","/**\n * Git push protocol for the `space` remote: porcelain parsing, retryable\n * transport classification, and actionable rejection messages. Remote URL,\n * credential-helper, and auth configuration remain in `vc-remote.ts`.\n */\n\nimport { shQuote } from './cli-format'\nimport { GitError } from './git/process'\nimport { findOversizedObjects } from './git/safety'\nimport { runGitRemote, SPACE_REMOTE } from './vc-remote'\n\nexport type PushRefStatus =\n | 'committed'\n | 'up_to_date'\n | 'non_fast_forward'\n | 'ref_conflict'\n | 'rejected'\n\n/**\n * The exact `ng` reasons emitted when the server's ref CAS loses a race. Other\n * server rejections are policy/data failures; `deepspace pull` cannot fix them.\n */\nconst CAS_CONFLICT_REASON = /stale ref|fetch first|no such ref|atomic push failed/i\n\nexport interface PushRefResult {\n status: PushRefStatus\n localRef: string\n remoteRef: string\n /** Raw summary column from `git push --porcelain`. */\n summary: string\n /** Parenthesized server/client rejection reason. */\n reason?: string\n}\n\n/** Parse `git push --porcelain` into one result per ref. */\nexport function parsePushPorcelain(out: string): PushRefResult[] {\n const results: PushRefResult[] = []\n for (const line of out.split('\\n')) {\n const match = /^([ +\\-*=!])\\t([^\\t]*)\\t(.*)$/.exec(line)\n if (!match) continue\n const [, flag, refspec, summary] = match\n const colon = refspec.indexOf(':')\n const localRef = colon >= 0 ? refspec.slice(0, colon) : refspec\n const remoteRef = colon >= 0 ? refspec.slice(colon + 1) : refspec\n let status: PushRefStatus\n let reason: string | undefined\n if (flag === '=') {\n status = 'up_to_date'\n } else if (flag === '!') {\n reason = /\\((.*)\\)\\s*$/.exec(summary)?.[1]\n if (!summary.startsWith('[remote rejected]')) {\n status = 'non_fast_forward'\n } else if (reason && CAS_CONFLICT_REASON.test(reason)) {\n status = 'ref_conflict'\n } else {\n status = 'rejected'\n }\n } else {\n status = 'committed'\n }\n results.push({ status, localRef, remoteRef, summary, ...(reason ? { reason } : {}) })\n }\n return results\n}\n\n/** The server explicitly asks for a full-pack retry on this one rejection. */\nexport function isThinPackRejection(result: PushRefResult): boolean {\n return (\n result.status === 'rejected' &&\n /thin (?:push|pack)|--no-thin/i.test(result.reason ?? result.summary ?? '')\n )\n}\n\n/** Whether pull is the one deterministic recovery for a failed push. */\nexport function isRecoverablePushFailure(status: PushRefStatus): boolean {\n return status === 'non_fast_forward' || status === 'ref_conflict'\n}\n\nexport interface PushTransportFailure {\n code: 'app_quota_exceeded' | 'rate_limited'\n error: string\n}\n\n/** Classify HTTP failures whose bodies Git's smart-HTTP transport discards. */\nexport function classifyPushTransportFailure(error: unknown): PushTransportFailure | null {\n const message = error instanceof Error ? error.message : String(error)\n // Match only HTTP-status contexts: `Total 429 (delta 3)` is valid git output.\n if (/(?:HTTP |error: )409\\b/i.test(message)) {\n return {\n code: 'app_quota_exceeded',\n error:\n `A first push to this new app hit your plan's active-app quota. ` +\n `Use \\`deepspace app list\\` to choose an app to undeploy, or upgrade your plan, then retry.`,\n }\n }\n if (/(?:HTTP |error: )429\\b/i.test(message)) {\n return {\n code: 'rate_limited',\n error: 'The cloud repo rate-limited this push. Wait a few seconds, then retry.',\n }\n }\n return null\n}\n\n/** Push one refspec and return Git's porcelain result. */\nexport function pushToSpace(\n cwd: string,\n token: string,\n refspec: string,\n opts: { force?: boolean } = {},\n): PushRefResult {\n const doPush = (extra: string[]): PushRefResult => {\n const result = runGitRemote(\n cwd,\n token,\n ['push', '--porcelain', ...(opts.force ? ['--force'] : []), ...extra, SPACE_REMOTE, refspec],\n { allowFail: true },\n )\n const parsed = parsePushPorcelain(result.stdout.toString('utf-8'))\n if (parsed.length === 0) {\n const stderr = result.stderr.toString('utf-8').trim()\n throw new GitError(\n stderr || `git push exited ${result.status} without reporting a ref status`,\n )\n }\n return parsed[0]\n }\n const first = doPush([])\n return isThinPackRejection(first) ? doPush(['--no-thin']) : first\n}\n\n/** Matches the server's oversized-object rejection text. */\nexport const OVERSIZED_PUSH_RE = /too large|exceeds|\\bLFS\\b/i\n\n/** Mirrors deploy-worker's per-object cap; the server remains the enforcer. */\nconst SERVER_OBJECT_CAP_BYTES = 20 * 1024 * 1024\n\nexport const OVERSIZED_PUSH_FIX =\n `Find the offending object with ` +\n `\\`git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectsize) %(rest)' | sort -k2 -n | tail\\`, ` +\n `then .gitignore it (or move it to Git LFS) and re-commit.`\n\nfunction formatBytes(bytes: number): string {\n if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`\n if (bytes >= 1024) return `${Math.round(bytes / 1024)} KiB`\n return `${bytes} B`\n}\n\n/** Name over-cap objects when possible so the correction is mechanical. */\nexport function oversizedPushFix(cwd?: string, cap: number = SERVER_OBJECT_CAP_BYTES): string {\n const objects = cwd ? findOversizedObjects(cwd, cap) : []\n if (objects.length === 0) return OVERSIZED_PUSH_FIX\n const one = objects.length === 1\n const named = objects.map((object) => `${object.path} (${formatBytes(object.bytes)})`).join(', ')\n return (\n `The oversized ${one ? 'file is' : 'files are'} ${named}. ` +\n `Remove ${one ? 'it' : 'them'} from history (\\`git rm --cached ${one ? shQuote(objects[0].path) : '<path>'}\\`, ` +\n `add to .gitignore, re-commit) or track ${one ? 'it' : 'them'} with Git LFS.`\n )\n}\n\n/**\n * Render a non-divergence push rejection. Only the server's explicit\n * retry-the-push race is classified transient; unknown and policy rejections\n * fail closed so agents do not loop on a permanent refusal.\n */\nexport function pushFailureMessage(label: string, push: PushRefResult, cwd?: string): string {\n const reason = push.reason ?? push.summary ?? ''\n const detail = `${push.status}${reason ? `: ${reason}` : ''}`\n if (OVERSIZED_PUSH_RE.test(reason)) {\n return `${label} failed (${detail}) — an object exceeds the server's size cap, so retrying cannot succeed. ${oversizedPushFix(cwd)}`\n }\n if (/^missing necessary objects — retry the push$/i.test(reason)) {\n return `${label} failed (${detail}). Retry; if it persists, report it with \\`deepspace feedback\\`.`\n }\n return (\n `${label} failed (${detail}). The server rejected this push; correct the reported ` +\n `history/ref problem, or report it with \\`deepspace feedback\\` if the reason is unclear.`\n )\n}\n","/**\n * Workspace naming — the deterministic mapping between a server workspace id\n * (`ws_<26-char Crockford ULID>`) and its local git branch (`ws/<ulid,\n * lowercased>`). Deterministic both ways so `workspace sync`/`land`/`status`\n * can infer which workspace a worktree belongs to from nothing but the\n * checked-out branch, on any machine.\n */\n\nconst ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/i\nconst WORKSPACE_ID_RE = /^ws_[0-9A-HJKMNP-TV-Z]{26}$/\n\nexport function isWorkspaceId(id: string): boolean {\n return WORKSPACE_ID_RE.test(id)\n}\n\nexport function workspaceBranchName(workspaceId: string): string {\n return `ws/${workspaceId.replace(/^ws_/, '').toLowerCase()}`\n}\n\n/** `ws/<ulid>` → `ws_<ULID>`, or null when the branch isn't workspace-shaped. */\nexport function workspaceIdFromBranch(branch: string | null): string | null {\n if (!branch || !branch.startsWith('ws/')) return null\n const ulid = branch.slice(3)\n if (!ULID_RE.test(ulid)) return null\n return `ws_${ulid.toUpperCase()}`\n}\n\nexport function isSelectedWorkspaceCheckout(branch: string | null, workspaceId: string): boolean {\n return workspaceIdFromBranch(branch) === workspaceId\n}\n\n/** Find a workspace's checkout among the repository's linked worktrees. */\nexport function resolveWorkspaceWorktree(\n worktrees: readonly { path: string; branch: string | null }[],\n workspaceId: string,\n): string | null {\n const branch = workspaceBranchName(workspaceId)\n return worktrees.find((worktree) => worktree.branch === branch)?.path ?? null\n}\n","import * as p from '@clack/prompts'\nimport { existsSync, readFileSync } from 'node:fs'\nimport {\n RESERVED_BINDING_NAMES,\n type CustomBindingManifest,\n} from '../../../server/rooms/binding-manifest'\nimport { extractCustomDevVars, parseDevVars, writeDevVars } from '../../lib/dev-vars'\nimport {\n refreshSecretsCache,\n stripGeneratedSecretsCache,\n type PulledSecretsCache,\n} from '../../lib/secrets'\nimport { devVarsPathFor } from '../../lib/wrangler-env'\nimport type { DurableObjectManifestEntry } from './build'\nimport type { DeployOutput } from './output'\n\nexport interface DeploySecretsCache {\n linked: PulledSecretsCache | null\n localOnlyDevVars: Record<string, string>\n}\n\nexport interface DeploySecretsPayload {\n values: Record<string, string>\n names: string[]\n}\n\nexport function classifyDevVarsSecrets(options: {\n storeSecretNames: string[]\n handEditedDevVarKeys: string[]\n allowMissing: boolean\n}):\n | { kind: 'ok' }\n | { kind: 'warn'; strayKeys: string[] }\n | { kind: 'block'; strayKeys: string[] } {\n const store = new Set(options.storeSecretNames)\n const strayKeys = options.handEditedDevVarKeys.filter((key) => !store.has(key))\n if (strayKeys.length === 0) return { kind: 'ok' }\n if (options.storeSecretNames.length === 0 && !options.allowMissing) {\n return { kind: 'block', strayKeys }\n }\n return { kind: 'warn', strayKeys }\n}\n\nexport async function loadDeploySecrets(options: {\n deployUrl: string\n appDir: string\n appId: string\n envName: string | undefined\n ownerId: string\n token: string\n output: DeployOutput\n}): Promise<DeploySecretsCache> {\n const { deployUrl, appDir, appId, envName, ownerId, token, output } = options\n let linked: PulledSecretsCache | null = null\n let localOnlyDevVars: Record<string, string> = {}\n\n try {\n const refreshed = await refreshSecretsCache(deployUrl, token, appId, envName)\n if (refreshed) {\n linked = refreshed.pulled\n localOnlyDevVars = readCustomDevVars(\n devVarsPathFor(appDir, envName, { sharedDevVarsCache: true }),\n output,\n )\n await writeDevVars(appDir, ownerId, token, envName, {\n appId,\n generatedSecretsCache: refreshed.rendered,\n sharedDevVarsCache: true,\n })\n p.log.info(refreshed.summary)\n }\n } catch (error: unknown) {\n if ((error as { status?: number })?.status === 403) {\n output.die(\n \"You're not authorized to deploy this app — you must be its owner or a current \" +\n 'collaborator. If you were a collaborator, your access may have been revoked.',\n 'not_authorized',\n )\n }\n output.die(\n `Failed to refresh app secrets before deploy: ${errorMessage(error)}`,\n 'secrets_refresh_failed',\n )\n }\n\n return { linked, localOnlyDevVars }\n}\n\nexport function prepareDeploySecrets(options: {\n appDir: string\n envName: string | undefined\n cache: DeploySecretsCache\n allowMissing: boolean\n customBindings: CustomBindingManifest\n doManifest: DurableObjectManifestEntry[] | undefined\n output: DeployOutput\n}): DeploySecretsPayload {\n const { appDir, envName, cache, allowMissing, customBindings, doManifest, output } = options\n const values = cache.linked ? { ...cache.linked.values } : {}\n const devVarsPath = devVarsPathFor(appDir, envName, {\n sharedDevVarsCache: cache.linked !== null,\n })\n const handEditedDevVars = cache.linked\n ? cache.localOnlyDevVars\n : readCustomDevVars(devVarsPath, output)\n const decision = classifyDevVarsSecrets({\n storeSecretNames: Object.keys(values),\n handEditedDevVarKeys: Object.keys(handEditedDevVars),\n allowMissing,\n })\n\n if (decision.kind === 'block') {\n const uploadArgv = [\n 'deepspace',\n 'secrets',\n 'upload',\n '.dev.vars',\n ...(envName ? ['-e', envName] : []),\n ]\n output.die(\n `Refusing to deploy: the app store has no secrets, but .dev.vars has ${decision.strayKeys.join(', ')}. ` +\n 'Deploying now would ship the app with no secrets — replacing any secrets a previous ' +\n 'deploy set (they would be dropped from production). Upload them first, then ' +\n 'redeploy. (Pass --allow-missing-secrets to deploy without them.)',\n 'secrets_not_uploaded',\n { action: { cwd: appDir, argv: uploadArgv } },\n )\n }\n if (decision.kind === 'warn') {\n const stray = decision.strayKeys\n p.log.warn(\n `.dev.vars has ${stray.join(', ')} not in the app store — ${stray.length === 1 ? 'it is' : 'they are'} NOT deployed. ` +\n '`.dev.vars` is a local dev cache, not deploy config. Move ' +\n `${stray.length === 1 ? 'it' : 'them'} into the store with ` +\n '`deepspace secrets set KEY=value` (or `deepspace secrets upload .dev.vars`), then redeploy.',\n )\n }\n\n const names = Object.keys(values)\n const declaredBindingNames = new Set([\n ...customBindings.map((binding) => binding.name),\n ...(doManifest ?? []).map((binding) => binding.binding),\n ])\n for (const name of names) {\n if (RESERVED_BINDING_NAMES.has(name)) {\n output.die(\n `App secret \"${name}\" is a reserved binding name — rename or remove that secret before deploying.`,\n 'reserved_binding',\n )\n }\n if (declaredBindingNames.has(name)) {\n output.die(\n `App secret \"${name}\" collides with a binding declared in wrangler.toml — rename one or the other.`,\n 'binding_collision',\n )\n }\n }\n if (names.length) p.log.info(`App secrets: ${names.join(', ')}`)\n\n return { values, names }\n}\n\nfunction readCustomDevVars(path: string, output: DeployOutput): Record<string, string> {\n if (!existsSync(path)) return {}\n const section = extractCustomDevVars(stripGeneratedSecretsCache(readFileSync(path, 'utf-8')))\n if (!section) return {}\n try {\n return parseDevVars(section)\n } catch (error: unknown) {\n output.die(`.dev.vars: ${errorMessage(error)}`, 'invalid_dev_vars')\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * deepspace app undeploy\n *\n * Removes a deployed app from *.app.space via the deploy worker.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug and the exit codes come from there. Undeploy is TERMINAL — it emits\n * no `Next:` line (the human outro already says a redeploy brings it back).\n */\n\nimport { readAppId } from '../lib/app-identity'\nimport * as p from '@clack/prompts'\nimport { createSpinner } from '../lib/spinner'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { resolveAppSelector } from '../lib/app-target'\nimport { hasWranglerConfig } from '../lib/wrangler-env'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'undeploy',\n description: 'Remove a deployed DeepSpace app',\n },\n args: {\n name: {\n type: 'positional',\n description: 'App id or subdomain name to undeploy (reads DEEPSPACE_APP_ID from wrangler.toml if omitted)',\n required: false,\n },\n env: {\n type: 'string',\n description:\n 'wrangler.toml [env.<name>] block whose deployed app to remove ' +\n '(e.g. --env staging). Ignored if a positional name is given.',\n required: false,\n },\n },\n async run({ args }) {\n const envName = typeof args.env === 'string' && args.env.trim() ? args.env.trim() : undefined\n\n // Token first — resolving a subdomain name to its id needs the registry.\n let token: string\n try {\n token = await ensureToken()\n } catch (err: unknown) {\n throw new Refusal(err instanceof Error ? err.message : String(err), 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n // Target: an explicit positional — app id OR live subdomain name, resolved\n // via the registry (DEP-5) — else DEEPSPACE_APP_ID from wrangler.toml.\n // resolveAppSelector's own InputErrors already carry codes (app_not_found,\n // invalid_app, invalid_response); let them escape rather than re-wrap.\n let appId: string | undefined\n const positional =\n typeof args.name === 'string' && args.name.trim() ? args.name.trim() : undefined\n if (positional) {\n appId = await resolveAppSelector(DEPLOY_URL, token, positional)\n } else if (hasWranglerConfig(process.cwd())) {\n appId = readAppId(process.cwd(), envName) ?? undefined\n }\n if (!appId) {\n throw new Refusal(\n 'Provide an app id or subdomain name, or run from a DeepSpace app directory with a DEEPSPACE_APP_ID.',\n 'not_in_app_repo',\n )\n }\n\n if (!args.json) p.intro(`Undeploying ${appId}`)\n const s = args.json ? null : createSpinner()\n s?.start('Removing...')\n\n const res = await fetch(`${DEPLOY_URL}/api/deploy/${appId}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${token}` },\n })\n\n const body = (await res.json().catch(() => ({}))) as {\n success?: boolean\n error?: string\n code?: string\n releasedHosts?: string[]\n }\n\n if (!res.ok || !body.success) {\n s?.stop('Failed')\n if (body.code === 'registry_takedown_failed') {\n throw new Refusal(\n body.error ?? 'Registry takedown failed after the cloud script was removed.',\n body.code,\n {\n actionRequired: true,\n action: cliAction('deepspace', 'app', 'undeploy', appId),\n extra: { appId },\n },\n )\n }\n throw new Refusal(body.error ?? `Undeploy error (${res.status})`, 'undeploy_failed')\n }\n\n s?.stop('Removed')\n const hosts = body.releasedHosts ?? []\n if (!args.json) {\n p.outro(\n hosts.length\n ? `${hosts.join(', ')} taken down. The app keeps its id — redeploy to bring it back.`\n : `App ${appId} taken down.`,\n )\n }\n return { data: { appId, releasedHosts: hosts } }\n },\n})\n","/** Resolve explicit or local app selectors to canonical app ids. */\n\nimport { APP_ID_RE, readAppId } from './app-identity'\nimport { apiFetch } from './api'\nimport { InputError } from './cli-errors'\nimport { findAppDir } from './app-context'\nimport { resolveAppIdByName } from './repo-api'\nimport { STRICT_APP_ID_RE } from '../../server/utils/registry-client'\nimport { APP_NAME_RULES } from '../../server/rooms/app-name'\n\nfunction isCanonicalAppName(name: string): boolean {\n return (\n name.length >= APP_NAME_RULES.minLength &&\n name.length <= APP_NAME_RULES.maxLength &&\n APP_NAME_RULES.pattern.test(name)\n )\n}\n\n/** Resolve an explicit app id, or read it from the surrounding app. */\nexport function requireAppIdArg(explicit: string | undefined): string {\n const { app, error } = parseAppArg(explicit)\n if (error) throw new InputError(error, 'invalid_app')\n if (app !== undefined) {\n if (!APP_ID_RE.test(app)) {\n throw new Error(`\"${app}\" is not an app id (app_…). Pass --app <appId>.`)\n }\n return app\n }\n const appDir = findAppDir()\n const id = appDir ? readAppId(appDir) : null\n if (!id) {\n throw new Error(\n 'No app id. Run from an app directory whose wrangler.toml carries DEEPSPACE_APP_ID, or pass --app <appId>.',\n )\n }\n return id\n}\n\ninterface AppListEntry {\n appId: string\n name: string | null\n}\n\n/** Find an app id or subdomain name in the caller's registry list. */\nexport function matchAppSelector(apps: AppListEntry[], selector: string): string | null {\n const byId = apps.find((app) => app.appId === selector)\n if (byId) return byId.appId\n const byName = apps.find((app) => app.name === selector)\n if (byName) return byName.appId\n return STRICT_APP_ID_RE.test(selector) ? selector : null\n}\n\n/** Resolve an app id or live subdomain name to the canonical app id. */\nexport async function resolveAppSelector(\n deployUrl: string,\n token: string,\n selector: string,\n): Promise<string> {\n if (STRICT_APP_ID_RE.test(selector)) return selector\n const { apps } = await apiFetch<{ apps: AppListEntry[] }>(deployUrl, token, '/api/apps')\n if (!Array.isArray(apps)) {\n throw new InputError(\n `The deploy service at ${deployUrl} returned an unexpected response shape for the app list — ` +\n `check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n 'invalid_response',\n )\n }\n const id = matchAppSelector(apps, selector)\n if (id) return id\n\n // The owner-scoped app list omits apps on which the caller collaborates.\n const shared = await resolveAppIdByName(deployUrl, token, selector)\n if (shared) return shared\n throw new InputError(\n `No app \"${selector}\" found, or you don't have access to it. ` +\n `If the app exists but was never deployed, it has no name yet; target it by app id. ` +\n `Run \\`deepspace app list\\` to list your apps and their ids.`,\n 'app_not_found',\n )\n}\n\n/** Resolve an explicit selector, or read the surrounding app id. */\nexport async function resolveAppTarget(\n deployUrl: string,\n token: string,\n explicit: string | undefined,\n): Promise<string> {\n const { app, error } = parseAppArg(explicit)\n if (error) throw new InputError(error, 'invalid_app')\n if (app !== undefined) return resolveAppSelector(deployUrl, token, app)\n const appDir = findAppDir()\n const id = appDir ? readAppId(appDir) : null\n if (!id) {\n throw new InputError(\n 'No app id. Run from an app directory whose wrangler.toml carries DEEPSPACE_APP_ID, or pass --app <id or name>.',\n 'not_in_app_repo',\n )\n }\n return id\n}\n\n/** Preserve absent-vs-blank so a blank selector cannot target the local app. */\nexport function parseAppArg(raw: string | undefined): { app?: string; error?: string } {\n if (raw === undefined) return {}\n const selector = raw.trim()\n if (selector === '') {\n return {\n error:\n '--app was given an empty app id — pass an app id/name, or omit --app to use the current directory.',\n }\n }\n if (selector.startsWith('app_')) {\n if (!STRICT_APP_ID_RE.test(selector)) {\n return {\n error: `--app \"${selector}\" looks like an app id but isn't a valid app_<ULID> — check for a typo.`,\n }\n }\n return { app: selector }\n }\n if (!isCanonicalAppName(selector)) {\n return {\n error: `--app \"${selector}\" is not a valid app id or name (expected app_<ULID>, or a subdomain name — lowercase letters, digits and hyphens).`,\n }\n }\n return { app: selector }\n}\n\n/** Validate that a target is locally determinable before reading credentials. */\nexport function assertAppTargetResolvable(appArg: string | undefined): void {\n const { app, error } = parseAppArg(appArg)\n if (error) throw new InputError(error, 'invalid_app')\n if (app !== undefined) return\n\n const appDir = findAppDir()\n if (!appDir || !readAppId(appDir)) {\n throw new InputError(\n 'No app id. Run from an app directory whose wrangler.toml carries DEEPSPACE_APP_ID, or pass --app <id or name>.',\n 'not_in_app_repo',\n )\n }\n}\n\n/** Warn before an explicit unknown id can be registered by push or deploy. */\nexport async function warnIfPhantomApp(\n deployUrl: string,\n token: string,\n appId: string,\n explicit: string | undefined,\n): Promise<void> {\n if (!explicit || !STRICT_APP_ID_RE.test(explicit.trim())) return\n try {\n const { apps } = await apiFetch<{ apps: AppListEntry[] }>(deployUrl, token, '/api/apps')\n if (!apps.some((app) => app.appId === appId)) {\n process.stderr.write(\n `warning: ${appId} is not among your apps. If it exists and you have access ` +\n `(collaborator/admin), the server will use it; if it doesn't exist, this will ` +\n `register it as a NEW app under your account — check the id if that's not what ` +\n `you meant (a subdomain name also works with -a).\\n`,\n )\n }\n } catch {\n // Advisory only.\n }\n}\n","/**\n * deepspace auth whoami\n *\n * Shows the currently logged-in user. Auto-refreshes the JWT if expired.\n *\n * Prints all the identity fields a developer cares about (email, name,\n * userId, issuer) so you don't have to peek into ~/.deepspace/token.\n * Also flags whether the session is for a test account (`@deepspace.test`\n * email), since that's a meaningful distinction for who can do what — see\n * docs/auth/dev-vs-test-accounts.md.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport { ensureToken } from '../auth'\nimport { DASHBOARD_URL } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\ninterface JwtPayload {\n sub?: string\n name?: string\n email?: string\n image?: string | null\n iss?: string\n iat?: number\n exp?: number\n}\n\n/**\n * A network failure reaching the auth server (Node fetch throws\n * `TypeError: fetch failed`, or a DNS/socket errno) is NOT proof of being\n * logged out — code it apart so a retry isn't mistaken for a re-login.\n */\nconst isNetworkError = (err: unknown): boolean =>\n err instanceof TypeError ||\n (err instanceof Error &&\n /fetch failed|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|getaddrinfo|network/i.test(err.message))\n\nexport default defineDeepspaceCommand({\n meta: { name: 'whoami', description: 'Show the currently logged-in user' },\n async run({ args }) {\n let jwt: string\n try {\n jwt = await ensureToken()\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : 'Not logged in. Run `deepspace auth login` first.'\n // The code distinguishes a genuine logged-out state (log in) from an\n // unreachable auth server (retry): both would otherwise read as\n // \"not logged in\", and an agent would re-login instead of reconnecting.\n throw isNetworkError(err)\n ? new Refusal(msg, 'network_error')\n : new Refusal(msg, 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n let payload: JwtPayload\n try {\n payload = decodeJwtPayload<JwtPayload>(jwt)\n } catch {\n throw new Refusal('Malformed session token. Run `deepspace auth login` again.', 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const isTestAccount = !!payload.email?.endsWith('@deepspace.test')\n const accountType: 'developer' | 'test-account' | 'unknown' = isTestAccount\n ? 'test-account'\n : payload.email\n ? 'developer'\n : 'unknown'\n\n if (!args.json) {\n console.log(`Name: ${payload.name ?? '(none)'}`)\n console.log(`Email: ${payload.email ?? '(none)'}`)\n console.log(`UserID: ${payload.sub ?? '(none)'}`)\n console.log(`Type: ${accountType}`)\n if (payload.iss) console.log(`Issuer: ${payload.iss}`)\n console.log(`Dashboard: ${DASHBOARD_URL}`)\n if (isTestAccount) {\n console.log('')\n console.log('Note: this is a test account, not a real OAuth developer.')\n console.log('See docs/auth/dev-vs-test-accounts.md.')\n }\n }\n\n return {\n data: {\n name: payload.name ?? null,\n email: payload.email ?? null,\n userId: payload.sub ?? null,\n accountType,\n issuer: payload.iss ?? null,\n expiresAt: payload.exp ? new Date(payload.exp * 1000).toISOString() : null,\n },\n }\n },\n})\n","/**\n * deepspace app list\n *\n * Lists every app registered to the logged-in user — deployed or not — with\n * its id, live URL, and deploy state. This is the answer to \"which app do I\n * undeploy?\" when the deploy quota message names an id you've lost track of,\n * and the discovery surface for a second checkout / lost app dir.\n *\n * `--json` emits the entries for scripts, under `apps` in the standard\n * `{ ok, … }` envelope.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { apiFetch } from '../lib/api'\nimport { defineDeepspaceCommand } from '../lib/command'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\ninterface AppEntry {\n appId: string\n status: string\n createdAt: string\n deployedAt: string | null\n /** Current subdomain lease; null when undeployed. */\n name: string | null\n url: string | null\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'apps',\n description: 'List your apps (deployed and registered)',\n },\n async run({ args }) {\n const token = await ensureToken()\n const { apps } = await apiFetch<{ apps: AppEntry[] }>(DEPLOY_URL, token, '/api/apps')\n\n if (!args.json) {\n if (!apps.length) {\n console.log('No apps yet. Create one with `npx create-deepspace <name>` and `deepspace deploy`.')\n } else {\n const nameWidth = Math.max(4, ...apps.map((a) => (a.name ?? '—').length))\n const idWidth = Math.max(6, ...apps.map((a) => a.appId.length))\n console.log(`${'NAME'.padEnd(nameWidth)} ${'APP ID'.padEnd(idWidth)} URL`)\n for (const a of apps) {\n const url = a.url ?? '(not deployed)'\n console.log(`${(a.name ?? '—').padEnd(nameWidth)} ${a.appId.padEnd(idWidth)} ${url}`)\n }\n }\n }\n // No `next`: a listing is terminal — which app you act on, and how, is the\n // caller's choice.\n return { data: { apps } }\n },\n})\n","/**\n * deepspace logs\n *\n * Production logs for a deployed app — console output, request summaries,\n * and exceptions — read from Workers Logs through the platform (7-day\n * retention). Defaults to the last 15 minutes; `--follow` keeps polling\n * for new events until Ctrl+C. There is no push channel for\n * dispatch-namespace scripts, so polling IS the tail (the server's\n * `pollIntervalMs` sets the cadence).\n *\n * `--json` emits NDJSON — one event object per line — so agents and pipes\n * get a parseable stream in both one-shot and follow mode (deliberately\n * not the pretty-array shape `apps --json` uses). A truncated page also\n * emits one `{ \"type\": \"meta\", \"truncated\": true }` record (events never\n * carry a `type`, so consumers can branch on it) — otherwise a dropped\n * burst would be invisible to a machine reader.\n *\n * Ingestion lags real time by seconds up to ~1 minute: an empty result\n * right after a request is lag, not absence.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { apiFetch, ApiError } from '../lib/api'\nimport { InputError } from '../lib/cli-errors'\nimport { findAppDir } from '../lib/app-context'\nimport { resolveAppTarget } from '../lib/app-target'\nimport { readAppId } from '../lib/app-identity'\n// Whitelisted wire DTO + level set — shared with the platform reader and the\n// dashboard (packages/deepspace/src/shared/log-events.ts) so they can't drift.\nimport { LOG_LEVELS, type AppLogEvent, type AppLogsResponse } from '../../shared/log-events'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nconst RETENTION_MS = 7 * 24 * 60 * 60 * 1000\nconst DEFAULT_WINDOW_MS = 15 * 60 * 1000\nconst MIN_POLL_MS = 2500\n/**\n * Follow mode re-scans this far back of the last cursor before each poll.\n * Workers Logs ingestion is completion-ordered and lags up to ~1 min, so a\n * slow invocation's earlier-stamped line can arrive AFTER a fast request's\n * later-stamped line already advanced the cursor past it — polling only from\n * `cursor` would drop it permanently. The id dedupe (SeenEvents) discards the\n * re-fetched overlap, so the lag window costs nothing but a slightly larger page.\n *\n * Set above the stated ~60s max lag for margin: an event ingested more than\n * this late is still missed (CF's telemetry API has no ascending drain to\n * recover it), so this shrinks — not eliminates — the drop window.\n */\nconst FOLLOW_LAG_MS = 90_000\n\n/**\n * The page size a follow tail requests. Follow defaults to the max page so a\n * burst between polls is less likely to overflow one page and silently drop its\n * oldest events; an explicit `--limit` still wins. Exported for tests.\n */\nexport function followInitialLimit(limit: number | undefined, maxLimit: number): number {\n return limit ?? maxLimit\n}\n\n/**\n * Where the next follow poll starts: `FOLLOW_LAG_MS` before the last cursor,\n * floored at the original window start so a tail never scans before the user's\n * `--since`. Exported for tests.\n */\nexport function nextPollSince(cursor: number, floor: number, lagMs: number = FOLLOW_LAG_MS): number {\n return Math.max(cursor - lagMs, floor)\n}\n\n/**\n * `30s` / `15m` / `2h` / `7d` or an ISO timestamp → unix ms. Exported for\n * tests.\n */\nexport function parseSince(input: string, now: number = Date.now()): number {\n const trimmed = input.trim()\n const rel = /^(\\d+)([smhd])$/.exec(trimmed)\n let ts: number\n if (rel) {\n const unit = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }[rel[2] as 's' | 'm' | 'h' | 'd']\n ts = now - Number(rel[1]) * unit\n } else {\n ts = Date.parse(trimmed)\n if (Number.isNaN(ts)) {\n throw new InputError(`Invalid --since \"${input}\" — use 30s, 15m, 2h, 7d, or an ISO timestamp.`, 'invalid_since')\n }\n }\n if (now - ts > RETENTION_MS) {\n throw new InputError('Logs are retained for 7 days — --since can reach back at most 7d.', 'since_out_of_range')\n }\n return ts\n}\n\n/**\n * Rolling dedupe window for follow mode. Poll N+1 re-fetches from the last\n * cursor timestamp (inclusive), so events at exactly that millisecond come\n * back again; a bounded id set drops them without assuming server ordering.\n * Exported for tests.\n */\nexport class SeenEvents {\n private ids = new Set<string>()\n private order: string[] = []\n constructor(private cap = 5000) {}\n\n /** Returns only the events not seen before, recording them. */\n fresh(events: AppLogEvent[]): AppLogEvent[] {\n const out: AppLogEvent[] = []\n for (const e of events) {\n if (this.ids.has(e.id)) continue\n this.ids.add(e.id)\n this.order.push(e.id)\n out.push(e)\n }\n while (this.order.length > this.cap) {\n this.ids.delete(this.order.shift()!)\n }\n return out\n }\n}\n\n// ── Pretty rendering ─────────────────────────────────────────────────────────\n\nconst stdoutColor = () => process.stdout.isTTY && !process.env.NO_COLOR\n// Status/diagnostic lines go to stderr, so their coloring must gate on\n// stderr's TTY-ness — not stdout's, which may be redirected to a file/pipe.\nconst stderrColor = () => process.stderr.isTTY && !process.env.NO_COLOR\nconst paint = (code: string, s: string, on: boolean) => (on ? `\\x1b[${code}m${s}\\x1b[0m` : s)\n\nconst LEVEL_STYLE: Record<string, string | null> = {\n error: '31', // red\n warn: '33', // yellow\n debug: '2', // dim\n info: null,\n log: null,\n}\n\nfunction formatTime(ts: number, now: number): string {\n const d = new Date(ts)\n const ref = new Date(now)\n const hms =\n `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:` +\n `${String(d.getSeconds()).padStart(2, '0')}.${String(d.getMilliseconds()).padStart(3, '0')}`\n if (d.toDateString() === ref.toDateString()) return hms\n const ymd = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n return `${ymd} ${hms}`\n}\n\n/** One event → printable line(s). Exported for tests (pass color=false). */\nexport function formatEvent(e: AppLogEvent, color: boolean, now: number = Date.now()): string {\n const time = paint('2', formatTime(e.timestamp, now), color)\n\n let tag: string\n let body: string\n if (e.eventType === 'exception' && e.exception) {\n tag = paint('31', 'ERROR', color)\n const where = e.request ? ` — ${e.request.method} ${e.request.path}` : ''\n body = `${e.exception.name}: ${e.exception.message}${where}`\n if (e.exception.stack) {\n // Drop a leading \"Name: message\" header line (V8 style) so it isn't\n // shown twice — but Cloudflare worker stacks are often frame-only\n // (e.g. \" at fetch (index.js:1:1)\") with NO header, so only strip the\n // first line when it actually IS that header. Otherwise we'd eat a frame.\n const lines = e.exception.stack.split('\\n')\n const firstIsHeader = lines.length > 0 && !/^\\s*at\\s/.test(lines[0]) && lines[0].includes(e.exception.message)\n const frames = (firstIsHeader ? lines.slice(1) : lines)\n .map((l) => ' ' + l.trim())\n .filter((l) => l.trim().length > 0)\n if (frames.length) body += '\\n' + paint('2', frames.join('\\n'), color)\n }\n } else if (e.eventType === 'request' && e.request) {\n tag = paint('36', 'REQ ', color)\n const status = e.request.status !== undefined ? ` ${e.request.status}` : ''\n const outcome = e.outcome && e.outcome !== 'ok' ? ` (${e.outcome})` : ''\n body = `${e.request.method} ${e.request.path}${status}${outcome}`\n } else {\n const style = LEVEL_STYLE[e.level]\n tag = (e.level.toUpperCase() + ' ').slice(0, 5)\n if (style) tag = paint(style, tag, color)\n body = style ? paint(style, e.message, color) : e.message\n }\n\n // A browser-forwarded error is tagged so it's not mistaken for a server log.\n const client = e.source === 'client' ? paint('35', 'CLIENT', color) + ' ' : ''\n return `${time} ${client}${tag} ${body}`\n}\n\n// ── Command ──────────────────────────────────────────────────────────────────\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))\n\nexport default defineCommand({\n meta: {\n name: 'logs',\n description: 'Show production logs for a deployed app (add --follow to tail)',\n },\n args: {\n app: {\n type: 'string',\n alias: 'a',\n description: 'App id or name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description: 'wrangler.toml [env.<name>] slot — reads that env’s own app id',\n required: false,\n },\n follow: {\n type: 'boolean',\n alias: 'f',\n description: 'Keep polling for new logs until Ctrl+C (~3s cadence)',\n default: false,\n },\n since: {\n type: 'string',\n description: 'Window start: 30s, 15m, 2h, 24h, 7d, or an ISO timestamp (default 15m)',\n required: false,\n },\n level: {\n type: 'string',\n description: `Only events at a level: ${LOG_LEVELS.join(', ')}`,\n required: false,\n },\n search: {\n type: 'string',\n description: 'Only events whose message contains this text',\n required: false,\n },\n limit: {\n type: 'string',\n description: 'Max events per fetch (default 100, max 500)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Emit NDJSON — one event object per line (for agents/pipes)',\n default: false,\n },\n },\n async run({ args }) {\n const token = await ensureToken()\n\n const wranglerEnv = args.env?.trim() || undefined\n // --app and --env are two different ways to name the target. Combining them\n // is ambiguous — and previously --env was silently ignored when --app was\n // also passed — so fail fast rather than tail the wrong app.\n if (args.app && wranglerEnv) {\n throw new InputError(\n 'Pass either --app or --env, not both — --env reads the [env.<name>] block’s own app id, --app names an app directly.',\n 'ambiguous_target',\n )\n }\n let appId: string\n if (!args.app && wranglerEnv) {\n // `--env <name>` targets the [env.<name>] block's own app id (a staging\n // deploy is its own app) — same convention as `secrets --env`.\n const appDir = findAppDir()\n const id = appDir ? readAppId(appDir, wranglerEnv) : null\n if (!id) {\n throw new InputError(\n `No app id for env \"${wranglerEnv}\" — wrangler.toml has no [env.${wranglerEnv}] block with its own DEEPSPACE_APP_ID.`,\n 'no_app_id_for_env',\n )\n }\n appId = id\n } else {\n appId = await resolveAppTarget(DEPLOY_URL, token, args.app)\n }\n\n if (args.level && !(LOG_LEVELS as readonly string[]).includes(args.level)) {\n throw new InputError(`Invalid --level \"${args.level}\". Use: ${LOG_LEVELS.join(', ')}`, 'invalid_level')\n }\n let limit: number | undefined\n if (args.limit !== undefined) {\n limit = Number(args.limit)\n if (!Number.isInteger(limit) || limit < 1 || limit > 500) {\n throw new InputError('Invalid --limit — expected an integer between 1 and 500.', 'invalid_limit')\n }\n }\n\n const initialSince = args.since ? parseSince(args.since) : Date.now() - DEFAULT_WINDOW_MS\n const windowLabel = args.since?.trim() || '15m'\n\n // Server clamp; used as the follow-mode default so a burst between polls is\n // less likely to overflow one page (see the truncation note below).\n const MAX_LIMIT = 500\n const followLimit = followInitialLimit(limit, MAX_LIMIT)\n\n const fetchPage = async (\n since: number,\n pageLimit: number | undefined,\n token: string,\n ): Promise<AppLogsResponse> => {\n const params = new URLSearchParams({ since: String(since) })\n if (pageLimit !== undefined) params.set('limit', String(pageLimit))\n if (args.level) params.set('level', args.level)\n if (args.search) params.set('search', args.search)\n return apiFetch<AppLogsResponse>(DEPLOY_URL, token, `/api/apps/${appId}/logs?${params}`)\n }\n\n const print = (events: AppLogEvent[]) => {\n for (const e of events) {\n process.stdout.write(args.json ? JSON.stringify(e) + '\\n' : formatEvent(e, stdoutColor()) + '\\n')\n }\n }\n\n // Follow mode tails from the max page too — a first page capped at the\n // default 100 would drop the rest of the initial window and jump the cursor\n // past it. One-shot mode keeps the user's (possibly unset) --limit.\n const first = await fetchPage(initialSince, args.follow ? followLimit : limit, token)\n print(first.events)\n\n if (!args.follow) {\n if (first.events.length === 0) {\n if (args.json) {\n // An empty NDJSON stream is indistinguishable from a crash without a\n // trailing record — emit a discriminable meta line so an agent can\n // tell \"ran, no events\" from \"died\". (events never carry `type`.)\n process.stdout.write(JSON.stringify({ type: 'meta', count: 0, window: windowLabel }) + '\\n')\n } else {\n console.log(\n `No logs in the last ${windowLabel} for ${appId}. New logs can take up to a minute to appear; retention is 7 days.`,\n )\n }\n } else if (first.truncated) {\n // A machine consumer reading NDJSON needs the signal too — emit a\n // discriminable meta record (events never carry a `type` field).\n if (args.json) process.stdout.write(JSON.stringify({ type: 'meta', truncated: true }) + '\\n')\n else console.error(`(showing the newest ${first.events.length} events — narrow with --since/--level/--search)`)\n }\n return\n }\n\n // ── Follow mode ──────────────────────────────────────────────────────────\n process.on('SIGINT', () => process.exit(0))\n if (!args.json) {\n console.error(`Tailing logs for ${appId} — Ctrl+C to stop.`)\n }\n\n // Poll for the newest events each tick. A page is capped at `limit`; when\n // more than that arrive between two polls, the server returns the NEWEST\n // and the cursor advances past the oldest of the burst — those are dropped,\n // not just delayed (CF's telemetry API has no ascending order to drain\n // forward). Default follow polls to the max page size to shrink that window,\n // and warn on `truncated` so a drop is never silent.\n const seen = new SeenEvents()\n seen.fresh(first.events)\n let cursor = first.cursor ?? initialSince\n let interval = Math.max(first.pollIntervalMs || 0, MIN_POLL_MS)\n let backoff = 0\n // Warn only on the transition into truncation, not every poll — a\n // sustained burst would otherwise flood the stream.\n let warnedTruncated = false\n\n // The initial page can already be truncated (the window held more than one\n // page). The loop only checks pages it fetches, so surface it once here —\n // otherwise `-f` would drop the overflow silently, unlike one-shot mode.\n if (first.truncated) {\n warnedTruncated = true\n if (args.json) {\n process.stdout.write(JSON.stringify({ type: 'meta', truncated: true }) + '\\n')\n } else {\n console.error(\n paint('33', `(more than ${followLimit} events in the initial ${windowLabel} window — some older events not shown; narrow with --since/--level/--search)`, stderrColor()),\n )\n }\n }\n\n for (;;) {\n await sleep(backoff || interval)\n // Refresh the token BEFORE the retryable fetch: the JWT is 5-minute-lived\n // and a tail outlives it. A refresh failure (session expired / logged out)\n // throws a plain Error and is fatal — it will not fix itself by retrying,\n // so let it propagate and end the tail cleanly.\n const freshToken = await ensureToken()\n let page: AppLogsResponse\n try {\n // Re-scan a lag window before the cursor so a late-ingested,\n // earlier-stamped event isn't skipped; SeenEvents drops the overlap.\n page = await fetchPage(nextPollSince(cursor, initialSince), followLimit, freshToken)\n } catch (err) {\n // Auth/authz/absence is fatal — the situation won't improve by\n // retrying. Everything else (5xx, 429, network) backs off.\n if (err instanceof ApiError && [401, 403, 404].includes(err.status)) throw err\n backoff = Math.min(backoff ? backoff * 2 : MIN_POLL_MS, 30_000)\n const msg = err instanceof Error ? err.message : String(err)\n console.error(paint('2', `(logs fetch failed: ${msg} — retrying in ${backoff / 1000}s)`, stderrColor()))\n continue\n }\n backoff = 0\n interval = Math.max(page.pollIntervalMs || 0, MIN_POLL_MS)\n const fresh = seen.fresh(page.events)\n print(fresh)\n // Warn only when a poll delivered a FULL page of genuinely-new events —\n // the real drop signal. `page.truncated` counts the re-scanned (already\n // seen, deduped) lag-window overlap toward the cap, so it cries wolf on a\n // busy-but-lossless tail; `fresh.length` excludes that overlap.\n const realDrop = fresh.length >= followLimit\n if (realDrop && !warnedTruncated) {\n warnedTruncated = true\n if (args.json) {\n process.stdout.write(JSON.stringify({ type: 'meta', truncated: true }) + '\\n')\n } else {\n console.error(\n paint('33', `(burst exceeded ${followLimit} events/poll — some may be dropped; narrow with --level/--search)`, stderrColor()),\n )\n }\n } else if (!realDrop) {\n warnedTruncated = false\n }\n if (page.cursor !== null) cursor = page.cursor\n }\n },\n})\n","/**\n * `deepspace logs` wire DTO — the single source of truth for the whitelisted\n * shape the platform telemetry reader emits and every consumer reads.\n *\n * The producer is `platform/deploy-worker/src/lib/workers-logs.ts` (which\n * rebuilds each event field-by-field from a raw Cloudflare row — see the\n * security invariant there). The consumers are the CLI tail\n * (`cli/commands/logs.ts`), the dashboard Logs panel\n * (`apps/dashboard/src/lib/apps.ts`), and the e2e whitelist assertion\n * (`tests/e2e/tests/logs.spec.ts`). This module used to be hand-mirrored in\n * all four places; `source` was added to three of them and missed in the\n * e2e whitelist, so it now lives here once and they import it.\n *\n * Isomorphic — no DOM, no Hono, no platform types — so it re-exports cleanly\n * from both `deepspace` (client) and `deepspace/worker` and is safe to import\n * from the private deploy-worker.\n */\n\nexport const LOG_LEVELS = ['debug', 'log', 'info', 'warn', 'error'] as const\nexport type LogLevel = (typeof LOG_LEVELS)[number]\n\n/** One log / request / exception event, rebuilt field-by-field from a CF row. */\nexport interface AppLogEvent {\n /** `$metadata.id` — unique per event; the client's dedupe key. */\n id: string\n /** Unix ms. */\n timestamp: number\n level: LogLevel\n eventType: 'log' | 'request' | 'exception' | 'other'\n message: string\n /**\n * Present (= `'client'`) only for a browser-forwarded error the app's own\n * Worker re-logged via `registerClientErrorRoute`. Absent means the log was\n * emitted server-side — there is no explicit `'server'` value, so consumers\n * branch on `source === 'client'`, never on a truthy/other check.\n */\n source?: 'client'\n /** Invocation outcome (`ok`, `exception`, `exceededCpu`, …) when present. */\n outcome?: string\n request?: { method: string; path: string; status?: number }\n exception?: { name: string; message: string; stack?: string }\n}\n\nexport interface AppLogsResponse {\n /** Ascending by timestamp (CF returns newest-first; the reader flips). */\n events: AppLogEvent[]\n /** Max event timestamp in ms — pass back as `since` to poll; null when empty. */\n cursor: number | null\n /** True when the window returned `limit` events (older events were cut). */\n truncated: boolean\n pollIntervalMs: number\n}\n\n/**\n * Runtime tuple of every key a whitelisted `AppLogEvent` may carry — the\n * canonical whitelist the e2e suite mirrors when asserting no event leaks a key\n * outside this set. The two type-level assertions below fail compilation if\n * this tuple and the `AppLogEvent` interface disagree in either direction, so\n * adding an interface field forces a matching key here.\n *\n * NOTE: the e2e spec keeps its OWN copy of this set (it can't import the SDK —\n * `@deepspace/e2e` has no `deepspace` dependency), kept in step by a comment,\n * not by these compile-time guards. So this tuple hardens the code copies\n * (deploy-worker/CLI/dashboard, which import it), while the e2e mirror remains a\n * knowingly-accepted duplicate.\n */\nexport const APP_LOG_EVENT_KEYS = [\n 'id',\n 'timestamp',\n 'level',\n 'eventType',\n 'message',\n 'source',\n 'outcome',\n 'request',\n 'exception',\n] as const\n\nexport type AppLogEventKey = (typeof APP_LOG_EVENT_KEYS)[number]\n\n// Compile-time guard: `APP_LOG_EVENT_KEYS` and `keyof AppLogEvent` list the\n// same keys. If either drifts, one of these aliases resolves to `never` and\n// `tsc` errors on the assignment.\ntype _KeysCoverInterface = AppLogEventKey extends keyof AppLogEvent ? true : never\ntype _InterfaceCoversKeys = keyof AppLogEvent extends AppLogEventKey ? true : never\nconst _assertKeysMatch: [_KeysCoverInterface, _InterfaceCoversKeys] = [true, true]\nvoid _assertKeysMatch\n","/**\n * deepspace app usage\n *\n * Shows the logged-in user's credit balance, quota headroom, and\n * per-integration spend — the CLI view of the dashboard's billing page.\n * Agents driving `deepspace integrations invoke` pay per call; this is how they check\n * the balance without a browser.\n *\n * Units: credits are the billing unit (100 credits = $1) and can be\n * fractional. Integration costs come back in USD — the marked-up figures\n * actually deducted from the balance. The balance covers the current\n * billing period; the per-integration table is a fixed 30-day window\n * (server-side).\n *\n * `--json` emits the /api/usage/summary response for scripts, inside the\n * standard `{ ok, … }` envelope.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS, DASHBOARD_URL } from '../env'\nimport { apiFetch } from '../lib/api'\nimport { defineDeepspaceCommand } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\ninterface CreditBucket {\n allocation: number\n used: number\n remaining: number\n}\n\nexport interface UsageSummary {\n credits: {\n credits: number\n totalUsed: number\n totalAllocation: number\n subscription: CreditBucket & { tier: string; renewsAt: string | null }\n bonus: CreditBucket & { expiresAt: string | null; expired: boolean }\n purchased: CreditBucket\n }\n usageByIntegration: { name: string; totalCost: number; count: number }[]\n /** Passed through on --json; not rendered in human output. */\n recentUsage: unknown[]\n}\n\n/**\n * Credits accrue in fractions (a small call can be 0.65 credits). Mirrors\n * the dashboard's CreditsMeter formatting so both surfaces read the same.\n */\nexport function formatCredits(value: number): string {\n if (value > 0 && value < 1) return '<1'\n if (value < 10) return value.toFixed(1).replace(/\\.0$/, '')\n return Math.round(value).toLocaleString('en-US')\n}\n\n/** Integration costs are often sub-cent; show 4 decimals below $0.01. */\nexport function formatUsd(value: number): string {\n return `$${Math.abs(value) >= 0.01 || value === 0 ? value.toFixed(2) : value.toFixed(4)}`\n}\n\n// UTC so the printed date matches the ISO timestamp regardless of the\n// machine's timezone (a midnight-UTC renewal shouldn't shift a day).\nfunction formatDate(iso: string): string {\n return new Date(iso).toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n timeZone: 'UTC',\n })\n}\n\nexport function renderSummary(summary: UsageSummary): string {\n const { credits, usageByIntegration } = summary\n const lines: string[] = []\n\n const renews = credits.subscription.renewsAt\n ? ` · renews ${formatDate(credits.subscription.renewsAt)}`\n : ''\n lines.push(`Plan: ${credits.subscription.tier}${renews}`)\n lines.push(\n `Credits: ${formatCredits(credits.credits)} of ${formatCredits(credits.totalAllocation)} remaining (100 credits = $1)`,\n )\n\n // A bucket breakdown only earns space when a pool beyond the subscription\n // is in play — otherwise it would just repeat the Credits line.\n const bonusActive = credits.bonus.allocation > 0 || credits.bonus.expired\n const purchasedActive = credits.purchased.allocation > 0 || credits.purchased.used > 0\n if (bonusActive || purchasedActive) {\n const bucket = (b: CreditBucket) =>\n `${formatCredits(b.remaining)} of ${formatCredits(b.allocation)} remaining`\n lines.push(` Subscription: ${bucket(credits.subscription)}`)\n if (bonusActive) {\n const expires = credits.bonus.expiresAt\n ? ` · expires ${formatDate(credits.bonus.expiresAt)}`\n : ''\n lines.push(\n ` Bonus: ${credits.bonus.expired ? 'expired' : bucket(credits.bonus) + expires}`,\n )\n }\n if (purchasedActive) {\n lines.push(` Purchased: ${bucket(credits.purchased)}`)\n }\n }\n\n lines.push('')\n if (!usageByIntegration.length) {\n lines.push('No integration usage in the last 30 days.')\n } else {\n lines.push('Usage by integration (last 30 days):')\n const nameWidth = Math.max(11, ...usageByIntegration.map((u) => u.name.length))\n lines.push(`${'INTEGRATION'.padEnd(nameWidth)} CALLS COST`)\n for (const u of usageByIntegration) {\n lines.push(`${u.name.padEnd(nameWidth)} ${String(u.count).padEnd(5)} ${formatUsd(u.totalCost)}`)\n }\n }\n\n lines.push('')\n lines.push(`Dashboard: ${DASHBOARD_URL}`)\n return lines.join('\\n')\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'usage',\n description: 'Show credit balance, quota headroom, and per-integration spend',\n },\n async run({ args }) {\n const token = await ensureToken()\n const summary = await apiFetch<UsageSummary>(API_URL, token, '/api/usage/summary')\n\n if (!args.json) console.log(renderSummary(summary))\n // No `next`: reading the balance is terminal — topping up happens in the\n // dashboard, which the human output already links.\n return { data: { ...summary } }\n },\n})\n","/**\n * deepspace add <feature> [dir]\n *\n * Catalog reads use this running CLI's package. Installation loads the typed\n * installer shipped by the target app's installed DeepSpace version, so an\n * app never receives feature files or manifest rules from a different SDK.\n */\n\nimport { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\nimport {\n featureCatalog,\n featurePackageRoot,\n hasFeatureCatalog,\n installFeature as runningInstaller,\n listFeatureConfigs,\n readFeatureConfig,\n resolveFeatureDestPath,\n suggestFeature,\n type FeatureConfig,\n type FeatureInstallOptions,\n type FeatureInstallOutcome,\n} from './feature-installer'\n\nconst CATEGORY_LABELS: Record<string, string> = {\n assistant: 'AI Features',\n data: 'Data Features',\n nav: 'Navigation',\n layout: 'Layouts',\n display: 'Display',\n landing: 'Landing Page Sections',\n}\nconst CATEGORY_ORDER = ['assistant', 'data', 'nav', 'layout', 'display', 'landing']\n\ninterface FeatureInstallerModule {\n installFeature(options: FeatureInstallOptions): FeatureInstallOutcome\n}\n\nfunction groupByCategory(features: FeatureConfig[]): Map<string, FeatureConfig[]> {\n const groups = new Map<string, FeatureConfig[]>()\n for (const feature of features) {\n const category = feature.category ?? 'other'\n groups.set(category, [...(groups.get(category) ?? []), feature])\n }\n return groups\n}\n\nfunction orderedCategories(groups: Map<string, FeatureConfig[]>): string[] {\n const known = CATEGORY_ORDER.filter((category) => groups.has(category))\n const unknown = [...groups.keys()]\n .filter((category) => !CATEGORY_ORDER.includes(category))\n .sort((a, b) => a.localeCompare(b))\n return [...known, ...unknown]\n}\n\nfunction catalogLines(\n groups: Map<string, FeatureConfig[]>,\n render: (feature: FeatureConfig) => string,\n): string[] {\n const lines: string[] = []\n for (const category of orderedCategories(groups)) {\n const features = groups.get(category)\n if (!features?.length) continue\n lines.push(`${CATEGORY_LABELS[category] ?? category}:`)\n for (const feature of features) lines.push(render(feature))\n lines.push('')\n }\n return lines\n}\n\nexport function renderFeatureHelp(packageRoot: string = featurePackageRoot()): string {\n const groups = groupByCategory(listFeatureConfigs(packageRoot))\n const example = orderedCategories(groups)\n .map((category) => groups.get(category)?.[0]?.id)\n .find(Boolean)\n return [\n '',\n 'Add a feature to your DeepSpace app',\n '',\n 'Usage: deepspace add <feature> [dir]',\n '',\n 'Commands:',\n ' <feature> [dir] Install a feature (dir defaults to .)',\n ' --list, -l List all available features',\n ' --info <feature> Show detailed info about a feature',\n ' --install Run your package manager after adding deps',\n ' --help, -h Show this help',\n '',\n ...catalogLines(groups, (feature) => ` ${feature.id.padEnd(22)} ${feature.name}`),\n 'Examples:',\n ' deepspace add --list',\n ` deepspace add ${example ?? '<feature>'}`,\n ` deepspace add ${example ?? '<feature>'} ./my-app`,\n '',\n ].join('\\n')\n}\n\nexport function renderFeatureList(packageRoot: string = featurePackageRoot()): string {\n const groups = groupByCategory(listFeatureConfigs(packageRoot))\n return [\n '',\n 'Available Features',\n '',\n ...catalogLines(\n groups,\n (feature) =>\n ` ${feature.id.padEnd(22)} ${feature.name.padEnd(24)} ${feature.description ?? ''}`,\n ),\n 'Use: deepspace add <feature>',\n '',\n ].join('\\n')\n}\n\nexport function renderFeatureInfo(config: FeatureConfig): string {\n const lines = ['', `${config.name} (${config.id})`]\n if (config.category) {\n lines.push(` Category: ${CATEGORY_LABELS[config.category] ?? config.category}`)\n }\n lines.push(` ${config.description ?? ''}`, '', ` ${config.details ?? ''}`, '', ' Files:')\n for (const file of config.files) {\n lines.push(` - ${file.src} -> ${resolveFeatureDestPath(file.dest, config.route)}`)\n }\n if (config.instructions?.length) {\n lines.push('', ' Integration steps:')\n config.instructions.forEach((instruction, index) => {\n lines.push(` ${index + 1}. ${instruction}`)\n })\n }\n if (config.patterns?.length) {\n lines.push('', ' Patterns:')\n config.patterns.forEach((pattern) => lines.push(` - ${pattern}`))\n }\n if (config.example) {\n lines.push('', ' Example:')\n config.example.split('\\n').forEach((line) => lines.push(` ${line}`))\n }\n lines.push('')\n return lines.join('\\n')\n}\n\n/** A bare directory is not an install target even if dependency setup happens to exist above it. */\nexport function isDeepSpaceApp(dir: string): boolean {\n if (existsSync(join(dir, 'wrangler.toml'))) return true\n const packagePath = join(dir, 'package.json')\n if (!existsSync(packagePath)) return false\n try {\n const pkg = JSON.parse(readFileSync(packagePath, 'utf-8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n return Boolean(pkg.dependencies?.deepspace || pkg.devDependencies?.deepspace)\n } catch {\n return false\n }\n}\n\n/** Match Node's upward dependency lookup, including DeepSpace worktrees nested in an app. */\nfunction installedPackageRoot(fromDir: string): string | null {\n let dir = fromDir\n for (;;) {\n const candidate = join(dir, 'node_modules', 'deepspace')\n if (existsSync(join(candidate, 'package.json'))) return candidate\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\nasync function targetInstaller(appDir: string): Promise<FeatureInstallerModule> {\n const installedRoot = installedPackageRoot(appDir)\n if (!installedRoot) {\n throw new Refusal(\n \"Could not resolve the app's installed deepspace package. Run your package manager, then retry.\",\n 'feature_installer_missing',\n )\n }\n\n // Tests and source checkouts commonly link this exact package. Avoid asking\n // them for an emitted build entry when the already-loaded typed owner is the\n // same package on disk.\n if (realpathSync(installedRoot) === realpathSync(featurePackageRoot())) {\n return { installFeature: runningInstaller }\n }\n\n const entry = join(installedRoot, 'dist', 'feature-installer.js')\n const catalog = join(installedRoot, 'features')\n if (!existsSync(entry) || !existsSync(catalog)) {\n throw new Refusal(\n \"The app's installed deepspace package does not contain the typed feature installer.\\n\" +\n `Expected: ${entry}\\n` +\n 'Install a current DeepSpace version in the app, then retry.',\n 'feature_installer_missing',\n )\n }\n\n let loaded: Partial<FeatureInstallerModule>\n try {\n loaded = (await import(pathToFileURL(entry).href)) as Partial<FeatureInstallerModule>\n } catch (error) {\n throw new Refusal(\n `Could not load the app's feature installer: ${\n error instanceof Error ? error.message : String(error)\n }`,\n 'feature_installer_invalid',\n )\n }\n if (typeof loaded.installFeature !== 'function') {\n throw new Refusal(`Invalid feature installer entry: ${entry}`, 'feature_installer_invalid')\n }\n return loaded as FeatureInstallerModule\n}\n\nfunction catalogRoot(): string {\n const root = featurePackageRoot()\n if (!hasFeatureCatalog(root)) {\n throw new Refusal(\n 'Could not find the deepspace feature catalog.\\n' +\n 'Reinstall deepspace or run inside a DeepSpace app.',\n 'feature_catalog_missing',\n )\n }\n return root\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'add',\n description: 'Add a feature to your DeepSpace app',\n },\n args: {\n list: {\n type: 'boolean',\n alias: 'l',\n description: 'List available features',\n required: false,\n },\n info: {\n type: 'string',\n description: 'Show details about a feature',\n required: false,\n },\n install: {\n type: 'boolean',\n description: 'Run your package manager after adding dependencies',\n required: false,\n },\n feature: {\n type: 'positional',\n description: 'Feature to install',\n required: false,\n },\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n },\n async run({ args }) {\n const feature = args.feature as string | undefined\n const info = args.info as string | undefined\n\n if (args.list || info || !feature) {\n const root = catalogRoot()\n if (info) {\n const config = readFeatureConfig(info, root)\n if (!config) {\n const suggestion = suggestFeature(info, root)\n throw new Refusal(\n [\n `Unknown feature: ${info}`,\n ...(suggestion ? [`Did you mean \"${suggestion}\"?`] : []),\n 'Run `deepspace add --list` to see available features.',\n ].join('\\n'),\n 'unknown_feature',\n { action: cliAction('deepspace', 'add', '--list') },\n )\n }\n if (!args.json) process.stdout.write(renderFeatureInfo(config))\n return { data: { feature: config } }\n }\n\n if (!args.json) {\n process.stdout.write(args.list ? renderFeatureList(root) : renderFeatureHelp(root))\n }\n return { data: { features: featureCatalog(root) } }\n }\n\n const appDir = resolve((args.dir as string | undefined) ?? '.')\n if (!existsSync(appDir)) {\n throw new Refusal(\n `Target directory not found: ${appDir}\\nCreate a new app first: deepspace app create <name>`,\n 'app_dir_not_found',\n )\n }\n if (!isDeepSpaceApp(appDir)) {\n throw new Refusal(\n `Not a DeepSpace app: ${appDir}\\n` +\n '(no wrangler.toml and no \"deepspace\" dependency found)\\n' +\n 'Create one with: deepspace app create <name>',\n 'not_a_deepspace_app',\n )\n }\n\n ensureInstallReady(appDir)\n const installer = await targetInstaller(appDir)\n let outcome: FeatureInstallOutcome\n try {\n outcome = installer.installFeature({\n feature,\n targetDir: appDir,\n installDependencies: Boolean(args.install),\n ...(!args.json\n ? {\n emit(line: string, stream: 'stdout' | 'stderr' = 'stdout') {\n if (stream === 'stderr') console.error(line)\n else console.log(line)\n },\n }\n : {}),\n })\n } catch (error) {\n throw new Refusal(\n `Installing '${feature}' failed: ${error instanceof Error ? error.message : String(error)}`,\n 'add_failed',\n )\n }\n if (!outcome || typeof outcome.ok !== 'boolean') {\n throw new Refusal(\n \"The app's feature installer returned an invalid result.\",\n 'feature_installer_invalid',\n )\n }\n\n if (!outcome.ok) {\n throw new Refusal(outcome.error, outcome.code, {\n ...('data' in outcome ? { extra: outcome.data } : {}),\n })\n }\n return {\n data: outcome.data,\n ...(outcome.action ? { action: outcome.action } : {}),\n }\n },\n})\n","/**\n * The feature catalog and installer.\n *\n * This is a separate build entry because `add` loads the copy shipped by the\n * target app's installed `deepspace` package. That keeps feature files,\n * manifest interpretation, and mutations on the app-pinned SDK version while\n * leaving the public command/output contract in add.ts.\n */\n\nimport {\n closeSync,\n copyFileSync,\n existsSync,\n fstatSync,\n mkdirSync,\n mkdtempSync,\n openSync,\n readFileSync,\n readSync,\n readdirSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { spawnSync } from 'node:child_process'\nimport { tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { detectPackageManager } from '../lib/package-manager'\n\nconst NAV_MARKER = '// ── Features add nav items below this line ──'\n\ninterface FeatureFile {\n src: string\n dest: string\n overwrite?: boolean\n}\n\ninterface FeatureSchema {\n exportName: string\n importPath: string\n spreadOperator?: boolean\n}\n\ninterface FeatureAction {\n exportName: string\n registerAs: string\n importPath: string\n}\n\nexport interface FeatureConfig {\n id: string\n name: string\n category?: string\n description?: string\n details?: string\n internal?: boolean\n files: FeatureFile[]\n route?: { path?: string; protected?: boolean }\n schema?: FeatureSchema\n actions?: FeatureAction[]\n css?: string[]\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n instructions?: string[]\n patterns?: string[]\n agentNotes?: string[]\n example?: string\n [key: string]: unknown\n}\n\nexport interface FeatureCatalogEntry {\n id: string\n name: string\n category: string | null\n description: string | null\n}\n\ntype DependencySection = 'dependencies' | 'devDependencies'\n\ninterface DependencyAddition {\n name: string\n section: DependencySection\n version: unknown\n}\n\ntype IntegrationArea = 'schema' | 'actions' | 'css' | 'nav'\n\ninterface UnresolvedIntegration {\n area: IntegrationArea\n reason: string\n steps: string[]\n}\n\ninterface InstallData extends Record<string, unknown> {\n feature: string\n dir: string\n installed: boolean\n observedChanges: {\n files: { created: string[]; preexisting: string[]; missing: string[] }\n dependencies: {\n added: DependencyAddition[]\n missingDeclarations: string[]\n installRequested: boolean\n diagnosticTail?: string\n }\n }\n unresolvedIntegrations: UnresolvedIntegration[]\n manifestGuidance: {\n instructions: string[]\n patterns: string[]\n agentNotes: string[]\n }\n}\n\ninterface InstallerAction {\n cwd: string\n argv: string[]\n}\n\nexport type FeatureInstallOutcome =\n | { ok: true; data: InstallData; action?: InstallerAction }\n | {\n ok: false\n code: 'unknown_feature'\n error: string\n data: {\n requestedFeature: string\n suggestedFeature: string | null\n availableFeatures: FeatureCatalogEntry[]\n }\n }\n | {\n ok: false\n code: 'dependency_install_failed' | 'manual_integration_required'\n error: string\n data: InstallData\n }\n\nexport type FeatureInstallerOutput = (line: string, stream?: 'stdout' | 'stderr') => void\n\nexport interface FeatureInstallOptions {\n feature: string\n targetDir: string\n installDependencies: boolean\n emit?: FeatureInstallerOutput\n}\n\n/** Find the package containing this source file or emitted build entry. */\nexport function featurePackageRoot(moduleUrl: string = import.meta.url): string {\n let dir = dirname(fileURLToPath(moduleUrl))\n for (;;) {\n const packagePath = join(dir, 'package.json')\n if (existsSync(packagePath)) {\n try {\n const pkg = JSON.parse(readFileSync(packagePath, 'utf-8')) as { name?: unknown }\n if (pkg.name === 'deepspace') return dir\n } catch {\n // Keep walking: a nearer unrelated package.json is not this package.\n }\n }\n const parent = dirname(dir)\n if (parent === dir) throw new Error('Could not locate the deepspace package root')\n dir = parent\n }\n}\n\nexport function hasFeatureCatalog(packageRoot: string = featurePackageRoot()): boolean {\n return existsSync(join(packageRoot, 'features'))\n}\n\nexport function readFeatureConfig(\n id: string,\n packageRoot: string = featurePackageRoot(),\n): FeatureConfig | null {\n const configPath = join(packageRoot, 'features', id, 'feature.json')\n if (!existsSync(configPath)) return null\n try {\n const config = JSON.parse(readFileSync(configPath, 'utf-8')) as Partial<FeatureConfig>\n if (\n typeof config.id !== 'string' ||\n typeof config.name !== 'string' ||\n !Array.isArray(config.files)\n ) {\n return null\n }\n return config as FeatureConfig\n } catch {\n return null\n }\n}\n\nexport function listFeatureConfigs(packageRoot: string = featurePackageRoot()): FeatureConfig[] {\n const featuresDir = join(packageRoot, 'features')\n if (!existsSync(featuresDir)) return []\n return readdirSync(featuresDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => readFeatureConfig(entry.name, packageRoot))\n .filter((config): config is FeatureConfig => config !== null && !config.internal)\n .sort((a, b) => a.id.localeCompare(b.id))\n}\n\nexport function featureCatalog(packageRoot: string = featurePackageRoot()): FeatureCatalogEntry[] {\n return listFeatureConfigs(packageRoot).map((config) => ({\n id: config.id,\n name: config.name,\n category: config.category ?? null,\n description: config.description ?? null,\n }))\n}\n\nfunction editDistance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, index) => index)\n for (let i = 1; i <= a.length; i++) {\n let previous = row[0]\n row[0] = i\n for (let j = 1; j <= b.length; j++) {\n const current = row[j]\n row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1))\n previous = current\n }\n }\n return row[b.length]\n}\n\nexport function suggestFeature(\n featureId: string,\n packageRoot: string = featurePackageRoot(),\n): string | null {\n let closest: string | null = null\n let closestDistance = Number.POSITIVE_INFINITY\n for (const feature of listFeatureConfigs(packageRoot)) {\n const distance = editDistance(featureId, feature.id)\n if (distance < closestDistance) {\n closest = feature.id\n closestDistance = distance\n }\n }\n const threshold = Math.max(2, Math.floor(featureId.length / 3))\n return closest !== null && closestDistance <= threshold ? closest : null\n}\n\nfunction resolveTargetDir(raw: string): string {\n return isAbsolute(raw) ? raw : resolve(raw)\n}\n\nexport function resolveFeatureDestPath(fileDest: string, route: FeatureConfig['route']): string {\n const pages = 'src/pages/'\n const appPages = 'src/pages/(app)/'\n if (!fileDest.startsWith(pages) || fileDest.startsWith(appPages)) return fileDest\n const rest = fileDest.slice(pages.length)\n return route?.protected === false ? `${appPages}${rest}` : `${appPages}(protected)/${rest}`\n}\n\nfunction copyFile(src: string, dest: string): void {\n mkdirSync(dirname(dest), { recursive: true })\n copyFileSync(src, dest)\n}\n\nfunction copyFileWithImportShift(src: string, dest: string, levels: number): void {\n mkdirSync(dirname(dest), { recursive: true })\n const prefix = '../'.repeat(levels)\n const shifted = readFileSync(src, 'utf-8').replace(\n /(from\\s+|import\\s+|import\\()(['\"])(\\.\\.\\/)/g,\n `$1$2${prefix}$3`,\n )\n writeFileSync(dest, shifted)\n}\n\nfunction installFiles(\n packageRoot: string,\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): {\n copied: number\n skipped: number\n files: { created: string[]; preexisting: string[]; missing: string[] }\n} {\n let copied = 0\n let skipped = 0\n const created: string[] = []\n const preexisting: string[] = []\n const missing: string[] = []\n\n for (const file of config.files) {\n const srcPath = join(packageRoot, 'features', config.id, file.src)\n const resolvedDest = resolveFeatureDestPath(file.dest, config.route)\n const destPath = join(targetDir, resolvedDest)\n const existed = existsSync(destPath)\n if (existed) preexisting.push(resolvedDest)\n\n if (!existsSync(srcPath)) {\n emit(` Warning: source not found: ${file.src}`, 'stderr')\n if (!existed) missing.push(resolvedDest)\n continue\n }\n\n if (existed && !file.overwrite) {\n emit(` Exists (skipped): ${resolvedDest}`)\n skipped++\n continue\n }\n\n const wasRedirected = resolvedDest !== file.dest\n const shiftLevels = resolvedDest.split('/').length - file.dest.split('/').length\n if (wasRedirected) copyFileWithImportShift(srcPath, destPath, shiftLevels)\n else copyFile(srcPath, destPath)\n emit(` ${existed ? 'Overwrote' : 'Copied'}: ${resolvedDest}`)\n if (!existed) created.push(resolvedDest)\n copied++\n }\n\n return { copied, skipped, files: { created, preexisting, missing } }\n}\n\nfunction unresolvedSchema(\n schema: FeatureSchema,\n reason: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration {\n const entry = schema.spreadOperator ? `...${schema.exportName}` : schema.exportName\n emit('')\n emit(' Add manually to src/schemas.ts:')\n emit(` import { ${schema.exportName} } from '${schema.importPath}'`)\n emit(` // then add ${entry} to the schemas array`)\n return {\n area: 'schema',\n reason,\n steps: [\n `Add import { ${schema.exportName} } from '${schema.importPath}' to src/schemas.ts.`,\n `Add ${entry} to the exported schemas array.`,\n ],\n }\n}\n\nfunction integrateSchema(\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration[] {\n if (!config.schema) return []\n const schemasPath = join(targetDir, 'src', 'schemas.ts')\n if (!existsSync(schemasPath)) {\n return [unresolvedSchema(config.schema, 'src/schemas.ts was not found.', emit)]\n }\n\n let content = readFileSync(schemasPath, 'utf-8')\n const { exportName, importPath, spreadOperator } = config.schema\n const importPattern = new RegExp(`^import\\\\s+\\\\{[^}]*\\\\b${exportName}\\\\b`, 'm')\n if (importPattern.test(content)) {\n emit(` Schema already present: ${exportName}`)\n return []\n }\n if (\n !content.includes('export const schemas') ||\n !/export const schemas:\\s*CollectionSchema\\[\\]\\s*=\\s*\\[/.test(content)\n ) {\n const reason = 'src/schemas.ts has an unexpected structure.'\n emit(` Could not auto-integrate schema (${reason})`)\n return [unresolvedSchema(config.schema, reason, emit)]\n }\n\n const importLine = `import { ${exportName} } from '${importPath}'`\n const withImport = content.replace(\n /export const schemas/,\n `${importLine}\\n\\nexport const schemas`,\n )\n const schemaEntry = spreadOperator ? `...${exportName}` : exportName\n const withEntry = withImport.replace(\n /export const schemas:\\s*CollectionSchema\\[\\]\\s*=\\s*\\[/,\n `export const schemas: CollectionSchema[] = [\\n ${schemaEntry},`,\n )\n if (withImport === content || withEntry === withImport) {\n const reason = 'src/schemas.ts could not be updated safely.'\n emit(` Could not auto-integrate schema (${reason})`)\n return [unresolvedSchema(config.schema, reason, emit)]\n }\n content = withEntry\n writeFileSync(schemasPath, content)\n emit(` Schema integrated: ${exportName} -> schemas.ts`)\n return []\n}\n\nfunction unresolvedActions(\n actions: FeatureAction[],\n reason: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration {\n emit('')\n emit(' Add manually to src/actions/index.ts:')\n for (const action of actions) {\n emit(` import { ${action.exportName} } from '${action.importPath}'`)\n emit(` // then add '${action.registerAs}': ${action.exportName} to the actions object`)\n }\n return {\n area: 'actions',\n reason,\n steps: actions.flatMap((action) => [\n `Add import { ${action.exportName} } from '${action.importPath}' to src/actions/index.ts.`,\n `Register '${action.registerAs}': ${action.exportName} in the exported actions object.`,\n ]),\n }\n}\n\nfunction integrateActions(\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration[] {\n if (!config.actions?.length) return []\n const actionsPath = join(targetDir, 'src', 'actions', 'index.ts')\n if (!existsSync(actionsPath)) {\n return [unresolvedActions(config.actions, 'src/actions/index.ts was not found.', emit)]\n }\n\n let content = readFileSync(actionsPath, 'utf-8')\n const registryPattern =\n /export const actions:\\s*Record<string,\\s*ActionHandler(?:<[^>]*>)?>\\s*=\\s*\\{/\n if (!registryPattern.test(content)) {\n const reason = 'src/actions/index.ts has an unexpected structure.'\n emit(` Could not auto-integrate actions (${reason})`)\n return [unresolvedActions(config.actions, reason, emit)]\n }\n\n let integrated = 0\n const unresolved: UnresolvedIntegration[] = []\n for (const action of config.actions) {\n const importPattern = new RegExp(`^import\\\\s+\\\\{[^}]*\\\\b${action.exportName}\\\\b`, 'm')\n if (importPattern.test(content)) {\n emit(` Action already present: ${action.registerAs}`)\n continue\n }\n const importLine = `import { ${action.exportName} } from '${action.importPath}'`\n const withImport = content.replace(\n /export const actions:/,\n `${importLine}\\n\\nexport const actions:`,\n )\n const registryEntry = ` '${action.registerAs}': ${action.exportName},`\n const withEntry = withImport.replace(registryPattern, (match) => `${match}\\n${registryEntry}`)\n if (withImport === content || withEntry === withImport) {\n emit(` Could not integrate action: ${action.registerAs}`)\n unresolved.push(\n unresolvedActions(\n [action],\n `Action '${action.registerAs}' could not be registered safely.`,\n emit,\n ),\n )\n continue\n }\n content = withEntry\n integrated++\n emit(` Action integrated: ${action.registerAs} (${action.exportName})`)\n }\n if (integrated > 0) writeFileSync(actionsPath, content)\n return unresolved\n}\n\nfunction integrateCss(\n packageRoot: string,\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration[] {\n if (!config.css?.length) return []\n const stylesPath = join(targetDir, 'src', 'styles.css')\n if (!existsSync(stylesPath)) {\n emit(' Warning: Cannot integrate CSS — src/styles.css not found')\n return [\n {\n area: 'css',\n reason: 'src/styles.css was not found.',\n steps: config.css.map(\n (cssFile) =>\n `Append node_modules/deepspace/features/${config.id}/${cssFile} to src/styles.css.`,\n ),\n },\n ]\n }\n\n let styles = readFileSync(stylesPath, 'utf-8')\n let integrated = 0\n const unresolved: UnresolvedIntegration[] = []\n for (const cssFile of config.css) {\n const srcPath = join(packageRoot, 'features', config.id, cssFile)\n if (!existsSync(srcPath)) {\n emit(` Warning: CSS source not found: ${cssFile}`, 'stderr')\n unresolved.push({\n area: 'css',\n reason: `Feature CSS source '${cssFile}' was not found in the installed package.`,\n steps: ['Reinstall the current deepspace package, then retry this feature installation.'],\n })\n continue\n }\n const css = readFileSync(srcPath, 'utf-8')\n const fingerprint = css.match(/\\.([\\w-]+)\\s*\\{|@keyframes\\s+([\\w-]+)/)\n const marker = fingerprint?.[1] ?? fingerprint?.[2]\n if (marker && styles.includes(marker)) {\n emit(` CSS already present: ${cssFile} (found .${marker})`)\n continue\n }\n styles += `\\n${css}`\n integrated++\n emit(` CSS integrated: ${cssFile} -> styles.css`)\n }\n if (integrated > 0) writeFileSync(stylesPath, styles)\n return unresolved\n}\n\nfunction unresolvedRoute(\n route: NonNullable<FeatureConfig['route']>,\n config: FeatureConfig,\n reason: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration {\n emit('')\n emit(' Add manually to src/nav.ts:')\n emit(` { path: '${route.path}', label: '${config.name}' },`)\n return {\n area: 'nav',\n reason,\n steps: [`Add { path: '${route.path}', label: '${config.name}' } to the exported nav array.`],\n }\n}\n\nfunction integrateRoute(\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration[] {\n if (!config.route) return []\n const navPath = join(targetDir, 'src', 'nav.ts')\n if (!existsSync(navPath)) {\n return [unresolvedRoute(config.route, config, 'src/nav.ts was not found.', emit)]\n }\n let content = readFileSync(navPath, 'utf-8')\n const routePath = config.route.path\n if (content.includes(`'${routePath}'`)) {\n emit(` Nav already present: ${routePath}`)\n return []\n }\n if (!content.includes(NAV_MARKER)) {\n emit(' Could not auto-wire nav (marker not found in nav.ts)')\n return [\n unresolvedRoute(\n config.route,\n config,\n 'The feature insertion marker was not found in src/nav.ts.',\n emit,\n ),\n ]\n }\n const roles = config.route.protected === false ? '' : \", roles: ['member' as Role]\"\n const entry = ` { path: '${routePath}', label: '${config.name}'${roles} },`\n content = content.replace(NAV_MARKER, `${NAV_MARKER}\\n${entry}`)\n writeFileSync(navPath, content)\n emit(` Nav wired: ${routePath} (${config.name})`)\n emit(' Route: automatic (file-based routing via src/pages/)')\n return []\n}\n\nconst INSTALL_DIAGNOSTIC_BYTES = 16 * 1024\n\ninterface PackageInstallRun {\n error?: Error\n status: number | null\n diagnosticTail?: string\n}\n\nfunction readDiagnosticTail(outputFd: number): string | undefined {\n const size = fstatSync(outputFd).size\n if (size === 0) return undefined\n const length = Math.min(size, INSTALL_DIAGNOSTIC_BYTES)\n const buffer = Buffer.alloc(length)\n readSync(outputFd, buffer, 0, length, size - length)\n const tail = buffer.toString('utf-8').trim()\n if (!tail) return undefined\n return size > length ? `[last ${length} bytes]\\n${tail}` : tail\n}\n\nfunction runPackageInstall(\n packageManager: string,\n targetDir: string,\n outputVisible: boolean,\n): PackageInstallRun {\n const options = {\n cwd: targetDir,\n shell: process.platform === 'win32',\n }\n if (outputVisible) {\n const child = spawnSync(packageManager, ['install'], { ...options, stdio: 'inherit' })\n return { error: child.error, status: child.status }\n }\n\n // Keep stdout reserved for the command's one-line JSON envelope. Both child\n // streams share a temporary file, then only a fixed-size tail enters memory.\n const captureDir = mkdtempSync(join(tmpdir(), 'deepspace-add-install-'))\n let outputFd: number | undefined\n try {\n outputFd = openSync(join(captureDir, 'output.log'), 'w+')\n const child = spawnSync(packageManager, ['install'], {\n ...options,\n stdio: ['ignore', outputFd, outputFd],\n })\n return {\n error: child.error,\n status: child.status,\n diagnosticTail: readDiagnosticTail(outputFd),\n }\n } finally {\n if (outputFd !== undefined) closeSync(outputFd)\n rmSync(captureDir, { recursive: true, force: true })\n }\n}\n\nfunction integrateDependencies(\n config: FeatureConfig,\n targetDir: string,\n runInstall: boolean,\n outputVisible: boolean,\n emit: FeatureInstallerOutput,\n): {\n added: DependencyAddition[]\n installRan: boolean\n installError?: string\n diagnosticTail?: string\n packageManager: string\n} {\n const packageManager = detectPackageManager(targetDir)\n const declarations: Array<{\n section: DependencySection\n values: Record<string, string> | undefined\n }> = [\n { section: 'dependencies', values: config.dependencies },\n { section: 'devDependencies', values: config.devDependencies },\n ]\n if (declarations.every(({ values }) => !values || Object.keys(values).length === 0)) {\n return { added: [], installRan: false, packageManager }\n }\n\n const packagePath = join(targetDir, 'package.json')\n if (!existsSync(packagePath)) {\n emit(' Could not patch package.json (file not found)')\n return { added: [], installRan: false, packageManager }\n }\n\n let pkg: Record<string, unknown> & {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n }\n try {\n pkg = JSON.parse(readFileSync(packagePath, 'utf-8')) as typeof pkg\n } catch (error) {\n emit(\n ` Could not patch package.json (parse error: ${error instanceof Error ? error.message : String(error)})`,\n )\n return { added: [], installRan: false, packageManager }\n }\n\n const added: DependencyAddition[] = []\n const skipped: string[] = []\n for (const { section, values } of declarations) {\n if (!values) continue\n pkg[section] ??= {}\n for (const [name, version] of Object.entries(values)) {\n if (pkg.dependencies?.[name] || pkg.devDependencies?.[name]) {\n if (!added.some((dependency) => dependency.name === name)) skipped.push(name)\n continue\n }\n pkg[section]![name] = version\n added.push({ name, section, version })\n }\n }\n\n if (added.length === 0) {\n emit(' Dependencies already present')\n } else {\n writeFileSync(packagePath, `${JSON.stringify(pkg, null, 2)}\\n`, 'utf-8')\n emit(` Added to package.json: ${added.map(({ name }) => name).join(', ')}`)\n if (skipped.length) emit(` Already present (kept your version): ${skipped.join(', ')}`)\n }\n\n if (!runInstall) return { added, installRan: false, packageManager }\n emit('')\n emit(` Installing dependencies with ${packageManager}...`)\n const child = runPackageInstall(packageManager, targetDir, outputVisible)\n if (child.error) {\n const error = child.error as NodeJS.ErrnoException\n const reason = error.code === 'ENOENT' ? `${packageManager} not found on PATH` : error.message\n return {\n added,\n installRan: false,\n installError: `Could not launch ${packageManager} (${reason}).`,\n diagnosticTail: child.diagnosticTail,\n packageManager,\n }\n }\n if (child.status !== 0) {\n const diagnostic = child.diagnosticTail ? `\\nDiagnostic tail:\\n${child.diagnosticTail}` : ''\n return {\n added,\n installRan: false,\n installError: `${packageManager} install did not complete (exit ${child.status ?? 'unknown'}).${diagnostic}`,\n diagnosticTail: child.diagnosticTail,\n packageManager,\n }\n }\n return { added, installRan: true, packageManager }\n}\n\nfunction dependencySnapshot(targetDir: string): {\n dependencies: Record<string, unknown>\n devDependencies: Record<string, unknown>\n} {\n try {\n const pkg = JSON.parse(readFileSync(join(targetDir, 'package.json'), 'utf-8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n return {\n dependencies: pkg.dependencies ?? {},\n devDependencies: pkg.devDependencies ?? {},\n }\n } catch {\n return { dependencies: {}, devDependencies: {} }\n }\n}\n\nfunction installedNavFeatures(packageRoot: string, targetDir: string): string[] {\n return listFeatureConfigs(packageRoot)\n .filter((feature) => feature.category === 'nav' && feature.files.length > 0)\n .filter((feature) => {\n const signature = resolveFeatureDestPath(feature.files[0].dest, feature.route)\n return existsSync(join(targetDir, signature))\n })\n .map((feature) => feature.id)\n}\n\nfunction warnNavConflicts(\n packageRoot: string,\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): void {\n if (config.category !== 'nav') return\n const present = installedNavFeatures(packageRoot, targetDir)\n if (present.length <= 1) return\n emit('')\n emit(`⚠ Multiple navigation features present (${present.join(', ')}).`)\n emit(' sidebar, topbar, and tree are mutually exclusive — keep one and remove the')\n emit(' others to avoid competing navigation in your layout.')\n}\n\nexport function installFeature(options: FeatureInstallOptions): FeatureInstallOutcome {\n const packageRoot = featurePackageRoot()\n const targetDir = resolveTargetDir(options.targetDir)\n const config = readFeatureConfig(options.feature, packageRoot)\n if (!config) {\n const suggestion = suggestFeature(options.feature, packageRoot)\n return {\n ok: false,\n code: 'unknown_feature',\n error: [\n `Unknown feature: ${options.feature}`,\n ...(suggestion ? [`Did you mean \"${suggestion}\"?`] : []),\n ].join('\\n'),\n data: {\n requestedFeature: options.feature,\n suggestedFeature: suggestion,\n availableFeatures: featureCatalog(packageRoot),\n },\n }\n }\n\n const emit: FeatureInstallerOutput = options.emit ?? (() => undefined)\n emit('')\n emit(`Installing: ${config.name}`)\n emit(` ${config.description ?? ''}`)\n emit(` Target: ${targetDir}`)\n\n const installedFiles = installFiles(packageRoot, config, targetDir, emit)\n emit('')\n emit(\n `Copied ${installedFiles.copied} file(s)${\n installedFiles.skipped > 0 ? `, skipped ${installedFiles.skipped} existing` : ''\n }`,\n )\n\n const unresolvedIntegrations = [\n ...integrateSchema(config, targetDir, emit),\n ...integrateActions(config, targetDir, emit),\n ...integrateCss(packageRoot, config, targetDir, emit),\n ...integrateRoute(config, targetDir, emit),\n ]\n const dependencyResult = integrateDependencies(\n config,\n targetDir,\n options.installDependencies,\n options.emit !== undefined,\n emit,\n )\n\n if (config.instructions?.length) {\n emit('')\n emit('--- Manual wiring needed ---')\n emit('')\n config.instructions.forEach((instruction, index) => {\n emit(`${index + 1}. ${instruction}`)\n emit('')\n })\n }\n if (config.patterns?.length) {\n emit('--- Key patterns ---')\n emit('')\n config.patterns.forEach((pattern) => emit(`- ${pattern}`))\n emit('')\n }\n warnNavConflicts(packageRoot, config, targetDir, emit)\n\n const dependenciesAfter = dependencySnapshot(targetDir)\n const declaredDependencies = [\n ...Object.keys(config.dependencies ?? {}),\n ...Object.keys(config.devDependencies ?? {}),\n ]\n const missingDeclarations = declaredDependencies.filter(\n (name) =>\n !(name in dependenciesAfter.dependencies) && !(name in dependenciesAfter.devDependencies),\n )\n const installed =\n installedFiles.files.missing.length === 0 &&\n missingDeclarations.length === 0 &&\n unresolvedIntegrations.length === 0 &&\n dependencyResult.installError === undefined\n const dependencyInstallRequired =\n installed &&\n dependencyResult.added.length > 0 &&\n !options.installDependencies &&\n !dependencyResult.installRan\n\n const data: InstallData = {\n feature: config.id,\n dir: targetDir,\n installed,\n observedChanges: {\n files: installedFiles.files,\n dependencies: {\n added: dependencyResult.added,\n missingDeclarations,\n installRequested: options.installDependencies,\n ...(dependencyResult.diagnosticTail\n ? { diagnosticTail: dependencyResult.diagnosticTail }\n : {}),\n },\n },\n unresolvedIntegrations,\n manifestGuidance: {\n instructions: config.instructions ?? [],\n patterns: config.patterns ?? [],\n agentNotes: config.agentNotes ?? [],\n },\n }\n if (dependencyResult.installError) {\n return {\n ok: false,\n code: 'dependency_install_failed',\n error: dependencyResult.installError,\n data,\n }\n }\n if (unresolvedIntegrations.length > 0) {\n const count = unresolvedIntegrations.length\n return {\n ok: false,\n code: 'manual_integration_required',\n error: `${count} app integration${count === 1 ? '' : 's'} require manual completion. Follow the unresolved integration steps, then run your checks.`,\n data,\n }\n }\n\n return {\n ok: true,\n data,\n ...(dependencyInstallRequired\n ? {\n action: {\n cwd: targetDir,\n argv: [dependencyResult.packageManager, 'install'],\n },\n }\n : {}),\n }\n}\n","/**\n * deepspace app domain — purchase and manage custom domains for your apps.\n *\n * Designed to be both human-friendly and agent/script-friendly:\n * - All destructive commands accept `--yes` to skip prompts.\n * - `--json` (injected by the command runtime) gives every subcommand a\n * single-line `{ ok, … }` document on stdout.\n * - `--app` accepts an app id or live name and defaults to the cwd's app id.\n * - `domain buy` opens Stripe Checkout in a browser and polls until live;\n * pass `--no-open` to print the URL only, `--no-wait` to skip polling.\n *\n * Subcommands:\n * search <query> — find available domains and prices\n * buy <domain> — buy a domain via Stripe Checkout (browser)\n * list — list domains you own\n * status <domain> — detail view for one domain\n * attach <domain> — re-point a domain at a different app\n * detach <domain> — stop routing the domain (keeps registration)\n * renew <domain> --auto X — toggle auto-renew on/off at the registrar\n *\n * Defined with the command runtime (lib/command.ts). Two deviations fixed\n * here: `buy --json` used to emit TWO JSON documents (the checkout session,\n * then the provisioning outcome), and the confirmation prompts in `buy` and\n * `detach` would hang a `--json` caller. See each subcommand.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { apiFetch } from '../lib/api'\nimport { openBrowser } from '../lib/open-browser'\nimport { resolveAppTarget } from '../lib/app-target'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\ninterface SearchResult {\n name: string\n registrable: boolean\n registrar?: 'cloudflare' | 'namesilo'\n pricing?: { currency: string; registrationCost: string; renewalCost: string }\n registrationCost?: number\n renewalCost?: number\n chargedCents?: number | null\n costCents?: number | null\n reason?: string\n premium?: boolean\n}\n\ninterface DomainPurchase {\n id: string\n domain: string\n appId: string\n status: string\n statusError?: string | null\n registeredAt?: string | null\n expiresAt?: string | null\n chargedCents: number\n autoRenew: boolean\n registrar: string\n}\n\nconst api = <T>(token: string, path: string, init?: RequestInit): Promise<T> =>\n apiFetch<T>(API_URL, token, path, init)\n\n/**\n * Strip internal-only pricing fields from any value before emitting it to\n * stdout. The api-worker exposes both the user-facing `chargedCents` and the\n * platform's at-cost `costCents`; only the former should reach the CLI user.\n */\nfunction scrubInternal<T>(value: T): T {\n if (Array.isArray(value)) return value.map(scrubInternal) as unknown as T\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (k === 'costCents') continue\n out[k] = scrubInternal(v)\n }\n return out as T\n }\n return value\n}\n\nfunction fmtCents(cents: number | null | undefined): string {\n if (cents === null || cents === undefined) return '—'\n return `$${(cents / 100).toFixed(2)}`\n}\n\nfunction fmtDate(iso: string | null | undefined): string {\n if (!iso) return '—'\n return iso.slice(0, 10)\n}\n\n/**\n * Plain stdin Y/N prompt — no clack. Only ever reached on the interactive\n * human path: callers refuse with `confirmation_required` when there is no\n * TTY or `--json` is set, so a prompt can never hang a machine caller.\n */\nasync function confirm(message: string): Promise<boolean> {\n process.stdout.write(`${message} [y/N] `)\n return new Promise((resolve) => {\n process.stdin.setEncoding('utf-8')\n process.stdin.once('data', (data) => {\n const answer = data.toString().trim().toLowerCase()\n resolve(answer === 'y' || answer === 'yes')\n })\n })\n}\n\n/** True when asking a question would hang the caller (agent, pipe, `--json`). */\nconst cannotPrompt = (json: boolean): boolean => json || !process.stdin.isTTY\n\n// ============================================================================\n// search\n// ============================================================================\n\nconst search = defineDeepspaceCommand({\n meta: { name: 'search', description: 'Search for available domains' },\n args: {\n query: { type: 'positional', description: 'Domain or keyword', required: true },\n limit: { type: 'string', description: 'Max results (default 10)', default: '10' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const limit = parseInt(String(args.limit ?? '10'), 10) || 10\n const result = await api<{ domains: SearchResult[] }>(\n token,\n `/api/domains/search?q=${encodeURIComponent(String(args.query))}&limit=${limit}`,\n )\n const scrubbed = scrubInternal(result)\n if (!args.json) {\n if (result.domains.length === 0) {\n console.log('No matches.')\n } else {\n for (const d of result.domains) {\n const tag = d.registrable ? '✓' : '✗'\n const price = d.registrable ? `${fmtCents(d.chargedCents)}/yr` : (d.reason ?? '—')\n // Annotate slow-path TLDs so users have realistic expectations.\n const slowFlag =\n d.registrar && d.registrar !== 'cloudflare' ? ' (15-60 min provisioning)' : ''\n console.log(`${tag} ${d.name.padEnd(40)} ${price}${slowFlag}`)\n }\n }\n }\n return { data: { domains: scrubbed.domains } }\n },\n})\n\n// ============================================================================\n// buy\n// ============================================================================\n\nconst buy = defineDeepspaceCommand({\n meta: { name: 'buy', description: 'Buy a domain and attach it to an app' },\n args: {\n domain: { type: 'positional', description: 'Domain to buy', required: true },\n app: { type: 'string', description: 'App id or live name (defaults to ./wrangler.toml)' },\n yes: { type: 'boolean', description: 'Skip the confirmation prompt', default: false },\n open: {\n type: 'boolean',\n description: 'Open browser at Stripe URL (use --no-open to print URL only)',\n default: true,\n },\n wait: {\n type: 'boolean',\n description:\n 'Poll until provisioning completes (use --no-wait to exit after session creation). ' +\n 'Implicitly off under --json, whose single document is the checkout session.',\n default: true,\n },\n },\n async run({ args }) {\n const domain = String(args.domain)\n const token = await ensureToken()\n const appId = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n\n // Re-check pricing\n const priceCheck = await api<{ domains: SearchResult[] }>(token, '/api/domains/check', {\n method: 'POST',\n body: JSON.stringify({ domains: [domain] }),\n })\n const result = priceCheck.domains[0]\n if (!result || !result.registrable) {\n throw new Refusal(`Not available: ${result?.reason ?? 'unknown'}`, 'domain_not_available', {\n action: cliAction('deepspace', 'app', 'domain', 'search', domain),\n })\n }\n\n const price = fmtCents(result.chargedCents)\n // Provisioning time depends on registrar:\n // CF Registrar (.com/.dev/.app/.xyz/etc): ~60-90s — registry publishes\n // CF nameservers atomically with registration.\n // Porkbun fallback (.ai/.io/.me/.co/etc + ccTLDs): 15-60 min — depends\n // on the destination registry (Verisign/.me, NIC.AI, etc) batch-\n // publishing our NS records to public DNS. The platform side is\n // done in <30s; the wait is registry-side.\n const expectedTime =\n result.registrar === 'cloudflare'\n ? '~60-90 seconds'\n : '15-60 minutes (registry NS propagation)'\n\n if (!args.yes) {\n // A purchase is irreversible, so it must be confirmed — but a prompt\n // would hang an agent or a `--json` caller. Refuse and name the flag.\n if (cannotPrompt(args.json)) {\n throw new Refusal(\n `Buying ${domain} for ${price}/yr (auto-renews; non-refundable) and attaching it to ` +\n `${appId} needs confirmation. Provisioning takes ${expectedTime}. Re-run with --yes.`,\n 'confirmation_required',\n )\n }\n const ok = await confirm(\n `Buy ${domain} for ${price}/yr (auto-renews; non-refundable), attach to ${appId}? Provisioning takes ${expectedTime}.`,\n )\n if (!ok) {\n console.log('Cancelled.')\n return { data: { domain, cancelled: true } }\n }\n }\n\n const checkout = await api<{\n purchaseId: string\n sessionId: string\n url: string\n chargedCents: number\n }>(token, '/api/domains/checkout', {\n method: 'POST',\n body: JSON.stringify({ domain, appId }),\n })\n\n if (!args.json) console.log(`Stripe Checkout: ${checkout.url}`)\n\n if (args.open && process.stdin.isTTY) {\n openBrowser(checkout.url)\n }\n\n // ONE document under --json. The checkout URL is the actionable outcome\n // and the caller needs it NOW (it has to be paid before provisioning even\n // starts) — so `--json` never polls; it returns the session and points at\n // `domain status` for the result. The human path keeps the live progress.\n if (!args.wait || args.json) {\n return {\n data: scrubInternal({ ...checkout, expectedTime, registrar: result.registrar, domain }),\n action: cliAction('deepspace', 'app', 'domain', 'status', domain),\n }\n }\n\n // Poll until active or failed.\n // Timeout depends on registrar — CF can take 5 min worst case, Porkbun\n // up to 60 min for slow registries. User can Ctrl-C and resume polling\n // later via `deepspace app domain status <domain>` — provisioning runs\n // server-side regardless.\n const timeoutMs = result.registrar === 'cloudflare' ? 5 * 60 * 1000 : 60 * 60 * 1000\n console.log(\n `Waiting for payment & provisioning (up to ${expectedTime}). Press Ctrl-C anytime —`,\n )\n console.log(\n `provisioning continues server-side; check later with \\`deepspace app domain status ${domain}\\`.`,\n )\n const deadline = Date.now() + timeoutMs\n let lastStatus = ''\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 5000))\n try {\n const detail = await api<{ domain: DomainPurchase }>(\n token,\n `/api/domains/${checkout.purchaseId}`,\n )\n if (detail.domain.status !== lastStatus) {\n lastStatus = detail.domain.status\n console.log(` → ${lastStatus}`)\n }\n if (detail.domain.status === 'active') {\n console.log(`✓ ${domain} is live and pointing at ${appId}`)\n return {\n data: scrubInternal({ ...checkout, status: 'active', domain, appId }),\n }\n }\n if (detail.domain.status.startsWith('failed:')) {\n throw new Refusal(\n `Provisioning failed: ${detail.domain.statusError ?? detail.domain.status}`,\n 'provisioning_failed',\n { action: cliAction('deepspace', 'app', 'domain', 'status', domain) },\n )\n }\n } catch (err) {\n if (err instanceof Refusal) throw err\n // Transient — keep polling\n console.error(`(poll error: ${err instanceof Error ? err.message : String(err)})`)\n }\n }\n throw new Refusal(\n `Polling timed out. Provisioning may still be in progress; check with: deepspace app domain status ${domain}`,\n 'provisioning_timeout',\n { action: cliAction('deepspace', 'app', 'domain', 'status', domain) },\n )\n },\n})\n\n// ============================================================================\n// list\n// ============================================================================\n\nconst list = defineDeepspaceCommand({\n meta: { name: 'list', description: 'List your domains' },\n async run({ args }) {\n const token = await ensureToken()\n const result = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const scrubbed = scrubInternal(result)\n if (result.domains.length === 0) {\n if (!args.json) console.log('No domains. Try `deepspace app domain search <name>`.')\n return { data: { domains: scrubbed.domains } }\n }\n if (!args.json) {\n console.log(\n `DOMAIN APP STATUS EXPIRES AUTO-RENEW`,\n )\n for (const d of result.domains) {\n console.log(\n `${d.domain.padEnd(35)} ${d.appId.padEnd(20)} ${d.status.padEnd(20)} ${fmtDate(d.expiresAt).padEnd(12)} ${d.autoRenew ? 'on' : 'off'}`,\n )\n }\n }\n return { data: { domains: scrubbed.domains } }\n },\n})\n\n// ============================================================================\n// status\n// ============================================================================\n\n/** The caller's domain, or a coded refusal naming how to list them. */\nasync function requireDomain(token: string, domain: string): Promise<DomainPurchase> {\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === domain)\n if (!found) {\n throw new Refusal(`No domain ${domain} in your account`, 'domain_not_found', {\n action: cliAction('deepspace', 'app', 'domain', 'list'),\n })\n }\n return found\n}\n\nconst status = defineDeepspaceCommand({\n meta: { name: 'status', description: 'Show details for one domain' },\n args: {\n domain: { type: 'positional', description: 'Domain', required: true },\n },\n async run({ args }) {\n const token = await ensureToken()\n const found = await requireDomain(token, String(args.domain))\n if (!args.json) {\n console.log(`Domain: ${found.domain}`)\n console.log(\n `Status: ${found.status}${found.statusError ? ` (${found.statusError})` : ''}`,\n )\n console.log(`Attached app: ${found.appId}`)\n console.log(`Registrar: ${found.registrar}`)\n console.log(`Registered: ${fmtDate(found.registeredAt)}`)\n console.log(`Expires: ${fmtDate(found.expiresAt)}`)\n console.log(`Auto-renew: ${found.autoRenew ? 'on' : 'off'}`)\n console.log(`Charged: ${fmtCents(found.chargedCents)}/yr`)\n }\n return { data: scrubInternal({ ...found }) }\n },\n})\n\n// ============================================================================\n// attach\n// ============================================================================\n\nconst attach = defineDeepspaceCommand({\n meta: { name: 'attach', description: 'Re-point a domain at a different app' },\n args: {\n domain: { type: 'positional', description: 'Domain to re-point', required: true },\n app: { type: 'string', description: 'Target app id or live name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const domain = String(args.domain)\n const token = await ensureToken()\n const targetAppId = await resolveAppTarget(\n DEPLOY_URL,\n token,\n args.app as string | undefined,\n )\n const found = await requireDomain(token, domain)\n const result = await api<{ success: boolean; appId: string }>(\n token,\n `/api/domains/${found.id}/reattach`,\n {\n method: 'POST',\n body: JSON.stringify({ appId: targetAppId }),\n },\n )\n if (!args.json) console.log(`✓ ${domain} now points at ${targetAppId}`)\n // `success` is dropped: the envelope's `ok` already carries it.\n return { data: { domain, appId: result.appId } }\n },\n})\n\n// ============================================================================\n// detach\n// ============================================================================\n\nconst detach = defineDeepspaceCommand({\n meta: {\n name: 'detach',\n description: 'Stop routing the domain (keeps the registration; auto-renew unchanged)',\n },\n args: {\n domain: { type: 'positional', description: 'Domain to detach', required: true },\n yes: { type: 'boolean', description: 'Skip the confirmation prompt' },\n },\n async run({ args }) {\n const domain = String(args.domain)\n const token = await ensureToken()\n const found = await requireDomain(token, domain)\n if (!args.yes) {\n if (cannotPrompt(args.json)) {\n throw new Refusal(\n `Detaching ${domain} stops routing (the domain stays registered; auto-renew is ` +\n 'unchanged) and needs confirmation. Re-run with --yes.',\n 'confirmation_required',\n )\n }\n const ok = await confirm(\n `Detach ${domain}? Routing will stop; the domain stays registered (auto-renew is unchanged).`,\n )\n if (!ok) {\n console.log('Cancelled.')\n return { data: { domain, cancelled: true } }\n }\n }\n await api(token, `/api/domains/${found.id}`, { method: 'DELETE' })\n if (!args.json) {\n console.log(\n `✓ ${domain} detached. Use \\`deepspace app domain attach\\` to re-route, or \\`renew --auto off\\` to stop auto-renewal.`,\n )\n }\n return { data: { domain, detached: true } }\n },\n})\n\n// ============================================================================\n// renew\n// ============================================================================\n\nconst renew = defineDeepspaceCommand({\n meta: { name: 'renew', description: 'Toggle auto-renewal at the registrar' },\n args: {\n domain: { type: 'positional', description: 'Domain', required: true },\n auto: { type: 'string', description: '\"on\" or \"off\"', required: true },\n },\n async run({ args }) {\n const domain = String(args.domain)\n if (args.auto !== 'on' && args.auto !== 'off') {\n throw new Refusal('--auto must be \"on\" or \"off\"', 'invalid_auto')\n }\n const token = await ensureToken()\n const found = await requireDomain(token, domain)\n const enabled = args.auto === 'on'\n await api(token, `/api/domains/${found.id}/auto-renew`, {\n method: 'POST',\n body: JSON.stringify({ autoRenew: enabled }),\n })\n if (!args.json) console.log(`✓ ${domain} auto-renew ${enabled ? 'enabled' : 'disabled'}`)\n // Terminal toggle: nothing follows.\n return { data: { domain, autoRenew: enabled } }\n },\n})\n\n// ============================================================================\n// Top-level\n// ============================================================================\n\n// Note: no `run()` on the parent — citty otherwise calls it after every\n// subcommand finishes, which prints spurious help text.\n//\nexport default defineCommand({\n meta: { name: 'domain', description: 'Buy and manage custom domains' },\n subCommands: { search, buy, list, status, attach, detach, renew },\n})\n","/**\n * Manage app collaborators: users you authorize to deploy your app on your\n * behalf. A collaborator just runs `deepspace deploy`; the deploy keeps your\n * identity and billing. Collaborators have owner-equivalent deploy access, so\n * only add people you trust.\n *\n * Defined with the command runtime (lib/command.ts): `--json` (now a\n * single-line `{ ok, … }` envelope instead of each subcommand's own\n * pretty-printed blob), the slug, the `Next:` line and the exit codes come\n * from there. No subcommand prompts — `remove`/`cancel` refuse an unknown\n * target rather than asking.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { resolveAppTarget } from '../lib/app-target'\nimport { apiFetch } from '../lib/api'\nimport { isTestAccountEmail } from '../../server/auth/testAccounts'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\ninterface Collaborator {\n userId: string\n emailDisplay: string\n createdAt: string | number\n}\n\ninterface PendingInvite {\n email: string\n /** Epoch milliseconds. */\n expiresAt: number\n invitedAt: number\n}\n\ntype AddResponse =\n | { status: 'added'; collaborator: Collaborator }\n | { status: 'invited'; email: string; token: string; expiresAt: number }\n // A live invite already existed → the server did NOT re-charge or re-send.\n | { status: 'already_invited'; email: string; token: string; expiresAt: number }\n\nfunction api<T>(token: string, path: string, init?: RequestInit): Promise<T> {\n return apiFetch<T>(API_URL, token, path, init)\n}\n\nconst list = defineDeepspaceCommand({\n meta: { name: 'list', description: 'List collaborators on your app' },\n args: {\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n const { collaborators, pending = [] } = await api<{\n collaborators: Collaborator[]\n pending?: PendingInvite[]\n }>(token, `/api/app-collaborators/${encodeURIComponent(app)}`)\n if (!collaborators.length && !pending.length) {\n if (!args.json) {\n console.log(`No collaborators on ${app}. Add one with \\`deepspace app collaborators add <email>\\`.`)\n }\n return { data: { collaborators, pending } }\n }\n // COL-4: print a header and the resolved email (emailDisplay). The raw\n // userId is dropped from the human view — it's still in --json, a human\n // reads the email, and `collaborators remove <email>` matches on it.\n if (!args.json) {\n if (collaborators.length) {\n console.log(`COLLABORATORS ON ${app}`)\n for (const c of collaborators) {\n console.log(` ${c.emailDisplay}`)\n }\n }\n if (pending.length) {\n console.log(`PENDING INVITES ON ${app}`)\n for (const p of pending) {\n console.log(` ${p.email} (expires ${new Date(p.expiresAt).toLocaleDateString()})`)\n }\n }\n }\n return { data: { collaborators, pending } }\n },\n})\n\nconst add = defineDeepspaceCommand({\n meta: { name: 'add', description: 'Authorize someone to deploy your app' },\n args: {\n email: {\n type: 'positional',\n description: 'Collaborator email',\n required: true,\n },\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const email = String(args.email)\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n if (isTestAccountEmail(email)) {\n throw new Refusal(\n 'Test accounts (@deepspace.test) cannot be added as collaborators. Use a real DeepSpace account.',\n 'test_account_cannot_be_collaborator',\n )\n }\n // Failure slugs (insufficient_credits, test_account_cannot_be_collaborator,\n // ...) are translated centrally by wrapCommandErrors — just let them escape.\n // An email with no DeepSpace user is no longer an error: the server creates\n // a pending invite ({status:'invited'}) and emails the person.\n const res = await api<AddResponse>(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}`,\n { method: 'POST', body: JSON.stringify({ email }) },\n )\n if (res.status === 'invited' || res.status === 'already_invited') {\n const expires = new Date(res.expiresAt).toLocaleDateString()\n if (res.status === 'already_invited') {\n if (!args.json) {\n console.log(\n `• ${res.email} already has a pending invite (expires ${expires}). ` +\n `No new email was sent. Cancel it with \\`deepspace app collaborators cancel ${res.email}\\` to reset.`,\n )\n }\n return { data: { ...res } }\n }\n if (!args.json) {\n console.log(\n `✓ Invite sent to ${res.email} (expires ${expires}). ` +\n `They become a collaborator when they sign in.`,\n )\n }\n return { data: { ...res } }\n }\n if (!args.json) console.log(`✓ ${res.collaborator.emailDisplay} can now deploy ${app}`)\n return { data: { ...res } }\n },\n})\n\nconst remove = defineDeepspaceCommand({\n meta: { name: 'remove', description: 'Remove a collaborator from your app' },\n args: {\n email: { type: 'positional', description: 'Collaborator email', required: true },\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const email = String(args.email)\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n const { collaborators } = await api<{ collaborators: Collaborator[] }>(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}`,\n )\n const target = email.trim().toLowerCase()\n const found = collaborators.find((c) => c.emailDisplay.toLowerCase() === target)\n if (!found) {\n throw new Refusal(`${email} is not a collaborator on ${app}`, 'not_a_collaborator', {\n action: cliAction('deepspace', 'app', 'collaborators', 'list', '--app', app),\n })\n }\n await api(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}/${encodeURIComponent(found.userId)}`,\n { method: 'DELETE' },\n )\n if (!args.json) console.log(`✓ ${found.emailDisplay} can no longer deploy ${app}`)\n // Terminal: nothing follows a removal.\n return { data: { removed: found } }\n },\n})\n\nconst cancel = defineDeepspaceCommand({\n meta: { name: 'cancel', description: 'Cancel a pending (un-accepted) email invite' },\n args: {\n email: { type: 'positional', description: 'Invited email', required: true },\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const email = String(args.email)\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n // Match against the pending list (mirrors `remove`) so we can tell the user\n // when there's nothing to cancel rather than silently no-op'ing the DELETE.\n const { pending = [] } = await api<{ pending?: PendingInvite[] }>(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}`,\n )\n const target = email.trim().toLowerCase()\n const found = pending.find((p) => p.email.toLowerCase() === target)\n if (!found) {\n throw new Refusal(`${email} has no pending invite on ${app}`, 'no_pending_invite', {\n action: cliAction('deepspace', 'app', 'collaborators', 'list', '--app', app),\n })\n }\n await api(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}/pending/${encodeURIComponent(found.email)}`,\n { method: 'DELETE' },\n )\n if (!args.json) console.log(`✓ Cancelled the pending invite to ${found.email} on ${app}`)\n // Terminal: nothing follows a cancellation.\n return { data: { cancelled: found } }\n },\n})\n\n// No `run()` on the parent: citty otherwise cascades it after each subcommand,\n// printing spurious help text.\nexport default defineCommand({\n meta: { name: 'collaborators', description: 'Manage who can deploy your app' },\n subCommands: { list, add, remove, cancel },\n})\n","/**\n * Test-account identification, shared by every platform worker.\n *\n * Test accounts (created via `deepspace test accounts`) are real Better Auth\n * users demarcated three ways, and a caller may present as any of them\n * depending on where the check runs:\n * - their email always ends with @deepspace.test (enforced at creation)\n * - their JWTs carry `isTestAccount: true` (minted by the auth-worker,\n * the source of truth)\n * - their billing profile's subscription tier is 'test' (mirrored by the\n * api-worker on every authenticated request)\n *\n * Gate anything a test account must not do with these helpers rather than\n * hand-rolled string comparisons, so the policy stays in one place. Prefer\n * checking the claim when a verified JWT is at hand, and the tier as the\n * fallback for persisted state that may outlive a claim (e.g. rows written\n * before a guard existed).\n */\n\nimport type { JwtClaims } from './types'\n\nexport const TEST_ACCOUNT_EMAIL_SUFFIX = '@deepspace.test'\n\n/** True when the email belongs to a test account (case-insensitive). */\nexport function isTestAccountEmail(email: string | null | undefined): boolean {\n return !!email && email.trim().toLowerCase().endsWith(TEST_ACCOUNT_EMAIL_SUFFIX)\n}\n\n/** True when verified JWT claims identify the caller as a test account. */\nexport function isTestAccountClaims(\n claims: JwtClaims | Record<string, unknown> | null | undefined,\n): boolean {\n return claims?.isTestAccount === true\n}\n\n/** True when a billing subscription tier marks a test account. */\nexport function isTestAccountTier(tier: string | null | undefined): boolean {\n return tier === 'test'\n}\n","/**\n * Transfer app ownership — the GitHub-style offer/accept handshake.\n *\n * `deepspace app transfer offer <email>` creates (or replaces) a 7-day offer;\n * the recipient runs `deepspace app transfer accept --app <appId>` to commit.\n * Acceptance flips the registry owner and re-tags the deployed script for\n * billing in the same call. Either party can `cancel`. Data, secrets, and\n * routes travel with the app — only the owner (and billing) changes.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, the `Next:` line and the exit codes come from there. The one\n * confirmation prompt (`offer` over a pending offer to someone else) is\n * TTY-only: under `--json` a prompt is a hang, so it refuses with\n * `confirmation_required` and points at `--replace`.\n */\n\nimport { defineCommand } from 'citty'\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { requireAppIdArg, resolveAppTarget } from '../lib/app-target'\nimport { apiFetch as api } from '../lib/api'\nimport { InputError } from '../lib/cli-errors'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nconst offer = defineDeepspaceCommand({\n meta: { name: 'offer', description: 'Offer this app to another DeepSpace user' },\n args: {\n email: { type: 'positional', description: 'Recipient email', required: true },\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n replace: {\n type: 'boolean',\n description: 'Replace a pending offer to someone else without asking',\n },\n },\n async run({ args }) {\n const email = String(args.email)\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n\n // The server replaces a pending offer wholesale — a stray second `offer`\n // used to silently revoke the first with no signal to anyone, and the\n // original recipient's `accept` then failed with a mystery 404. Surface\n // the pending offer and make replacing it a deliberate choice.\n const pending = await api<{ transfer: { toEmailDisplay: string } | null }>(\n API_URL,\n token,\n `/api/app-transfers/${encodeURIComponent(app)}`,\n )\n const pendingTo = pending.transfer?.toEmailDisplay\n if (pendingTo && pendingTo.toLowerCase() !== email.trim().toLowerCase() && !args.replace) {\n // No TTY (agent, pipe) or `--json` — a prompt would hang. Refuse with the\n // flag that resolves it instead.\n if (!process.stdin.isTTY || args.json) {\n throw new Refusal(\n `A pending offer to ${pendingTo} already exists for ${app}. ` +\n 'Re-run with --replace to replace it, or `deepspace app transfer cancel` first.',\n 'confirmation_required',\n )\n }\n const yes = await p.confirm({\n message: `A pending offer to ${pendingTo} exists — replace it with ${email}?`,\n })\n if (p.isCancel(yes) || !yes) {\n throw new Refusal(`Kept the pending offer to ${pendingTo}.`, 'cancelled')\n }\n }\n\n const { expiresAt } = await api<{ toUserId: string; expiresAt: string }>(\n API_URL,\n token,\n `/api/app-transfers/${encodeURIComponent(app)}`,\n { method: 'POST', body: JSON.stringify({ email }) },\n )\n const replaced = pendingTo && pendingTo.toLowerCase() !== email.trim().toLowerCase()\n if (!args.json) {\n if (replaced) console.log(`▲ Replaced the pending offer to ${pendingTo}.`)\n console.log(\n `✓ Offered ${app} to ${email} (expires ${expiresAt}).\\n` +\n ` They accept with: deepspace app transfer accept --app ${app}`,\n )\n }\n return {\n data: {\n app,\n email,\n expiresAt,\n ...(replaced ? { replacedPendingTo: pendingTo } : {}),\n },\n }\n },\n})\n\nconst status = defineDeepspaceCommand({\n meta: { name: 'status', description: 'Show the pending transfer offer, if any' },\n args: {\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n const { transfer } = await api<{\n transfer: { toEmailDisplay: string; expiresAt: string } | null\n }>(API_URL, token, `/api/app-transfers/${encodeURIComponent(app)}`)\n if (!transfer) {\n if (!args.json) console.log(`No pending transfer for ${app}.`)\n return { data: { app, transfer: null } }\n }\n if (!args.json) {\n console.log(`Pending: ${app} → ${transfer.toEmailDisplay} (expires ${transfer.expiresAt}).`)\n }\n return { data: { app, transfer } }\n },\n})\n\nconst accept = defineDeepspaceCommand({\n meta: { name: 'accept', description: 'Accept a transfer offered to you' },\n args: {\n app: { type: 'string', alias: 'a', description: 'App id of the offered app', required: true },\n },\n async run({ args }) {\n const token = await ensureToken()\n // requireAppIdArg throws an UNCODED Error for a malformed/absent id; the\n // envelope needs a slug, so give it one here (its InputErrors already have\n // theirs).\n let app: string\n try {\n app = requireAppIdArg(args.app as string | undefined)\n } catch (err: unknown) {\n if (err instanceof InputError) throw err\n const msg = err instanceof Error ? err.message : String(err)\n throw new Refusal(msg, msg.startsWith('No app id') ? 'not_in_app_repo' : 'invalid_app')\n }\n await api(DEPLOY_URL, token, `/api/apps/${encodeURIComponent(app)}/transfer/accept`, {\n method: 'POST',\n })\n if (!args.json) {\n console.log(\n `✓ You now own ${app}. Run \\`deepspace app init\\` in a fresh clone (or set ` +\n `DEEPSPACE_APP_ID = \"${app}\" in wrangler.toml) and deploy.`,\n )\n }\n return { data: { app, accepted: true } }\n },\n})\n\nconst cancel = defineDeepspaceCommand({\n meta: { name: 'cancel', description: 'Cancel/decline the pending offer (either party)' },\n args: {\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n await api(API_URL, token, `/api/app-transfers/${encodeURIComponent(app)}`, { method: 'DELETE' })\n if (!args.json) console.log(`✓ Transfer offer for ${app} cancelled.`)\n // Terminal: nothing follows a cancellation.\n return { data: { app, cancelled: true } }\n },\n})\n\n// No `run()` on the parent: citty otherwise cascades it after each subcommand.\nexport default defineCommand({\n meta: { name: 'transfer', description: 'Transfer app ownership to another user' },\n subCommands: { offer, status, accept, cancel },\n})\n","/**\n * deepspace integrations <subcommand>\n *\n * Namespace for working with platform integrations from the command line.\n *\n * deepspace integrations # prints help\n * deepspace integrations list # list all\n * deepspace integrations info openai/chat-completion # schema + example\n * deepspace integrations invoke openai/chat-completion --body '{...}'\n *\n * All calls are made as the currently logged-in user (`deepspace auth whoami`).\n * That user is billed.\n *\n * Each subcommand is defined with the command runtime (lib/command.ts): the\n * `--json` flag, the `{ ok, … }` envelope, the refusal slug, the `Next:` line,\n * and the exit code come from there. Before that, the subcommands caught their\n * own errors and `console.error`'d the message — which meant a `--json` caller\n * got PLAIN PROSE on stderr and an empty stdout.\n *\n * No `run()` is defined on the parent — that matches the convention used\n * by `test-accounts` and prevents citty from firing both the parent and\n * a matched subcommand. Bare `deepspace integrations` (no subcommand)\n * prints citty's auto-generated help.\n */\n\nimport { defineCommand } from 'citty'\nimport { defineDeepspaceCommand } from '../lib/command'\nimport { runInvoke, runInfo, runList, parseTimeout } from './_invoke-impl'\n\nconst list = defineDeepspaceCommand({\n meta: {\n name: 'list',\n description: 'List all available integrations',\n },\n async run({ args }) {\n return runList({ json: args.json })\n },\n})\n\nconst info = defineDeepspaceCommand({\n meta: {\n name: 'info',\n description: 'Print schema + example body for an integration endpoint',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: true,\n },\n },\n async run({ args }) {\n return runInfo({ target: args.target as string, json: args.json })\n },\n})\n\nconst invoke = defineDeepspaceCommand({\n meta: {\n name: 'invoke',\n description: 'Invoke a platform integration as the logged-in user',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: true,\n },\n body: {\n type: 'string',\n alias: 'd',\n description: 'Inline JSON body',\n required: false,\n },\n 'body-file': {\n type: 'string',\n alias: 'f',\n description: 'Read JSON body from file (use - for stdin)',\n required: false,\n },\n timeout: {\n type: 'string',\n description: 'Request timeout in milliseconds (default: 120000)',\n required: false,\n },\n yes: {\n type: 'boolean',\n alias: 'y',\n description: 'Skip the paid-call cost confirmation',\n default: false,\n },\n },\n async run({ args }) {\n return runInvoke({\n target: args.target as string,\n body: args.body as string | undefined,\n bodyFile: args['body-file'] as string | undefined,\n json: args.json,\n timeout: parseTimeout(args.timeout),\n yes: Boolean(args.yes),\n })\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'integrations',\n description: 'List, inspect, and invoke platform integrations',\n },\n subCommands: {\n list,\n info,\n invoke,\n },\n})\n","/**\n * Implementation for `deepspace integrations list`, `info`, and `invoke`.\n *\n * The CLI invokes platform integrations as the currently logged-in user\n * (the same identity shown by `deepspace auth whoami`). That user is billed.\n *\n * This module is the single source of truth for:\n * - listing the integration catalog\n * - showing per-endpoint info (schema + example body)\n * - making the actual POST call\n *\n * This module is NOT a citty command, so it does not wrap itself in the\n * command runtime. Instead every `run*` here RETURNS a {@link CommandResult}\n * and throws a {@link Refusal} — exactly what a `defineDeepspaceCommand` body\n * produces — so the command definitions can let the runtime own the envelope,\n * the slug, the `Next:` line, and the exit code.\n * Nothing in here prints an envelope or calls process.exit.\n */\n\nimport { readFileSync } from 'node:fs'\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { cliAction, Refusal, type CommandResult } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\nconst DEFAULT_TIMEOUT_MS = 120_000\n\ninterface EndpointInfo {\n endpoint: string\n billing: { model: string; baseCost: number; currency: string }\n inputSchema: Record<string, unknown> | null\n example: Record<string, unknown> | null\n}\n\ninterface Catalog {\n integrations: Record<string, EndpointInfo[]>\n}\n\nexport interface InvokeArgs {\n target: string\n body?: string\n bodyFile?: string\n json?: boolean\n timeout?: number\n yes?: boolean\n}\n\nexport interface InfoArgs {\n target: string\n json?: boolean\n}\n\nexport interface ListArgs {\n json?: boolean\n}\n\n/**\n * Parse \"<integration>/<endpoint>\" into its two segments.\n * Throws on malformed input.\n */\nfunction parseTarget(target: string): { integration: string; endpoint: string } {\n if (!target || typeof target !== 'string') {\n throw new Refusal(\n \"Missing target. Expected '<integration>/<endpoint>' (e.g. 'openai/chat-completion').\",\n 'missing_target',\n { action: cliAction('deepspace', 'integrations', 'list') },\n )\n }\n const parts = target.split('/')\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Refusal(\n `Bad target '${target}'. Expected '<integration>/<endpoint>' (e.g. 'openai/chat-completion').`,\n 'bad_target',\n { action: cliAction('deepspace', 'integrations', 'list') },\n )\n }\n return { integration: parts[0], endpoint: parts[1] }\n}\n\n/**\n * Parse the `integrations invoke --timeout` value in milliseconds.\n */\nexport function parseTimeout(raw: unknown): number | undefined {\n if (raw == null) return undefined\n const timeout = Number(raw)\n if (!Number.isFinite(timeout) || timeout <= 0) {\n throw new Refusal(\n `Invalid --timeout '${String(raw)}'. Must be a positive number of milliseconds.`,\n 'invalid_timeout',\n )\n }\n return timeout\n}\n\n/**\n * Resolve the request body from --body, --body-file, or default to '{}'.\n * Errors if both --body and --body-file are provided, or the body isn't\n * valid JSON.\n */\nfunction resolveBody(opts: { body?: string; bodyFile?: string }): string {\n if (opts.body != null && opts.bodyFile != null) {\n throw new Refusal('Pass either --body or --body-file, not both.', 'conflicting_body_args')\n }\n\n let raw: string\n if (opts.body != null) {\n raw = opts.body\n } else if (opts.bodyFile != null) {\n raw = opts.bodyFile === '-' ? readFileSync(0, 'utf-8') : readFileSync(opts.bodyFile, 'utf-8')\n } else {\n return '{}'\n }\n\n // Validate it parses as JSON so we fail fast with a clear message.\n try {\n JSON.parse(raw)\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'invalid JSON'\n throw new Refusal(`Body is not valid JSON: ${msg}`, 'invalid_body_json')\n }\n return raw\n}\n\nasync function fetchCatalog(opts: { summary?: boolean } = {}): Promise<Catalog> {\n // `list` uses the summary view (names + billing); the full catalog with every\n // endpoint's schema is large enough to be truncated in an agent's terminal.\n // `info` omits the flag so it still gets the schema + example.\n const url = opts.summary ? `${API_URL}/api/integrations?summary=1` : `${API_URL}/api/integrations`\n const res = await fetch(url)\n if (!res.ok) {\n throw new Refusal(`Failed to fetch integration catalog (${res.status})`, 'catalog_unavailable')\n }\n return (await res.json()) as Catalog\n}\n\nfunction findEndpoint(\n catalog: Catalog,\n integration: string,\n endpoint: string,\n): EndpointInfo | null {\n const endpoints = catalog.integrations[integration]\n if (!endpoints) return null\n return endpoints.find((e) => e.endpoint === endpoint) ?? null\n}\n\nfunction formatCurrency(value: number, currency: string): string {\n if (currency === 'USD') return `$${value}`\n return `${value} ${currency}`\n}\n\n/**\n * Human-readable billing unit for a pricing model. `per_token` → \"per token\",\n * `per_call` → \"per call\". Unknown/future models render their raw `per_*` shape\n * (\"per foo\") or pass through, so we never mislabel one mode as another (INT-1).\n */\nexport function billingUnit(model: string): string {\n if (model === 'per_token') return 'per token'\n if (model === 'per_call') return 'per call'\n return model.startsWith('per_') ? model.replace(/^per_/, 'per ').replace(/_/g, ' ') : model\n}\n\n/**\n * Interactive only when BOTH streams are TTYs: p.confirm reads stdin and draws\n * to stdout, so a piped stdin (`echo {} | invoke … --body-file -`) must never\n * reach the prompt — it would hang waiting for input that can't arrive. Pure so\n * the both-streams rule is testable.\n */\nexport function isInteractive(\n stdin: { isTTY?: boolean },\n stdout: { isTTY?: boolean },\n): boolean {\n return Boolean(stdin.isTTY && stdout.isTTY)\n}\n\n/**\n * Whether to confirm a paid invoke before firing it (FEAT-13). Only on an\n * interactive terminal, for a non-free endpoint, when the caller hasn't asked\n * for machine output (--json) or pre-approved (--yes). Pure for testing.\n */\nexport function shouldConfirmCost(opts: {\n json: boolean\n yes: boolean\n isTTY: boolean\n baseCost: number\n}): boolean {\n return !opts.json && !opts.yes && opts.isTTY && opts.baseCost > 0\n}\n\n/**\n * `deepspace integrations list`\n * Prints the catalog grouped by integration.\n */\nexport async function runList(args: ListArgs): Promise<CommandResult> {\n const catalog = await fetchCatalog({ summary: true })\n const names = Object.keys(catalog.integrations).sort()\n\n if (!args.json) {\n if (names.length === 0) {\n console.log('No integrations available.')\n } else {\n for (const name of names) {\n console.log(name)\n const endpoints = [...catalog.integrations[name]].sort((a, b) =>\n a.endpoint.localeCompare(b.endpoint),\n )\n const widest = Math.max(...endpoints.map((e) => e.endpoint.length))\n for (const ep of endpoints) {\n const pad = ep.endpoint.padEnd(widest)\n const cost = formatCurrency(ep.billing.baseCost, ep.billing.currency)\n console.log(` ${pad} ${ep.billing.model.padEnd(12)} ${cost}`)\n }\n console.log()\n }\n }\n }\n\n return { data: catalog as unknown as Record<string, unknown> }\n}\n\n/**\n * `deepspace integrations info <target>`\n * Prints the schema + example body for a single endpoint.\n */\nexport async function runInfo(args: InfoArgs): Promise<CommandResult> {\n const { integration, endpoint } = parseTarget(args.target)\n const catalog = await fetchCatalog()\n const info = findEndpoint(catalog, integration, endpoint)\n\n if (!info) {\n const available = catalog.integrations[integration]\n if (!available) {\n const names = Object.keys(catalog.integrations).sort().join(', ')\n throw new Refusal(`Unknown integration '${integration}'. Available: ${names}`, 'unknown_integration', {\n action: cliAction('deepspace', 'integrations', 'list'),\n })\n }\n const endpoints = available.map((e) => e.endpoint).join(', ')\n throw new Refusal(\n `Unknown endpoint '${endpoint}' for '${integration}'. Available: ${endpoints}`,\n 'unknown_endpoint',\n { action: cliAction('deepspace', 'integrations', 'list') },\n )\n }\n\n if (!args.json) {\n console.log(`${integration}/${endpoint}`)\n console.log(\n ` billing: ${formatCurrency(info.billing.baseCost, info.billing.currency)} ${billingUnit(info.billing.model)}`,\n )\n console.log()\n console.log('Input schema:')\n console.log(\n info.inputSchema ? JSON.stringify(info.inputSchema, null, 2) : ' (no schema registered)',\n )\n console.log()\n console.log('Example body:')\n console.log(info.example ? JSON.stringify(info.example, null, 2) : ' (no example available)')\n }\n\n return { data: info as unknown as Record<string, unknown> }\n}\n\n/**\n * `deepspace integrations invoke <target>`\n * Performs the actual integration call.\n */\nexport async function runInvoke(args: InvokeArgs): Promise<CommandResult> {\n const { integration, endpoint } = parseTarget(args.target)\n const body = resolveBody({ body: args.body, bodyFile: args.bodyFile })\n const timeoutMs = args.timeout ?? DEFAULT_TIMEOUT_MS\n\n // FEAT-13: this fires a PAID call billed to the logged-in user. On a fully\n // interactive terminal, confirm the cost first (unless --yes or --json).\n // Gate on BOTH streams: p.confirm reads stdin and draws to stdout, so a piped\n // stdin (e.g. `echo {} | deepspace integrations invoke … --body-file -`) must never reach\n // the prompt — it would hang waiting for input that can't come.\n const interactive = isInteractive(process.stdin, process.stdout)\n if (!args.json && !args.yes && interactive) {\n let info: EndpointInfo | null = null\n try {\n info = findEndpoint(await fetchCatalog({ summary: true }), integration, endpoint)\n } catch {\n // Couldn't fetch billing — don't block the call, but say so, so a paid\n // call never fires completely silently. The POST still enforces\n // auth/existence and reports its own errors.\n console.error('Note: could not verify the call cost; proceeding. Pass --yes to skip this check.')\n info = null\n }\n if (\n info &&\n shouldConfirmCost({\n json: !!args.json,\n yes: !!args.yes,\n isTTY: interactive,\n baseCost: info.billing.baseCost,\n })\n ) {\n const cost = formatCurrency(info.billing.baseCost, info.billing.currency)\n const ok = await p.confirm({\n message: `${integration}/${endpoint} costs ${cost} ${billingUnit(info.billing.model)}, billed to your account. Continue?`,\n })\n if (p.isCancel(ok) || !ok) {\n p.cancel('Cancelled — no call made.')\n // Declining a paid call is a success, not a refusal: nothing was\n // billed and there is nothing to retry.\n return { data: { cancelled: true, integration, endpoint } }\n }\n }\n }\n\n let jwt: string\n try {\n jwt = await ensureToken()\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Refusal(msg, 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n const startedAt = Date.now()\n\n let res: Response\n try {\n res = await fetch(`${API_URL}/api/integrations/${integration}/${endpoint}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${jwt}`,\n },\n body,\n signal: controller.signal,\n })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Refusal(`Request timed out after ${timeoutMs}ms`, 'request_timeout')\n }\n throw new Refusal(err instanceof Error ? err.message : 'Request failed', 'request_failed')\n } finally {\n clearTimeout(timer)\n }\n\n const elapsed = Date.now() - startedAt\n let payload: Record<string, unknown>\n try {\n payload = (await res.json()) as Record<string, unknown>\n } catch {\n throw new Refusal(`Request failed (${res.status}) with non-JSON response`, 'invalid_response')\n }\n\n const ok = payload?.success !== false && res.ok\n if (ok) {\n if (!args.json) {\n const data = 'data' in payload ? payload.data : payload\n console.log(JSON.stringify(data, null, 2))\n console.error(`\\n✓ ${integration}/${endpoint} (${elapsed}ms)`)\n }\n // The server payload is the machine result, but it is NOT an envelope —\n // hand it to the runtime as `data` so it goes out as `{ ok, …payload }`\n // like every other command instead of passing through unnormalized.\n return { data: payload }\n }\n\n // Error path. The issue list is part of the message (the human line must\n // carry every fact --json does) and rides along in the envelope via `extra`.\n const errMsg = (payload.error as string) ?? `Request failed (${res.status})`\n // No `✗` prefix: the runtime renders the failure marker, and it would read\n // as `■ ✗ …` (and land in the `--json` `error` string) if we kept ours.\n const lines = [`${integration}/${endpoint} (${res.status}, ${elapsed}ms): ${errMsg}`]\n if (Array.isArray(payload.issues)) {\n for (const issue of payload.issues as Array<{ path?: string[]; message: string }>) {\n const path = issue.path?.length ? issue.path.join('.') : '(root)'\n lines.push(` - ${path}: ${issue.message}`)\n }\n }\n // Prefer the server's own slug so an agent branches on the same code the API\n // returns; fall back to a stable generic one.\n const code = typeof payload.code === 'string' ? payload.code : 'integration_call_failed'\n // `error` would only restate the message the runtime already renders.\n const rest = { ...payload }\n delete rest.error\n throw new Refusal(lines.join('\\n'), code, {\n ...(res.status === 401 ? { action: cliAction('deepspace', 'auth', 'login') } : {}),\n extra: rest,\n })\n}\n","/**\n * deepspace app library [publish|unpublish] [options]\n *\n * Manage entries in the DeepSpace community library (lives at\n * deepdotspace-site.app.space by default; override with --library-app\n * or DEEPSPACE_LIBRARY_HOST). Subcommands POST to that app's\n * `library.publish` / `library.unpublish` actions as the currently\n * logged-in user.\n *\n * The publish action verifies the caller owns the deployed app (by\n * checking the deploy worker's `/api/apps` registry) before writing\n * the row, so publishing another user's app is rejected server-side.\n *\n * Defined with the command runtime (lib/command.ts). That fixes this file's\n * long-standing deviation: both subcommands used to write their `--json`\n * envelope to STDERR (and the success envelope as the server's raw\n * `{success,data}` blob). It is now a single-line `{ ok, … }` document on\n * STDOUT, like every other command.\n *\n * Usage:\n * deepspace app library publish (uses wrangler.toml)\n * deepspace app library publish --app my-cool-app --name \"My Cool App\"\n * deepspace app library publish --description \"...\" --category Productivity\n * deepspace app library publish --tags utility,ai --visibility unlisted\n * deepspace app library unpublish <handle>\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport * as p from '@clack/prompts'\n\nimport { ensureToken } from '../auth'\nimport { parseAppArg } from '../lib/app-target'\nimport { resolveAppName } from '../../server/rooms/app-name'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst DEFAULT_LIBRARY_APP = 'deepdotspace-site'\n\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)\n\nconst publish = defineDeepspaceCommand({\n meta: {\n name: 'publish',\n description: 'Publish the current app to the DeepSpace library',\n },\n args: {\n dir: {\n type: 'string',\n description: 'App directory (default: current directory)',\n required: false,\n },\n app: {\n type: 'string',\n description: 'App name (default: read from wrangler.toml)',\n required: false,\n },\n name: {\n type: 'string',\n description: 'Display name (default: app name)',\n required: false,\n },\n description: {\n type: 'string',\n description: 'Short description',\n required: false,\n },\n category: {\n type: 'string',\n description: 'Category (e.g. Productivity, Finance, AI). Default: General',\n required: false,\n },\n tags: {\n type: 'string',\n description: 'Comma-separated tags',\n required: false,\n },\n visibility: {\n type: 'string',\n description: \"'public' (default), 'unlisted', or 'private'\",\n required: false,\n },\n screenshot: {\n type: 'string',\n description: 'Override the auto-captured preview with a public PNG URL',\n required: false,\n },\n 'library-app': {\n type: 'string',\n description: `Target library app subdomain (default: ${DEFAULT_LIBRARY_APP})`,\n required: false,\n },\n },\n async run({ args }) {\n const json = args.json\n const intro = (s: string) => { if (!json) p.intro(s) }\n const info = (s: string) => { if (!json) p.log.info(s) }\n\n intro('Publishing to the DeepSpace library')\n\n // An explicit blank --app must error, not silently fall back to the cwd app.\n const appErr = parseAppArg(str(args.app)).error\n if (appErr) throw new Refusal(appErr, 'invalid_app')\n let appName = str(args.app)?.trim()\n if (!appName) {\n const appDir = resolve(str(args.dir) ?? '.')\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n throw new Refusal(\n \"No --app provided and no wrangler.toml found. Either pass --app <name> or run from your app's directory.\",\n 'not_in_app_repo',\n )\n }\n const cfg = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n const nameRes = resolveAppName(cfg.name)\n if (!nameRes.ok) throw new Refusal(`wrangler.toml: ${nameRes.reason}`, 'invalid_config')\n appName = nameRes.name\n }\n info(`App: ${appName}`)\n\n const visibility = (str(args.visibility) ?? 'public') as string\n if (!['public', 'private', 'unlisted'].includes(visibility)) {\n throw new Refusal(\"--visibility must be 'public', 'unlisted', or 'private'.\", 'invalid_visibility')\n }\n\n const tags = str(args.tags)\n ? String(args.tags).split(',').map((t) => t.trim()).filter(Boolean)\n : undefined\n\n const libraryApp = str(args['library-app']) ?? DEFAULT_LIBRARY_APP\n const libraryHost = process.env.DEEPSPACE_LIBRARY_HOST ?? `https://${libraryApp}.app.space`\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err) {\n throw new Refusal(err instanceof Error ? err.message : String(err), 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const payload: Record<string, unknown> = {\n appName,\n ...(args.name ? { name: args.name } : {}),\n ...(args.description ? { description: args.description } : {}),\n ...(args.category ? { category: args.category } : {}),\n ...(tags ? { tags } : {}),\n visibility,\n ...(args.screenshot ? { screenshotUrl: args.screenshot } : {}),\n }\n\n const url = `${libraryHost}/api/actions/library.publish`\n let res: Response\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(payload),\n })\n } catch (err) {\n throw new Refusal(\n `Network error reaching ${url}: ${err instanceof Error ? err.message : String(err)}`,\n 'network_error',\n )\n }\n\n const body = await res.text()\n let parsed: { success?: boolean; data?: { templateHandle?: string; url?: string; version?: number }; error?: string }\n try {\n parsed = JSON.parse(body)\n } catch {\n throw new Refusal(`Server returned non-JSON (${res.status}): ${body.slice(0, 400)}`, 'invalid_response')\n }\n\n if (!parsed.success) {\n throw new Refusal(parsed.error ?? `Publish failed (HTTP ${res.status}).`, 'publish_failed')\n }\n\n if (!json) {\n p.log.success(`Published ${appName} as ${parsed.data?.templateHandle} (v${parsed.data?.version})`)\n if (parsed.data?.url) p.log.message(parsed.data.url)\n p.outro('Done')\n }\n return {\n data: {\n appName,\n templateHandle: parsed.data?.templateHandle ?? null,\n url: parsed.data?.url ?? null,\n version: parsed.data?.version ?? null,\n visibility,\n },\n }\n },\n})\n\nconst unpublish = defineDeepspaceCommand({\n meta: {\n name: 'unpublish',\n description: 'Remove a library entry (owner or admin only)',\n },\n args: {\n handle: {\n type: 'positional',\n description: 'templateHandle to remove (usually your app name)',\n required: true,\n },\n 'library-app': {\n type: 'string',\n description: `Target library app subdomain (default: ${DEFAULT_LIBRARY_APP})`,\n required: false,\n },\n },\n async run({ args }) {\n const json = args.json\n if (!json) p.intro('Unpublishing library entry')\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err) {\n throw new Refusal(err instanceof Error ? err.message : String(err), 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const libraryApp = str(args['library-app']) ?? DEFAULT_LIBRARY_APP\n const libraryHost = process.env.DEEPSPACE_LIBRARY_HOST ?? `https://${libraryApp}.app.space`\n\n const res = await fetch(`${libraryHost}/api/actions/library.unpublish`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify({ templateHandle: String(args.handle) }),\n })\n const body = await res.text()\n let parsed: { success?: boolean; error?: string; data?: { templateHandle?: string } }\n try {\n parsed = JSON.parse(body)\n } catch {\n throw new Refusal(`Server returned non-JSON (${res.status}): ${body.slice(0, 400)}`, 'invalid_response')\n }\n if (!parsed.success) {\n throw new Refusal(parsed.error ?? `HTTP ${res.status}`, 'unpublish_failed')\n }\n if (!json) {\n p.log.success(`Unpublished ${parsed.data?.templateHandle}`)\n p.outro('Done')\n }\n // Terminal: nothing follows an unpublish.\n return { data: { templateHandle: parsed.data?.templateHandle ?? String(args.handle) } }\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'library',\n description: 'Manage your DeepSpace library entries',\n },\n subCommands: {\n publish,\n unpublish,\n },\n})\n","/**\n * deepspace feedback\n *\n * Submit a bug report, feature request, or general feedback to the DeepSpace\n * team. The report is authenticated as the logged-in user and POSTed to the\n * api-worker, where it lands in the admin triage queue (dashboard ·\n * Admin · Feedback).\n *\n * Interactive when run in a TTY (prompts for type/title/details); flag-driven\n * for agents and CI. The title is a positional argument; the details go in\n * --message (-m). Both are required for non-interactive use.\n *\n * deepspace feedback # full interactive prompt\n * deepspace feedback \"Crash on deploy\" -m \"It explodes when…\" # quick, non-interactive\n * deepspace feedback -t feature \"Add dark mode\" -m \"…\" --yes --json\n *\n * Best-effort environment context (CLI version, Node version, OS, and the\n * current app name if run inside a scaffolded app) is attached automatically\n * so the team can reproduce issues without a round-trip.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * and the exit code come from there. Its old local `fail()` emitted\n * `{ ok:false, error }` with NO `code`, so a `--json` caller had nothing\n * stable to branch on — every refusal below now carries a slug.\n */\n\nimport * as p from '@clack/prompts'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { release } from 'node:os'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS, DASHBOARD_URL } from '../env'\nimport { apiFetch } from '../lib/api'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\nimport { hasWranglerConfig, readWranglerConfig } from '../lib/wrangler-env'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\nconst TYPES = ['bug', 'feature', 'other'] as const\ntype FeedbackType = (typeof TYPES)[number]\n\nconst TYPE_LABELS: Record<FeedbackType, string> = {\n bug: 'Bug report',\n feature: 'Feature request',\n other: 'Other feedback',\n}\n\n// Mirror the api-worker's limits so over-length input fails fast with a clear\n// field-specific message instead of a generic 400 after the round-trip.\nconst MAX_TITLE_LEN = 200\nconst MAX_BODY_LEN = 10_000\nconst MAX_CONTEXT_LEN = 200\n\ninterface FeedbackContext {\n cliVersion: string\n nodeVersion: string\n platform: string\n appName?: string\n}\n\ninterface FeedbackPayload extends FeedbackContext {\n type: FeedbackType\n title: string\n body: string\n}\n\ninterface FeedbackReport {\n id: string\n type: FeedbackType\n title: string\n status: string\n createdAt: string\n}\n\nconst api = <T>(token: string, path: string, init?: RequestInit): Promise<T> =>\n apiFetch<T>(API_URL, token, path, init)\n\n/** Normalize/validate a `--type` value. Throws on an unknown type. */\nexport function normalizeType(raw: string | undefined): FeedbackType {\n const value = (raw ?? 'bug').toLowerCase()\n if ((TYPES as readonly string[]).includes(value)) return value as FeedbackType\n throw new Error(`Invalid --type \"${raw}\". Use one of: ${TYPES.join(', ')}.`)\n}\n\n/** Read the deepspace CLI version from its own package.json. */\nfunction readCliVersion(): string {\n try {\n const here = dirname(fileURLToPath(import.meta.url))\n // Bundled output lives in <pkg>/dist (package.json one level up); the\n // source tree has it three levels up from src/cli/commands.\n const candidates = [\n join(here, '..', 'package.json'),\n join(here, '..', '..', '..', 'package.json'),\n ]\n for (const path of candidates) {\n if (!existsSync(path)) continue\n const pkg = JSON.parse(readFileSync(path, 'utf-8')) as {\n name?: string\n version?: string\n }\n if (pkg.name === 'deepspace' && pkg.version) return pkg.version\n }\n } catch {\n // fall through\n }\n return 'unknown'\n}\n\n/** Best-effort app name from the current dir's wrangler.toml, if any. */\nfunction detectAppName(): string | undefined {\n try {\n const cwd = process.cwd()\n if (!hasWranglerConfig(cwd)) return undefined\n const config = readWranglerConfig(cwd)\n return typeof config.name === 'string' ? config.name : undefined\n } catch {\n return undefined\n }\n}\n\n/** Clamp a best-effort context value so it can never block submission. */\nfunction clampContext(value: string): string {\n return value.length > MAX_CONTEXT_LEN ? value.slice(0, MAX_CONTEXT_LEN) : value\n}\n\n/** Collect the environment context attached to every report. */\nexport function collectContext(): FeedbackContext {\n const appName = detectAppName()\n return {\n cliVersion: clampContext(readCliVersion()),\n nodeVersion: clampContext(process.version),\n platform: clampContext(`${process.platform} ${release()}`),\n ...(appName ? { appName: clampContext(appName) } : {}),\n }\n}\n\n/** Assemble the request body. Trims and validates title/body are non-empty. */\nexport function buildFeedbackPayload(input: {\n type: string | undefined\n title: string\n body: string\n context: FeedbackContext\n}): FeedbackPayload {\n const title = input.title.trim()\n const body = input.body.trim()\n if (!title) throw new Error('A title is required.')\n if (!body) throw new Error('A message/description is required.')\n if (title.length > MAX_TITLE_LEN) {\n throw new Error(`Title must be ${MAX_TITLE_LEN} characters or fewer (got ${title.length}).`)\n }\n if (body.length > MAX_BODY_LEN) {\n throw new Error(`Description must be ${MAX_BODY_LEN} characters or fewer (got ${body.length}).`)\n }\n return {\n type: normalizeType(input.type),\n title,\n body,\n ...input.context,\n }\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'feedback',\n description: 'Submit a bug report, feature request, or feedback to DeepSpace',\n },\n args: {\n title: {\n type: 'positional',\n description: 'Short summary (prompted if omitted in a terminal)',\n required: false,\n },\n type: {\n type: 'string',\n alias: 't',\n description: `Report type: ${TYPES.join(' | ')} (default: bug)`,\n required: false,\n },\n message: {\n type: 'string',\n alias: 'm',\n description: 'Details / description (prompted if omitted in a terminal)',\n required: false,\n },\n yes: {\n type: 'boolean',\n description: 'Skip the confirmation prompt',\n default: false,\n },\n },\n async run({ args }) {\n const interactive = Boolean(process.stdin.isTTY) && !args.json\n\n let type: FeedbackType\n try {\n type = normalizeType(args.type ? String(args.type) : undefined)\n } catch (err) {\n throw new Refusal((err as Error).message, 'invalid_type')\n }\n\n let title = args.title ? String(args.title) : ''\n let body = args.message ? String(args.message) : ''\n\n // Non-interactive callers (agents/CI) must supply both fields up front.\n if ((!title || !body) && !interactive) {\n throw new Refusal(\n 'Provide a title and --message to submit non-interactively, ' +\n 'e.g. `deepspace feedback \"Title\" --message \"Details\"`.',\n 'missing_input',\n )\n }\n\n // Prompt for whatever is still missing — including the type, so an\n // interactive user who passed --title/--message but no --type is still\n // asked rather than having it silently default to \"bug\".\n if (interactive && (!args.type || !title || !body)) {\n p.intro('DeepSpace Feedback')\n\n if (!args.type) {\n const picked = await p.select({\n message: 'What kind of feedback is this?',\n options: TYPES.map((t) => ({ value: t, label: TYPE_LABELS[t] })),\n initialValue: type,\n })\n if (p.isCancel(picked)) {\n p.cancel('Cancelled.')\n return { data: { submitted: false, cancelled: true } }\n }\n type = picked as FeedbackType\n }\n\n if (!title) {\n const t = await p.text({\n message: 'Title',\n placeholder: 'Short summary of the issue',\n validate: (v) => {\n if (!v?.trim()) return 'Title is required'\n if (v.length > MAX_TITLE_LEN)\n return `Title must be ${MAX_TITLE_LEN} characters or fewer`\n return undefined\n },\n })\n if (p.isCancel(t)) {\n p.cancel('Cancelled.')\n return { data: { submitted: false, cancelled: true } }\n }\n title = String(t)\n }\n\n if (!body) {\n const m = await p.text({\n message: 'Details',\n placeholder: 'What happened? Steps to reproduce, what you expected…',\n validate: (v) => {\n if (!v?.trim()) return 'A description is required'\n if (v.length > MAX_BODY_LEN)\n return `Description must be ${MAX_BODY_LEN} characters or fewer`\n return undefined\n },\n })\n if (p.isCancel(m)) {\n p.cancel('Cancelled.')\n return { data: { submitted: false, cancelled: true } }\n }\n body = String(m)\n }\n }\n\n let payload: FeedbackPayload\n try {\n payload = buildFeedbackPayload({\n type,\n title,\n body,\n context: collectContext(),\n })\n } catch (err) {\n throw new Refusal((err as Error).message, 'invalid_input')\n }\n\n // Confirmation — only when interactive and not explicitly skipped.\n if (interactive && !args.yes) {\n p.note(\n `${TYPE_LABELS[payload.type]}\\n${payload.title}\\n\\n${payload.body}` +\n `\\n\\nContext: deepspace ${payload.cliVersion} · ${payload.nodeVersion} · ${payload.platform}` +\n (payload.appName ? ` · app ${payload.appName}` : ''),\n 'Review',\n )\n const ok = await p.confirm({ message: 'Send this to the DeepSpace team?' })\n if (p.isCancel(ok) || !ok) {\n p.cancel('Not sent.')\n return { data: { submitted: false, cancelled: true } }\n }\n }\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err) {\n throw new Refusal(\n (err as Error).message ?? 'Not signed in. Run `deepspace auth login`.',\n 'not_authenticated',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n\n // The POST is left uncaught on purpose: apiFetch throws a typed ApiError\n // whose `code` the runtime already lifts into the envelope, so wrapping it\n // here would only replace a real server slug with a made-up one.\n const result = await api<{ report: FeedbackReport }>(token, '/api/feedback', {\n method: 'POST',\n body: JSON.stringify(payload),\n })\n\n if (!args.json) {\n if (interactive) {\n p.outro(`Thanks! Submitted as ${result.report.id}.`)\n } else {\n console.log(`Submitted feedback ${result.report.id} (${result.report.type}).`)\n }\n console.log(`Track triage status at ${DASHBOARD_URL}.`)\n }\n\n // Terminal operation — nothing to run next, so no `next` (never filler).\n return { data: { report: result.report as unknown as Record<string, unknown> } }\n },\n})\n","/**\n * `deepspace secrets` — manage the app's secrets store.\n *\n * Every app has exactly one store, addressed by its immutable id (the\n * DEEPSPACE_APP_ID in wrangler.toml); configs follow the wrangler-env\n * convention (top-level → `prd`, `--env staging` → `staging`). There is no\n * project/link setup step: run the commands from the app directory (or pass\n * --app <appId>) and they just work — for the owner, collaborators, and\n * admin accounts alike.\n *\n * deepspace secrets list [-c prd]\n * deepspace secrets set KEY=value [KEY2=value2 …]\n * deepspace secrets get KEY [--plain]\n * deepspace secrets delete KEY [KEY2 …]\n * deepspace secrets upload <file> (dotenv or JSON; --replace)\n * deepspace secrets download [--format dotenv|json|shell]\n * deepspace secrets pull (refresh the .dev.vars cache)\n * deepspace secrets configs list|create|delete\n */\n\nimport { defineCommand } from 'citty'\nimport { readFileSync } from 'node:fs'\nimport { ensureToken } from '../auth'\nimport { decodeJwtPayload } from '../jwt'\nimport { PLATFORM_URLS } from '../env'\nimport { findAppDir } from '../lib/app-context'\nimport { writeDevVars } from '../lib/dev-vars'\nimport { parseAppArg } from '../lib/app-target'\nimport { InputError, renderCliError } from '../lib/cli-errors'\nimport { readAppId, APP_ID_RE } from '../lib/app-identity'\nimport { dedupePositionals } from '../lib/citty-args'\nimport {\n createConfig,\n defaultConfigNameForEnv,\n deleteConfig,\n deleteSecret,\n fetchSecretsValues,\n formatSecretsDownload,\n getSecretPlain,\n listConfigs,\n listSecrets,\n parseSecretsUpload,\n pullAppSecretsCache,\n renderSecretsCache,\n setSecret,\n uploadSecrets,\n validateConfigName,\n validateSecretName,\n validateSecretValue,\n type SecretsDownloadFormat,\n} from '../lib/secrets'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nconst COMMON_ARGS = {\n app: {\n type: 'string' as const,\n alias: 'a',\n description: 'App id (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n config: {\n type: 'string' as const,\n alias: 'c',\n description: 'Config name (default: the --env name, or \"prd\")',\n required: false,\n },\n env: {\n type: 'string' as const,\n alias: 'e',\n description: 'wrangler.toml [env.<name>] slot — selects that env’s app id and config',\n required: false,\n },\n json: {\n type: 'boolean' as const,\n description: 'Emit a single-line JSON result for scripts/agents',\n default: false,\n },\n}\n\ninterface Target {\n appId: string\n configName: string\n token: string\n}\n\nasync function resolveTarget(args: {\n app?: string\n config?: string\n env?: string\n}): Promise<Target> {\n const wranglerEnv = args.env?.trim() || undefined\n // An explicit blank --app must not silently fall back to the current dir's app\n // — secrets are written to the target app, so a wrong target leaks/overwrites.\n const { error: appErr } = parseAppArg(args.app)\n if (appErr) throw new InputError(appErr, 'invalid_app')\n let appId = args.app?.trim()\n if (appId && !APP_ID_RE.test(appId)) {\n throw new InputError(`Invalid app id \"${appId}\" — expected app_<26 chars>.`, 'invalid_app_id')\n }\n if (!appId) {\n const appDir = findAppDir()\n appId = (appDir && readAppId(appDir, wranglerEnv)) || undefined\n if (!appId) {\n // `--env <name>` selects a wrangler [env.<name>] slot with its OWN app id.\n // If the slot is missing but a top-level app id exists, the user almost\n // certainly wanted to pick a *config*, not an env — point them at `-c`.\n if (wranglerEnv && appDir && readAppId(appDir, undefined)) {\n throw new InputError(\n `No app id for env \"${wranglerEnv}\" — wrangler.toml has no [env.${wranglerEnv}] block with its own DEEPSPACE_APP_ID. ` +\n `To target the \"${wranglerEnv}\" config on this app, use \\`-c ${wranglerEnv}\\` instead of \\`--env ${wranglerEnv}\\`.`,\n 'no_app_id_for_env',\n )\n }\n throw new InputError(\n 'No app id. Run from an app directory whose wrangler.toml carries DEEPSPACE_APP_ID (`deepspace app init` mints one), or pass --app <appId>.',\n 'not_in_app_repo',\n )\n }\n }\n const configName = validateConfigName(args.config?.trim() || defaultConfigNameForEnv(wranglerEnv))\n const token = await ensureToken()\n return { appId, configName, token }\n}\n\nfunction fail(err: unknown): never {\n // Route through the shared renderer so `secrets` obeys the output contract\n // like every other command: `--json` gets the {ok,code,error} envelope on\n // stdout, the human path gets the message with its slug appended.\n renderCliError(err)\n}\n\n/**\n * A success result on the contract. Under `--json` it is the single\n * `{ ok: true, … }` line; otherwise it runs the human callback. Wires the\n * success paths that used to print prose regardless of `--json`.\n */\nfunction ok(json: boolean, data: Record<string, unknown>, human: () => void): void {\n if (json) console.log(JSON.stringify({ ok: true, ...data }))\n else human()\n}\n\n/**\n * Warn (once) when a write turns on the unauthenticated debug API. Applies to\n * every write path that can carry it — `set` and `upload` alike. Returns true\n * when it warned, so callers can skip the generic \"run deploy\" line (this\n * message already tells the user to redeploy).\n */\nfunction warnIfDebugRoutesEnabled(secrets: Record<string, string>): boolean {\n if (secrets.ALLOW_DEBUG_ROUTES !== 'true') return false\n console.warn(\n '\\n⚠ ALLOW_DEBUG_ROUTES=true exposes an UNAUTHENTICATED debug API on the deployed app —\\n' +\n ' anyone who can reach /api/debug/* can read and mutate any record. Redeploy to apply;\\n' +\n ' `deepspace secrets delete ALLOW_DEBUG_ROUTES` (then redeploy) turns it back off.',\n )\n return true\n}\n\nconst APPLY_HINT = 'Run `deepspace deploy` to apply — secrets take effect at deploy time.'\n// `deepspace dev start` regenerates .dev.vars from the store only at startup, so a\n// secret changed mid-session isn't picked up until dev restarts (DEV-4).\nconst LOCAL_DEV_HINT = 'Running `deepspace dev start`? Restart it to load the change locally.'\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List masked secrets in a config' },\n args: {\n ...COMMON_ARGS,\n 'only-names': {\n type: 'boolean',\n description: 'Only print secret names; omit values and metadata',\n default: false,\n },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const { secrets } = await listSecrets(DEPLOY_URL, t.token, t.appId, t.configName)\n if (args.json) {\n console.log(JSON.stringify({ ok: true, appId: t.appId, config: t.configName, secrets }))\n return\n }\n if (secrets.length === 0) {\n console.log(`No secrets in ${t.configName}.`)\n return\n }\n for (const s of secrets) {\n console.log(args['only-names'] ? s.key : `${s.key} (v${s.version}, ${s.updatedAt})`)\n }\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst set = defineCommand({\n meta: { name: 'set', description: 'Set secrets from KEY=value pairs' },\n args: {\n ...COMMON_ARGS,\n secret: { type: 'positional', description: 'KEY=value (repeatable)', required: true },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const pairs = dedupePositionals(args.secret, args._)\n const secrets: Record<string, string> = {}\n const dupes: string[] = []\n for (const pair of pairs) {\n const eq = pair.indexOf('=')\n if (eq <= 0) throw new InputError(`Expected KEY=value, got \"${pair}\"`, 'invalid_pair')\n const key = validateSecretName(pair.slice(0, eq))\n const value = pair.slice(eq + 1)\n validateSecretValue(key, value)\n // The same KEY given twice (with different values) silently keeps the\n // last — surface it instead of dropping a value without a word.\n if (key in secrets && !dupes.includes(key)) dupes.push(key)\n secrets[key] = value\n }\n if (dupes.length) {\n console.warn(\n `Warning: ${dupes.join(', ')} given more than once — kept the last value for each.`,\n )\n }\n if (Object.keys(secrets).length === 1) {\n const [[k, v]] = Object.entries(secrets)\n await setSecret(DEPLOY_URL, t.token, t.appId, t.configName, k, v)\n } else {\n await uploadSecrets(DEPLOY_URL, t.token, t.appId, t.configName, secrets, false)\n }\n const n = Object.keys(secrets).length\n ok(\n args.json === true,\n { appId: t.appId, config: t.configName, set: Object.keys(secrets) },\n () => {\n console.log(`Set ${n} secret${n === 1 ? '' : 's'} in ${t.configName}.`)\n if (!warnIfDebugRoutesEnabled(secrets)) {\n console.log(APPLY_HINT)\n console.log(LOCAL_DEV_HINT)\n }\n },\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst get = defineCommand({\n meta: { name: 'get', description: 'Get a secret; pass --plain to print the value' },\n args: {\n ...COMMON_ARGS,\n key: { type: 'positional', description: 'Secret name', required: true },\n plain: { type: 'boolean', description: 'Print the plaintext value', default: false },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const key = validateSecretName(args.key)\n if (args.plain) {\n const { value } = await getSecretPlain(DEPLOY_URL, t.token, t.appId, t.configName, key)\n // Raw value, byte-exact when piped (`… get --plain KEY > key.pem`) — a\n // --json wrapper would corrupt it, so --plain is a raw stream either\n // way (documented exception, like `download`). Trailing newline only\n // for a human at a TTY.\n process.stdout.write(process.stdout.isTTY ? value + '\\n' : value)\n return\n }\n const { secrets } = await listSecrets(DEPLOY_URL, t.token, t.appId, t.configName)\n const item = secrets.find((s) => s.key === key)\n if (!item)\n fail(new InputError(`Secret \"${key}\" not found in ${t.configName}`, 'secret_not_found'))\n ok(\n args.json === true,\n {\n appId: t.appId,\n config: t.configName,\n key: item!.key,\n version: item!.version,\n updatedAt: item!.updatedAt,\n },\n () => console.log(`${item!.key} (v${item!.version}, ${item!.updatedAt})`),\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst del = defineCommand({\n meta: { name: 'delete', description: 'Delete one or more secrets' },\n args: {\n ...COMMON_ARGS,\n key: { type: 'positional', description: 'Secret name (repeatable)', required: true },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const keys = dedupePositionals(args.key, args._)\n let deleted = 0\n let absent = 0\n for (const key of keys) {\n const name = validateSecretName(key)\n try {\n await deleteSecret(DEPLOY_URL, t.token, t.appId, t.configName, name)\n deleted++\n } catch (err) {\n // An already-absent key is a completed delete, not a failure: don't\n // let one missing key abort the rest, and keep retries idempotent.\n if ((err as { status?: number })?.status === 404) absent++\n else throw err\n }\n }\n const note = absent > 0 ? ` (${absent} already absent)` : ''\n ok(args.json === true, { appId: t.appId, config: t.configName, deleted, absent }, () => {\n console.log(\n `Deleted ${deleted} secret${deleted === 1 ? '' : 's'} from ${t.configName}.${note}`,\n )\n if (deleted > 0) console.log(APPLY_HINT)\n })\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst upload = defineCommand({\n meta: { name: 'upload', description: 'Upload secrets from a dotenv or JSON file' },\n args: {\n ...COMMON_ARGS,\n file: {\n type: 'positional',\n description: 'Path to a dotenv or JSON file (- for stdin)',\n required: true,\n },\n replace: {\n type: 'boolean',\n description: 'Replace the whole config (delete keys missing from the file)',\n default: false,\n },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const content =\n args.file === '-' ? readFileSync(0, 'utf-8') : readFileSync(args.file, 'utf-8')\n const secrets = parseSecretsUpload(content)\n if (Object.keys(secrets).length === 0)\n fail(new InputError('No secrets found in the input.', 'empty_input'))\n await uploadSecrets(DEPLOY_URL, t.token, t.appId, t.configName, secrets, args.replace)\n const uploaded = Object.keys(secrets)\n ok(\n args.json === true,\n { appId: t.appId, config: t.configName, uploaded, replaced: args.replace === true },\n () => {\n console.log(`Uploaded ${uploaded.length} secrets to ${t.configName}.`)\n // A file can turn on the debug API just like `set` can — warn either way.\n if (!warnIfDebugRoutesEnabled(secrets)) console.log(APPLY_HINT)\n },\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst download = defineCommand({\n meta: { name: 'download', description: 'Download a config’s secrets (dotenv/json/shell)' },\n args: {\n ...COMMON_ARGS,\n format: {\n type: 'string',\n description: 'dotenv (default) | json | shell',\n default: 'dotenv',\n },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const format = args.format as SecretsDownloadFormat\n if (!['dotenv', 'json', 'shell'].includes(format)) {\n fail(\n new InputError(\n `Unknown format \"${args.format}\" — use dotenv, json, or shell.`,\n 'invalid_format',\n ),\n )\n }\n const { secrets } = await fetchSecretsValues(DEPLOY_URL, t.token, t.appId, t.configName)\n process.stdout.write(formatSecretsDownload(secrets, format))\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst pull = defineCommand({\n meta: { name: 'pull', description: 'Refresh the .dev.vars cache from the app store' },\n args: { ...COMMON_ARGS },\n async run({ args }) {\n try {\n const wranglerEnv = args.env?.trim() || undefined\n const appDir = findAppDir()\n if (!appDir)\n fail(\n new InputError(\n 'Run from a DeepSpace app directory (one containing wrangler.toml).',\n 'not_in_app_repo',\n ),\n )\n const t = await resolveTarget(args)\n const ownerId = decodeJwtPayload<{ sub: string }>(t.token).sub\n const pulled = await pullAppSecretsCache(DEPLOY_URL, t.token, t.appId, t.configName)\n if (!pulled) {\n // A collaborator's first pull on a fresh clone often lands here —\n // point at how secrets get INTO the store, not just that it's empty.\n ok(args.json === true, { appId: t.appId, config: t.configName, pulled: 0 }, () =>\n console.log(\n `No secrets in ${t.configName} yet — nothing to pull. Whoever has them adds them with \\`deepspace secrets set KEY=value\\` (or \\`secrets upload <file>\\`); if the app truly needs none, you're ready as-is.`,\n ),\n )\n return\n }\n await writeDevVars(appDir, ownerId, t.token, wranglerEnv, {\n appId: t.appId,\n generatedSecretsCache: renderSecretsCache(pulled.values, pulled),\n sharedDevVarsCache: true,\n })\n const count = Object.keys(pulled.values).length\n ok(args.json === true, { appId: t.appId, config: t.configName, pulled: count }, () =>\n console.log(`Pulled ${count} secrets (${t.configName}) into .dev.vars.`),\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst configsList = defineCommand({\n meta: { name: 'list', description: 'List the app’s configs' },\n args: { ...COMMON_ARGS },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const { configs } = await listConfigs(DEPLOY_URL, t.token, t.appId)\n ok(args.json === true, { appId: t.appId, configs }, () => {\n if (configs.length === 0) {\n console.log('No configs yet — the first `secrets set` creates one.')\n return\n }\n for (const cfg of configs) {\n console.log(`${cfg.name} (${cfg.secretCount ?? 0} secrets, updated ${cfg.updatedAt})`)\n }\n })\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst configsCreate = defineCommand({\n meta: { name: 'create', description: 'Create a config (optionally copying another)' },\n args: {\n ...COMMON_ARGS,\n name: { type: 'positional', description: 'Config name', required: true },\n 'copy-from': { type: 'string', description: 'Copy secrets from this config', required: false },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const name = validateConfigName(args.name)\n const copyFrom = args['copy-from'] || undefined\n // Create is idempotent server-side, so a plain create of an existing\n // config used to print a false \"Created\". Distinguish the cases up front:\n // a bare re-create is a no-op (\"Already exists.\"); a --copy-from into an\n // existing config would clobber it, so refuse rather than silently create.\n const { configs } = await listConfigs(DEPLOY_URL, t.token, t.appId)\n if (configs.some((c) => c.name === name)) {\n if (copyFrom) {\n fail(\n new InputError(\n `Config \"${name}\" already exists — refusing to copy \"${copyFrom}\" over it. Delete it first, or pick a new name.`,\n 'config_exists',\n ),\n )\n }\n ok(args.json === true, { appId: t.appId, config: name, created: false }, () =>\n console.log(`Config ${name} already exists.`),\n )\n return\n }\n await createConfig(DEPLOY_URL, t.token, t.appId, name, copyFrom)\n ok(\n args.json === true,\n { appId: t.appId, config: name, created: true, ...(copyFrom ? { copyFrom } : {}) },\n () => console.log(`Created ${name}.`),\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst configsDelete = defineCommand({\n meta: { name: 'delete', description: 'Delete a config and all of its secrets' },\n args: {\n ...COMMON_ARGS,\n name: { type: 'positional', description: 'Config name', required: true },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const name = validateConfigName(args.name)\n await deleteConfig(DEPLOY_URL, t.token, t.appId, name)\n ok(args.json === true, { appId: t.appId, config: name, deleted: true }, () =>\n console.log(`Deleted ${name}.`),\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst configs = defineCommand({\n meta: { name: 'configs', description: 'Manage the app’s secrets configs' },\n subCommands: { list: configsList, create: configsCreate, delete: configsDelete },\n})\n\nexport default defineCommand({\n meta: { name: 'secrets', description: 'Manage the app’s secrets store' },\n subCommands: {\n list,\n set,\n get,\n delete: del,\n upload,\n download,\n pull,\n configs,\n },\n})\n","/**\n * Helpers for citty argument quirks.\n */\n\n/**\n * citty binds the first positional to its named arg AND *also* leaves the full\n * positional list in `args._`. A handler that naively unions `[named, ...args._]`\n * therefore processes the first positional twice — which silently broke\n * `secrets delete`: it deleted a key, re-attempted the same key, got a 404, and\n * aborted the rest (`delete A B` kept B; a single `delete A` exited 1 on success).\n *\n * Union + dedupe (dropping empties / non-strings) yields the caller's distinct\n * positionals exactly once, in first-seen order. Use this anywhere a command\n * accepts a repeatable positional.\n */\nexport function dedupePositionals(bound: unknown, rest: unknown): string[] {\n const restArr = Array.isArray(rest) ? rest : []\n return [...new Set([bound, ...restArr])].filter(\n (v): v is string => typeof v === 'string' && v.length > 0,\n )\n}\n\n// A page size / cursor is a plain base-10 non-negative integer — either a count\n// a human typed or, for a cursor, the exact token the server handed back.\n// Matching on the digit STRING (after trimming surrounding whitespace) rather\n// than coercing with Number() is deliberate: Number() is far too lenient here —\n// it maps whitespace-only input to 0 (`Number(\" \") === 0`, which silently\n// replayed history for a corrupted cursor), and accepts hex/binary/scientific/\n// float spellings (`0x10`, `1e3`, `5.0`) that the server never emits. `\\d+`\n// admits none of those, nor a sign, so negatives fall through to the error path.\n// Digits alone don't bound magnitude, so callers also require Number.isSafeInteger:\n// a value past 2^53 (e.g. `9007199254740993`) would round when parsed, and the\n// CLI echoes the cursor back to the server verbatim — a silently-rounded cursor\n// breaks the \"you get back the token you sent\" invariant. No legitimate page\n// size or cursor approaches 2^53, so rejecting the unsafe range costs nothing.\nconst NON_NEGATIVE_INT_RE = /^\\d+$/\n\n/**\n * Parse a user-supplied `--limit`. An absent flag yields `undefined` (the\n * server applies its own default page size). A present-but-invalid value —\n * non-numeric, fractional, signed, whitespace-only, past 2^53, or ≤ 0 — yields\n * an `error` string instead of silently collapsing to \"no limit\": the old\n * `args.limit ? Number(args.limit) : undefined` (and the `Number(x) || undefined`\n * variant) turned `--limit nope` and `--limit 0` into an UNBOUNDED request, so an\n * automation asking for a small page could get the entire list back without any\n * signal. Callers surface the error through their own `fail(...)` as\n * `code:\"invalid_limit\"`.\n */\nexport function parseLimitArg(raw: unknown): { limit?: number; error?: string } {\n if (raw === undefined || raw === null || raw === '') return {}\n const s = String(raw).trim()\n const n = Number(s)\n if (!NON_NEGATIVE_INT_RE.test(s) || !Number.isSafeInteger(n) || n <= 0) {\n return { error: `Invalid --limit: ${String(raw)} (expected a positive integer).` }\n }\n return { limit: n }\n}\n\n/**\n * Parse an activity `--since` cursor. An absent flag (or an empty string, the\n * shell idiom for \"no saved cursor yet\") yields cursor 0 (start of history). Any\n * other present value must be a non-negative integer the server handed back — a\n * fractional one like `1.9`, a whitespace-only one, or one past 2^53 yields an\n * `error` rather than being floored/coerced/rounded: silently replaying an\n * earlier page (or echoing back a rounded cursor) is exactly what an agent with\n * a corrupted saved cursor would mistake for new activity. Callers surface the\n * error as `code:\"invalid_cursor\"`.\n */\nexport function parseCursorArg(raw: unknown): { cursor: number; error?: string } {\n if (raw === undefined || raw === null || raw === '') return { cursor: 0 }\n const s = String(raw).trim()\n const n = Number(s)\n if (!NON_NEGATIVE_INT_RE.test(s) || !Number.isSafeInteger(n)) {\n return {\n cursor: 0,\n error: `Invalid --since cursor: ${String(raw)} (expected the integer cursor returned by a previous page).`,\n }\n }\n return { cursor: n }\n}\n","/**\n * `deepspace app init` — ensure this app carries its immutable identity.\n *\n * Mints DEEPSPACE_APP_ID into wrangler.toml (per wrangler env with --env).\n * Registration happens at the first deploy. `--new-id` replaces an existing\n * id, which FORKS the repo into a separate app: fresh registration, fresh\n * Durable Object data, fresh secrets store — the original app is untouched.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, the `Next:` line and the exit codes come from there.\n */\n\nimport { findAppDir } from '../lib/app-context'\nimport { mintAppId, readAppId, writeAppId } from '../lib/app-identity'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'init',\n description: 'Mint this app’s immutable DEEPSPACE_APP_ID into wrangler.toml',\n },\n args: {\n 'new-id': {\n type: 'boolean',\n description:\n 'Replace the existing id — forks this repo as a SEPARATE app (new data, new secrets, new registration). The original app keeps running.',\n default: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description: 'wrangler.toml [env.<name>] block to stamp (each env is its own app)',\n required: false,\n },\n },\n async run({ args }) {\n const appDir = findAppDir()\n if (!appDir) {\n throw new Refusal(\n 'No wrangler.toml here — `deepspace app init` stamps an app id into an existing ' +\n 'DeepSpace app. To create a new app, run `deepspace app create <name>` (or ' +\n '`npm create deepspace@latest <name>`), then run this from inside it.',\n 'not_an_app',\n )\n }\n const envName = (args.env as string) || undefined\n const existing = readAppId(appDir, envName)\n if (existing && !args['new-id']) {\n if (!args.json) {\n console.log(`Already initialized: ${existing}${envName ? ` (env: ${envName})` : ''}`)\n console.log(`App dir: ${appDir}`)\n }\n return {\n data: { status: 'already_initialized', appId: existing, appDir, env: envName ?? null },\n }\n }\n const appId = mintAppId()\n writeAppId(appDir, appId, { wranglerEnv: envName, force: Boolean(args['new-id']) })\n if (!args.json) {\n if (existing) {\n console.log(`Forked: ${existing} → ${appId}${envName ? ` (env: ${envName})` : ''}`)\n console.log('The next deploy registers this as a NEW app; the original is untouched.')\n } else {\n console.log(`Minted ${appId}${envName ? ` (env: ${envName})` : ''} — commit wrangler.toml.`)\n console.log('The first deploy registers it and claims the `name` subdomain.')\n }\n console.log(`App dir: ${appDir}`)\n }\n return {\n data: {\n status: existing ? 'forked' : 'minted',\n appId,\n ...(existing ? { previousAppId: existing } : {}),\n appDir,\n env: envName ?? null,\n },\n }\n },\n})\n","/**\n * `deepspace status` — one screenful of present-tense truth, so an agent\n * re-orients from a single command after any context loss instead of\n * reconstructing state from five reads and memory.\n *\n * State, not story: session, app, deps, branch/workspace position, live\n * and release. No narrative, no summarization — interpretation is the agent's\n * job. Recovery commands belong to the operation that refuses, not to a\n * centralized cross-product of every possible status fact. Live coordination\n * facts stream separately through `deepspace activity --follow`.\n *\n * Network sections are fetched in parallel and degrade PER LINE to\n * `(unreachable)` — status must never fail to report the local facts it has.\n * Informational throughout: exit 0 whenever the report itself was produced.\n */\n\nimport { defineCommand } from 'citty'\nimport * as p from '@clack/prompts'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { SESSION_PATH, TOKEN_PATH, ensureToken } from '../auth'\nimport { DEEPSPACE_ENV, effectivePlatformUrls } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { findAppDir, detectAppName } from '../lib/app-context'\nimport { readAppId } from '../lib/app-identity'\nimport { currentBranch, isAncestor, resolveCommit } from '../lib/git/repository'\nimport { statusFiles } from '../lib/git/safety'\nimport { workspaceIdFromBranch } from '../lib/workspace-id'\nimport { deployBaseUrl } from '../lib/vc-remote'\nimport { repoApi, type RemoteRelease, type RemoteWorkspaceView } from '../lib/repo-api'\nimport { errorCode } from '../lib/cli-errors'\nimport { installState } from '../lib/install-status'\nimport { installCommand } from '../lib/package-manager'\nimport { createSpinner } from '../lib/spinner'\n\nfunction timeAgo(iso: string): string {\n const ms = Date.now() - Date.parse(iso)\n if (!Number.isFinite(ms) || ms < 0) return iso\n const m = Math.floor(ms / 60_000)\n if (m < 1) return 'just now'\n if (m < 60) return `${m}m ago`\n const h = Math.floor(m / 60)\n if (h < 48) return `${h}h ago`\n return `${Math.floor(h / 24)}d ago`\n}\n\nconst UNREACHABLE = '(unreachable)'\n\ntype RemoteResult<T> = { ok: true; value: T } | { ok: false; error: unknown }\n\nconst observeRemote = <T>(promise: Promise<T>): Promise<RemoteResult<T>> =>\n promise.then(\n (value) => ({ ok: true, value }),\n (error: unknown) => ({ ok: false, error }),\n )\n\nexport function statusRemoteFailure(error: unknown): {\n human: string\n json: { state: 'unavailable'; error: string; code?: string }\n} {\n const message = error instanceof Error ? error.message : String(error)\n const code = errorCode(error)\n const suffix = code ? ` [${code}]` : ''\n return {\n human:\n code === 'network_error' ? `${UNREACHABLE} — ${message}${suffix}` : `${message}${suffix}`,\n json: { state: 'unavailable', error: message, ...(code ? { code } : {}) },\n }\n}\n\nexport default defineCommand({\n meta: {\n name: 'status',\n description: 'One screenful of current state: session, app, workspace, and live release',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Emit a single-line JSON result for scripts/agents',\n default: false,\n },\n },\n async run({ args }) {\n const lines: Array<[string, string]> = []\n const facts = {\n loggedIn: false,\n workspaceId: null as string | null,\n dirtyFiles: 0,\n unsynced: false,\n aheadOfBase: 0,\n trunkState: 'unknown' as\n | 'in_sync'\n | 'local_ahead'\n | 'local_behind'\n | 'diverged'\n | 'differs'\n | 'unknown',\n }\n const json: Record<string, unknown> = { ok: true }\n\n // ── environment (print ONLY when not plain prod — half of all staging\n // confusion is not being able to see which plane a command talks to) ──\n const urlOverrides = [\n 'DEEPSPACE_DEPLOY_URL',\n 'DEEPSPACE_AUTH_URL',\n 'DEEPSPACE_API_URL',\n 'DEEPSPACE_PLATFORM_URL',\n ].filter((k) => process.env[k])\n if (DEEPSPACE_ENV !== 'production' || urlOverrides.length > 0) {\n const urls = effectivePlatformUrls()\n const detail = [\n DEEPSPACE_ENV !== 'production' ? DEEPSPACE_ENV : null,\n ...urlOverrides.map((k) => `${k} set`),\n ]\n .filter(Boolean)\n .join(' · ')\n lines.push(['Env', detail])\n lines.push([\n 'Services',\n `auth ${urls.auth} · api ${urls.api} · platform ${urls.platform} · deploy ${urls.deploy}`,\n ])\n json.env = DEEPSPACE_ENV\n json.services = urls\n if (urlOverrides.length > 0) json.urlOverrides = urlOverrides\n }\n\n // ── session (local only — never blocks on the network) ──────────────\n facts.loggedIn = existsSync(SESSION_PATH)\n let userId: string | null = null\n if (!facts.loggedIn) {\n lines.push(['Session', 'not logged in'])\n json.loggedIn = false\n } else {\n let who = 'logged in'\n try {\n const payload = decodeJwtPayload<{ email?: string; sub?: string }>(\n readFileSync(TOKEN_PATH, 'utf-8').trim(),\n )\n if (payload.email) who = payload.email\n userId = payload.sub ?? null\n } catch {\n // token file absent/stale — the session still mints on next use\n }\n lines.push(['Session', `${who} · renews on use (re-login only after 30 idle days)`])\n json.loggedIn = true\n json.user = who\n }\n\n // ── app (local) ──────────────────────────────────────────────────────\n const appDir = findAppDir()\n if (!appDir) {\n lines.push(['App', 'not inside a DeepSpace app directory'])\n json.inApp = false\n } else {\n const appName = detectAppName(appDir) ?? '(unnamed)'\n const appId = readAppId(appDir)\n lines.push([\n 'App',\n `${appName}${appId ? ` (${appId})` : ' — no DEEPSPACE_APP_ID; run `deepspace app init`'}`,\n ])\n json.inApp = true\n json.appName = appName\n json.appId = appId\n\n const deps = installState(appDir)\n const depsInstallCommand = installCommand(appDir)\n lines.push([\n 'Deps',\n deps === 'ready'\n ? 'installed'\n : deps === 'installing'\n ? 'still installing (scaffold background install)'\n : `${deps} — run ${depsInstallCommand}`,\n ])\n json.deps = deps\n\n // ── local git position ────────────────────────────────────────────\n let branch: string | null = null\n try {\n branch = currentBranch(appDir)\n facts.dirtyFiles = statusFiles(appDir).length\n facts.workspaceId = workspaceIdFromBranch(branch)\n lines.push([\n 'Branch',\n `${branch ?? '(detached)'}${facts.workspaceId ? ` → workspace ${facts.workspaceId}` : ''}`,\n ])\n lines.push([\n 'Worktree',\n facts.dirtyFiles === 0\n ? 'clean'\n : `${facts.dirtyFiles} uncommitted file${facts.dirtyFiles === 1 ? '' : 's'}`,\n ])\n json.branch = branch\n json.workspaceId = facts.workspaceId\n json.dirtyFiles = facts.dirtyFiles\n } catch {\n lines.push(['Branch', 'not a git repository'])\n json.branch = null\n }\n\n // ── network facts, in parallel, each degrading alone ──────────────\n if (facts.loggedIn && appId) {\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Checking cloud state…')\n let token: string | null = null\n try {\n token = await ensureToken()\n } catch (err) {\n // Offline is NOT a dead session. exchangeSession's fetch REJECTS\n // when the network is down, and reporting that as \"expired\" both\n // lies and obscures every local fact status already gathered. Only\n // a real auth failure clears loggedIn.\n const offline = err instanceof TypeError || errorCode(err) === 'network_error'\n if (offline) {\n lines.push(['Cloud', `${UNREACHABLE} — local facts only`])\n json.cloudUnreachable = true\n } else {\n lines.push(['Cloud', 'session expired — run `deepspace auth login`'])\n facts.loggedIn = false\n json.sessionExpired = true\n }\n }\n if (token) {\n const api = repoApi(deployBaseUrl(), token, appId)\n const [refsResult, wsResult, releaseResult] = await Promise.all([\n observeRemote(api.getRefs()),\n facts.workspaceId\n ? observeRemote(api.getWorkspace(facts.workspaceId).then((r) => r.view))\n : Promise.resolve({ ok: true, value: null } as const),\n observeRemote(api.latestRelease().then((r) => r.release)),\n ] as const)\n\n // workspace position\n if (facts.workspaceId) {\n if (!wsResult.ok) reportRemoteFailure('Workspace', 'workspace', wsResult.error)\n else if (wsResult.value) reportWorkspace(wsResult.value)\n }\n function reportWorkspace(view: RemoteWorkspaceView): void {\n const localTip = branch ? resolveCommit(appDir!, `refs/heads/${branch}`) : null\n facts.unsynced = localTip !== null && view.tipOid !== localTip\n facts.aheadOfBase = view.aheadOfBase?.count ?? 0\n const behind = view.behindTrunk?.count ?? 0\n lines.push([\n 'Workspace',\n `\"${view.workspace.task}\" · ${facts.unsynced ? 'has UNSYNCED local commits' : 'synced'} · ` +\n `${facts.aheadOfBase} commit${facts.aheadOfBase === 1 ? '' : 's'} ahead of base · ` +\n (behind === 0 ? 'trunk unchanged since base' : `trunk moved ${behind} since base`),\n ])\n json.workspace = {\n task: view.workspace.task,\n unsynced: facts.unsynced,\n aheadOfBase: facts.aheadOfBase,\n behindTrunk: behind,\n }\n }\n\n // trunk position (only meaningful off a workspace branch)\n const refs = refsResult.ok ? refsResult.value : undefined\n const trunkRef = refs?.refs.find((r) => `refs/heads/${branch}` === r.name)\n if (!facts.workspaceId && branch) {\n if (!refsResult.ok) reportRemoteFailure('Trunk', 'trunk', refsResult.error)\n else {\n const remoteOid = trunkRef?.oid ?? null\n const localOid = resolveCommit(appDir, `refs/heads/${branch}`)\n const remoteKnownLocally = remoteOid\n ? resolveCommit(appDir, remoteOid) !== null\n : false\n facts.trunkState =\n remoteOid === null && localOid === null\n ? 'unknown'\n : remoteOid === localOid\n ? 'in_sync'\n : remoteOid &&\n localOid &&\n remoteKnownLocally &&\n isAncestor(appDir, remoteOid, localOid)\n ? 'local_ahead'\n : remoteOid &&\n localOid &&\n remoteKnownLocally &&\n isAncestor(appDir, localOid, remoteOid)\n ? 'local_behind'\n : remoteOid && localOid && remoteKnownLocally\n ? 'diverged'\n : 'differs'\n lines.push([\n 'Trunk',\n remoteOid === null\n ? `cloud repo has no ${branch} yet`\n : facts.trunkState === 'in_sync'\n ? `${branch} in sync with the cloud repo (${remoteOid.slice(0, 10)})`\n : `${branch} ${facts.trunkState.replace('_', ' ')} relative to the cloud repo (local ${localOid?.slice(0, 10) ?? 'none'}, cloud ${remoteOid.slice(0, 10)})`,\n ])\n json.trunk = { state: facts.trunkState, localOid, remoteOid }\n }\n }\n\n // live release\n if (!releaseResult.ok) reportRemoteFailure('Live', 'live', releaseResult.error)\n else if (releaseResult.value === null) {\n lines.push(['Live', 'never deployed'])\n json.live = null\n } else {\n reportRelease(releaseResult.value)\n }\n function reportRemoteFailure(label: string, key: string, error: unknown): void {\n const failure = statusRemoteFailure(error)\n lines.push([label, failure.human])\n json[key] = failure.json\n }\n function reportRelease(rel: RemoteRelease): void {\n const byYou = userId !== null && rel.actor === userId\n lines.push([\n 'Live',\n `release #${rel.seq} (${rel.kind} of ${rel.commitOid?.slice(0, 10) ?? 'unknown source'}, ${timeAgo(rel.createdAt)}${byYou ? ', by you' : ''})` +\n (rel.url ? ` · ${rel.url}` : ''),\n ])\n json.live = {\n seq: rel.seq,\n kind: rel.kind,\n commitOid: rel.commitOid,\n createdAt: rel.createdAt,\n url: rel.url,\n byYou,\n }\n }\n }\n spinner?.stop('Cloud state checked.')\n }\n }\n\n if (args.json) {\n console.log(JSON.stringify(json))\n return\n }\n const width = Math.max(...lines.map(([k]) => k.length))\n for (const [k, v] of lines) p.log.message(`${k.padEnd(width)} ${v}`)\n },\n})\n","/**\n * `deepspace push` — sync local git history to the app's cloud repo.\n *\n * The cloud repo is the platform-native remote every DeepSpace app gets,\n * keyed by its immutable app id: collaborators pull/clone from it without\n * GitHub, and deploys link releases to its commits.\n * Local work stays plain `git` — this command only moves committed history,\n * and the transfer itself IS `git push` (the wrapper adds app resolution,\n * auth injection, and machine-readable output).\n *\n * Fast-forward only by default (like git). `deepspace push --force` is GUARDED\n * (see run()): it refuses a force that would orphan a peer's committed work. That\n * guard is CLIENT-SIDE, though — a plain `git push --force space` through the\n * installed credential helper bypasses it, and the server ref-CAS does NOT reject\n * a force (git relearns the advertised old-oid). Fully preventing a force-clobber\n * would require server-side enforcement in the deploy worker.\n */\n\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { findAppDir } from '../lib/app-context'\nimport { resolveAppTarget, warnIfPhantomApp, assertAppTargetResolvable } from '../lib/app-target'\nimport {\n assertSyncableRepo,\n currentBranch,\n isAncestor,\n isPlausibleBranchName,\n listWorktrees,\n resolveCommit,\n updateRef,\n} from '../lib/git/repository'\nimport { SECRET_IN_HISTORY_CODE, trackedSecretFiles } from '../lib/git/safety'\nimport { workspaceIdFromBranch } from '../lib/workspace-id'\nimport { shQuote } from '../lib/cli-format'\nimport {\n classifyPushTransportFailure,\n isRecoverablePushFailure,\n OVERSIZED_PUSH_RE,\n oversizedPushFix,\n pushToSpace,\n} from '../lib/vc-push'\nimport { deployBaseUrl, ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../lib/vc-remote'\nimport { createSpinner } from '../lib/spinner'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport type { CliAction } from '../lib/output'\n\nfunction pullRecoveryAction(cwd: string, appId: string, branch: string): CliAction {\n return {\n cwd,\n argv: ['deepspace', 'pull', '--app', appId, '--branch', branch],\n }\n}\n\nfunction selectedBranchCheckout(appDir: string, branch: string): string | null {\n if (currentBranch(appDir) === branch) return appDir\n return listWorktrees(appDir).find((worktree) => worktree.branch === branch)?.path ?? null\n}\n\n/**\n * Whether a `--force` push of `tipOid` onto a branch would ORPHAN work — i.e.\n * drop commits that only the current remote tip holds. Refuse (true) unless the\n * force is safe: the remote tip is unset (first publish), equals the tip (up to\n * date), equals our own last-pushed record (a rewrite of our OWN line — the\n * legitimate reason to force), or is already CONTAINED in the tip (a normal\n * advance / we integrated it). Any other remote tip = a peer advanced the\n * branch to commits we lack, so forcing would silently lose their work. Pure —\n * the ancestry test (`tipContainsRemoteTip`) is injected so this is\n * unit-testable.\n */\nexport function forcePushOrphansWork(\n lastPushed: string | null,\n remoteTip: string | null,\n tipOid: string,\n tipContainsRemoteTip: boolean,\n): boolean {\n if (remoteTip === null) return false // no remote line yet — first publish\n if (remoteTip === tipOid) return false // already up to date\n if (remoteTip === lastPushed) return false // rewrite of our own line (no peer advance)\n return !tipContainsRemoteTip // else safe only if the tip already contains it\n}\n\n/** A `ws/<id>` branch is a workspace line: a plain push writes the visible\n * `refs/heads/ws/<id>` while `workspace sync` publishes the hidden coordination\n * ref AND records metadata. Pushing here looks successful yet leaves the\n * workspace tip, overlap warnings, and activity stale — so refuse and send the\n * agent to sync. Null on any ordinary branch (no behavior change). Pure +\n * exported for tests. */\nexport function workspaceBranchPushRefusal(\n branch: string | null,\n): { code: 'workspace_branch'; error: string } | null {\n const id = workspaceIdFromBranch(branch)\n if (!id) return null\n return {\n code: 'workspace_branch',\n error:\n `\"${branch}\" is a workspace branch (${id}). A plain push moves only the visible ref and ` +\n `bypasses workspace coordination — the workspace tip, overlap warnings, and activity would go ` +\n `stale. Publish it with \\`deepspace workspace sync\\` instead.`,\n }\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'push',\n description: \"Push local git commits to the app's cloud repo\",\n },\n args: {\n branch: {\n type: 'string',\n alias: 'b',\n description: 'Branch to push (default: the current branch)',\n required: false,\n },\n app: {\n type: 'string',\n alias: 'a',\n description:\n 'App id or subdomain name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n force: {\n type: 'boolean',\n description:\n 'Allow a non-fast-forward ref move to rewrite history you previously pushed with `deepspace push`. Guarded: refuses whenever the remote tip is a commit your branch does not contain, so no work is silently dropped (a first force from a fresh clone/pull is refused until you re-integrate that tip).',\n default: false,\n },\n },\n async run({ args }) {\n const branchArg = args.branch === undefined ? undefined : String(args.branch)\n const appArg = typeof args.app === 'string' ? args.app : undefined\n const force = args.force === true\n try {\n const appDir = findAppDir()\n if (!appDir)\n throw new Refusal(\n 'No wrangler.toml found — run from inside an app directory.',\n 'not_in_app_repo',\n )\n\n assertSyncableRepo(appDir)\n // An explicitly-blank --branch must not silently fall back to the current\n // branch (an unset `--branch \"$VAR\"` would push the wrong ref).\n if (branchArg !== undefined) {\n const b = branchArg.trim()\n if (!b) throw new Refusal('--branch was given an empty branch name.', 'invalid_branch')\n if (!isPlausibleBranchName(b))\n throw new Refusal(`--branch \"${b}\" is not a valid git branch name.`, 'invalid_branch')\n }\n const branch = branchArg?.trim() || currentBranch(appDir)\n if (!branch) {\n throw new Refusal(\n 'HEAD is detached — pass --branch <name> to choose what to push.',\n 'detached_head',\n )\n }\n const tipOid = resolveCommit(appDir, `refs/heads/${branch}`)\n if (!tipOid) {\n // refs/heads/<branch> doesn't resolve. If the repo HAS commits (HEAD\n // resolves), the branch simply doesn't exist — a typo'd -b, not an empty\n // repo. \"commit first\" is wrong advice there (committing on the current\n // branch never makes the missing ref appear — an agent would loop), so\n // give it a distinct code + remedy. Reserve no_commits for a genuinely\n // unborn repo (no HEAD at all).\n if (resolveCommit(appDir, 'HEAD')) {\n throw new Refusal(\n `Branch \"${branch}\" does not exist — create or switch to it first (e.g. git switch -c ${shQuote(branch)}), then push.`,\n 'unknown_branch',\n )\n }\n throw new Refusal(\n `Branch \"${branch}\" has no commits yet — commit first, then push.`,\n 'no_commits',\n )\n }\n\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Checking ${branch} before push…`)\n const resolveTarget = async (): Promise<{ token: string; appId: string }> => {\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const token = await ensureToken()\n // Accepts an id OR a subdomain name — a raw name must never pass\n // through as a literal app id (it would register a phantom app).\n const appId = await resolveAppTarget(deployBaseUrl(), token, appArg)\n await warnIfPhantomApp(deployBaseUrl(), token, appId, appArg?.trim() || undefined)\n return { token, appId }\n }\n\n // A workspace branch must go through `workspace sync`, not a plain push.\n // Resolve the target before emitting the continuation so a name or local\n // default cannot drift to another app when an agent executes it later.\n const wsRefusal = workspaceBranchPushRefusal(branch)\n if (wsRefusal) {\n const { appId } = await resolveTarget()\n const checkoutPath = selectedBranchCheckout(appDir, branch)\n const workspaceId = workspaceIdFromBranch(branch)\n if (!workspaceId) throw new Error(`Workspace branch did not contain an id: ${branch}`)\n const syncCommand =\n `deepspace workspace sync --app ${shQuote(appId)} ` +\n `--workspace ${shQuote(workspaceId)}`\n const quotedSyncCommand = `\\`${syncCommand}\\``\n const message = checkoutPath\n ? `${wsRefusal.error} Run ${quotedSyncCommand} from its checkout at ${checkoutPath}.`\n : `${wsRefusal.error} ${branch} exists locally but is not checked out. Check it out in a clean worktree, then run ${quotedSyncCommand}.`\n const action: CliAction | undefined = checkoutPath\n ? {\n cwd: checkoutPath,\n argv: ['deepspace', 'workspace', 'sync', '--app', appId, '--workspace', workspaceId],\n }\n : undefined\n spinner?.stop('Workspace branch.')\n throw new Refusal(message, wsRefusal.code, {\n actionRequired: action !== undefined,\n action,\n extra: { appId, branch, ...(checkoutPath ? { worktreePath: checkoutPath } : {}) },\n })\n }\n\n // Push IS `git push`, so it sends whatever was committed — including a\n // force-committed `.dev.vars` that .gitignore would normally keep out.\n // The push wrapper refuses them early; the server independently enforces\n // the same case-insensitive basename contract for raw Git clients.\n const secretFiles = trackedSecretFiles(appDir, tipOid)\n if (secretFiles.length > 0) {\n const checkoutPath = selectedBranchCheckout(appDir, branch)\n const checkoutNote = checkoutPath\n ? ''\n : ` Check out ${shQuote(branch)} in a clean worktree before untracking it.`\n throw new Refusal(\n `Refusing to push: the branch tracks secret file(s) — ${secretFiles.join(', ')}. ` +\n `These hold local secrets and must not reach the cloud repo. Untrack with ` +\n `\\`git rm --cached ${shQuote(secretFiles[0])}\\`, ensure it's .gitignored, commit, then push.` +\n checkoutNote,\n SECRET_IN_HISTORY_CODE,\n {\n action: checkoutPath\n ? { cwd: checkoutPath, argv: ['git', 'rm', '--cached', secretFiles[0]] }\n : undefined,\n extra: { branch, ...(checkoutPath ? { worktreePath: checkoutPath } : {}) },\n },\n )\n }\n\n const { token, appId } = await resolveTarget()\n const pullRecoveryCwd = selectedBranchCheckout(appDir, branch) ?? appDir\n ensureSpaceRemote(appDir, appId)\n\n // A `--force` push moves the ref non-fast-forward. That's legitimate for\n // rewriting YOUR OWN line (amend/rebase), but it must NOT silently drop a\n // peer's commits that landed on the cloud branch since you last synced —\n // the orphan protection this file's header describes for `deepspace push\n // --force` (a plain `git push --force` is out of our reach — see header).\n // Two ingredients:\n // 1. lastPushed = a PRIVATE ref (refs/deepspace/pushed/<branch>) that ONLY\n // our own successful push writes (see below). The obvious candidate,\n // refs/remotes/space/<branch>, is force-advanced by `deepspace pull`,\n // deploy, workspace fetches, and a bare `git fetch space` — so using it\n // would let the pull-then-retry flow the refusal itself recommends\n // poison the baseline and wave a clobber through. The workspace path is\n // safe for exactly this reason: its hidden ref moves only on its own\n // successful push.\n // 2. the current remote tip, fetched into FETCH_HEAD with `--refmap=` so\n // this guard's own fetch can't advance the tracking ref either.\n // Refuse if force-pushing would orphan the peer's work.\n if (force) {\n spinner?.message(`Checking the cloud ${branch} tip before force-push…`)\n const lastPushed = resolveCommit(appDir, `refs/deepspace/pushed/${branch}`)\n let remoteTip: string | null = null\n try {\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n '--refmap=',\n SPACE_REMOTE,\n `refs/heads/${branch}`,\n ])\n remoteTip = resolveCommit(appDir, 'FETCH_HEAD')\n } catch {\n // The fetch failed. We must NOT fall through to a blind force — that\n // would silently orphan a peer who'd advanced the branch. Disambiguate\n // with ls-remote: an absent branch (exit 0, empty) is a first-touch\n // force (nothing to orphan, safe); anything else (a non-zero status, or\n // an advertised tip we couldn't fetch) means we can't verify the tip, so\n // refuse — fail CLOSED.\n const ls = runGitRemote(\n appDir,\n token,\n ['ls-remote', SPACE_REMOTE, `refs/heads/${branch}`],\n {\n allowFail: true,\n },\n )\n if (ls.status === 0 && ls.stdout.toString('utf-8').trim() === '') {\n remoteTip = null // no such remote branch yet — first push, safe to force\n } else {\n const error =\n `Couldn't reach the cloud repo to check ${branch} before force-pushing. ` +\n `Refusing --force so it can't silently drop a peer's commits — retry when connected, ` +\n `or run \\`deepspace pull --app ${shQuote(appId)} --branch ${shQuote(branch)}\\` ` +\n `to integrate first.`\n // No `Next:`/`next`: the fix is \"retry when connected\" (not a single\n // command), and `deepspace pull` needs the very connectivity that just\n // failed — so naming it would loop an agent.\n // Plain failure (exit 1): NOTHING worked and no local step\n // remains — actionRequired/exit-2 is reserved for \"the operation\n // succeeded, now it's your turn\", which this is not.\n throw new Refusal(error, 'force_unverified', { extra: { appId, branch } })\n }\n }\n if (\n remoteTip &&\n forcePushOrphansWork(lastPushed, remoteTip, tipOid, isAncestor(appDir, remoteTip, tipOid))\n ) {\n const error =\n `The cloud repo's ${branch} advanced since you last synced — a peer pushed commit(s) you don't have. ` +\n `Force-pushing now would DROP that work. Run ` +\n `\\`deepspace pull --app ${shQuote(appId)} --branch ${shQuote(branch)}\\` and merge ` +\n `(or rebase onto it), then push.`\n throw new Refusal(error, 'diverged', {\n actionRequired: true,\n action: pullRecoveryAction(pullRecoveryCwd, appId, branch),\n extra: { appId, branch },\n })\n }\n }\n\n spinner?.message(`Pushing ${branch} to the cloud repo…`)\n const result = pushToSpace(appDir, token, `refs/heads/${branch}:refs/heads/${branch}`, {\n force,\n })\n spinner?.stop(\n result.status === 'up_to_date'\n ? `${branch} is already up to date at ${tipOid.slice(0, 10)}.`\n : result.status === 'committed'\n ? `Pushed ${branch} → ${tipOid.slice(0, 10)}.`\n : `Push did not complete.`,\n )\n\n const ok = result.status === 'up_to_date' || result.status === 'committed'\n if (ok) {\n // Record what THIS client just published, in a PRIVATE ref that only our\n // own successful push writes — the \"last pushed by me\" baseline the\n // --force orphan guard above reads. A bare `git fetch` / `deepspace pull`\n // never advances it (unlike refs/remotes/space/<branch>), so the guard\n // can't be poisoned into misreading a peer's tip as our own line.\n updateRef(appDir, `refs/deepspace/pushed/${branch}`, tipOid)\n }\n // A moved/diverged ref is a recovery state, not a dead end: nothing was\n // pushed, and `deepspace pull` is the one re-entry command. Carry that as\n // structured fields so an agent doesn't have to scrape the prose (a\n // server-side `rejected` — oversize, policy — is NOT self-recoverable).\n const recoverable = isRecoverablePushFailure(result.status)\n const rejectReason = result.reason ?? result.summary\n const errorMsg = ok\n ? null\n : result.status === 'ref_conflict'\n ? `The cloud repo's ${branch} moved while you worked (${rejectReason}). ` +\n `Run \\`deepspace pull --app ${shQuote(appId)} --branch ${shQuote(branch)}\\` ` +\n `to integrate, then push again.`\n : result.status === 'rejected'\n ? `The cloud repo rejected ${branch}: ${rejectReason}.` +\n (OVERSIZED_PUSH_RE.test(rejectReason) ? ` ${oversizedPushFix(appDir)}` : '')\n : `The cloud repo's ${branch} has commit(s) your local ${branch} doesn't. ` +\n `Run \\`deepspace pull --app ${shQuote(appId)} --branch ${shQuote(branch)}\\` ` +\n `and merge (or rebase), then push. Avoid --force here — it's guarded and ` +\n `will refuse rather than silently drop a peer's commits.`\n\n // Completeness: `appId` is the one --json fact the spinner line doesn't\n // already carry (branch + oid are in it), so the human surface names it too.\n if (!args.json && ok) p.log.info(`App: ${appId}`)\n // A push that landed is terminal — whether to deploy or open a workspace is\n // the agent's call, and a `Next:` there would be filler. Only the recoverable\n // divergence has one true follow-up.\n const action = recoverable ? pullRecoveryAction(pullRecoveryCwd, appId, branch) : undefined\n // A recoverable divergence (non_fast_forward / ref_conflict) is the\n // action-required tier — it already carries `actionRequired:true` + a\n // `action` above, so exit 2 like `push --force` diverged / `pull` diverged /\n // `workspace land` dirty. A non-recoverable rejection (oversize, policy)\n // stays an ordinary exit 1.\n if (!ok) {\n throw new Refusal(errorMsg ?? `Push did not complete.`, result.status, {\n actionRequired: recoverable,\n action,\n extra: { status: result.status, appId, branch, oid: tipOid },\n })\n }\n return { data: { status: result.status, appId, branch, oid: tipOid } }\n } catch (err) {\n if (err instanceof Refusal) throw err\n const transportFailure = classifyPushTransportFailure(err)\n if (transportFailure) {\n throw new Refusal(transportFailure.error, transportFailure.code)\n }\n throw err\n }\n },\n})\n","/**\n * `deepspace pull` — bring cloud-repo history into the local git repo.\n *\n * A real `git fetch` moves what's missing into `.git/objects` and updates\n * the tracking ref (`refs/remotes/space/<branch>`); then integrate\n * conservatively: fast-forward when that's all it takes, otherwise leave the\n * merge to the caller (`git merge refs/remotes/space/<branch>` — the objects\n * are already local, so that merge needs no network). Never touches a dirty\n * worktree.\n */\n\nimport * as p from '@clack/prompts'\nimport { realpathSync } from 'node:fs'\nimport { ensureToken } from '../auth'\nimport { findAppDir } from '../lib/app-context'\nimport { resolveAppTarget, assertAppTargetResolvable } from '../lib/app-target'\nimport {\n assertSyncableRepo,\n checkoutHead,\n currentBranch,\n fastForwardCurrentBranch,\n isAncestor,\n isWorkTreeClean,\n listWorktrees,\n resolveCommit,\n updateRef,\n isPlausibleBranchName,\n} from '../lib/git/repository'\nimport { workspaceIdFromBranch } from '../lib/workspace-id'\nimport { shQuote } from '../lib/cli-format'\nimport { deployBaseUrl, ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../lib/vc-remote'\nimport { repoApi } from '../lib/repo-api'\nimport { createSpinner } from '../lib/spinner'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport type { CliAction } from '../lib/output'\n\ntype Integration =\n | 'up_to_date'\n | 'fast_forwarded'\n | 'branch_created'\n | 'fetched_only_diverged'\n | 'fetched_only_dirty'\n | 'fetched_only_unborn'\n | 'fetched_only_worktree'\n\nfunction targetedVcAction(\n command: 'push' | 'pull',\n cwd: string,\n appId: string,\n branch: string,\n): CliAction {\n return {\n cwd,\n argv: ['deepspace', command, '--app', appId, '--branch', branch],\n }\n}\n\nfunction targetedVcCommand(command: 'push' | 'pull', appId: string, branch: string): string {\n return `deepspace ${command} --app ${shQuote(appId)} --branch ${shQuote(branch)}`\n}\n\n/** A `ws/<id>` branch is a workspace line, not an ordinary branch: trunk does\n * not fast-forward into it — it integrates by MERGE, and the two lines stay\n * distinct until `workspace land`. A plain pull would either bypass that model\n * or fail confusingly, so refuse with the exact manual merge. Null on any\n * ordinary branch (no behavior change). Pure + exported for tests. */\nexport function workspaceBranchPullRefusal(\n branch: string | null,\n trunkBranch: string | null,\n): { code: 'workspace_branch'; trunk: string; error: string } | null {\n const id = workspaceIdFromBranch(branch)\n if (!id) return null\n const trunk = trunkBranch || 'main'\n // Git allows branch names with shell metacharacters ($(), ;, &, spaces); quote\n // the interpolated ref so an agent copy-pasting this \"run this\" line can't\n // shell-expand a collaborator-controlled name. Never a machine contract.\n const merge = `git merge refs/remotes/space/${shQuote(trunk)}`\n return {\n code: 'workspace_branch',\n trunk,\n error:\n `\"${branch}\" is a workspace branch (${id}). Trunk integrates into a workspace by MERGE, not ` +\n `fast-forward — the two lines stay distinct until \\`deepspace workspace land\\`. Bring trunk in ` +\n `with \\`${merge}\\` after it is fetched (then resolve/commit), or land the workspace when it's ready.`,\n }\n}\n\n/** The path of ANOTHER worktree (not `selfPath`) that has `branch` checked out,\n * or null. Pull must not move a branch ref while a linked worktree holds it:\n * that worktree's HEAD would advance while its index and files stay at the old\n * commit, fabricating deletions/modifications. Pure + exported for tests. */\nexport function worktreeHoldingBranch(\n worktrees: { path: string; branch: string | null }[],\n branch: string,\n selfPath: string,\n): string | null {\n const real = (pth: string): string => {\n try {\n return realpathSync(pth)\n } catch {\n return pth\n }\n }\n const self = real(selfPath)\n for (const w of worktrees) {\n if (w.branch === branch && real(w.path) !== self) return w.path\n }\n return null\n}\n\n/**\n * The next-step advice for a diverged pull. `git merge` always merges INTO\n * the checked-out branch. When the selected branch is checked out in ANY\n * worktree, merge there; only an unowned branch needs a checkout first. Pure +\n * exported for tests.\n */\nexport function divergedMergeAdvice(branch: string, hasSelectedCheckout: boolean): string {\n // Shell-quote the interpolated branch — Git permits $(), ;, &, and spaces in\n // branch names, so an unquoted \"run this\" line could mis-parse or expand a\n // collaborator-controlled name. Human rendering only, never a machine contract.\n const b = shQuote(branch)\n return hasSelectedCheckout\n ? `git merge refs/remotes/space/${b}`\n : `git checkout ${b} && git merge refs/remotes/space/${b}`\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'pull',\n description:\n \"Fetch the app's cloud repo and fast-forward the local branch \" +\n '(exit 2 only when one executable local continuation remains)',\n },\n args: {\n branch: {\n type: 'string',\n alias: 'b',\n description: 'Branch to pull (default: the current branch)',\n required: false,\n },\n app: {\n type: 'string',\n alias: 'a',\n description:\n 'App id or subdomain name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n },\n async run({ args }) {\n const branchArg = args.branch === undefined ? undefined : String(args.branch)\n const appArg = typeof args.app === 'string' ? args.app : undefined\n const appDir = findAppDir()\n if (!appDir)\n throw new Refusal(\n 'No wrangler.toml found — run from inside an app directory.',\n 'not_in_app_repo',\n )\n\n // An explicitly-blank --branch must not silently fall back to the current\n // branch (an unset `--branch \"$VAR\"` would pull the wrong ref). Validate\n // the argument before inspecting repository state so a shallow checkout\n // cannot mask this pre-repository input error.\n if (branchArg !== undefined) {\n const b = branchArg.trim()\n if (!b) throw new Refusal('--branch was given an empty branch name.', 'invalid_branch')\n if (!isPlausibleBranchName(b))\n throw new Refusal(`--branch \"${b}\" is not a valid git branch name.`, 'invalid_branch')\n }\n assertSyncableRepo(appDir)\n const branch = branchArg?.trim() || currentBranch(appDir)\n if (!branch)\n throw new Refusal(\n 'HEAD is detached — pass --branch <name> to choose what to pull.',\n 'detached_head',\n )\n const refName = `refs/heads/${branch}`\n const selectedBranchCheckout = (): { onCurrent: boolean; path: string | null } => {\n const onCurrent = currentBranch(appDir) === branch\n return {\n onCurrent,\n path: onCurrent ? appDir : worktreeHoldingBranch(listWorktrees(appDir), branch, appDir),\n }\n }\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Preparing to pull ${branch}…`)\n\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const token = await ensureToken()\n const deployUrl = deployBaseUrl()\n const appId = await resolveAppTarget(deployUrl, token, appArg)\n ensureSpaceRemote(appDir, appId)\n\n // JSON refs first: \"no repo\" and \"no such branch\" get actionable\n // messages instead of git's couldn't-find-remote-ref stderr.\n spinner?.message(`Checking the cloud ${branch} ref…`)\n const remote = await repoApi(deployUrl, token, appId).getRefs()\n if (!remote) {\n spinner?.stop('No cloud repo yet.')\n const pushCommand = targetedVcCommand('push', appId, branch)\n throw new Refusal(\n `This app has no cloud repo yet — run \\`${pushCommand}\\` from the repo that has the history.`,\n 'no_cloud_repo',\n { action: targetedVcAction('push', appDir, appId, branch) },\n )\n }\n\n // A workspace branch can't be pulled like an ordinary branch — refuse\n // BEFORE the branch-existence check (its visible ref usually doesn't even\n // exist on the cloud repo, which would otherwise print a confusing \"no\n // such branch\"). Exit 2 with the one manual merge to run instead.\n const trunkBranch = remote.head?.startsWith('refs/heads/')\n ? remote.head.slice('refs/heads/'.length)\n : null\n const wsRefusal = workspaceBranchPullRefusal(branch, trunkBranch)\n if (wsRefusal) {\n const trunkRef = `refs/heads/${wsRefusal.trunk}`\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+${trunkRef}:refs/remotes/space/${wsRefusal.trunk}`,\n ])\n spinner?.stop('Workspace branch.')\n const { path: branchWorktreePath } = selectedBranchCheckout()\n const workspaceId = workspaceIdFromBranch(branch)\n if (!workspaceId) throw new Error(`Workspace branch did not contain an id: ${branch}`)\n const pullCommand = targetedVcCommand('pull', appId, branch)\n const localBranchExists = resolveCommit(appDir, refName) !== null\n const selectedCheckoutClean =\n branchWorktreePath !== null && isWorkTreeClean(branchWorktreePath)\n const canCheckoutHere =\n branchWorktreePath === null && localBranchExists && isWorkTreeClean(appDir)\n const step = branchWorktreePath\n ? selectedCheckoutClean\n ? `Merge the fetched trunk in the checkout that owns ${branch} (${branchWorktreePath}).`\n : `The checkout that owns ${branch} (${branchWorktreePath}) is dirty. Commit or stash there, then rerun \\`${pullCommand}\\` from that checkout.`\n : localBranchExists\n ? canCheckoutHere\n ? `The branch is not checked out. Check it out here, then rerun \\`${pullCommand}\\` to receive the merge step.`\n : `The branch is not checked out and this checkout is dirty. Commit or stash first (or use a clean worktree), check out ${shQuote(branch)}, then rerun \\`${pullCommand}\\`.`\n : `This clone has not attached the workspace. Attach ${workspaceId}, then rerun \\`${pullCommand}\\` from its checkout.`\n const action: CliAction | undefined =\n branchWorktreePath && selectedCheckoutClean\n ? {\n cwd: branchWorktreePath,\n argv: ['git', 'merge', `refs/remotes/space/${wsRefusal.trunk}`],\n }\n : canCheckoutHere\n ? { cwd: appDir, argv: ['git', 'checkout', branch] }\n : !localBranchExists\n ? {\n cwd: appDir,\n argv: ['deepspace', 'workspace', 'attach', workspaceId, '--app', appId],\n }\n : undefined\n throw new Refusal(`${wsRefusal.error} ${step}`, wsRefusal.code, {\n actionRequired: action !== undefined,\n action,\n extra: {\n appId,\n branch,\n ...(branchWorktreePath ? { worktreePath: branchWorktreePath } : {}),\n },\n })\n }\n\n if (!remote.refs.some((r) => r.name === refName)) {\n spinner?.stop('Branch not found.')\n const branches = remote.refs\n .filter((r) => r.name.startsWith('refs/heads/'))\n .map((r) => r.name.slice('refs/heads/'.length))\n throw new Refusal(\n `The cloud repo has no branch \"${branch}\".` +\n (branches.length ? ` Available: ${branches.join(', ')}.` : ' It is empty — push first.'),\n 'branch_not_found',\n )\n }\n\n // Real git does the transfer; `+` force-updates the tracking ref (a\n // remote-tracking ref always mirrors the remote, rewrites included).\n spinner?.message(`Fetching ${branch} from the cloud repo…`)\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+${refName}:refs/remotes/space/${branch}`,\n ])\n const remoteOid = resolveCommit(appDir, `refs/remotes/space/${branch}`)\n if (!remoteOid) {\n spinner?.stop('Fetch failed.')\n throw new Refusal(\n `Fetched, but refs/remotes/space/${branch} did not materialize — retry; if it persists, report it with \\`deepspace feedback\\`.`,\n 'fetch_incomplete',\n )\n }\n\n // Integrate — conservatively.\n // Resolve the owner immediately after fetch, before BOTH fast-forward and\n // divergence handling, so the action reflects the live worktree layout.\n const { onCurrent, path: branchWorktreePath } = selectedBranchCheckout()\n const localOid = resolveCommit(appDir, refName)\n let integration: Integration\n if (localOid === remoteOid) {\n integration = 'up_to_date'\n } else if (localOid === null) {\n // The branch doesn't exist locally yet. Creating the ref is always\n // safe; materializing the worktree only is when nothing can collide.\n updateRef(appDir, refName, remoteOid)\n if (onCurrent && isWorkTreeClean(appDir)) {\n checkoutHead(appDir)\n integration = 'branch_created'\n } else {\n integration = onCurrent ? 'fetched_only_unborn' : 'branch_created'\n }\n } else if (isAncestor(appDir, localOid, remoteOid)) {\n if (onCurrent) {\n if (!isWorkTreeClean(appDir)) {\n integration = 'fetched_only_dirty'\n } else {\n fastForwardCurrentBranch(appDir, remoteOid)\n integration = 'fast_forwarded'\n }\n } else {\n // Fast-forwarding a NON-current branch writes its ref directly — but\n // if another linked worktree has it checked out, moving the ref\n // desyncs that worktree (its HEAD advances while its index/files stay\n // put, fabricating deletions). Leave the ref alone and send the agent\n // to pull from that worktree instead.\n if (branchWorktreePath) {\n integration = 'fetched_only_worktree'\n } else {\n updateRef(appDir, refName, remoteOid)\n integration = 'fast_forwarded'\n }\n }\n } else {\n integration = 'fetched_only_diverged'\n }\n\n // Render the integration once, exhaustively. Summary, refusal code, and\n // structured action belong to the same outcome branch so they cannot drift.\n const qBranch = shQuote(branch)\n const ffRef = `git merge --ff-only refs/remotes/space/${qBranch}`\n const mergeRef = `git merge refs/remotes/space/${qBranch}`\n const pullCommand = targetedVcCommand('pull', appId, branch)\n const pushCommand = targetedVcCommand('push', appId, branch)\n const selectedCheckoutClean = branchWorktreePath !== null && isWorkTreeClean(branchWorktreePath)\n const canCheckoutHere = branchWorktreePath === null && isWorkTreeClean(appDir)\n let line: string\n let codeForState: string | undefined\n let recoveryAction: CliAction | undefined\n switch (integration) {\n case 'up_to_date':\n line = `${branch} is already up to date.`\n break\n case 'fast_forwarded':\n line = `Fast-forwarded ${branch} to ${remoteOid.slice(0, 10)}.`\n break\n case 'branch_created':\n line = `Created ${branch} at ${remoteOid.slice(0, 10)}.`\n break\n case 'fetched_only_diverged':\n codeForState = 'diverged'\n if (branchWorktreePath && selectedCheckoutClean) {\n const mergeAdvice = divergedMergeAdvice(branch, true)\n line =\n `Fetched space/${branch}. ${branch} and the cloud repo diverged — run ` +\n `\\`${mergeAdvice}\\` in ${branchWorktreePath} (no network needed), then \\`${pushCommand}\\`.`\n recoveryAction = {\n cwd: branchWorktreePath,\n argv: ['git', 'merge', `refs/remotes/space/${branch}`],\n }\n } else if (branchWorktreePath) {\n line =\n `Fetched space/${branch}. ${branch} and the cloud repo diverged, but its checkout ` +\n `(${branchWorktreePath}) is dirty. Commit or stash there, then rerun ` +\n `\\`${pullCommand}\\` from that checkout.`\n } else if (canCheckoutHere) {\n line =\n `Fetched space/${branch}. ${branch} and the cloud repo diverged, but ${branch} is ` +\n `not checked out. Check it out here, then rerun \\`${pullCommand}\\` to receive the merge step.`\n recoveryAction = { cwd: appDir, argv: ['git', 'checkout', branch] }\n } else {\n line =\n `Fetched space/${branch}. ${branch} and the cloud repo diverged, but ${branch} is ` +\n `not checked out and this checkout is dirty. Commit or stash first (or use a clean ` +\n `worktree), check out ${qBranch}, then rerun \\`${pullCommand}\\`.`\n }\n break\n case 'fetched_only_dirty':\n codeForState = 'dirty_worktree'\n // A commit diverges the branch, while a stash preserves fast-forward.\n line =\n `Fetched space/${branch}, but the worktree is dirty. Either stash → \\`${ffRef}\\` → ` +\n `\\`git stash pop\\`, or commit first → \\`${mergeRef}\\` (or \\`git rebase\\`).`\n break\n case 'fetched_only_unborn':\n codeForState = 'dirty_worktree'\n line =\n `Fetched space/${branch} and created ${branch}, but the worktree has uncommitted files. ` +\n `Preserve them in a commit or stash (including untracked files), then restore the checkout; ` +\n `do not run reset --hard until \\`git status\\` confirms nothing worth keeping remains.`\n break\n case 'fetched_only_worktree':\n codeForState = 'branch_in_worktree'\n if (branchWorktreePath && selectedCheckoutClean) {\n line =\n `Fetched space/${branch}, but ${branch} is checked out in another worktree ` +\n `(${branchWorktreePath}) — its ref was left untouched to keep that worktree in sync. ` +\n `Run \\`${pullCommand}\\` from there.`\n recoveryAction = targetedVcAction('pull', branchWorktreePath, appId, branch)\n } else {\n line =\n `Fetched space/${branch}, but its checkout ` +\n `(${branchWorktreePath ?? 'a linked worktree'}) is dirty, so the ref and worktree were ` +\n `left untouched. Commit or stash there, then run \\`${pullCommand}\\` from that checkout.`\n }\n break\n default: {\n const exhaustive: never = integration\n throw new Error(`Unhandled pull integration: ${exhaustive}`)\n }\n }\n // Exit 2 is reserved for a single executable continuation. Dirty or\n // unavailable checkout states require judgment and remain ordinary,\n // actionless refusals even though the fetch itself succeeded.\n const actionRequired = recoveryAction !== undefined\n spinner?.stop(codeForState ? `Fetched space/${branch}.` : line)\n // Completeness: appId and the fetched remote oid are --json facts the\n // summary line doesn't always carry — say them in the text too.\n if (!args.json) p.log.info(`App: ${appId} · space/${branch} at ${remoteOid.slice(0, 10)}`)\n if (codeForState) {\n // Every blocked integration is ok:false. Only one with an executable\n // continuation adds actionRequired and exits 2; judgment states exit 1.\n throw new Refusal(line, codeForState, {\n actionRequired,\n action: recoveryAction,\n extra: {\n status: integration,\n ...(branchWorktreePath ? { worktreePath: branchWorktreePath } : {}),\n appId,\n branch,\n remoteOid,\n },\n })\n }\n return { data: { status: integration, appId, branch, remoteOid } }\n },\n})\n","/**\n * `deepspace clone <app> [dir]` — materialize an app's cloud repo locally.\n *\n * The collaborator on-ramp with no GitHub in the loop: resolve the app (id\n * or subdomain name), then let REAL git clone the platform's smart-HTTP\n * remote — full history, all branches, default branch checked out. The\n * remote comes out named `space` and the credential helper is configured,\n * so plain `git push space` / `git fetch space` work from here on. The\n * clone is deploy-ready because identity travels in the repo itself\n * (wrangler.toml carries DEEPSPACE_APP_ID); secrets come separately via\n * `deepspace secrets pull`.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport * as p from '@clack/prompts'\nimport { existsSync, readdirSync, rmSync } from 'node:fs'\nimport { resolve, basename, join } from 'node:path'\nimport { ensureToken } from '../auth'\nimport { resolveAppSelector, assertAppTargetResolvable } from '../lib/app-target'\nimport { currentBranch, resolveCommit } from '../lib/git/repository'\nimport {\n deployBaseUrl,\n ensureSpaceRemote,\n repoUrl,\n runGitRemote,\n SPACE_REMOTE,\n} from '../lib/vc-remote'\nimport { repoApi } from '../lib/repo-api'\nimport { createSpinner } from '../lib/spinner'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport { detectPackageManager } from '../lib/package-manager'\n\n/**\n * Tidy a PRE-EXISTING target dir after a failed clone. git removes a clone\n * target it CREATED, but a dir that already existed keeps whatever partial\n * content the failure left. The caller verified the dir was empty right\n * before cloning, so a leftover that is ONLY `.git` is unambiguously the\n * failed transfer's debris — remove it. Anything else (a partial checkout, a\n * concurrent writer) is left alone: never delete content we didn't watch git\n * create. Returns what remains (empty when the dir is clean again). Pure fs\n * + exported for tests.\n */\nexport function cleanFailedCloneDir(dir: string): string[] {\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n return existsSync(dir) ? ['<unreadable>'] : []\n }\n if (entries.length === 1 && entries[0] === '.git') {\n try {\n rmSync(join(dir, '.git'), { recursive: true, force: true })\n return []\n } catch {\n return entries\n }\n }\n return entries\n}\n\n/** Validate the target before authentication or network work. */\nexport function validateCloneTarget(dir: string): boolean {\n if (!existsSync(dir)) return false\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOTDIR') {\n throw new Refusal(`${dir} already exists and is not a directory.`, 'dir_exists')\n }\n throw new Refusal(`${dir} already exists but could not be read.`, 'dir_unreadable')\n }\n if (entries.length > 0) {\n throw new Refusal(`${dir} already exists and is not empty.`, 'dir_exists')\n }\n return true\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'clone',\n description: \"Clone an app's cloud repo into a new directory\",\n },\n args: {\n app: {\n type: 'positional',\n description: 'App id (app_…) or subdomain name',\n required: true,\n },\n dir: {\n type: 'positional',\n description: 'Target directory (default: the app name you passed)',\n required: false,\n },\n },\n async run({ args }) {\n // A blank app selector is a client-side error — reject it BEFORE the token\n // read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(String(args.app))\n const selector = String(args.app).trim()\n const dir = resolve(String(args.dir ?? selector))\n // Whether the target existed before the clone: git only removes a\n // failed clone's dir when IT created the dir, so a pre-existing (empty)\n // one is ours to tidy on failure.\n const dirPreexisted = validateCloneTarget(dir)\n\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Resolving ${selector}…`)\n const token = await ensureToken()\n const deployUrl = deployBaseUrl()\n const appId = await resolveAppSelector(deployUrl, token, selector)\n\n // Probe the JSON refs first: cloning an unregistered/empty repo would\n // \"succeed\" as an empty checkout — an actionable message beats that.\n spinner?.message(`Checking ${selector}'s cloud repo…`)\n const remote = await repoApi(deployUrl, token, appId).getRefs()\n const branches = (remote?.refs ?? []).filter((r) => r.name.startsWith('refs/heads/'))\n if (!remote || branches.length === 0) {\n spinner?.stop('Nothing to clone.')\n throw new Refusal(\n `${selector} has no cloud repo history yet. Its owner (or their agent) needs to run \\`deepspace push\\` from the app's repo first.`,\n 'no_cloud_repo',\n )\n }\n\n // Real git does the transfer; auth rides in env, never argv.\n spinner?.message(`Cloning ${selector}…`)\n try {\n runGitRemote(process.cwd(), token, [\n 'clone',\n '--quiet',\n '--origin',\n SPACE_REMOTE,\n repoUrl(appId),\n dir,\n ])\n } catch (err) {\n // A failed clone into a dir the user pre-created leaves the partial\n // transfer behind (git only cleans dirs it made). Reap the\n // unambiguous debris; report anything left.\n if (dirPreexisted) {\n const leftovers = cleanFailedCloneDir(dir)\n if (leftovers.length > 0 && !args.json) {\n process.stderr.write(\n `note: the failed clone left files in ${dir}: ${leftovers.join(', ')}\\n`,\n )\n }\n }\n // Rethrown as-is: the runtime keeps the machine code (a GitError slug,\n // not_authenticated, an ApiError slug) so a --json caller can branch on it.\n throw err\n }\n // The remote URL is already right — this installs the credential\n // helper so bare git works in this clone from now on.\n ensureSpaceRemote(dir, appId)\n\n const head = resolveCommit(dir, 'HEAD')\n const branch = currentBranch(dir)\n spinner?.stop(\n `Cloned ${selector} (${branches.length} ${branches.length === 1 ? 'branch' : 'branches'}) into ${basename(dir)}/ at ${head?.slice(0, 10) ?? '(unborn)'}.`,\n )\n\n if (!args.json && !branch) {\n p.log.warn('HEAD is detached — check `git branch -a`.')\n }\n return {\n data: {\n appId,\n dir,\n head,\n branch,\n remoteBranches: branches.map((r) => r.name.replace(/^refs\\/heads\\//, '')),\n },\n // One runnable follow-up instead of the old five-line \"Next steps\" block:\n // nothing else in the clone works until the deps are installed. Secrets\n // (`deepspace secrets pull`) and `dev` follow from there.\n action: { cwd: dir, argv: [detectPackageManager(dir), 'install'] },\n }\n },\n})\n","/**\n * `deepspace releases` — the app's immutable deploy history.\n *\n * Every deploy (and rollback) records a release: who shipped it, when, the\n * commit it was built from, and the retained bundle rollback re-ships. What\n * `deepspace rollback` reads its targets from.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { resolveAppTarget, assertAppTargetResolvable } from '../lib/app-target'\nimport { repoApi } from '../lib/repo-api'\nimport { parseLimitArg } from '../lib/citty-args'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport { createSpinner } from '../lib/spinner'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'releases',\n description: \"List the app's deploy history (immutable releases)\",\n },\n args: {\n app: {\n type: 'string',\n alias: 'a',\n description: 'App id or subdomain name (default: the surrounding app directory)',\n required: false,\n },\n limit: {\n type: 'string',\n description: 'Max entries (default 20)',\n required: false,\n },\n },\n async run({ args }) {\n const appArg = args.app as string | undefined\n const { limit, error: limitError } = parseLimitArg(args.limit)\n if (limitError) throw new Refusal(limitError, 'invalid_limit')\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Loading release history…')\n const token = await ensureToken()\n const appId = await resolveAppTarget(DEPLOY_URL, token, appArg)\n const { releases } = await repoApi(DEPLOY_URL, token, appId).listReleases(limit)\n spinner?.stop(`Loaded ${releases.length} ${releases.length === 1 ? 'release' : 'releases'}.`)\n\n if (!args.json) {\n if (releases.length === 0) {\n p.log.info('No releases yet — the history starts with the next `deepspace deploy`.')\n } else {\n for (const r of releases) {\n const source = r.commitOid ? `commit ${r.commitOid.slice(0, 10)}` : '(no source recorded)'\n const rollback = r.rollbackAvailable ? 'rollback available' : 'rollback unavailable'\n console.log(\n `#${r.seq} ${r.id} ${r.kind.padEnd(8)} ${r.createdAt} ${r.actor} ${source} ${rollback}`,\n )\n }\n p.log.info('Roll back an available release with: deepspace rollback <release-id>')\n }\n }\n // No `next`: a listing is terminal — the follow-up depends on which row you\n // pick, and the human path already names `deepspace rollback <release-id>`.\n return { data: { appId, releases } }\n },\n})\n","/**\n * `deepspace rollback [release-id]` — restore a prior release, instantly.\n *\n * Re-ships the exact bundle that release deployed (retained server-side at\n * deploy time) — no rebuild, no local checkout needed. Secrets stay as they\n * are; only code moves. The rollback itself becomes the newest release, so\n * history is append-only and a rollback can be rolled back.\n *\n * With no argument, targets the release before the current one.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { resolveAppTarget, assertAppTargetResolvable } from '../lib/app-target'\nimport { apiFetch, ApiError } from '../lib/api'\nimport { mintIdempotencyKey, repoApi } from '../lib/repo-api'\nimport { createSpinner } from '../lib/spinner'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst REL_ID_RE = /^rel_[0-9A-HJKMNP-TV-Z]{26}$/\n\nexport function unavailableDoGuardRefusal(message: string): Refusal {\n return new Refusal(\n `${message}\\nRetry in a moment, or re-run with --allow-do-deletion to accept the risk.`,\n 'do_guard_unavailable',\n )\n}\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\n/**\n * Pick the default rollback target (the release before the current one) from\n * the two most-recent releases. Pure + exported for tests: the two rejection\n * states carry stable machine `code`s parallel to the explicit-id `not_found`,\n * so release automation distinguishes empty history from a single-release repo\n * without scraping the prose.\n */\nexport function pickPreviousRelease(\n releases: { id: string }[],\n): { releaseId: string } | { error: string; code: string } {\n if (releases.length === 0) {\n return { error: 'No releases recorded yet — nothing to roll back to.', code: 'no_releases' }\n }\n if (releases.length === 1) {\n return {\n error:\n 'Only one release exists — nothing earlier to roll back to. Pass an explicit release id once more history accrues.',\n code: 'no_previous_release',\n }\n }\n return { releaseId: releases[1].id }\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'rollback',\n description: \"Re-deploy a prior release's exact bundle (no rebuild)\",\n },\n args: {\n release: {\n type: 'positional',\n description: 'Release id (rel_…) from `deepspace releases` (default: the previous release)',\n required: false,\n },\n app: {\n type: 'string',\n alias: 'a',\n description: 'App id or subdomain name (default: the surrounding app directory)',\n required: false,\n },\n 'allow-do-deletion': {\n type: 'boolean',\n description:\n 'Proceed even though the target release declares fewer Durable Object classes than ' +\n 'the current one — THEIR STORED DATA IS DELETED.',\n default: false,\n },\n },\n async run({ args }) {\n const appArg = args.app as string | undefined\n // An explicitly-blank release id must not silently auto-pick the previous\n // release (a mutating op) — an unset `rollback \"$VAR\"` would roll back to an\n // unintended target. Absent (no positional) still auto-picks by design.\n if (args.release !== undefined) {\n const r = String(args.release).trim()\n if (!r) {\n throw new Refusal(\n '--release was given an empty release id — pass a rel_… id, or omit it to roll back to the previous release.',\n 'invalid_release',\n )\n }\n if (!REL_ID_RE.test(r)) {\n throw new Refusal(`Invalid release id: ${r} (expected rel_<ULID>).`, 'invalid_release')\n }\n }\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing rollback…')\n const token = await ensureToken()\n const appId = await resolveAppTarget(DEPLOY_URL, token, appArg)\n const api = repoApi(DEPLOY_URL, token, appId)\n\n let releaseId = args.release ? String(args.release).trim() : ''\n if (!releaseId) {\n const { releases } = await api.listReleases(2)\n const picked = pickPreviousRelease(releases)\n if ('error' in picked) throw new Refusal(picked.error, picked.code)\n releaseId = picked.releaseId\n }\n\n spinner?.message(`Rolling back to ${releaseId}…`)\n let result: {\n success: boolean\n url?: string\n versionId?: string\n rolledBackTo?: string\n releaseId?: string\n bundleRetained?: boolean\n // 'unverified' when --allow-do-deletion bypassed the DO-class guard, so\n // the platform did NOT check the rollback against the live DO classes.\n doClassGuard?: string\n }\n try {\n result = await apiFetch(DEPLOY_URL, token, `/api/deploy/${appId}/rollback`, {\n method: 'POST',\n body: JSON.stringify({\n releaseId,\n idempotencyKey: mintIdempotencyKey(),\n ...(args['allow-do-deletion'] ? { allowDoClassDeletion: true } : {}),\n }),\n })\n } catch (err) {\n // Data-loss consent is a user decision, never an executable action.\n if (err instanceof ApiError && err.code === 'do_class_deletion') {\n throw new Refusal(\n `${err.message}\\nRe-run with --allow-do-deletion to accept the data loss.`,\n err.code,\n )\n }\n // Fail-closed guard: the platform couldn't verify which Durable Object\n // classes are live, so it refused rather than risk deleting one's data.\n if (err instanceof ApiError && err.code === 'do_guard_unavailable') {\n throw unavailableDoGuardRefusal(err.message)\n }\n throw err\n }\n if (!result.success) {\n // A 2xx that isn't a well-formed rollback ack — e.g. a wrong/broken service\n // answering 200 {} — must NOT read as a successful (mutating) rollback. Code\n // it like the repo-API shape guard so a --json caller can classify it.\n throw new Refusal(\n 'The deploy service returned an unexpected response to the rollback — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).',\n 'invalid_response',\n )\n }\n spinner?.stop(`Rolled back to ${result.rolledBackTo ?? releaseId}.`)\n // Degraded guard: --allow-do-deletion bypassed the DO-class check, so the\n // platform never verified this rollback against the live Durable Object\n // classes. Surface it in both modes — an agent branches on the field.\n const doClassGuard = result.doClassGuard === 'unverified' ? ('unverified' as const) : undefined\n if (!args.json) {\n if (result.url) p.log.success(`Live at: ${result.url}`)\n if (result.bundleRetained === false) {\n p.log.warn(\n 'The rollback is live, but its bundle was concurrently retired and is not available for a future rollback.',\n )\n }\n if (doClassGuard === 'unverified') {\n p.log.warn(\n 'DO-class guard bypassed (--allow-do-deletion): this rollback was NOT checked against the ' +\n \"live Durable Object classes — any class the target doesn't declare has been deleted with its data.\",\n )\n }\n p.log.info(\n 'This rollback is itself the newest release — `deepspace releases` shows the full history.',\n )\n }\n return {\n data: {\n appId,\n rolledBackTo: result.rolledBackTo ?? releaseId,\n newReleaseId: result.releaseId ?? null,\n bundleRetained: result.bundleRetained ?? null,\n url: result.url ?? null,\n versionId: result.versionId ?? null,\n ...(doClassGuard ? { doClassGuard } : {}),\n },\n }\n },\n})\n","/**\n * `deepspace workspace` — durable, named lines of work for parallel agents.\n *\n * Command implementations live beside this registry under `workspace/`.\n */\n\nimport { defineCommand } from 'citty'\nimport { newWorkspaceCommand } from './workspace/new'\nimport { attachWorkspaceCommand } from './workspace/attach'\nimport { syncWorkspaceCommand } from './workspace/sync'\nimport { listWorkspacesCommand } from './workspace/list'\nimport { workspaceStatusCommand } from './workspace/status'\nimport { landWorkspaceCommand } from './workspace/land'\nimport { dropWorkspaceCommand } from './workspace/drop'\n\nexport default defineCommand({\n meta: {\n name: 'workspace',\n description: 'Durable parallel-agent workspaces (new/attach/sync/list/status/land/drop)',\n },\n subCommands: {\n new: newWorkspaceCommand,\n attach: attachWorkspaceCommand,\n sync: syncWorkspaceCommand,\n list: listWorkspacesCommand,\n status: workspaceStatusCommand,\n land: landWorkspaceCommand,\n drop: dropWorkspaceCommand,\n },\n})\n","import * as p from '@clack/prompts'\nimport { isAbsolute, join, resolve } from 'node:path'\nimport { findAppDir } from '../../lib/app-context'\nimport { mintUlid } from '../../lib/app-identity'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport { resolveCommit } from '../../lib/git/repository'\nimport { workspaceBranchName } from '../../lib/workspace-id'\nimport { ensureSpaceRemote } from '../../lib/vc-remote'\nimport { mintIdempotencyKey } from '../../lib/repo-api'\nimport { createSpinner } from '../../lib/spinner'\nimport { fetchTrunk } from './analysis'\nimport { materializeWorkspaceWorktree } from './local'\nimport { APP_ARG, resolveTarget } from './runtime'\n\nexport const newWorkspaceCommand = defineDeepspaceCommand({\n meta: { name: 'new', description: 'Create a workspace: server-side ref + local worktree' },\n args: {\n task: {\n type: 'string',\n alias: 't',\n // NOT citty-required: a missing required arg makes citty print human\n // usage text even under --json. Validated in run() for a JSON refusal.\n description: 'What this workspace is for (shown to every collaborator/agent; required)',\n required: false,\n },\n base: {\n type: 'string',\n description: 'Base revision (default: the cloud repo trunk tip)',\n required: false,\n },\n dir: {\n type: 'string',\n description: 'Worktree directory (default: .deepspace/ws/<id>)',\n required: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const task = typeof args.task === 'string' ? args.task.trim() : ''\n if (!task) {\n throw new Refusal(\n 'A workspace needs a task — pass -t \"<what this workspace is for>\" (it is shown to every collaborator and agent).',\n 'invalid_task',\n )\n }\n const baseArg = typeof args.base === 'string' ? args.base.trim() : ''\n // Validate an explicit --base before auth: it is a local input error.\n if (baseArg) {\n const baseDir = findAppDir()\n if (baseDir && !resolveCommit(baseDir, baseArg)) {\n throw new Refusal(\n `--base ${String(args.base)} does not resolve to a local commit.`,\n 'invalid_base',\n )\n }\n }\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing workspace…')\n const { appDir, appId, token, api } = await resolveTarget(\n typeof args.app === 'string' ? args.app : undefined,\n )\n spinner?.message('Creating workspace…')\n ensureSpaceRemote(appDir, appId)\n\n // Prefer the requested revision, then cloud trunk, then local HEAD for an empty cloud repo.\n let baseOid: string | null = null\n const refs = await api.getRefs()\n if (baseArg) {\n baseOid = resolveCommit(appDir, baseArg)\n if (!baseOid) {\n spinner?.stop('Base not found.')\n throw new Refusal(\n `--base ${String(args.base)} does not resolve to a local commit.`,\n 'invalid_base',\n )\n }\n } else {\n const trunk = refs?.head ? refs.refs.find((ref) => ref.name === refs.head) : undefined\n if (trunk) {\n baseOid = trunk.oid\n if (!resolveCommit(appDir, baseOid)) fetchTrunk(appDir, token, refs!.head)\n if (!resolveCommit(appDir, baseOid)) {\n spinner?.stop('Base not fetchable.')\n throw new Refusal(\n `Could not fetch the trunk tip ${baseOid.slice(0, 10)} from the cloud repo. Retry; if it persists, report it with \\`deepspace feedback\\`.`,\n 'fetch_failed',\n )\n }\n } else {\n baseOid = resolveCommit(appDir, 'HEAD')\n if (!baseOid) {\n spinner?.stop('No base.')\n throw new Refusal(\n 'The repo has no commits yet — commit first, then create a workspace.',\n 'no_commits',\n )\n }\n }\n }\n\n const id = `ws_${mintUlid()}`\n const branch = workspaceBranchName(id)\n const { view } = await api.createWorkspace({\n workspaceId: id,\n task,\n baseOid,\n idempotencyKey: mintIdempotencyKey(),\n })\n\n const dirInput = typeof args.dir === 'string' ? args.dir.trim() : ''\n const dirArg = dirInput || join('.deepspace', 'ws', id.slice(3).toLowerCase())\n const dir = isAbsolute(dirArg) ? dirArg : resolve(appDir, dirArg)\n let provisioned: string[] = []\n try {\n provisioned = materializeWorkspaceWorktree(appDir, dir, branch, baseOid)\n } catch (error) {\n spinner?.stop('Worktree failed.')\n const reason = error instanceof Error ? error.message : String(error)\n throw new Refusal(\n `Workspace ${id} was created in the cloud, but the local worktree could not be set up: ${reason} — attach it with \\`deepspace workspace attach ${id} <dir>\\` (or drop it: \\`deepspace workspace drop ${id}\\`).`,\n 'worktree_setup_failed',\n { extra: { workspaceId: id, ref: view.workspace.ref, baseOid } },\n )\n }\n\n spinner?.stop(`Workspace ${id} created.`)\n if (!args.json) {\n if (provisioned.length > 0)\n p.log.info(`Linked from the main checkout: ${provisioned.join(', ')}`)\n p.log.info(`Work in: cd ${dir}`)\n p.log.info(\n `Then: commit as usual, \\`deepspace workspace sync\\` to publish, \\`deepspace workspace land\\` when done.`,\n )\n }\n return {\n data: {\n workspaceId: id,\n appId,\n ref: view.workspace.ref,\n baseOid,\n branch,\n dir,\n provisioned,\n },\n }\n },\n})\n","import * as p from '@clack/prompts'\nimport { findAppDir } from '../../lib/app-context'\nimport { readAppId } from '../../lib/app-identity'\nimport {\n assertSyncableRepo,\n diffNameOnly,\n isAncestor,\n mergeBase,\n resolveCommit,\n} from '../../lib/git/repository'\nimport type { RemoteRefsResult, RemoteWorkspaceView, RepoApi } from '../../lib/repo-api'\nimport { ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../../lib/vc-remote'\n\nconst MAX_OVERLAP_PATHS = 20\nconst PEER_REF_PREFIX = 'refs/deepspace/peers/'\n\nexport function peerWorkspaceRef(workspaceId: string): string {\n return `${PEER_REF_PREFIX}${workspaceId}`\n}\n\nexport interface WorkspaceOverlap {\n workspaceId: string\n task: string\n paths: string[]\n morePaths: number\n}\n\nexport function formatCount(count: { count: number; capped: boolean } | null): string {\n if (!count) return '?'\n return count.capped ? `${count.count}+` : String(count.count)\n}\n\nexport function fetchTrunk(\n appDir: string,\n token: string,\n head: string | null,\n): { branch: string; ref: string; oid: string } | null {\n if (!head?.startsWith('refs/heads/')) return null\n const branch = head.slice('refs/heads/'.length)\n const remoteRef = `refs/remotes/space/${branch}`\n runGitRemote(appDir, token, ['fetch', '--quiet', SPACE_REMOTE, `+${head}:${remoteRef}`])\n const oid = resolveCommit(appDir, remoteRef)\n return oid ? { branch, ref: remoteRef, oid } : null\n}\n\nexport function localTrunkOid(appDir: string, refs: RemoteRefsResult | null): string | null {\n const head = refs?.head\n if (!head?.startsWith('refs/heads/')) return null\n const advertised = refs?.refs.find((ref) => ref.name === head)?.oid ?? null\n if (advertised && resolveCommit(appDir, advertised)) return advertised\n return resolveCommit(appDir, `refs/remotes/space/${head.slice('refs/heads/'.length)}`)\n}\n\nfunction fetchPeerWorkspaceRefs(appDir: string, token: string): void {\n try {\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n '--prune',\n SPACE_REMOTE,\n `+refs/deepspace/ws/*:${PEER_REF_PREFIX}*`,\n ])\n } catch {\n // Overlap reporting is advisory and can use already-fetched refs offline.\n }\n}\n\nexport function lineChangedPaths(\n appDir: string,\n baseOid: string,\n tipOid: string,\n trunkOid: string | null,\n): { diffBase: string; paths: string[] } | null {\n if (!resolveCommit(appDir, baseOid) || !resolveCommit(appDir, tipOid)) return null\n let diffBase = baseOid\n if (trunkOid && resolveCommit(appDir, trunkOid)) {\n const candidate = mergeBase(appDir, tipOid, trunkOid)\n if (candidate && candidate !== diffBase && isAncestor(appDir, diffBase, candidate)) {\n diffBase = candidate\n }\n }\n return { diffBase, paths: diffNameOnly(appDir, diffBase, tipOid) }\n}\n\nexport function trunkOverlapPaths(\n appDir: string,\n diffBase: string,\n trunkOid: string | null,\n myPaths: string[],\n): string[] {\n if (!trunkOid || trunkOid === diffBase || myPaths.length === 0) return []\n if (!resolveCommit(appDir, trunkOid) || !isAncestor(appDir, diffBase, trunkOid)) return []\n const trunkChanged = new Set(diffNameOnly(appDir, diffBase, trunkOid))\n return myPaths.filter((path) => trunkChanged.has(path))\n}\n\nfunction changedPathsByWorkspace(\n appDir: string,\n views: RemoteWorkspaceView[],\n trunkOid: string | null,\n): Map<string, { task: string; paths: string[] }> {\n const lines = new Map<string, { task: string; paths: string[] }>()\n for (const view of views) {\n const workspace = view.workspace\n if (workspace.status !== 'active') continue\n const tip = resolveCommit(appDir, peerWorkspaceRef(workspace.id)) ?? view.tipOid\n if (!tip) continue\n const line = lineChangedPaths(appDir, workspace.baseOid, tip, trunkOid)\n if (line?.paths.length) lines.set(workspace.id, { task: workspace.task, paths: line.paths })\n }\n return lines\n}\n\nexport function overlapsWith(\n myPaths: string[],\n lines: Map<string, { task: string; paths: string[] }>,\n selfId: string | null,\n): WorkspaceOverlap[] {\n const mine = new Set(myPaths)\n const overlaps: WorkspaceOverlap[] = []\n for (const [workspaceId, line] of lines) {\n if (workspaceId === selfId) continue\n const shared = line.paths.filter((path) => mine.has(path))\n if (!shared.length) continue\n overlaps.push({\n workspaceId,\n task: line.task,\n paths: shared.slice(0, MAX_OVERLAP_PATHS),\n morePaths: Math.max(0, shared.length - MAX_OVERLAP_PATHS),\n })\n }\n return overlaps\n}\n\nexport async function loadWorkspaceLines(\n appDir: string,\n token: string,\n api: RepoApi,\n trunkOid: string | null,\n): Promise<Map<string, { task: string; paths: string[] }>> {\n try {\n const { views } = await api.listWorkspaces()\n fetchPeerWorkspaceRefs(appDir, token)\n return changedPathsByWorkspace(appDir, views, trunkOid)\n } catch {\n return new Map()\n }\n}\n\nexport async function listOverlaps(\n appId: string,\n token: string,\n api: RepoApi,\n views: RemoteWorkspaceView[],\n): Promise<Map<string, WorkspaceOverlap[]>> {\n const appDir = findAppDir()\n if (!appDir || readAppId(appDir) !== appId) return new Map()\n try {\n assertSyncableRepo(appDir)\n ensureSpaceRemote(appDir, appId)\n const refs = await api.getRefs().catch(() => null)\n try {\n fetchTrunk(appDir, token, refs?.head ?? null)\n } catch {\n // localTrunkOid tolerates a stale tracking ref.\n }\n fetchPeerWorkspaceRefs(appDir, token)\n const lines = changedPathsByWorkspace(appDir, views, localTrunkOid(appDir, refs))\n return new Map([...lines].map(([id, line]) => [id, overlapsWith(line.paths, lines, id)]))\n } catch {\n return new Map()\n }\n}\n\nexport function printOverlaps(overlaps: WorkspaceOverlap[], json: boolean): void {\n if (json) return\n for (const overlap of overlaps) {\n const sample = overlap.paths.slice(0, 5).join(', ')\n const more = overlap.paths.length - 5 + overlap.morePaths\n p.log.warn(\n `Overlap: ${overlap.workspaceId} (\"${overlap.task}\") also modified ${sample}${more > 0 ? ` (+${more} more)` : ''} — coordinate before landing.`,\n )\n }\n}\n","import * as p from '@clack/prompts'\nimport { existsSync, realpathSync, statSync, symlinkSync } from 'node:fs'\nimport { isAbsolute, join, relative, sep } from 'node:path'\nimport { shQuote } from '../../lib/cli-format'\nimport { runGit } from '../../lib/git/process'\nimport {\n addWorktreeNewBranch,\n currentBranch,\n ensureLocalExclude,\n listWorktrees,\n repoToplevel,\n resolveCommit,\n} from '../../lib/git/repository'\nimport { workspaceBranchName, workspaceIdFromBranch } from '../../lib/workspace-id'\n\nexport function excludeWorktreeDir(appDir: string, dir: string): void {\n try {\n ensureLocalExclude(appDir, '.deepspace/')\n const realDir = realpathSync(dir)\n const rel = relative(realpathSync(repoToplevel(appDir)), realDir)\n if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return\n const pattern = rel.split(sep).join('/')\n if (pattern === '.deepspace' || pattern.startsWith('.deepspace/')) return\n const relApp = relative(realpathSync(appDir), realDir).split(sep).join('/')\n if (relApp === '.deepspace' || relApp.startsWith('.deepspace/')) return\n ensureLocalExclude(appDir, `/${pattern}/`)\n } catch {\n // Local exclusion is best-effort; failure only makes git status noisier.\n }\n}\n\nexport function provisionWorktreeDeps(appDir: string, dir: string): string[] {\n const linked: string[] = []\n try {\n const src = join(appDir, 'node_modules')\n const dest = join(dir, 'node_modules')\n if (existsSync(src) && !existsSync(dest)) {\n symlinkSync(src, dest, process.platform === 'win32' ? 'junction' : 'dir')\n linked.push('node_modules')\n }\n } catch {\n // Best-effort; the workspace can install its own dependencies.\n }\n return linked\n}\n\n/** Create a local workspace checkout and apply its standard local setup. */\nexport function materializeWorkspaceWorktree(\n appDir: string,\n dir: string,\n branch: string,\n startPoint: string,\n): string[] {\n addWorktreeNewBranch(appDir, dir, branch, startPoint)\n excludeWorktreeDir(appDir, dir)\n return provisionWorktreeDeps(appDir, dir)\n}\n\nexport function inOwnLinkedWorktree(appDir: string, id: string): boolean {\n if (workspaceIdFromBranch(currentBranch(appDir)) !== id) return false\n try {\n return statSync(join(appDir, '.git')).isFile()\n } catch {\n return false\n }\n}\n\nexport interface CleanupOutcome {\n worktreeRemoved: string | null\n branchDeleted: string | null\n mainDir?: string\n error?: string\n worktreeDir: string | null\n branch: string\n}\n\nexport function cleanupJson(outcome: CleanupOutcome): Record<string, unknown> {\n return {\n worktreeRemoved: outcome.worktreeRemoved,\n branchDeleted: outcome.branchDeleted,\n ...(outcome.mainDir ? { mainDir: outcome.mainDir } : {}),\n ...(outcome.error ? { error: outcome.error } : {}),\n }\n}\n\nfunction deleteWsBranch(cwd: string, branch: string, out: CleanupOutcome): void {\n const del = runGit(cwd, ['branch', '-D', branch], { allowFail: true })\n if (del.status === 0) out.branchDeleted = branch\n else\n out.error ??= `git branch -D ${branch} failed: ${del.stderr.toString('utf-8').trim() || 'unknown git error'}`\n}\n\nfunction switchOffWsBranch(mainDir: string, trunkBranch: string | null): boolean {\n if (trunkBranch) {\n if (resolveCommit(mainDir, `refs/heads/${trunkBranch}`)) {\n return runGit(mainDir, ['switch', '--quiet', trunkBranch], { allowFail: true }).status === 0\n }\n const remote = resolveCommit(mainDir, `refs/remotes/space/${trunkBranch}`)\n if (remote) {\n return (\n runGit(mainDir, ['switch', '--quiet', '-c', trunkBranch, remote], { allowFail: true })\n .status === 0\n )\n }\n }\n return runGit(mainDir, ['switch', '--quiet', '--detach'], { allowFail: true }).status === 0\n}\n\nexport function cleanupWorkspaceLocal(\n appDir: string,\n id: string,\n trunkBranch: string | null,\n): CleanupOutcome {\n const branch = workspaceBranchName(id)\n const out: CleanupOutcome = {\n worktreeRemoved: null,\n branchDeleted: null,\n worktreeDir: null,\n branch,\n }\n try {\n const worktrees = listWorktrees(appDir)\n const mainDir = worktrees[0]?.path ?? repoToplevel(appDir)\n const linked = worktrees.find((worktree, index) => index > 0 && worktree.branch === branch)\n if (linked) {\n out.worktreeDir = linked.path\n let inside = false\n try {\n inside = realpathSync(appDir) === realpathSync(linked.path)\n } catch {\n inside = false\n }\n if (inside) {\n process.chdir(mainDir)\n out.mainDir = mainDir\n }\n const remove = runGit(mainDir, ['worktree', 'remove', linked.path], { allowFail: true })\n if (remove.status !== 0) {\n out.error = `git worktree remove ${linked.path} failed: ${remove.stderr.toString('utf-8').trim() || 'unknown git error'}`\n return out\n }\n out.worktreeRemoved = linked.path\n deleteWsBranch(mainDir, branch, out)\n return out\n }\n if (currentBranch(mainDir) === branch && !switchOffWsBranch(mainDir, trunkBranch)) {\n out.error = `could not switch off ${branch} to delete it`\n return out\n }\n if (resolveCommit(mainDir, `refs/heads/${branch}`)) deleteWsBranch(mainDir, branch, out)\n return out\n } catch (err) {\n out.error = err instanceof Error ? err.message : String(err)\n return out\n }\n}\n\nexport function cleanupRefusalMessage(outcome: {\n error: string\n worktreeDir: string | null\n branch: string\n}): string {\n if (outcome.worktreeDir) {\n const dir = shQuote(outcome.worktreeDir)\n return (\n `Cleanup incomplete: ${outcome.error}. The worktree at ${dir} still holds uncommitted or untracked work — ` +\n `that's why the plain removal refused. Inspect it (\\`git -C ${dir} status\\`) and commit anything worth ` +\n `keeping to the workspace branch. Once it's clean, remove it from the main checkout: \\`git worktree remove ${dir}\\`.`\n )\n }\n return `Cleanup incomplete: ${outcome.error}. Finish it from the main checkout once ${shQuote(outcome.branch)} is safe to delete.`\n}\n\nexport function cleanupAction(outcome: { worktreeDir: string | null; branch: string }): {\n cwd: string\n argv: string[]\n} {\n return outcome.worktreeDir\n ? { cwd: outcome.worktreeDir, argv: ['git', 'status'] }\n : { cwd: process.cwd(), argv: ['git', 'branch', '--list', outcome.branch] }\n}\n\nexport function reportCleanupHuman(outcome: CleanupOutcome): void {\n if (outcome.error) {\n p.log.warn(\n cleanupRefusalMessage({\n error: outcome.error,\n worktreeDir: outcome.worktreeDir,\n branch: outcome.branch,\n }),\n )\n return\n }\n const parts = [\n outcome.worktreeRemoved ? 'worktree' : null,\n outcome.branchDeleted ? `branch ${outcome.branch}` : null,\n ].filter(Boolean)\n if (parts.length) p.log.success(`Removed ${parts.join(' + ')}.`)\n if (outcome.worktreeRemoved && outcome.mainDir) {\n p.log.info(`This directory was removed — run: cd ${shQuote(outcome.mainDir)}`)\n }\n}\n","import { ensureToken } from '../../auth'\nimport { findAppDir } from '../../lib/app-context'\nimport { resolveAppTarget, parseAppArg, assertAppTargetResolvable } from '../../lib/app-target'\nimport { Refusal } from '../../lib/command'\nimport type { CliAction } from '../../lib/output'\nimport { assertSyncableRepo, currentBranch, listWorktrees } from '../../lib/git/repository'\nimport { committedSecretRefusal } from '../../lib/git/safety'\nimport {\n isSelectedWorkspaceCheckout,\n isWorkspaceId,\n resolveWorkspaceWorktree,\n workspaceIdFromBranch,\n} from '../../lib/workspace-id'\nimport { pushFailureMessage, pushToSpace } from '../../lib/vc-push'\nimport { deployBaseUrl, SPACE_REMOTE } from '../../lib/vc-remote'\nimport { repoApi, type RepoApi } from '../../lib/repo-api'\n\nexport const APP_ARG = {\n type: 'string' as const,\n alias: 'a',\n description:\n 'App id or subdomain name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n}\n\ninterface Target {\n appDir: string\n appId: string\n token: string\n api: RepoApi\n}\n\nexport async function resolveTarget(appArg: string | undefined): Promise<Target> {\n const appDir = findAppDir()\n if (!appDir) {\n throw new Refusal(\n 'No wrangler.toml found — run from inside an app directory (or use -a <app> for list, and for drop with an explicit ws_ id).',\n 'not_in_app_repo',\n )\n }\n const { error: appErr } = parseAppArg(appArg)\n if (appErr) throw new Refusal(appErr, 'invalid_app')\n assertSyncableRepo(appDir)\n assertAppTargetResolvable(appArg)\n const token = await ensureToken()\n const appId = await resolveAppTarget(deployBaseUrl(), token, appArg)\n return { appDir, appId, token, api: repoApi(deployBaseUrl(), token, appId) }\n}\n\n/** Server-only resolution for list-style reads, including calls outside a checkout. */\nexport async function resolveApiOnly(\n appArg: string | undefined,\n): Promise<{ appId: string; api: RepoApi; token: string }> {\n assertAppTargetResolvable(appArg)\n const token = await ensureToken()\n const appId = await resolveAppTarget(deployBaseUrl(), token, appArg)\n return { appId, api: repoApi(deployBaseUrl(), token, appId), token }\n}\n\nexport function inferWorkspaceId(appDir: string, explicit: string | undefined): string {\n const id = explicit?.trim() || workspaceIdFromBranch(currentBranch(appDir))\n if (!id) {\n throw new Refusal(\n 'Not inside a workspace worktree (the branch is not ws/<id>). Pass the workspace id, or create one with `deepspace workspace new -t \"…\"`.',\n 'not_in_workspace',\n )\n }\n if (!isWorkspaceId(id)) {\n throw new Refusal(`Invalid workspace id: ${id} (expected ws_<ULID>).`, 'invalid_workspace')\n }\n return id\n}\n\n/** Mutating verbs must run from the selected workspace's own checkout. */\nexport function assertSelectedWorkspaceCheckout(\n appDir: string,\n id: string,\n resumeArgv: string[],\n): void {\n const branch = currentBranch(appDir)\n if (isSelectedWorkspaceCheckout(branch, id)) return\n const worktree = resolveWorkspaceWorktree(listWorktrees(appDir), id)\n const action: CliAction = worktree\n ? { cwd: worktree, argv: resumeArgv }\n : { cwd: appDir, argv: ['deepspace', 'workspace', 'attach', id] }\n throw new Refusal(\n `Workspace ${id} is not checked out here (current branch: ${branch ?? 'detached'}). ` +\n (worktree\n ? `Run this command from its checkout at ${worktree}.`\n : 'Attach it in this clone before mutating its published line.'),\n 'workspace_checkout_mismatch',\n {\n action,\n extra: worktree ? { workspaceDir: worktree } : undefined,\n },\n )\n}\n\n/** Reject malformed explicit ids before auth/network. */\nexport function assertExplicitWorkspaceId(explicit: string | undefined): void {\n if (explicit === undefined) return\n const id = explicit.trim()\n if (!id || !isWorkspaceId(id)) {\n throw new Refusal(\n `Invalid workspace id: ${explicit} (expected ws_<ULID>).`,\n 'invalid_workspace',\n )\n }\n}\n\n/** Publish a workspace line with Git's fast-forward rule as the lost-update guard. */\nexport function pushWorkspaceRef(\n appDir: string,\n token: string,\n ref: string,\n headOid: string,\n): void {\n const secret = committedSecretRefusal(appDir, headOid, {\n action: 'publish this workspace',\n then: 're-run the command',\n })\n if (secret) throw new Refusal(secret.message, secret.code)\n\n const push = pushToSpace(appDir, token, `${headOid}:${ref}`)\n if (push.status === 'committed' || push.status === 'up_to_date') return\n if (push.status === 'ref_conflict' || push.status === 'non_fast_forward') {\n throw new Refusal(\n `Another checkout advanced this workspace's line, so publishing yours is not a ` +\n `fast-forward — the push was refused rather than drop that work. Integrate its tip ` +\n `(\\`git pull ${SPACE_REMOTE} ${ref}\\`, or re-attach the workspace in a fresh dir), ` +\n `resolve any conflicts, then re-run the command. (Amended or rebased your own ` +\n `commits? Same refusal — merge your old tip back in.)`,\n push.status,\n {\n action: { cwd: appDir, argv: ['git', 'pull', SPACE_REMOTE, ref] },\n },\n )\n }\n throw new Refusal(pushFailureMessage('Workspace upload', push, appDir), push.status)\n}\n","import * as p from '@clack/prompts'\nimport { existsSync, readdirSync, rmSync } from 'node:fs'\nimport { isAbsolute, join, resolve } from 'node:path'\nimport { ensureToken } from '../../auth'\nimport { findAppDir } from '../../lib/app-context'\nimport { parseAppArg, resolveAppTarget } from '../../lib/app-target'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport { runGit } from '../../lib/git/process'\nimport { resolveCommit, switchToNewBranch } from '../../lib/git/repository'\nimport { isWorkspaceId, workspaceBranchName } from '../../lib/workspace-id'\nimport { deployBaseUrl, ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../../lib/vc-remote'\nimport { repoApi, type RemoteWorkspaceView } from '../../lib/repo-api'\nimport { createSpinner } from '../../lib/spinner'\nimport { errorCode } from '../../lib/cli-errors'\nimport type { CliAction } from '../../lib/output'\nimport { detectPackageManager } from '../../lib/package-manager'\nimport { materializeWorkspaceWorktree } from './local'\nimport { APP_ARG, resolveTarget } from './runtime'\n\n/** Explain why a finished workspace cannot be attached. */\nexport function finishedWorkspaceMessage(id: string, view: RemoteWorkspaceView): string {\n const workspace = view.workspace\n if (workspace.status === 'landed') {\n return (\n `Workspace ${id} landed at ${workspace.landedOid?.slice(0, 10) ?? 'an unrecorded commit'} and its ref was deleted — ` +\n `its whole line is reachable through that merge commit (\\`git log ${workspace.landedOid ?? '<oid>'}\\`). ` +\n `Attach only works on active workspaces; start a new one for follow-up work.`\n )\n }\n return (\n `Workspace ${id} is ${workspace.status} — its ref is retained briefly (fetch ${workspace.ref} to inspect), ` +\n `but attach only works on active workspaces.`\n )\n}\n\n/**\n * Reap a failed fresh attach only when the target still contains nothing but\n * the repository metadata this command created. Any checkout file or\n * concurrent write makes the directory user-owned and therefore untouchable.\n */\nexport function cleanFailedFreshAttachDir(dir: string): string[] {\n if (!existsSync(dir)) return []\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n return ['<unreadable>']\n }\n if (entries.length > 0 && !(entries.length === 1 && entries[0] === '.git')) {\n return entries\n }\n try {\n rmSync(dir, { recursive: true, force: true })\n return []\n } catch {\n return entries.length > 0 ? entries : ['<cleanup-failed>']\n }\n}\n\nexport const attachWorkspaceCommand = defineDeepspaceCommand({\n meta: {\n name: 'attach',\n description: 'Resume a workspace here (another machine or a fresh sandbox)',\n },\n args: {\n id: { type: 'positional', description: 'Workspace id (ws_…)', required: true },\n dir: {\n type: 'positional',\n description: 'Directory (worktree or fresh clone target)',\n required: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const id = String(args.id).trim()\n if (!isWorkspaceId(id)) {\n throw new Refusal(`Invalid workspace id: ${id} (expected ws_<ULID>).`, 'invalid_workspace')\n }\n const branch = workspaceBranchName(id)\n const insideRepo = findAppDir()\n const appArg = typeof args.app === 'string' ? args.app : undefined\n const { app: appSelector, error: appError } = parseAppArg(appArg)\n if (appError) throw new Refusal(appError, 'invalid_app')\n if (!insideRepo && appSelector === undefined) {\n throw new Refusal(\n 'Not inside an app repo — pass the app explicitly: deepspace workspace attach <ws_id> [dir] -a <app id or name>.',\n 'not_in_app_repo',\n )\n }\n\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Preparing to attach ${id}…`)\n\n if (insideRepo) {\n const { appDir, appId, api, token } = await resolveTarget(appArg)\n spinner?.message(`Attaching ${id}…`)\n const { view } = await api.getWorkspace(id)\n if (view.workspace.status !== 'active') {\n spinner?.stop('Workspace finished.')\n throw new Refusal(finishedWorkspaceMessage(id, view), 'workspace_not_active', {\n extra: { status: view.workspace.status },\n })\n }\n ensureSpaceRemote(appDir, appId)\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+${view.workspace.ref}:${view.workspace.ref}`,\n ])\n const tip = view.tipOid ?? view.workspace.baseOid\n if (!resolveCommit(appDir, tip)) {\n spinner?.stop('Fetch failed.')\n throw new Refusal(\n `Could not fetch ${view.workspace.ref} from the cloud repo. Retry; if it persists, report it with \\`deepspace feedback\\`.`,\n 'fetch_failed',\n )\n }\n const requestedDir = typeof args.dir === 'string' ? args.dir.trim() : ''\n const dirArg = requestedDir || join('.deepspace', 'ws', id.slice(3).toLowerCase())\n const dir = isAbsolute(dirArg) ? dirArg : resolve(appDir, dirArg)\n if (resolveCommit(appDir, `refs/heads/${branch}`)) {\n throw new Refusal(\n `Branch ${branch} already exists locally (this workspace has a worktree here). Find it with \\`git worktree list\\` and continue there.`,\n 'branch_exists',\n )\n }\n const provisioned = materializeWorkspaceWorktree(appDir, dir, branch, tip)\n spinner?.stop(`Attached ${id}.`)\n if (!args.json) {\n if (provisioned.length > 0)\n p.log.info(`Linked from the main checkout: ${provisioned.join(', ')}`)\n p.log.info(`Task: ${view.workspace.task}`)\n p.log.info(`Work in: cd ${dir}`)\n }\n return {\n data: {\n workspaceId: id,\n mode: 'worktree',\n dir,\n branch,\n tipOid: tip,\n task: view.workspace.task,\n provisioned,\n },\n }\n }\n\n // Fresh-clone mode materializes only this workspace's hidden ref.\n const token = await ensureToken()\n const appId = await resolveAppTarget(deployBaseUrl(), token, appSelector)\n const api = repoApi(deployBaseUrl(), token, appId)\n spinner?.message(`Attaching ${id} into a fresh clone…`)\n const { view } = await api.getWorkspace(id)\n if (view.workspace.status !== 'active') {\n spinner?.stop('Workspace finished.')\n throw new Refusal(finishedWorkspaceMessage(id, view), 'workspace_not_active', {\n extra: { status: view.workspace.status },\n })\n }\n const dir = resolve(\n process.cwd(),\n (typeof args.dir === 'string' ? args.dir.trim() : '') || `ws-${id.slice(3).toLowerCase()}`,\n )\n if (existsSync(dir)) {\n spinner?.stop('Target exists.')\n throw new Refusal(`${dir} already exists — pass a different directory.`, 'dir_exists')\n }\n const failFreshAttach = (message: string, code?: string): never => {\n const leftovers = cleanFailedFreshAttachDir(dir)\n const cleanupNote =\n leftovers.length > 0\n ? ` The failed attach left ${dir} in place because it contains: ${leftovers.join(', ')}.`\n : ''\n throw new Refusal(message + cleanupNote, code ?? 'attach_failed', {\n extra: leftovers.length > 0 ? { leftovers } : undefined,\n })\n }\n let tip: string\n try {\n runGit(process.cwd(), ['init', '--quiet', dir])\n ensureSpaceRemote(dir, appId)\n runGitRemote(dir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+${view.workspace.ref}:${view.workspace.ref}`,\n ])\n tip = view.tipOid ?? view.workspace.baseOid\n if (!resolveCommit(dir, tip)) {\n spinner?.stop('Fetch failed.')\n return failFreshAttach(\n `Could not fetch ${view.workspace.ref} from the cloud repo. Retry; if it persists, report it with \\`deepspace feedback\\`.`,\n 'fetch_failed',\n )\n }\n switchToNewBranch(dir, branch, tip)\n } catch (error) {\n if (error instanceof Refusal) throw error\n return failFreshAttach(\n error instanceof Error ? error.message : String(error),\n errorCode(error),\n )\n }\n spinner?.stop(`Attached ${id}.`)\n const action: CliAction = { cwd: dir, argv: [detectPackageManager(dir), 'install'] }\n if (!args.json) {\n p.log.info(`Task: ${view.workspace.task}`)\n p.log.info('Pull app secrets after install if this workspace needs them.')\n }\n return {\n data: {\n workspaceId: id,\n mode: 'clone',\n dir,\n branch,\n tipOid: tip,\n task: view.workspace.task,\n },\n action,\n }\n },\n})\n","import * as p from '@clack/prompts'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport { resolveCommit } from '../../lib/git/repository'\nimport { statusFiles } from '../../lib/git/safety'\nimport { ensureSpaceRemote } from '../../lib/vc-remote'\nimport { createSpinner } from '../../lib/spinner'\nimport {\n fetchTrunk,\n lineChangedPaths,\n loadWorkspaceLines,\n localTrunkOid,\n overlapsWith,\n printOverlaps,\n trunkOverlapPaths,\n} from './analysis'\nimport {\n APP_ARG,\n assertExplicitWorkspaceId,\n assertSelectedWorkspaceCheckout,\n inferWorkspaceId,\n pushWorkspaceRef,\n resolveTarget,\n} from './runtime'\n\nexport const syncWorkspaceCommand = defineDeepspaceCommand({\n meta: {\n name: 'sync',\n description: 'Publish this workspace: push its branch + report changed paths',\n },\n args: {\n workspace: {\n type: 'string',\n alias: 'w',\n description: 'Workspace id (default: inferred from the ws/<id> branch)',\n required: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const workspaceArg = typeof args.workspace === 'string' ? args.workspace : undefined\n assertExplicitWorkspaceId(workspaceArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing workspace sync…')\n const { appDir, appId, token, api } = await resolveTarget(\n typeof args.app === 'string' ? args.app : undefined,\n )\n const id = inferWorkspaceId(appDir, workspaceArg)\n assertSelectedWorkspaceCheckout(appDir, id, ['deepspace', 'workspace', 'sync'])\n const headOid = resolveCommit(appDir, 'HEAD')\n if (!headOid) {\n throw new Refusal('The workspace has no commits yet — commit first, then sync.', 'no_commits')\n }\n\n spinner?.message(`Syncing ${id}…`)\n const [{ view: before }, refs] = await Promise.all([\n api.getWorkspace(id),\n api.getRefs().catch(() => null),\n ])\n if (before.workspace.status !== 'active') {\n spinner?.stop('Workspace finished.')\n throw new Refusal(\n `Workspace ${id} is ${before.workspace.status} — create a new workspace to continue this line of work.`,\n 'workspace_not_active',\n { extra: { status: before.workspace.status } },\n )\n }\n ensureSpaceRemote(appDir, appId)\n pushWorkspaceRef(appDir, token, before.workspace.ref, headOid)\n\n // Keep advisory overlap math current without turning a transient fetch into a sync failure.\n try {\n fetchTrunk(appDir, token, refs?.head ?? null)\n } catch {\n // localTrunkOid can use the existing tracking ref.\n }\n\n const trunkOid = localTrunkOid(appDir, refs)\n const line = lineChangedPaths(appDir, before.workspace.baseOid, headOid, trunkOid)\n const changedPaths = line?.paths\n const trunkOverlap = line ? trunkOverlapPaths(appDir, line.diffBase, trunkOid, line.paths) : []\n const overlaps =\n changedPaths && changedPaths.length > 0\n ? overlapsWith(changedPaths, await loadWorkspaceLines(appDir, token, api, trunkOid), id)\n : []\n\n const upToDate = headOid === before.tipOid\n const view = upToDate ? before : (await api.syncWorkspace(id, { headOid })).view\n const dirty = statusFiles(appDir)\n spinner?.stop(\n upToDate\n ? `Already synced — ${id} is up to date at ${headOid.slice(0, 10)}.`\n : changedPaths !== undefined\n ? `Synced ${id} → ${headOid.slice(0, 10)} (${changedPaths.length} ${changedPaths.length === 1 ? 'file' : 'files'} vs base).`\n : `Synced ${id} → ${headOid.slice(0, 10)} (base not present locally — no overlap report).`,\n )\n printOverlaps(overlaps, args.json)\n if (!args.json && trunkOverlap.length > 0) {\n p.log.warn(\n `Trunk already changed ${trunkOverlap.length} file(s) you also touch — landed work you haven't merged: ` +\n `${trunkOverlap.slice(0, 5).join(', ')}${trunkOverlap.length > 5 ? ` (+${trunkOverlap.length - 5} more)` : ''}. ` +\n `Merge trunk before landing (\\`deepspace workspace status\\` shows the full picture).`,\n )\n }\n if (!args.json && dirty.length > 0) {\n p.log.warn(\n `${dirty.length} uncommitted ${dirty.length === 1 ? 'file' : 'files'} NOT synced — commit them to this workspace branch (WIP commits are fine — they land with the merge).`,\n )\n }\n return {\n data: {\n status: upToDate ? 'up_to_date' : 'synced',\n workspaceId: id,\n headOid,\n changedPaths: changedPaths ?? null,\n overlaps,\n trunkOverlap,\n uncommitted: dirty,\n view,\n },\n }\n },\n})\n","import * as p from '@clack/prompts'\nimport { parseLimitArg } from '../../lib/citty-args'\nimport { actorLabels } from '../../lib/actor-labels'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport type { RemoteWorkspaceView } from '../../lib/repo-api'\nimport { createSpinner } from '../../lib/spinner'\nimport { formatCount, listOverlaps, type WorkspaceOverlap } from './analysis'\nimport { APP_ARG, resolveApiOnly } from './runtime'\n\nexport function withWorkspaceOverlaps(\n views: RemoteWorkspaceView[],\n overlapsById: Map<string, WorkspaceOverlap[]>,\n) {\n return views.map((view) => ({\n ...view,\n overlaps: overlapsById.get(view.workspace.id) ?? [],\n }))\n}\n\nexport const listWorkspacesCommand = defineDeepspaceCommand({\n meta: { name: 'list', description: 'List workspaces on the cloud repo' },\n args: {\n all: { type: 'boolean', description: 'Include landed/dropped workspaces', default: false },\n limit: { type: 'string', description: 'Max entries (default 50)', required: false },\n app: APP_ARG,\n },\n async run({ args }) {\n const { limit, error: limitError } = parseLimitArg(args.limit)\n if (limitError) throw new Refusal(limitError, 'invalid_limit')\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Loading workspaces…')\n const { appId, api, token } = await resolveApiOnly(\n typeof args.app === 'string' ? args.app : undefined,\n )\n const all = Boolean(args.all)\n const { views } = await api.listWorkspaces({ all, limit })\n if (views.length === 0) {\n spinner?.stop('No workspaces found.')\n if (!args.json) {\n p.log.info(\n all\n ? 'No workspaces.'\n : 'No active workspaces. Create one with `deepspace workspace new -t \"…\"`.',\n )\n }\n return { data: { workspaces: views } }\n }\n\n spinner?.message('Checking workspace overlaps…')\n const overlapsPromise = listOverlaps(appId, token, api, views)\n if (args.json) {\n return {\n data: { workspaces: withWorkspaceOverlaps(views, await overlapsPromise) },\n }\n }\n const [actors, overlapsById] = await Promise.all([actorLabels(token, appId), overlapsPromise])\n const workspaces = withWorkspaceOverlaps(views, overlapsById)\n spinner?.stop(`Loaded ${views.length} ${views.length === 1 ? 'workspace' : 'workspaces'}.`)\n for (const view of workspaces) {\n const workspace = view.workspace\n const overlaps = view.overlaps\n const marker =\n workspace.status === 'active'\n ? overlaps.length > 0\n ? '⚠'\n : ' '\n : workspace.status === 'landed'\n ? '✓'\n : '✗'\n console.log(\n `${marker} ${workspace.id} ${workspace.status} ↑${formatCount(view.aheadOfBase)} ↓${formatCount(view.behindTrunk)} ${actors.get(workspace.createdBy) ?? workspace.createdBy} ${workspace.updatedAt} ${workspace.task}`,\n )\n for (const overlap of overlaps) {\n console.log(\n ` overlaps ${overlap.workspaceId}: ${overlap.paths.slice(0, 3).join(', ')}${overlap.paths.length + overlap.morePaths > 3 ? ` (+${overlap.paths.length + overlap.morePaths - 3} more)` : ''}`,\n )\n }\n }\n p.log.info('↑ commits ahead of base · ↓ trunk commits since base (staleness)')\n return { data: { workspaces } }\n },\n})\n","/**\n * Best-effort userId → human label map for the coordination read commands\n * (activity, workspace list). Raw actor ids are stable\n * API surface and stay in --json; the HUMAN views resolve them to emails\n * where the platform can: the caller's own id from the JWT (\"(you)\"), and\n * collaborators from the api-worker roster (owner-scoped — a collaborator's\n * view quietly falls back to raw ids). Any source failing degrades to ids,\n * never to a failed command.\n */\n\nimport { PLATFORM_URLS } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { apiFetch } from './api'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\nexport async function actorLabels(token: string, appId: string): Promise<Map<string, string>> {\n const labels = new Map<string, string>()\n try {\n const { sub, email } = decodeJwtPayload<{ sub?: string; email?: string }>(token)\n if (sub && email) labels.set(sub, `${email} (you)`)\n } catch {\n // unreadable token — ids only\n }\n try {\n const { collaborators } = await apiFetch<{\n collaborators: Array<{ userId: string; emailDisplay: string }>\n }>(API_URL, token, `/api/app-collaborators/${encodeURIComponent(appId)}`)\n for (const c of collaborators) {\n if (!labels.has(c.userId)) labels.set(c.userId, c.emailDisplay)\n }\n } catch {\n // not the owner / roster unavailable — ids only\n }\n return labels\n}\n","import * as p from '@clack/prompts'\nimport { defineDeepspaceCommand } from '../../lib/command'\nimport { listWorktrees, resolveCommit, revListCount } from '../../lib/git/repository'\nimport { statusFiles } from '../../lib/git/safety'\nimport { ensureSpaceRemote } from '../../lib/vc-remote'\nimport { createSpinner } from '../../lib/spinner'\nimport { resolveWorkspaceWorktree } from '../../lib/workspace-id'\nimport {\n fetchTrunk,\n lineChangedPaths,\n loadWorkspaceLines,\n overlapsWith,\n peerWorkspaceRef,\n printOverlaps,\n trunkOverlapPaths,\n} from './analysis'\nimport { APP_ARG, assertExplicitWorkspaceId, inferWorkspaceId, resolveTarget } from './runtime'\n\nexport const workspaceStatusCommand = defineDeepspaceCommand({\n meta: { name: 'status', description: 'This workspace: base staleness, overlaps, sync state' },\n args: {\n workspace: {\n type: 'string',\n alias: 'w',\n description: 'Workspace id (default: inferred from the ws/<id> branch)',\n required: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const workspaceArg = typeof args.workspace === 'string' ? args.workspace : undefined\n assertExplicitWorkspaceId(workspaceArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing workspace status…')\n const { appDir, appId, token, api } = await resolveTarget(\n typeof args.app === 'string' ? args.app : undefined,\n )\n const id = inferWorkspaceId(appDir, workspaceArg)\n spinner?.message(`Checking ${id}…`)\n ensureSpaceRemote(appDir, appId)\n const [{ view }, refs] = await Promise.all([api.getWorkspace(id), api.getRefs()])\n const workspace = view.workspace\n\n // Read checkout-only state from this workspace's actual worktree. Object-level\n // graph queries can safely use appDir even when status is invoked elsewhere.\n const workspaceDir = resolveWorkspaceWorktree(listWorktrees(appDir), id)\n const attached = workspaceDir !== null\n const headOid = workspaceDir ? resolveCommit(workspaceDir, 'HEAD') : null\n const trunk = fetchTrunk(appDir, token, refs?.head ?? null)\n const trunkOid = trunk?.oid ?? null\n const baseLocal = resolveCommit(appDir, workspace.baseOid) !== null\n const behindExact =\n trunk && baseLocal ? revListCount(appDir, workspace.baseOid, trunk.oid) : null\n const aheadExact =\n headOid && baseLocal ? revListCount(appDir, workspace.baseOid, headOid) : null\n const unsynced = headOid !== null && view.tipOid !== headOid\n const dirty = workspaceDir ? statusFiles(workspaceDir) : []\n\n const lines = await loadWorkspaceLines(appDir, token, api, trunkOid)\n const myTip = headOid ?? resolveCommit(appDir, peerWorkspaceRef(id)) ?? view.tipOid\n const line = myTip ? lineChangedPaths(appDir, workspace.baseOid, myTip, trunkOid) : null\n const trunkOverlap = line ? trunkOverlapPaths(appDir, line.diffBase, trunkOid, line.paths) : []\n const overlaps = overlapsWith(line?.paths ?? [], lines, id)\n\n spinner?.stop(`Workspace ${id} (${workspace.status}).`)\n const data = {\n workspaceId: id,\n task: workspace.task,\n status: workspace.status,\n baseOid: workspace.baseOid,\n syncedTip: view.tipOid,\n landedOid: workspace.landedOid,\n trunkCommitsSinceBase: behindExact,\n aheadOfBase:\n attached && aheadExact !== null ? { count: aheadExact, capped: false } : view.aheadOfBase,\n attached,\n ...(attached\n ? {\n headOid,\n unsynced,\n uncommitted: dirty,\n trunkOverlap,\n }\n : {}),\n overlaps,\n }\n if (!args.json) {\n p.log.info(`Task: ${workspace.task}`)\n p.log.info(\n `Base: ${workspace.baseOid.slice(0, 10)} · ahead ${aheadExact ?? '?'} commit(s) · trunk moved ${behindExact ?? '?'} commit(s) since your base`,\n )\n if (!attached) {\n p.log.info(\n `Not checked out in this clone — showing the published state (local HEAD/uncommitted unavailable). Attach it with \\`deepspace workspace attach ${id} <dir>\\`.`,\n )\n }\n if (unsynced)\n p.log.warn(\n `Local HEAD ${headOid?.slice(0, 10)} is not synced (server has ${view.tipOid?.slice(0, 10) ?? 'nothing'}) — run \\`deepspace workspace sync\\`.`,\n )\n if (dirty.length > 0) p.log.warn(`${dirty.length} uncommitted file(s) in the worktree.`)\n if (trunkOverlap.length > 0) {\n p.log.warn(\n `Trunk also modified: ${trunkOverlap.slice(0, 5).join(', ')}${trunkOverlap.length > 5 ? ` (+${trunkOverlap.length - 5} more)` : ''} — expect merge attention at land time.`,\n )\n }\n printOverlaps(overlaps, false)\n }\n return { data }\n },\n})\n","import * as p from '@clack/prompts'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport type { CliAction } from '../../lib/output'\nimport { runGit } from '../../lib/git/process'\nimport { isPlausibleBranchName, isWorkTreeClean, resolveCommit } from '../../lib/git/repository'\nimport { committedSecretRefusal } from '../../lib/git/safety'\nimport { pushToSpace } from '../../lib/vc-push'\nimport { ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../../lib/vc-remote'\nimport { resolveValidationCommand, runValidationCommand } from '../../lib/validation'\nimport { createSpinner } from '../../lib/spinner'\nimport { humanCommand } from '../../lib/cli-format'\nimport {\n cleanupAction,\n cleanupJson,\n cleanupRefusalMessage,\n cleanupWorkspaceLocal,\n inOwnLinkedWorktree,\n reportCleanupHuman,\n} from './local'\nimport {\n APP_ARG,\n assertExplicitWorkspaceId,\n assertSelectedWorkspaceCheckout,\n inferWorkspaceId,\n pushWorkspaceRef,\n resolveTarget,\n} from './runtime'\n\nexport function hasLeftoverConflictMarkers(diffCheckOutput: string): boolean {\n return /leftover conflict marker/.test(diffCheckOutput)\n}\n\nexport interface LandArgs {\n workspace?: string\n into?: string\n validate?: boolean\n 'keep-worktree'?: boolean\n}\n\n/** Rebuild land argv so every resumable refusal preserves the caller's safety flags. */\nexport function landResumeArgv(args: LandArgs): string[] {\n const argv = ['deepspace', 'workspace', 'land']\n const workspace = args.workspace?.trim()\n if (workspace) argv.push('-w', workspace)\n const into = args.into?.trim()\n if (into) argv.push('--into', into)\n if (args.validate) argv.push('--validate')\n if (args['keep-worktree']) argv.push('--keep-worktree')\n return argv\n}\n\nexport const landWorkspaceCommand = defineDeepspaceCommand({\n meta: { name: 'land', description: 'Merge this workspace into trunk (both sides retained)' },\n args: {\n into: {\n type: 'string',\n description: 'Target branch (default: the cloud repo default branch)',\n required: false,\n },\n workspace: {\n type: 'string',\n alias: 'w',\n description: 'Workspace id (default: inferred from the ws/<id> branch)',\n required: false,\n },\n 'keep-worktree': {\n type: 'boolean',\n description: 'Keep the local worktree and branch after landing',\n default: false,\n },\n validate: {\n type: 'boolean',\n description:\n 'Run the project validation on the merged tree before publishing trunk (exit 2 on failure)',\n default: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const intoArg = typeof args.into === 'string' ? args.into : undefined\n const workspaceArg = typeof args.workspace === 'string' ? args.workspace : undefined\n const validate = Boolean(args.validate)\n const keepWorktree = Boolean(args['keep-worktree'])\n if (args.into !== undefined) {\n const branch = String(args.into).trim()\n if (!branch) {\n throw new Refusal('--into was given an empty branch name.', 'invalid_branch')\n }\n if (!isPlausibleBranchName(branch)) {\n throw new Refusal(`--into \"${branch}\" is not a valid git branch name.`, 'invalid_branch')\n }\n }\n assertExplicitWorkspaceId(workspaceArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing workspace land…')\n const { appDir, appId, token, api } = await resolveTarget(\n typeof args.app === 'string' ? args.app : undefined,\n )\n const id = inferWorkspaceId(appDir, workspaceArg)\n const resumeArgv = landResumeArgv({\n workspace: workspaceArg,\n into: intoArg,\n validate,\n 'keep-worktree': keepWorktree,\n })\n const recoveryAction: CliAction = { cwd: appDir, argv: resumeArgv }\n const resumeNext = humanCommand(resumeArgv)\n assertSelectedWorkspaceCheckout(appDir, id, resumeArgv)\n const headBefore = resolveCommit(appDir, 'HEAD')\n if (!headBefore) {\n throw new Refusal('The workspace has no commits — nothing to land.', 'no_commits')\n }\n\n if (!isWorkTreeClean(appDir)) {\n throw new Refusal(\n `The worktree has uncommitted changes, and landing publishes committed HEAD only. Commit them to this workspace branch, then re-run \\`${resumeNext}\\`.`,\n 'dirty_worktree',\n { extra: { workspaceId: id } },\n )\n }\n\n spinner?.message(`Landing ${id}…`)\n const [{ view }, refs] = await Promise.all([api.getWorkspace(id), api.getRefs()])\n if (view.workspace.status !== 'active') {\n spinner?.stop('Workspace finished.')\n throw new Refusal(\n `Workspace ${id} is already ${view.workspace.status}.`,\n 'workspace_not_active',\n { extra: { status: view.workspace.status } },\n )\n }\n ensureSpaceRemote(appDir, appId)\n\n // A conflict retry keeps the pure workspace line immutable: HEAD's first parent is its tip.\n const isResumedMerge =\n resolveCommit(appDir, 'HEAD^2') !== null &&\n view.tipOid !== null &&\n resolveCommit(appDir, 'HEAD^') === view.tipOid\n if (!isResumedMerge) {\n pushWorkspaceRef(appDir, token, view.workspace.ref, headBefore)\n }\n\n const intoBranch =\n intoArg?.trim() ||\n (refs?.head?.startsWith('refs/heads/') ? refs.head.slice('refs/heads/'.length) : null)\n if (!intoBranch) {\n spinner?.stop('No trunk.')\n throw new Refusal(\n 'The cloud repo has no default branch yet — push trunk first (`deepspace push`), then land.',\n 'no_default_branch',\n )\n }\n const intoRef = `refs/heads/${intoBranch}`\n const remoteRef = `refs/remotes/space/${intoBranch}`\n runGitRemote(appDir, token, ['fetch', '--quiet', SPACE_REMOTE, `+${intoRef}:${remoteRef}`], {\n allowFail: true,\n })\n const remoteTip = resolveCommit(appDir, remoteRef)\n\n if (\n remoteTip &&\n runGit(appDir, ['merge-base', '--is-ancestor', remoteTip, 'HEAD'], { allowFail: true })\n .status !== 0\n ) {\n const hasIdent = runGit(appDir, ['config', 'user.email'], { allowFail: true }).status === 0\n const identEnv: Record<string, string> = hasIdent\n ? {}\n : {\n GIT_AUTHOR_NAME: 'DeepSpace Workspace',\n GIT_AUTHOR_EMAIL: 'workspace@deep.space',\n GIT_COMMITTER_NAME: 'DeepSpace Workspace',\n GIT_COMMITTER_EMAIL: 'workspace@deep.space',\n }\n const merge = runGit(appDir, ['merge', '--no-edit', remoteRef], {\n allowFail: true,\n env: identEnv,\n })\n if (merge.status !== 0) {\n const conflicted =\n runGit(appDir, ['ls-files', '-u'], { allowFail: true })\n .stdout.toString('utf-8')\n .trim() !== ''\n if (!conflicted) {\n runGit(appDir, ['merge', '--abort'], { allowFail: true })\n spinner?.stop('Merge failed.')\n throw new Refusal(\n `Merging trunk (${intoBranch}) failed (not a conflict): ${merge.stderr.toString('utf-8').trim() || 'unknown git error'}.`,\n 'merge_failed',\n )\n }\n spinner?.stop('Merge conflict.')\n throw new Refusal(\n `Merging trunk (${intoBranch}) hit conflicts. Resolve them, \\`git add\\` + \\`git commit\\` (validate the merged tree — a marker-free merge can still be semantically wrong), then re-run \\`${resumeNext}\\`. Your original line is safe on ${view.workspace.ref}.`,\n 'merge_conflict',\n {\n actionRequired: true,\n extra: { workspaceId: id, conflict: true },\n },\n )\n }\n }\n\n if (resolveCommit(appDir, 'HEAD^2') !== null) {\n const markerCheck = runGit(appDir, ['diff', '--check', 'HEAD^', 'HEAD'], {\n allowFail: true,\n })\n if (hasLeftoverConflictMarkers(markerCheck.stdout.toString('utf-8'))) {\n spinner?.stop('Conflict markers in merge.')\n throw new Refusal(\n `The merge commit still contains unresolved conflict markers (<<<<<<< / ======= / >>>>>>>). Fix the marked files, commit the correction, then re-run \\`${resumeNext}\\`. Nothing was pushed to ${intoBranch}.`,\n 'conflict_markers',\n {\n actionRequired: true,\n extra: { workspaceId: id, conflict: true },\n },\n )\n }\n }\n\n const landedOid = resolveCommit(appDir, 'HEAD')!\n let validationResult: {\n passed: boolean\n command: string\n durationMs: number\n outputTail?: string\n } | null = null\n if (validate) {\n const command = resolveValidationCommand(appDir)\n if (!command) {\n spinner?.stop('No validation command.')\n throw new Refusal(\n 'No validation command for --validate. Add a \"validate\" script to package.json (e.g. \"vitest run\"), or land without --validate.',\n 'no_validate_command',\n )\n }\n spinner?.message(`Validating: ${command}`)\n const run = runValidationCommand(appDir, command)\n const headAfter = resolveCommit(appDir, 'HEAD')\n const dirtyAfter = !isWorkTreeClean(appDir)\n const outputTail = run.output.slice(-2000) || run.summary || undefined\n validationResult = {\n passed: run.passed,\n command,\n durationMs: run.durationMs,\n ...(run.passed ? {} : { outputTail }),\n }\n if (!run.passed) {\n spinner?.stop('Validation failed.')\n throw new Refusal(\n `Validation FAILED on the merged tree (exit ${run.exitStatus ?? '?'}) — the merge is local and nothing was pushed to ${intoBranch}. Fix it, commit, then re-run \\`${resumeNext}\\`. Your original line is safe on ${view.workspace.ref}.`,\n 'validation_failed',\n {\n actionRequired: true,\n extra: { workspaceId: id, passed: false, outputTail },\n },\n )\n }\n if (headAfter !== landedOid || dirtyAfter) {\n spinner?.stop('Validation changed the tree.')\n throw new Refusal(\n `Validation modified the working tree or HEAD (a formatter, \\`eslint --fix\\`, codegen, or a snapshot update). ` +\n `Nothing was pushed to ${intoBranch}: landing would publish ${landedOid.slice(0, 10)} and exclude those changes. ` +\n `Review and commit them (or revert), then re-run \\`${resumeNext}\\`. Your original line is safe on ${view.workspace.ref}.`,\n 'validation_mutated_tree',\n {\n actionRequired: true,\n extra: { workspaceId: id },\n },\n )\n }\n }\n\n const trunkSecret = committedSecretRefusal(appDir, resolveCommit(appDir, 'HEAD'), {\n action: `land onto ${intoBranch}`,\n then: 're-run the land',\n })\n if (trunkSecret) {\n spinner?.stop('Secret in history.')\n throw new Refusal(trunkSecret.message, trunkSecret.code, {\n extra: { workspaceId: id },\n })\n }\n const push = pushToSpace(appDir, token, `HEAD:${intoRef}`)\n if (push.status === 'ref_conflict' || push.status === 'non_fast_forward') {\n spinner?.stop('Trunk moved.')\n throw new Refusal(\n `${intoBranch} moved while you merged (${push.reason ?? push.summary}). Re-run \\`${resumeNext}\\` to integrate the new tip.`,\n 'trunk_moved',\n {\n actionRequired: true,\n action: recoveryAction,\n extra: { workspaceId: id },\n },\n )\n }\n if (push.status === 'rejected') {\n spinner?.stop('Push rejected.')\n throw new Refusal(\n `The cloud repo rejected the land push: ${push.reason ?? push.summary}.`,\n 'push_rejected',\n )\n }\n\n await api.landWorkspace(id, { landedOid, intoRef })\n spinner?.stop(`Landed ${id} into ${intoBranch} at ${landedOid.slice(0, 10)}.`)\n const cleanup = keepWorktree ? null : cleanupWorkspaceLocal(appDir, id, intoBranch)\n const inOwnWorktree = !cleanup && inOwnLinkedWorktree(appDir, id)\n const retainedWorktree = keepWorktree || inOwnWorktree ? appDir : null\n const data = {\n workspaceId: id,\n into: intoBranch,\n landedOid,\n ...(validationResult ? { validation: validationResult } : {}),\n ...(retainedWorktree ? { worktree: retainedWorktree } : {}),\n ...(cleanup ? { cleanup: cleanupJson(cleanup) } : {}),\n }\n if (!args.json && cleanup && !cleanup.error) {\n reportCleanupHuman(cleanup)\n } else if (!args.json && retainedWorktree) {\n p.log.info(`Retained checkout: ${retainedWorktree}`)\n }\n if (cleanup?.error) {\n const action = cleanupAction({\n worktreeDir: cleanup.worktreeDir,\n branch: cleanup.branch,\n })\n throw new Refusal(\n cleanupRefusalMessage({\n error: cleanup.error,\n worktreeDir: cleanup.worktreeDir,\n branch: cleanup.branch,\n }),\n 'cleanup_incomplete',\n { actionRequired: true, action, extra: data },\n )\n }\n return { data }\n },\n})\n","/**\n * The project's own check, run locally — the machinery behind\n * `deepspace workspace land --validate`.\n *\n * A validation is a pure LOCAL GATE: it runs the project's check against the\n * merged tree and aborts the land on failure. Nothing is recorded anywhere —\n * \"tests were green\" is a fact about a tree, and the tree is right here.\n */\n\nimport { sync as spawnSync } from 'cross-spawn'\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { detectPackageManager } from './package-manager'\n\nconst MAX_SUMMARY_CHARS = 4_000\nconst MAX_OUTPUT_BUFFER = 64 * 1024 * 1024\n\n/** The script runner matching the repo's lockfile (npm unless proven otherwise). */\nfunction configuredCommand(appDir: string): string | null {\n try {\n const pkg = JSON.parse(readFileSync(join(appDir, 'package.json'), 'utf-8')) as {\n scripts?: Record<string, string>\n }\n if (pkg.scripts?.validate) return `${detectPackageManager(appDir)} run --silent validate`\n } catch {\n // no/broken package.json — handled by the caller's advice\n }\n return null\n}\n\nexport interface ValidationRun {\n passed: boolean\n durationMs: number\n summary: string | null\n output: string\n exitStatus: number | null\n}\n\n/** Resolve the validation command: an explicit override, else the package.json\n * `validate` script (via the repo's package runner), else null. */\nexport function resolveValidationCommand(appDir: string, explicit?: string): string | null {\n return explicit?.trim() || configuredCommand(appDir)\n}\n\n/** Run a validation command and capture its outcome. Never throws on a non-zero\n * exit — a failed check is a well-formed result the caller turns into its own\n * refusal. */\nexport function runValidationCommand(appDir: string, command: string): ValidationRun {\n const started = Date.now()\n const res = spawnSync(command, [], {\n cwd: appDir,\n shell: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n maxBuffer: MAX_OUTPUT_BUFFER,\n env: { ...process.env, CI: process.env.CI ?? '1' },\n })\n const durationMs = Date.now() - started\n const passed = res.status === 0 && !res.error\n const output =\n `${res.stdout?.toString('utf-8') ?? ''}\\n${res.stderr?.toString('utf-8') ?? ''}`.trim()\n const summary = output.slice(-MAX_SUMMARY_CHARS) || (res.error ? res.error.message : null)\n return { passed, durationMs, summary, output, exitStatus: res.status ?? null }\n}\n","import * as p from '@clack/prompts'\nimport { findAppDir } from '../../lib/app-context'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport { isWorkTreeClean } from '../../lib/git/repository'\nimport type { CliAction } from '../../lib/output'\nimport { humanCommand } from '../../lib/cli-format'\nimport { createSpinner } from '../../lib/spinner'\nimport {\n cleanupAction,\n cleanupRefusalMessage,\n cleanupJson,\n cleanupWorkspaceLocal,\n inOwnLinkedWorktree,\n reportCleanupHuman,\n} from './local'\nimport {\n APP_ARG,\n assertExplicitWorkspaceId,\n inferWorkspaceId,\n resolveApiOnly,\n resolveTarget,\n} from './runtime'\n\nexport const dropWorkspaceCommand = defineDeepspaceCommand({\n meta: { name: 'drop', description: 'Abandon a workspace (ref retained briefly, then GC)' },\n args: {\n id: {\n type: 'positional',\n description: 'Workspace id (default: inferred from the ws/<id> branch)',\n required: false,\n },\n 'keep-worktree': {\n type: 'boolean',\n description: 'Keep the local worktree and branch after dropping',\n default: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const explicitId = typeof args.id === 'string' ? args.id.trim() : undefined\n assertExplicitWorkspaceId(explicitId)\n const appArg = typeof args.app === 'string' ? args.app : undefined\n const keepWorktree = Boolean(args['keep-worktree'])\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Preparing to drop ${explicitId ?? 'workspace'}…`)\n if (!findAppDir() && explicitId) {\n const { api } = await resolveApiOnly(appArg)\n const { view } = await api.dropWorkspace(explicitId)\n spinner?.stop()\n if (!args.json) {\n p.log.success(\n `Dropped ${explicitId}. Its ref sticks around briefly for undo, then is reaped.`,\n )\n }\n return { data: { workspaceId: explicitId, status: view.workspace.status } }\n }\n\n const { appDir, api } = await resolveTarget(appArg)\n const id = inferWorkspaceId(appDir, explicitId)\n if (!keepWorktree && !isWorkTreeClean(appDir)) {\n const dropArgv = ['deepspace', 'workspace', 'drop', ...(explicitId ? [explicitId] : [])]\n const dropNext = humanCommand(dropArgv)\n throw new Refusal(\n `The worktree has uncommitted changes and cleanup would remove it. Commit them to the workspace branch and re-run \\`${dropNext}\\`, or pass \\`--keep-worktree\\` to drop while keeping the worktree. Nothing was dropped.`,\n 'dirty_worktree',\n { extra: { workspaceId: id } },\n )\n }\n\n const { view } = await api.dropWorkspace(id)\n spinner?.message(`Cleaning up ${id} locally…`)\n const cleanup = keepWorktree ? null : cleanupWorkspaceLocal(appDir, id, null)\n const inOwnWorktree = !cleanup && inOwnLinkedWorktree(appDir, id)\n const retainedWorktree = keepWorktree || inOwnWorktree ? appDir : null\n const data = {\n workspaceId: id,\n status: view.workspace.status,\n ...(retainedWorktree ? { worktree: retainedWorktree } : {}),\n ...(cleanup ? { cleanup: cleanupJson(cleanup) } : {}),\n }\n spinner?.stop()\n if (!args.json) {\n p.log.success(`Dropped ${id}. Its ref sticks around briefly for undo, then is reaped.`)\n if (cleanup && !cleanup.error) reportCleanupHuman(cleanup)\n else if (retainedWorktree) p.log.info(`Retained checkout: ${retainedWorktree}`)\n }\n if (cleanup?.error) {\n const action: CliAction = cleanupAction({\n worktreeDir: cleanup.worktreeDir,\n branch: cleanup.branch,\n })\n throw new Refusal(\n cleanupRefusalMessage({\n error: cleanup.error,\n worktreeDir: cleanup.worktreeDir,\n branch: cleanup.branch,\n }),\n 'cleanup_incomplete',\n { actionRequired: true, action, extra: data },\n )\n }\n return { data }\n },\n})\n","/**\n * `deepspace activity` — the app's coordination feed: pushes, workspace\n * lifecycle and releases, merged and cursored. This is how an\n * agent answers \"did trunk move / did a workspace land / did someone\n * deploy?\" without cloning anything.\n *\n * deepspace activity [--since <cursor|now>] [--limit N] [--json]\n * deepspace activity --follow # poll loop (Ctrl-C to stop)\n *\n * Agents own their cursor: keep the returned value and pass it back as\n * `--since`. Follow starts at \"now\" unless an explicit cursor is supplied,\n * then streams one NDJSON record per fact. There is deliberately no shared\n * machine cursor for sibling agents to consume from each other.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file. The one\n * exception is `--follow --json`, a documented NDJSON *stream* that never\n * returns — it emits a ready frame, then one frame per activity or transport\n * error.\n */\n\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { resolveAppTarget, assertAppTargetResolvable } from '../lib/app-target'\nimport { deployBaseUrl } from '../lib/vc-remote'\nimport { repoApi, type RemoteActivityEvent } from '../lib/repo-api'\nimport { actorLabels } from '../lib/actor-labels'\nimport { parseLimitArg, parseCursorArg } from '../lib/citty-args'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport { errorCode } from '../lib/cli-errors'\nimport { createSpinner } from '../lib/spinner'\n\nconst FOLLOW_INTERVAL_MS = 5_000\n\n/** landedOid → workspace id for a page of events. A land reaches the feed as\n * a trunk `push` followed by `workspace.landed`, and the undifferentiated\n * push reads as someone pushing directly to trunk (a live study's only\n * misreading of shared state). Correlating within the page labels it. */\nexport function landIndex(events: RemoteActivityEvent[]): Map<string, string> {\n const m = new Map<string, string>()\n for (const e of events) {\n if (e.kind !== 'workspace.landed') continue\n const s = (e.summary ?? {}) as Record<string, unknown>\n if (typeof s.landedOid === 'string' && e.subjectId) m.set(s.landedOid, e.subjectId)\n }\n return m\n}\n\nexport function formatEvent(\n e: RemoteActivityEvent,\n lands?: Map<string, string>,\n actors?: Map<string, string>,\n): string {\n const s = (e.summary ?? {}) as Record<string, unknown>\n const short = (oid: unknown) => (typeof oid === 'string' ? oid.slice(0, 10) : '?')\n const who = (id: unknown) =>\n typeof id === 'string' ? (actors?.get(id) ?? id) : String(id ?? '?')\n let detail = ''\n switch (e.kind) {\n case 'push': {\n const refs = Array.isArray(s.refs) ? (s.refs as Array<{ ref?: string; newOid?: string }>) : []\n detail = refs\n .map((r) => `${String(r.ref ?? '').replace('refs/heads/', '')} → ${short(r.newOid)}`)\n .join(', ')\n const landWs = refs\n .map((r) => (typeof r.newOid === 'string' ? lands?.get(r.newOid) : undefined))\n .find(Boolean)\n if (landWs) detail += ` (land of ${landWs})`\n break\n }\n case 'workspace.created':\n detail = `\"${String(s.task ?? '')}\" from ${short(s.baseOid)}`\n break\n case 'workspace.synced':\n detail = `→ ${short(s.headOid)} (${Number(s.files ?? 0)} files vs base)`\n break\n case 'workspace.landed':\n detail = `\"${String(s.task ?? '')}\" → ${short(s.landedOid)} on ${String(s.into ?? 'trunk')}`\n break\n case 'workspace.dropped':\n detail = `\"${String(s.task ?? '')}\"`\n break\n case 'release.deploy':\n case 'release.rollback':\n detail = `#${Number(s.seq ?? 0)} ${short(s.commitOid)}`\n break\n // Unknown kinds still print their kind + actor — never crash the feed.\n default:\n detail = ''\n }\n return `#${e.seq} ${e.createdAt} ${e.kind} ${who(e.actor)} ${detail}`.trimEnd()\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'activity',\n description: \"The app's coordination feed (pushes, workspaces, releases)\",\n },\n args: {\n since: {\n type: 'string',\n description:\n 'Events after this cursor, or \"now\". One-shot defaults to 0; follow defaults to now',\n required: false,\n },\n limit: { type: 'string', description: 'Max events per page (default 50)', required: false },\n follow: {\n type: 'boolean',\n description: 'Keep polling for new events (Ctrl-C to stop)',\n default: false,\n },\n app: {\n type: 'string',\n alias: 'a',\n description:\n 'App id or subdomain name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n },\n async run({ args }) {\n const appArg = args.app as string | undefined\n // Validate cheap args before any auth/network round-trip. A malformed\n // cursor must FAIL, not silently coerce — an agent with a corrupted saved\n // cursor would otherwise replay full history and mistake it for new\n // activity (parseCursorArg also rejects a fractional cursor rather than\n // flooring it to an earlier page).\n const fromNow = args.since === 'now'\n const { cursor: startCursor, error: cursorError } = fromNow\n ? { cursor: 0, error: null }\n : parseCursorArg(args.since)\n if (cursorError) throw new Refusal(cursorError, 'invalid_cursor')\n const { limit, error: limitError } = parseLimitArg(args.limit)\n if (limitError) throw new Refusal(limitError, 'invalid_limit')\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start(args.follow ? 'Starting activity feed…' : 'Loading activity…')\n const token = await ensureToken()\n // Activity is a pure server read — usable from anywhere with -a; the\n // wrangler.toml default applies when run inside an app dir.\n const appId = await resolveAppTarget(deployBaseUrl(), token, appArg)\n const initialApi = repoApi(deployBaseUrl(), token, appId)\n // A follower starts after the latest committed event unless the caller\n // supplied a cursor. The tail read and later activity writes serialize in\n // the same repo DO, so an event cannot slip through the handoff.\n let cursor =\n fromNow || (args.follow && args.since === undefined)\n ? (await initialApi.listActivity({ tail: true })).cursor\n : startCursor\n\n // Human view only: resolve actor ids to emails once per invocation —\n // raw ids stay in --json (stable surface).\n const actors = args.json ? undefined : await actorLabels(token, appId)\n if (args.follow) {\n spinner?.stop(`Following activity after #${cursor} (Ctrl-C to stop).`)\n if (args.json) {\n console.log(JSON.stringify({ type: 'ready', appId, cursor }))\n }\n }\n for (;;) {\n try {\n // Refresh through the normal session path each iteration. A follow\n // process commonly outlives the short JWT it started with.\n const pageToken = args.follow ? await ensureToken() : token\n const page = await repoApi(deployBaseUrl(), pageToken, appId).listActivity({\n since: cursor,\n limit,\n })\n if (!args.follow) {\n spinner?.stop(\n `Loaded ${page.events.length} ${page.events.length === 1 ? 'event' : 'events'}.`,\n )\n }\n if (args.json) {\n // Follow is an NDJSON stream: one fact per line lets an agent react\n // immediately without unpacking page envelopes.\n if (args.follow) {\n for (const event of page.events) {\n console.log(JSON.stringify({ type: 'activity', appId, cursor: event.seq, event }))\n }\n }\n } else {\n const lands = landIndex(page.events)\n for (const e of page.events) console.log(formatEvent(e, lands, actors))\n if (page.events.length === 0 && !args.follow) {\n p.log.info(cursor > 0 ? `No activity after #${cursor}.` : 'No activity yet.')\n }\n }\n cursor = page.cursor\n const result = { data: { events: page.events, cursor: page.cursor, hasMore: page.hasMore } }\n if (args.json && !args.follow) {\n // Exactly one JSON document per one-shot invocation. The caller\n // pages explicitly while hasMore is true.\n return result\n }\n if (!args.follow) {\n if (page.events.length > 0) {\n p.log.info(\n `Cursor: ${cursor}` +\n (page.hasMore\n ? ` · more available (next page: --since ${cursor})`\n : ` (resume later with --since ${cursor})`),\n )\n }\n // A feed reports facts only. Recovery actions belong to the command\n // that actually refuses an operation.\n return result\n }\n if (page.hasMore) continue // a follower drains its backlog before sleeping\n } catch (error) {\n if (!args.follow) throw error\n const code = errorCode(error) ?? 'network_error'\n if (args.json) {\n console.log(\n JSON.stringify({\n type: 'transport',\n appId,\n state: 'retrying',\n cursor,\n retryInMs: FOLLOW_INTERVAL_MS,\n code,\n }),\n )\n } else {\n p.log.warn(`Activity feed interrupted (${code}); retrying in 5s.`)\n }\n }\n await new Promise((resolveSleep) => setTimeout(resolveSleep, FOLLOW_INTERVAL_MS))\n }\n },\n})\n","/**\n * `deepspace git-credential` — a standard git credential helper.\n *\n * `ensureSpaceRemote` installs it host-scoped\n * (`credential.<scheme>://<host>.helper`), so once any sync command has run,\n * plain `git push space` / `git fetch space` work in any terminal: git asks\n * this helper, and it answers with the logged-in DeepSpace bearer token as\n * the password (the server ignores the username).\n *\n * Protocol (git-credential(7)): the op arrives as argv (`get`/`store`/\n * `erase`), the request as `key=value` lines on stdin up to a blank line,\n * and the answer as `key=value` lines on stdout. This helper never prompts,\n * never logs the token, and always exits 0 — for a non-DeepSpace host or a\n * logged-out user its STDOUT stays silent so git falls through to its other\n * helpers (or fails the request with the server's 401). A declined `get`\n * leaves a one-line stderr breadcrumb, because the downstream git failure\n * (\"could not read Username\") never says WHY no credentials came back.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { deployBaseUrl } from '../lib/vc-remote'\n\nfunction parseFields(input: string): Map<string, string> {\n const fields = new Map<string, string>()\n for (const line of input.split('\\n')) {\n if (line === '') break // blank line terminates the request\n const eq = line.indexOf('=')\n if (eq > 0) fields.set(line.slice(0, eq), line.slice(eq + 1))\n }\n return fields\n}\n\n/** Does the credential request target the deploy worker (scheme + host,\n * port included — a localhost override carries one)? */\nexport function credentialHostMatches(input: string, deployUrl: string): boolean {\n let base: URL\n try {\n base = new URL(deployUrl)\n } catch {\n return false\n }\n const fields = parseFields(input)\n if (fields.get('host') !== base.host) return false\n // Fail closed on a missing protocol: git always sends one for HTTP remotes,\n // so its absence is anomalous — never hand a token to an unspecified scheme.\n const protocol = fields.get('protocol')\n return `${protocol}:` === base.protocol\n}\n\n/**\n * The helper's pure core: the exact stdout for one request. Empty string ⇒\n * print nothing (foreign host, store/erase, or no token available).\n */\nexport function respondCredential(\n op: string,\n input: string,\n token: string | null,\n deployUrl: string,\n): string {\n if (op !== 'get' || !token) return ''\n if (!credentialHostMatches(input, deployUrl)) return ''\n // Username is ignored by the server; \"deepspace\" by convention.\n return `username=deepspace\\npassword=${token}\\n`\n}\n\n/**\n * The stderr line for a declined `get` (empty string ⇒ nothing to say).\n * The helper is installed host-scoped, so a mismatch means the remote's host\n * WAS a deploy service when it was configured but the current environment\n * points elsewhere — name both so the fix (usually DEEPSPACE_DEPLOY_URL) is\n * self-evident. Never includes the token; stdout stays untouched.\n */\nexport function declineHint(\n op: string,\n input: string,\n token: string | null,\n deployUrl: string,\n): string {\n if (op !== 'get') return ''\n const host = parseFields(input).get('host')\n if (!host) return ''\n if (!credentialHostMatches(input, deployUrl)) {\n return `deepspace git-credential: no credentials for ${host} — the current deploy service is ${deployUrl}. If ${host} is your deploy service, export DEEPSPACE_DEPLOY_URL to match.\\n`\n }\n if (!token) {\n return 'deepspace git-credential: not logged in (or the session could not be refreshed) — run `deepspace auth login`.\\n'\n }\n return ''\n}\n\nasync function readStdin(): Promise<string> {\n // Git always pipes the request; a bare interactive invocation gets an\n // empty request instead of a hung read.\n if (process.stdin.isTTY) return ''\n process.stdin.setEncoding('utf-8')\n let data = ''\n for await (const chunk of process.stdin) data += chunk\n return data\n}\n\nexport default defineCommand({\n meta: {\n name: 'git-credential',\n description: 'Git credential helper (installed automatically; not for direct use)',\n },\n args: {\n op: {\n type: 'positional',\n description: 'Credential operation: get, store, or erase',\n required: false,\n },\n },\n async run({ args }) {\n const op = String(args.op ?? '')\n const input = await readStdin()\n // store/erase are silent no-ops — the token lives in ~/.deepspace, not in\n // git's credential storage.\n if (op !== 'get') return\n const url = deployBaseUrl()\n // Only touch auth for our own host: a foreign host must get an instant\n // empty answer, not a token-refresh round-trip.\n let token: string | null = null\n if (credentialHostMatches(input, url)) {\n try {\n token = await ensureToken()\n } catch {\n // Not logged in / session expired — stay silent (see header).\n }\n }\n const out = respondCredential(op, input, token, url)\n if (out) {\n process.stdout.write(out)\n } else {\n const hint = declineHint(op, input, token, url)\n if (hint) process.stderr.write(hint)\n }\n },\n})\n"],"mappings":";;;AAUA,SAAS,iBAAAA,iBAAe,SAAS,kBAAkB;AAKnD,SAAS,QAAQC,kBAAiB;AAClC,SAAS,gBAAAC,gBAAc,cAAAC,oBAAkB;AACzC,SAAS,WAAAC,UAAS,QAAAC,cAAY;AAC9B,SAAS,iBAAAC,sBAAqB;;;AClB9B,YAAY,OAAO;AAenB,IAAI,gBAAgC;AAO7B,SAAS,gBAAyB;AACvC,QAAM,OAAgB,QAAQ,OAAO,QAC/B,UAAQ,IACV;AAAA,IACE,OAAO,CAAC,QAAiB;AAAE,UAAI,IAAK,SAAQ,IAAI,GAAG;AAAA,IAAE;AAAA,IACrD,MAAM,CAAC,QAAiB;AAAE,UAAI,IAAK,SAAQ,IAAI,GAAG;AAAA,IAAE;AAAA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kB,IAAI,CAAC;AACjC;","names":["defineCommand","spawnSync","readFileSync","existsSync","dirname","join","fileURLToPath","p","status","text","status","run","p","writeFileSync","mkdirSync","readFileSync","join","homedir","p","AUTH_URL","readFileSync","join","homedir","mkdirSync","writeFileSync","resolve","existsSync","readFileSync","AUTH_URL","SESSION_PATH","TOKEN_PATH","existsSync","readFileSync","existsSync","readFileSync","writeFileSync","join","join","existsSync","readFileSync","writeFileSync","resolve","basename","join","existsSync","readFileSync","join","resolve","parseToml","join","resolve","existsSync","parseToml","readFileSync","existsSync","readFileSync","writeFileSync","mkdirSync","join","resolve","dirname","isAbsolute","mkdirSync","dirname","writeFileSync","existsSync","readFileSync","join","resolve","isAbsolute","p","existsSync","readFileSync","out","writeFileSync","existsSync","readFileSync","rmSync","writeFileSync","join","parseToml","join","existsSync","writeFileSync","rmSync","readFileSync","parseToml","existsSync","readFileSync","existsSync","readFileSync","dirname","join","existsSync","readFileSync","join","pkg","join","existsSync","readFileSync","log","dirname","existsSync","resolve","status","readdirSync","rmSync","join","existsSync","join","p","join","existsSync","resolve","resolve","join","basename","readFileSync","readdirSync","readFileSync","readdirSync","resolve","spawnSync","spawnSync","DEPLOY_URL","resolve","spawnSync","spawnSync","resolve","resolve","spawnSync","defineCommand","p","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","SESSION_COOKIE","AUTH_URL","DIR","join","homedir","existsSync","readFileSync","mkdirSync","writeFileSync","ok","defineCommand","p","defineCommand","resolve","p","execSync","existsSync","readFileSync","readdirSync","dirname","join","resolve","spinner","execSync","join","existsSync","readFileSync","resolve","dirname","readdirSync","p","existsSync","join","pathToFileURL","API_URL","errorMessage","join","existsSync","pathToFileURL","spinner","p","text","p","randomUUID","p","mkdirSync","readFileSync","dirname","join","resolve","spawnSync","status","resolve","join","readFileSync","mkdirSync","dirname","existsSync","isAbsolute","resolve","resolve","isAbsolute","existsSync","status","errorMessage","resolve","status","spinner","randomUUID","errorMessage","resolve","status","p","existsSync","readFileSync","errorMessage","existsSync","readFileSync","DEPLOY_URL","defineCommand","resolve","spinner","errorMessage","p","app","DEPLOY_URL","DEPLOY_URL","defineCommand","DEPLOY_URL","status","sleep","defineCommand","token","API_URL","existsSync","readFileSync","dirname","join","resolve","pathToFileURL","existsSync","mkdirSync","readFileSync","readdirSync","rmSync","writeFileSync","spawnSync","tmpdir","dirname","isAbsolute","join","resolve","dirname","join","existsSync","pkg","readFileSync","readdirSync","isAbsolute","resolve","mkdirSync","writeFileSync","spawnSync","tmpdir","rmSync","existsSync","join","pkg","readFileSync","dirname","pathToFileURL","info","resolve","defineCommand","API_URL","DEPLOY_URL","confirm","resolve","ok","list","defineCommand","defineCommand","API_URL","DEPLOY_URL","api","list","app","p","cancel","defineCommand","defineCommand","p","API_URL","DEPLOY_URL","app","status","cancel","defineCommand","defineCommand","readFileSync","p","API_URL","readFileSync","info","ok","list","defineCommand","defineCommand","existsSync","readFileSync","join","resolve","parseToml","p","intro","info","resolve","join","existsSync","parseToml","readFileSync","defineCommand","p","existsSync","readFileSync","dirname","join","fileURLToPath","API_URL","api","dirname","fileURLToPath","join","existsSync","pkg","readFileSync","detectAppName","ok","defineCommand","readFileSync","DEPLOY_URL","list","defineCommand","del","note","readFileSync","configs","defineCommand","p","existsSync","readFileSync","defineCommand","existsSync","readFileSync","spinner","reportWorkspace","reportRemoteFailure","reportRelease","api","p","spinner","resolveTarget","token","appId","action","ok","p","realpathSync","realpathSync","selectedBranchCheckout","onCurrent","spinner","pushCommand","branchWorktreePath","pullCommand","selectedCheckoutClean","canCheckoutHere","p","existsSync","readdirSync","rmSync","resolve","basename","join","readdirSync","existsSync","rmSync","join","resolve","spinner","basename","p","DEPLOY_URL","spinner","p","DEPLOY_URL","spinner","api","defineCommand","p","isAbsolute","join","resolve","p","api","p","existsSync","realpathSync","isAbsolute","join","relative","sep","realpathSync","relative","sep","isAbsolute","join","existsSync","del","remove","resolveTarget","spinner","api","resolveTarget","join","isAbsolute","resolve","p","existsSync","readdirSync","rmSync","isAbsolute","join","resolve","existsSync","readdirSync","rmSync","spinner","appId","api","token","resolveTarget","view","tip","join","dir","isAbsolute","resolve","p","spinner","api","resolveTarget","p","API_URL","spinner","api","p","spinner","api","resolveTarget","p","spawnSync","readFileSync","join","pkg","readFileSync","join","spawnSync","spinner","api","resolveTarget","run","p","spinner","api","view","resolveTarget","defineCommand","p","formatEvent","spinner","defineCommand","defineCommand","dirname","fileURLToPath","readFileSync","join","existsSync","create","defineCommand","rawArgs","spawnSync","editDistance"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli/cli.ts","../src/cli/lib/spinner.ts","../src/cli/lib/output.ts","../src/cli/lib/cli-format.ts","../src/cli/lib/api.ts","../src/cli/lib/cli-errors.ts","../src/cli/env.ts","../src/cli/auth.ts","../src/cli/jwt.ts","../src/cli/session.ts","../src/cli/lib/command.ts","../src/cli/commands/login.ts","../src/cli/lib/open-browser.ts","../src/cli/commands/logout.ts","../src/cli/lib/app-identity.ts","../src/server/utils/registry-client.ts","../src/cli/commands/dev.ts","../src/cli/lib/app-context.ts","../src/cli/lib/launch-config.ts","../src/cli/lib/git/repository.ts","../src/cli/lib/git/process.ts","../src/cli/lib/dev-vars.ts","../src/cli/lib/app-tokens.ts","../src/server/rooms/binding-manifest.ts","../src/cli/lib/secrets.ts","../src/cli/lib/secure-file.ts","../src/cli/lib/wrangler-env.ts","../src/server/rooms/app-name.ts","../src/cli/lib/install-status.ts","../src/cli/lib/package-manager.ts","../src/cli/lib/preflight.ts","../src/cli/lib/macos-junk.ts","../src/cli/lib/schema-lint.ts","../src/server/schemas/registry.ts","../src/cli/lib/port.ts","../src/cli/commands/kill.ts","../src/cli/commands/test.ts","../src/cli/lib/playwright.ts","../src/cli/commands/screenshot.ts","../src/cli/commands/test-accounts.ts","../src/cli/commands/deploy.ts","../src/cli/commands/deploy/build.ts","../src/cli/commands/deploy/commerce.ts","../src/cli/commands/deploy/output.ts","../src/cli/commands/deploy/request.ts","../src/cli/commands/deploy/repository.ts","../src/cli/lib/git/safety.ts","../src/cli/lib/repo-api.ts","../src/cli/lib/vc-remote.ts","../src/cli/lib/vc-push.ts","../src/cli/lib/workspace-id.ts","../src/cli/commands/deploy/secrets.ts","../src/cli/commands/undeploy.ts","../src/cli/lib/app-target.ts","../src/cli/commands/whoami.ts","../src/cli/commands/apps.ts","../src/cli/commands/logs.ts","../src/shared/log-events.ts","../src/cli/commands/usage.ts","../src/cli/commands/add.ts","../src/cli/commands/feature-installer.ts","../src/cli/commands/domain.ts","../src/cli/commands/collaborators.ts","../src/server/auth/testAccounts.ts","../src/cli/commands/transfer.ts","../src/cli/commands/integrations.ts","../src/cli/commands/_invoke-impl.ts","../src/cli/commands/library.ts","../src/cli/commands/feedback.ts","../src/cli/commands/secrets.ts","../src/cli/lib/citty-args.ts","../src/cli/commands/init.ts","../src/cli/commands/status.ts","../src/cli/commands/push.ts","../src/cli/commands/pull.ts","../src/cli/commands/clone.ts","../src/cli/commands/releases.ts","../src/cli/commands/rollback.ts","../src/cli/commands/workspace.ts","../src/cli/commands/workspace/new.ts","../src/cli/commands/workspace/analysis.ts","../src/cli/commands/workspace/local.ts","../src/cli/commands/workspace/runtime.ts","../src/cli/commands/workspace/attach.ts","../src/cli/commands/workspace/sync.ts","../src/cli/commands/workspace/list.ts","../src/cli/lib/actor-labels.ts","../src/cli/commands/workspace/status.ts","../src/cli/commands/workspace/land.ts","../src/cli/lib/validation.ts","../src/cli/commands/workspace/drop.ts","../src/cli/commands/activity.ts","../src/cli/commands/git-credential.ts"],"sourcesContent":["/**\n * DeepSpace CLI\n *\n * Commands:\n * login — authenticate with your DeepSpace account\n * deploy — build and deploy your app to *.app.space\n * undeploy — remove a deployed app\n * create — redirects to `npm create deepspace`\n */\n\nimport { defineCommand, runMain, runCommand } from 'citty'\n// cross-spawn, not node:child_process: on Windows `npx` is `npx.cmd`, and since\n// Node's CVE-2024-27980 hardening a plain spawn/spawnSync refuses to exec a\n// .cmd (ENOENT / EINVAL) unless shell:true is set — which we won't do (rawArgs\n// would become a shell-injection surface). cross-spawn resolves the shim safely.\nimport { sync as spawnSync } from 'cross-spawn'\nimport { readFileSync, existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { wrapCommandErrors, errorCode } from './lib/cli-errors'\nimport { stopActiveSpinner } from './lib/spinner'\nimport { printAction } from './lib/output'\nimport { DEEPSPACE_ENV } from './env'\nimport login from './commands/login'\nimport logout from './commands/logout'\nimport dev from './commands/dev'\nimport kill from './commands/kill'\nimport test from './commands/test'\nimport screenshot from './commands/screenshot'\nimport testAccounts from './commands/test-accounts'\nimport deploy from './commands/deploy'\nimport undeploy from './commands/undeploy'\nimport whoami from './commands/whoami'\nimport apps from './commands/apps'\nimport logs from './commands/logs'\nimport usage from './commands/usage'\nimport add from './commands/add'\nimport domain from './commands/domain'\nimport collaborators from './commands/collaborators'\nimport transfer from './commands/transfer'\nimport integrations from './commands/integrations'\nimport library from './commands/library'\nimport feedback from './commands/feedback'\nimport secrets from './commands/secrets'\nimport init from './commands/init'\nimport status from './commands/status'\nimport push from './commands/push'\nimport pull from './commands/pull'\nimport clone from './commands/clone'\nimport releases from './commands/releases'\nimport rollback from './commands/rollback'\nimport workspace from './commands/workspace'\nimport activity from './commands/activity'\nimport gitCredential from './commands/git-credential'\n\n// Read own version from package.json so the CLI banner stays in sync with publishes.\n// __dirname of the bundled output is <pkg>/dist; package.json sits one level up.\nconst __dirname = dirname(fileURLToPath(import.meta.url))\nconst pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'))\n\n// workerd doesn't auto-discover system CAs in containers — outbound HTTPS to the\n// auth/api workers fails with \"TLS peer's certificate is not trusted\" until we\n// point it at the standard Debian/Ubuntu cert bundle. Harmless on macOS (path\n// doesn't exist, env var not set).\nif (\n process.platform === 'linux' &&\n !process.env.SSL_CERT_FILE &&\n existsSync('/etc/ssl/certs/ca-certificates.crt')\n) {\n process.env.SSL_CERT_FILE = '/etc/ssl/certs/ca-certificates.crt'\n}\n\nconst create = defineCommand({\n meta: {\n name: 'create',\n description: 'Create a new DeepSpace app (runs create-deepspace; all flags are forwarded)',\n },\n args: {\n name: {\n type: 'positional',\n description: 'App name',\n required: false,\n },\n interactive: {\n type: 'boolean',\n description: 'Prompt for options instead of using defaults',\n },\n template: {\n type: 'string',\n description: 'Starter template (default: starter)',\n },\n local: {\n type: 'string',\n description: 'Use a local SDK monorepo checkout instead of the published package',\n },\n },\n run({ rawArgs }) {\n // Forward EVERY argument verbatim and pin the scaffolder to this CLI's own\n // version — `npm create deepspace@latest` used to drop all flags and could\n // fetch a create-deepspace newer than the running CLI.\n const scaffolder = `create-deepspace@${pkg.version}`\n console.log(`Running: npx ${scaffolder} ${rawArgs.join(' ')}`.trimEnd() + '\\n')\n const res = spawnSync('npx', ['-y', scaffolder, ...rawArgs], { stdio: 'inherit' })\n // Surface a spawn failure instead of exiting silently: with stdio:'inherit'\n // and a spawn error, res.status is null and `?? 1` would swallow the real\n // cause (npx missing from PATH, etc.) behind a bare exit 1.\n if (res.error) {\n const err = res.error as NodeJS.ErrnoException\n console.error(\n `Failed to run \\`npx ${scaffolder}\\`: ${err.message}` +\n (err.code === 'ENOENT' ? '\\nIs Node.js (which provides npx) installed and on PATH?' : ''),\n )\n process.exit(1)\n }\n process.exit(res.status ?? 1)\n },\n})\n\n// ── command groups ──────────────────────────────────────────────────────────\n// Command implementations keep their files; the key is the public name, and\n// the spread re-stamps meta.name so group help renders the full tree.\n\nconst rename = <T extends { meta?: unknown }>(cmd: T, name: string): T =>\n ({ ...cmd, meta: { ...((cmd.meta ?? {}) as Record<string, unknown>), name } }) as T\n\nconst auth = defineCommand({\n meta: { name: 'auth', description: 'Session: login, logout, whoami' },\n subCommands: { login, logout, whoami },\n})\n\nconst app = defineCommand({\n meta: {\n name: 'app',\n description:\n 'The app itself: create, init, list, undeploy, transfer, collaborators, domain, library, usage',\n },\n subCommands: {\n create,\n init,\n list: rename(apps, 'list'),\n undeploy,\n transfer,\n collaborators,\n domain,\n library,\n usage,\n },\n})\n\nconst devGroup = defineCommand({\n meta: { name: 'dev', description: 'Local development' },\n subCommands: { start: rename(dev, 'start'), kill },\n})\nconst testGroup = defineCommand({\n meta: { name: 'test', description: 'App tests and test tooling' },\n subCommands: {\n run: rename(test, 'run'),\n screenshot,\n accounts: rename(testAccounts, 'accounts'),\n },\n})\n\nconst main = defineCommand({\n meta: {\n name: 'deepspace',\n version: pkg.version,\n description: 'DeepSpace SDK CLI',\n },\n subCommands: {\n status,\n activity,\n // Production log tail (arrived from main after the re-tree; a top-level\n // observability verb alongside `activity`, not an `app` subcommand — it\n // is a daily agent verb, and its --follow NDJSON stream is the same\n // documented exception `activity --follow` holds).\n logs,\n push,\n pull,\n clone,\n workspace,\n releases,\n rollback,\n deploy,\n dev: devGroup,\n test: testGroup,\n add,\n secrets,\n integrations,\n auth,\n app,\n feedback,\n 'git-credential': gitCredential,\n },\n // No `run()` here — citty cascades parent run() AFTER subcommand finishes,\n // which corrupts agent-friendly output (`--json`) and prints noise on every\n // command. Citty's default behavior when no subcommand matches is to print\n // help, which is what we want for `deepspace` with no args.\n})\n\n// Escaped errors (API failures, network hiccups) render as one clean line\n// instead of citty's default Error-object dump with a stack trace.\n//\n// For `--json` callers, drive runCommand ourselves: citty validates the argv and\n// throws its own CLIError BEFORE run() executes, so a parse failure (missing\n// required positional like `workspace attach` with no id, unknown command) never\n// reaches a command's own --json catch — runMain would print the human usage\n// page, which a machine consumer can't parse. Convert it into a coded JSON\n// refusal. `--help`/`-h` still goes through runMain so help stays read-only and\n// exits 0 regardless of --json (runCommand would ignore the flag and could run a\n// mutating command); everything else keeps runMain's behavior untouched.\n/** Levenshtein distance, for the did-you-mean hint below. Inputs are command\n * names (short), so the O(n·m) DP is trivially cheap. */\nfunction editDistance(a: string, b: string): number {\n const dp = Array.from({ length: a.length + 1 }, (_, i) => [\n i,\n ...new Array<number>(b.length).fill(0),\n ])\n for (let j = 1; j <= b.length; j++) dp[0][j] = j\n for (let i = 1; i <= a.length; i++) {\n for (let j = 1; j <= b.length; j++) {\n dp[i][j] = Math.min(\n dp[i - 1][j] + 1,\n dp[i][j - 1] + 1,\n dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),\n )\n }\n }\n return dp[a.length][b.length]\n}\n\nfunction closestCommand(input: string, candidates: string[]): string | null {\n let best: string | null = null\n let bestDist = 4 // farther than 3 edits is a different word, not a typo\n for (const c of candidates) {\n const d = editDistance(input.toLowerCase(), c)\n if (d < bestDist) {\n best = c\n bestDist = d\n }\n }\n return best\n}\n\n/**\n * Fail-fast unknown-command guard for the HUMAN path. citty's default for an\n * unknown (sub)command is to print usage and exit 0 — which lets a script or\n * agent driving a stale command surface read a typo as success. The --json\n * path already converts citty's E_UNKNOWN_COMMAND into a coded exit-1\n * refusal; this makes the exit-code contract uniform for everyone else.\n *\n * Walks the static subcommand tables only while tokens look like command\n * names: the first flag ends the walk (citty may still resolve a subcommand\n * placed after flags — that arrangement just isn't pre-checked), and a\n * command without subCommands consumes the rest of argv as its own args.\n */\nfunction assertKnownCommandPath(argv: string[]): void {\n let table: Record<string, unknown> | undefined = main.subCommands as Record<string, unknown>\n let path = 'deepspace'\n for (const tok of argv) {\n if (!table || tok.startsWith('-')) return\n const entry: unknown = table[tok]\n if (!entry) {\n const hint = closestCommand(tok, Object.keys(table))\n console.error(\n `Unknown command: ${path} ${tok}${hint ? ` — did you mean \\`${path} ${hint}\\`?` : ''}\\n` +\n `Run \\`${path} --help\\` for the command list.`,\n )\n if (hint) {\n printAction({ cwd: process.cwd(), argv: [...path.split(' '), hint] })\n }\n process.exit(1)\n }\n path += ` ${tok}`\n table = (entry as { subCommands?: Record<string, unknown> }).subCommands\n }\n}\n\nconst rawArgs = process.argv.slice(2)\nconst wantsHelp = rawArgs.some((arg) => arg === '--help' || arg === '-h')\nif (DEEPSPACE_ENV === 'invalid') {\n const error =\n `Invalid DEEPSPACE_ENV=${JSON.stringify(process.env.DEEPSPACE_ENV)}. ` +\n 'Use `staging`, `production`, or unset it; refusing to default to production.'\n if (rawArgs.includes('--json') && !wantsHelp) {\n console.log(JSON.stringify({ ok: false, code: 'invalid_environment', error }))\n } else {\n console.error(error)\n }\n process.exit(1)\n}\nif (rawArgs.includes('--json') && !wantsHelp) {\n const first = rawArgs.find((a) => !a.startsWith('-'))\n // Unknown top-level command: give the MACHINE caller the same did-you-mean\n // the human path gets — the consumer that most needs it. (Deeper paths fall\n // through to citty's E_UNKNOWN_COMMAND mapping below.)\n if (first && !Object.prototype.hasOwnProperty.call(main.subCommands ?? {}, first)) {\n const hint = closestCommand(first, Object.keys(main.subCommands ?? {}))\n console.log(\n JSON.stringify({\n ok: false,\n code: 'unknown_command',\n error: `Unknown command: deepspace ${first}${hint ? ` — did you mean \\`deepspace ${hint}\\`?` : ''}`,\n ...(hint ? { action: { cwd: process.cwd(), argv: ['deepspace', hint] } } : {}),\n }),\n )\n process.exit(1)\n }\n runCommand(wrapCommandErrors(main), { rawArgs }).catch((err) => {\n stopActiveSpinner()\n // citty's CLIError carries a `.code` per condition; map each to its own\n // stable slug (EARG = a missing/invalid positional or flag). A genuinely\n // escaped run() error is already handled by wrapCommandErrors → renderCliError\n // and exits before this catch, so the errorCode() branch only guards the\n // rare non-citty throw that reaches here.\n const cittyCode =\n err instanceof Error && err.name === 'CLIError' ? (err as { code?: string }).code : undefined\n const code =\n cittyCode === 'EARG'\n ? 'missing_argument'\n : cittyCode === 'E_UNKNOWN_COMMAND'\n ? 'unknown_command'\n : cittyCode === 'E_NO_COMMAND'\n ? 'no_command'\n : errorCode(err)\n // citty colorizes some messages (cyan) and its no-color check ignores a\n // non-TTY stdout, so strip ANSI before it lands in the machine-read string.\n const message = (err instanceof Error ? err.message : String(err)).replace(\n // eslint-disable-next-line no-control-regex\n /\\u001b\\[[0-9;]*m/g,\n '',\n )\n console.log(JSON.stringify({ ok: false, error: message, ...(code ? { code } : {}) }))\n process.exit(1)\n })\n} else {\n // `--help` stays exempt so help probes remain read-only.\n if (!wantsHelp) assertKnownCommandPath(rawArgs)\n runMain(wrapCommandErrors(main))\n}\n","import * as p from '@clack/prompts'\n\nexport interface Spinner {\n start: (msg?: string) => void\n stop: (msg?: string) => void\n message: (msg?: string) => void\n}\n\n// The spinner currently painting the terminal, if any. On Windows a live\n// @clack/prompts spinner registers a `process.on('exit')` handler that writes\n// a final frame to the TTY; calling process.exit() while it is still running\n// makes that write land as libuv tears the TTY handle down —\n// `Assertion failed: !(handle->flags & UV_HANDLE_CLOSING)` — turning a clean\n// exit(1) into an abort. Tracking the active spinner lets error helpers stop it\n// (which clears the interval and neuters that exit handler) before they exit.\nlet activeSpinner: Spinner | null = null\n\n// In a real terminal, @clack/prompts repaints the spinner by writing `\\r`\n// to overwrite the previous frame. In non-TTY contexts (agents, CI logs,\n// pipes, `tee`-ed output) `\\r` does nothing and every frame becomes a new\n// line — a single long phase floods the log with thousands of repeats.\n// When stdout is not a TTY we fall back to one static line per phase.\nexport function createSpinner(): Spinner {\n const impl: Spinner = process.stdout.isTTY\n ? p.spinner()\n : {\n start: (msg?: string) => { if (msg) console.log(msg) },\n stop: (msg?: string) => { if (msg) console.log(msg) },\n message: (msg?: string) => { if (msg) console.log(msg) },\n }\n const wrapper: Spinner = {\n start: (msg?: string) => {\n activeSpinner = wrapper\n impl.start(msg)\n },\n stop: (msg?: string) => {\n impl.stop(msg)\n if (activeSpinner === wrapper) activeSpinner = null\n },\n message: (msg?: string) => impl.message(msg),\n }\n return wrapper\n}\n\n/**\n * Stop whatever spinner is currently painting, if any. Call before\n * process.exit() on an error path so a live spinner never tears down mid-write\n * (see activeSpinner above). Idempotent and safe when nothing is active.\n */\nexport function stopActiveSpinner(): void {\n activeSpinner?.stop()\n}\n","/**\n * The output contract (docs: agent-experience standard).\n *\n * Agents read text: the human output is the interface and must be complete.\n * These helpers standardize its two optional machine anchors —\n *\n * 1. a refusal's final line carries its slug: `…message. [non_fast_forward]`\n * 2. when a command owns one safe follow-up, its final line names it:\n * `Next: deepspace pull`\n *\n * `--json` mirrors them (`code`, `action: { cwd, argv }`) but is never the primary\n * surface. Exit codes stay load-bearing: 0 done, 1 failed, 2 succeeded with\n * a local step remaining.\n */\n\nimport * as p from '@clack/prompts'\nimport { isAbsolute } from 'node:path'\nimport { shQuote } from './cli-format'\n\n/** One executable recovery step. Commands decide which action is appropriate;\n * the runtime only transports and renders it. */\nexport interface CliAction {\n cwd: string\n argv: string[]\n}\n\n/** Construct an action without turning argv back into a shell program. */\nexport function cliAction(...argv: string[]): CliAction {\n const action = { cwd: process.cwd(), argv }\n assertExecutableAction(action)\n return action\n}\n\n/** Reject action-shaped hints that an agent cannot execute verbatim. */\nexport function assertExecutableAction(action: CliAction): void {\n if (!isAbsolute(action.cwd)) throw new TypeError('CLI action cwd must be absolute')\n if (action.argv.length === 0 || action.argv[0].trim() === '') {\n throw new TypeError('CLI action argv must name an executable')\n }\n if (action.argv.some((arg) => /^<[^<>]+>$/.test(arg))) {\n throw new TypeError('CLI action argv must not contain placeholder tokens')\n }\n}\n\n/** Suffix a refusal message with its machine slug, last line only. Idempotent\n * (a message already carrying `[slug]` at the end is left alone) so wrapper\n * layers can apply it without double-tagging. */\nexport function withSlug(msg: string, code: string): string {\n const tag = `[${code}]`\n return msg.trimEnd().endsWith(tag) ? msg : `${msg.trimEnd()} ${tag}`\n}\n\nfunction displayArg(arg: string): string {\n return /^[A-Za-z0-9_./:@%+=,-]+$/.test(arg) ? arg : shQuote(arg)\n}\n\n/** Render the same structured action exposed to agents as a copy-pasteable\n * human command. The shell string is presentation only, never machine data. */\nexport function printAction(action: CliAction): void {\n assertExecutableAction(action)\n const command = action.argv.map(displayArg).join(' ')\n const prefix = action.cwd === process.cwd() ? '' : `cd ${displayArg(action.cwd)} && `\n p.log.message(`Next: ${prefix}${command}`)\n}\n","/** POSIX single-quote a string for safe interpolation into a human-facing\n * \"run this\" command. Never use the result as a machine contract — that's\n * what structured {cwd, argv} is for. */\nexport function shQuote(s: string): string {\n return `'${s.replace(/'/g, \"'\\\\''\")}'`\n}\n\n/** Render argv as a copy-pasteable human command. */\nexport function humanCommand(argv: readonly string[]): string {\n return argv.map((arg) => (/^[A-Za-z0-9_./=:@-]+$/.test(arg) ? arg : shQuote(arg))).join(' ')\n}\n","/**\n * Authenticated JSON fetch against a platform worker.\n *\n * Shared by the CLI commands that call the platform as the logged-in user\n * (`domain`, `feedback`, `collaborators`, `transfer`, …). Sends a Bearer\n * token, parses the JSON body, and on a non-2xx response throws an ApiError\n * carrying the worker's `{ error, code }` — message for display, code for\n * branching — so callers never string-sniff error text.\n */\nexport class ApiError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly code?: string,\n /** Internal REST path — kept off the message (DEBUG-only rendering). */\n readonly apiPath?: string,\n ) {\n super(message)\n }\n}\n\n/**\n * Registered by auth.ts at load: force-mint a fresh JWT from the stored\n * session, bypassing the cached token file. Lets apiFetch heal a 401 whose\n * cause is a token that is locally \"valid\" but rejected server-side (signing-\n * key rotation, revocation) with one silent refresh + retry instead of a hard\n * error an agent has to reason about. Null ⇒ the session itself is dead and\n * the original 401 stands. A callback (not an import) so this low-level\n * module stays dependency-free of auth.ts.\n */\nlet refreshAuthToken: (() => Promise<string | null>) | null = null\nexport function registerAuthRefresh(fn: () => Promise<string | null>): void {\n refreshAuthToken = fn\n}\n\nexport async function apiFetch<T>(\n baseUrl: string,\n token: string,\n path: string,\n init?: RequestInit,\n isRetry = false,\n): Promise<T> {\n let res: Response\n let text: string\n try {\n res = await fetch(`${baseUrl}${path}`, {\n ...init,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n ...(init?.headers ?? {}),\n },\n })\n // One transparent recovery per request. Safe for mutations too: every\n // repo-API mutation is idempotency-keyed, and the 401 means the server\n // never acted. Requires a NEW token — retrying the same rejected bearer\n // would just double the failure latency.\n if (res.status === 401 && !isRetry && refreshAuthToken) {\n const fresh = await refreshAuthToken()\n if (fresh && fresh !== token) return apiFetch<T>(baseUrl, fresh, path, init, true)\n }\n text = await res.text()\n } catch (err) {\n // A network-level failure (connection refused, DNS, TLS, offline) throws a\n // TypeError('fetch failed'), not an HTTP status — give it a stable code so a\n // --json caller can classify the transport outage instead of scraping prose.\n throw new ApiError(\n `Could not reach the deploy service at ${baseUrl}: ${err instanceof Error ? err.message : String(err)}. Check your connection (and DEEPSPACE_DEPLOY_URL), then retry.`,\n 0,\n 'network_error',\n path,\n )\n }\n if (!res.ok) {\n let msg = text\n let code: string | undefined\n try {\n const body = JSON.parse(text) as { error?: string; code?: string }\n msg = body.error ?? text\n code = body.code\n } catch {\n // not JSON\n }\n // A bare router 404 (\"Not found\", no server code) means DEEPSPACE_DEPLOY_URL\n // points at a service that doesn't host the repo API (wrong/old URL). Give it\n // an actionable message + code UNIFORMLY for every caller (incl. rollback's\n // direct endpoint), so a --json agent gets one stable slug for this case.\n if (!code && res.status === 404 && text.trim() === 'Not found') {\n code = 'unrecognized_service'\n msg = `The deploy service at ${baseUrl} doesn't recognize this request — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?); if it is, the server may be older than this CLI.`\n }\n // Any other server error that supplied no `code` of its own (a non-conforming\n // 5xx, an HTML error page) still needs a stable slug to classify.\n code = code ?? (res.status >= 500 ? 'server_error' : 'http_error')\n // Message = the server's sentence only. The internal REST path and raw\n // status read like a stack trace to users (same treatment as secretsApi);\n // they stay on the error's fields for DEBUG rendering and branching.\n throw new ApiError(msg || `Request failed (${res.status})`, res.status, code, path)\n }\n if (!text) return {} as T\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n // A 2xx with a non-JSON body isn't the repo API — code it so a --json caller\n // doesn't get a bare SyntaxError.\n throw new ApiError(\n `The deploy service at ${baseUrl} returned a malformed (non-JSON) response — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n res.status,\n 'invalid_response',\n path,\n )\n }\n // Every repo-API response is a JSON object; a null/array/primitive 2xx body is a\n // wrong/broken service — reject it with a code instead of letting a caller\n // destructure null and crash uncoded.\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new ApiError(\n `The deploy service at ${baseUrl} returned an unexpected response shape — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n res.status,\n 'invalid_response',\n path,\n )\n }\n return parsed as T\n}\n","/**\n * Friendly rendering for errors that escape a command's run().\n *\n * citty's runMain catches escaped errors and console.errors the full Error\n * object — stack trace and all. For expected operational failures (an API\n * 403, a network hiccup) that reads like a crash. wrapCommandErrors()\n * recursively wraps every command's run() so escaped errors render as a\n * single clean message (with known API error slugs translated), while\n * citty's own help/version/usage handling stays untouched. Set DEBUG=1 to\n * get the full stack back.\n */\n\nimport type { CommandDef } from 'citty'\nimport { stopActiveSpinner } from './spinner'\nimport { withSlug } from './output'\nimport { ApiError } from './api'\n\n/**\n * A client-side or precondition failure that carries a machine `code`, so a\n * thrown error (a blank `--app`, \"not logged in\", an empty repo) reads in\n * `--json` exactly like a server ApiError — `{ ok:false, code, error }` — rather\n * than a bare message. Reuses no HTTP semantics (unlike ApiError). Most instances\n * are pure client-side validation that never touch the network; a few are\n * preconditions checked before the real work (e.g. an expired session, detected\n * after a refresh attempt) — the shared contract is only \"carries a stable code\".\n */\nexport class InputError extends Error {\n constructor(\n message: string,\n readonly code: string,\n ) {\n super(message)\n }\n}\n\n/**\n * The machine `code` slug an error carries, if any — an {@link ApiError} (server\n * failure) or an {@link InputError} (client-side validation). Lets a command's\n * `--json` catch surface `code` uniformly without knowing the concrete type.\n * Deliberately narrow: it does NOT read arbitrary `.code` properties (a Node\n * `ENOENT` fs error must not leak into the machine contract as a `code`).\n */\nexport function errorCode(err: unknown): string | undefined {\n if (err instanceof ApiError || err instanceof InputError) return err.code\n // GitError (raw git operation/transport failure) — duck-typed by `name` to\n // avoid a cli-errors↔git import cycle. Give it a generic `git_error` (or its\n // own slug, if set) so a --json caller can branch on \"a git op failed\"\n // instead of scraping the fatal-… prose.\n if (err instanceof Error && err.name === 'GitError') return (err as { code?: string }).code ?? 'git_error'\n return undefined\n}\n\n/**\n * API error slugs that genuinely confuse people → what to tell them. Slugs\n * whose meaning is obvious from the name (invalid_email, ...) stay unmapped\n * and render as-is; don't grow this into a mirror of the server's errors.\n */\nconst API_ERROR_HINTS: Record<string, string> = {\n not_app_owner: 'Only the app owner can do this.',\n app_not_found:\n 'App not found on the service this command asked. Check the app id — the DEEPSPACE_APP_ID ' +\n 'value in wrangler.toml, usually `app_…` (a legacy app\\'s id is its name); list your apps ' +\n 'with `deepspace app list`. If you are overriding DEEPSPACE_DEPLOY_URL (staging), note that ' +\n 'account/collaborator commands go to the PLATFORM API — an app registered only on a staging ' +\n 'deploy service is unknown there. (`domain` commands take the deployed app *name* instead.)',\n not_app_owner_or_collaborator: 'You must be the app owner or a collaborator to do this.',\n test_account_cannot_be_collaborator:\n 'Test accounts cannot be added as collaborators. Use a real DeepSpace account.',\n user_not_found:\n 'No DeepSpace user with that email. They need to log in to DeepSpace at least once ' +\n '(`deepspace auth login`, or sign in to any app) before they can be referenced by email.',\n insufficient_credits:\n 'Out of credits. Inviting a new collaborator by email sends them a transactional ' +\n 'email billed to your account — top up your credits and try again.',\n invite_email_failed:\n 'The invite email could not be sent. You were not charged — please try again in a moment.',\n}\n\n/** Exported for tests. One clean message for an escaped error. */\nexport function formatCliError(err: unknown): string {\n const message = err instanceof Error ? err.message : String(err)\n // The platform returns { error: <sentence>, code: <slug> }, and apiFetch\n // preserves that code on a typed error. Never infer machine state from prose.\n const slug = errorCode(err)\n const hint = slug ? API_ERROR_HINTS[slug] : undefined\n // The server sentence and the hint can say the same thing — don't stutter.\n return hint && !message.includes(hint) ? `${message}\\n${hint}` : message\n}\n\nexport function renderCliError(err: unknown): never {\n // A command may throw with its progress spinner still live; stop it before\n // the process.exit below so the exit can't abort on Windows (see spinner.ts).\n stopActiveSpinner()\n const message = formatCliError(err)\n const slug = errorCode(err)\n // `--json` callers get the envelope every other refusal path emits. Without\n // this, an error that ESCAPES a command's own try/catch printed prose to\n // stderr and left stdout EMPTY — a machine consumer saw a non-zero exit with\n // nothing to parse. Commands that catch their own errors are unaffected;\n // this is the fallback for the ~15 that don't.\n if (process.argv.includes('--json')) {\n console.log(JSON.stringify({ ok: false, ...(slug ? { code: slug } : {}), error: message }))\n process.exit(1)\n }\n // Human path: the last line carries the machine slug, per the output\n // contract (lib/output.ts).\n console.error(slug ? withSlug(message, slug) : message)\n if (process.env.DEBUG) {\n // ApiError/secretsApi keep the internal REST path off the message; show it here.\n const { apiPath, status } = err as { apiPath?: string; status?: number }\n if (apiPath) console.error(`\\nAPI ${apiPath}${status ? ` (${status})` : ''}`)\n if (err instanceof Error && err.stack) console.error('\\n' + err.stack)\n }\n process.exit(1)\n}\n\ntype RunFn = NonNullable<CommandDef['run']>\n\n/**\n * Recursively wrap a concrete command tree's run() handlers. Only plain\n * object subcommands are wrapped — every command in this CLI is one; lazy\n * (function/promise) subcommand definitions would pass through unwrapped.\n */\nexport function wrapCommandErrors<T extends CommandDef>(cmd: T): T {\n const run = cmd.run\n if (run) {\n cmd.run = (async (ctx: Parameters<RunFn>[0]) => {\n try {\n await run(ctx)\n } catch (err) {\n renderCliError(err)\n }\n }) as RunFn\n }\n if (cmd.subCommands && typeof cmd.subCommands === 'object') {\n for (const sub of Object.values(cmd.subCommands)) {\n if (sub && typeof sub === 'object') wrapCommandErrors(sub as CommandDef)\n }\n }\n return cmd\n}\n","/** Stable platform-environment selection shared by every CLI command. */\n\n/**\n * `staging` targets the isolated constellation on spacestest.com. Unknown\n * explicit values are invalid and receive inert URLs, never production URLs.\n */\nexport type DeepSpaceEnvironment = 'production' | 'staging' | 'invalid'\n\nexport function resolveDeepSpaceEnvironment(value: string | undefined): DeepSpaceEnvironment {\n if (value === undefined || value === 'production') return 'production'\n if (value === 'staging') return 'staging'\n return 'invalid'\n}\n\nexport const DEEPSPACE_ENV = resolveDeepSpaceEnvironment(process.env.DEEPSPACE_ENV)\n\nconst PROD_URLS = {\n auth: 'https://auth.deep.space',\n api: 'https://api-worker.deep.space',\n platform: 'https://platform-worker.deep.space',\n deploy: 'https://deploy-worker.deep.space',\n} as const\n\nconst STAGING_URLS = {\n // Services live on deepspacesites.com, apps on spacestest.com. This mirrors\n // prod's two-zone split because a Worker cannot fetch one in its own zone.\n auth: 'https://auth.deepspacesites.com',\n api: 'https://api.deepspacesites.com',\n platform: 'https://platform.deepspacesites.com',\n deploy: 'https://deploy.deepspacesites.com',\n} as const\n\n// Defense in depth for callers imported without cli.ts's validation.\nconst INVALID_URLS = {\n auth: 'http://127.0.0.1:9',\n api: 'http://127.0.0.1:9',\n platform: 'http://127.0.0.1:9',\n deploy: 'http://127.0.0.1:9',\n} as const\n\nexport const PLATFORM_URLS =\n DEEPSPACE_ENV === 'production'\n ? PROD_URLS\n : DEEPSPACE_ENV === 'staging'\n ? STAGING_URLS\n : INVALID_URLS\n\n/** Report per-service process overrides without changing the stable presets. */\nexport function effectivePlatformUrls(env: NodeJS.ProcessEnv = process.env) {\n return {\n auth: env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth,\n api: env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api,\n platform: env.DEEPSPACE_PLATFORM_URL ?? PLATFORM_URLS.platform,\n deploy: env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy,\n }\n}\n\nexport const DASHBOARD_URL =\n DEEPSPACE_ENV === 'production'\n ? 'https://dashboard.deep.space'\n : DEEPSPACE_ENV === 'staging'\n ? 'https://dashboard.deepspacesites.com'\n : 'http://127.0.0.1:9'\n","/**\n * CLI auth utilities — shared across all commands.\n *\n * Reads the session token from ~/.deepspace/session and ensures\n * a fresh JWT is available at ~/.deepspace/token.\n */\n\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nimport { PLATFORM_URLS } from './env'\nimport { decodeJwtPayload } from './jwt'\nimport { exchangeSession } from './session'\nimport { registerAuthRefresh } from './lib/api'\nimport { cliAction, Refusal } from './lib/command'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth\n/** The plane whose credentials keep the historical un-suffixed filenames. */\nconst PROD_AUTH_URL = 'https://auth.deep.space'\n\nconst DIR = join(homedir(), '.deepspace')\n\n/**\n * Credentials are stored PER AUTH PLANE.\n *\n * They used to be one global pair (`~/.deepspace/{session,token}`), so a\n * single `DEEPSPACE_ENV=staging` login silently clobbered the production\n * session — and the next prod command exchanged a staging cookie against the\n * prod auth worker and reported \"Session expired. Run `deepspace auth\n * login`\", which reads like a token-refresh failure but is actually a\n * different account plane. Auto-refresh was working the whole time.\n *\n * Keyed by the effective auth URL, because that (not DEEPSPACE_ENV alone) is\n * what decides who issued the cookie — a bare `DEEPSPACE_AUTH_URL` override\n * gets its own slot too. Production keeps the historical filenames, so\n * upgrading does not log anyone out.\n */\nfunction credentialSuffix(authUrl: string): string {\n if (authUrl === PROD_AUTH_URL) return ''\n const host = (() => {\n try {\n return new URL(authUrl).host\n } catch {\n return authUrl\n }\n })()\n return `.${host.replace(/[^a-zA-Z0-9]+/g, '-')}`\n}\n\n/** The {session,token} file pair for a given auth plane. */\nexport function credentialPaths(authUrl: string = AUTH_URL): {\n sessionPath: string\n tokenPath: string\n} {\n const suffix = credentialSuffix(authUrl)\n return { sessionPath: join(DIR, `session${suffix}`), tokenPath: join(DIR, `token${suffix}`) }\n}\n\nexport const { sessionPath: SESSION_PATH, tokenPath: TOKEN_PATH } = credentialPaths()\n\n/**\n * Ensure a valid JWT exists. Refreshes from the session token if expired.\n * Returns the JWT string or throws if not logged in / session expired.\n */\nexport async function ensureToken(): Promise<string> {\n // Try existing token first — if it's still valid, skip the refresh\n if (existsSync(TOKEN_PATH)) {\n const existing = readFileSync(TOKEN_PATH, 'utf-8').trim()\n if (isTokenValid(existing)) {\n return existing\n }\n }\n\n if (!existsSync(SESSION_PATH)) {\n throw new Refusal('Not logged in. Run `deepspace auth login` first.', 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const sessionToken = readFileSync(SESSION_PATH, 'utf-8').trim()\n\n // Refresh from session\n const token = await exchangeSession(AUTH_URL, sessionToken)\n if (!token) {\n throw new Refusal(\n 'Session expired. Run `deepspace auth login` to re-authenticate.',\n 'not_authenticated',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n\n mkdirSync(DIR, { recursive: true, mode: 0o700 })\n writeFileSync(TOKEN_PATH, token, { mode: 0o600 })\n\n return token\n}\n\n/** Check if a JWT has at least 30 seconds of validity remaining. */\nfunction isTokenValid(jwt: string): boolean {\n try {\n const payload = decodeJwtPayload<{ exp?: number }>(jwt)\n return typeof payload.exp === 'number' && payload.exp * 1000 > Date.now() + 30_000\n } catch {\n return false\n }\n}\n\n/**\n * Force-mint a fresh JWT from the stored session, ignoring the cached token\n * file — apiFetch's 401 recovery (see registerAuthRefresh). Never throws:\n * null means the session is gone/expired, and the caller's original 401\n * (with its own actionable message) is the right error to surface.\n */\nregisterAuthRefresh(async (): Promise<string | null> => {\n try {\n if (!existsSync(SESSION_PATH)) return null\n const sessionToken = readFileSync(SESSION_PATH, 'utf-8').trim()\n const token = await exchangeSession(AUTH_URL, sessionToken)\n if (!token) return null\n mkdirSync(DIR, { recursive: true, mode: 0o700 })\n writeFileSync(TOKEN_PATH, token, { mode: 0o600 })\n return token\n } catch {\n return null\n }\n})\n","export function decodeJwtPayload<T = Record<string, unknown>>(token: string): T {\n const payloadSegment = token.split('.')[1]\n if (!payloadSegment) {\n throw new Error('JWT payload is missing')\n }\n return JSON.parse(Buffer.from(payloadSegment, 'base64url').toString('utf8')) as T\n}\n","/**\n * CLI session helpers — exchange a Better Auth session cookie for a short-lived\n * JWT against the auth worker. Shared by `auth.ts` (token refresh for all\n * authenticated commands) and `login.ts` (email/password flow).\n */\n\nexport const SESSION_COOKIE = '__Secure-better-auth.session_token'\n\n/**\n * Exchange a Better Auth session token for a fresh JWT.\n * Returns null if the session is invalid or expired.\n */\nexport async function exchangeSession(\n authUrl: string,\n sessionToken: string,\n): Promise<string | null> {\n const res = await fetch(`${authUrl}/api/auth/token`, {\n method: 'POST',\n headers: {\n Cookie: `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}`,\n Origin: authUrl,\n },\n })\n if (!res.ok) return null\n const data = (await res.json()) as { token?: string | null }\n return data.token ?? null\n}\n","/**\n * The shared command-output boundary. Command bodies return content or throw\n * a {@link Refusal}; this runtime owns JSON envelopes, human slugs and optional\n * actions, plus the 0/1/2 exit convention.\n */\n\nimport { defineCommand, type ArgsDef, type CommandDef } from 'citty'\nimport * as p from '@clack/prompts'\nimport { stopActiveSpinner } from './spinner'\nimport { assertExecutableAction, printAction, withSlug, type CliAction } from './output'\nimport { errorCode } from './cli-errors'\n\nexport { cliAction } from './output'\n\n/**\n * A refusal the caller can act on: carries the machine slug that appears both\n * in `--json` as `code` and at the end of the human line, plus at most one\n * executable action that resolves it.\n *\n * `actionRequired` marks the third exit state — the operation did what it\n * could and a LOCAL step remains (merge the tip, commit the tree). It exits 2,\n * which is the difference between \"this failed\" and \"your turn\", and is the\n * single most useful signal an agent gets from this CLI.\n */\nexport class Refusal extends Error {\n readonly code: string\n readonly action: CliAction | undefined\n readonly actionRequired: boolean\n readonly extra: Record<string, unknown>\n\n constructor(\n message: string,\n code: string,\n opts: { action?: CliAction; actionRequired?: boolean; extra?: Record<string, unknown> } = {},\n ) {\n super(message)\n this.name = 'Refusal'\n this.code = code\n if (opts.action) assertExecutableAction(opts.action)\n this.action = opts.action\n this.actionRequired = opts.actionRequired ?? false\n this.extra = opts.extra ?? {}\n }\n}\n\n/** What a command body returns: the machine payload plus its follow-ups. */\nexport interface CommandResult {\n /** Merged into the `--json` envelope. Omit for commands with no payload. */\n data?: Record<string, unknown>\n /** One executable follow-up: the `Next:` line and envelope's `action`. */\n action?: CliAction\n}\n\n/**\n * Strip the envelope's reserved keys from a payload before it is spread into\n * the envelope. `data`/`extra` can carry raw server JSON (`integrations\n * invoke` forwards the response body verbatim), and a payload containing\n * `ok`, `action`, or `actionRequired` must not be able to flip a failure to\n * success or hand an agent an unvalidated recovery action.\n */\nfunction withoutReservedKeys(payload: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(payload).filter(\n ([key]) =>\n ![\n 'ok',\n 'code',\n 'error',\n 'action',\n 'actionRequired',\n 'next',\n 'nextAction',\n 'resume',\n ].includes(key),\n ),\n )\n}\n\n/**\n * Exit only once stdout has drained. `console.log` on a PIPE is asynchronous\n * past the OS buffer (64 KiB on Linux/macOS), so exiting immediately truncates\n * a large payload mid-write — `integrations list --json` is already ~29 KB and\n * the catalog grows. The empty write's callback fires after the queue flushes.\n */\nfunction exitWhenFlushed(code: number): never {\n // Nothing queued (a TTY, a small payload, or a test harness capturing\n // console.log) — exit synchronously. Deferring unconditionally would break\n // any caller that mocks process.exit and asserts synchronously, and would\n // let execution continue past a `never` return.\n if (process.stdout.writableLength === 0) process.exit(code)\n process.stdout.write('', () => process.exit(code))\n return undefined as never\n}\n\nexport interface DeepspaceCommandDef<A extends ArgsDef> {\n meta: { name: string; description: string }\n args?: A\n /** Print human output yourself; return the machine payload. Throw a\n * {@link Refusal} for an actionable failure. */\n run: (ctx: { args: Record<string, unknown> & { json: boolean } }) => Promise<CommandResult | void>\n}\n\n/**\n * Wrap a command body in the contract. Injects `--json`, renders both output\n * paths, and owns the exit codes — a body never calls process.exit itself.\n */\nexport function defineDeepspaceCommand<A extends ArgsDef>(def: DeepspaceCommandDef<A>): CommandDef {\n // The injected `json` arg widens citty's inferred ArgsDef generic, which no\n // longer matches the bare `CommandDef` the registry holds. The runtime reads\n // args dynamically, so the erasure is safe and keeps every command in the\n // tree one uniform type.\n return defineCommand({\n meta: def.meta,\n args: {\n ...(def.args ?? ({} as A)),\n json: {\n type: 'boolean',\n description: 'Emit a single-line JSON result for scripts/agents',\n default: false,\n },\n },\n async run({ args }) {\n const json = Boolean((args as { json?: boolean }).json)\n let succeeded = false\n try {\n const out =\n (await def.run({ args: args as Record<string, unknown> & { json: boolean } })) ?? {}\n if (out.action) assertExecutableAction(out.action)\n if (json) {\n console.log(\n JSON.stringify({\n ok: true,\n ...withoutReservedKeys(out.data ?? {}),\n ...(out.action ? { action: out.action } : {}),\n }),\n )\n } else if (out.action) {\n printAction(out.action)\n }\n succeeded = true\n } catch (err) {\n stopActiveSpinner()\n const refusal = err instanceof Refusal ? err : null\n const code = refusal?.code ?? errorCode(err)\n const message = err instanceof Error ? err.message : String(err)\n if (json) {\n console.log(\n JSON.stringify({\n ok: false,\n ...(code ? { code } : {}),\n ...(refusal?.actionRequired ? { actionRequired: true } : {}),\n error: message,\n ...(refusal?.action ? { action: refusal.action } : {}),\n ...withoutReservedKeys(refusal?.extra ?? {}),\n }),\n )\n } else {\n const line = code ? withSlug(message, code) : message\n if (refusal?.actionRequired) p.log.warn(line)\n else p.log.error(line)\n if (refusal?.action) printAction(refusal.action)\n }\n // 2 = \"it worked, but a local step remains\"; 1 = it failed.\n exitWhenFlushed(refusal?.actionRequired ? 2 : 1)\n }\n // OUTSIDE the try on purpose: a test that mocks process.exit to throw\n // would otherwise have the success path land in the catch above and be\n // re-rendered as a failure.\n if (succeeded) exitWhenFlushed(0)\n },\n }) as CommandDef\n}\n","/**\n * deepspace auth login\n *\n * Opens the browser to sign in with GitHub or Google.\n * CLI polls the auth worker until login is complete.\n *\n * deepspace auth login # browser-based OAuth\n * deepspace auth login --email x --password y # non-interactive (discouraged: argv leaks)\n * echo \"$PW\" | deepspace auth login --email x --password-stdin # password via stdin\n * DEEPSPACE_EMAIL=x DEEPSPACE_PASSWORD=y deepspace auth login # via env\n *\n * `--json` (from the command runtime, lib/command.ts) matters more here than\n * anywhere else: login is the FIRST command an agent runs, and until now it\n * had no machine surface at all. Two rules keep it usable:\n *\n * 1. `--json` is an explicit machine signal, so it also means \"non-\n * interactive\" for credential resolution — $DEEPSPACE_EMAIL/$DEEPSPACE_\n * PASSWORD are consulted even from a pty. (The guard against ambient\n * DEEPSPACE_* hijacking a HUMAN `deepspace auth login` is untouched: a\n * human doesn't pass --json.)\n * 2. The browser flow polls for up to TEN MINUTES. Entering it from a\n * machine caller with nowhere to click is a silent hang, so `--json`\n * without credentials and without a TTY refuses immediately\n * (`interactive_required`) instead.\n */\n\nimport { credentialPaths } from '../auth'\nimport { writeFileSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\nimport { randomBytes, createHash } from 'node:crypto'\nimport * as p from '@clack/prompts'\n\nimport { createSpinner } from '../lib/spinner'\nimport { DASHBOARD_URL, PLATFORM_URLS } from '../env'\nimport { exchangeSession, SESSION_COOKIE } from '../session'\nimport { decodeJwtPayload } from '../jwt'\nimport { openBrowser } from '../lib/open-browser'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'login',\n description: 'Log in to your DeepSpace account',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email address (non-interactive mode; or $DEEPSPACE_EMAIL)',\n required: false,\n },\n password: {\n type: 'string',\n description: 'Password (discouraged — visible in ps/history; prefer --password-stdin or $DEEPSPACE_PASSWORD)',\n required: false,\n },\n 'password-stdin': {\n type: 'boolean',\n description: 'Read the password from stdin instead of --password',\n default: false,\n },\n },\n async run({ args }) {\n const json = args.json\n // Non-interactive mode for CI/agents. Password from --password-stdin\n // (safest), $DEEPSPACE_PASSWORD, or --password (discouraged — visible in\n // `ps`/shell history); email from --email or $DEEPSPACE_EMAIL. The env vars\n // are consulted ONLY when stdin is non-interactive (or --json was asked\n // for), so ambient DEEPSPACE_* in a dev shell can't hijack an interactive\n // `deepspace auth login` into a password login as a different identity.\n const interactive = Boolean(process.stdin.isTTY) && !json\n const { email, password } = resolveLoginCredentials({\n emailArg: args.email as string | undefined,\n passwordArg: args.password as string | undefined,\n envEmail: interactive ? undefined : process.env.DEEPSPACE_EMAIL,\n envPassword: interactive ? undefined : process.env.DEEPSPACE_PASSWORD,\n passwordStdin: args['password-stdin'] ? readPasswordFromStdin() : undefined,\n })\n const passwordIntent =\n Boolean(args['password-stdin']) || args.password !== undefined || password !== undefined\n\n const decision = loginModeDecision({ email, password, passwordIntent })\n if (decision.mode === 'error') {\n throw new Refusal(decision.message, decision.code)\n }\n if (decision.mode === 'password') {\n if (!json) console.log(`Signing in as ${email}...`)\n const who = await doEmailLogin(email as string, password as string)\n if (!json) {\n console.log(`Logged in as ${who.email} (${who.userId})`)\n console.log(`Dashboard: ${DASHBOARD_URL}`)\n }\n return { data: { email: who.email, userId: who.userId } }\n }\n // decision.mode === 'oauth' → fall through to the browser flow below.\n\n // The browser flow polls for up to ten minutes. --json is the machine\n // signal on its own — a caller running under a pty (stdout IS a TTY) would\n // otherwise fall through and hang for ten minutes. Refuse for ANY --json\n // caller, or any non-TTY, with the flags that actually work.\n if (json || !process.stdout.isTTY) {\n throw new Refusal(\n 'Browser login needs an interactive terminal. Use --email with --password-stdin (or $DEEPSPACE_EMAIL/$DEEPSPACE_PASSWORD).',\n 'interactive_required',\n )\n }\n\n // Browser-based OAuth flow\n if (!json) p.intro('DeepSpace Login')\n\n const s = createSpinner()\n if (!json) s.start('Creating login session...')\n\n // PKCE: generate a random verifier and send only its SHA-256 hash to the\n // server. The verifier never leaves this process, so the loginUrl alone\n // can't be used to drain credentials at /status — only this CLI can.\n const codeVerifier = base64url(randomBytes(32))\n const codeChallenge = base64url(createHash('sha256').update(codeVerifier).digest())\n\n // 1. Create a CLI session\n const sessionRes = await fetch(`${AUTH_URL}/api/auth/cli/session`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code_challenge: codeChallenge }),\n })\n // The runtime stops any live spinner before it renders a refusal, so these\n // throws don't need to unwind the spinner themselves.\n if (!sessionRes.ok) {\n throw new Refusal(\n `Could not create login session (${sessionRes.status})`,\n 'login_session_failed',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n const sessionData = (await sessionRes.json()) as {\n sessionId?: string\n loginUrl?: string\n }\n if (!sessionData.sessionId || !sessionData.loginUrl) {\n throw new Refusal(\n 'Could not create login session — the auth server returned no session id or login url.',\n 'login_session_failed',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n\n const { sessionId, loginUrl } = sessionData as {\n sessionId: string\n loginUrl: string\n }\n\n if (!json) {\n s.stop('Opening browser...')\n p.log.info(`If the browser doesn't open, visit:\\n ${loginUrl}`)\n }\n\n // 2. Open browser\n openBrowser(loginUrl)\n\n // 3. Poll for completion\n if (!json) s.start('Waiting for authentication...')\n const result = await pollForCompletion(sessionId, codeVerifier)\n\n if (!result) {\n throw new Refusal('Login timed out. Run `deepspace auth login` to try again.', 'login_timeout', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n // 4. Store credentials + provision the billing profile (see provisionProfile)\n storeCredentials(result.sessionToken, result.jwt)\n await provisionProfile(result.jwt)\n\n // Report the same identity fields the password path does, so an agent\n // never has to follow login with `whoami` to learn who it became.\n let userId = '(unknown)'\n try {\n userId = decodeJwtPayload<{ sub?: string }>(result.jwt).sub ?? userId\n } catch {\n // A malformed JWT is the session's problem, not login's — keep going.\n }\n\n if (!json) {\n s.stop('Authenticated')\n p.log.success(`Logged in as ${result.name ?? result.email}`)\n p.note(\n `Manage your account, deployed apps, billing, and subscription\\nplans on the web dashboard:\\n\\n ${DASHBOARD_URL}`,\n 'Dashboard',\n )\n p.outro('Done')\n }\n return { data: { email: result.email, userId } }\n },\n})\n\n/**\n * Resolve non-interactive login credentials with a clear precedence (ONB-4):\n * email = --email > $DEEPSPACE_EMAIL; password = --password-stdin (when the flag\n * is set, its already-read value wins) > --password > $DEEPSPACE_PASSWORD.\n * Pure for testing.\n */\nexport function resolveLoginCredentials(opts: {\n emailArg?: string\n passwordArg?: string\n envEmail?: string\n envPassword?: string\n passwordStdin?: string\n}): { email?: string; password?: string } {\n const email = opts.emailArg || opts.envEmail || undefined\n const password =\n opts.passwordStdin !== undefined\n ? opts.passwordStdin\n : opts.passwordArg || opts.envPassword || undefined\n return { email, password }\n}\n\n/**\n * Decide how `login` should proceed given the resolved credentials (ONB-4).\n * `passwordIntent` is true when the user asked for a password login (a\n * credential flag/stdin or a resolved password). Crucially, a supplied-but-\n * incomplete credential set (missing email, or an EMPTY password — e.g. an\n * empty `--password-stdin` in CI) becomes an `error`, not a silent fall-through\n * to the browser OAuth flow (which would hang ~10 min in a headless pipeline).\n * `code` is the machine slug the refusal carries. Pure for testing.\n */\nexport function loginModeDecision(opts: {\n email?: string\n password?: string\n passwordIntent: boolean\n}): { mode: 'password' } | { mode: 'oauth' } | { mode: 'error'; message: string; code: string } {\n if (opts.email && opts.password) return { mode: 'password' }\n if (!opts.passwordIntent) return { mode: 'oauth' }\n if (!opts.email) {\n return {\n mode: 'error',\n code: 'missing_email',\n message: 'Non-interactive login needs an email: --email <you@example.com> (or $DEEPSPACE_EMAIL).',\n }\n }\n return {\n mode: 'error',\n code: 'missing_password',\n message:\n 'Non-interactive login needs a non-empty password: --password-stdin, $DEEPSPACE_PASSWORD, or --password.',\n }\n}\n\n/**\n * Read a password piped on stdin (one trailing newline stripped). Refuses on a\n * TTY, where reading stdin would block forever waiting for EOF.\n */\nfunction readPasswordFromStdin(): string {\n if (process.stdin.isTTY) {\n throw new Refusal(\n '--password-stdin expects the password piped on stdin, e.g. `printf %s \"$PW\" | deepspace auth login --email you@x.com --password-stdin`.',\n 'password_stdin_needs_pipe',\n )\n }\n return readFileSync(0, 'utf-8').replace(/\\r?\\n$/, '')\n}\n\ninterface LoginResult {\n sessionToken: string\n jwt: string\n email: string\n name: string | null\n}\n\nasync function pollForCompletion(\n sessionId: string,\n codeVerifier: string,\n): Promise<LoginResult | null> {\n const maxAttempts = 120 // 10 minutes at 5s intervals\n const interval = 5000\n\n for (let i = 0; i < maxAttempts; i++) {\n await sleep(interval)\n\n try {\n const res = await fetch(`${AUTH_URL}/api/auth/cli/status/${sessionId}`, {\n headers: { 'x-code-verifier': codeVerifier },\n })\n\n if (res.status === 410 || res.status === 404) return null // expired / not found\n if (!res.ok) continue\n\n const data = (await res.json()) as {\n state?: string\n sessionToken?: string\n jwt?: string\n email?: string\n name?: string\n }\n\n if (data.state === 'complete' && data.sessionToken && data.jwt) {\n return {\n sessionToken: data.sessionToken,\n jwt: data.jwt,\n email: data.email ?? '',\n name: data.name ?? null,\n }\n }\n } catch {\n // Network error, keep polling\n }\n }\n\n return null\n}\n\nfunction storeCredentials(sessionToken: string, jwt: string) {\n const dir = join(homedir(), '.deepspace')\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n // Per-plane paths: a staging login must not overwrite the production\n // session (that clobber surfaced as a bogus \"Session expired\" on the next\n // prod command).\n const { sessionPath, tokenPath } = credentialPaths(AUTH_URL)\n writeFileSync(sessionPath, sessionToken, { mode: 0o600 })\n writeFileSync(tokenPath, jwt, { mode: 0o600 })\n}\n\n/**\n * Provision the user's billing profile so they can be referenced by email\n * immediately after logging in — e.g. added as a collaborator on someone\n * else's app. The api-worker's auth middleware upserts the `userProfiles`\n * row on any authenticated call, but login/whoami only ever touch the auth\n * worker, so a fresh CLI-only account otherwise has no profile and\n * `collaborators add <their-email>` 404s until their first deploy. One GET\n * to /api/users/me creates it. Best-effort: the same upsert happens on any\n * later api-worker call, so a transient failure here must not fail login.\n */\nasync function provisionProfile(jwt: string): Promise<void> {\n try {\n await fetch(`${API_URL}/api/users/me`, { headers: { Authorization: `Bearer ${jwt}` } })\n } catch {\n // non-fatal — the profile is upserted on the next api-worker request\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction base64url(bytes: Buffer): string {\n return bytes.toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n// ── Email/password login (for test accounts and CI) ────────────────\n\nasync function doEmailLogin(\n email: string,\n password: string,\n): Promise<{ email: string; userId: string }> {\n const res = await fetch(`${AUTH_URL}/api/auth/sign-in/email`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Origin: AUTH_URL },\n body: JSON.stringify({ email, password }),\n redirect: 'manual',\n })\n\n if (!res.ok) {\n const body = (await res.json().catch(() => ({}))) as { message?: string }\n throw new Error(body.message ?? `Authentication failed (${res.status})`)\n }\n\n const setCookie = res.headers.get('set-cookie') ?? ''\n const cookieMatch = setCookie.match(new RegExp(`${SESSION_COOKIE}=([^;]+)`))\n if (!cookieMatch) {\n throw new Error('No session cookie returned')\n }\n const sessionToken = decodeURIComponent(cookieMatch[1])\n\n const jwt = await exchangeSession(AUTH_URL, sessionToken)\n if (!jwt) {\n throw new Error('JWT issuance failed')\n }\n\n storeCredentials(sessionToken, jwt)\n await provisionProfile(jwt)\n // The user id is the fact `whoami --json` reports as `userId`; surface it at\n // login too so an agent never has to re-run whoami to learn who it became.\n let userId = '(unknown)'\n try {\n userId = decodeJwtPayload<{ sub?: string }>(jwt).sub ?? userId\n } catch {\n // A malformed JWT is the session's problem, not login's — keep going.\n }\n return { email, userId }\n}\n","/**\n * Best-effort \"open this URL in the default browser\".\n *\n * Non-blocking and never throws: every caller has already printed the URL, so\n * a failure to launch the browser is harmless — the user opens it manually.\n * `JSON.stringify` quotes the URL so query strings / special chars can't break\n * out of the shell command.\n */\nimport { exec } from 'node:child_process'\n\nexport function openBrowser(url: string): void {\n const quoted = JSON.stringify(url)\n const cmd =\n process.platform === 'darwin'\n ? `open ${quoted}`\n : process.platform === 'win32'\n ? `start \"\" ${quoted}`\n : `xdg-open ${quoted}`\n\n // Swallow errors — the URL was already shown, so launching is optional.\n exec(cmd, () => {})\n}\n","/**\n * deepspace auth logout\n *\n * Revokes the session on the auth worker, then removes the cached session\n * token and JWT from ~/.deepspace/. Test accounts (managed by `deepspace\n * test-accounts`) are not touched.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope\n * and the exit code come from there. Logging out is TERMINAL — there is no\n * follow-up worth naming, so this command emits no `next` (the contract\n * forbids filler).\n */\n\nimport { existsSync, readFileSync, rmSync } from 'node:fs'\n\nimport { PLATFORM_URLS } from '../env'\nimport { SESSION_COOKIE } from '../session'\nimport { credentialPaths } from '../auth'\nimport { defineDeepspaceCommand } from '../lib/command'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth\n\n// Per-plane paths from the shared helper — logging out of staging must not\n// delete the production session (and vice versa).\nconst { sessionPath: SESSION_PATH, tokenPath: TOKEN_PATH } = credentialPaths(AUTH_URL)\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'logout',\n description: 'Sign out and remove cached credentials',\n },\n async run({ args }) {\n // Read the session token before deleting it so we can revoke server-side.\n const sessionToken = existsSync(SESSION_PATH)\n ? readFileSync(SESSION_PATH, 'utf-8').trim()\n : null\n\n if (sessionToken) {\n try {\n await fetch(`${AUTH_URL}/api/auth/sign-out`, {\n method: 'POST',\n headers: {\n Cookie: `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}`,\n Origin: AUTH_URL,\n },\n })\n } catch {\n // Network failure — still wipe local credentials so the user can\n // re-authenticate. Server-side session will expire on its own.\n }\n }\n\n let removed = 0\n for (const path of [SESSION_PATH, TOKEN_PATH]) {\n if (existsSync(path)) {\n rmSync(path)\n removed++\n }\n }\n\n // Already-logged-out is a SUCCESS, not a refusal: the requested end state\n // (no cached credentials) holds either way, so an agent retrying logout\n // must not read exit 1.\n if (!args.json) console.log(removed === 0 ? 'Already logged out.' : 'Logged out.')\n return { data: { loggedOut: true, removed, alreadyLoggedOut: removed === 0 } }\n },\n})\n","/**\n * App identity (docs/proposals/app-identity-registry.md).\n *\n * Every app carries an immutable id in wrangler.toml:\n *\n * [vars]\n * DEEPSPACE_APP_ID = \"app_01JG8QK…\" # minted at scaffold/init\n *\n * [env.staging.vars]\n * DEEPSPACE_APP_ID = \"app_01JG8QM…\" # each env is its own app\n *\n * The wrangler `name` field is just the subdomain label the next deploy\n * claims; identity is the id. Minting is local (a ULID — 80 random bits\n * need no server round-trip to be unique); registration happens at first\n * deploy.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport { InputError } from './cli-errors'\n\n// Single source: the shared registry client owns the id shape. Import-then-\n// re-export (not a bare `export from`) because line ~151 uses it locally too.\nimport { APP_ID_RE } from '../../server/utils/registry-client'\nexport { APP_ID_RE }\n\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\n/** A 26-char ULID (48-bit ms timestamp + 80 random bits, Crockford base32) —\n * the id shape shared by app ids (`app_…`) and workspace ids (`ws_…`). */\nexport function mintUlid(now = Date.now()): string {\n let ts = ''\n let t = now\n for (let i = 0; i < 10; i++) {\n ts = CROCKFORD[t % 32] + ts\n t = Math.floor(t / 32)\n }\n const rand = new Uint8Array(10)\n crypto.getRandomValues(rand)\n let rs = ''\n let acc = 0\n let bits = 0\n for (const byte of rand) {\n acc = (acc << 8) | byte\n bits += 8\n while (bits >= 5) {\n bits -= 5\n rs += CROCKFORD[(acc >> bits) & 31]\n }\n }\n return `${ts}${rs}`.slice(0, 26)\n}\n\n/** Mint a fresh app id: `app_` + 26-char ULID. */\nexport function mintAppId(now = Date.now()): string {\n return `app_${mintUlid(now)}`\n}\n\n/** Outcome of looking for an app already registered at this name. */\nexport type ExistingAppResolution =\n /** A registered app the caller can deploy — reuse its id. `owned` is false\n * when access comes from the on-behalf matrix (collaborator/admin) rather\n * than ownership; callers must confirm before deploying those. */\n | { kind: 'adopted'; appId: string; owned: boolean }\n /** A registered app the caller CANNOT deploy — abort before minting. */\n | { kind: 'taken' }\n /** Nothing registered here → mint a fresh id. */\n | { kind: 'none' }\n\n/**\n * Resolve the app already registered at this subdomain, if any. A repo with no\n * `DEEPSPACE_APP_ID` must NOT blindly mint a fresh id: an app the platform\n * already registered — e.g. one backfilled during the app-identity cutover —\n * owns its route, so a fresh id would collide (\"name … is taken by another\n * app\"). Two probes:\n *\n * 1. The caller's own apps (`/api/apps`), matched by subdomain — the owner\n * redeploying a legacy repo.\n * 2. The name itself as a legacy id: backfilled apps use their name as their\n * appId, so a gated per-app read (`/api/apps/:appId/analytics`, the same\n * owner / collaborator / admin matrix deploy grants) answers in one call\n * whether the app exists and whether the caller may deploy it. 200 → adopt\n * (deploy runs on-behalf when the caller isn't the owner); 403 → the name\n * belongs to an app the caller can't deploy, so minting would only defer\n * the failure to a confusing route-claim collision — report `taken` so\n * deploy can fail with the real reason; 404 → nothing there.\n *\n * Best-effort otherwise: network errors and unexpected responses resolve to\n * `none` so the deploy still proceeds and mints, exactly as before.\n */\nexport async function resolveExistingAppId(\n deployUrl: string,\n token: string,\n appName: string,\n): Promise<ExistingAppResolution> {\n const headers = { Authorization: `Bearer ${token}` }\n\n try {\n const res = await fetch(`${deployUrl}/api/apps`, { headers })\n if (res.ok) {\n const body = (await res.json()) as {\n apps?: Array<{ appId?: string; name?: string | null }>\n }\n const match = body.apps?.find((a) => a.name === appName)\n if (match?.appId) return { kind: 'adopted', appId: match.appId, owned: true }\n }\n } catch {\n // fall through to the legacy-id probe\n }\n\n try {\n const res = await fetch(\n `${deployUrl}/api/apps/${encodeURIComponent(appName)}/analytics?period=1h`,\n { headers },\n )\n // Not in the owned list but the gated read authorizes → on-behalf access\n // (collaborator or admin). NOT ownership: for an admin this is true of\n // EVERY registered app, so the caller must confirm before deploying.\n if (res.ok) return { kind: 'adopted', appId: appName, owned: false }\n if (res.status === 403) return { kind: 'taken' }\n } catch {\n // best-effort: fall through\n }\n\n return { kind: 'none' }\n}\n\ninterface WranglerVars {\n vars?: Record<string, unknown>\n env?: Record<string, { vars?: Record<string, unknown> }>\n}\n\n/** Read DEEPSPACE_APP_ID for the given wrangler env (top-level when omitted).\n * Env blocks do NOT inherit the top-level id — each env is its own app. */\nexport function readAppId(cwd: string = process.cwd(), wranglerEnv?: string): string | null {\n const wranglerPath = join(resolve(cwd), 'wrangler.toml')\n if (!existsSync(wranglerPath)) return null\n let cfg: WranglerVars\n try {\n cfg = parseToml(readFileSync(wranglerPath, 'utf-8')) as WranglerVars\n } catch (err) {\n // A corrupt wrangler.toml must NOT read as \"no id yet\" — callers would\n // tell the user to run `deepspace app init` (a lie) or mint a SECOND id\n // into the broken file. Surface the real problem.\n throw new InputError(\n `Could not parse ${wranglerPath}: ${err instanceof Error ? err.message : String(err)}`,\n 'invalid_config',\n )\n }\n const vars = wranglerEnv ? cfg.env?.[wranglerEnv]?.vars : cfg.vars\n const id = vars?.DEEPSPACE_APP_ID\n return typeof id === 'string' && APP_ID_RE.test(id) ? id : null\n}\n\n/**\n * Write DEEPSPACE_APP_ID into wrangler.toml, text-preserving: appended to the\n * existing `[vars]` / `[env.<name>.vars]` block, or the block is created.\n * Refuses to overwrite an existing id unless `force` — identity is immutable;\n * a new id means a new app (`deepspace app init --new-id`).\n */\nexport function writeAppId(\n cwd: string,\n appId: string,\n opts: { wranglerEnv?: string; force?: boolean } = {},\n): void {\n const wranglerPath = join(resolve(cwd), 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n throw new Error(`No wrangler.toml in ${resolve(cwd)}`)\n }\n const existing = readAppId(cwd, opts.wranglerEnv)\n if (existing && !opts.force) {\n if (existing === appId) return\n throw new Error(\n `wrangler.toml already carries ${existing}. The app id is immutable — use --new-id only to fork this repo as a separate app.`,\n )\n }\n\n let src = readFileSync(wranglerPath, 'utf-8')\n const header = opts.wranglerEnv ? `[env.${opts.wranglerEnv}.vars]` : '[vars]'\n const line = `DEEPSPACE_APP_ID = \"${appId}\"`\n const headerRe = new RegExp(`^\\\\${header.replace(/\\./g, '\\\\.')}[ \\\\t]*$`, 'm')\n const idLineRe = /^DEEPSPACE_APP_ID\\s*=.*$/m\n\n const match = headerRe.exec(src)\n if (match) {\n // Insert (or replace) inside the existing block: from the header to the\n // next section header or EOF.\n const blockStart = match.index + match[0].length\n const rest = src.slice(blockStart)\n const nextSection = rest.search(/^\\s*\\[/m)\n const blockEnd = nextSection === -1 ? src.length : blockStart + nextSection\n const block = src.slice(blockStart, blockEnd)\n const newBlock = idLineRe.test(block)\n ? block.replace(idLineRe, line)\n : `\\n${line}${block}`\n src = src.slice(0, blockStart) + newBlock + src.slice(blockEnd)\n } else {\n src = src.trimEnd() + `\\n\\n${header}\\n${line}\\n`\n }\n writeFileSync(wranglerPath, src)\n}\n","/**\n * The ONE registry client. Every platform worker reaches the app-registry\n * Durable Object (hosted by the deploy worker, singleton `v1:global`) through\n * a cross-script REGISTRY binding — and before this module, each of the five\n * workers hand-rolled its own copy of the same mechanics: the instance name\n * appeared in 6 places, the `https://registry/` URL in 6, `APP_ID_RE` in 5,\n * and `RegistryClientError` + `registryErrorJson` existed byte-identical in\n * two workers. Copies that must agree and nothing enforcing it.\n *\n * This module owns the MECHANICS: instance name, stub lookup, the wire call,\n * the error type, and the standard route mapping. Each worker still declares\n * its own typed convenience wrapper listing only the actions it uses — that\n * subset is genuinely per-worker; the plumbing is not.\n */\n\n/** The singleton registry instance — one DO holds every app/route/collaborator. */\nexport const REGISTRY_INSTANCE = 'v1:global'\n\n/** App id shape: a ULID-minted `app_…` id, or a legacy name-as-id. */\nexport const APP_ID_RE = /^(app_[0-9A-HJKMNP-TV-Z]{26}|[a-z0-9][a-z0-9_-]{0,63})$/\n\n/** ONLY a ULID-minted id — surfaces that must not accept a legacy name. */\nexport const STRICT_APP_ID_RE = /^app_[0-9A-HJKMNP-TV-Z]{26}$/\n\nexport class RegistryClientError extends Error {\n constructor(\n message: string,\n readonly code: string,\n readonly status: number,\n ) {\n super(message)\n this.name = 'RegistryClientError'\n }\n}\n\nexport function registryStub(ns: DurableObjectNamespace): DurableObjectStub {\n return ns.get(ns.idFromName(REGISTRY_INSTANCE))\n}\n\n/**\n * One registry action over the wire. Non-2xx answers throw\n * {@link RegistryClientError} carrying the DO's structured `code` (or\n * `'error'` for a transport-shaped body) — callers distinguish a registry-\n * REPORTED miss (`code === 'not_found'`) from an outage by that code, never\n * by treating every throw as \"not found\".\n */\nexport async function callRegistry<T>(\n stub: DurableObjectStub,\n body: { action: string } & Record<string, unknown>,\n): Promise<T> {\n const res = await stub.fetch('https://registry/', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n })\n const json = (await res.json().catch(() => ({}))) as { error?: string; code?: string }\n if (!res.ok) {\n throw new RegistryClientError(\n json.error ?? `Registry error (${res.status})`,\n json.code ?? 'error',\n res.status,\n )\n }\n return json as T\n}\n\n/** Standard mapping of a registry failure onto a route response. */\nexport function registryErrorJson(\n c: { json: (body: unknown, status?: number) => Response },\n err: unknown,\n): Response {\n if (err instanceof RegistryClientError) {\n return c.json({ error: err.message, code: err.code }, err.status as 400)\n }\n throw err\n}\n","/**\n * deepspace dev start [--port N]\n *\n * Starts local development:\n * 1. Ensures you're logged in\n * 2. Writes .dev.vars pointing to the production platform workers\n * 3. Starts vite dev (Cloudflare Vite plugin runs the worker in-process)\n *\n * deepspace dev start # port 5173 (strict)\n * deepspace dev start --port 5180 # bind to a different port (multi-app dev)\n *\n * Port is `--port` > $DEEPSPACE_PORT > a stable linked-worktree port > 5173,\n * so Codex, Claude, and ordinary Git worktrees do not collide with a primary\n * checkout server. We always pass --strictPort to vite so a busy port\n * fails loudly instead of silently jumping to 5174 (which would diverge from\n * anything Playwright/test config is expecting).\n *\n * Defined with the command runtime (lib/command.ts) so every PREFLIGHT failure\n * (no app dir, logged out, port busy, secrets refresh) carries a slug and a\n * `--json` envelope. The server itself is long-running: the body awaits vite's\n * exit and the envelope lands after it, since there is no earlier moment that\n * means \"done\". Vite's own output streams through inherited stdio and is never\n * buffered or suppressed — under `--json` the envelope is the LAST line, not\n * the only one.\n */\n\nimport { readAppId } from '../lib/app-identity'\nimport { resolve, basename, join } from 'node:path'\nimport spawn from 'cross-spawn'\nimport { ensureToken } from '../auth'\nimport { detectAppName, findAppDir, findChildApps } from '../lib/app-context'\nimport {\n detectClaudeWorktree,\n detectLinkedWorktree,\n deriveWorktreePort,\n upsertWorktreeLaunchConfig,\n writeLaunchConfigIfMissing,\n} from '../lib/launch-config'\nimport { PLATFORM_URLS } from '../env'\nimport { writeDevVars } from '../lib/dev-vars'\nimport { decodeJwtPayload } from '../jwt'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { preflightNodeVersion, preflightWindowsWorkerd } from '../lib/preflight'\nimport { removeMacosJunk } from '../lib/macos-junk'\nimport { refreshSecretsCache } from '../lib/secrets'\nimport { lintProjectSchemas, formatSchemaLintFindings } from '../lib/schema-lint'\nimport { DEFAULT_PORT, resolvePort, checkPortAvailable } from '../lib/port'\nimport {\n prepareWranglerEnvConfig,\n wranglerViteEnv,\n type PreparedWranglerEnvConfig,\n} from '../lib/wrangler-env'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\n/**\n * The \"no wrangler.toml here\" refusal, shared verbatim by `dev` and `test`.\n * Multi-line on purpose: the sibling-app suggestions are the whole point of\n * the message, and the runtime appends the slug to its last line.\n */\nexport function noAppDirMessage(start: string, children: string[]): string {\n const lines = [`No wrangler.toml found at or above ${start}.`]\n if (children.length > 0) {\n lines.push('Did you mean to run inside one of these app directories?')\n for (const c of children) lines.push(` cd ${c}`)\n } else {\n lines.push('Run from a DeepSpace app directory (one containing wrangler.toml).')\n }\n return lines.join('\\n')\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'dev',\n description: 'Start local development server',\n },\n args: {\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description:\n 'wrangler.toml [env.<name>] block to run (e.g. --env staging). ' +\n \"Applies the env's overrides at build time.\",\n required: false,\n },\n port: {\n type: 'string',\n description: `Port to bind (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n },\n async run({ args }) {\n const say = (line: string) => {\n if (!args.json) console.log(line)\n }\n preflightNodeVersion('dev start')\n const wranglerEnv =\n typeof args.env === 'string' && args.env.trim() ? args.env.trim() : undefined\n\n // Resolve the app root by walking up from the requested dir (default cwd),\n // so running from a subdirectory still works instead of hard-failing.\n const start = resolve((args.dir as string | undefined) ?? '.')\n const appDir = findAppDir(start)\n if (!appDir) {\n throw new Refusal(noAppDirMessage(start, findChildApps(start)), 'no_app_dir')\n }\n\n const junk = removeMacosJunk(appDir)\n if (junk > 0) say(`Removed ${junk} macOS metadata file(s) (._*, .DS_Store)`)\n\n // Inside a Claude Code worktree the desktop preview tool reads only the\n // MAIN repo's launch.json and would serve the main repo's stale code\n // (anthropics/claude-code#56688) — so upsert a cwd-pinned entry there.\n // Explicit --port and $DEEPSPACE_PORT are honored before any derived\n // worktree default. Otherwise a stable per-worktree port (bumped past\n // other Claude launch entries' ports)\n // avoids colliding with a main-repo server. This run binds the same port\n // the entry advertises, so the preview tool can attach to an\n // already-running worktree server instead of spawning a duplicate.\n const worktree = detectClaudeWorktree(appDir)\n const linkedWorktree = detectLinkedWorktree(appDir)\n const explicitPort = Boolean(args.port)\n const configuredPort = explicitPort || Boolean(process.env.DEEPSPACE_PORT)\n let port =\n linkedWorktree && !configuredPort\n ? deriveWorktreePort(linkedWorktree.worktreeRoot)\n : resolvePort(args.port as string | undefined)\n if (worktree) {\n const upserted = upsertWorktreeLaunchConfig(\n worktree.mainRepoRoot,\n worktree.worktreeName,\n appDir,\n {\n port,\n probePort: !configuredPort,\n extraArgs: [...(wranglerEnv ? ['--env', wranglerEnv] : [])],\n },\n )\n if (upserted) {\n port = upserted.port\n say(\n `Claude worktree detected — preview tool: use preview_start with name \"${upserted.entryName}\" (port ${upserted.port})`,\n )\n } else if (!args.json) {\n console.warn(\n `Warning: could not update ${join(worktree.mainRepoRoot, '.claude', 'launch.json')} ` +\n `(malformed or unwritable) — the Claude preview tool may serve the main repo's code ` +\n `instead of this worktree.`,\n )\n }\n }\n\n // Seed an app-local .claude/launch.json (only if absent) so the Claude Code\n // preview tool launches this app on the resolved port, instead of walking\n // up and latching onto an ancestor repo's config. With an explicit --port,\n // also update the existing entry so `kill` and the preview tool track the\n // port we actually bind (DEV-3).\n writeLaunchConfigIfMissing(appDir, detectAppName(appDir) ?? basename(appDir), port, {\n updatePort: explicitPort,\n })\n\n ensureInstallReady(appDir)\n\n // Surface schema-lint findings in the terminal the developer is watching.\n // The worker also warns at runtime, but only in the DO's console after a\n // client connects — easy to miss, and these are shipping privacy bugs.\n const lintFindings = await lintProjectSchemas(appDir)\n if (lintFindings && lintFindings.length > 0 && !args.json) {\n for (const line of formatSchemaLintFindings(lintFindings)) console.warn(line)\n }\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err: unknown) {\n // Keep ensureToken's canonical wording (\"Not logged in…\" / \"Session\n // expired…\") and add the slug + the command that fixes it.\n throw new Refusal(err instanceof Error ? err.message : String(err), 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n let payload: { sub: string; name?: string; email?: string }\n try {\n payload = decodeJwtPayload<{ sub: string; name?: string; email?: string }>(token)\n } catch {\n throw new Refusal(\n 'Malformed session token. Run `npx deepspace auth login`.',\n 'not_authenticated',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n // `--env` selects which `[env.<name>]` block of wrangler.toml we apply\n // (renames the app, swaps vars, etc.). Surface it in the startup log so\n // it's obvious which app slot a session is hitting when it's set.\n say(`Logged in as ${payload.name ?? payload.email}`)\n if (wranglerEnv) say(`Wrangler env: ${wranglerEnv}`)\n say(`Port: ${port}`)\n\n // Refresh the app-store secrets cache (config = wrangler env, or 'prd').\n // A repo without a DEEPSPACE_APP_ID hasn't been initialized — writeDevVars\n // below throws with the `deepspace app init` pointer, so skip the pull.\n let generatedSecretsCache: string | undefined\n const appIdForSecrets = readAppId(appDir, wranglerEnv)\n if (appIdForSecrets) {\n try {\n const refreshed = await refreshSecretsCache(DEPLOY_URL, token, appIdForSecrets, wranglerEnv)\n if (refreshed) {\n generatedSecretsCache = refreshed.rendered\n say(refreshed.summary)\n }\n } catch (err: unknown) {\n throw new Refusal(\n `Failed to refresh app secrets: ${err instanceof Error ? err.message : String(err)}`,\n 'secrets_refresh_failed',\n )\n }\n }\n\n const sharedDevVarsCache = generatedSecretsCache !== undefined\n await writeDevVars(appDir, payload.sub, token, wranglerEnv, {\n generatedSecretsCache,\n sharedDevVarsCache,\n })\n // prepareWranglerEnvConfig throws typed errors that already carry slugs;\n // let them through untouched rather than flattening them to a message.\n const wranglerConfig: PreparedWranglerEnvConfig = prepareWranglerEnvConfig(\n appDir,\n wranglerEnv,\n { sharedDevVarsCache },\n )\n preflightWindowsWorkerd(appDir)\n\n // Pre-probe the port so a collision gets a friendly remedy instead of\n // vite's raw --strictPort EADDRINUSE stack trace (DEV-5).\n if (!(await checkPortAvailable(port))) {\n const killArgv =\n port === DEFAULT_PORT\n ? ['deepspace', 'dev', 'kill']\n : ['deepspace', 'dev', 'kill', '--port', String(port)]\n const killCmd = killArgv.join(' ')\n wranglerConfig.cleanup()\n throw new Refusal(\n `Port ${port} is already in use.\\n` +\n `Free it with \\`${killCmd}\\`, or start on another port: \\`deepspace dev start --port <other>\\`.`,\n 'port_in_use',\n { extra: { port } },\n )\n }\n\n say('Starting dev server...\\n')\n\n const vite = spawn('npx', ['vite', '--port', String(port), '--strictPort', '--host'], {\n cwd: appDir,\n stdio: 'inherit',\n env: wranglerViteEnv(process.env, wranglerConfig, { DEEPSPACE_PORT: String(port) }),\n })\n const stop = () => {\n wranglerConfig.cleanup()\n vite.kill()\n }\n process.on('SIGINT', stop)\n process.on('SIGTERM', stop)\n\n // `dev` runs until vite exits (Ctrl-C, or a crash). Await that instead of\n // exiting from the close handler: the runtime owns exit codes now, and a\n // body that called process.exit would skip the envelope entirely.\n const code = await new Promise<number | null>((res) => {\n vite.on('close', (c) => {\n wranglerConfig.cleanup()\n res(c)\n })\n })\n // A signal-terminated vite reports code null — that's Ctrl-C, i.e. the\n // normal way this command ends, so it stays a success.\n if (code !== null && code !== 0) {\n throw new Refusal(`Dev server exited with code ${code}.`, 'dev_server_failed', {\n extra: { port, appDir, exitCode: code },\n })\n }\n return { data: { port, appDir, wranglerEnv: wranglerEnv ?? null } }\n },\n})\n","/** Discover the local DeepSpace app surrounding a working directory. */\n\nimport { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport { InputError } from './cli-errors'\n\n/** Read the app name from the local wrangler.toml, when present. */\nexport function detectAppName(cwd: string = process.cwd()): string | null {\n const wranglerPath = join(resolve(cwd), 'wrangler.toml')\n if (!existsSync(wranglerPath)) return null\n try {\n const config = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n return typeof config.name === 'string' && config.name.length > 0 ? config.name : null\n } catch (error) {\n throw new InputError(\n `Could not parse ${wranglerPath}: ${error instanceof Error ? error.message : String(error)}`,\n 'invalid_config',\n )\n }\n}\n\n/** Walk upward to the nearest directory containing wrangler.toml. */\nexport function findAppDir(start: string = process.cwd()): string | null {\n let dir = resolve(start)\n for (;;) {\n if (existsSync(join(dir, 'wrangler.toml'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/** Immediate child directories that contain wrangler.toml. */\nexport function findChildApps(dir: string): string[] {\n try {\n return readdirSync(dir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && existsSync(join(dir, entry.name, 'wrangler.toml')))\n .map((entry) => entry.name)\n .sort()\n } catch {\n return []\n }\n}\n","/** Claude preview launch configuration for local apps and worktrees. */\n\nimport {\n existsSync,\n readFileSync,\n realpathSync,\n writeFileSync,\n mkdirSync,\n renameSync,\n unlinkSync,\n} from 'node:fs'\nimport { join, resolve, dirname, basename, isAbsolute, sep } from 'node:path'\nimport { detectAppName } from './app-context'\nimport { listWorktrees, repoToplevel } from './git/repository'\n\n/**\n * Atomic launch.json write: temp file + rename, so an interrupted write can\n * never leave torn (permanently unparseable) JSON behind.\n */\nfunction writeLaunchFile(launchPath: string, config: unknown): void {\n mkdirSync(dirname(launchPath), { recursive: true })\n const tmpPath = `${launchPath}.${process.pid}.tmp`\n writeFileSync(tmpPath, JSON.stringify(config, null, 2) + '\\n')\n try {\n renameSync(tmpPath, launchPath)\n } catch (err) {\n // Don't leave an orphan tmp file behind (e.g. Windows EPERM while the\n // preview tool holds launch.json open).\n try {\n unlinkSync(tmpPath)\n } catch {\n // best-effort cleanup\n }\n throw err\n }\n}\n\n/**\n * Read + validate a launch.json. Returns the parsed config, an empty skeleton\n * when the file is absent or empty (interrupted write, `touch` — nothing to\n * preserve), or null when it exists but is malformed / wrong-shaped (leave it\n * alone rather than clobber a hand-edited file). Trimmed before parsing so a\n * UTF-8 BOM from Windows editors doesn't read as \"malformed\".\n */\nfunction readLaunchFile(\n launchPath: string,\n): { version?: string; configurations: Array<Record<string, unknown>> } | null {\n const empty = { version: '0.0.1', configurations: [] }\n if (!existsSync(launchPath)) return empty\n const raw = readFileSync(launchPath, 'utf-8').trim()\n if (!raw) return empty\n const parsed = JSON.parse(raw)\n if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.configurations)) return null\n return parsed\n}\n\n/**\n * Seed the app's own entry in `<appDir>/.claude/launch.json` so the Claude\n * Code preview tool launches THIS app. Without an app-local launch.json the\n * tool walks up the directory tree and can latch onto an ancestor repo's\n * config — pointing at a different app and port — which is a real failure\n * when a DeepSpace app lives inside another repo.\n *\n * Entry-level, not file-level: if the file already has an entry named\n * `appName` (possibly user-customized) it is left untouched by default, but a\n * file that exists without it — e.g. created by a worktree run's upsert before\n * the main app ever ran `dev` — still gets the app's entry appended.\n *\n * `opts.updatePort` (DEV-3): when the user passed an explicit `--port`, update\n * the existing entry's `port` and the `--port` value inside its `runtimeArgs`\n * (other args like `--env` are preserved) so `kill` and the preview tool track\n * the port `dev` actually bound. Without it, a scaffold pinned to 5173 would\n * stay stale after `dev --port 5180`. Best-effort: a failure must never block\n * `dev` from starting.\n */\nexport function writeLaunchConfigIfMissing(\n appDir: string,\n appName: string,\n port: number,\n opts: { updatePort?: boolean } = {},\n): void {\n const launchPath = join(appDir, '.claude', 'launch.json')\n try {\n const config = readLaunchFile(launchPath)\n if (!config) return\n const existing = config.configurations.find((c) => c?.name === appName)\n if (existing) {\n if (!opts.updatePort) return\n // Resync BOTH the `port` field and the `--port` value in runtimeArgs — a\n // stale runtimeArgs (even when the port field matches) makes the preview\n // tool launch on the wrong port. Only write when something actually changed.\n let changed = false\n if (Number(existing.port) !== port) {\n existing.port = port\n changed = true\n }\n if (Array.isArray(existing.runtimeArgs)) {\n const ra = existing.runtimeArgs.map(String)\n const pi = ra.indexOf('--port')\n if (pi >= 0 && pi + 1 < ra.length) {\n if (ra[pi + 1] !== String(port)) {\n ra[pi + 1] = String(port)\n changed = true\n }\n } else {\n ra.push('--port', String(port))\n changed = true\n }\n if (changed) existing.runtimeArgs = ra\n }\n if (changed) writeLaunchFile(launchPath, config)\n return\n }\n config.configurations.push({\n name: appName,\n runtimeExecutable: 'npx',\n runtimeArgs: ['deepspace', 'dev', 'start', '--port', String(port)],\n port,\n })\n writeLaunchFile(launchPath, config)\n } catch {\n // best-effort only\n }\n}\n\n/**\n * The port `kill` should target for the app at `appDir` when no `--port` was\n * given and we're not in a worktree (DEV-2): the port recorded in the app's own\n * `.claude/launch.json` entry, which `dev --port` keeps in sync (see above).\n * Falls back to null (caller uses the default) when there's no launch.json,\n * no matching entry, or a malformed file.\n */\nexport function resolveAppLaunchPort(appDir: string): number | null {\n try {\n const config = readLaunchFile(join(appDir, '.claude', 'launch.json'))\n if (!config) return null\n const appName = detectAppName(appDir) ?? basename(appDir)\n const entry =\n config.configurations.find((c) => c?.name === appName) ??\n (config.configurations.length === 1 ? config.configurations[0] : undefined)\n const port = Number(entry?.port)\n return Number.isInteger(port) && port > 0 ? port : null\n } catch {\n return null\n }\n}\n\n/**\n * Detect whether `appDir` lives inside a registered Git worktree created at\n * `<root>/.claude/worktrees/<name>`. Returns the checkout whose `.claude`\n * directory owns that worktree and the worktree name, or null.\n *\n * The Claude desktop preview tool starts dev servers from the session's\n * primary working directory and reads only the MAIN repo's\n * `.claude/launch.json` — a worktree's own launch.json is never read\n * (anthropics/claude-code#56688). Detecting this lets `dev` seed a\n * `cwd`-pinned entry where the tool will actually look. The path shape alone\n * is deliberately insufficient: both the child and inferred owner must be\n * registered checkouts of the same repository. That prevents an ordinary\n * directory merely named `.claude/worktrees/<name>` from changing ports or\n * mutating an unrelated ancestor's launch configuration.\n */\nexport function detectClaudeWorktree(\n appDir: string,\n): { mainRepoRoot: string; worktreeName: string } | null {\n try {\n // Git owns the worktree boundary. `appDir` may be any nested app path, so\n // never infer that boundary from path segments.\n const worktreeRoot = canonicalPath(repoToplevel(appDir))\n const registered = new Set(\n listWorktrees(appDir).map((worktree) => canonicalPath(worktree.path)),\n )\n if (!registered.has(worktreeRoot)) return null\n\n const worktreesDir = dirname(worktreeRoot)\n const claudeDir = dirname(worktreesDir)\n if (basename(worktreesDir) !== 'worktrees' || basename(claudeDir) !== '.claude') return null\n\n // For a nested Claude worktree, the owner may itself be a linked worktree.\n // Requiring it in `git worktree list` keeps the innermost-session behavior\n // without trusting a coincidental directory name.\n const ownerRoot = canonicalPath(dirname(claudeDir))\n if (!registered.has(ownerRoot)) return null\n\n return { mainRepoRoot: ownerRoot, worktreeName: basename(worktreeRoot) }\n } catch {\n // Non-Git directories, stale worktree registrations, and unreadable paths\n // are ordinary \"not a Claude worktree\" states.\n return null\n }\n}\n\nexport interface LinkedWorktree {\n worktreeRoot: string\n mainRepoRoot: string\n}\n\nfunction canonicalPath(path: string): string {\n try {\n return realpathSync(path)\n } catch {\n // One stale unrelated registration must not disable the active checkout.\n return resolve(path)\n }\n}\n\n/** Detect any registered linked Git worktree, independent of agent or layout. */\nexport function detectLinkedWorktree(appDir: string): LinkedWorktree | null {\n try {\n const worktreeRoot = canonicalPath(repoToplevel(appDir))\n const registered = listWorktrees(appDir).map((worktree) => canonicalPath(worktree.path))\n const currentIndex = registered.indexOf(worktreeRoot)\n if (currentIndex <= 0 || !registered[0]) return null\n return { worktreeRoot, mainRepoRoot: registered[0] }\n } catch {\n return null\n }\n}\n\nconst WORKTREE_ENTRY_PREFIX = 'wt-'\nconst WORKTREE_PORT_MIN = 5180\nconst WORKTREE_PORT_RANGE = 1000\n\n/**\n * Deterministic per-worktree preview port in the worktree band\n * (5180–6179), distinct from the default 5173 so a preview server for the\n * worktree never collides with a main-repo dev server. Stable across runs\n * for the same canonical worktree path. Hash collisions between worktrees are\n * resolved at write time by `upsertWorktreeLaunchConfig`, which probes past\n * ports already claimed by other launch.json entries.\n */\nexport function deriveWorktreePort(worktreeKey: string): number {\n let hash = 0\n for (const ch of worktreeKey) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0\n return WORKTREE_PORT_MIN + (hash % WORKTREE_PORT_RANGE)\n}\n\nexport interface WorktreeLaunchOptions {\n /** Desired port for the entry (and for the current dev run). */\n port: number\n /**\n * When true, bump the port past any port already claimed by another\n * launch.json entry (wrapping within 5180–6179). Off for an explicit\n * --port, which is honored verbatim.\n */\n probePort?: boolean\n /** Extra `deepspace dev start` args to preserve in the entry (e.g. --prod, --env). */\n extraArgs?: string[]\n}\n\n/**\n * Upsert a `cwd`-pinned entry named `wt-<worktreeName>` into the MAIN repo's\n * `.claude/launch.json`, so the Claude desktop preview tool (which only reads\n * that file) starts the dev server inside the worktree instead of serving the\n * main repo's stale code. Also prunes `wt-*` entries whose absolute `cwd` no\n * longer exists (deleted worktrees) — relative `cwd`s are left alone, since\n * `existsSync` would resolve them against this process's cwd, not the\n * preview tool's. All other entries are preserved verbatim.\n *\n * Returns the entry name and the (possibly probed) port on success, or null\n * if the file was malformed or unwritable — best-effort: must never block\n * `dev` from starting, but the caller should warn, since a missing entry\n * means the preview tool will serve the main repo's code.\n */\nexport function upsertWorktreeLaunchConfig(\n mainRepoRoot: string,\n worktreeName: string,\n appDir: string,\n opts: WorktreeLaunchOptions,\n): { entryName: string; port: number } | null {\n const launchPath = join(mainRepoRoot, '.claude', 'launch.json')\n const entryName = WORKTREE_ENTRY_PREFIX + worktreeName\n try {\n const config = readLaunchFile(launchPath)\n if (!config) return null\n // Ownership check for pruning: only entries whose cwd lives under this\n // repo's .claude/worktrees/ could have been written by us. A hand-authored\n // wt-* entry pointing elsewhere (or at an unmounted volume) is never ours\n // to delete.\n const worktreesRoot = join(mainRepoRoot, '.claude', 'worktrees') + sep\n config.configurations = config.configurations.filter((c) => {\n if (c?.name === entryName) return false // replaced below\n const isStaleWorktreeEntry =\n typeof c?.name === 'string' &&\n c.name.startsWith(WORKTREE_ENTRY_PREFIX) &&\n typeof c.cwd === 'string' &&\n isAbsolute(c.cwd) &&\n c.cwd.startsWith(worktreesRoot) &&\n !existsSync(c.cwd)\n return !isStaleWorktreeEntry\n })\n\n let port = opts.port\n if (opts.probePort) {\n // Number() coercion so a hand-edited string port (\"5186\") still counts\n // as claimed.\n const taken = new Set(\n config.configurations\n .map((c) => Number(c?.port))\n .filter((p) => Number.isInteger(p) && p > 0),\n )\n for (let i = 0; i < WORKTREE_PORT_RANGE && taken.has(port); i++) {\n port = WORKTREE_PORT_MIN + ((port - WORKTREE_PORT_MIN + 1) % WORKTREE_PORT_RANGE)\n }\n }\n\n config.configurations.push({\n name: entryName,\n runtimeExecutable: 'npx',\n runtimeArgs: ['deepspace', 'dev', 'start', '--port', String(port), ...(opts.extraArgs ?? [])],\n port,\n // `cwd` is honored verbatim by the desktop preview tool (documented in\n // the Claude Code desktop launch.json reference alongside `port`) and\n // verified end-to-end: with it set, the preview server builds from the\n // worktree instead of the session's main repo.\n cwd: resolve(appDir),\n })\n writeLaunchFile(launchPath, config)\n return { entryName, port }\n } catch {\n return null\n }\n}\n\n/**\n * The port dev/test/kill should default to inside any linked Git worktree, so\n * all three commands target the same server (`test` against a different port\n * silently exercises the main repo's code via Playwright's\n * reuseExistingServer). A Claude worktree's `wt-<name>` entry remains the\n * source of truth when present; every other linked worktree derives a stable\n * port from its canonical checkout path. Returns null in the primary checkout.\n */\nexport function resolveWorktreePort(appDir: string): number | null {\n const linked = detectLinkedWorktree(appDir)\n if (!linked) return null\n const claude = detectClaudeWorktree(appDir)\n if (claude) {\n try {\n const config = readLaunchFile(join(claude.mainRepoRoot, '.claude', 'launch.json'))\n const entry = config?.configurations.find(\n (c) => c?.name === WORKTREE_ENTRY_PREFIX + claude.worktreeName,\n )\n const port = Number(entry?.port)\n if (Number.isInteger(port) && port > 0) return port\n } catch {\n // malformed launch.json — fall through to the generic derived port\n }\n }\n return deriveWorktreePort(linked.worktreeRoot)\n}\n","import { appendFileSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { InputError } from '../cli-errors'\nimport { gitLine, gitMeetsFloor, parseGitVersion, runGit, splitNulFields } from './process'\n\n/** Conservative client-side approximation of `git check-ref-format --branch`. */\nexport function isPlausibleBranchName(name: string): boolean {\n if (!name || name === 'HEAD' || name === '@') return false\n if (name.startsWith('/') || name.startsWith('-') || name.startsWith('.')) return false\n if (name.endsWith('/') || name.endsWith('.') || name.endsWith('.lock')) return false\n if (name.includes('/.') || name.includes('.lock/')) return false\n // eslint-disable-next-line no-control-regex\n return !/(\\.\\.|\\/\\/|@\\{|[\\x00-\\x20\\x7f~^:?*[\\\\])/.test(name)\n}\n\n/** Require a full, SHA-1 Git repository supported by the cloud repo protocol. */\nexport function assertSyncableRepo(cwd: string): void {\n const inside = runGit(cwd, ['rev-parse', '--is-inside-work-tree'], { allowFail: true })\n if (inside.status !== 0 || inside.stdout.toString().trim() !== 'true') {\n throw new InputError(\n `${cwd} is not a git repository. DeepSpace apps are scaffolded as git repos — run \\`git init\\` first.`,\n 'not_git_repo',\n )\n }\n\n const versionOutput = runGit(cwd, ['--version'], { allowFail: true })\n .stdout.toString('utf-8')\n .trim()\n if (!gitMeetsFloor(parseGitVersion(versionOutput))) {\n throw gitTooOld(versionOutput)\n }\n\n const formatResult = runGit(cwd, ['rev-parse', '--show-object-format'], { allowFail: true })\n const format = formatResult.stdout.toString('utf-8').trim()\n if (formatResult.status !== 0 || format.startsWith('--')) throw gitTooOld(versionOutput)\n if (format !== 'sha1') {\n throw new InputError(\n `This repo uses object format \"${format}\" — DeepSpace version control supports sha1 repos only (git's default) for now.`,\n 'unsupported_object_format',\n )\n }\n if (gitLine(cwd, ['rev-parse', '--is-shallow-repository']) === 'true') {\n throw new InputError(\n 'This is a shallow clone. Run `git fetch --unshallow` before pushing to DeepSpace.',\n 'shallow_repo',\n )\n }\n}\n\nfunction gitTooOld(versionOutput: string): InputError {\n return new InputError(\n `DeepSpace version control needs git ≥ 2.29 — found ${versionOutput || 'an unknown git version'}. Upgrade git and retry.`,\n 'git_too_old',\n )\n}\n\n/** The repository's top-level worktree directory. */\nexport function repoToplevel(cwd: string): string {\n return gitLine(cwd, ['rev-parse', '--show-toplevel'])\n}\n\n/** Current branch short name, or null when HEAD is detached. */\nexport function currentBranch(cwd: string): string | null {\n const result = runGit(cwd, ['symbolic-ref', '--short', '-q', 'HEAD'], { allowFail: true })\n const name = result.stdout.toString('utf-8').trim()\n return result.status === 0 && name ? name : null\n}\n\n/** Resolve a ref or oid to a commit oid. */\nexport function resolveCommit(cwd: string, ref: string): string | null {\n const result = runGit(cwd, ['rev-parse', '-q', '--verify', `${ref}^{commit}`], {\n allowFail: true,\n })\n const oid = result.stdout.toString('utf-8').trim()\n return result.status === 0 && /^[0-9a-f]{40}$/.test(oid) ? oid : null\n}\n\nexport function isWorkTreeClean(cwd: string): boolean {\n return gitLine(cwd, ['status', '--porcelain']) === ''\n}\n\nexport function updateRef(cwd: string, ref: string, oid: string): void {\n runGit(cwd, ['update-ref', ref, oid])\n}\n\nexport function isAncestor(cwd: string, ancestor: string, descendant: string): boolean {\n return (\n runGit(cwd, ['merge-base', '--is-ancestor', ancestor, descendant], { allowFail: true })\n .status === 0\n )\n}\n\nexport function mergeBase(cwd: string, left: string, right: string): string | null {\n const result = runGit(cwd, ['merge-base', left, right], { allowFail: true })\n if (result.status !== 0) return null\n const oid = result.stdout.toString('utf-8').trim()\n return /^[0-9a-f]{40}$/.test(oid) ? oid : null\n}\n\nexport function fastForwardCurrentBranch(cwd: string, oid: string): void {\n runGit(cwd, ['merge', '--ff-only', oid])\n}\n\nexport function initRepo(dir: string, branch: string): void {\n runGit(dir, ['init', '--quiet', '-b', branch])\n}\n\nexport function checkoutHead(cwd: string): void {\n runGit(cwd, ['reset', '--hard', '--quiet'])\n}\n\nexport function switchToNewBranch(cwd: string, name: string, oid: string): void {\n runGit(cwd, ['switch', '--quiet', '-c', name, oid])\n}\n\n/** Changed paths between commits, with rename detection disabled so both sides remain visible. */\nexport function diffNameOnly(cwd: string, base: string, head: string): string[] {\n return splitNulFields(\n runGit(cwd, [\n '-c',\n 'core.quotePath=false',\n 'diff',\n '--name-only',\n '--no-renames',\n '-z',\n base,\n head,\n ]).stdout,\n )\n}\n\nexport function revListCount(cwd: string, exclude: string, include: string): number {\n const count = Number(gitLine(cwd, ['rev-list', '--count', `${exclude}..${include}`]))\n return Number.isFinite(count) ? count : 0\n}\n\nexport function addWorktreeNewBranch(cwd: string, dir: string, branch: string, oid: string): void {\n runGit(cwd, ['worktree', 'add', '--quiet', '-b', branch, dir, oid])\n}\n\nexport interface GitWorktree {\n path: string\n branch: string | null\n}\n\nexport function listWorktrees(cwd: string): GitWorktree[] {\n const result = runGit(cwd, ['worktree', 'list', '--porcelain'], { allowFail: true })\n if (result.status !== 0) return []\n const worktrees: GitWorktree[] = []\n let current: GitWorktree | null = null\n for (const line of result.stdout.toString('utf-8').split('\\n')) {\n if (line.startsWith('worktree ')) {\n current = { path: line.slice('worktree '.length), branch: null }\n worktrees.push(current)\n } else if (line.startsWith('branch ') && current) {\n const ref = line.slice('branch '.length)\n current.branch = ref.startsWith('refs/heads/') ? ref.slice('refs/heads/'.length) : ref\n }\n }\n return worktrees\n}\n\n/** Add a pattern to the repository's shared, local-only info/exclude file. */\nexport function ensureLocalExclude(cwd: string, pattern: string): void {\n const commonDir = resolve(cwd, gitLine(cwd, ['rev-parse', '--git-common-dir']))\n const excludePath = join(commonDir, 'info', 'exclude')\n let current = ''\n try {\n current = readFileSync(excludePath, 'utf-8')\n } catch {\n // The append below creates an absent file.\n }\n if (current.split('\\n').some((line) => line.trim() === pattern)) return\n try {\n mkdirSync(dirname(excludePath), { recursive: true })\n appendFileSync(\n excludePath,\n `${current.endsWith('\\n') || current === '' ? '' : '\\n'}${pattern}\\n`,\n )\n } catch {\n // Best-effort: a failed exclude makes status noisy but does not break the worktree.\n }\n}\n","import { sync as spawnSync } from 'cross-spawn'\n\nconst MAX_GIT_BUFFER = 512 * 1024 * 1024\n\nexport class GitError extends Error {\n constructor(\n message: string,\n /** Optional machine slug; generic Git errors fall back to `git_error`. */\n readonly code?: string,\n ) {\n super(message)\n this.name = 'GitError'\n }\n}\n\n/** Execute git without terminal prompts, localized output, or shell interpolation. */\nexport function runGit(\n cwd: string,\n args: string[],\n opts: { input?: string | Buffer; allowFail?: boolean; env?: Record<string, string> } = {},\n): { stdout: Buffer; stderr: Buffer; status: number } {\n const result = spawnSync('git', args, {\n cwd,\n input: opts.input,\n maxBuffer: MAX_GIT_BUFFER,\n stdio: ['pipe', 'pipe', 'pipe'],\n env: {\n ...process.env,\n GIT_TERMINAL_PROMPT: '0',\n LC_ALL: 'C',\n ...(opts.env ?? {}),\n },\n })\n if (result.error) {\n const code = (result.error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new GitError(\n 'git is not installed or not on PATH — install git and retry.',\n 'git_not_installed',\n )\n }\n throw new GitError(`git ${args[0]} failed: ${result.error.message}`)\n }\n const status = result.status ?? 1\n if (status !== 0 && !opts.allowFail) {\n const stderr = result.stderr?.toString('utf-8').trim() ?? ''\n throw new GitError(`git ${args.join(' ')} exited ${status}${stderr ? `: ${stderr}` : ''}`)\n }\n return {\n stdout: result.stdout ?? Buffer.alloc(0),\n stderr: result.stderr ?? Buffer.alloc(0),\n status,\n }\n}\n\nexport function gitLine(cwd: string, args: string[]): string {\n return runGit(cwd, args).stdout.toString('utf-8').trim()\n}\n\n/** Decode a NUL-delimited git result without corrupting control characters in paths. */\nexport function splitNulFields(buffer: Buffer): string[] {\n const fields: string[] = []\n let start = 0\n for (let index = 0; index < buffer.length; index++) {\n if (buffer[index] === 0) {\n fields.push(buffer.toString('utf-8', start, index))\n start = index + 1\n }\n }\n if (start < buffer.length) fields.push(buffer.toString('utf-8', start))\n return fields\n}\n\n/** Parse `git --version` into the major/minor pair used by the compatibility floor. */\nexport function parseGitVersion(output: string): [number, number] | null {\n const match = /(\\d+)\\.(\\d+)/.exec(output)\n return match ? [Number(match[1]), Number(match[2])] : null\n}\n\n/** Git 2.29 is the minimum version that exposes the required object-format probe. */\nexport function gitMeetsFloor(version: [number, number] | null): boolean {\n if (!version) return true\n const [major, minor] = version\n return major > 2 || (major === 2 && minor >= 29)\n}\n","/** Local `.dev.vars` parsing, preservation, and SDK-managed writes. */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { PLATFORM_URLS } from '../env'\nimport { readAppId } from './app-identity'\nimport { fetchAppIdentityToken, fetchPublicKey, mintAppOwnerJwt } from './app-tokens'\nimport { stripGeneratedSecretsCache } from './secrets'\nimport { writeSecretFileSync } from './secure-file'\nimport { devVarsPathFor } from './wrangler-env'\n\n/** Keys rewritten from platform truth on every dev, test, and deploy run. */\nconst SDK_MANAGED_KEYS = new Set([\n 'AUTH_JWT_PUBLIC_KEY',\n 'AUTH_JWT_ISSUER',\n 'AUTH_WORKER_URL',\n 'API_WORKER_URL',\n 'PLATFORM_WORKER_URL',\n 'OWNER_USER_ID',\n 'APP_OWNER_JWT',\n 'APP_IDENTITY_TOKEN',\n 'ALLOW_DEBUG_ROUTES',\n])\n\nexport const DEV_VARS_DIVIDER = '# --- not managed by the SDK; preserved across dev/test runs ---'\n\ninterface WriteDevVarsOptions {\n appId?: string\n /** Rendered remote secrets cache, which replaces legacy preserved values. */\n generatedSecretsCache?: string\n /** Linked configs share `.dev.vars`; unlinked apps use `.dev.vars.<env>`. */\n sharedDevVarsCache?: boolean\n}\n\n/**\n * Strip SDK-managed lines above the divider while preserving all other content\n * verbatim, including comments and multi-line quoted values.\n */\nexport function extractCustomDevVars(content: string): string {\n const lines = content.split('\\n')\n const out: string[] = []\n let belowDivider = false\n let i = 0\n while (i < lines.length) {\n const line = lines[i]\n if (line.trim() === DEV_VARS_DIVIDER.trim()) {\n belowDivider = true\n i++\n continue\n }\n const eq = line.indexOf('=')\n const keyMatch = eq >= 0 ? line.slice(0, eq).match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*$/) : null\n if (!keyMatch) {\n out.push(line)\n i++\n continue\n }\n const key = keyMatch[1]\n const valueStart = line.slice(eq + 1)\n const block: string[] = [line]\n if (valueStart.startsWith('\"') && !hasUnescapedQuote(valueStart.slice(1))) {\n i++\n while (i < lines.length) {\n block.push(lines[i])\n const closed = hasUnescapedQuote(lines[i])\n i++\n if (closed) break\n }\n } else {\n i++\n }\n if (belowDivider || !SDK_MANAGED_KEYS.has(key)) out.push(...block)\n }\n while (out.length && out[out.length - 1].trim() === '') out.pop()\n return out.join('\\n')\n}\n\nfunction hasUnescapedQuote(value: string): boolean {\n let escaped = false\n for (const char of value) {\n if (escaped) {\n escaped = false\n continue\n }\n if (char === '\\\\') {\n escaped = true\n continue\n }\n if (char === '\"') return true\n }\n return false\n}\n\n/** Parse values used by deploy safety checks from a dotenv-formatted string. */\nexport function parseDevVars(content: string): Record<string, string> {\n const result: Record<string, string> = {}\n const lines = content.split('\\n')\n let i = 0\n while (i < lines.length) {\n const line = lines[i]\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith('#')) {\n i++\n continue\n }\n const eq = line.indexOf('=')\n if (eq < 0) {\n i++\n continue\n }\n const keyMatch = line.slice(0, eq).match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*$/)\n if (!keyMatch) {\n i++\n continue\n }\n const key = keyMatch[1]\n let value = line.slice(eq + 1)\n\n let closed = !value.startsWith('\"') || hasUnescapedQuote(value.slice(1))\n if (!closed) {\n i++\n while (i < lines.length) {\n value += '\\n' + lines[i]\n if (hasUnescapedQuote(lines[i])) {\n closed = true\n i++\n break\n }\n i++\n }\n } else {\n i++\n }\n\n if (value.startsWith('\"') && !closed) {\n throw new Error(\n `parseDevVars: unterminated quoted value for key \"${key}\" — check your .dev.vars file for a missing closing quote.`,\n )\n }\n if (value.startsWith('\"') && value.endsWith('\"') && value.length >= 2) {\n value = unescapeQuotedDevVar(value.slice(1, -1))\n }\n result[key] = value\n }\n return result\n}\n\nfunction unescapeQuotedDevVar(value: string): string {\n let out = ''\n for (let i = 0; i < value.length; i++) {\n const char = value[i]\n if (char !== '\\\\' || i === value.length - 1) {\n out += char\n continue\n }\n const next = value[i + 1]\n if (next === '\\\\' || next === '\"') {\n out += next\n i++\n continue\n }\n out += char\n }\n return out\n}\n\nfunction requireAppIdFor(appDir: string, wranglerEnv?: string): string {\n const id = readAppId(appDir, wranglerEnv)\n if (id) return id\n throw new Error(\n 'wrangler.toml has no DEEPSPACE_APP_ID' +\n (wranglerEnv ? ` for [env.${wranglerEnv}]` : '') +\n '. Run `deepspace app init` (or `deepspace app init --env <name>`) and retry.',\n )\n}\n\n/** Rewrite the SDK section and preserve user-owned values below it. */\nexport async function writeDevVars(\n appDir: string,\n ownerId: string,\n callerJwt: string,\n wranglerEnv?: string,\n opts: WriteDevVarsOptions = {},\n): Promise<void> {\n const urls = PLATFORM_URLS\n const publicKey = await fetchPublicKey(urls.auth)\n const appId = opts.appId ?? requireAppIdFor(appDir, wranglerEnv)\n const appOwnerJwt = await mintAppOwnerJwt(urls.auth, callerJwt, appId)\n const appIdentityToken = await fetchAppIdentityToken(urls.deploy, callerJwt, appId)\n\n // Wrangler requires quotes around multi-line PEM values.\n const sdkVars = [\n `AUTH_JWT_PUBLIC_KEY=\"${publicKey}\"`,\n `AUTH_JWT_ISSUER=${urls.auth}/api/auth`,\n `AUTH_WORKER_URL=${urls.auth}`,\n `API_WORKER_URL=${urls.api}`,\n `PLATFORM_WORKER_URL=${urls.platform}`,\n `OWNER_USER_ID=${ownerId}`,\n `APP_OWNER_JWT=${appOwnerJwt}`,\n ...(appIdentityToken ? [`APP_IDENTITY_TOKEN=${appIdentityToken}`] : []),\n `ALLOW_DEBUG_ROUTES=true`,\n ].join('\\n')\n\n const useSharedDevVarsCache = opts.sharedDevVarsCache ?? opts.generatedSecretsCache !== undefined\n const devVarsPath = devVarsPathFor(appDir, wranglerEnv, {\n sharedDevVarsCache: useSharedDevVarsCache,\n })\n const existing = existsSync(devVarsPath) ? readFileSync(devVarsPath, 'utf-8') : ''\n const custom =\n opts.generatedSecretsCache ??\n extractCustomDevVars(stripGeneratedSecretsCache(existing).trimEnd())\n let body: string\n if (!custom) {\n body = `${sdkVars}\\n`\n } else if (opts.generatedSecretsCache) {\n body = `${sdkVars}\\n\\n${custom}\\n`\n } else {\n body = `${sdkVars}\\n\\n${DEV_VARS_DIVIDER}\\n${custom}\\n`\n }\n\n writeSecretFileSync(devVarsPath, body)\n}\n","/** Platform calls that obtain app-scoped credentials for local execution. */\n\n/** Fetch the JWT public key from an auth worker's JWKS endpoint. */\nexport async function fetchPublicKey(authUrl: string): Promise<string> {\n const response = await fetch(`${authUrl}/api/auth/jwks`)\n if (!response.ok) {\n throw new Error(`Failed to fetch JWT public key (${response.status})`)\n }\n const body = (await response.json()) as { publicKey?: string }\n if (!body.publicKey) throw new Error('JWKS response missing publicKey')\n return body.publicKey\n}\n\n/** Mint a long-lived owner token bound to the app's immutable id. */\nexport async function mintAppOwnerJwt(\n authUrl: string,\n callerJwt: string,\n appId: string,\n): Promise<string> {\n const response = await fetch(`${authUrl}/api/auth/mint-app-token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${callerJwt}`,\n },\n body: JSON.stringify({ appId }),\n })\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n throw new Error(`Failed to mint APP_OWNER_JWT (${response.status}): ${detail}`)\n }\n const body = (await response.json()) as { token?: string; error?: string }\n if (!body.token) {\n throw new Error(`Auth worker returned no token: ${body.error ?? 'unknown error'}`)\n }\n return body.token\n}\n\n/**\n * Fetch the app-origin identity token. A missing app is expected before its\n * first deployment and therefore returns null.\n */\nexport async function fetchAppIdentityToken(\n deployUrl: string,\n callerJwt: string,\n appId: string,\n): Promise<string | null> {\n const response = await fetch(\n `${deployUrl}/api/apps/${encodeURIComponent(appId)}/identity-token`,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${callerJwt}` },\n },\n )\n if (response.status === 404) return null\n if (!response.ok) {\n const detail = await response.text().catch(() => '')\n throw new Error(`Failed to fetch APP_IDENTITY_TOKEN (${response.status}): ${detail}`)\n }\n const body = (await response.json()) as { token?: string; error?: string }\n if (!body.token) {\n throw new Error(`Deploy worker returned no token: ${body.error ?? 'unknown error'}`)\n }\n return body.token\n}\n","/**\n * Binding Manifest — non-DO bindings declared by an app's wrangler.toml that\n * the deploy-worker should pass through to Cloudflare's WfP upload API.\n *\n * Apps don't export a `__BINDING_MANIFEST__`; the CLI extracts these from the\n * normalized vite/wrangler output config at deploy time. This file just owns\n * the types + validation so both sides (CLI client and deploy-worker server)\n * agree on the shape.\n */\n/// <reference types=\"@cloudflare/workers-types\" />\n\n/**\n * A single non-DO binding the app declares. Mirrors CF's WfP binding API.\n *\n * Provisionable resources (d1, kv_namespace, vectorize, r2_bucket, queue) accept\n * the literal string `\"auto\"` in their ID field to request platform-side\n * provisioning at deploy time. When `\"auto\"` is used, the deploy-worker creates\n * the resource on the platform CF account, persists the resulting CF ID in the\n * app registry, and substitutes the real ID before forwarding to WfP. The\n * sentinel sticks around in this type because:\n * 1. `wrangler` parsing requires a non-empty string in the id field\n * 2. The CLI passes the unresolved manifest through to the deploy-worker\n * 3. The deploy-worker is the only side with CF API credentials\n *\n * Companion fields (`database_name`, `title`, `dimensions`, `metric`) are only\n * used when `\"auto\"` is set — they tell the provisioner how to create the\n * resource. After provisioning these fields are still present on the wire but\n * ignored by WfP.\n */\nexport type CustomBinding =\n | {\n type: 'vectorize'\n name: string\n /** Either a pre-existing index name or the literal `\"auto\"`. */\n index_name: string\n /** Required when `index_name === \"auto\"`. */\n dimensions?: number\n /** Required when `index_name === \"auto\"`. */\n metric?: 'cosine' | 'euclidean' | 'dot-product'\n }\n | { type: 'ai'; name: string }\n | {\n type: 'r2_bucket'\n name: string\n /** Either a pre-existing bucket name or the literal `\"auto\"`. */\n bucket_name: string\n }\n | {\n type: 'kv_namespace'\n name: string\n /** Either a pre-existing KV namespace ID or the literal `\"auto\"`. */\n namespace_id: string\n /** Required when `namespace_id === \"auto\"`. Human-readable namespace title. */\n title?: string\n }\n | {\n type: 'd1'\n name: string\n /** Either a pre-existing D1 database UUID or the literal `\"auto\"`. */\n id: string\n /** Required when `id === \"auto\"`. Human-readable database name. */\n database_name?: string\n }\n | {\n type: 'queue'\n name: string\n /** Either a pre-existing queue name or the literal `\"auto\"`. */\n queue_name: string\n }\n | { type: 'browser_rendering'; name: string }\n | { type: 'analytics_engine'; name: string; dataset?: string }\n | { type: 'hyperdrive'; name: string; id: string }\n\nexport type CustomBindingManifest = CustomBinding[]\n\n/** Sentinel string in an ID field that requests platform-side provisioning. */\nexport const AUTO_PROVISION_SENTINEL = 'auto'\n\n/** Binding types whose ID field accepts the `\"auto\"` sentinel for provisioning. */\nexport const AUTO_PROVISIONABLE_TYPES = new Set([\n 'd1',\n 'kv_namespace',\n 'vectorize',\n 'r2_bucket',\n 'queue',\n])\n\n/** Vectorize metric values accepted by CF when creating an index. */\nconst VECTORIZE_METRICS = new Set(['cosine', 'euclidean', 'dot-product'])\n\n/**\n * True if a binding has the `\"auto\"` sentinel in its primary ID field. Used by\n * the deploy-worker to decide which entries need provisioning and by the\n * validator to enforce companion-field requirements.\n */\nexport function isAutoProvision(b: CustomBinding): boolean {\n switch (b.type) {\n case 'd1':\n return b.id === AUTO_PROVISION_SENTINEL\n case 'kv_namespace':\n return b.namespace_id === AUTO_PROVISION_SENTINEL\n case 'vectorize':\n return b.index_name === AUTO_PROVISION_SENTINEL\n case 'r2_bucket':\n return b.bucket_name === AUTO_PROVISION_SENTINEL\n case 'queue':\n return b.queue_name === AUTO_PROVISION_SENTINEL\n default:\n return false\n }\n}\n\n/** Binding `type` values an app is allowed to declare. */\nexport const ALLOWED_BINDING_TYPES = new Set([\n 'vectorize',\n 'ai',\n 'r2_bucket',\n 'kv_namespace',\n 'd1',\n 'queue',\n 'browser_rendering',\n 'analytics_engine',\n 'hyperdrive',\n])\n\n/**\n * Binding NAMES the SDK reserves on every app — apps may not redeclare them.\n *\n * Includes:\n * - Static-asset + service bindings the platform sets up automatically.\n * - SDK-managed env (auth, identity, owner JWT).\n * - The auto-attached cost-tracking AE dataset (`USAGE_EVENTS`).\n *\n * DO binding names (RECORD_ROOMS, YJS_ROOMS, etc.) are NOT in this set\n * because they live in a separate manifest (`__DO_MANIFEST__`).\n */\nexport const RESERVED_BINDING_NAMES = new Set([\n 'ASSETS',\n 'PLATFORM_WORKER',\n 'API_WORKER',\n 'APP_NAME',\n 'OWNER_USER_ID',\n 'AUTH_JWT_PUBLIC_KEY',\n 'AUTH_JWT_ISSUER',\n 'AUTH_WORKER_URL',\n 'APP_IDENTITY_TOKEN',\n 'APP_OWNER_JWT',\n 'USAGE_EVENTS',\n])\n\n/**\n * Per-binding validation error. `binding` is undefined for top-level\n * shape failures (e.g. manifest is not an array).\n */\nexport interface ValidationError {\n binding?: CustomBinding\n reason: string\n}\n\n/**\n * Validate a binding manifest. Returns errors; an empty array means valid.\n *\n * Used both client-side (CLI) for friendly fail-fast and server-side\n * (deploy-worker) as a security boundary — apps can't sneak in reserved\n * binding names by editing the wire format.\n */\nexport function validateBindingManifest(\n manifest: unknown,\n): { valid: true; bindings: CustomBindingManifest } | { valid: false; errors: ValidationError[] } {\n if (!Array.isArray(manifest)) {\n return { valid: false, errors: [{ reason: 'Manifest must be an array' }] }\n }\n const errors: ValidationError[] = []\n const seenNames = new Set<string>()\n for (const entry of manifest) {\n if (!entry || typeof entry !== 'object') {\n errors.push({ reason: `Entry must be an object (got ${entry === null ? 'null' : typeof entry})` })\n continue\n }\n const e = entry as Record<string, unknown>\n const type = e.type\n const name = e.name\n if (typeof type !== 'string' || !ALLOWED_BINDING_TYPES.has(type)) {\n errors.push({\n reason: `Disallowed binding type: ${typeof type === 'string' ? type : `(${typeof type})`}. Allowed: ${[...ALLOWED_BINDING_TYPES].sort().join(', ')}`,\n })\n continue\n }\n if (typeof name !== 'string' || !name) {\n errors.push({ reason: `Binding of type \"${type}\" missing 'name' (string)` })\n continue\n }\n if (RESERVED_BINDING_NAMES.has(name)) {\n errors.push({ reason: `Binding name \"${name}\" is reserved by the SDK` })\n continue\n }\n if (seenNames.has(name)) {\n errors.push({ reason: `Duplicate binding name \"${name}\"` })\n continue\n }\n seenNames.add(name)\n // Now safely typed: type is in ALLOWED_BINDING_TYPES + name is a string.\n const binding = entry as CustomBinding\n const fieldErr = requiredFieldError(binding)\n if (fieldErr) errors.push({ binding, reason: fieldErr })\n }\n if (errors.length) return { valid: false, errors }\n return { valid: true, bindings: manifest as CustomBindingManifest }\n}\n\nfunction requiredFieldError(b: CustomBinding): string | null {\n switch (b.type) {\n case 'vectorize': {\n if (!b.index_name) return `vectorize binding \"${b.name}\" missing index_name (or \"auto\")`\n if (b.index_name === AUTO_PROVISION_SENTINEL) {\n // Auto-provisioning needs the index shape upfront — CF requires both\n // dimensions and metric at index-create time.\n if (typeof b.dimensions !== 'number' || b.dimensions <= 0) {\n return `vectorize binding \"${b.name}\" with index_name=\"auto\" requires \"dimensions\" (positive number)`\n }\n if (!b.metric || !VECTORIZE_METRICS.has(b.metric)) {\n return `vectorize binding \"${b.name}\" with index_name=\"auto\" requires \"metric\" (one of: ${[...VECTORIZE_METRICS].join(', ')})`\n }\n }\n return null\n }\n case 'r2_bucket':\n return b.bucket_name ? null : `r2_bucket binding \"${b.name}\" missing bucket_name (or \"auto\")`\n case 'kv_namespace': {\n if (!b.namespace_id) return `kv_namespace binding \"${b.name}\" missing namespace_id (or \"auto\")`\n if (b.namespace_id === AUTO_PROVISION_SENTINEL && !b.title) {\n return `kv_namespace binding \"${b.name}\" with namespace_id=\"auto\" requires \"title\"`\n }\n return null\n }\n case 'd1': {\n if (!b.id) return `d1 binding \"${b.name}\" missing id (or \"auto\")`\n if (b.id === AUTO_PROVISION_SENTINEL && !b.database_name) {\n return `d1 binding \"${b.name}\" with id=\"auto\" requires \"database_name\"`\n }\n return null\n }\n case 'queue':\n return b.queue_name ? null : `queue binding \"${b.name}\" missing queue_name (or \"auto\")`\n case 'hyperdrive':\n // Hyperdrive auto-provisioning is out of scope for v1 (needs upstream\n // connection-string management). Only pre-existing IDs accepted.\n if (!b.id) return `hyperdrive binding \"${b.name}\" missing id`\n if (b.id === AUTO_PROVISION_SENTINEL) {\n return `hyperdrive binding \"${b.name}\": auto-provisioning not yet supported (provide a real id)`\n }\n return null\n case 'ai':\n case 'browser_rendering':\n case 'analytics_engine':\n return null // no required fields beyond `name`\n default: {\n // Exhaustiveness guard — adding a new variant without a case fails here.\n const _exhaustive: never = b\n void _exhaustive\n return null\n }\n }\n}\n\n/**\n * Convert vite/wrangler's normalized config (from `.wrangler/deploy/config.json`)\n * into a CustomBindingManifest.\n *\n * Vite normalizes wrangler.toml into object/array structures with shapes like\n * `{ ai: { binding: 'AI' } }`, `{ vectorize: [{ binding, index_name }] }`,\n * etc. We extract each known shape with explicit field plucks (no broad\n * `as` casts) and return a flat array.\n */\nexport function bindingManifestFromOutputConfig(\n outputConfig: Record<string, unknown>,\n): CustomBindingManifest {\n const out: CustomBindingManifest = []\n\n // ai: single object\n const aiBinding = pluckString(outputConfig.ai, 'binding')\n if (aiBinding) out.push({ type: 'ai', name: aiBinding })\n\n // vectorize: array of { binding, index_name, dimensions?, metric? }\n // `dimensions` and `metric` are only required when index_name === \"auto\"\n // (auto-provisioning); the validator enforces that, so we just pluck both\n // here and let it decide.\n for (const v of asObjectArray(outputConfig.vectorize)) {\n const name = pluckString(v, 'binding')\n const index_name = pluckString(v, 'index_name')\n if (!name || !index_name) continue\n const dimensions = pluckNumber(v, 'dimensions')\n const metric = pluckString(v, 'metric')\n out.push({\n type: 'vectorize',\n name,\n index_name,\n ...(dimensions != null && { dimensions }),\n ...(metric && (metric === 'cosine' || metric === 'euclidean' || metric === 'dot-product') && { metric }),\n })\n }\n\n // r2_buckets: array of { binding, bucket_name }\n for (const r of asObjectArray(outputConfig.r2_buckets)) {\n const name = pluckString(r, 'binding')\n const bucket_name = pluckString(r, 'bucket_name')\n if (name && bucket_name) out.push({ type: 'r2_bucket', name, bucket_name })\n }\n\n // kv_namespaces: array of { binding, id, title? }\n // `title` is only required when id === \"auto\"; pluck both here and let\n // the validator enforce the dependency.\n for (const k of asObjectArray(outputConfig.kv_namespaces)) {\n const name = pluckString(k, 'binding')\n const namespace_id = pluckString(k, 'id')\n if (!name || !namespace_id) continue\n const title = pluckString(k, 'title')\n out.push({\n type: 'kv_namespace',\n name,\n namespace_id,\n ...(title && { title }),\n })\n }\n\n // d1_databases: array of { binding, database_id, database_name? }\n // `database_name` is only required when database_id === \"auto\"; pluck both\n // and let the validator enforce.\n for (const d of asObjectArray(outputConfig.d1_databases)) {\n const name = pluckString(d, 'binding')\n const id = pluckString(d, 'database_id')\n if (!name || !id) continue\n const database_name = pluckString(d, 'database_name')\n out.push({\n type: 'd1',\n name,\n id,\n ...(database_name && { database_name }),\n })\n }\n\n // queues.producers: array of { binding, queue }\n const queues = isObject(outputConfig.queues) ? outputConfig.queues : null\n for (const q of asObjectArray(queues?.producers)) {\n const name = pluckString(q, 'binding')\n const queue_name = pluckString(q, 'queue')\n if (name && queue_name) out.push({ type: 'queue', name, queue_name })\n }\n\n // browser: { binding } (Cloudflare names this `browser` not `browser_rendering`)\n const browserBinding = pluckString(outputConfig.browser, 'binding')\n if (browserBinding) out.push({ type: 'browser_rendering', name: browserBinding })\n\n // analytics_engine_datasets: array of { binding, dataset? }\n for (const a of asObjectArray(outputConfig.analytics_engine_datasets)) {\n const name = pluckString(a, 'binding')\n const dataset = pluckString(a, 'dataset')\n if (name) out.push({ type: 'analytics_engine', name, dataset: dataset ?? undefined })\n }\n\n // hyperdrive: array of { binding, id }\n for (const h of asObjectArray(outputConfig.hyperdrive)) {\n const name = pluckString(h, 'binding')\n const id = pluckString(h, 'id')\n if (name && id) out.push({ type: 'hyperdrive', name, id })\n }\n\n return out\n}\n\n// ---- internal helpers (no broad `as` casts) ----\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\nfunction pluckString(v: unknown, key: string): string | null {\n if (!isObject(v)) return null\n const val = v[key]\n return typeof val === 'string' && val.length > 0 ? val : null\n}\n\nfunction pluckNumber(v: unknown, key: string): number | null {\n if (!isObject(v)) return null\n const val = v[key]\n return typeof val === 'number' && Number.isFinite(val) ? val : null\n}\n\nfunction asObjectArray(v: unknown): Record<string, unknown>[] {\n if (!Array.isArray(v)) return []\n return v.filter(isObject)\n}\n","/**\n * App secrets — client helpers for the app-anchored store\n * (docs/proposals/app-identity-registry.md §4.3).\n *\n * Every app has exactly one store, addressed by its immutable id:\n * `/api/secrets/:appId/configs/:config/...` on the deploy worker. Configs\n * follow the wrangler-env convention: the top-level config is `prd`, an\n * `--env staging` deploy ships the `staging` config. There are no per-user\n * projects and no app↔project links — those concepts are gone.\n */\n\nimport { RESERVED_BINDING_NAMES } from '../../server/rooms/binding-manifest'\nimport { ApiError } from './api'\n\nexport const GENERATED_SECRETS_DIVIDER =\n '# --- DeepSpace secrets cache: generated by `npx deepspace secrets`; do not edit manually ---'\n\n/**\n * Names a user may not set as an app secret. `RESERVED_BINDING_NAMES` covers\n * runtime bindings the platform injects; `API_WORKER_URL`/`PLATFORM_WORKER_URL`\n * are SDK-managed env that isn't a binding (so absent from that set) but is\n * still platform-owned. `ALLOW_DEBUG_ROUTES` is deliberately NOT here — it's a\n * normal, user-settable flag. Rejecting these client-side gives a clear message\n * instead of a raw server `(400)` that leaks the API path.\n */\nconst RESERVED_SECRET_NAMES = new Set([\n ...RESERVED_BINDING_NAMES,\n 'API_WORKER_URL',\n 'PLATFORM_WORKER_URL',\n])\n\nexport const SECRET_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/\nexport const CONFIG_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/\nconst MAX_SECRET_VALUE_BYTES = 32 * 1024\n\nexport interface SecretListItem {\n key: string\n version: number\n updatedAt: string\n updatedBy: string\n}\n\nexport interface SecretsConfigInfo {\n name: string\n createdAt: string\n updatedAt: string\n secretCount?: number\n}\n\nexport interface PulledSecretsCache {\n appId: string\n configName: string\n values: Record<string, string>\n}\n\nexport type SecretsDownloadFormat = 'dotenv' | 'json' | 'shell'\n\nexport function validateConfigName(configName: string): string {\n if (!CONFIG_NAME_RE.test(configName)) {\n throw new Error(\n `Invalid config \"${configName}\". Use letters, numbers, underscores, or hyphens; start with a letter or number.`,\n )\n }\n return configName\n}\n\nexport function validateSecretName(name: string): string {\n if (!SECRET_NAME_RE.test(name)) {\n throw new Error(\n `Invalid secret name \"${name}\". Use letters, numbers, and underscores; start with a letter or underscore.`,\n )\n }\n if (RESERVED_SECRET_NAMES.has(name)) {\n throw new Error(\n `\"${name}\" is managed by the DeepSpace SDK and can't be set as an app secret — ` +\n 'the platform injects it at deploy time.',\n )\n }\n return name\n}\n\nexport function validateSecretValue(key: string, value: string): void {\n if (new TextEncoder().encode(value).byteLength > MAX_SECRET_VALUE_BYTES) {\n throw new Error(`Secret \"${key}\" exceeds ${MAX_SECRET_VALUE_BYTES} bytes`)\n }\n}\n\n/** Config convention: top-level deploys/dev use `prd`; a wrangler env uses\n * its own name. */\nexport function defaultConfigNameForEnv(wranglerEnv?: string): string {\n return wranglerEnv ?? 'prd'\n}\n\n// ── HTTP plumbing ────────────────────────────────────────────────────────────\n\nexport async function secretsApi<T>(\n deployUrl: string,\n token: string,\n path: string,\n init: RequestInit = {},\n): Promise<T> {\n const res = await fetch(`${deployUrl}/api/secrets${path}`, {\n ...init,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n ...(init.headers ?? {}),\n },\n })\n const body = (await res.json().catch(() => ({}))) as T & { error?: string }\n if (!res.ok) {\n // Surface the server's sentence, not the internal `/api/secrets/app_…/…`\n // slug — that path is an implementation detail and reads like a bug to\n // users. `status` carries the code for programmatic branches; set DEBUG=1\n // (via cli-errors) for the full error. `apiPath` is kept for debugging.\n const err = new Error(body.error ?? `Secrets request failed (${res.status})`) as Error & {\n status?: number\n apiPath?: string\n }\n err.status = res.status\n err.apiPath = path\n throw err\n }\n return body\n}\n\nexport function listSecrets(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n): Promise<{ secrets: SecretListItem[] }> {\n return secretsApi(deployUrl, token, `/${appId}/configs/${encodeURIComponent(configName)}`)\n}\n\nexport function fetchSecretsValues(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n): Promise<{ secrets: Record<string, string> }> {\n return secretsApi(deployUrl, token, `/${appId}/configs/${encodeURIComponent(configName)}/values`)\n}\n\nexport function getSecretPlain(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n key: string,\n): Promise<{ key: string; value: string }> {\n return secretsApi(\n deployUrl,\n token,\n `/${appId}/configs/${encodeURIComponent(configName)}/secrets/${encodeURIComponent(key)}?plain=true`,\n )\n}\n\nexport function setSecret(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n key: string,\n value: string,\n): Promise<{ ok: boolean }> {\n return secretsApi(\n deployUrl,\n token,\n `/${appId}/configs/${encodeURIComponent(configName)}/secrets/${encodeURIComponent(key)}`,\n { method: 'PUT', body: JSON.stringify({ value }) },\n )\n}\n\nexport function deleteSecret(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n key: string,\n): Promise<{ ok: boolean }> {\n return secretsApi(\n deployUrl,\n token,\n `/${appId}/configs/${encodeURIComponent(configName)}/secrets/${encodeURIComponent(key)}`,\n { method: 'DELETE' },\n )\n}\n\nexport function uploadSecrets(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n secrets: Record<string, string>,\n replace: boolean,\n): Promise<{ ok: boolean }> {\n return secretsApi(\n deployUrl,\n token,\n `/${appId}/configs/${encodeURIComponent(configName)}/secrets`,\n { method: 'PUT', body: JSON.stringify({ secrets, replace }) },\n )\n}\n\nexport function listConfigs(\n deployUrl: string,\n token: string,\n appId: string,\n): Promise<{ configs: SecretsConfigInfo[] }> {\n return secretsApi(deployUrl, token, `/${appId}/configs`)\n}\n\nexport function createConfig(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n copyFrom?: string,\n): Promise<{ ok: boolean }> {\n return secretsApi(deployUrl, token, `/${appId}/configs`, {\n method: 'POST',\n body: JSON.stringify({ name: configName, ...(copyFrom ? { copyFrom } : {}) }),\n })\n}\n\nexport function deleteConfig(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n): Promise<{ ok: boolean }> {\n return secretsApi(deployUrl, token, `/${appId}/configs/${encodeURIComponent(configName)}`, {\n method: 'DELETE',\n })\n}\n\n/**\n * Pull the app's config values for dev/test/deploy caches. Missing store or\n * config is NOT an error — a fresh app simply has no secrets yet.\n */\nexport async function pullAppSecretsCache(\n deployUrl: string,\n token: string,\n appId: string,\n configName: string,\n): Promise<PulledSecretsCache | null> {\n try {\n const { secrets } = await fetchSecretsValues(deployUrl, token, appId, configName)\n // A wrong/broken service can answer 200 without the documented `secrets`\n // object (or with null); left unchecked `Object.keys(values)` downstream throws\n // a raw, uncoded `Cannot convert undefined or null to object` on the deploy\n // path. Code it invalid_response — the same slug the repo-API guard uses — so\n // the refresh fails closed with a real message instead of a leaked TypeError.\n if (secrets === null || typeof secrets !== 'object' || Array.isArray(secrets)) {\n throw new ApiError(\n `The secrets service at ${deployUrl} returned an unexpected response shape — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n 200,\n 'invalid_response',\n `/${appId}/configs/${configName}/values`,\n )\n }\n return { appId, configName, values: secrets }\n } catch (err) {\n // 404: no store yet, or no such config. Both mean \"nothing to ship\". Match\n // on the status field, not the message (which no longer carries the code).\n if ((err as { status?: number })?.status === 404) return null\n throw err\n }\n}\n\n// ── Cache rendering / parsing ────────────────────────────────────────────────\n\nexport function quoteDotenvValue(value: string): string {\n if (/^[A-Za-z0-9_./:@+-]*$/.test(value) && value !== '') return value\n // Newlines must be escaped or the value's tail parses as extra env vars;\n // dotenv expands \\n / \\r inside double-quoted values.\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n return `\"${escaped}\"`\n}\n\n/** Render pulled values as the generated `.dev.vars` cache section. */\nexport function renderSecretsCache(\n secrets: Record<string, string>,\n source: { appId: string; configName: string },\n): string {\n const keys = Object.keys(secrets).sort()\n const lines = [\n GENERATED_SECRETS_DIVIDER,\n `# app ${source.appId} · config ${source.configName}`,\n '# Use `npx deepspace secrets` to change these values.',\n ]\n for (const key of keys) {\n validateSecretValue(key, secrets[key])\n lines.push(`${key}=${quoteDotenvValue(secrets[key])}`)\n }\n return lines.join('\\n')\n}\n\n/** Strip a previously generated cache section from a `.dev.vars` body. */\nexport function stripGeneratedSecretsCache(content: string): string {\n const idx = content.indexOf(GENERATED_SECRETS_DIVIDER)\n if (idx === -1) return content\n return content.slice(0, idx).trimEnd() + '\\n'\n}\n\n// ── Upload/download formats (Doppler-compatible) ─────────────────────────────\n\nexport function parseSecretsUpload(content: string): Record<string, string> {\n const trimmed = content.trim()\n if (!trimmed) return {}\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n const parsed = JSON.parse(trimmed) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('JSON upload must be an object of KEY=value strings.')\n }\n const out: Record<string, string> = {}\n for (const [key, value] of Object.entries(parsed)) {\n validateSecretName(key)\n if (typeof value !== 'string') throw new Error(`Secret \"${key}\" must be a string`)\n validateSecretValue(key, value)\n out[key] = value\n }\n return out\n }\n // dotenv — supports multiline quoted values (dotenv ≥15 semantics): a value\n // whose opening quote isn't closed on its own line continues, verbatim,\n // until a line ending with the closing quote. Without this, uploading a\n // .env holding a real PEM silently stored one byte and minted phantom keys\n // from the base64 continuation lines.\n const out: Record<string, string> = {}\n const lines = trimmed.split(/\\r?\\n/)\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim()\n if (!line || line.startsWith('#')) continue\n const eq = line.indexOf('=')\n if (eq <= 0) continue // junk line — tolerated, like comments\n const key = line.slice(0, eq).trim()\n if (!SECRET_NAME_RE.test(key)) continue\n validateSecretName(key) // reject reserved/SDK-managed names with a clear message, same as `set`\n const raw = line.slice(eq + 1).trim()\n const quote = raw[0] === '\"' || raw[0] === \"'\" ? raw[0] : null\n let value: string\n if (!quote) {\n value = raw\n } else if (endsWithUnescapedQuote(raw.slice(1), quote)) {\n const inner = raw.slice(1, -1)\n value = quote === '\"' ? unescapeDotenv(inner) : inner\n } else {\n // Multiline: consume raw (untrimmed) lines until one closes the quote.\n const startLine = i + 1\n const parts = [raw.slice(1)]\n let closed = false\n while (++i < lines.length) {\n const cont = lines[i].trimEnd()\n if (endsWithUnescapedQuote(cont, quote)) {\n parts.push(cont.slice(0, -1))\n closed = true\n break\n }\n parts.push(lines[i])\n }\n if (!closed) {\n throw new Error(\n `Unterminated quoted value for \"${key}\" (opens on line ${startLine}). ` +\n `Close the ${quote === '\"' ? 'double' : 'single'} quote, or escape newlines as \\\\n on one line.`,\n )\n }\n value = parts.join('\\n')\n if (quote === '\"') value = unescapeDotenv(value)\n }\n validateSecretValue(key, value)\n out[key] = value\n }\n return out\n}\n\n/** True when `s` is non-empty and ends with `q` not preceded by an odd run of\n * backslashes (only `\"` values support escapes; `'` closes unconditionally). */\nfunction endsWithUnescapedQuote(s: string, q: string): boolean {\n if (!s.endsWith(q)) return false\n if (q === \"'\") return true\n let backslashes = 0\n for (let j = s.length - 2; j >= 0 && s[j] === '\\\\'; j--) backslashes++\n return backslashes % 2 === 0\n}\n\n/** Left-to-right so `\\\\n` (escaped backslash + n) isn't confused with `\\n`. */\nfunction unescapeDotenv(v: string): string {\n let out = ''\n for (let i = 0; i < v.length; i++) {\n if (v[i] === '\\\\' && i + 1 < v.length) {\n const c = v[++i]\n out += c === 'n' ? '\\n' : c === 'r' ? '\\r' : c\n } else {\n out += v[i]\n }\n }\n return out\n}\n\n/**\n * POSIX single-quote: wrap in `'…'`, closing/reopening around any embedded\n * single quote (`'\\''`). Unlike dotenv double-quoting, this preserves real\n * newlines literally, so `eval \"$(… download --format shell)\"` restores a\n * multiline value (e.g. a PEM key) byte-for-byte instead of a one-line `\\n`.\n */\nexport function shellSingleQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`\n}\n\nexport function formatSecretsDownload(\n secrets: Record<string, string>,\n format: SecretsDownloadFormat,\n): string {\n const entries = Object.entries(secrets).sort(([a], [b]) => a.localeCompare(b))\n if (format === 'json') {\n return JSON.stringify(Object.fromEntries(entries), null, 2) + '\\n'\n }\n if (format === 'shell') {\n return entries.map(([k, v]) => `export ${k}=${shellSingleQuote(v)}`).join('\\n') + '\\n'\n }\n return entries.map(([k, v]) => `${k}=${quoteDotenvValue(v)}`).join('\\n') + '\\n'\n}\n\n/**\n * The pull-and-render step every command shares (deploy/dev/test): fetch the\n * app's config values and render the generated `.dev.vars` cache section.\n * Returns null when the store/config doesn't exist yet (\"nothing to ship\").\n * Real failures (auth, 5xx) throw — callers cancel loudly.\n */\nexport async function refreshSecretsCache(\n deployUrl: string,\n token: string,\n appId: string,\n wranglerEnv: string | undefined,\n): Promise<{ pulled: PulledSecretsCache; rendered: string; summary: string } | null> {\n const configName = defaultConfigNameForEnv(wranglerEnv)\n const pulled = await pullAppSecretsCache(deployUrl, token, appId, configName)\n if (!pulled) return null\n const count = Object.keys(pulled.values).length\n return {\n pulled,\n rendered: renderSecretsCache(pulled.values, pulled),\n summary: `Secrets: ${pulled.configName} (${count} secret${count === 1 ? '' : 's'})`,\n }\n}\n","import { chmodSync, writeFileSync } from 'node:fs'\n\n/**\n * Write a file that holds plaintext secret values (`.dev.vars` caches,\n * `secrets download` output) readable by the owner only. `writeFileSync`'s\n * `mode` applies only when the file is created, so chmod separately to\n * tighten files that already exist with a wider mode.\n */\nexport function writeSecretFileSync(path: string, content: string): void {\n writeFileSync(path, content, { mode: 0o600 })\n try {\n chmodSync(path, 0o600)\n } catch {\n // POSIX modes are best-effort on Windows; the write itself succeeded.\n }\n}\n","/**\n * Wrangler env resolution for DeepSpace's multi-environment deploys.\n *\n * Lets a single repo deploy to `<app>.app.space` and `<app>-staging.app.space`\n * (or any other named environment) from one `wrangler.toml`:\n *\n * name = \"hopkins\"\n * [vars]\n * APP_NAME = \"hopkins\"\n *\n * [env.staging]\n * name = \"hopkins-staging\"\n * [env.staging.vars]\n * APP_NAME = \"hopkins-staging\"\n *\n * Then `npx deepspace deploy --env staging` reads the override and ships to\n * `hopkins-staging.app.space`. The platform treats it as a fully separate\n * app — its own DO state, OAuth tokens, Stripe products, cron schedule.\n * No platform-side change needed beyond letting the CLI register a second\n * app under the same owner.\n *\n * When an app links a remote secrets project, DeepSpace keeps generated\n * dev/test/deploy credentials in a single `.dev.vars` cache so named\n * environments do not leave extra local files. In that linked-secrets mode,\n * `--env` flattens the selected Wrangler env into a generated config for the\n * Cloudflare Vite plugin instead of passing `CLOUDFLARE_ENV`; otherwise\n * Wrangler would prefer legacy `.dev.vars.<env>` files over the shared cache.\n * Unlinked apps keep Wrangler's legacy env-file behavior.\n */\n\nimport { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { parse as parseToml, stringify as stringifyToml } from 'smol-toml'\nimport { resolveAppName } from '../../server/rooms/app-name'\n\n/** Shape of the bits of wrangler.toml that DeepSpace CLI commands read.\n * Add an optional field here whenever a new command starts consulting\n * the config — avoids one-off `WranglerConfig & { … }` casts at\n * call sites and keeps the canonical type in one place. */\nexport interface WranglerConfig {\n name?: string\n env?: Record<\n string,\n ({ name?: string; vars?: Record<string, unknown> } & Record<string, unknown>) | undefined\n >\n /** `[assets]` block (`directory`, `binding`, `not_found_handling`,\n * `run_worker_first`). Consumed by deploy.ts to merge extra\n * worker-first routes into the deployed metadata. */\n assets?: {\n directory?: string\n binding?: string\n not_found_handling?: string\n run_worker_first?: unknown\n }\n /** `[vars]` block — string-valued environment variables baked into\n * the worker at deploy time. */\n vars?: Record<string, unknown>\n}\n\nexport interface PreparedWranglerEnvConfig {\n configPath?: string\n wranglerEnv?: string\n cleanup(): void\n}\n\nexport interface WranglerEnvModeOptions {\n sharedDevVarsCache?: boolean\n}\n\ntype TomlRecord = Record<string, unknown>\n\nconst NON_INHERITABLE_ENV_KEYS = new Set([\n 'define',\n 'vars',\n 'durable_objects',\n 'kv_namespaces',\n 'r2_buckets',\n 'ai_search_namespaces',\n 'ai_search',\n 'vectorize',\n 'services',\n 'queues',\n 'workflows',\n 'tail_consumers',\n 'secrets',\n 'secrets_store_secrets',\n])\n\nlet generatedConfigSeq = 0\n\n/**\n * Resolve the appName that this CLI invocation should target.\n *\n * Without `envName`: returns the top-level `name`.\n * With `envName`: returns `[env.<envName>].name` and requires that the\n * env block exists and declares a name. We refuse to\n * fall back to the top-level name because that would\n * silently deploy staging code to production.\n *\n * Returns a discriminated union so callers can surface a precise error\n * (matches the existing `resolveAppName` contract).\n */\nexport function resolveAppNameForEnv(\n config: WranglerConfig,\n envName: string | undefined,\n): { ok: true; name: string; warning?: string } | { ok: false; reason: string } {\n if (!envName) {\n return resolveAppName(config.name)\n }\n const envBlock = config.env?.[envName]\n if (!envBlock) {\n return {\n ok: false,\n reason:\n `wrangler.toml: no [env.${envName}] block found. ` +\n `Add one with a distinct \\`name\\` to deploy this environment.`,\n }\n }\n if (typeof envBlock.name !== 'string' || envBlock.name.trim() === '') {\n return {\n ok: false,\n reason:\n `wrangler.toml: [env.${envName}].name is missing. ` +\n `Set a distinct app name (e.g. \"${typeof config.name === 'string' ? config.name : 'myapp'}-${envName}\") so this environment doesn't overwrite the default.`,\n }\n }\n if (envBlock.name === config.name) {\n return {\n ok: false,\n reason:\n `wrangler.toml: [env.${envName}].name \"${envBlock.name}\" is the same as the top-level name. ` +\n `Pick a distinct name (e.g. \"${config.name}-${envName}\") so deploys don't collide.`,\n }\n }\n return resolveAppName(envBlock.name)\n}\n\n/** The .dev.vars path for the selected mode. Linked secrets use a shared cache. */\nexport function devVarsPathFor(\n appDir: string,\n envName: string | undefined,\n opts: WranglerEnvModeOptions = {},\n): string {\n if (opts.sharedDevVarsCache || !envName) return join(appDir, '.dev.vars')\n return join(appDir, `.dev.vars.${envName}`)\n}\n\nexport function legacyEnvDevVarsPathFor(\n appDir: string,\n envName: string | undefined,\n): string | undefined {\n return envName ? join(appDir, `.dev.vars.${envName}`) : undefined\n}\n\nexport function warnIfLegacyEnvDevVarsExists(\n appDir: string,\n envName: string | undefined,\n warn: (message: string) => void = console.warn,\n): void {\n const legacyPath = legacyEnvDevVarsPathFor(appDir, envName)\n if (!legacyPath || !existsSync(legacyPath)) return\n warn(\n `Warning: ${legacyPath} exists, but DeepSpace now uses ${devVarsPathFor(appDir, envName, { sharedDevVarsCache: true })} ` +\n `for every environment. This run will ignore ${legacyPath}; move any secrets you still ` +\n `need into .dev.vars, then remove the env-specific file when you're ready.`,\n )\n}\n\nexport function prepareWranglerEnvConfig(\n appDir: string,\n envName: string | undefined,\n opts: { warn?: (message: string) => void } & WranglerEnvModeOptions = {},\n): PreparedWranglerEnvConfig {\n if (!envName) return { cleanup() {} }\n if (!opts.sharedDevVarsCache) return { wranglerEnv: envName, cleanup() {} }\n\n warnIfLegacyEnvDevVarsExists(appDir, envName, opts.warn)\n\n const config = readWranglerConfig(appDir)\n const resolved = resolveAppNameForEnv(config, envName)\n if (!resolved.ok) throw new Error(resolved.reason)\n const flattened = flattenWranglerEnvConfig(config as TomlRecord, envName)\n const configPath = join(\n appDir,\n `.wrangler.deepspace.${safeGeneratedConfigSegment(envName)}.${process.pid}.${++generatedConfigSeq}.toml`,\n )\n writeFileSync(\n configPath,\n [\n '# Generated by DeepSpace for this CLI run.',\n '# Do not edit; wrangler.toml remains the source of truth.',\n stringifyToml(flattened),\n ]\n .join('\\n')\n .replace(/\\s*$/u, '\\n'),\n )\n return {\n configPath,\n cleanup() {\n rmSync(configPath, { force: true })\n },\n }\n}\n\nexport function wranglerViteEnv(\n baseEnv: NodeJS.ProcessEnv,\n prepared: PreparedWranglerEnvConfig,\n extraEnv: NodeJS.ProcessEnv = {},\n): NodeJS.ProcessEnv {\n const env = { ...baseEnv, ...extraEnv }\n if (prepared.configPath) {\n delete env.CLOUDFLARE_ENV\n env.CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH = prepared.configPath\n } else if (prepared.wranglerEnv) {\n env.CLOUDFLARE_ENV = prepared.wranglerEnv\n }\n return env\n}\n\nfunction flattenWranglerEnvConfig(config: TomlRecord, envName: string): TomlRecord {\n const envRoot = asTomlRecord(config.env)\n const envBlock = asTomlRecord(envRoot?.[envName])\n if (!envBlock) {\n throw new Error(`wrangler.toml: no [env.${envName}] block found.`)\n }\n\n const flattened: TomlRecord = {}\n for (const [key, value] of Object.entries(config)) {\n if (key === 'env' || NON_INHERITABLE_ENV_KEYS.has(key)) continue\n flattened[key] = value\n }\n for (const [key, value] of Object.entries(envBlock)) {\n flattened[key] = value\n }\n return flattened\n}\n\nfunction asTomlRecord(value: unknown): TomlRecord | undefined {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as TomlRecord)\n : undefined\n}\n\nfunction safeGeneratedConfigSegment(value: string): string {\n return value.replace(/[^A-Za-z0-9._-]/gu, '_')\n}\n\n/**\n * Read + parse wrangler.toml. Caller checks existence first via\n * `hasWranglerConfig`. Throws a `WranglerConfigError` with the absolute\n * path embedded on a malformed file — saves the user from staring at\n * a raw smol-toml parser stack trace when they have one stray\n * unquoted character in their config.\n */\nexport class WranglerConfigError extends Error {\n constructor(\n public readonly path: string,\n public readonly cause: unknown,\n ) {\n const detail = cause instanceof Error ? cause.message : String(cause)\n super(`wrangler.toml: malformed TOML at ${path}: ${detail}`)\n this.name = 'WranglerConfigError'\n }\n}\n\nexport function readWranglerConfig(appDir: string): WranglerConfig {\n const path = join(appDir, 'wrangler.toml')\n const raw = readFileSync(path, 'utf-8')\n try {\n return parseToml(raw) as WranglerConfig\n } catch (err) {\n throw new WranglerConfigError(path, err)\n }\n}\n\n/** Convenience: true when wrangler.toml exists at the standard path. */\nexport function hasWranglerConfig(appDir: string): boolean {\n return existsSync(join(appDir, 'wrangler.toml'))\n}\n","/**\n * App-name validation + sanitization helpers.\n *\n * Strategy: validate strictly so we have a precise definition of \"valid\",\n * but DON'T reject non-conforming names — sanitize them, warn the user, and\n * proceed. Hard rejection would break apps whose `wrangler.toml name` was\n * something like `My_App` (previously deployed as `my-app` via silent\n * server-side sanitization). The new behavior preserves \"still deploys,\"\n * but the CLI now surfaces a warning so the user can fix the name when\n * convenient instead of being silently surprised by their hostname.\n *\n * Rules track Cloudflare's WfP script-name constraints (RFC 1035 host label,\n * no consecutive dashes) plus our 2-char minimum so subdomains read sensibly.\n */\n\nexport const APP_NAME_RULES = {\n /** ^[a-z0-9](-?[a-z0-9])+$ — RFC 1035 host label, no consecutive dashes. */\n pattern: /^[a-z0-9](?:-?[a-z0-9])+$/,\n minLength: 2,\n maxLength: 63,\n} as const\n\nexport type AppNameValidation =\n | { valid: true; name: string }\n | { valid: false; reason: string }\n\n/**\n * Strict validation: returns valid only if the name already conforms.\n * Useful as a precondition test or for CI lints.\n */\nexport function validateAppName(raw: unknown): AppNameValidation {\n if (typeof raw !== 'string') {\n return { valid: false, reason: 'App name must be a string' }\n }\n const name = raw.trim()\n if (!name) {\n return { valid: false, reason: 'App name is required' }\n }\n if (name.length < APP_NAME_RULES.minLength) {\n return { valid: false, reason: `App name \"${name}\" is too short (min ${APP_NAME_RULES.minLength} chars)` }\n }\n if (name.length > APP_NAME_RULES.maxLength) {\n return { valid: false, reason: `App name \"${name}\" is too long (max ${APP_NAME_RULES.maxLength} chars)` }\n }\n if (!APP_NAME_RULES.pattern.test(name)) {\n return {\n valid: false,\n reason:\n `App name \"${name}\" is invalid. Use lowercase letters, digits, and single hyphens only ` +\n `(must start + end with alphanumeric). Examples: my-app, search-v2, unison-search.`,\n }\n }\n return { valid: true, name }\n}\n\nexport type AppNameResolution =\n | { ok: true; name: string; warning?: string }\n | { ok: false; reason: string }\n\n/**\n * Resolve an app name for deploy: prefer the input as-is if valid, otherwise\n * sanitize and warn. Hard-fail only if even sanitization can't produce a\n * valid name (empty, all-non-alphanumeric, too short, too long).\n *\n * The intent is \"what previously worked still works, with a friendly warning\n * about non-conforming names.\"\n */\nexport function resolveAppName(raw: unknown): AppNameResolution {\n const strict = validateAppName(raw)\n if (strict.valid) return { ok: true, name: strict.name }\n\n if (typeof raw !== 'string') return { ok: false, reason: strict.reason }\n const trimmed = raw.trim()\n if (!trimmed) return { ok: false, reason: 'App name is required' }\n\n const sanitized = sanitizeAppName(trimmed)\n const sanitizedStrict = validateAppName(sanitized)\n if (!sanitizedStrict.valid) {\n return {\n ok: false,\n reason: `App name \"${trimmed}\" can't be sanitized into a valid name (${sanitizedStrict.reason}). Pick something matching: lowercase letters, digits, single hyphens, ${APP_NAME_RULES.minLength}-${APP_NAME_RULES.maxLength} chars.`,\n }\n }\n return {\n ok: true,\n name: sanitized,\n warning:\n `App name \"${trimmed}\" doesn't conform to deploy rules — using \"${sanitized}\" instead. ` +\n `Update wrangler.toml's \\`name\\` to silence this warning.`,\n }\n}\n\n/**\n * Lossy normalization that mirrors what the deploy-worker historically did\n * server-side. Keep only [a-z0-9-], collapse consecutive dashes, trim leading\n * and trailing dashes.\n */\nfunction sanitizeAppName(raw: string): string {\n return raw\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n","import { Refusal } from './command'\n/**\n * Verifies the app's dependencies are installed before running a command that\n * needs them (dev, test, deploy, add).\n *\n * Current `create-deepspace` completes installation before returning and\n * before its initial commit. Sentinels under `<appDir>/.deepspace/` retain\n * compatibility with scaffolds created by the older detached installer:\n *\n * install.started — created before the worker is spawned\n * install.pid — legacy worker pid (liveness check for an older scaffold)\n * install.done — written on successful completion\n * install.err — written on failure (contains the error message)\n * install.log — legacy combined stdout/stderr\n *\n * The presence of `node_modules/deepspace/package.json` is the ground truth\n * for \"ready\"; the sentinels only shape the error message.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { detectPackageManager } from './package-manager'\n\nexport type InstallState = 'ready' | 'installing' | 'failed' | 'missing'\n\n/** Non-throwing install state for informational surfaces such as status. */\nexport function installState(appDir: string): InstallState {\n if (resolvesDeepspace(appDir)) return 'ready'\n const sentinelDir = join(appDir, '.deepspace')\n if (existsSync(join(sentinelDir, 'install.err'))) return 'failed'\n if (existsSync(join(sentinelDir, 'install.started'))) {\n if (!existsSync(join(sentinelDir, 'install.done')) && installWorkerAlive(sentinelDir)) {\n return 'installing'\n }\n return 'failed'\n }\n return 'missing'\n}\n\n/** How to watch the install log live, per platform: `tail -f` isn't on Windows\n * (PowerShell's `Get-Content -Wait` is the equivalent). */\nexport function tailHint(logPath: string, platform: NodeJS.Platform = process.platform): string {\n return platform === 'win32' ? `Get-Content -Wait ${logPath}` : `tail -f ${logPath}`\n}\n\nexport function ensureInstallReady(appDir: string): void {\n if (resolvesDeepspace(appDir)) return\n\n const sentinelDir = join(appDir, '.deepspace')\n const errPath = join(sentinelDir, 'install.err')\n const startedPath = join(sentinelDir, 'install.started')\n const donePath = join(sentinelDir, 'install.done')\n const logPath = join(sentinelDir, 'install.log')\n\n if (existsSync(errPath)) {\n const detail = readFileSync(errPath, 'utf-8').trimEnd()\n const log = existsSync(logPath) ? ` Full log: ${logPath}.` : ''\n throw new Refusal(\n `Dependency install failed: ${detail}.${log} Run \\`npm install\\` (or \\`bun install\\`) manually, then retry.`,\n 'install_failed',\n { action: { cwd: appDir, argv: [detectPackageManager(appDir), 'install'] } },\n )\n }\n\n if (existsSync(startedPath) && !existsSync(donePath)) {\n // A worker that died without writing done/err (OOM, docker stop, laptop\n // shutdown) must not read as \"still installing\" forever. Every installer\n // generation writes a valid install.pid before starting package-manager work.\n if (!installWorkerAlive(sentinelDir)) {\n const log = existsSync(logPath) ? ` See what happened: ${logPath}.` : ''\n throw new Refusal(\n `The dependency install is no longer running and never finished.${log} Run \\`npm install\\` (or \\`bun install\\`) manually, then retry.`,\n 'install_failed',\n { action: { cwd: appDir, argv: [detectPackageManager(appDir), 'install'] } },\n )\n }\n // `tail -f` isn't a Windows command — tailHint points PowerShell users at its equivalent.\n const tail = existsSync(logPath) ? ` Tail progress: ${tailHint(logPath)}.` : ''\n throw new Refusal(\n `Dependencies are still installing.${tail} Retry once it finishes.`,\n 'install_in_progress',\n )\n }\n\n throw new Refusal(\n 'Dependencies not installed. Run `npm install` (or `bun install`) first.',\n 'deps_missing',\n {\n action: { cwd: appDir, argv: [detectPackageManager(appDir), 'install'] },\n },\n )\n}\n\n/**\n * Ground truth for \"dependencies ready\", matching Node's resolver: walk up\n * from `fromDir` looking for node_modules/deepspace. This supports ordinary\n * monorepo hoisting; managed worktrees themselves receive an install action\n * and no longer link dependencies from another checkout.\n */\nexport function resolvesDeepspace(fromDir: string): boolean {\n let dir = fromDir\n for (;;) {\n if (existsSync(join(dir, 'node_modules', 'deepspace', 'package.json'))) return true\n const parent = dirname(dir)\n if (parent === dir) return false\n dir = parent\n }\n}\n\n/**\n * Is the detached install worker still running? Missing or malformed identity\n * fails closed; a valid pid is alive when signal 0 succeeds. EPERM means\n * \"alive, not ours\".\n */\nfunction installWorkerAlive(sentinelDir: string): boolean {\n const pidPath = join(sentinelDir, 'install.pid')\n if (!existsSync(pidPath)) return false\n const pid = Number(readFileSync(pidPath, 'utf-8').trim())\n if (!Number.isSafeInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/** Resolve the repository's package manager from its explicit packageManager\n * field first, then its lockfile. npm is the conservative fallback. */\nexport function detectPackageManager(appDir: string): PackageManager {\n try {\n const pkg = JSON.parse(readFileSync(join(appDir, 'package.json'), 'utf-8')) as {\n packageManager?: unknown\n }\n const name = typeof pkg.packageManager === 'string' ? pkg.packageManager.split('@')[0] : ''\n if (name === 'npm' || name === 'pnpm' || name === 'yarn' || name === 'bun') return name\n } catch {\n // Missing/malformed package.json falls through to lockfile detection.\n }\n if (existsSync(join(appDir, 'pnpm-lock.yaml'))) return 'pnpm'\n if (existsSync(join(appDir, 'yarn.lock'))) return 'yarn'\n if (existsSync(join(appDir, 'bun.lock')) || existsSync(join(appDir, 'bun.lockb'))) return 'bun'\n return 'npm'\n}\n\nexport function installCommand(appDir: string): string {\n return `${detectPackageManager(appDir)} install`\n}\n","import { Refusal } from './command'\nimport { execFileSync } from 'node:child_process'\nimport { existsSync } from 'node:fs'\n// Namespace import on purpose: a named `import { registerHooks }` would itself\n// crash at load time on the very Nodes this preflight exists to catch.\nimport * as nodeModule from 'node:module'\nimport { resolve } from 'node:path'\n\n/**\n * The Cloudflare Vite plugin uses `module.registerHooks` (Node 22.15+ /\n * 23.5+). On older Nodes, `vite build` and the dev server die with a cryptic\n * ESM error from deep inside the plugin:\n *\n * SyntaxError: The requested module 'node:module' does not provide an\n * export named 'registerHooks'\n *\n * Catch it before spawning Vite and print the actual fix instead. Feature-\n * detected rather than version-pinned so the check can't go stale; the\n * `hasRegisterHooks` parameter exists only for tests.\n */\nexport function preflightNodeVersion(\n command: string,\n hasRegisterHooks: boolean = typeof (nodeModule as { registerHooks?: unknown }).registerHooks ===\n 'function',\n): void {\n if (hasRegisterHooks) return\n // Throw, never process.exit — see resolvePort: an exit inside a runtime\n // command body skips the --json envelope entirely.\n throw new Refusal(\n `deepspace ${command} requires Node 22.15 or newer (found v${process.versions.node}). ` +\n 'Install the current LTS from https://nodejs.org and re-run.',\n 'node_too_old',\n )\n}\n\n// 0xC0000135 = STATUS_DLL_NOT_FOUND on Windows. Node reports it as a signed int.\nconst DLL_NOT_FOUND = -1073741515\n\n/**\n * On Windows, the Cloudflare Workers runtime (`workerd.exe`) is built with\n * MSVC and links against `vcruntime140.dll`. A bare Windows install (Server\n * 2022, Server Core, minimal Windows 11) does not ship those DLLs, so workerd\n * exits immediately with STATUS_DLL_NOT_FOUND. Miniflare then surfaces this as\n * \"Error: write EOF\" because workerd closed the stdin pipe before reading its\n * config — an error with no JS stack trace and no hint at the cause.\n *\n * This preflight catches the case and prints the actual fix (install VC++\n * Redistributable). Skip silently if workerd isn't installed yet or runs fine.\n */\nexport function preflightWindowsWorkerd(appDir: string): void {\n if (process.platform !== 'win32') return\n\n const workerdExe = resolve(\n appDir,\n 'node_modules',\n '@cloudflare',\n 'workerd-windows-64',\n 'bin',\n 'workerd.exe',\n )\n if (!existsSync(workerdExe)) return\n\n try {\n execFileSync(workerdExe, ['--help'], { stdio: 'pipe', timeout: 10_000 })\n return\n } catch (err: unknown) {\n const status = (err as { status?: number }).status\n if (status !== DLL_NOT_FOUND) return\n\n throw new Refusal(\n 'workerd (Cloudflare Workers runtime) cannot start on this system: it needs the ' +\n 'Microsoft Visual C++ Redistributable, which is not installed. Install it with ' +\n '`winget install Microsoft.VCRedist.2015+.x64` (or choco install -y vcredist140, or ' +\n 'https://aka.ms/vs/17/release/vc_redist.x64.exe), then restart this terminal and re-run.',\n 'vcredist_missing',\n )\n }\n}\n","import { readdirSync, rmSync } from 'node:fs'\nimport { join } from 'node:path'\n\nconst SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.wrangler', '.vite'])\n\n/**\n * Delete macOS metadata files (AppleDouble `._*` and `.DS_Store`) under an\n * app directory. They appear when a project is copied from macOS through\n * tar/zip/SMB onto another system, and they poison the toolchain: ESLint\n * hard-fails on their binary content (\"Parsing error: Invalid character\",\n * failing the deploy lint), and generouted can pick up `._index.tsx` in\n * src/pages as a phantom route. Returns the number of files removed.\n */\nexport function removeMacosJunk(dir: string): number {\n let removed = 0\n // Best-effort throughout: an unreadable subdir or undeletable file must\n // never abort a build that would otherwise have worked.\n let entries\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return removed\n }\n for (const entry of entries) {\n const path = join(dir, entry.name)\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) removed += removeMacosJunk(path)\n continue\n }\n if (entry.name === '.DS_Store' || entry.name.startsWith('._')) {\n try {\n rmSync(path, { force: true })\n removed++\n } catch {\n // Leave it — the lint may still trip on it, but we didn't make\n // anything worse.\n }\n }\n }\n return removed\n}\n","/**\n * CLI surface for schema lint.\n *\n * `lintSchema` findings otherwise print only from the worker console when a\n * RecordRoom DO constructs — after a client connects, interleaved with the\n * rest of the runtime log, and never at deploy time. These are exactly the\n * warnings that ship as privacy/permission bugs (e.g. a declared\n * visibilityField that no role actually enforces), so `dev` and `deploy`\n * also run them up front where the developer is already looking.\n *\n * Bundles the app's `src/schemas.ts` with esbuild and imports the resulting\n * ESM — the same approach `deploy` uses for `src/subscriptions.ts`. Lint is\n * advisory: any failure to load or parse returns null and the command\n * proceeds (the worker still warns at runtime).\n */\n\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { lintSchema, type CollectionSchema } from '../../server/schemas/registry'\n\n/**\n * Lint every schema exported from `<appDir>/src/schemas.ts`.\n * Returns the warning messages (empty = clean), or null when the file is\n * absent or couldn't be loaded — callers should stay quiet on null.\n */\nexport async function lintProjectSchemas(appDir: string): Promise<string[] | null> {\n const schemasPath = join(appDir, 'src', 'schemas.ts')\n if (!existsSync(schemasPath)) return null\n\n let schemas: unknown\n try {\n const esbuild = await import('esbuild')\n const outFile = join(appDir, '.wrangler', 'deploy', 'schemas.lint.bundle.mjs')\n await esbuild.build({\n entryPoints: [schemasPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: outFile,\n logLevel: 'silent',\n write: true,\n })\n // Cache-bust the import so repeat runs in the same Node process don't\n // reuse a stale module from the loader cache.\n const mod = (await import(`${pathToFileURL(outFile).href}?t=${Date.now()}`)) as {\n schemas?: unknown\n }\n schemas = mod.schemas\n } catch {\n // Say why lint is being skipped — a schema graph esbuild can't bundle\n // (e.g. a transitive `cloudflare:workers` import) would otherwise read\n // as \"schemas are clean\".\n console.warn(\n 'Schema lint skipped: could not bundle src/schemas.ts (the worker still lints at runtime).',\n )\n return null\n }\n\n if (!Array.isArray(schemas)) return null\n\n const findings: string[] = []\n for (const schema of schemas) {\n if (!schema || typeof schema !== 'object') continue\n try {\n findings.push(...lintSchema(schema as CollectionSchema))\n } catch {\n // A malformed schema entry fails loudly at runtime anyway — skip here.\n }\n }\n return findings\n}\n\n/** Max findings printed in full — the rest collapse to a count so a\n * pathological schema file can't flood the terminal (or an agent's context). */\nconst MAX_PRINTED_FINDINGS = 5\n\n/**\n * Format findings as printable lines. Empty input → empty output (print\n * nothing when clean — lint earns attention by being rare).\n */\nexport function formatSchemaLintFindings(findings: string[]): string[] {\n if (findings.length === 0) return []\n const n = findings.length\n const shown = findings.slice(0, MAX_PRINTED_FINDINGS)\n const hidden = n - shown.length\n return [\n `Schema lint: ${n} warning${n === 1 ? '' : 's'} in src/schemas.ts — ${n === 1 ? 'this ships' : 'these ship'} as permission/privacy bugs:`,\n ...shown.map((f) => ` • ${f}`),\n ...(hidden > 0 ? [` …and ${hidden} more — fix the above and re-run to see the rest.`] : []),\n ]\n}\n","/**\n * Collection Schema Definitions & Validation\n *\n * All collections use typed SQL columns. No document-mode / fields-based storage.\n */\n\nimport type {\n CollectionSchema,\n ColumnDefinition,\n ColumnInterpretation,\n PermissionLevel,\n RolePermissions,\n} from '../../shared/types'\n\nexport type {\n CollectionSchema,\n ColumnDefinition,\n ColumnInterpretation,\n PermissionLevel,\n RolePermissions,\n} from '../../shared/types'\n\n// ============================================================================\n// Column Definitions\n// ============================================================================\n\nexport interface ResolvedColumn {\n id: string\n name: string\n storage: 'number' | 'text'\n interpretation: ColumnInterpretation\n expression?: string\n readonly: boolean\n userBound?: boolean\n immutable?: boolean\n required?: boolean\n default?: unknown\n timestampTrigger?: { field: string; value?: unknown }\n}\n\n// ============================================================================\n// Column Helpers\n// ============================================================================\n\nexport function collectionTableName(name: string): string {\n return `c_${name.replace(/[^a-zA-Z0-9_]/g, '_')}`\n}\n\nexport function columnId(name: string): string {\n return `col_${name.toLowerCase().replace(/[^a-z0-9]/g, '_')}`\n}\n\nexport function resolveColumn(col: ColumnDefinition): ResolvedColumn {\n const interp: ColumnInterpretation =\n typeof col.interpretation === 'string'\n ? ({ kind: col.interpretation } as ColumnInterpretation)\n : col.interpretation\n return {\n id: col.id ?? columnId(col.name),\n name: col.name,\n storage: col.storage,\n interpretation: interp,\n expression: col.expression,\n readonly: !!col.expression,\n userBound: col.userBound,\n immutable: col.immutable,\n required: col.required,\n default: col.default,\n timestampTrigger: col.timestampTrigger,\n }\n}\n\nexport function rowToData(\n row: Record<string, unknown>,\n columns: ResolvedColumn[],\n): Record<string, unknown> {\n const data: Record<string, unknown> = {}\n for (const col of columns) {\n if (row[col.id] !== undefined && row[col.id] !== null) {\n let val = row[col.id]\n if (col.interpretation.kind === 'json' && typeof val === 'string') {\n try {\n val = JSON.parse(val as string)\n } catch {\n /* keep as string */\n }\n }\n data[col.name] = val\n }\n }\n return data\n}\n\nexport function dataToColumnValues(\n data: Record<string, unknown>,\n columns: ResolvedColumn[],\n): Record<string, unknown> {\n const values: Record<string, unknown> = {}\n for (const col of columns) {\n if (col.expression || col.readonly) continue\n const val = data[col.id] ?? data[col.name]\n if (val !== undefined) {\n values[col.id] = coerceValue(val, col.storage, col.interpretation)\n }\n }\n return values\n}\n\nexport function coerceValue(\n value: unknown,\n storage: 'number' | 'text',\n interpretation: ColumnInterpretation,\n): unknown {\n if (value === null || value === undefined || value === '') return null\n\n if (storage === 'text') {\n if (interpretation.kind === 'json') {\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value)\n } catch {\n return null\n }\n }\n return typeof value === 'string' ? value : String(value)\n }\n\n if (typeof value === 'number') return isFinite(value) ? value : null\n if (typeof value === 'boolean') return value ? 1 : 0\n if (typeof value !== 'string') return String(value)\n\n const s = value.trim()\n\n if (interpretation.kind === 'boolean') {\n const lower = s.toLowerCase()\n if (lower === 'true' || lower === '1' || lower === 'yes') return 1\n if (lower === 'false' || lower === '0' || lower === 'no') return 0\n return s\n }\n\n if (interpretation.kind === 'percent') {\n const m = s.match(/^(-?\\d+(?:\\.\\d+)?)\\s*%$/)\n if (m) return parseFloat(m[1]) / 100\n }\n\n if (interpretation.kind === 'currency') {\n const cleaned = s.replace(/[^0-9.-]/g, '')\n const n = parseFloat(cleaned)\n if (!isNaN(n)) return n\n return s\n }\n\n if (interpretation.kind === 'date' || interpretation.kind === 'datetime') {\n const d = new Date(s)\n if (!isNaN(d.getTime())) return Math.floor(d.getTime() / 1000)\n return s\n }\n\n const cleaned = s.replace(/[$€£¥,\\s]/g, '')\n const n = parseFloat(cleaned)\n if (!isNaN(n) && isFinite(n)) return n\n\n return s\n}\n\nexport function buildTableSelect(collectionName: string, columns: ResolvedColumn[]): string {\n const tbl = collectionTableName(collectionName)\n const parts: string[] = ['_row_id', '_created_by', '_created_at', '_updated_at']\n for (const col of columns) {\n if (col.expression) {\n parts.push(`(${col.expression}) AS \"${col.id}\"`)\n } else {\n parts.push(`\"${col.id}\"`)\n }\n }\n return `SELECT ${parts.join(', ')} FROM \"${tbl}\"`\n}\n\nexport interface User {\n id: string\n email: string\n name: string\n imageUrl?: string\n role: string\n createdAt: string\n lastSeenAt: string\n}\n\nexport interface StoredRecord {\n collection: string\n recordId: string\n data: Record<string, unknown>\n createdBy: string\n createdAt: string\n updatedAt: string\n}\n\n// ============================================================================\n// Permission Checking\n// ============================================================================\n\nexport interface PermissionContext {\n isTeamMember: (teamId: string, userId: string) => boolean\n}\n\nexport const noopPermissionContext: PermissionContext = {\n isTeamMember: () => false,\n}\n\nexport function getRolePermissions(schema: CollectionSchema, role: string): RolePermissions {\n if (schema.permissions[role]) return schema.permissions[role]\n if (schema.permissions['*']) return schema.permissions['*']\n return { read: false, create: false, update: false, delete: false }\n}\n\nexport function isOwner(\n schema: CollectionSchema,\n record: { data: Record<string, unknown>; createdBy: string },\n userId: string,\n): boolean {\n if (schema.ownerField) return record.data[schema.ownerField] === userId\n return record.createdBy === userId\n}\n\nfunction isCollaborator(\n schema: CollectionSchema,\n record: { data: Record<string, unknown> },\n userId: string,\n): boolean {\n if (!schema.collaboratorsField) return false\n const collab = record.data[schema.collaboratorsField]\n if (typeof collab === 'string') {\n try {\n return (JSON.parse(collab) as string[]).includes(userId)\n } catch {\n return false\n }\n }\n if (Array.isArray(collab)) return collab.includes(userId)\n return false\n}\n\nfunction passesVisibilityCheck(\n schema: CollectionSchema,\n record: { data: Record<string, unknown> },\n): boolean {\n if (!schema.visibilityField) return false\n if (typeof schema.visibilityField === 'string') {\n return record.data[schema.visibilityField] === 'public'\n }\n return record.data[schema.visibilityField.field] === schema.visibilityField.value\n}\n\nfunction checkPermissionLevel(\n level: PermissionLevel,\n schema: CollectionSchema,\n record: { data: Record<string, unknown>; createdBy: string; recordId?: string },\n userId: string,\n ctx: PermissionContext = noopPermissionContext,\n): boolean {\n if (level === true) return true\n if (level === false) return false\n if (level === 'own') return isOwner(schema, record, userId)\n if (level === 'unclaimed-or-own') {\n if (schema.ownerField) {\n const ownerVal = record.data[schema.ownerField]\n if (!ownerVal || ownerVal === '') return true\n }\n return isOwner(schema, record, userId)\n }\n if (level === 'collaborator') {\n return isOwner(schema, record, userId) || isCollaborator(schema, record, userId)\n }\n if (level === 'team' || level === 'access') {\n if (isOwner(schema, record, userId)) return true\n if (isCollaborator(schema, record, userId)) return true\n if (schema.teamField) {\n const teamId = record.data[schema.teamField]\n if (typeof teamId === 'string' && ctx.isTeamMember(teamId, userId)) return true\n }\n return false\n }\n if (level === 'published') {\n return isOwner(schema, record, userId) || passesVisibilityCheck(schema, record)\n }\n if (level === 'shared') {\n return (\n isOwner(schema, record, userId) ||\n isCollaborator(schema, record, userId) ||\n passesVisibilityCheck(schema, record)\n )\n }\n return false\n}\n\nexport function canRead(\n schema: CollectionSchema,\n role: string,\n record: { data: Record<string, unknown>; createdBy: string; recordId?: string },\n userId: string,\n ctx: PermissionContext = noopPermissionContext,\n): boolean {\n return checkPermissionLevel(getRolePermissions(schema, role).read, schema, record, userId, ctx)\n}\n\nexport function canCreate(schema: CollectionSchema, role: string): boolean {\n return getRolePermissions(schema, role).create === true\n}\n\nexport function canUpdate(\n schema: CollectionSchema,\n role: string,\n record: { data: Record<string, unknown>; createdBy: string; recordId?: string },\n userId: string,\n ctx: PermissionContext = noopPermissionContext,\n): boolean {\n return checkPermissionLevel(getRolePermissions(schema, role).update, schema, record, userId, ctx)\n}\n\nexport function canDelete(\n schema: CollectionSchema,\n role: string,\n record: { data: Record<string, unknown>; createdBy: string; recordId?: string },\n userId: string,\n ctx: PermissionContext = noopPermissionContext,\n): boolean {\n return checkPermissionLevel(getRolePermissions(schema, role).delete, schema, record, userId, ctx)\n}\n\n/** Check if a field update violates writableFields restrictions. */\nexport function checkFieldPermissions(\n schema: CollectionSchema,\n role: string,\n newData: Record<string, unknown>,\n existingData?: Record<string, unknown>,\n): string | null {\n const perms = getRolePermissions(schema, role)\n if (!perms.writableFields) return null // no restrictions\n\n const allowedFields = new Set(perms.writableFields)\n for (const key of Object.keys(newData)) {\n if (existingData && newData[key] === existingData[key]) continue\n if (!allowedFields.has(key)) {\n return `Role '${role}' cannot modify field '${key}'`\n }\n }\n return null\n}\n\n// ============================================================================\n// System-Managed Columns (users collection)\n// ============================================================================\n\n/** Names of columns managed by the system (registerUser), not client mutations. */\nexport const SYSTEM_MANAGED_COLUMNS = new Set([\n 'email',\n 'name',\n 'imageUrl',\n 'role',\n 'createdAt',\n 'lastSeenAt',\n])\n\n/** Standard user columns. Apps spread these into their users schema. */\nexport const USERS_COLUMNS: ColumnDefinition[] = [\n { name: 'email', storage: 'text', interpretation: 'plain' },\n { name: 'name', storage: 'text', interpretation: 'plain' },\n { name: 'imageUrl', storage: 'text', interpretation: 'plain' },\n { name: 'role', storage: 'text', interpretation: 'plain' },\n { name: 'createdAt', storage: 'text', interpretation: { kind: 'datetime' } },\n { name: 'lastSeenAt', storage: 'text', interpretation: { kind: 'datetime' } },\n]\n\nexport const BASE_USERS_SCHEMA: CollectionSchema = {\n name: 'users',\n columns: [...USERS_COLUMNS],\n permissions: {\n '*': { read: 'own', create: false, update: false, delete: false },\n admin: { read: true, create: false, update: true, delete: true },\n },\n}\n\n// ============================================================================\n// Schema Registry\n// ============================================================================\n\n/**\n * Lint a CollectionSchema for declarations that look like they should\n * enforce something but don't, due to interactions between top-level\n * fields (visibilityField, ownerField) and per-role permission levels.\n *\n * The SDK has historically silently accepted schemas that imply more\n * enforcement than they actually deliver — e.g., `visibilityField` set\n * but every role's `read: true` means \"anyone can read everything\"\n * regardless of `visibility`. Warn loudly at registration so app\n * authors notice before shipping a privacy bug.\n *\n * Returns an array of warning messages. Empty = clean.\n */\nexport function lintSchema(schema: CollectionSchema): string[] {\n const warnings: string[] = []\n const VISIBILITY_AWARE: ReadonlyArray<PermissionLevel> = ['published', 'shared']\n\n // Roles that grant unconditional read despite visibilityField being declared.\n if (schema.visibilityField) {\n const offendingRoles = Object.entries(schema.permissions)\n .filter(([, perms]) => perms.read === true)\n .map(([role]) => role)\n if (offendingRoles.length > 0) {\n const usesAware = Object.values(schema.permissions).some(\n (p) => typeof p.read === 'string' && VISIBILITY_AWARE.includes(p.read as PermissionLevel),\n )\n if (!usesAware) {\n warnings.push(\n `[${schema.name}] visibilityField is declared but no role uses read: 'published' or 'shared'. ` +\n `Roles with read: true (${offendingRoles.join(', ')}) will see every row regardless of visibility. ` +\n `Change those to read: 'published' (owner OR public) or 'shared' (owner OR collaborator OR public) ` +\n `to actually enforce the filter, or remove visibilityField if you don't intend to gate reads by it.`,\n )\n }\n }\n }\n\n // ownerField declared but the named column isn't userBound — easy to\n // create a row claiming someone else's ownership.\n if (schema.ownerField) {\n const col = schema.columns.find((c) => c.name === schema.ownerField)\n if (col && !col.userBound) {\n warnings.push(\n `[${schema.name}] ownerField is '${schema.ownerField}' but that column is not marked userBound: true. ` +\n `A client can create a row with someone else's id in this field, bypassing 'own' permission checks. ` +\n `Add userBound: true (and ideally immutable: true) to the column.`,\n )\n }\n }\n\n // userBound columns that aren't text storage — userBound sets the\n // field to the caller's userId (a string), so non-text storage is a\n // schema mistake that will surface as a coercion error at write time.\n for (const col of schema.columns) {\n if (col.userBound && col.storage !== 'text') {\n warnings.push(\n `[${schema.name}] column '${col.name}' is userBound but storage is '${col.storage}'. ` +\n `userBound stamps the user id (a string); use storage: 'text'.`,\n )\n }\n }\n\n return warnings\n}\n\nexport class SchemaRegistry {\n private trusted: Map<string, CollectionSchema> = new Map()\n\n constructor(schemas: CollectionSchema[] = []) {\n for (const schema of schemas) {\n this.registerTrusted(schema)\n }\n }\n\n registerTrusted(schema: CollectionSchema): void {\n for (const w of lintSchema(schema)) {\n console.warn(`[schema-lint] ${w}`)\n }\n this.trusted.set(schema.name, schema)\n }\n\n get(name: string): CollectionSchema | undefined {\n return this.trusted.get(name)\n }\n\n has(name: string): boolean {\n return this.trusted.has(name)\n }\n\n all(): CollectionSchema[] {\n return Array.from(this.trusted.values())\n }\n\n names(): string[] {\n return Array.from(this.trusted.keys())\n }\n}\n\n// ============================================================================\n// Permission Analysis\n// ============================================================================\n\nexport type PermissionSource = 'explicit' | 'wildcard' | 'default-deny'\n\nexport interface ResolvedPermission {\n level: PermissionLevel | boolean\n source: PermissionSource\n}\n\nexport interface CollectionPermissionSummary {\n collection: string\n ownerField?: string\n collaboratorsField?: string\n teamField?: string\n columns: ColumnDefinition[]\n permissions: Record<\n string,\n {\n read: ResolvedPermission\n create: ResolvedPermission\n update: ResolvedPermission\n delete: ResolvedPermission\n writableFields?: string[]\n }\n >\n}\n\nexport interface PermissionAnalysis {\n roles: string[]\n collections: CollectionPermissionSummary[]\n}\n\nexport function analyzePermissions(schemas: CollectionSchema[]): PermissionAnalysis {\n const roleSet = new Set<string>()\n for (const schema of schemas) {\n for (const role of Object.keys(schema.permissions)) roleSet.add(role)\n }\n roleSet.delete('*')\n const roles = Array.from(roleSet)\n\n const collections: CollectionPermissionSummary[] = schemas.map((schema) => {\n const permissions: CollectionPermissionSummary['permissions'] = {}\n for (const role of roles) {\n let source: PermissionSource\n let perms: RolePermissions\n if (schema.permissions[role]) {\n source = 'explicit'\n perms = schema.permissions[role]\n } else if (schema.permissions['*']) {\n source = 'wildcard'\n perms = schema.permissions['*']\n } else {\n source = 'default-deny'\n perms = { read: false, create: false, update: false, delete: false }\n }\n permissions[role] = {\n read: { level: perms.read, source },\n create: { level: perms.create, source },\n update: { level: perms.update, source },\n delete: { level: perms.delete, source },\n writableFields: perms.writableFields,\n }\n }\n return {\n collection: schema.name,\n ownerField: schema.ownerField,\n collaboratorsField: schema.collaboratorsField,\n teamField: schema.teamField,\n columns: schema.columns,\n permissions,\n }\n })\n\n return { roles, collections }\n}\n","import { Refusal } from './command'\n/**\n * Shared dev-server port resolution for `dev`, `test`, and `kill`.\n *\n * Precedence: explicit `--port` arg > $DEEPSPACE_PORT > DEFAULT_PORT. An\n * out-of-range value is a hard error (exit 1) rather than a silent fallback,\n * so a typo doesn't quietly bind the wrong port.\n */\n\nimport { createServer } from 'node:net'\n\nexport const DEFAULT_PORT = 5173\n\n/**\n * Whether `port` is free to bind on `host`. Used by `dev` to pre-probe before\n * spawning vite (which binds with `--host`, i.e. 0.0.0.0), so a busy port gets\n * a friendly `deepspace dev kill` / `--port` remedy instead of vite's raw\n * EADDRINUSE stack (DEV-5). Best-effort: a bind race after the probe still\n * surfaces vite's own error, but the common \"server already running\" case is\n * caught cleanly.\n */\nexport function checkPortAvailable(port: number, host = '0.0.0.0'): Promise<boolean> {\n return new Promise((resolve) => {\n const srv = createServer()\n srv.once('error', () => resolve(false))\n srv.once('listening', () => srv.close(() => resolve(true)))\n srv.listen(port, host)\n })\n}\n\nexport function resolvePort(arg?: string): number {\n const raw = arg ?? process.env.DEEPSPACE_PORT\n if (!raw) return DEFAULT_PORT\n const n = Number(raw)\n if (!Number.isInteger(n) || n < 1 || n > 65535) {\n // Throw, never process.exit: these helpers run inside runtime command\n // bodies, and an exit skips the runtime's envelope — a --json caller\n // would get code 1 with an EMPTY stdout, the exact hole the runtime\n // exists to close.\n throw new Refusal(`Invalid port: ${raw}. Must be an integer between 1 and 65535.`, 'invalid_port')\n }\n return n\n}\n","/**\n * deepspace dev kill [--port N] [--all]\n *\n * Stops a local dev server bound to the given port, plus the workerd\n * child processes that wrangler/Vite would normally clean up but\n * sometimes leak when the parent dies ungracefully (Ctrl-C in a\n * detached terminal, IDE close, sandbox deny on signal, etc).\n *\n * deepspace dev kill # kill listener on 5173 + its workerd children\n * deepspace dev kill --port 5180 # kill listener on a different port\n * deepspace dev kill --all # also sweep ALL stray workerd/wrangler procs on the machine\n *\n * Cross-platform: uses lsof/pgrep on macOS and Linux, and PowerShell\n * (Get-NetTCPConnection / Get-CimInstance) on Windows. PowerShell ships\n * with every supported Windows version since 7; no extra install required.\n *\n * Always sends SIGTERM first, waits briefly, then SIGKILL anything\n * still alive — same shape as `vite`'s own shutdown handler so we\n * don't trample DO state mid-write. (On Windows, SIGTERM is best-effort:\n * Win32 has no real signals, so node maps both to TerminateProcess. We\n * still issue them in the same order for consistent log output.)\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { readFileSync, readdirSync, readlinkSync } from 'node:fs'\nimport { setTimeout as wait } from 'node:timers/promises'\nimport { findAppDir } from '../lib/app-context'\nimport { resolveWorktreePort, resolveAppLaunchPort } from '../lib/launch-config'\nimport { DEFAULT_PORT, resolvePort } from '../lib/port'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst SIGTERM_GRACE_MS = 1500\nconst IS_WIN = process.platform === 'win32'\n\n/**\n * Pick the port `kill` targets, mirroring `dev`'s binding precedence so the two\n * always agree (DEV-2). Pure for testing.\n * 1. explicit --port\n * 2. $DEEPSPACE_PORT\n * 3. generic linked-worktree port\n * 4. the app's launch.json port (kept in sync by `dev --port`)\n * 5. the default\n */\nexport function pickKillPort(opts: {\n explicit: number | null\n worktree: number | null\n env: number | null\n appLaunch: number | null\n}): number {\n if (opts.explicit != null) return opts.explicit\n if (opts.env != null) return opts.env\n if (opts.worktree != null) return opts.worktree\n return opts.appLaunch ?? DEFAULT_PORT\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'kill',\n description: 'Kill the local dev server and any orphaned workerd processes',\n },\n args: {\n port: {\n type: 'string',\n description: `Port the dev server is bound to (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n all: {\n type: 'boolean',\n description: 'Also kill stray workerd/wrangler processes across all ports',\n default: false,\n },\n },\n async run({ args }) {\n const portArg = args.port as string | undefined\n const all = Boolean(args.all)\n const say = (line: string) => {\n if (!args.json) console.log(line)\n }\n // Resolve which port to target, mirroring `dev`'s own precedence so `kill`\n // always targets the server `dev` bound (DEV-2). Without this, no-arg `kill`\n // hit :5173 even when `dev --port 8790` was running elsewhere.\n const cwd = process.cwd()\n const port = pickKillPort({\n explicit: portArg ? resolvePort(portArg) : null,\n worktree: resolveWorktreePort(cwd),\n // resolvePort() reads + validates $DEEPSPACE_PORT; only consult it when set.\n env: process.env.DEEPSPACE_PORT ? resolvePort() : null,\n appLaunch: resolveAppLaunchPort(findAppDir(cwd) ?? cwd),\n })\n const targets = new Set<number>()\n\n // 1. Anything LISTENing on the dev port (vite + the workerd child it\n // publishes through, occasionally a stray inspector). `enumerated`\n // tells us whether we could actually inspect the port at all.\n const listeners = enumerateListeners(port)\n for (const pid of listeners.pids) targets.add(pid)\n\n // 2. Children of those listeners — wrangler/vite tend to spawn workerd\n // as a sibling, but in some shells it ends up as a child instead.\n for (const pid of [...targets]) {\n for (const child of childPids(pid)) targets.add(child)\n }\n\n // 3. With --all, sweep workerd / wrangler / vite anywhere on the box.\n // Useful when port 5173 is \"free\" but a leftover workerd from a\n // previous run is still holding D1 / DO state in .wrangler/.\n let swept = false\n if (all) {\n const sweep = sweepByName(['workerd', 'wrangler', 'vite'])\n swept = sweep.swept\n for (const pid of sweep.pids) targets.add(pid)\n }\n\n if (targets.size === 0) {\n // DEV-1: distinguish \"inspected, found nothing\" from \"couldn't inspect\".\n // The latter must NOT report the port free (exit 0) while a leaked\n // workerd keeps holding DO/D1 state — that was the original silent no-op.\n const outcome = noTargetsMessage({\n enumerated: listeners.enumerated,\n swept,\n all,\n port,\n })\n if (!outcome.ok) {\n throw new Refusal(outcome.message, 'inspect_unavailable')\n }\n say(outcome.message)\n return { data: { port, all, killed: [], portFree: true } }\n }\n\n // SIGTERM pass.\n for (const pid of targets) {\n if (sendSignal(pid, 'SIGTERM')) {\n say(`SIGTERM → pid ${pid}`)\n }\n }\n await wait(SIGTERM_GRACE_MS)\n\n const stillAlive: number[] = []\n for (const pid of targets) {\n if (isAlive(pid)) stillAlive.push(pid)\n }\n\n // SIGKILL holdouts.\n const killed: number[] = []\n for (const pid of stillAlive) {\n if (sendSignal(pid, 'SIGKILL')) {\n killed.push(pid)\n say(`SIGKILL → pid ${pid} (did not exit on SIGTERM)`)\n }\n }\n\n // Re-verify the port is free.\n await wait(200)\n const remaining = listenerPids(port)\n if (remaining.length > 0) {\n throw new Refusal(\n `Port ${port} is still held by pid(s) ${remaining.join(', ')} — try \\`deepspace dev kill --port ${port}\\` again, or kill manually.`,\n 'port_still_held',\n {\n action: cliAction('deepspace', 'dev', 'kill', '--port', String(port)),\n extra: { port, holders: remaining },\n },\n )\n }\n\n // Report what actually happened. Under --all we may have swept processes on\n // ports other than `port` (matched by name), so a bare \"Port 5173 is free\"\n // would misrepresent the sweep (DEV-6).\n say(\n all\n ? `Killed ${targets.size} process(es) (workerd/wrangler/vite sweep). :${port} is free.`\n : `Port ${port} is free.`,\n )\n return {\n data: { port, all, killed: [...targets], sigkilled: killed, portFree: true },\n }\n },\n})\n\n// ── Platform-specific helpers ─────────────────────────────────────────────\n\n/**\n * Decide what to print when no kill targets were found. Pure so the DEV-1\n * rule — never claim the port is free when we couldn't actually inspect it —\n * is unit-testable. `ok:false` means we lacked any way to observe the system\n * (no lsof/pgrep AND no /proc) and must exit non-zero rather than lie.\n */\nexport function noTargetsMessage(opts: {\n enumerated: boolean\n swept: boolean\n all: boolean\n port: number\n}): { ok: boolean; message: string } {\n const { enumerated, swept, all, port } = opts\n const couldObserve = enumerated || (all && swept)\n if (!couldObserve) {\n return {\n ok: false,\n message:\n `Couldn't determine what's running on :${port}: no lsof/pgrep and /proc ` +\n `is unavailable, so nothing was inspected or killed. Install lsof (or ` +\n `procps for pgrep), or find and kill the process manually.`,\n }\n }\n return {\n ok: true,\n message: all\n ? `Nothing listening on :${port} and no stray workerd/wrangler/vite processes found.`\n : `Nothing listening on :${port}. (Pass --all to sweep stray workerd/wrangler.)`,\n }\n}\n\n/**\n * PIDs listening on `port`, plus whether we could inspect the port at all.\n * `enumerated:false` means every available method (lsof / PowerShell / /proc)\n * was missing — a genuine \"don't know\", not \"nothing there\".\n */\nfunction enumerateListeners(port: number): { pids: number[]; enumerated: boolean } {\n if (IS_WIN) {\n // Get-NetTCPConnection is the modern replacement for netstat -ano.\n // -ErrorAction SilentlyContinue swallows \"No matching connection\" so\n // the command exits 0 with empty stdout instead of a noisy red error.\n const r = runPowershellChecked(\n `Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess`,\n )\n return { pids: r.pids, enumerated: r.ran }\n }\n // lsof is authoritative when present. It exits 1 (not an error, for us) when\n // nothing matches, so \"ran but empty\" is a real \"nothing listening\".\n const lsof = runLsof(port)\n if (lsof.ran) return { pids: lsof.pids, enumerated: true }\n // lsof is absent on many container/CI images — the official Bookworm Node\n // images ship none of lsof/ss/fuser/netstat. /proc needs no external binary\n // and covers Linux; if it's also unavailable we truly can't tell (enumerated:false).\n const proc = listenerPidsViaProc(port)\n return { pids: proc.pids, enumerated: proc.available }\n}\n\n/** Thin wrapper for the post-kill re-verify, where capability is irrelevant. */\nfunction listenerPids(port: number): number[] {\n return enumerateListeners(port).pids\n}\n\n/** Run lsof for a port. `ran` distinguishes \"lsof absent\" from \"found nothing\". */\nfunction runLsof(port: number): { pids: number[]; ran: boolean } {\n try {\n // -t prints PIDs only, one per line; -nP avoids DNS / service lookups.\n const r = spawnSync('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'], {\n encoding: 'utf-8',\n })\n if (r.error) return { pids: [], ran: false } // ENOENT: lsof not installed\n // 0 = matches printed; 1 = no matches. Both mean lsof ran successfully.\n return { pids: r.status === 0 ? parsePidLines(r.stdout) : [], ran: true }\n } catch {\n return { pids: [], ran: false }\n }\n}\n\n/** Port → listening PIDs via /proc alone (no lsof/ss). Finds the LISTEN\n * socket's inode in /proc/net/tcp{,6}, then the process holding that fd.\n * `available` is false when /proc itself couldn't be read. */\nfunction listenerPidsViaProc(port: number): { pids: number[]; available: boolean } {\n let available = false\n try {\n const hexPort = port.toString(16).toUpperCase().padStart(4, '0')\n const inodes = new Set<string>()\n for (const f of ['/proc/net/tcp', '/proc/net/tcp6']) {\n let data: string\n try {\n data = readFileSync(f, 'utf-8')\n } catch {\n continue\n }\n available = true\n for (const line of data.split('\\n').slice(1)) {\n const cols = line.trim().split(/\\s+/)\n // sl local_address(1) rem_address(2) st(3) … inode(9); st 0A = LISTEN.\n if (cols[3] !== '0A') continue\n if (cols[1]?.split(':')[1] === hexPort && cols[9]) inodes.add(cols[9])\n }\n }\n if (!available) return { pids: [], available: false }\n if (!inodes.size) return { pids: [], available: true }\n const pids = new Set<number>()\n for (const pidDir of readdirSync('/proc')) {\n if (!/^\\d+$/.test(pidDir)) continue\n let fds: string[]\n try {\n fds = readdirSync(`/proc/${pidDir}/fd`)\n } catch {\n continue // not ours / gone\n }\n for (const fd of fds) {\n let link: string\n try {\n link = readlinkSync(`/proc/${pidDir}/fd/${fd}`)\n } catch {\n continue\n }\n const m = link.match(/^socket:\\[(\\d+)\\]$/)\n if (m && inodes.has(m[1])) {\n pids.add(Number(pidDir))\n break\n }\n }\n }\n return { pids: [...pids], available: true }\n } catch {\n return { pids: [], available }\n }\n}\n\nfunction childPids(parentPid: number): number[] {\n if (IS_WIN) {\n return runPowershell(\n `Get-CimInstance Win32_Process -Filter \"ParentProcessId=${parentPid}\" | Select-Object -ExpandProperty ProcessId`,\n )\n }\n return run(['pgrep', '-P', String(parentPid)])\n}\n\n/**\n * Sweep processes by name/commandline. `swept` reports whether the enumerator\n * (pgrep / PowerShell) actually ran — so `--all` doesn't falsely claim \"no\n * stray processes\" when it never got to look.\n */\nfunction sweepByName(names: string[]): { pids: number[]; swept: boolean } {\n const all = new Set<number>()\n if (IS_WIN) {\n // Match against process Name (e.g. \"workerd\") AND CommandLine (catches\n // npx-launched scripts like \"vite\" that show up as node.exe with vite\n // in the args).\n const orClauses = names\n .map((n) => `($_.Name -like '*${n}*') -or ($_.CommandLine -like '*${n}*')`)\n .join(' -or ')\n const script = `Get-CimInstance Win32_Process | Where-Object { ${orClauses} } | Select-Object -ExpandProperty ProcessId`\n const r = runPowershellChecked(script)\n for (const pid of r.pids) if (pid !== process.pid) all.add(pid)\n return { pids: [...all], swept: r.ran }\n }\n let swept = false\n for (const name of names) {\n const r = runPgrep(['-f', name])\n if (r.ran) swept = true\n for (const pid of r.pids) if (pid !== process.pid) all.add(pid)\n }\n return { pids: [...all], swept }\n}\n\n/** Run pgrep. `ran` distinguishes \"pgrep absent\" from \"matched nothing\" (exit 1). */\nfunction runPgrep(pgrepArgs: string[]): { pids: number[]; ran: boolean } {\n try {\n const r = spawnSync('pgrep', pgrepArgs, { encoding: 'utf-8' })\n if (r.error) return { pids: [], ran: false } // ENOENT: pgrep not installed\n // 0 = matches; 1 = no matches. Both mean pgrep ran.\n return {\n pids: r.status === 0 ? parsePidLines(r.stdout) : [],\n ran: r.status === 0 || r.status === 1,\n }\n } catch {\n return { pids: [], ran: false }\n }\n}\n\n// ── Process primitives ────────────────────────────────────────────────────\n\n/** Run a command and return whitespace-separated PIDs (empty array on failure). */\nfunction run(cmd: string[]): number[] {\n try {\n const r = spawnSync(cmd[0], cmd.slice(1), { encoding: 'utf-8' })\n if (r.status !== 0) return []\n return parsePidLines(r.stdout)\n } catch {\n return []\n }\n}\n\n/**\n * Run a PowerShell snippet. Prefers `pwsh` (PowerShell 7+) when available\n * and falls back to `powershell.exe` (Windows PowerShell 5.1, ships with\n * every Windows version we care about).\n */\nfunction runPowershell(script: string): number[] {\n return runPowershellChecked(script).pids\n}\n\n/** Like runPowershell but reports whether PowerShell actually ran (`ran`),\n * so callers can tell \"no matches\" (exit 0, empty) from \"PowerShell absent\". */\nfunction runPowershellChecked(script: string): { pids: number[]; ran: boolean } {\n const exe = pwshOrPowershell()\n try {\n const r = spawnSync(exe, ['-NoProfile', '-NonInteractive', '-Command', script], {\n encoding: 'utf-8',\n })\n if (r.error) return { pids: [], ran: false }\n // With -ErrorAction SilentlyContinue the query exits 0 even with no matches.\n return { pids: r.status === 0 ? parsePidLines(r.stdout) : [], ran: r.status === 0 }\n } catch {\n return { pids: [], ran: false }\n }\n}\n\nfunction pwshOrPowershell(): string {\n // `pwsh` is the modern cross-platform binary; `powershell.exe` is the\n // legacy Windows-only one. Try modern first, fall back if missing.\n const probe = spawnSync('pwsh', ['-NoProfile', '-Command', '$PSVersionTable.PSVersion.Major'], {\n encoding: 'utf-8',\n })\n if (probe.status === 0) return 'pwsh'\n return 'powershell.exe'\n}\n\nfunction parsePidLines(stdout: string): number[] {\n return stdout\n .split(/\\s+/)\n .map((s) => Number.parseInt(s, 10))\n .filter((n) => Number.isFinite(n) && n > 0)\n}\n\nfunction sendSignal(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(pid, signal)\n return true\n } catch {\n return false\n }\n}\n\nfunction isAlive(pid: number): boolean {\n try {\n // signal 0 = \"do nothing, just check\"\n process.kill(pid, 0)\n return true\n } catch {\n return false\n }\n}\n","/**\n * deepspace test run [suite] [--port N]\n *\n * Runs tests for a DeepSpace app. Always uses dev workers.\n *\n * deepspace test run # smoke + api (quick check)\n * deepspace test run smoke # smoke tests only\n * deepspace test run api # API tests only\n * deepspace test run e2e # all Playwright tests\n * deepspace test run unit # vitest unit tests\n * deepspace test run all # everything\n * deepspace test run <file> # run specific test file\n *\n * Port is `--port` > $DEEPSPACE_PORT > a stable linked-worktree port > 5173.\n * In any linked checkout the worktree's own default is used\n * so tests hit the worktree's server, not the main repo's. The chosen port is\n * exported as DEEPSPACE_PORT to the Playwright child so the config +\n * webServer both bind to the same address. Pass a different port per app to\n * run multiple apps\n * (and test suites) in parallel.\n *\n * Defined with the command runtime (lib/command.ts). The suite runner streams\n * playwright/vitest output through inherited stdio, so under `--json` that\n * text still scrolls past and the envelope is the LAST line rather than the\n * only one — buffering a test run to keep stdout pristine would cost the live\n * feedback the command exists for. The suite's own exit code collapses to the\n * contract's 0/1.\n */\n\nimport { readAppId } from '../lib/app-identity'\nimport { resolve } from 'node:path'\nimport { sync as spawnSync } from 'cross-spawn'\nimport { ensureToken } from '../auth'\nimport { findAppDir, findChildApps } from '../lib/app-context'\nimport { resolveWorktreePort } from '../lib/launch-config'\nimport { PLATFORM_URLS } from '../env'\nimport { writeDevVars } from '../lib/dev-vars'\nimport { decodeJwtPayload } from '../jwt'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { ensurePlaywright } from '../lib/playwright'\nimport { preflightNodeVersion, preflightWindowsWorkerd } from '../lib/preflight'\nimport { refreshSecretsCache } from '../lib/secrets'\nimport { DEFAULT_PORT, resolvePort } from '../lib/port'\nimport {\n prepareWranglerEnvConfig,\n wranglerViteEnv,\n type PreparedWranglerEnvConfig,\n} from '../lib/wrangler-env'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n// Same refusal text `dev` uses — one source so the two can't drift.\nimport { noAppDirMessage } from './dev'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'test',\n description: 'Run tests for your DeepSpace app',\n },\n args: {\n suite: {\n type: 'positional',\n description: 'Test suite: smoke, api, e2e, unit, all (default: smoke+api)',\n required: false,\n },\n port: {\n type: 'string',\n description: `Port for vite/webServer (default ${DEFAULT_PORT}, or $DEEPSPACE_PORT)`,\n required: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description:\n 'wrangler.toml [env.<name>] block to test (uses secrets config <name> by default).',\n required: false,\n },\n },\n async run({ args }) {\n const say = (line: string) => {\n if (!args.json) console.log(line)\n }\n preflightNodeVersion('test run')\n const suite = (args.suite as string | undefined) ?? 'default'\n const wranglerEnv =\n typeof args.env === 'string' && args.env.trim() ? args.env.trim() : undefined\n\n // Resolve the app root by walking up from cwd, matching `deepspace dev start`.\n const start = resolve('.')\n const appDir = findAppDir(start)\n if (!appDir) {\n throw new Refusal(noAppDirMessage(start, findChildApps(start)), 'no_app_dir')\n }\n\n // Inside any linked Git worktree the default port must match that\n // checkout's dev server (not 5173): Playwright's reuseExistingServer\n // would otherwise attach to the MAIN repo's server and silently test\n // stale code. Explicit --port still wins.\n const configuredPort = Boolean(args.port) || Boolean(process.env.DEEPSPACE_PORT)\n const worktreePort = configuredPort ? null : resolveWorktreePort(appDir)\n const port = worktreePort ?? resolvePort(args.port as string | undefined)\n\n ensureInstallReady(appDir)\n\n // Always write .dev.vars pointing to dev workers. A logged-in user is\n // required so writeDevVars can mint APP_OWNER_JWT via the auth-worker.\n let token: string\n let ownerId: string\n try {\n token = await ensureToken()\n const payload = decodeJwtPayload<{ sub: string }>(token)\n ownerId = payload.sub\n } catch (err) {\n // Surface ensureToken's canonical message (\"Not logged in. Run `deepspace\n // login` first.\" / \"Session expired…\") instead of a bespoke one (ONB-5).\n throw new Refusal(\n err instanceof Error ? err.message : 'Not logged in. Run `deepspace auth login` first.',\n 'not_authenticated',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n\n // Refresh the app-store secrets cache (config = wrangler env, or 'prd').\n // A repo without a DEEPSPACE_APP_ID hasn't been initialized — writeDevVars\n // below throws with the `deepspace app init` pointer, so skip the pull.\n let generatedSecretsCache: string | undefined\n const appIdForSecrets = readAppId(appDir, wranglerEnv)\n if (appIdForSecrets) {\n try {\n const refreshed = await refreshSecretsCache(DEPLOY_URL, token, appIdForSecrets, wranglerEnv)\n if (refreshed) {\n generatedSecretsCache = refreshed.rendered\n say(refreshed.summary)\n }\n } catch (err: unknown) {\n throw new Refusal(\n `Failed to refresh app secrets: ${err instanceof Error ? err.message : String(err)}`,\n 'secrets_refresh_failed',\n )\n }\n }\n\n const sharedDevVarsCache = generatedSecretsCache !== undefined\n await writeDevVars(appDir, ownerId, token, wranglerEnv, {\n generatedSecretsCache,\n sharedDevVarsCache,\n })\n\n if (suite !== 'unit') {\n preflightWindowsWorkerd(appDir)\n ensurePlaywright(appDir)\n }\n\n let exitCode = 0\n\n switch (suite) {\n case 'smoke':\n exitCode = runPlaywright(\n appDir,\n ['tests/smoke.spec.ts'],\n port,\n wranglerEnv,\n sharedDevVarsCache,\n )\n break\n case 'api':\n exitCode = runPlaywright(\n appDir,\n ['tests/api.spec.ts'],\n port,\n wranglerEnv,\n sharedDevVarsCache,\n )\n break\n case 'e2e':\n exitCode = runPlaywright(appDir, [], port, wranglerEnv, sharedDevVarsCache)\n break\n case 'unit':\n exitCode = runVitest(appDir)\n break\n case 'all':\n exitCode = runVitest(appDir)\n if (exitCode === 0)\n exitCode = runPlaywright(appDir, [], port, wranglerEnv, sharedDevVarsCache)\n break\n case 'default':\n exitCode = runPlaywright(\n appDir,\n ['tests/smoke.spec.ts', 'tests/api.spec.ts'],\n port,\n wranglerEnv,\n sharedDevVarsCache,\n )\n break\n default:\n if (suite.endsWith('.spec.ts')) {\n exitCode = runPlaywright(appDir, [suite], port, wranglerEnv, sharedDevVarsCache)\n } else {\n throw new Refusal(\n `Unknown test suite: ${suite}\\nAvailable: smoke, api, e2e, unit, all`,\n 'unknown_suite',\n )\n }\n }\n\n // The runner already printed every failure in detail; the refusal adds the\n // slug and the non-zero exit. Playwright's own code collapses to 1 — the\n // contract reserves 0/1/2 and every non-zero code here means \"tests failed\".\n if (exitCode !== 0) {\n throw new Refusal(`Test suite '${suite}' failed (exit ${exitCode}).`, 'tests_failed', {\n extra: { suite, port, exitCode },\n })\n }\n return { data: { suite, port, appDir, wranglerEnv: wranglerEnv ?? null } }\n },\n})\n\nfunction runPlaywright(\n appDir: string,\n testFiles: string[],\n port: number,\n wranglerEnv?: string,\n sharedDevVarsCache = false,\n): number {\n let wranglerConfig: PreparedWranglerEnvConfig\n try {\n wranglerConfig = prepareWranglerEnvConfig(appDir, wranglerEnv, { sharedDevVarsCache })\n } catch (err: unknown) {\n console.error(err instanceof Error ? err.message : String(err))\n return 1\n }\n try {\n const result = spawnSync(\n 'npx',\n ['playwright', 'test', '--config', 'tests/playwright.config.ts', ...testFiles],\n {\n cwd: appDir,\n stdio: 'inherit',\n env: wranglerViteEnv(process.env, wranglerConfig, { DEEPSPACE_PORT: String(port) }),\n },\n )\n return result.status ?? 1\n } finally {\n wranglerConfig.cleanup()\n }\n}\n\nfunction runVitest(appDir: string): number {\n const result = spawnSync('npx', ['vitest', 'run', '--passWithNoTests'], {\n cwd: appDir,\n stdio: 'inherit',\n })\n return result.status ?? 1\n}\n","import { Refusal } from './command'\nimport { execSync } from 'node:child_process'\nimport { sync as spawnSync } from 'cross-spawn'\n\nexport function ensurePlaywright(appDir: string) {\n try {\n // execSync interprets the command via shell, so it handles npx/npx.cmd\n // resolution on its own. Only spawn()/spawnSync() need cross-spawn.\n execSync('npx playwright --version', { cwd: appDir, stdio: 'pipe' })\n } catch {\n console.log('Installing Playwright...')\n execSync('npm install -D @playwright/test', { cwd: appDir, stdio: 'pipe' })\n }\n\n // `playwright install` is idempotent: a fast no-op when Chromium already\n // exists, and the first real browser download only when a browser command\n // actually needs it.\n const isLinux = process.platform === 'linux'\n const isRoot = isLinux && typeof process.getuid === 'function' && process.getuid() === 0\n const args = isRoot ? ['install', '--with-deps', 'chromium'] : ['install', 'chromium']\n const result = spawnSync('npx', ['playwright', ...args], {\n cwd: appDir,\n stdio: 'inherit',\n })\n\n if (result.status !== 0) {\n throw new Refusal(\n 'Playwright install failed. On Linux, system libs may be missing. Try: sudo npx playwright install --with-deps chromium',\n 'playwright_install_failed',\n )\n }\n}\n","/**\n * deepspace test screenshot <url> <output> [--full-page] [--wait-for-timeout ms]\n *\n * Takes a Playwright Chromium screenshot, installing the browser on demand.\n *\n * Playwright is spawned with inherited stdio, so its progress streams straight\n * through — under `--json` that streamed text precedes the envelope, which is\n * still the last line on stdout.\n */\n\nimport { sync as spawnSync } from 'cross-spawn'\nimport { resolve } from 'node:path'\nimport { ensurePlaywright } from '../lib/playwright'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'screenshot',\n description: 'Take a Playwright screenshot, installing Chromium on demand',\n },\n args: {\n url: {\n type: 'positional',\n description: 'URL to capture, for example http://localhost:5173/',\n required: true,\n },\n output: {\n type: 'positional',\n description: 'Output image path, for example screenshot.png',\n required: true,\n },\n 'full-page': {\n type: 'boolean',\n description: 'Capture the full scrollable page',\n required: false,\n },\n 'wait-for-timeout': {\n type: 'string',\n description: 'Milliseconds to wait before capture',\n required: false,\n },\n },\n async run({ args }) {\n const appDir = resolve('.')\n ensurePlaywright(appDir)\n\n const url = String(args.url)\n const output = String(args.output)\n const playwrightArgs = ['playwright', 'screenshot', url, output]\n if (args['full-page']) playwrightArgs.push('--full-page')\n if (args['wait-for-timeout']) {\n playwrightArgs.push('--wait-for-timeout', String(args['wait-for-timeout']))\n }\n\n const result = spawnSync('npx', playwrightArgs, {\n cwd: appDir,\n stdio: 'inherit',\n })\n\n // Playwright already printed the reason; the refusal adds the slug an\n // agent branches on. Its own exit code collapses to 1 — the contract\n // reserves 0/1/2, and playwright only ever means \"failed\" here.\n if (result.status !== 0) {\n throw new Refusal(\n `Screenshot failed: playwright exited ${result.status ?? 'without a status'}.`,\n 'screenshot_failed',\n )\n }\n\n return { data: { url, output, fullPage: Boolean(args['full-page']) } }\n },\n})\n","/**\n * deepspace test accounts\n *\n * Manage test accounts for local development and CI.\n * Test accounts use @deepspace.test emails and are clearly\n * demarcated in the database. Max 10 per developer.\n *\n * Credentials are saved to ~/.deepspace/test-accounts.json (0600)\n * so they persist across projects and sessions.\n *\n * deepspace test accounts create --email bot@deepspace.test --password Pass123!\n * deepspace test accounts list\n * deepspace test accounts delete --email bot@deepspace.test\n * deepspace test accounts delete --id <id>\n * deepspace test accounts clear # delete all (with confirm)\n * deepspace test accounts clear --label e2e # delete only label=e2e\n * deepspace test accounts clear --yes # skip confirm (CI)\n */\n\nimport { defineCommand } from 'citty'\nimport * as p from '@clack/prompts'\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\nimport { ensureToken, SESSION_PATH } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst SESSION_COOKIE = '__Secure-better-auth.session_token'\n\nconst AUTH_URL = process.env.DEEPSPACE_AUTH_URL ?? PLATFORM_URLS.auth\nconst DIR = join(homedir(), '.deepspace')\nconst ACCOUNTS_PATH = join(DIR, 'test-accounts.json')\n\n// ── Local credential store ─────────────────────────────────────────\n\ninterface StoredAccount {\n id: string\n email: string\n password: string\n userId: string\n name?: string\n label?: string | null\n createdAt: number\n}\n\nfunction loadAccounts(): StoredAccount[] {\n if (!existsSync(ACCOUNTS_PATH)) return []\n try {\n return JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'))\n } catch {\n return []\n }\n}\n\nfunction saveAccounts(accounts: StoredAccount[]) {\n mkdirSync(DIR, { recursive: true })\n writeFileSync(ACCOUNTS_PATH, JSON.stringify(accounts, null, 2), { mode: 0o600 })\n}\n\n// ── Helpers ────────────────────────────────────────────────────────\n\nfunction sessionCookie(): string {\n const token = readFileSync(SESSION_PATH, 'utf-8').trim()\n return `${SESSION_COOKIE}=${encodeURIComponent(token)}`\n}\n\ninterface RemoteAccount {\n id: string\n email: string\n userId: string\n label: string | null\n createdAt: number\n}\n\nasync function fetchRemoteAccounts(): Promise<RemoteAccount[]> {\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts`, {\n headers: { Cookie: sessionCookie(), Origin: AUTH_URL },\n })\n const data = (await res.json().catch(() => ({}))) as {\n accounts?: RemoteAccount[]\n error?: string\n }\n if (!res.ok || !data.accounts) {\n throw new Error(data.error ?? 'Failed to list test accounts')\n }\n return data.accounts\n}\n\nasync function deleteRemote(id: string): Promise<void> {\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts/${id}`, {\n method: 'DELETE',\n headers: { Cookie: sessionCookie(), Origin: AUTH_URL },\n })\n if (!res.ok) {\n const data = (await res.json().catch(() => ({}))) as { error?: string }\n throw new Error(data.error ?? `DELETE returned ${res.status}`)\n }\n}\n\n// ── Subcommands ────────────────────────────────────────────────────\n\nconst create = defineDeepspaceCommand({\n meta: {\n name: 'create',\n description: 'Create a test account',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email (must end with @deepspace.test)',\n required: true,\n },\n password: {\n type: 'string',\n description: 'Password (min 8 characters)',\n required: true,\n },\n name: {\n type: 'string',\n description: 'Display name',\n required: false,\n },\n label: {\n type: 'string',\n description: 'Label for this test account',\n required: false,\n },\n },\n async run({ args }) {\n await ensureToken()\n\n const res = await fetch(`${AUTH_URL}/api/auth/test-accounts`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Cookie: sessionCookie(),\n Origin: AUTH_URL,\n },\n body: JSON.stringify({\n email: args.email,\n password: args.password,\n name: args.name,\n label: args.label,\n }),\n })\n\n const data = (await res.json().catch(() => ({}))) as {\n id?: string\n email?: string\n userId?: string\n label?: string | null\n createdAt?: number\n error?: string\n }\n\n if (!res.ok || !data.id) {\n throw new Refusal(`Failed: ${data.error ?? 'Unknown error'}`, 'test_account_create_failed')\n }\n\n const account = data as {\n id: string\n email: string\n userId: string\n label: string | null\n createdAt: number\n }\n\n // Save credentials locally\n const accounts = loadAccounts()\n accounts.push({\n id: account.id,\n email: args.email as string,\n password: args.password as string,\n userId: account.userId,\n name: args.name as string | undefined,\n label: account.label,\n createdAt: account.createdAt,\n })\n saveAccounts(accounts)\n\n if (!args.json) {\n console.log(`Created test account:`)\n console.log(` ID: ${account.id}`)\n console.log(` Email: ${account.email}`)\n console.log(` Password: ${args.password}`)\n console.log(` UserID: ${account.userId}`)\n if (account.label) console.log(` Label: ${account.label}`)\n console.log(`\\nSaved to ${ACCOUNTS_PATH}`)\n }\n\n return {\n data: {\n id: account.id,\n email: account.email,\n // The password is already echoed on the human path and stored 0600 in\n // ACCOUNTS_PATH — withholding it from --json would only force scripts\n // to parse the file themselves.\n password: args.password,\n userId: account.userId,\n label: account.label ?? null,\n createdAt: account.createdAt,\n savedTo: ACCOUNTS_PATH,\n },\n }\n },\n})\n\nconst list = defineDeepspaceCommand({\n meta: {\n name: 'list',\n description: 'List your test accounts',\n },\n async run({ args }) {\n await ensureToken()\n\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n throw new Refusal(`Failed: ${(err as Error).message}`, 'test_accounts_list_failed')\n }\n\n // Merge with local credentials (passwords are only stored locally)\n const local = loadAccounts()\n const localByEmail = new Map(local.map((a) => [a.email, a]))\n\n if (remote.length === 0) {\n if (!args.json) {\n console.log(\n 'No test accounts. Create one with: deepspace test accounts create --email <email> --password <password>',\n )\n }\n return { data: { accounts: [], count: 0, limit: 10 } }\n }\n\n if (!args.json) {\n console.log(`Test accounts (${remote.length}/10):\\n`)\n for (const a of remote) {\n const stored = localByEmail.get(a.email)\n const date = new Date(a.createdAt).toLocaleDateString()\n console.log(` ${a.email}${a.label ? ` (${a.label})` : ''}`)\n console.log(` ID: ${a.id} UserID: ${a.userId} Created: ${date}`)\n if (stored?.password) {\n console.log(` Password: ${stored.password}`)\n } else {\n console.log(` Password: (not saved locally)`)\n }\n }\n }\n\n return {\n data: {\n accounts: remote.map((a) => ({\n id: a.id,\n email: a.email,\n userId: a.userId,\n label: a.label,\n createdAt: a.createdAt,\n password: localByEmail.get(a.email)?.password ?? null,\n })),\n count: remote.length,\n limit: 10,\n },\n }\n },\n})\n\nconst del = defineDeepspaceCommand({\n meta: {\n name: 'delete',\n description: 'Delete a test account by --email or --id',\n },\n args: {\n email: {\n type: 'string',\n description: 'Email of the test account to delete',\n required: false,\n },\n id: {\n type: 'string',\n description: 'ID of the test account to delete',\n required: false,\n },\n },\n async run({ args }) {\n if (!args.email && !args.id) {\n throw new Refusal('Provide --email <email> or --id <id>.', 'missing_argument')\n }\n if (args.email && args.id) {\n throw new Refusal('Provide either --email or --id, not both.', 'conflicting_arguments')\n }\n\n await ensureToken()\n\n let targetId = args.id as string | undefined\n const targetEmail = args.email as string | undefined\n\n if (targetEmail && !targetId) {\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n throw new Refusal(`Failed: ${(err as Error).message}`, 'test_accounts_list_failed')\n }\n const match = remote.find((a) => a.email === targetEmail)\n if (!match) {\n throw new Refusal(`No test account with email ${targetEmail}.`, 'test_account_not_found', {\n action: cliAction('deepspace', 'test', 'accounts', 'list'),\n })\n }\n targetId = match.id\n }\n\n try {\n await deleteRemote(targetId!)\n } catch (err) {\n throw new Refusal(`Failed: ${(err as Error).message}`, 'test_account_delete_failed')\n }\n\n // Remove from local store\n const accounts = loadAccounts().filter(\n (a) => a.id !== targetId && (!targetEmail || a.email !== targetEmail),\n )\n saveAccounts(accounts)\n\n if (!args.json) {\n console.log(`Test account deleted${targetEmail ? `: ${targetEmail}` : `: ${targetId}`}`)\n }\n return { data: { deleted: true, id: targetId ?? null, email: targetEmail ?? null } }\n },\n})\n\nconst clear = defineDeepspaceCommand({\n meta: {\n name: 'clear',\n description: 'Delete all your test accounts (or those matching --label)',\n },\n args: {\n label: {\n type: 'string',\n description: 'Only delete accounts with this label (e.g. e2e, slack-clone)',\n required: false,\n },\n yes: {\n type: 'boolean',\n description: 'Skip confirmation prompt (for CI scripts)',\n default: false,\n },\n },\n async run({ args }) {\n const label = args.label as string | undefined\n await ensureToken()\n\n let remote: RemoteAccount[]\n try {\n remote = await fetchRemoteAccounts()\n } catch (err) {\n throw new Refusal(`Failed: ${(err as Error).message}`, 'test_accounts_list_failed')\n }\n\n const targets = label ? remote.filter((a) => a.label === label) : remote\n\n if (targets.length === 0) {\n const suffix = label ? ` with label '${label}'` : ''\n if (!args.json) console.log(`No test accounts${suffix} to delete.`)\n return { data: { deleted: 0, requested: 0, failures: [] } }\n }\n\n if (!args.yes) {\n // p.confirm needs a TTY it can prompt on. A `--json` caller is a script by\n // definition, so prompting would block forever with nothing on stdout —\n // refuse with the flag that resolves it instead of hanging.\n if (args.json) {\n throw new Refusal(\n 'Deleting test accounts needs confirmation. Pass --yes to confirm non-interactively.',\n 'confirmation_required',\n )\n }\n const subject = label\n ? `${targets.length} test account(s) labeled '${label}'`\n : `all ${targets.length} test account(s)`\n const confirmed = await p.confirm({\n message: `Delete ${subject}? This is not reversible.`,\n initialValue: false,\n })\n if (p.isCancel(confirmed) || !confirmed) {\n console.log('Cancelled.')\n return { data: { deleted: 0, requested: targets.length, cancelled: true, failures: [] } }\n }\n }\n\n let ok = 0\n const failures: Array<{ email: string; error: string }> = []\n for (const a of targets) {\n try {\n await deleteRemote(a.id)\n ok++\n } catch (err) {\n failures.push({ email: a.email, error: (err as Error).message })\n }\n }\n\n // Sync local store with what's actually deleted.\n const deletedIds = new Set(\n targets.filter((t) => !failures.find((f) => f.email === t.email)).map((t) => t.id),\n )\n saveAccounts(loadAccounts().filter((a) => !deletedIds.has(a.id)))\n\n if (failures.length > 0) {\n // A partial delete still failed overall — carry the per-account reasons\n // in the refusal so --json reports them instead of only the count.\n throw new Refusal(\n `Deleted ${ok}/${targets.length} test account(s).\\nFailed:\\n` +\n failures.map((f) => ` ${f.email}: ${f.error}`).join('\\n'),\n 'test_account_delete_failed',\n { extra: { deleted: ok, requested: targets.length, failures } },\n )\n }\n if (!args.json) console.log(`Deleted ${ok}/${targets.length} test account(s).`)\n return { data: { deleted: ok, requested: targets.length, failures: [] } }\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'test-accounts',\n description: 'Manage test accounts for development',\n },\n subCommands: {\n create,\n list,\n delete: del,\n clear,\n },\n})\n","/** Build and deploy a DeepSpace app through the platform deploy worker. */\n\nimport * as p from '@clack/prompts'\nimport { defineCommand } from 'citty'\nimport { resolve } from 'node:path'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { mintAppId, readAppId, resolveExistingAppId, writeAppId } from '../lib/app-identity'\nimport { ensureInstallReady } from '../lib/install-status'\nimport type { CliAction } from '../lib/output'\nimport { preflightNodeVersion } from '../lib/preflight'\nimport { createSpinner } from '../lib/spinner'\nimport {\n hasWranglerConfig,\n readWranglerConfig,\n resolveAppNameForEnv,\n type WranglerConfig,\n} from '../lib/wrangler-env'\nimport { buildDeployBundle } from './deploy/build'\nimport { syncOneTimeProducts, syncSubscriptionPlans } from './deploy/commerce'\nimport { createDeployOutput, type DeployOutput } from './deploy/output'\nimport { deployBuiltBundle } from './deploy/request'\nimport { syncDeployRepository } from './deploy/repository'\nimport { loadDeploySecrets, prepareDeploySecrets } from './deploy/secrets'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nexport default defineCommand({\n meta: {\n name: 'deploy',\n description: 'Build and deploy your DeepSpace app',\n },\n args: {\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description:\n 'wrangler.toml [env.<name>] block to deploy (e.g. --env staging). ' +\n 'Omit to deploy the top-level config.',\n required: false,\n },\n rename: {\n type: 'boolean',\n description:\n 'Confirm that a changed wrangler `name` renames this app (its URL moves; data, secrets, and collaborators travel). Without this flag an interactive prompt asks.',\n default: false,\n },\n 'allow-missing-secrets': {\n type: 'boolean',\n description:\n 'Deploy even though hand-edited .dev.vars secrets are absent from the store (they will NOT be deployed, and any a previous deploy set are dropped).',\n default: false,\n },\n adopt: {\n type: 'boolean',\n description:\n 'Confirm adopting an existing app you can deploy but do not own (collaborator/admin ' +\n 'on-behalf) when wrangler.toml has no DEEPSPACE_APP_ID. Without this flag an ' +\n 'interactive prompt asks.',\n default: false,\n },\n // Citty maps --no-push to the negation of an argument named `push`.\n push: {\n type: 'boolean',\n description:\n \"Sync the branch to the app's cloud repo before deploying (--no-push to skip; the \" +\n 'release then may point at source the platform cannot recover).',\n default: true,\n },\n 'ignore-stale': {\n type: 'boolean',\n description:\n 'Deploy even if someone released a newer version since you last synced (skips the ' +\n 'stale-base guard).',\n default: false,\n },\n json: {\n type: 'boolean',\n description:\n 'Emit a single-line JSON result for scripts/agents (human output goes to stderr)',\n default: false,\n },\n },\n async run({ args }) {\n const output = createDeployOutput(args.json === true)\n preflightNodeVersion('deploy')\n const appDir = resolve(args.dir ?? '.')\n\n const selectorRefusal = blankSelectorRefusal(args)\n if (selectorRefusal) output.die(selectorRefusal.error, selectorRefusal.code)\n const envName = typeof args.env === 'string' && args.env.trim() ? args.env.trim() : undefined\n\n if (!hasWranglerConfig(appDir)) {\n output.die('No wrangler.toml found. Are you in a DeepSpace app directory?', 'not_in_app_repo')\n }\n try {\n ensureInstallReady(appDir)\n } catch (error: unknown) {\n const refusal = error as { message?: string; code?: string; action?: CliAction }\n output.die(refusal.message ?? String(error), refusal.code ?? 'deps_missing', {\n action: refusal.action,\n })\n }\n\n p.intro('Deploying DeepSpace app')\n output.showIntro()\n\n const wranglerConfig: WranglerConfig = readWranglerConfig(appDir)\n const nameResult = resolveAppNameForEnv(wranglerConfig, envName)\n if (!nameResult.ok) return output.die(nameResult.reason, 'invalid_app_name')\n const declaredName = envName ? wranglerConfig.env?.[envName]?.name : wranglerConfig.name\n if (declaredName !== nameResult.name) {\n const location = envName ? `[env.${envName}].name` : '`name`'\n output.die(\n `wrangler.toml: ${location} \"${declaredName}\" is not in canonical form. ` +\n `Update it to \"${nameResult.name}\" and re-run.`,\n 'invalid_app_name',\n )\n }\n const appName = nameResult.name\n let appId = readAppId(appDir, envName)\n p.log.info(envName ? `App: ${appName} (env: ${envName})` : `App: ${appName}`)\n\n const { token, ownerId } = await authenticate(appDir, output)\n\n if (!appId) {\n const existing = await resolveExistingAppId(DEPLOY_URL, token, appName)\n if (existing.kind === 'taken') {\n output.die(\n `\"${appName}\" is taken by an app you don't have deploy access to. ` +\n 'Ask the owner to add you as a collaborator (`deepspace app collaborators add`), ' +\n 'or pick a different `name` in wrangler.toml.',\n 'name_taken',\n )\n }\n if (existing.kind === 'adopted' && !existing.owned && !args.adopt) {\n if (output.nonInteractive) {\n output.die(\n `\"${appName}\" is an existing app owned by another account that you can deploy ` +\n 'on-behalf (collaborator/admin). Confirmation needs --adopt here — ' +\n 're-run with --adopt to deploy it, or pick a different `name` in wrangler.toml ' +\n 'if you meant a new app.',\n 'confirmation_required',\n )\n }\n const confirmed = await p.confirm({\n message:\n `\"${appName}\" is an existing app owned by another account that you can deploy ` +\n 'on-behalf (you are a collaborator or admin). Deploy it? ' +\n '(Meant a new app? Pick a different `name` in wrangler.toml.)',\n })\n if (p.isCancel(confirmed) || !confirmed) {\n output.die('Deploy cancelled.', 'cancelled')\n }\n }\n appId = existing.kind === 'adopted' ? existing.appId : mintAppId()\n writeAppId(appDir, appId, { wranglerEnv: envName })\n p.log.info(\n existing.kind === 'adopted'\n ? `Adopted existing app id ${appId} for ${appName} — commit wrangler.toml.`\n : `Minted app id ${appId} — commit wrangler.toml.`,\n )\n }\n p.log.info(`Id: ${appId}`)\n\n const secretsCache = await loadDeploySecrets({\n deployUrl: DEPLOY_URL,\n appDir,\n appId,\n envName,\n ownerId,\n token,\n output,\n })\n const repository = await syncDeployRepository({\n deployUrl: DEPLOY_URL,\n appDir,\n appId,\n token,\n push: args.push !== false,\n ignoreStale: Boolean(args['ignore-stale']),\n output,\n })\n\n const spinner = createSpinner()\n const bundle = await buildDeployBundle({\n appDir,\n appName,\n envName,\n sharedDevVarsCache: secretsCache.linked !== null,\n wranglerConfig,\n output,\n spinner,\n })\n const secrets = prepareDeploySecrets({\n appDir,\n envName,\n cache: secretsCache,\n allowMissing: Boolean(args['allow-missing-secrets']),\n customBindings: bundle.customBindings,\n doManifest: bundle.doManifest,\n output,\n })\n const body = await deployBuiltBundle({\n deployUrl: DEPLOY_URL,\n appDir,\n appId,\n appName,\n token,\n rename: args.rename === true,\n ignoreStale: Boolean(args['ignore-stale']),\n bundle,\n secrets,\n repository,\n output,\n spinner,\n })\n\n if (body.url) {\n spinner.message('Waiting for edge propagation...')\n const ready = await waitForAssetsReady(body.url, 90_000)\n if (!ready) {\n spinner.stop('Deployed (edge propagation still in progress after 90s)')\n p.log.warn(\n 'First requests may briefly hit the assets transitional page; retry in a minute.',\n )\n p.log.info(`URL: ${body.url} (deploy accepted; serving not yet verified from here)`)\n await syncCommerce(appDir, appId, token, output.nonInteractive)\n if (output.json) {\n return output.emitJson({\n ok: true,\n appId,\n appName,\n url: body.url,\n releaseId: body.releaseId ?? null,\n bundleRetained: body.bundleRetained ?? null,\n edgePropagating: true,\n recoverable: repository.recoverable,\n ...staleBaseGuardFields(body),\n })\n }\n p.outro('Done')\n return\n }\n }\n\n spinner.stop('Deployed!')\n p.log.success(`Live at: ${body.url}`)\n await syncCommerce(appDir, appId, token, output.nonInteractive)\n if (output.json) {\n return output.emitJson({\n ok: true,\n appId,\n appName,\n url: body.url ?? null,\n releaseId: body.releaseId ?? null,\n bundleRetained: body.bundleRetained ?? null,\n recoverable: repository.recoverable,\n ...staleBaseGuardFields(body),\n })\n }\n p.outro('Done')\n },\n})\n\nasync function syncCommerce(\n appDir: string,\n appId: string,\n token: string,\n nonInteractive: boolean,\n): Promise<void> {\n await syncSubscriptionPlans(appDir, appId, token, nonInteractive)\n await syncOneTimeProducts(appDir, appId, token)\n}\n\n/** Refuse explicit blank selectors before auth so they cannot fall back to production/cwd. */\nexport function blankSelectorRefusal(args: {\n dir?: unknown\n env?: unknown\n}): { code: string; error: string } | null {\n if (args.env !== undefined && !String(args.env).trim()) {\n return {\n code: 'invalid_env',\n error:\n '--env was given an empty environment name — pass an env (e.g. --env staging), or omit --env to deploy the top-level config.',\n }\n }\n if (args.dir !== undefined && !String(args.dir).trim()) {\n return {\n code: 'invalid_dir',\n error:\n 'The app directory argument was empty — pass a directory, or omit it to deploy the current directory.',\n }\n }\n return null\n}\n\nexport function staleBaseGuardFields(body: {\n staleBaseGuard?: unknown\n}): { staleBaseGuard: 'skipped' } | Record<string, never> {\n return body.staleBaseGuard === 'skipped' ? { staleBaseGuard: 'skipped' } : {}\n}\n\n/** Wait until the new deployment is consistently serving across edge isolates. */\nasync function waitForAssetsReady(url: string, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs\n let attempt = 0\n let streak = 0\n\n while (Date.now() < deadline) {\n attempt++\n try {\n const response = await fetch(url, { redirect: 'manual' })\n const body = await response.text()\n if (!body.includes('Assets have not yet deployed') && !body.includes('No app configured')) {\n streak++\n if (streak >= 3) return true\n await new Promise((resolve) => setTimeout(resolve, 1_500))\n continue\n }\n streak = 0\n } catch {\n streak = 0\n }\n\n const waitMs = Math.min(8_000, 1_000 * 2 ** (attempt - 1))\n await new Promise((resolve) => setTimeout(resolve, waitMs))\n }\n return false\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nasync function authenticate(\n appDir: string,\n output: DeployOutput,\n): Promise<{ token: string; ownerId: string }> {\n try {\n const token = await ensureToken()\n return { token, ownerId: decodeJwtPayload<{ sub: string }>(token).sub }\n } catch (error: unknown) {\n output.die(errorMessage(error), 'not_authenticated', {\n action: { cwd: appDir, argv: ['deepspace', 'auth', 'login'] },\n })\n }\n}\n","import * as p from '@clack/prompts'\nimport { execSync } from 'node:child_process'\nimport { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport {\n bindingManifestFromOutputConfig,\n validateBindingManifest,\n type CustomBindingManifest,\n} from '../../../server/rooms/binding-manifest'\nimport { removeMacosJunk } from '../../lib/macos-junk'\nimport { formatSchemaLintFindings, lintProjectSchemas } from '../../lib/schema-lint'\nimport type { Spinner } from '../../lib/spinner'\nimport {\n prepareWranglerEnvConfig,\n wranglerViteEnv,\n type PreparedWranglerEnvConfig,\n type WranglerConfig,\n} from '../../lib/wrangler-env'\nimport type { DeployOutput } from './output'\n\nconst RESERVED_RUN_WORKER_FIRST = new Set([\n '/api/*',\n '/ws/*',\n '/internal/*',\n '/v1/*',\n '/_deepspace/*',\n])\n\nexport interface DeployAsset {\n path: string\n contentBase64: string\n}\n\nexport interface DurableObjectManifestEntry {\n binding: string\n className: string\n sqlite: boolean\n}\n\nexport interface DeployBundle {\n assets: DeployAsset[]\n workerJs: string\n doManifest: DurableObjectManifestEntry[] | undefined\n customBindings: CustomBindingManifest\n extraRoutes: string[]\n}\n\ninterface OutputWranglerConfig extends Record<string, unknown> {\n name?: string\n main: string\n assets?: { directory: string }\n durable_objects?: { bindings: Array<{ name: string; class_name: string }> }\n migrations?: Array<{ new_sqlite_classes?: string[] }>\n}\n\nexport async function buildDeployBundle(options: {\n appDir: string\n appName: string\n envName: string | undefined\n sharedDevVarsCache: boolean\n wranglerConfig: WranglerConfig\n output: DeployOutput\n spinner: Spinner\n}): Promise<DeployBundle> {\n const { appDir, appName, envName, sharedDevVarsCache, wranglerConfig, output, spinner } = options\n const junk = removeMacosJunk(appDir)\n if (junk > 0) p.log.info(`Removed ${junk} macOS metadata file(s) (._*, .DS_Store)`)\n\n const lintFindings = await lintProjectSchemas(appDir)\n if (lintFindings && lintFindings.length > 0) {\n p.log.warn(formatSchemaLintFindings(lintFindings).join('\\n'))\n }\n\n spinner.start('Building...')\n let preparedWranglerConfig: PreparedWranglerEnvConfig | undefined\n try {\n preparedWranglerConfig = prepareWranglerEnvConfig(appDir, envName, {\n sharedDevVarsCache,\n })\n execSync('npx vite build', {\n cwd: appDir,\n stdio: 'pipe',\n env: wranglerViteEnv(process.env, preparedWranglerConfig),\n })\n } catch (error: unknown) {\n spinner.stop('Build failed')\n const execError = error as {\n stdout?: { toString(): string }\n stderr?: { toString(): string }\n }\n const detail = [execError.stdout?.toString(), execError.stderr?.toString()]\n .filter(Boolean)\n .join('\\n')\n .trim()\n output.die(detail || errorMessage(error), 'build_failed')\n } finally {\n preparedWranglerConfig?.cleanup()\n }\n spinner.stop('Built')\n\n const deployConfigPath = join(appDir, '.wrangler', 'deploy', 'config.json')\n if (!existsSync(deployConfigPath)) {\n output.die(\n 'Build output config not found at .wrangler/deploy/config.json',\n 'build_output_missing',\n )\n }\n\n const deployConfig = JSON.parse(readFileSync(deployConfigPath, 'utf-8')) as {\n configPath: string\n }\n const outputWranglerPath = resolve(dirname(deployConfigPath), deployConfig.configPath)\n if (!existsSync(outputWranglerPath)) {\n output.die(`Output wrangler.json not found at ${outputWranglerPath}`, 'build_output_missing')\n }\n\n const outputConfig = JSON.parse(readFileSync(outputWranglerPath, 'utf-8')) as OutputWranglerConfig\n if (outputConfig.name && outputConfig.name !== appName) {\n const envHint = envName ? ` (--env ${envName})` : ''\n output.die(\n `Build output mismatch: expected name \"${appName}\"${envHint}, ` +\n `but the built wrangler.json declares \"${outputConfig.name}\". ` +\n `This usually means the Cloudflare Vite plugin didn't apply ` +\n `DeepSpace's generated env config. Check the plugin version and re-run.`,\n 'build_output_mismatch',\n )\n }\n\n const workerDir = dirname(outputWranglerPath)\n const workerBundlePath = join(workerDir, outputConfig.main)\n const clientDir = outputConfig.assets?.directory\n ? resolve(workerDir, outputConfig.assets.directory)\n : null\n if (!existsSync(workerBundlePath)) {\n output.die(`Worker bundle not found at ${workerBundlePath}`, 'build_output_missing')\n }\n if (!clientDir || !existsSync(clientDir)) {\n return output.die(`Client assets not found at ${clientDir}`, 'build_output_missing')\n }\n\n spinner.start('Collecting assets...')\n const assets = collectAssets(clientDir)\n spinner.stop(`Collected ${assets.length} assets`)\n const workerJs = readFileSync(workerBundlePath, 'utf-8')\n\n const doBindings = outputConfig.durable_objects?.bindings\n const sqliteClasses = new Set(\n outputConfig.migrations?.flatMap((migration) => migration.new_sqlite_classes ?? []) ?? [],\n )\n const doManifest = doBindings?.map((binding) => ({\n binding: binding.name,\n className: binding.class_name,\n sqlite: sqliteClasses.has(binding.class_name),\n }))\n if (doManifest?.length) p.log.info(`DO manifest: ${doManifest.length} binding(s)`)\n\n const customBindings = bindingManifestFromOutputConfig(outputConfig)\n const validation = validateBindingManifest(customBindings)\n if (!validation.valid) {\n output.die(\n `Invalid binding(s) in wrangler.toml:\\n` +\n validation.errors.map((error) => ` • ${error.reason}`).join('\\n'),\n 'invalid_bindings',\n )\n }\n if (customBindings.length) {\n p.log.info(\n `Custom bindings: ${customBindings.map((binding) => `${binding.name} (${binding.type})`).join(', ')}`,\n )\n }\n\n const extraRoutes = extractRunWorkerFirst(wranglerConfig)\n\n return {\n assets,\n workerJs,\n doManifest,\n customBindings,\n extraRoutes,\n }\n}\n\nfunction extractRunWorkerFirst(config: WranglerConfig): string[] {\n const raw = config.assets?.run_worker_first\n if (!Array.isArray(raw)) return []\n\n const routes: string[] = []\n const seen = new Set<string>()\n for (const entry of raw) {\n if (typeof entry !== 'string') continue\n const route = entry.trim()\n if (!route.startsWith('/') || RESERVED_RUN_WORKER_FIRST.has(route) || seen.has(route)) continue\n seen.add(route)\n routes.push(route)\n }\n return routes\n}\n\nfunction collectAssets(dir: string): DeployAsset[] {\n const assets: DeployAsset[] = []\n const walk = (currentDir: string, prefix: string): void => {\n for (const entry of readdirSync(currentDir, { withFileTypes: true })) {\n if (entry.name === '.assetsignore') continue\n const fullPath = join(currentDir, entry.name)\n const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n walk(fullPath, relativePath)\n } else {\n assets.push({\n path: `/${relativePath}`,\n contentBase64: readFileSync(fullPath).toString('base64'),\n })\n }\n }\n }\n walk(dir, '')\n return assets\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import * as p from '@clack/prompts'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { PLATFORM_URLS } from '../../env'\nimport { createSpinner } from '../../lib/spinner'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\ninterface PlanChange {\n slug: string\n reason: 'removed' | 'repriced'\n affectedSubscribers: number\n intervals?: Array<{ interval: 'month' | 'year'; oldCents: number; newCents: number }>\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nasync function loadDeclaration(\n appDir: string,\n sourceFile: string,\n outputFile: string,\n exportName: string,\n): Promise<unknown> {\n const sourcePath = join(appDir, 'src', sourceFile)\n if (!existsSync(sourcePath)) return undefined\n const esbuild = await import('esbuild')\n const outputPath = join(appDir, '.wrangler', 'deploy', outputFile)\n await esbuild.build({\n entryPoints: [sourcePath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'node18',\n outfile: outputPath,\n logLevel: 'silent',\n write: true,\n })\n const module = (await import(`${pathToFileURL(outputPath).href}?t=${Date.now()}`)) as Record<\n string,\n unknown\n >\n return module[exportName]\n}\n\nfunction formatCents(cents: number): string {\n return cents === 0 ? 'free' : `$${(cents / 100).toFixed(2)}`\n}\n\nfunction planChangeSummary(change: PlanChange): string {\n const count = `${change.affectedSubscribers} subscriber${change.affectedSubscribers === 1 ? '' : 's'}`\n if (change.reason === 'removed') return ` • ${change.slug} — removed (${count} still on it)`\n const diffs = (change.intervals ?? [])\n .map(\n (interval) =>\n `${interval.interval}: ${formatCents(interval.oldCents)} → ${formatCents(interval.newCents)}`,\n )\n .join('; ')\n return ` • ${change.slug} — repriced (${diffs}; ${count} grandfathered on old price)`\n}\n\nasync function cancelChangedPlans(appName: string, token: string, changes: PlanChange[]) {\n p.log.warn(\n `Plan change${changes.length === 1 ? '' : 's'} from this deploy left subscribers stranded:\\n` +\n `${changes.map(planChangeSummary).join('\\n')}\\n\\n` +\n 'Stripe will keep charging them until you cancel. Cancel at the end of their current billing period?',\n )\n const confirmed = await p.confirm({\n message: `Cancel ${changes.length === 1 ? 'these subscribers' : 'all of them'} at period end?`,\n initialValue: false,\n })\n if (p.isCancel(confirmed) || !confirmed) {\n p.log.info('Skipped — existing subscribers stay on their current plan/price.')\n return\n }\n\n const maxIterations = 100\n for (const change of changes) {\n const spinner = createSpinner()\n spinner.start(\n `Canceling ${change.affectedSubscribers} subscriber${change.affectedSubscribers === 1 ? '' : 's'} on ${change.slug}...`,\n )\n let canceled = 0\n let failed = 0\n let iteration = 0\n let lastError: string | null = null\n let stopped = false\n try {\n while (iteration < maxIterations) {\n const response = await fetch(`${API_URL}/api/subscriptions/admin-cancel`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n appName,\n planSlug: change.slug,\n atPeriodEnd: true,\n reason: `plan ${change.reason} via deploy`,\n }),\n })\n const body = (await response.json().catch(() => ({}))) as {\n success?: boolean\n canceled?: number\n failures?: unknown[]\n hasMore?: boolean\n error?: string\n }\n if (!response.ok || !body.success) {\n lastError = body.error ?? `HTTP ${response.status}`\n spinner.stop(`Cancel failed for ${change.slug}: ${lastError}`)\n stopped = true\n break\n }\n const batchCanceled = body.canceled ?? 0\n canceled += batchCanceled\n failed += body.failures?.length ?? 0\n if (!body.hasMore) break\n if (batchCanceled === 0) {\n lastError = 'no progress (all rows failed this batch)'\n break\n }\n iteration++\n }\n if (!stopped) {\n const failureSuffix = failed ? `; ${failed} failed (see Stripe)` : ''\n const capSuffix = iteration >= maxIterations ? ' (batch cap reached — re-run deploy)' : ''\n spinner.stop(\n `Canceled ${canceled} on ${change.slug}${failureSuffix}${capSuffix}${lastError ? ` — ${lastError}` : ''}`,\n )\n }\n } catch (error) {\n spinner.stop(`Cancel failed for ${change.slug}: ${errorMessage(error)}`)\n }\n }\n}\n\nexport async function syncSubscriptionPlans(\n appDir: string,\n appName: string,\n token: string,\n nonInteractive: boolean,\n): Promise<void> {\n if (!existsSync(join(appDir, 'src', 'subscriptions.ts'))) return\n let plans: unknown\n try {\n plans = await loadDeclaration(\n appDir,\n 'subscriptions.ts',\n 'subscriptions.bundle.mjs',\n 'subscriptionPlans',\n )\n } catch (error) {\n p.log.warn(`Could not load src/subscriptions.ts: ${errorMessage(error)}`)\n return\n }\n if (!Array.isArray(plans)) {\n p.log.warn('src/subscriptions.ts must `export const subscriptionPlans = [...] as const`')\n return\n }\n if (!plans.length) return\n\n const spinner = createSpinner()\n spinner.start('Syncing subscription plans...')\n try {\n const response = await fetch(`${API_URL}/api/subscriptions/sync`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify({ appId: appName, plans }),\n })\n const body = (await response.json().catch(() => ({}))) as {\n ok?: boolean\n error?: string\n hint?: string\n planChanges?: PlanChange[]\n connectMissing?: boolean\n }\n if (!response.ok || !body.ok) {\n spinner.stop('Plan sync skipped')\n p.log.warn(\n `Plan sync failed: ${body.error ?? `HTTP ${response.status}`}${body.hint ? ` — ${body.hint}` : ''}`,\n )\n return\n }\n spinner.stop(`Synced ${plans.length} plan${plans.length === 1 ? '' : 's'} to Stripe`)\n if (body.connectMissing) {\n p.log.warn(\n 'Stripe Connect not yet set up. Customers can subscribe and earnings ' +\n 'will queue in your platform balance until you finish onboarding at ' +\n '/earnings on the dashboard. The first payout after you connect ' +\n 'will sweep everything that accumulated in the meantime.',\n )\n }\n const changes = (body.planChanges ?? []).filter((change) => change.affectedSubscribers > 0)\n if (!changes.length) return\n if (nonInteractive) {\n p.log.warn(\n `${changes.length} plan change${changes.length === 1 ? '' : 's'} left subscribers stranded; ` +\n 'grandfathered (non-interactive deploy). Cancel later via the subscriptions admin helper if intended.',\n )\n return\n }\n await cancelChangedPlans(appName, token, changes)\n } catch (error) {\n spinner.stop('Plan sync skipped')\n p.log.warn(`Plan sync request failed: ${errorMessage(error)}`)\n }\n}\n\nexport async function syncOneTimeProducts(\n appDir: string,\n appName: string,\n token: string,\n): Promise<void> {\n if (!existsSync(join(appDir, 'src', 'products.ts'))) return\n let products: unknown\n try {\n products = await loadDeclaration(\n appDir,\n 'products.ts',\n 'products.bundle.mjs',\n 'oneTimeProducts',\n )\n } catch (error) {\n p.log.warn(`Could not load src/products.ts: ${errorMessage(error)}`)\n return\n }\n if (!Array.isArray(products)) {\n p.log.warn('src/products.ts must `export const oneTimeProducts = [...] as const`')\n return\n }\n\n const spinner = products.length ? createSpinner() : null\n spinner?.start('Syncing one-time products...')\n try {\n const response = await fetch(`${API_URL}/api/charges/products/sync`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify({ appId: appName, products }),\n })\n const body = (await response.json().catch(() => ({}))) as {\n ok?: boolean\n count?: number\n error?: string\n details?: unknown\n }\n if (response.ok && body.ok) {\n const count = body.count ?? products.length\n spinner?.stop(`Synced ${count} one-time product${count === 1 ? '' : 's'}`)\n return\n }\n spinner?.stop('Product sync skipped')\n p.log.warn(\n `Product sync failed: ${body.error ?? `HTTP ${response.status}`}${body.details ? ` — ${JSON.stringify(body.details)}` : ''}`,\n )\n } catch (error) {\n spinner?.stop('Product sync skipped')\n p.log.warn(`Product sync request failed: ${errorMessage(error)}`)\n }\n}\n","import * as p from '@clack/prompts'\nimport { printAction, withSlug, type CliAction } from '../../lib/output'\n\nexport interface DeployOutput {\n readonly json: boolean\n readonly nonInteractive: boolean\n emitJson(value: unknown): void\n showIntro(): void\n die(message: string, code: string, opts?: { action?: CliAction; actionRequired?: boolean }): never\n}\n\n/** Owns deploy's human/JSON output contract and its single pre-upload exit door. */\nexport function createDeployOutput(json: boolean): DeployOutput {\n const nonInteractive = json || !process.stdin.isTTY\n const realStdoutWrite = process.stdout.write.bind(process.stdout)\n let emitted = false\n let introShown = false\n let lastHuman = ''\n\n if (json) {\n process.stdout.write = ((chunk: unknown, ...rest: unknown[]): boolean => {\n const text = typeof chunk === 'string' ? chunk : String(chunk ?? '')\n const ansiSgr = new RegExp(`${String.fromCodePoint(27)}\\\\[[0-9;]*m`, 'g')\n const line = text\n .replace(ansiSgr, '')\n .replace(/[│◇◆■└┌]/g, '')\n .trim()\n if (line) lastHuman = line\n return (process.stderr.write as (...args: unknown[]) => boolean)(chunk, ...rest)\n }) as typeof process.stdout.write\n\n process.on('exit', (code) => {\n if (emitted || code === 0) return\n process.stdout.write = realStdoutWrite\n realStdoutWrite(\n `${JSON.stringify({ ok: false, code: 'deploy_failed', error: lastHuman || 'deploy failed' })}\\n`,\n )\n })\n }\n\n const emitJson = (value: unknown): void => {\n emitted = true\n process.stdout.write = realStdoutWrite\n realStdoutWrite(`${JSON.stringify(value)}\\n`)\n }\n\n return {\n json,\n nonInteractive,\n emitJson,\n showIntro() {\n introShown = true\n },\n die(message, code, opts = {}) {\n if (json) {\n emitJson({\n ok: false,\n code,\n error: message,\n ...(opts.actionRequired ? { actionRequired: true } : {}),\n ...(opts.action ? { action: opts.action } : {}),\n })\n } else {\n if (introShown && opts.actionRequired) p.log.warn(withSlug(message, code))\n else if (introShown) p.cancel(withSlug(message, code))\n else console.error(withSlug(message, code))\n if (opts.action) printAction(opts.action)\n }\n process.exit(opts.actionRequired ? 2 : 1)\n },\n }\n}\n","import * as p from '@clack/prompts'\nimport { randomUUID } from 'node:crypto'\nimport { printAction, withSlug, type CliAction } from '../../lib/output'\nimport type { Spinner } from '../../lib/spinner'\nimport type { DeployBundle } from './build'\nimport type { DeployOutput } from './output'\nimport { shouldSendLineage, type DeployRepositoryState } from './repository'\nimport type { DeploySecretsPayload } from './secrets'\n\nconst CLOUDFLARE_DEPLOY_ERROR_HINT =\n \"Deployment reached the DeepSpace deploy worker, but Cloudflare's deployment \" +\n 'control-plane API failed. This is often caused by a Cloudflare Dashboard/API ' +\n 'incident or Workers for Platforms entitlement outage. Already deployed apps ' +\n 'should keep serving; wait for Cloudflare to recover and retry.'\n\nconst MAX_GROUP_BYTES = 40 * 1024 * 1024\nconst GROUP_BYTES = (() => {\n const configured = Number(process.env.DEEPSPACE_DEPLOY_GROUP_BYTES)\n const bytes = Number.isInteger(configured) && configured > 0 ? configured : 3 * 1024 * 1024\n return Math.min(bytes, MAX_GROUP_BYTES)\n})()\n\nexport interface DeployCommitResponse {\n success?: boolean\n url?: string\n error?: string\n code?: string\n fromHost?: string\n toHost?: string\n onBehalfOfOwner?: string\n staleBaseGuard?: string\n releaseId?: string\n bundleRetained?: boolean\n}\n\nexport async function deployBuiltBundle(options: {\n deployUrl: string\n appDir: string\n appId: string\n appName: string\n token: string\n rename: boolean\n ignoreStale: boolean\n bundle: DeployBundle\n secrets: DeploySecretsPayload\n repository: DeployRepositoryState\n output: DeployOutput\n spinner: Spinner\n}): Promise<DeployCommitResponse> {\n const {\n deployUrl,\n appDir,\n appId,\n appName,\n token,\n ignoreStale,\n bundle,\n secrets,\n repository,\n output,\n spinner,\n } = options\n\n spinner.start(`Deploying ${appName}...`)\n if (bundle.extraRoutes.length) {\n p.log.info(`Custom worker-first routes: ${bundle.extraRoutes.join(', ')}`)\n }\n const assetGroups = packAssetGroups(bundle.assets, GROUP_BYTES)\n if (assetGroups.length === 0) assetGroups.push([])\n const uploadId = randomUUID()\n const totalGroups = assetGroups.length\n try {\n for (let index = 0; index < totalGroups; index++) {\n const groupJson = JSON.stringify(assetGroups[index])\n spinner.message(`Uploading assets — group ${index + 1}/${totalGroups}...`)\n const groupResponse = await postWithRetry(\n `${deployUrl}/api/deploy/${appId}/assets` +\n `?uploadId=${uploadId}&groupIndex=${index}&totalGroups=${totalGroups}`,\n () => ({\n method: 'POST',\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n },\n body: groupJson,\n }),\n )\n if (!groupResponse.ok) {\n const errorBody = (await groupResponse.json().catch(() => ({}))) as { error?: string }\n await abortStagedUpload(deployUrl, appId, uploadId, totalGroups, token)\n spinner.stop('Deploy failed')\n output.die(\n `Asset upload failed on group ${index + 1}/${totalGroups}: ` +\n `${errorBody.error ?? `HTTP ${groupResponse.status}`}`,\n 'upload_failed',\n )\n }\n }\n } catch (error: unknown) {\n await abortStagedUpload(deployUrl, appId, uploadId, totalGroups, token)\n spinner.stop('Deploy failed')\n output.die(`Asset upload failed (network): ${errorMessage(error)}`, 'upload_failed')\n }\n spinner.message(`Deploying ${appName}...`)\n\n let confirmRename = options.rename\n const bail = async (\n message: string,\n stopLabel: string | null = 'Deploy failed',\n code?: string,\n actionRequired = false,\n action?: CliAction,\n ): Promise<never> => {\n await abortStagedUpload(deployUrl, appId, uploadId, totalGroups, token)\n if (stopLabel !== null) spinner.stop(stopLabel)\n p.cancel(code ? withSlug(message, code) : message)\n if (action) printAction(action)\n if (output.json) {\n output.emitJson({\n ok: false,\n ...(actionRequired ? { actionRequired: true } : {}),\n error: message,\n ...(code ? { code } : {}),\n ...(action ? { action } : {}),\n })\n }\n process.exit(actionRequired ? 2 : 1)\n }\n\n const makeForm = (): FormData => {\n const form = new FormData()\n form.append(\n 'worker',\n new Blob([bundle.workerJs], { type: 'application/javascript' }),\n 'worker.js',\n )\n form.append('uploadId', uploadId)\n form.append('totalGroups', String(totalGroups))\n if (bundle.doManifest) form.append('doManifest', JSON.stringify(bundle.doManifest))\n if (bundle.customBindings.length) {\n form.append('bindingManifest', JSON.stringify(bundle.customBindings))\n }\n if (secrets.names.length) form.append('userSecrets', JSON.stringify(secrets.values))\n if (bundle.extraRoutes.length) {\n form.append('extraRunWorkerFirst', JSON.stringify(bundle.extraRoutes))\n }\n form.append('name', appName)\n if (confirmRename) form.append('confirmRename', 'true')\n if (shouldSendLineage(repository.commitOid, repository.recoverable)) {\n form.append('commitOid', repository.commitOid as string)\n }\n if (ignoreStale) form.append('ignoreStale', 'true')\n form.append('deployKey', repository.deployKey)\n return form\n }\n\n const postCommit = async (): Promise<Response> =>\n postWithRetry(\n `${deployUrl}/api/deploy/${appId}`,\n () => ({\n method: 'POST',\n headers: { Authorization: `Bearer ${token}` },\n body: makeForm(),\n }),\n { retryServerErrors: false },\n )\n\n let response: Response\n try {\n response = await postCommit()\n } catch (error: unknown) {\n await bail(\n `Deploy request failed: ${errorMessage(error)}`,\n 'Deploy failed',\n 'deploy_request_failed',\n )\n throw error\n }\n\n let body = (await response.json().catch(() => ({}))) as DeployCommitResponse\n for (\n let attempt = 0;\n response.status === 503 && body.code === 'release_finalization_pending' && attempt < 3;\n attempt++\n ) {\n await new Promise((resolve) => setTimeout(resolve, 250 * 2 ** attempt))\n response = await postCommit()\n body = (await response.json().catch(() => ({}))) as DeployCommitResponse\n }\n\n if (response.status === 409 && body.code === 'rename_required' && !confirmRename) {\n spinner.stop('Rename confirmation needed')\n if (output.nonInteractive) {\n await bail(\n `This deploy renames the app: ${body.fromHost} → ${body.toHost}. ` +\n 'Confirmation needs an interactive terminal — re-run with --rename to approve the ' +\n 'rename, or `deepspace app init --new-id` if you meant a separate app.',\n null,\n 'rename_required',\n )\n }\n const confirmed = await p.confirm({\n message:\n `This deploy renames the app: ${body.fromHost} → ${body.toHost}. ` +\n `The URL changes and the old one stops serving right away; data, secrets, and collaborators travel with it. ` +\n '(Meant a separate app? Run `deepspace app init --new-id` instead.) Rename?',\n })\n if (p.isCancel(confirmed) || !confirmed) await bail('Deploy cancelled.', null)\n\n confirmRename = true\n spinner.start(`Deploying ${appName}...`)\n response = await postCommit()\n body = (await response.json().catch(() => ({}))) as DeployCommitResponse\n }\n\n if (response.status === 409 && body.code === 'stale_base') {\n await bail(\n body.error ??\n 'A newer release landed while you worked — pull, integrate, and redeploy (or --ignore-stale).',\n 'Deploy failed',\n 'stale_base',\n true,\n { cwd: appDir, argv: ['deepspace', 'pull'] },\n )\n }\n if (!response.ok || !body.success) {\n await bail(formatDeployWorkerError(response.status, body.error), 'Deploy failed', body.code)\n }\n\n if (body.onBehalfOfOwner) {\n p.log.warn(`Deployed on behalf of owner ${body.onBehalfOfOwner}`)\n }\n if (body.staleBaseGuard === 'skipped') {\n p.log.warn(\n 'The stale-base guard was skipped (repo store unavailable) — this deploy was NOT ' +\n \"checked against the live release. Verify you're not clobbering newer work.\",\n )\n }\n if (body.bundleRetained === false) {\n p.log.warn(\n 'This deploy is live, but its rollback bundle was not retained because the app storage quota is full.',\n )\n }\n return body\n}\n\nasync function abortStagedUpload(\n deployUrl: string,\n appId: string,\n uploadId: string,\n totalGroups: number,\n token: string,\n): Promise<void> {\n try {\n await fetch(\n `${deployUrl}/api/deploy/${appId}/assets` +\n `?uploadId=${uploadId}&totalGroups=${totalGroups}`,\n { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } },\n )\n } catch {\n // Staged groups are also covered by the R2 lifecycle rule.\n }\n}\n\nfunction formatDeployWorkerError(status: number, error: string | undefined): string {\n const detail = error ?? `Deployment error (${status})`\n if (\n status < 500 &&\n ![\n 'Upload session failed',\n 'Asset upload failed',\n 'Worker deploy failed',\n 'entitlements.not_available',\n 'Internal Server Error',\n ].some((needle) => error?.includes(needle))\n ) {\n return detail\n }\n return `${CLOUDFLARE_DEPLOY_ERROR_HINT}\\n\\nUnderlying error: ${detail}`\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Pack whole asset entries into request groups under the serialized byte cap. */\nexport function packAssetGroups<T>(assets: T[], maxBytes: number): T[][] {\n const groups: T[][] = []\n let current: T[] = []\n let currentBytes = 2\n for (const asset of assets) {\n const entryBytes = Buffer.byteLength(JSON.stringify(asset), 'utf-8') + 1\n if (current.length > 0 && currentBytes + entryBytes > maxBytes) {\n groups.push(current)\n current = []\n currentBytes = 2\n }\n current.push(asset)\n currentBytes += entryBytes\n }\n if (current.length > 0) groups.push(current)\n return groups\n}\n\n/** Retry rebuilt request bodies on network failures and eligible transient responses. */\nexport async function postWithRetry(\n url: string,\n makeInit: () => RequestInit,\n {\n attempts = 4,\n retryServerErrors = true,\n }: { attempts?: number; retryServerErrors?: boolean } = {},\n): Promise<Response> {\n let lastResponse: Response | undefined\n let lastError: unknown\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n const response = await fetch(url, makeInit())\n const transient =\n retryServerErrors &&\n (response.status >= 500 || response.status === 408 || response.status === 429)\n if (!transient) return response\n lastResponse = response\n } catch (error) {\n lastError = error\n }\n if (attempt < attempts) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(8_000, 500 * 2 ** (attempt - 1))))\n }\n }\n if (lastResponse) return lastResponse\n throw lastError instanceof Error ? lastError : new Error(String(lastError))\n}\n","import * as p from '@clack/prompts'\nimport {\n assertSyncableRepo,\n currentBranch,\n isAncestor,\n isWorkTreeClean,\n resolveCommit,\n revListCount,\n} from '../../lib/git/repository'\nimport { trackedSecretFiles } from '../../lib/git/safety'\nimport { mintIdempotencyKey, repoApi, type RemoteWorkspace } from '../../lib/repo-api'\nimport { classifyPushTransportFailure, pushToSpace, type PushRefResult } from '../../lib/vc-push'\nimport { ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../../lib/vc-remote'\nimport { workspaceIdFromBranch } from '../../lib/workspace-id'\nimport { errorCode } from '../../lib/cli-errors'\nimport type { DeployOutput } from './output'\n\nexport interface DeployRepositoryState {\n commitOid: string | null\n recoverable: boolean\n deployKey: string\n}\n\nexport async function syncDeployRepository(options: {\n deployUrl: string\n appDir: string\n appId: string\n token: string\n push: boolean\n ignoreStale: boolean\n output: DeployOutput\n}): Promise<DeployRepositoryState> {\n const { deployUrl, appDir, appId, token, push, ignoreStale, output } = options\n let commitOid: string | null = null\n let recoverable = false\n const deployKey = mintIdempotencyKey()\n\n if (!push) {\n try {\n assertSyncableRepo(appDir)\n commitOid = resolveCommit(appDir, 'HEAD')\n } catch {\n // A non-repository app can still deploy; it simply has no source lineage.\n }\n return { commitOid, recoverable, deployKey }\n }\n\n try {\n assertSyncableRepo(appDir)\n ensureSpaceRemote(appDir, appId)\n const branch = currentBranch(appDir)\n const workspaceBranchId = workspaceIdFromBranch(branch)\n\n if (!isWorkTreeClean(appDir)) {\n const refusal = dirtyWorktreeRefusal(branch)\n output.die(refusal.error, refusal.code)\n }\n\n if (!branch) {\n const refusal = detachedHeadRefusal()\n output.die(refusal.error, refusal.code)\n throw new Error(refusal.error)\n }\n\n const tip = resolveCommit(appDir, `refs/heads/${branch}`)\n if (!tip) return { commitOid, recoverable, deployKey }\n\n const secretFiles = workspaceBranchId ? [] : trackedSecretFiles(appDir, tip)\n if (workspaceBranchId) {\n const { view } = await repoApi(deployUrl, token, appId).getWorkspace(workspaceBranchId)\n const lineage = workspaceDeployLineage(view.workspace.status, view.tipOid, tip)\n if (lineage === 'inactive') {\n output.die(\n `Workspace ${workspaceBranchId} is ${view.workspace.status}; deploy from trunk or create a new workspace.`,\n 'workspace_not_active',\n )\n }\n if (lineage === 'unsynced') {\n output.die(\n `Workspace ${workspaceBranchId} has unsynced commits. Publish this exact HEAD before deploying so the release keeps recoverable source lineage.`,\n 'workspace_unsynced',\n {\n action: { cwd: appDir, argv: ['deepspace', 'workspace', 'sync'] },\n actionRequired: true,\n },\n )\n }\n recoverable = true\n p.log.info(`Workspace ${workspaceBranchId} is synced at ${tip.slice(0, 10)}.`)\n } else if (secretFiles.length > 0) {\n p.log.warn(\n `Skipping cloud-repo push — the branch tracks secret file(s): ${secretFiles.join(', ')}. ` +\n `Untrack with \\`git rm --cached ${secretFiles[0]}\\` (add to .gitignore), re-commit, then ` +\n `\\`deepspace push\\`. Deploy continues; this release's source isn't recoverable until then.`,\n )\n } else {\n const pushResult = await pushWithTransientRetry(() =>\n pushToSpace(appDir, token, `refs/heads/${branch}:refs/heads/${branch}`),\n )\n if (pushResult.status === 'committed' || pushResult.status === 'up_to_date') {\n recoverable = true\n if (pushResult.status === 'committed') {\n p.log.info(`Pushed ${branch} → ${tip.slice(0, 10)}.`)\n }\n } else if (pushResult.status === 'rejected') {\n output.die(\n `Cloud repo rejected ${branch}${pushResult.reason ? `: ${pushResult.reason}` : ''}. Resolve the rejection and publish the commit before deploying.`,\n 'vc_push_rejected',\n )\n } else {\n const remoteState = classifyRemoteState(appDir, token, branch, tip)\n if (remoteState.strictlyBehind && !ignoreStale) {\n let behind = 'several'\n try {\n behind = String(revListCount(appDir, tip, remoteState.remoteTip as string))\n } catch {\n // The count is decoration; the refusal remains valid without it.\n }\n const message =\n `Your ${branch} is ${behind} commit(s) behind the cloud repo — deploying would take ` +\n `already-landed work off the live app. Run \\`deepspace pull\\`, then redeploy ` +\n `(or pass --ignore-stale to ship this older tree anyway).`\n output.die(message, 'behind_trunk', {\n action: {\n cwd: appDir,\n argv: ['deepspace', 'pull'],\n },\n actionRequired: true,\n })\n }\n if (remoteState.strictlyBehind) {\n recoverable = true\n p.log.warn(\n `Deploying a tree behind the cloud repo (--ignore-stale) — the live app reverts to ` +\n `${tip.slice(0, 10)} until the next deploy from an up-to-date checkout.`,\n )\n } else {\n output.die(\n `Cloud repo's ${branch} diverged (${pushResult.status}). Integrate the cloud tip, or explicitly publish an intentional history rewrite, before deploying.`,\n 'vc_diverged',\n {\n action: { cwd: appDir, argv: ['deepspace', 'pull'] },\n actionRequired: true,\n },\n )\n }\n }\n }\n commitOid = tip\n } catch (error: unknown) {\n const failure = deployRepositoryFailure(error)\n output.die(failure.error, failure.code)\n }\n\n return { commitOid, recoverable, deployKey }\n}\n\nfunction classifyRemoteState(\n appDir: string,\n token: string,\n branch: string,\n localTip: string,\n): { remoteTip: string | null; strictlyBehind: boolean } {\n let remoteTip: string | null = null\n try {\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+refs/heads/${branch}:refs/remotes/space/${branch}`,\n ])\n remoteTip = resolveCommit(appDir, `refs/remotes/space/${branch}`)\n return {\n remoteTip,\n strictlyBehind:\n remoteTip !== null && remoteTip !== localTip && isAncestor(appDir, localTip, remoteTip),\n }\n } catch {\n return { remoteTip, strictlyBehind: false }\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nexport function deployRepositoryFailure(error: unknown): { code: string; error: string } {\n const transportFailure = classifyPushTransportFailure(error)\n if (transportFailure) return transportFailure\n\n const code = errorCode(error)\n const message = errorMessage(error)\n if (code && code !== 'git_error') return { code, error: message }\n return {\n code: code ?? 'vc_sync_failed',\n error: `Version-control sync failed: ${message}`,\n }\n}\n\nexport async function pushWithTransientRetry(push: () => PushRefResult): Promise<PushRefResult> {\n const backoffMs = [500, 1500, 3500]\n for (let attempt = 0; ; attempt++) {\n try {\n return push()\n } catch (error) {\n const message = errorMessage(error)\n if (/(?:HTTP |error: )(?:429|503)\\b/i.test(message) && attempt < backoffMs.length) {\n await new Promise((resolve) => setTimeout(resolve, backoffMs[attempt]))\n continue\n }\n throw error\n }\n }\n}\n\nexport function shouldSendLineage(commitOid: string | null, recoverable: boolean): boolean {\n return commitOid !== null && recoverable\n}\n\nexport function workspaceDeployLineage(\n status: RemoteWorkspace['status'],\n publishedTip: string | null,\n localTip: string,\n): 'recoverable' | 'inactive' | 'unsynced' {\n if (status !== 'active') return 'inactive'\n return publishedTip === localTip ? 'recoverable' : 'unsynced'\n}\n\nexport function dirtyWorktreeRefusal(branch: string | null): {\n code: 'dirty_worktree'\n error: string\n} {\n const workspaceId = workspaceIdFromBranch(branch)\n return {\n code: 'dirty_worktree',\n error:\n 'The worktree has uncommitted changes, and a deploy records the commit it ships. ' +\n (workspaceId\n ? `Commit them to this workspace branch (${branch}) — WIP commits are fine — then redeploy. `\n : 'Commit them (to a workspace branch if this is work in progress: `deepspace workspace new -t \"…\"`), then redeploy. ') +\n 'Or pass --no-push to deploy without version-control sync — the release then records no source lineage.',\n }\n}\n\nexport function detachedHeadRefusal(): { code: 'detached_head'; error: string } {\n return {\n code: 'detached_head',\n error:\n 'HEAD is detached, so DeepSpace cannot publish this commit to a recoverable branch. ' +\n 'Create or switch to a branch before deploying, or pass `--no-push` to explicitly deploy without source lineage.',\n }\n}\n","import { shQuote } from '../cli-format'\nimport { runGit, splitNulFields } from './process'\nimport { repoToplevel } from './repository'\n\nconst SECRET_FILE_RE = /(^|\\/)(\\.dev\\.vars(\\.[^/]*)?|\\.env(\\.[^/]*)?|\\.npmrc|\\.envrc|\\.mcp\\.json)$/i\nconst SECRET_TEMPLATE_RE = /\\.(example|sample|template)$/i\n\n/** Best-effort oversized-blob diagnostics for a rejected push. */\nexport function findOversizedObjects(\n cwd: string,\n capBytes: number,\n limit = 3,\n): { path: string; bytes: number }[] {\n try {\n const revisionObjects = runGit(cwd, ['rev-list', '--objects', '--all'], { allowFail: true })\n if (revisionObjects.status !== 0) return []\n const pathByOid = new Map<string, string>()\n for (const line of revisionObjects.stdout.toString('utf-8').split('\\n')) {\n const separator = line.indexOf(' ')\n if (separator > 0) pathByOid.set(line.slice(0, separator), line.slice(separator + 1))\n }\n\n const sizedObjects = runGit(\n cwd,\n [\n 'cat-file',\n '--batch-all-objects',\n '--batch-check=%(objectname) %(objecttype) %(objectsize)',\n ],\n { allowFail: true },\n )\n if (sizedObjects.status !== 0) return []\n const oversized: { path: string; bytes: number }[] = []\n for (const line of sizedObjects.stdout.toString('utf-8').split('\\n')) {\n const [oid, type, size] = line.split(' ')\n if (type !== 'blob') continue\n const bytes = Number(size)\n const path = pathByOid.get(oid)\n if (path && Number.isFinite(bytes) && bytes > capBytes) oversized.push({ path, bytes })\n }\n return oversized.sort((left, right) => right.bytes - left.bytes).slice(0, limit)\n } catch {\n return []\n }\n}\n\n/** Dirty paths safe to expose in logs; local secret filenames are redacted. */\nexport function statusFiles(cwd: string): string[] {\n const records = splitNulFields(\n runGit(cwd, [\n '-c',\n 'core.quotePath=false',\n 'status',\n '--porcelain',\n '--untracked-files=all',\n '-z',\n ]).stdout,\n )\n const files: string[] = []\n for (let index = 0; index < records.length; index++) {\n const record = records[index]\n files.push(record.slice(3))\n if (/[RC]/.test(record.slice(0, 2))) {\n index++\n if (/R/.test(record.slice(0, 2)) && index < records.length) files.push(records[index])\n }\n }\n return [\n ...new Set(\n files.filter((path) => !(SECRET_FILE_RE.test(path) && !SECRET_TEMPLATE_RE.test(path))),\n ),\n ]\n}\n\n/** Secret-bearing files in a committed tree, scanned from the repository root. */\nexport function trackedSecretFiles(cwd: string, ref: string): string[] {\n const result = runGit(\n repoToplevel(cwd),\n ['-c', 'core.quotePath=false', 'ls-tree', '-r', '--name-only', '-z', ref],\n { allowFail: true },\n )\n if (result.status !== 0) return []\n return splitNulFields(result.stdout).filter(\n (path) => SECRET_FILE_RE.test(path) && !SECRET_TEMPLATE_RE.test(path),\n )\n}\n\nexport const SECRET_IN_HISTORY_CODE = 'secret_in_history'\n\nexport function committedSecretRefusal(\n cwd: string,\n commitOid: string | null,\n options: { action: string; then: string },\n): { files: string[]; message: string; code: string } | null {\n if (!commitOid) return null\n const files = trackedSecretFiles(cwd, commitOid)\n if (files.length === 0) return null\n return {\n files,\n code: SECRET_IN_HISTORY_CODE,\n message:\n `Refusing to ${options.action}: the commit being published carries secret file(s) — ` +\n `${files.join(', ')}. These hold local secrets and must not reach the cloud repo, ` +\n `but pushing this commit would upload them through its history. ` +\n `Untrack with \\`git rm --cached ${shQuote(files[0])}\\`, ensure it's .gitignored, commit, ` +\n `then ${options.then}.`,\n }\n}\n","/**\n * Typed client for the deploy-worker's /api/repo JSON surface — the DeepSpace\n * layer on top of the git remote: refs for scripting, workspaces, the activity\n * feed, and the release history. Object transfer itself never goes through\n * here; that's real git against the smart-HTTP endpoint (lib/vc-remote.ts).\n *\n * Idempotency: `createWorkspace` carries a client-minted key, so a retried\n * create replays the recorded outcome instead of double-writing. sync, land\n * and drop are idempotent by CONSTRUCTION instead — each is a state\n * transition whose replay is a no-op (same tip, already-landed, already-\n * dropped all return the current view) — so they send no key.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { apiFetch, ApiError } from './api'\n\nexport interface RemoteRef {\n name: string\n oid: string\n updatedAt: string\n updatedBy: string\n}\n\nexport interface RemoteRefsResult {\n refs: RemoteRef[]\n head: string | null\n}\n\nexport interface RemoteRelease {\n id: string\n seq: number\n commitOid: string | null\n cfVersionId: string | null\n rollbackAvailable: boolean\n config: unknown\n actor: string\n url: string | null\n kind: 'deploy' | 'rollback'\n createdAt: string\n}\n\nexport interface RemoteWorkspace {\n id: string\n task: string\n baseOid: string\n ref: string\n status: 'active' | 'landed' | 'dropped'\n createdBy: string\n createdAt: string\n updatedAt: string\n landedOid: string | null\n}\n\nexport interface RemoteCommitCount {\n count: number\n capped: boolean\n}\n\n/** Commit-graph facts the repo DO owns. Path-level coordination (which other\n * workspaces touch the same files) is computed client-side from local diffs —\n * see `workspace.ts`. */\nexport interface RemoteWorkspaceView {\n workspace: RemoteWorkspace\n tipOid: string | null\n aheadOfBase: RemoteCommitCount | null\n behindTrunk: RemoteCommitCount | null\n}\n\nexport interface RemoteActivityEvent {\n seq: number\n kind: string\n subjectId: string | null\n summary: unknown\n actor: string\n createdAt: string\n}\n\nexport function mintIdempotencyKey(): string {\n return randomUUID()\n}\n\n/**\n * Resolve a live subdomain name to its app id via the deploy worker's\n * access-gated resolver (`GET /api/repo/resolve-name/:name`). Unlike the\n * owner-only `/api/apps` list, this also finds apps the caller merely\n * COLLABORATES on. Returns null when the name is unknown, malformed, or the\n * caller has no access — the server deliberately doesn't distinguish the\n * first from the last (no existence oracle).\n */\nexport async function resolveAppIdByName(\n deployUrl: string,\n token: string,\n name: string,\n): Promise<string | null> {\n try {\n const { appId } = await apiFetch<{ appId: string }>(\n deployUrl,\n token,\n `/api/repo/resolve-name/${encodeURIComponent(name)}`,\n )\n return appId ?? null\n } catch (err) {\n if (err instanceof ApiError && (err.status === 404 || err.status === 400)) return null\n throw err\n }\n}\n\nexport function repoApi(deployUrl: string, token: string, appId: string) {\n const base = `/api/repo/${encodeURIComponent(appId)}`\n const call = async <T>(path: string, init?: RequestInit): Promise<T> => {\n // The bare-404 \"wrong/old service\" case (→ unrecognized_service) is handled\n // uniformly in apiFetch now, for every caller incl. rollback's direct endpoint.\n return await apiFetch<T>(deployUrl, token, `${base}${path}`, init)\n }\n const post = <T>(path: string, body: unknown) =>\n call<T>(path, { method: 'POST', body: JSON.stringify(body) })\n\n // A well-formed repo-API 2xx body carries the endpoint's documented fields with\n // the right shape. A wrong/broken service can answer 200 with `{}` (or an empty\n // body, which apiFetch reads as `{}`), a null-valued field, or the wrong type;\n // left unchecked those destructure to `undefined`/`null` downstream and surface\n // as a false `ok:true` or an uncoded `reading '…' of null|undefined` crash. Code\n // such a body as invalid_response — the same slug apiFetch uses for a\n // null/array/non-JSON 2xx. This enforces every SCHEMA-FREE degeneracy check —\n // present, correct JSON type, non-null, arrays carry no null entries, objects\n // are non-empty — and stops exactly where a check would need the per-endpoint\n // field schema (a populated-but-wrong-fielded entity like `{view:{wrong:1}}` or\n // `[{}]` is left to the caller's TS types + happy-path tests, NOT re-validated\n // here). Kinds: `array` (a list, never null, no null entries), `object` (a\n // non-empty, non-null, non-array object — a real entity is never `{}`, and no\n // top-level field is a legitimately-empty map; do NOT tag such a field `object`\n // if one is ever added), `present` (key exists; value may be null — e.g. a\n // nullable ref like getRefs' `head`).\n const KIND = {\n array: (v: unknown) => Array.isArray(v) && v.every((e) => e !== null),\n object: (v: unknown) =>\n v !== null && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length > 0,\n present: (v: unknown) => v !== undefined,\n }\n type Kind = keyof typeof KIND\n const shapeError = (path: string) =>\n new ApiError(\n `The deploy service at ${deployUrl} returned an unexpected response shape — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n 200,\n 'invalid_response',\n `${base}${path}`,\n )\n // Each `spec` key must name a documented top-level field of the response (a\n // typo'd key rejects every valid 2xx as invalid_response — fail-loud, caught by\n // the per-endpoint happy-path tests). Keys stay strings (not `keyof T`) so T\n // still infers from each method's return annotation rather than from the spec.\n const assertShape = <T>(r: T, spec: Record<string, Kind>, path: string): T => {\n if (r === null || typeof r !== 'object') throw shapeError(path)\n const obj = r as Record<string, unknown>\n for (const [key, kind] of Object.entries(spec)) {\n if (!KIND[kind](obj[key])) throw shapeError(path)\n }\n return r\n }\n const getShape = async <T>(path: string, spec: Record<string, Kind>): Promise<T> =>\n assertShape(await call<T>(path), spec, path)\n const postShape = async <T>(\n path: string,\n body: unknown,\n spec: Record<string, Kind>,\n ): Promise<T> => assertShape(await post<T>(path, body), spec, path)\n\n return {\n /** null ⇒ the app has never been registered (fresh repo, no history). */\n async getRefs(): Promise<RemoteRefsResult | null> {\n try {\n return await getShape<RemoteRefsResult>('/refs', { refs: 'array', head: 'present' })\n } catch (err) {\n if (err instanceof ApiError && err.code === 'app_not_found') return null\n throw err\n }\n },\n\n createWorkspace(args: {\n workspaceId: string\n task: string\n baseOid: string\n idempotencyKey: string\n }): Promise<{ view: RemoteWorkspaceView }> {\n return postShape('/workspaces', args, { view: 'object' })\n },\n\n listWorkspaces(opts?: {\n all?: boolean\n limit?: number\n }): Promise<{ views: RemoteWorkspaceView[] }> {\n const params = new URLSearchParams()\n if (opts?.all) params.set('all', '1')\n if (opts?.limit) params.set('limit', String(opts.limit))\n const qs = params.toString()\n return getShape(`/workspaces${qs ? `?${qs}` : ''}`, { views: 'array' })\n },\n\n getWorkspace(id: string): Promise<{ view: RemoteWorkspaceView }> {\n return getShape(`/workspaces/${encodeURIComponent(id)}`, { view: 'object' })\n },\n\n syncWorkspace(id: string, args: { headOid: string }): Promise<{ view: RemoteWorkspaceView }> {\n return postShape(`/workspaces/${encodeURIComponent(id)}/sync`, args, { view: 'object' })\n },\n\n landWorkspace(\n id: string,\n args: { landedOid: string; intoRef?: string },\n ): Promise<{ view: RemoteWorkspaceView }> {\n return postShape(`/workspaces/${encodeURIComponent(id)}/land`, args, { view: 'object' })\n },\n\n dropWorkspace(id: string): Promise<{ view: RemoteWorkspaceView }> {\n return postShape(`/workspaces/${encodeURIComponent(id)}/drop`, {}, { view: 'object' })\n },\n\n listActivity(opts?: {\n since?: number\n limit?: number\n tail?: boolean\n }): Promise<{ events: RemoteActivityEvent[]; cursor: number; hasMore: boolean }> {\n const params = new URLSearchParams()\n if (opts?.since) params.set('since', String(opts.since))\n if (opts?.limit) params.set('limit', String(opts.limit))\n if (opts?.tail) params.set('tail', '1')\n const qs = params.toString()\n return getShape(`/activity${qs ? `?${qs}` : ''}`, {\n events: 'array',\n cursor: 'present',\n hasMore: 'present',\n })\n },\n\n listReleases(limit?: number): Promise<{ releases: RemoteRelease[] }> {\n return getShape(`/releases${limit ? `?limit=${limit}` : ''}`, { releases: 'array' })\n },\n\n latestRelease(): Promise<{ release: RemoteRelease | null }> {\n // `release` is nullable (no releases yet) — presence-only, not `object`.\n return getShape('/releases/latest', { release: 'present' })\n },\n\n getRelease(id: string): Promise<{ release: RemoteRelease }> {\n return getShape(`/releases/${encodeURIComponent(id)}`, { release: 'object' })\n },\n }\n}\n\nexport type RepoApi = ReturnType<typeof repoApi>\n","/**\n * Remote URL, bearer auth, and credential-helper setup for the `space` remote.\n * The transfer itself is real Git; push protocol parsing lives in `vc-push.ts`.\n */\n\nimport { existsSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, relative, resolve } from 'node:path'\nimport { PLATFORM_URLS } from '../env'\nimport { shQuote } from './cli-format'\nimport { runGit } from './git/process'\n\n/** The remote name the platform repo lives under in every synced clone. */\nexport const SPACE_REMOTE = 'space'\n\n/** The deploy worker base URL, honoring the per-command override convention. */\nexport function deployBaseUrl(): string {\n return process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n}\n\n/** The app's smart-HTTP remote URL — clonable/pushable by real Git. */\nexport function repoUrl(appId: string, base: string = deployBaseUrl()): string {\n return `${base.replace(/\\/+$/, '')}/api/repo/${encodeURIComponent(appId)}`\n}\n\n/**\n * Auth env for CLI-driven Git invocations. The bearer header is scoped to the\n * platform base URL and travels only in the child environment, never argv or\n * disk. Existing `GIT_CONFIG_*` entries are preserved.\n */\nexport function gitAuthEnv(token: string, base: string = deployBaseUrl()): Record<string, string> {\n const existing = Number(process.env.GIT_CONFIG_COUNT ?? '0')\n const index = Number.isInteger(existing) && existing > 0 ? existing : 0\n return {\n GIT_CONFIG_COUNT: String(index + 1),\n [`GIT_CONFIG_KEY_${index}`]: `http.${base.replace(/\\/+$/, '')}.extraHeader`,\n [`GIT_CONFIG_VALUE_${index}`]: `Authorization: Bearer ${token}`,\n }\n}\n\n/** Run Git with bearer-auth configuration injected via its environment. */\nexport function runGitRemote(\n cwd: string,\n token: string,\n args: string[],\n opts: { input?: string | Buffer; allowFail?: boolean; env?: Record<string, string> } = {},\n): { stdout: Buffer; stderr: Buffer; status: number } {\n return runGit(cwd, args, { ...opts, env: { ...gitAuthEnv(token), ...(opts.env ?? {}) } })\n}\n\n/**\n * Whether the running CLI entry is ephemeral. A credential helper pinned into\n * global Git config must not point at an npm cache or app-local install that\n * can disappear.\n */\nfunction entryIsTransient(cwd: string): boolean {\n const entry = process.argv[1]\n if (!entry) return true\n if (/[\\\\/]_npx[\\\\/]/.test(entry) || entry.startsWith(tmpdir())) return true\n const rel = relative(resolve(cwd), resolve(entry))\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))\n}\n\n/** Does an existing pinned helper entry still point at usable files? */\nfunction helperEntryUsable(command: string): boolean {\n // Quoted paths containing a single quote deliberately fall through to false;\n // re-aiming that rare form is simpler and safer than partially parsing shell.\n const match = /^!'([^']*)' '([^']*)' git-credential$/.exec(command)\n return match !== null && existsSync(match[1]) && existsSync(match[2])\n}\n\n/**\n * Pin the exact node binary and CLI entry, avoiding PATH and stale global CLI\n * shadowing. `shQuote` neutralizes every shell metacharacter in those paths.\n */\nexport function credentialHelperCommand(): string {\n const entry = process.argv[1]\n if (!entry) throw new Error('CLI entry path is unavailable')\n return `!${shQuote(process.execPath)} ${shQuote(entry)} git-credential`\n}\n\n/**\n * Best-effort host-scoped credential-helper installation. Wrapped commands\n * inject auth themselves; this setup exists so plain `git push space` and\n * `git clone <app-url>` work afterward.\n */\nfunction installCredentialHelper(cwd: string, url: string): void {\n try {\n const origin = new URL(url)\n const key = `credential.${origin.protocol}//${origin.host}.helper`\n const helper = credentialHelperCommand()\n // The empty first value resets inherited helpers. Otherwise Git's approve\n // step could persist the short-lived DeepSpace bearer in an OS keychain.\n const wanted = ['', helper]\n const transient = entryIsTransient(cwd)\n const scope = transient ? '--worktree' : '--global'\n if (transient) {\n // Repository-local config is shared by every linked worktree. Never pin\n // an ephemeral Codex/Claude/app-local CLI path there: deleting that\n // checkout would break plain Git in all siblings. Git's worktree config\n // keeps the helper beside the checkout whose executable it references.\n const enabled = runGit(cwd, ['config', '--local', 'extensions.worktreeConfig', 'true'], {\n allowFail: true,\n })\n if (enabled.status !== 0) return\n runGit(cwd, ['config', '--local', '--unset-all', key], { allowFail: true })\n }\n const current = runGit(cwd, ['config', scope, '--get-all', key], { allowFail: true })\n if (current.status === 0) {\n const existing = current.stdout\n .toString('utf-8')\n .split('\\n')\n .filter((_, index, lines) => index < lines.length - 1)\n if (existing.length === wanted.length && existing.every((value, i) => value === wanted[i])) {\n return\n }\n // Leave another usable checkout's helper alone so parallel checkouts do\n // not ping-pong global config. Rewrite only malformed or stale entries.\n if (\n existing.length === wanted.length &&\n existing[0] === '' &&\n helperEntryUsable(existing[1])\n ) {\n return\n }\n runGit(cwd, ['config', scope, '--unset-all', key], { allowFail: true })\n }\n runGit(cwd, ['config', scope, '--add', key, ''])\n runGit(cwd, ['config', scope, '--add', key, helper])\n if (scope === '--global' && !process.argv.includes('--json')) {\n process.stderr.write(\n `note: added a git credential helper for ${origin.host} to your global git config so ` +\n `plain \\`git clone\\`/\\`git push\\` to DeepSpace authenticate. ` +\n `Undo with: git config --global --unset-all ${key}\\n`,\n )\n }\n } catch {\n // Best effort: wrapped transfers remain authenticated without the helper.\n }\n}\n\n/** Point `space` at this app and install the host-scoped credential helper. */\nexport function ensureSpaceRemote(cwd: string, appId: string): string {\n const url = repoUrl(appId)\n const current = runGit(cwd, ['remote', 'get-url', SPACE_REMOTE], { allowFail: true })\n if (current.status !== 0) {\n runGit(cwd, ['remote', 'add', SPACE_REMOTE, url])\n } else {\n const existing = current.stdout.toString('utf-8').trim()\n if (existing !== url) {\n const priorApp = appIdFromRepoUrl(existing)\n if (priorApp && priorApp !== appId && !process.argv.includes('--json')) {\n process.stderr.write(\n `warning: remote '${SPACE_REMOTE}' was pointed at app ${priorApp}; re-aiming it at ${appId}.\\n`,\n )\n }\n runGit(cwd, ['remote', 'set-url', SPACE_REMOTE, url])\n }\n }\n installCredentialHelper(cwd, url)\n return url\n}\n\n/** Extract the app id from a DeepSpace repository URL. */\nfunction appIdFromRepoUrl(url: string): string | null {\n const match = /\\/api\\/repo\\/([^/]+)\\/?$/.exec(url)\n return match ? decodeURIComponent(match[1]) : null\n}\n","/**\n * Git push protocol for the `space` remote: porcelain parsing, retryable\n * transport classification, and actionable rejection messages. Remote URL,\n * credential-helper, and auth configuration remain in `vc-remote.ts`.\n */\n\nimport { shQuote } from './cli-format'\nimport { GitError } from './git/process'\nimport { findOversizedObjects } from './git/safety'\nimport { runGitRemote, SPACE_REMOTE } from './vc-remote'\n\nexport type PushRefStatus =\n | 'committed'\n | 'up_to_date'\n | 'non_fast_forward'\n | 'ref_conflict'\n | 'rejected'\n\n/**\n * The exact `ng` reasons emitted when the server's ref CAS loses a race. Other\n * server rejections are policy/data failures; `deepspace pull` cannot fix them.\n */\nconst CAS_CONFLICT_REASON = /stale ref|fetch first|no such ref|atomic push failed/i\n\nexport interface PushRefResult {\n status: PushRefStatus\n localRef: string\n remoteRef: string\n /** Raw summary column from `git push --porcelain`. */\n summary: string\n /** Parenthesized server/client rejection reason. */\n reason?: string\n}\n\n/** Parse `git push --porcelain` into one result per ref. */\nexport function parsePushPorcelain(out: string): PushRefResult[] {\n const results: PushRefResult[] = []\n for (const line of out.split('\\n')) {\n const match = /^([ +\\-*=!])\\t([^\\t]*)\\t(.*)$/.exec(line)\n if (!match) continue\n const [, flag, refspec, summary] = match\n const colon = refspec.indexOf(':')\n const localRef = colon >= 0 ? refspec.slice(0, colon) : refspec\n const remoteRef = colon >= 0 ? refspec.slice(colon + 1) : refspec\n let status: PushRefStatus\n let reason: string | undefined\n if (flag === '=') {\n status = 'up_to_date'\n } else if (flag === '!') {\n reason = /\\((.*)\\)\\s*$/.exec(summary)?.[1]\n if (!summary.startsWith('[remote rejected]')) {\n status = 'non_fast_forward'\n } else if (reason && CAS_CONFLICT_REASON.test(reason)) {\n status = 'ref_conflict'\n } else {\n status = 'rejected'\n }\n } else {\n status = 'committed'\n }\n results.push({ status, localRef, remoteRef, summary, ...(reason ? { reason } : {}) })\n }\n return results\n}\n\n/** The server explicitly asks for a full-pack retry on this one rejection. */\nexport function isThinPackRejection(result: PushRefResult): boolean {\n return (\n result.status === 'rejected' &&\n /thin (?:push|pack)|--no-thin/i.test(result.reason ?? result.summary ?? '')\n )\n}\n\n/** Whether pull is the one deterministic recovery for a failed push. */\nexport function isRecoverablePushFailure(status: PushRefStatus): boolean {\n return status === 'non_fast_forward' || status === 'ref_conflict'\n}\n\nexport interface PushTransportFailure {\n code: 'app_quota_exceeded' | 'rate_limited'\n error: string\n}\n\n/** Classify HTTP failures whose bodies Git's smart-HTTP transport discards. */\nexport function classifyPushTransportFailure(error: unknown): PushTransportFailure | null {\n const message = error instanceof Error ? error.message : String(error)\n // Match only HTTP-status contexts: `Total 429 (delta 3)` is valid git output.\n if (/(?:HTTP |error: )409\\b/i.test(message)) {\n return {\n code: 'app_quota_exceeded',\n error:\n `A first push to this new app hit your plan's active-app quota. ` +\n `Use \\`deepspace app list\\` to choose an app to undeploy, or upgrade your plan, then retry.`,\n }\n }\n if (/(?:HTTP |error: )429\\b/i.test(message)) {\n return {\n code: 'rate_limited',\n error: 'The cloud repo rate-limited this push. Wait a few seconds, then retry.',\n }\n }\n return null\n}\n\n/** Push one refspec and return Git's porcelain result. */\nexport function pushToSpace(\n cwd: string,\n token: string,\n refspec: string,\n opts: { force?: boolean } = {},\n): PushRefResult {\n const doPush = (extra: string[]): PushRefResult => {\n const result = runGitRemote(\n cwd,\n token,\n ['push', '--porcelain', ...(opts.force ? ['--force'] : []), ...extra, SPACE_REMOTE, refspec],\n { allowFail: true },\n )\n const parsed = parsePushPorcelain(result.stdout.toString('utf-8'))\n if (parsed.length === 0) {\n const stderr = result.stderr.toString('utf-8').trim()\n throw new GitError(\n stderr || `git push exited ${result.status} without reporting a ref status`,\n )\n }\n return parsed[0]\n }\n const first = doPush([])\n return isThinPackRejection(first) ? doPush(['--no-thin']) : first\n}\n\n/** Matches the server's oversized-object rejection text. */\nexport const OVERSIZED_PUSH_RE = /too large|exceeds|\\bLFS\\b/i\n\n/** Mirrors deploy-worker's per-object cap; the server remains the enforcer. */\nconst SERVER_OBJECT_CAP_BYTES = 20 * 1024 * 1024\n\nexport const OVERSIZED_PUSH_FIX =\n `Find the offending object with ` +\n `\\`git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectsize) %(rest)' | sort -k2 -n | tail\\`, ` +\n `then .gitignore it (or move it to Git LFS) and re-commit.`\n\nfunction formatBytes(bytes: number): string {\n if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`\n if (bytes >= 1024) return `${Math.round(bytes / 1024)} KiB`\n return `${bytes} B`\n}\n\n/** Name over-cap objects when possible so the correction is mechanical. */\nexport function oversizedPushFix(cwd?: string, cap: number = SERVER_OBJECT_CAP_BYTES): string {\n const objects = cwd ? findOversizedObjects(cwd, cap) : []\n if (objects.length === 0) return OVERSIZED_PUSH_FIX\n const one = objects.length === 1\n const named = objects.map((object) => `${object.path} (${formatBytes(object.bytes)})`).join(', ')\n return (\n `The oversized ${one ? 'file is' : 'files are'} ${named}. ` +\n `Remove ${one ? 'it' : 'them'} from history (\\`git rm --cached ${one ? shQuote(objects[0].path) : '<path>'}\\`, ` +\n `add to .gitignore, re-commit) or track ${one ? 'it' : 'them'} with Git LFS.`\n )\n}\n\n/**\n * Render a non-divergence push rejection. Only the server's explicit\n * retry-the-push race is classified transient; unknown and policy rejections\n * fail closed so agents do not loop on a permanent refusal.\n */\nexport function pushFailureMessage(label: string, push: PushRefResult, cwd?: string): string {\n const reason = push.reason ?? push.summary ?? ''\n const detail = `${push.status}${reason ? `: ${reason}` : ''}`\n if (OVERSIZED_PUSH_RE.test(reason)) {\n return `${label} failed (${detail}) — an object exceeds the server's size cap, so retrying cannot succeed. ${oversizedPushFix(cwd)}`\n }\n if (/^missing necessary objects — retry the push$/i.test(reason)) {\n return `${label} failed (${detail}). Retry; if it persists, report it with \\`deepspace feedback\\`.`\n }\n return (\n `${label} failed (${detail}). The server rejected this push; correct the reported ` +\n `history/ref problem, or report it with \\`deepspace feedback\\` if the reason is unclear.`\n )\n}\n","/**\n * Workspace naming — the deterministic mapping between a server workspace id\n * (`ws_<26-char Crockford ULID>`) and its local git branch (`ws/<ulid,\n * lowercased>`). Deterministic both ways so `workspace sync`/`land`/`status`\n * can infer which workspace a worktree belongs to from nothing but the\n * checked-out branch, on any machine.\n */\n\nconst ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/i\nconst WORKSPACE_ID_RE = /^ws_[0-9A-HJKMNP-TV-Z]{26}$/\n\nexport function isWorkspaceId(id: string): boolean {\n return WORKSPACE_ID_RE.test(id)\n}\n\nexport function workspaceBranchName(workspaceId: string): string {\n return `ws/${workspaceId.replace(/^ws_/, '').toLowerCase()}`\n}\n\n/** `ws/<ulid>` → `ws_<ULID>`, or null when the branch isn't workspace-shaped. */\nexport function workspaceIdFromBranch(branch: string | null): string | null {\n if (!branch || !branch.startsWith('ws/')) return null\n const ulid = branch.slice(3)\n if (!ULID_RE.test(ulid)) return null\n return `ws_${ulid.toUpperCase()}`\n}\n\nexport function isSelectedWorkspaceCheckout(branch: string | null, workspaceId: string): boolean {\n return workspaceIdFromBranch(branch) === workspaceId\n}\n\n/** Find a workspace's checkout among the repository's linked worktrees. */\nexport function resolveWorkspaceWorktree(\n worktrees: readonly { path: string; branch: string | null }[],\n workspaceId: string,\n): string | null {\n const branch = workspaceBranchName(workspaceId)\n return worktrees.find((worktree) => worktree.branch === branch)?.path ?? null\n}\n","import * as p from '@clack/prompts'\nimport { existsSync, readFileSync } from 'node:fs'\nimport {\n RESERVED_BINDING_NAMES,\n type CustomBindingManifest,\n} from '../../../server/rooms/binding-manifest'\nimport { extractCustomDevVars, parseDevVars, writeDevVars } from '../../lib/dev-vars'\nimport {\n refreshSecretsCache,\n stripGeneratedSecretsCache,\n type PulledSecretsCache,\n} from '../../lib/secrets'\nimport { devVarsPathFor } from '../../lib/wrangler-env'\nimport type { DurableObjectManifestEntry } from './build'\nimport type { DeployOutput } from './output'\n\nexport interface DeploySecretsCache {\n linked: PulledSecretsCache | null\n localOnlyDevVars: Record<string, string>\n}\n\nexport interface DeploySecretsPayload {\n values: Record<string, string>\n names: string[]\n}\n\nexport function classifyDevVarsSecrets(options: {\n storeSecretNames: string[]\n handEditedDevVarKeys: string[]\n allowMissing: boolean\n}):\n | { kind: 'ok' }\n | { kind: 'warn'; strayKeys: string[] }\n | { kind: 'block'; strayKeys: string[] } {\n const store = new Set(options.storeSecretNames)\n const strayKeys = options.handEditedDevVarKeys.filter((key) => !store.has(key))\n if (strayKeys.length === 0) return { kind: 'ok' }\n if (options.storeSecretNames.length === 0 && !options.allowMissing) {\n return { kind: 'block', strayKeys }\n }\n return { kind: 'warn', strayKeys }\n}\n\nexport async function loadDeploySecrets(options: {\n deployUrl: string\n appDir: string\n appId: string\n envName: string | undefined\n ownerId: string\n token: string\n output: DeployOutput\n}): Promise<DeploySecretsCache> {\n const { deployUrl, appDir, appId, envName, ownerId, token, output } = options\n let linked: PulledSecretsCache | null = null\n let localOnlyDevVars: Record<string, string> = {}\n\n try {\n const refreshed = await refreshSecretsCache(deployUrl, token, appId, envName)\n if (refreshed) {\n linked = refreshed.pulled\n localOnlyDevVars = readCustomDevVars(\n devVarsPathFor(appDir, envName, { sharedDevVarsCache: true }),\n output,\n )\n await writeDevVars(appDir, ownerId, token, envName, {\n appId,\n generatedSecretsCache: refreshed.rendered,\n sharedDevVarsCache: true,\n })\n p.log.info(refreshed.summary)\n }\n } catch (error: unknown) {\n if ((error as { status?: number })?.status === 403) {\n output.die(\n \"You're not authorized to deploy this app — you must be its owner or a current \" +\n 'collaborator. If you were a collaborator, your access may have been revoked.',\n 'not_authorized',\n )\n }\n output.die(\n `Failed to refresh app secrets before deploy: ${errorMessage(error)}`,\n 'secrets_refresh_failed',\n )\n }\n\n return { linked, localOnlyDevVars }\n}\n\nexport function prepareDeploySecrets(options: {\n appDir: string\n envName: string | undefined\n cache: DeploySecretsCache\n allowMissing: boolean\n customBindings: CustomBindingManifest\n doManifest: DurableObjectManifestEntry[] | undefined\n output: DeployOutput\n}): DeploySecretsPayload {\n const { appDir, envName, cache, allowMissing, customBindings, doManifest, output } = options\n const values = cache.linked ? { ...cache.linked.values } : {}\n const devVarsPath = devVarsPathFor(appDir, envName, {\n sharedDevVarsCache: cache.linked !== null,\n })\n const handEditedDevVars = cache.linked\n ? cache.localOnlyDevVars\n : readCustomDevVars(devVarsPath, output)\n const decision = classifyDevVarsSecrets({\n storeSecretNames: Object.keys(values),\n handEditedDevVarKeys: Object.keys(handEditedDevVars),\n allowMissing,\n })\n\n if (decision.kind === 'block') {\n const uploadArgv = [\n 'deepspace',\n 'secrets',\n 'upload',\n '.dev.vars',\n ...(envName ? ['-e', envName] : []),\n ]\n output.die(\n `Refusing to deploy: the app store has no secrets, but .dev.vars has ${decision.strayKeys.join(', ')}. ` +\n 'Deploying now would ship the app with no secrets — replacing any secrets a previous ' +\n 'deploy set (they would be dropped from production). Upload them first, then ' +\n 'redeploy. (Pass --allow-missing-secrets to deploy without them.)',\n 'secrets_not_uploaded',\n { action: { cwd: appDir, argv: uploadArgv } },\n )\n }\n if (decision.kind === 'warn') {\n const stray = decision.strayKeys\n p.log.warn(\n `.dev.vars has ${stray.join(', ')} not in the app store — ${stray.length === 1 ? 'it is' : 'they are'} NOT deployed. ` +\n '`.dev.vars` is a local dev cache, not deploy config. Move ' +\n `${stray.length === 1 ? 'it' : 'them'} into the store with ` +\n '`deepspace secrets set KEY=value` (or `deepspace secrets upload .dev.vars`), then redeploy.',\n )\n }\n\n const names = Object.keys(values)\n const declaredBindingNames = new Set([\n ...customBindings.map((binding) => binding.name),\n ...(doManifest ?? []).map((binding) => binding.binding),\n ])\n for (const name of names) {\n if (RESERVED_BINDING_NAMES.has(name)) {\n output.die(\n `App secret \"${name}\" is a reserved binding name — rename or remove that secret before deploying.`,\n 'reserved_binding',\n )\n }\n if (declaredBindingNames.has(name)) {\n output.die(\n `App secret \"${name}\" collides with a binding declared in wrangler.toml — rename one or the other.`,\n 'binding_collision',\n )\n }\n }\n if (names.length) p.log.info(`App secrets: ${names.join(', ')}`)\n\n return { values, names }\n}\n\nfunction readCustomDevVars(path: string, output: DeployOutput): Record<string, string> {\n if (!existsSync(path)) return {}\n const section = extractCustomDevVars(stripGeneratedSecretsCache(readFileSync(path, 'utf-8')))\n if (!section) return {}\n try {\n return parseDevVars(section)\n } catch (error: unknown) {\n output.die(`.dev.vars: ${errorMessage(error)}`, 'invalid_dev_vars')\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * deepspace app undeploy\n *\n * Removes a deployed app from *.app.space via the deploy worker.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug and the exit codes come from there. Undeploy is TERMINAL — it emits\n * no `Next:` line (the human outro already says a redeploy brings it back).\n */\n\nimport { readAppId } from '../lib/app-identity'\nimport * as p from '@clack/prompts'\nimport { createSpinner } from '../lib/spinner'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { resolveAppSelector } from '../lib/app-target'\nimport { hasWranglerConfig } from '../lib/wrangler-env'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'undeploy',\n description: 'Remove a deployed DeepSpace app',\n },\n args: {\n name: {\n type: 'positional',\n description: 'App id or subdomain name to undeploy (reads DEEPSPACE_APP_ID from wrangler.toml if omitted)',\n required: false,\n },\n env: {\n type: 'string',\n description:\n 'wrangler.toml [env.<name>] block whose deployed app to remove ' +\n '(e.g. --env staging). Ignored if a positional name is given.',\n required: false,\n },\n },\n async run({ args }) {\n const envName = typeof args.env === 'string' && args.env.trim() ? args.env.trim() : undefined\n\n // Token first — resolving a subdomain name to its id needs the registry.\n let token: string\n try {\n token = await ensureToken()\n } catch (err: unknown) {\n throw new Refusal(err instanceof Error ? err.message : String(err), 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n // Target: an explicit positional — app id OR live subdomain name, resolved\n // via the registry (DEP-5) — else DEEPSPACE_APP_ID from wrangler.toml.\n // resolveAppSelector's own InputErrors already carry codes (app_not_found,\n // invalid_app, invalid_response); let them escape rather than re-wrap.\n let appId: string | undefined\n const positional =\n typeof args.name === 'string' && args.name.trim() ? args.name.trim() : undefined\n if (positional) {\n appId = await resolveAppSelector(DEPLOY_URL, token, positional)\n } else if (hasWranglerConfig(process.cwd())) {\n appId = readAppId(process.cwd(), envName) ?? undefined\n }\n if (!appId) {\n throw new Refusal(\n 'Provide an app id or subdomain name, or run from a DeepSpace app directory with a DEEPSPACE_APP_ID.',\n 'not_in_app_repo',\n )\n }\n\n if (!args.json) p.intro(`Undeploying ${appId}`)\n const s = args.json ? null : createSpinner()\n s?.start('Removing...')\n\n const res = await fetch(`${DEPLOY_URL}/api/deploy/${appId}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${token}` },\n })\n\n const body = (await res.json().catch(() => ({}))) as {\n success?: boolean\n error?: string\n code?: string\n releasedHosts?: string[]\n }\n\n if (!res.ok || !body.success) {\n s?.stop('Failed')\n if (body.code === 'registry_takedown_failed') {\n throw new Refusal(\n body.error ?? 'Registry takedown failed after the cloud script was removed.',\n body.code,\n {\n actionRequired: true,\n action: cliAction('deepspace', 'app', 'undeploy', appId),\n extra: { appId },\n },\n )\n }\n throw new Refusal(body.error ?? `Undeploy error (${res.status})`, 'undeploy_failed')\n }\n\n s?.stop('Removed')\n const hosts = body.releasedHosts ?? []\n if (!args.json) {\n p.outro(\n hosts.length\n ? `${hosts.join(', ')} taken down. The app keeps its id — redeploy to bring it back.`\n : `App ${appId} taken down.`,\n )\n }\n return { data: { appId, releasedHosts: hosts } }\n },\n})\n","/** Resolve explicit or local app selectors to canonical app ids. */\n\nimport { APP_ID_RE, readAppId } from './app-identity'\nimport { apiFetch } from './api'\nimport { InputError } from './cli-errors'\nimport { findAppDir } from './app-context'\nimport { resolveAppIdByName } from './repo-api'\nimport { STRICT_APP_ID_RE } from '../../server/utils/registry-client'\nimport { APP_NAME_RULES } from '../../server/rooms/app-name'\n\nfunction isCanonicalAppName(name: string): boolean {\n return (\n name.length >= APP_NAME_RULES.minLength &&\n name.length <= APP_NAME_RULES.maxLength &&\n APP_NAME_RULES.pattern.test(name)\n )\n}\n\n/** Resolve an explicit app id, or read it from the surrounding app. */\nexport function requireAppIdArg(explicit: string | undefined): string {\n const { app, error } = parseAppArg(explicit)\n if (error) throw new InputError(error, 'invalid_app')\n if (app !== undefined) {\n if (!APP_ID_RE.test(app)) {\n throw new Error(`\"${app}\" is not an app id (app_…). Pass --app <appId>.`)\n }\n return app\n }\n const appDir = findAppDir()\n const id = appDir ? readAppId(appDir) : null\n if (!id) {\n throw new Error(\n 'No app id. Run from an app directory whose wrangler.toml carries DEEPSPACE_APP_ID, or pass --app <appId>.',\n )\n }\n return id\n}\n\ninterface AppListEntry {\n appId: string\n name: string | null\n}\n\n/** Find an app id or subdomain name in the caller's registry list. */\nexport function matchAppSelector(apps: AppListEntry[], selector: string): string | null {\n const byId = apps.find((app) => app.appId === selector)\n if (byId) return byId.appId\n const byName = apps.find((app) => app.name === selector)\n if (byName) return byName.appId\n return STRICT_APP_ID_RE.test(selector) ? selector : null\n}\n\n/** Resolve an app id or live subdomain name to the canonical app id. */\nexport async function resolveAppSelector(\n deployUrl: string,\n token: string,\n selector: string,\n): Promise<string> {\n if (STRICT_APP_ID_RE.test(selector)) return selector\n const { apps } = await apiFetch<{ apps: AppListEntry[] }>(deployUrl, token, '/api/apps')\n if (!Array.isArray(apps)) {\n throw new InputError(\n `The deploy service at ${deployUrl} returned an unexpected response shape for the app list — ` +\n `check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).`,\n 'invalid_response',\n )\n }\n const id = matchAppSelector(apps, selector)\n if (id) return id\n\n // The owner-scoped app list omits apps on which the caller collaborates.\n const shared = await resolveAppIdByName(deployUrl, token, selector)\n if (shared) return shared\n throw new InputError(\n `No app \"${selector}\" found, or you don't have access to it. ` +\n `If the app exists but was never deployed, it has no name yet; target it by app id. ` +\n `Run \\`deepspace app list\\` to list your apps and their ids.`,\n 'app_not_found',\n )\n}\n\n/** Resolve an explicit selector, or read the surrounding app id. */\nexport async function resolveAppTarget(\n deployUrl: string,\n token: string,\n explicit: string | undefined,\n): Promise<string> {\n const { app, error } = parseAppArg(explicit)\n if (error) throw new InputError(error, 'invalid_app')\n if (app !== undefined) return resolveAppSelector(deployUrl, token, app)\n const appDir = findAppDir()\n const id = appDir ? readAppId(appDir) : null\n if (!id) {\n throw new InputError(\n 'No app id. Run from an app directory whose wrangler.toml carries DEEPSPACE_APP_ID, or pass --app <id or name>.',\n 'not_in_app_repo',\n )\n }\n return id\n}\n\n/** Preserve absent-vs-blank so a blank selector cannot target the local app. */\nexport function parseAppArg(raw: string | undefined): { app?: string; error?: string } {\n if (raw === undefined) return {}\n const selector = raw.trim()\n if (selector === '') {\n return {\n error:\n '--app was given an empty app id — pass an app id/name, or omit --app to use the current directory.',\n }\n }\n if (selector.startsWith('app_')) {\n if (!STRICT_APP_ID_RE.test(selector)) {\n return {\n error: `--app \"${selector}\" looks like an app id but isn't a valid app_<ULID> — check for a typo.`,\n }\n }\n return { app: selector }\n }\n if (!isCanonicalAppName(selector)) {\n return {\n error: `--app \"${selector}\" is not a valid app id or name (expected app_<ULID>, or a subdomain name — lowercase letters, digits and hyphens).`,\n }\n }\n return { app: selector }\n}\n\n/** Validate that a target is locally determinable before reading credentials. */\nexport function assertAppTargetResolvable(appArg: string | undefined): void {\n const { app, error } = parseAppArg(appArg)\n if (error) throw new InputError(error, 'invalid_app')\n if (app !== undefined) return\n\n const appDir = findAppDir()\n if (!appDir || !readAppId(appDir)) {\n throw new InputError(\n 'No app id. Run from an app directory whose wrangler.toml carries DEEPSPACE_APP_ID, or pass --app <id or name>.',\n 'not_in_app_repo',\n )\n }\n}\n\n/** Warn before an explicit unknown id can be registered by push or deploy. */\nexport async function warnIfPhantomApp(\n deployUrl: string,\n token: string,\n appId: string,\n explicit: string | undefined,\n): Promise<void> {\n if (!explicit || !STRICT_APP_ID_RE.test(explicit.trim())) return\n try {\n const { apps } = await apiFetch<{ apps: AppListEntry[] }>(deployUrl, token, '/api/apps')\n if (!apps.some((app) => app.appId === appId)) {\n process.stderr.write(\n `warning: ${appId} is not among your apps. If it exists and you have access ` +\n `(collaborator/admin), the server will use it; if it doesn't exist, this will ` +\n `register it as a NEW app under your account — check the id if that's not what ` +\n `you meant (a subdomain name also works with -a).\\n`,\n )\n }\n } catch {\n // Advisory only.\n }\n}\n","/**\n * deepspace auth whoami\n *\n * Shows the currently logged-in user. Auto-refreshes the JWT if expired.\n *\n * Prints all the identity fields a developer cares about (email, name,\n * userId, issuer) so you don't have to peek into ~/.deepspace/token.\n * Also flags whether the session is for a test account (`@deepspace.test`\n * email), since that's a meaningful distinction for who can do what — see\n * docs/auth/dev-vs-test-accounts.md.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport { ensureToken } from '../auth'\nimport { DASHBOARD_URL } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\ninterface JwtPayload {\n sub?: string\n name?: string\n email?: string\n image?: string | null\n iss?: string\n iat?: number\n exp?: number\n}\n\n/**\n * A network failure reaching the auth server (Node fetch throws\n * `TypeError: fetch failed`, or a DNS/socket errno) is NOT proof of being\n * logged out — code it apart so a retry isn't mistaken for a re-login.\n */\nconst isNetworkError = (err: unknown): boolean =>\n err instanceof TypeError ||\n (err instanceof Error &&\n /fetch failed|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|getaddrinfo|network/i.test(err.message))\n\nexport default defineDeepspaceCommand({\n meta: { name: 'whoami', description: 'Show the currently logged-in user' },\n async run({ args }) {\n let jwt: string\n try {\n jwt = await ensureToken()\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : 'Not logged in. Run `deepspace auth login` first.'\n // The code distinguishes a genuine logged-out state (log in) from an\n // unreachable auth server (retry): both would otherwise read as\n // \"not logged in\", and an agent would re-login instead of reconnecting.\n throw isNetworkError(err)\n ? new Refusal(msg, 'network_error')\n : new Refusal(msg, 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n let payload: JwtPayload\n try {\n payload = decodeJwtPayload<JwtPayload>(jwt)\n } catch {\n throw new Refusal('Malformed session token. Run `deepspace auth login` again.', 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const isTestAccount = !!payload.email?.endsWith('@deepspace.test')\n const accountType: 'developer' | 'test-account' | 'unknown' = isTestAccount\n ? 'test-account'\n : payload.email\n ? 'developer'\n : 'unknown'\n\n if (!args.json) {\n console.log(`Name: ${payload.name ?? '(none)'}`)\n console.log(`Email: ${payload.email ?? '(none)'}`)\n console.log(`UserID: ${payload.sub ?? '(none)'}`)\n console.log(`Type: ${accountType}`)\n if (payload.iss) console.log(`Issuer: ${payload.iss}`)\n console.log(`Dashboard: ${DASHBOARD_URL}`)\n if (isTestAccount) {\n console.log('')\n console.log('Note: this is a test account, not a real OAuth developer.')\n console.log('See docs/auth/dev-vs-test-accounts.md.')\n }\n }\n\n return {\n data: {\n name: payload.name ?? null,\n email: payload.email ?? null,\n userId: payload.sub ?? null,\n accountType,\n issuer: payload.iss ?? null,\n expiresAt: payload.exp ? new Date(payload.exp * 1000).toISOString() : null,\n },\n }\n },\n})\n","/**\n * deepspace app list\n *\n * Lists every app registered to the logged-in user — deployed or not — with\n * its id, live URL, and deploy state. This is the answer to \"which app do I\n * undeploy?\" when the deploy quota message names an id you've lost track of,\n * and the discovery surface for a second checkout / lost app dir.\n *\n * `--json` emits the entries for scripts, under `apps` in the standard\n * `{ ok, … }` envelope.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { apiFetch } from '../lib/api'\nimport { defineDeepspaceCommand } from '../lib/command'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\ninterface AppEntry {\n appId: string\n status: string\n createdAt: string\n deployedAt: string | null\n /** Current subdomain lease; null when undeployed. */\n name: string | null\n url: string | null\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'apps',\n description: 'List your apps (deployed and registered)',\n },\n async run({ args }) {\n const token = await ensureToken()\n const { apps } = await apiFetch<{ apps: AppEntry[] }>(DEPLOY_URL, token, '/api/apps')\n\n if (!args.json) {\n if (!apps.length) {\n console.log('No apps yet. Create one with `npx create-deepspace <name>` and `deepspace deploy`.')\n } else {\n const nameWidth = Math.max(4, ...apps.map((a) => (a.name ?? '—').length))\n const idWidth = Math.max(6, ...apps.map((a) => a.appId.length))\n console.log(`${'NAME'.padEnd(nameWidth)} ${'APP ID'.padEnd(idWidth)} URL`)\n for (const a of apps) {\n const url = a.url ?? '(not deployed)'\n console.log(`${(a.name ?? '—').padEnd(nameWidth)} ${a.appId.padEnd(idWidth)} ${url}`)\n }\n }\n }\n // No `next`: a listing is terminal — which app you act on, and how, is the\n // caller's choice.\n return { data: { apps } }\n },\n})\n","/**\n * deepspace logs\n *\n * Production logs for a deployed app — console output, request summaries,\n * and exceptions — read from Workers Logs through the platform (7-day\n * retention). Defaults to the last 15 minutes; `--follow` keeps polling\n * for new events until Ctrl+C. There is no push channel for\n * dispatch-namespace scripts, so polling IS the tail (the server's\n * `pollIntervalMs` sets the cadence).\n *\n * `--json` emits NDJSON — one event object per line — so agents and pipes\n * get a parseable stream in both one-shot and follow mode (deliberately\n * not the pretty-array shape `apps --json` uses). A truncated page also\n * emits one `{ \"type\": \"meta\", \"truncated\": true }` record (events never\n * carry a `type`, so consumers can branch on it) — otherwise a dropped\n * burst would be invisible to a machine reader.\n *\n * Ingestion lags real time by seconds up to ~1 minute: an empty result\n * right after a request is lag, not absence.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { apiFetch, ApiError } from '../lib/api'\nimport { InputError } from '../lib/cli-errors'\nimport { findAppDir } from '../lib/app-context'\nimport { resolveAppTarget } from '../lib/app-target'\nimport { readAppId } from '../lib/app-identity'\n// Whitelisted wire DTO + level set — shared with the platform reader and the\n// dashboard (packages/deepspace/src/shared/log-events.ts) so they can't drift.\nimport { LOG_LEVELS, type AppLogEvent, type AppLogsResponse } from '../../shared/log-events'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nconst RETENTION_MS = 7 * 24 * 60 * 60 * 1000\nconst DEFAULT_WINDOW_MS = 15 * 60 * 1000\nconst MIN_POLL_MS = 2500\n/**\n * Follow mode re-scans this far back of the last cursor before each poll.\n * Workers Logs ingestion is completion-ordered and lags up to ~1 min, so a\n * slow invocation's earlier-stamped line can arrive AFTER a fast request's\n * later-stamped line already advanced the cursor past it — polling only from\n * `cursor` would drop it permanently. The id dedupe (SeenEvents) discards the\n * re-fetched overlap, so the lag window costs nothing but a slightly larger page.\n *\n * Set above the stated ~60s max lag for margin: an event ingested more than\n * this late is still missed (CF's telemetry API has no ascending drain to\n * recover it), so this shrinks — not eliminates — the drop window.\n */\nconst FOLLOW_LAG_MS = 90_000\n\n/**\n * The page size a follow tail requests. Follow defaults to the max page so a\n * burst between polls is less likely to overflow one page and silently drop its\n * oldest events; an explicit `--limit` still wins. Exported for tests.\n */\nexport function followInitialLimit(limit: number | undefined, maxLimit: number): number {\n return limit ?? maxLimit\n}\n\n/**\n * Where the next follow poll starts: `FOLLOW_LAG_MS` before the last cursor,\n * floored at the original window start so a tail never scans before the user's\n * `--since`. Exported for tests.\n */\nexport function nextPollSince(cursor: number, floor: number, lagMs: number = FOLLOW_LAG_MS): number {\n return Math.max(cursor - lagMs, floor)\n}\n\n/**\n * `30s` / `15m` / `2h` / `7d` or an ISO timestamp → unix ms. Exported for\n * tests.\n */\nexport function parseSince(input: string, now: number = Date.now()): number {\n const trimmed = input.trim()\n const rel = /^(\\d+)([smhd])$/.exec(trimmed)\n let ts: number\n if (rel) {\n const unit = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }[rel[2] as 's' | 'm' | 'h' | 'd']\n ts = now - Number(rel[1]) * unit\n } else {\n ts = Date.parse(trimmed)\n if (Number.isNaN(ts)) {\n throw new InputError(`Invalid --since \"${input}\" — use 30s, 15m, 2h, 7d, or an ISO timestamp.`, 'invalid_since')\n }\n }\n if (now - ts > RETENTION_MS) {\n throw new InputError('Logs are retained for 7 days — --since can reach back at most 7d.', 'since_out_of_range')\n }\n return ts\n}\n\n/**\n * Rolling dedupe window for follow mode. Poll N+1 re-fetches from the last\n * cursor timestamp (inclusive), so events at exactly that millisecond come\n * back again; a bounded id set drops them without assuming server ordering.\n * Exported for tests.\n */\nexport class SeenEvents {\n private ids = new Set<string>()\n private order: string[] = []\n constructor(private cap = 5000) {}\n\n /** Returns only the events not seen before, recording them. */\n fresh(events: AppLogEvent[]): AppLogEvent[] {\n const out: AppLogEvent[] = []\n for (const e of events) {\n if (this.ids.has(e.id)) continue\n this.ids.add(e.id)\n this.order.push(e.id)\n out.push(e)\n }\n while (this.order.length > this.cap) {\n this.ids.delete(this.order.shift()!)\n }\n return out\n }\n}\n\n// ── Pretty rendering ─────────────────────────────────────────────────────────\n\nconst stdoutColor = () => process.stdout.isTTY && !process.env.NO_COLOR\n// Status/diagnostic lines go to stderr, so their coloring must gate on\n// stderr's TTY-ness — not stdout's, which may be redirected to a file/pipe.\nconst stderrColor = () => process.stderr.isTTY && !process.env.NO_COLOR\nconst paint = (code: string, s: string, on: boolean) => (on ? `\\x1b[${code}m${s}\\x1b[0m` : s)\n\nconst LEVEL_STYLE: Record<string, string | null> = {\n error: '31', // red\n warn: '33', // yellow\n debug: '2', // dim\n info: null,\n log: null,\n}\n\nfunction formatTime(ts: number, now: number): string {\n const d = new Date(ts)\n const ref = new Date(now)\n const hms =\n `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:` +\n `${String(d.getSeconds()).padStart(2, '0')}.${String(d.getMilliseconds()).padStart(3, '0')}`\n if (d.toDateString() === ref.toDateString()) return hms\n const ymd = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n return `${ymd} ${hms}`\n}\n\n/** One event → printable line(s). Exported for tests (pass color=false). */\nexport function formatEvent(e: AppLogEvent, color: boolean, now: number = Date.now()): string {\n const time = paint('2', formatTime(e.timestamp, now), color)\n\n let tag: string\n let body: string\n if (e.eventType === 'exception' && e.exception) {\n tag = paint('31', 'ERROR', color)\n const where = e.request ? ` — ${e.request.method} ${e.request.path}` : ''\n body = `${e.exception.name}: ${e.exception.message}${where}`\n if (e.exception.stack) {\n // Drop a leading \"Name: message\" header line (V8 style) so it isn't\n // shown twice — but Cloudflare worker stacks are often frame-only\n // (e.g. \" at fetch (index.js:1:1)\") with NO header, so only strip the\n // first line when it actually IS that header. Otherwise we'd eat a frame.\n const lines = e.exception.stack.split('\\n')\n const firstIsHeader = lines.length > 0 && !/^\\s*at\\s/.test(lines[0]) && lines[0].includes(e.exception.message)\n const frames = (firstIsHeader ? lines.slice(1) : lines)\n .map((l) => ' ' + l.trim())\n .filter((l) => l.trim().length > 0)\n if (frames.length) body += '\\n' + paint('2', frames.join('\\n'), color)\n }\n } else if (e.eventType === 'request' && e.request) {\n tag = paint('36', 'REQ ', color)\n const status = e.request.status !== undefined ? ` ${e.request.status}` : ''\n const outcome = e.outcome && e.outcome !== 'ok' ? ` (${e.outcome})` : ''\n body = `${e.request.method} ${e.request.path}${status}${outcome}`\n } else {\n const style = LEVEL_STYLE[e.level]\n tag = (e.level.toUpperCase() + ' ').slice(0, 5)\n if (style) tag = paint(style, tag, color)\n body = style ? paint(style, e.message, color) : e.message\n }\n\n // A browser-forwarded error is tagged so it's not mistaken for a server log.\n const client = e.source === 'client' ? paint('35', 'CLIENT', color) + ' ' : ''\n return `${time} ${client}${tag} ${body}`\n}\n\n// ── Command ──────────────────────────────────────────────────────────────────\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))\n\nexport default defineCommand({\n meta: {\n name: 'logs',\n description: 'Show production logs for a deployed app (add --follow to tail)',\n },\n args: {\n app: {\n type: 'string',\n alias: 'a',\n description: 'App id or name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description: 'wrangler.toml [env.<name>] slot — reads that env’s own app id',\n required: false,\n },\n follow: {\n type: 'boolean',\n alias: 'f',\n description: 'Keep polling for new logs until Ctrl+C (~3s cadence)',\n default: false,\n },\n since: {\n type: 'string',\n description: 'Window start: 30s, 15m, 2h, 24h, 7d, or an ISO timestamp (default 15m)',\n required: false,\n },\n level: {\n type: 'string',\n description: `Only events at a level: ${LOG_LEVELS.join(', ')}`,\n required: false,\n },\n search: {\n type: 'string',\n description: 'Only events whose message contains this text',\n required: false,\n },\n limit: {\n type: 'string',\n description: 'Max events per fetch (default 100, max 500)',\n required: false,\n },\n json: {\n type: 'boolean',\n description: 'Emit NDJSON — one event object per line (for agents/pipes)',\n default: false,\n },\n },\n async run({ args }) {\n const token = await ensureToken()\n\n const wranglerEnv = args.env?.trim() || undefined\n // --app and --env are two different ways to name the target. Combining them\n // is ambiguous — and previously --env was silently ignored when --app was\n // also passed — so fail fast rather than tail the wrong app.\n if (args.app && wranglerEnv) {\n throw new InputError(\n 'Pass either --app or --env, not both — --env reads the [env.<name>] block’s own app id, --app names an app directly.',\n 'ambiguous_target',\n )\n }\n let appId: string\n if (!args.app && wranglerEnv) {\n // `--env <name>` targets the [env.<name>] block's own app id (a staging\n // deploy is its own app) — same convention as `secrets --env`.\n const appDir = findAppDir()\n const id = appDir ? readAppId(appDir, wranglerEnv) : null\n if (!id) {\n throw new InputError(\n `No app id for env \"${wranglerEnv}\" — wrangler.toml has no [env.${wranglerEnv}] block with its own DEEPSPACE_APP_ID.`,\n 'no_app_id_for_env',\n )\n }\n appId = id\n } else {\n appId = await resolveAppTarget(DEPLOY_URL, token, args.app)\n }\n\n if (args.level && !(LOG_LEVELS as readonly string[]).includes(args.level)) {\n throw new InputError(`Invalid --level \"${args.level}\". Use: ${LOG_LEVELS.join(', ')}`, 'invalid_level')\n }\n let limit: number | undefined\n if (args.limit !== undefined) {\n limit = Number(args.limit)\n if (!Number.isInteger(limit) || limit < 1 || limit > 500) {\n throw new InputError('Invalid --limit — expected an integer between 1 and 500.', 'invalid_limit')\n }\n }\n\n const initialSince = args.since ? parseSince(args.since) : Date.now() - DEFAULT_WINDOW_MS\n const windowLabel = args.since?.trim() || '15m'\n\n // Server clamp; used as the follow-mode default so a burst between polls is\n // less likely to overflow one page (see the truncation note below).\n const MAX_LIMIT = 500\n const followLimit = followInitialLimit(limit, MAX_LIMIT)\n\n const fetchPage = async (\n since: number,\n pageLimit: number | undefined,\n token: string,\n ): Promise<AppLogsResponse> => {\n const params = new URLSearchParams({ since: String(since) })\n if (pageLimit !== undefined) params.set('limit', String(pageLimit))\n if (args.level) params.set('level', args.level)\n if (args.search) params.set('search', args.search)\n return apiFetch<AppLogsResponse>(DEPLOY_URL, token, `/api/apps/${appId}/logs?${params}`)\n }\n\n const print = (events: AppLogEvent[]) => {\n for (const e of events) {\n process.stdout.write(args.json ? JSON.stringify(e) + '\\n' : formatEvent(e, stdoutColor()) + '\\n')\n }\n }\n\n // Follow mode tails from the max page too — a first page capped at the\n // default 100 would drop the rest of the initial window and jump the cursor\n // past it. One-shot mode keeps the user's (possibly unset) --limit.\n const first = await fetchPage(initialSince, args.follow ? followLimit : limit, token)\n print(first.events)\n\n if (!args.follow) {\n if (first.events.length === 0) {\n if (args.json) {\n // An empty NDJSON stream is indistinguishable from a crash without a\n // trailing record — emit a discriminable meta line so an agent can\n // tell \"ran, no events\" from \"died\". (events never carry `type`.)\n process.stdout.write(JSON.stringify({ type: 'meta', count: 0, window: windowLabel }) + '\\n')\n } else {\n console.log(\n `No logs in the last ${windowLabel} for ${appId}. New logs can take up to a minute to appear; retention is 7 days.`,\n )\n }\n } else if (first.truncated) {\n // A machine consumer reading NDJSON needs the signal too — emit a\n // discriminable meta record (events never carry a `type` field).\n if (args.json) process.stdout.write(JSON.stringify({ type: 'meta', truncated: true }) + '\\n')\n else console.error(`(showing the newest ${first.events.length} events — narrow with --since/--level/--search)`)\n }\n return\n }\n\n // ── Follow mode ──────────────────────────────────────────────────────────\n process.on('SIGINT', () => process.exit(0))\n if (!args.json) {\n console.error(`Tailing logs for ${appId} — Ctrl+C to stop.`)\n }\n\n // Poll for the newest events each tick. A page is capped at `limit`; when\n // more than that arrive between two polls, the server returns the NEWEST\n // and the cursor advances past the oldest of the burst — those are dropped,\n // not just delayed (CF's telemetry API has no ascending order to drain\n // forward). Default follow polls to the max page size to shrink that window,\n // and warn on `truncated` so a drop is never silent.\n const seen = new SeenEvents()\n seen.fresh(first.events)\n let cursor = first.cursor ?? initialSince\n let interval = Math.max(first.pollIntervalMs || 0, MIN_POLL_MS)\n let backoff = 0\n // Warn only on the transition into truncation, not every poll — a\n // sustained burst would otherwise flood the stream.\n let warnedTruncated = false\n\n // The initial page can already be truncated (the window held more than one\n // page). The loop only checks pages it fetches, so surface it once here —\n // otherwise `-f` would drop the overflow silently, unlike one-shot mode.\n if (first.truncated) {\n warnedTruncated = true\n if (args.json) {\n process.stdout.write(JSON.stringify({ type: 'meta', truncated: true }) + '\\n')\n } else {\n console.error(\n paint('33', `(more than ${followLimit} events in the initial ${windowLabel} window — some older events not shown; narrow with --since/--level/--search)`, stderrColor()),\n )\n }\n }\n\n for (;;) {\n await sleep(backoff || interval)\n // Refresh the token BEFORE the retryable fetch: the JWT is 5-minute-lived\n // and a tail outlives it. A refresh failure (session expired / logged out)\n // throws a plain Error and is fatal — it will not fix itself by retrying,\n // so let it propagate and end the tail cleanly.\n const freshToken = await ensureToken()\n let page: AppLogsResponse\n try {\n // Re-scan a lag window before the cursor so a late-ingested,\n // earlier-stamped event isn't skipped; SeenEvents drops the overlap.\n page = await fetchPage(nextPollSince(cursor, initialSince), followLimit, freshToken)\n } catch (err) {\n // Auth/authz/absence is fatal — the situation won't improve by\n // retrying. Everything else (5xx, 429, network) backs off.\n if (err instanceof ApiError && [401, 403, 404].includes(err.status)) throw err\n backoff = Math.min(backoff ? backoff * 2 : MIN_POLL_MS, 30_000)\n const msg = err instanceof Error ? err.message : String(err)\n console.error(paint('2', `(logs fetch failed: ${msg} — retrying in ${backoff / 1000}s)`, stderrColor()))\n continue\n }\n backoff = 0\n interval = Math.max(page.pollIntervalMs || 0, MIN_POLL_MS)\n const fresh = seen.fresh(page.events)\n print(fresh)\n // Warn only when a poll delivered a FULL page of genuinely-new events —\n // the real drop signal. `page.truncated` counts the re-scanned (already\n // seen, deduped) lag-window overlap toward the cap, so it cries wolf on a\n // busy-but-lossless tail; `fresh.length` excludes that overlap.\n const realDrop = fresh.length >= followLimit\n if (realDrop && !warnedTruncated) {\n warnedTruncated = true\n if (args.json) {\n process.stdout.write(JSON.stringify({ type: 'meta', truncated: true }) + '\\n')\n } else {\n console.error(\n paint('33', `(burst exceeded ${followLimit} events/poll — some may be dropped; narrow with --level/--search)`, stderrColor()),\n )\n }\n } else if (!realDrop) {\n warnedTruncated = false\n }\n if (page.cursor !== null) cursor = page.cursor\n }\n },\n})\n","/**\n * `deepspace logs` wire DTO — the single source of truth for the whitelisted\n * shape the platform telemetry reader emits and every consumer reads.\n *\n * The producer is `platform/deploy-worker/src/lib/workers-logs.ts` (which\n * rebuilds each event field-by-field from a raw Cloudflare row — see the\n * security invariant there). The consumers are the CLI tail\n * (`cli/commands/logs.ts`), the dashboard Logs panel\n * (`apps/dashboard/src/lib/apps.ts`), and the e2e whitelist assertion\n * (`tests/e2e/tests/logs.spec.ts`). This module used to be hand-mirrored in\n * all four places; `source` was added to three of them and missed in the\n * e2e whitelist, so it now lives here once and they import it.\n *\n * Isomorphic — no DOM, no Hono, no platform types — so it re-exports cleanly\n * from both `deepspace` (client) and `deepspace/worker` and is safe to import\n * from the private deploy-worker.\n */\n\nexport const LOG_LEVELS = ['debug', 'log', 'info', 'warn', 'error'] as const\nexport type LogLevel = (typeof LOG_LEVELS)[number]\n\n/** One log / request / exception event, rebuilt field-by-field from a CF row. */\nexport interface AppLogEvent {\n /** `$metadata.id` — unique per event; the client's dedupe key. */\n id: string\n /** Unix ms. */\n timestamp: number\n level: LogLevel\n eventType: 'log' | 'request' | 'exception' | 'other'\n message: string\n /**\n * Present (= `'client'`) only for a browser-forwarded error the app's own\n * Worker re-logged via `registerClientErrorRoute`. Absent means the log was\n * emitted server-side — there is no explicit `'server'` value, so consumers\n * branch on `source === 'client'`, never on a truthy/other check.\n */\n source?: 'client'\n /** Invocation outcome (`ok`, `exception`, `exceededCpu`, …) when present. */\n outcome?: string\n request?: { method: string; path: string; status?: number }\n exception?: { name: string; message: string; stack?: string }\n}\n\nexport interface AppLogsResponse {\n /** Ascending by timestamp (CF returns newest-first; the reader flips). */\n events: AppLogEvent[]\n /** Max event timestamp in ms — pass back as `since` to poll; null when empty. */\n cursor: number | null\n /** True when the window returned `limit` events (older events were cut). */\n truncated: boolean\n pollIntervalMs: number\n}\n\n/**\n * Runtime tuple of every key a whitelisted `AppLogEvent` may carry — the\n * canonical whitelist the e2e suite mirrors when asserting no event leaks a key\n * outside this set. The two type-level assertions below fail compilation if\n * this tuple and the `AppLogEvent` interface disagree in either direction, so\n * adding an interface field forces a matching key here.\n *\n * NOTE: the e2e spec keeps its OWN copy of this set (it can't import the SDK —\n * `@deepspace/e2e` has no `deepspace` dependency), kept in step by a comment,\n * not by these compile-time guards. So this tuple hardens the code copies\n * (deploy-worker/CLI/dashboard, which import it), while the e2e mirror remains a\n * knowingly-accepted duplicate.\n */\nexport const APP_LOG_EVENT_KEYS = [\n 'id',\n 'timestamp',\n 'level',\n 'eventType',\n 'message',\n 'source',\n 'outcome',\n 'request',\n 'exception',\n] as const\n\nexport type AppLogEventKey = (typeof APP_LOG_EVENT_KEYS)[number]\n\n// Compile-time guard: `APP_LOG_EVENT_KEYS` and `keyof AppLogEvent` list the\n// same keys. If either drifts, one of these aliases resolves to `never` and\n// `tsc` errors on the assignment.\ntype _KeysCoverInterface = AppLogEventKey extends keyof AppLogEvent ? true : never\ntype _InterfaceCoversKeys = keyof AppLogEvent extends AppLogEventKey ? true : never\nconst _assertKeysMatch: [_KeysCoverInterface, _InterfaceCoversKeys] = [true, true]\nvoid _assertKeysMatch\n","/**\n * deepspace app usage\n *\n * Shows the logged-in user's credit balance, quota headroom, and\n * per-integration spend — the CLI view of the dashboard's billing page.\n * Agents driving `deepspace integrations invoke` pay per call; this is how they check\n * the balance without a browser.\n *\n * Units: credits are the billing unit (100 credits = $1) and can be\n * fractional. Integration costs come back in USD — the marked-up figures\n * actually deducted from the balance. The balance covers the current\n * billing period; the per-integration table is a fixed 30-day window\n * (server-side).\n *\n * `--json` emits the /api/usage/summary response for scripts, inside the\n * standard `{ ok, … }` envelope.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS, DASHBOARD_URL } from '../env'\nimport { apiFetch } from '../lib/api'\nimport { defineDeepspaceCommand } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\ninterface CreditBucket {\n allocation: number\n used: number\n remaining: number\n}\n\nexport interface UsageSummary {\n credits: {\n credits: number\n totalUsed: number\n totalAllocation: number\n subscription: CreditBucket & { tier: string; renewsAt: string | null }\n bonus: CreditBucket & { expiresAt: string | null; expired: boolean }\n purchased: CreditBucket\n }\n usageByIntegration: { name: string; totalCost: number; count: number }[]\n /** Passed through on --json; not rendered in human output. */\n recentUsage: unknown[]\n}\n\n/**\n * Credits accrue in fractions (a small call can be 0.65 credits). Mirrors\n * the dashboard's CreditsMeter formatting so both surfaces read the same.\n */\nexport function formatCredits(value: number): string {\n if (value > 0 && value < 1) return '<1'\n if (value < 10) return value.toFixed(1).replace(/\\.0$/, '')\n return Math.round(value).toLocaleString('en-US')\n}\n\n/** Integration costs are often sub-cent; show 4 decimals below $0.01. */\nexport function formatUsd(value: number): string {\n return `$${Math.abs(value) >= 0.01 || value === 0 ? value.toFixed(2) : value.toFixed(4)}`\n}\n\n// UTC so the printed date matches the ISO timestamp regardless of the\n// machine's timezone (a midnight-UTC renewal shouldn't shift a day).\nfunction formatDate(iso: string): string {\n return new Date(iso).toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n year: 'numeric',\n timeZone: 'UTC',\n })\n}\n\nexport function renderSummary(summary: UsageSummary): string {\n const { credits, usageByIntegration } = summary\n const lines: string[] = []\n\n const renews = credits.subscription.renewsAt\n ? ` · renews ${formatDate(credits.subscription.renewsAt)}`\n : ''\n lines.push(`Plan: ${credits.subscription.tier}${renews}`)\n lines.push(\n `Credits: ${formatCredits(credits.credits)} of ${formatCredits(credits.totalAllocation)} remaining (100 credits = $1)`,\n )\n\n // A bucket breakdown only earns space when a pool beyond the subscription\n // is in play — otherwise it would just repeat the Credits line.\n const bonusActive = credits.bonus.allocation > 0 || credits.bonus.expired\n const purchasedActive = credits.purchased.allocation > 0 || credits.purchased.used > 0\n if (bonusActive || purchasedActive) {\n const bucket = (b: CreditBucket) =>\n `${formatCredits(b.remaining)} of ${formatCredits(b.allocation)} remaining`\n lines.push(` Subscription: ${bucket(credits.subscription)}`)\n if (bonusActive) {\n const expires = credits.bonus.expiresAt\n ? ` · expires ${formatDate(credits.bonus.expiresAt)}`\n : ''\n lines.push(\n ` Bonus: ${credits.bonus.expired ? 'expired' : bucket(credits.bonus) + expires}`,\n )\n }\n if (purchasedActive) {\n lines.push(` Purchased: ${bucket(credits.purchased)}`)\n }\n }\n\n lines.push('')\n if (!usageByIntegration.length) {\n lines.push('No integration usage in the last 30 days.')\n } else {\n lines.push('Usage by integration (last 30 days):')\n const nameWidth = Math.max(11, ...usageByIntegration.map((u) => u.name.length))\n lines.push(`${'INTEGRATION'.padEnd(nameWidth)} CALLS COST`)\n for (const u of usageByIntegration) {\n lines.push(`${u.name.padEnd(nameWidth)} ${String(u.count).padEnd(5)} ${formatUsd(u.totalCost)}`)\n }\n }\n\n lines.push('')\n lines.push(`Dashboard: ${DASHBOARD_URL}`)\n return lines.join('\\n')\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'usage',\n description: 'Show credit balance, quota headroom, and per-integration spend',\n },\n async run({ args }) {\n const token = await ensureToken()\n const summary = await apiFetch<UsageSummary>(API_URL, token, '/api/usage/summary')\n\n if (!args.json) console.log(renderSummary(summary))\n // No `next`: reading the balance is terminal — topping up happens in the\n // dashboard, which the human output already links.\n return { data: { ...summary } }\n },\n})\n","/**\n * deepspace add <feature> [dir]\n *\n * Catalog reads use this running CLI's package. Installation loads the typed\n * installer shipped by the target app's installed DeepSpace version, so an\n * app never receives feature files or manifest rules from a different SDK.\n */\n\nimport { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { ensureInstallReady } from '../lib/install-status'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\nimport {\n featureCatalog,\n featurePackageRoot,\n hasFeatureCatalog,\n installFeature as runningInstaller,\n listFeatureConfigs,\n readFeatureConfig,\n resolveFeatureDestPath,\n suggestFeature,\n type FeatureConfig,\n type FeatureInstallOptions,\n type FeatureInstallOutcome,\n} from './feature-installer'\n\nconst CATEGORY_LABELS: Record<string, string> = {\n assistant: 'AI Features',\n data: 'Data Features',\n nav: 'Navigation',\n layout: 'Layouts',\n display: 'Display',\n landing: 'Landing Page Sections',\n}\nconst CATEGORY_ORDER = ['assistant', 'data', 'nav', 'layout', 'display', 'landing']\n\ninterface FeatureInstallerModule {\n installFeature(options: FeatureInstallOptions): FeatureInstallOutcome\n}\n\nfunction groupByCategory(features: FeatureConfig[]): Map<string, FeatureConfig[]> {\n const groups = new Map<string, FeatureConfig[]>()\n for (const feature of features) {\n const category = feature.category ?? 'other'\n groups.set(category, [...(groups.get(category) ?? []), feature])\n }\n return groups\n}\n\nfunction orderedCategories(groups: Map<string, FeatureConfig[]>): string[] {\n const known = CATEGORY_ORDER.filter((category) => groups.has(category))\n const unknown = [...groups.keys()]\n .filter((category) => !CATEGORY_ORDER.includes(category))\n .sort((a, b) => a.localeCompare(b))\n return [...known, ...unknown]\n}\n\nfunction catalogLines(\n groups: Map<string, FeatureConfig[]>,\n render: (feature: FeatureConfig) => string,\n): string[] {\n const lines: string[] = []\n for (const category of orderedCategories(groups)) {\n const features = groups.get(category)\n if (!features?.length) continue\n lines.push(`${CATEGORY_LABELS[category] ?? category}:`)\n for (const feature of features) lines.push(render(feature))\n lines.push('')\n }\n return lines\n}\n\nexport function renderFeatureHelp(packageRoot: string = featurePackageRoot()): string {\n const groups = groupByCategory(listFeatureConfigs(packageRoot))\n const example = orderedCategories(groups)\n .map((category) => groups.get(category)?.[0]?.id)\n .find(Boolean)\n return [\n '',\n 'Add a feature to your DeepSpace app',\n '',\n 'Usage: deepspace add <feature> [dir]',\n '',\n 'Commands:',\n ' <feature> [dir] Install a feature (dir defaults to .)',\n ' --list, -l List all available features',\n ' --info <feature> Show detailed info about a feature',\n ' --install Run your package manager after adding deps',\n ' --help, -h Show this help',\n '',\n ...catalogLines(groups, (feature) => ` ${feature.id.padEnd(22)} ${feature.name}`),\n 'Examples:',\n ' deepspace add --list',\n ` deepspace add ${example ?? '<feature>'}`,\n ` deepspace add ${example ?? '<feature>'} ./my-app`,\n '',\n ].join('\\n')\n}\n\nexport function renderFeatureList(packageRoot: string = featurePackageRoot()): string {\n const groups = groupByCategory(listFeatureConfigs(packageRoot))\n return [\n '',\n 'Available Features',\n '',\n ...catalogLines(\n groups,\n (feature) =>\n ` ${feature.id.padEnd(22)} ${feature.name.padEnd(24)} ${feature.description ?? ''}`,\n ),\n 'Use: deepspace add <feature>',\n '',\n ].join('\\n')\n}\n\nexport function renderFeatureInfo(config: FeatureConfig): string {\n const lines = ['', `${config.name} (${config.id})`]\n if (config.category) {\n lines.push(` Category: ${CATEGORY_LABELS[config.category] ?? config.category}`)\n }\n lines.push(` ${config.description ?? ''}`, '', ` ${config.details ?? ''}`, '', ' Files:')\n for (const file of config.files) {\n lines.push(` - ${file.src} -> ${resolveFeatureDestPath(file.dest, config.route)}`)\n }\n if (config.instructions?.length) {\n lines.push('', ' Integration steps:')\n config.instructions.forEach((instruction, index) => {\n lines.push(` ${index + 1}. ${instruction}`)\n })\n }\n if (config.patterns?.length) {\n lines.push('', ' Patterns:')\n config.patterns.forEach((pattern) => lines.push(` - ${pattern}`))\n }\n if (config.example) {\n lines.push('', ' Example:')\n config.example.split('\\n').forEach((line) => lines.push(` ${line}`))\n }\n lines.push('')\n return lines.join('\\n')\n}\n\n/** A bare directory is not an install target even if dependency setup happens to exist above it. */\nexport function isDeepSpaceApp(dir: string): boolean {\n if (existsSync(join(dir, 'wrangler.toml'))) return true\n const packagePath = join(dir, 'package.json')\n if (!existsSync(packagePath)) return false\n try {\n const pkg = JSON.parse(readFileSync(packagePath, 'utf-8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n return Boolean(pkg.dependencies?.deepspace || pkg.devDependencies?.deepspace)\n } catch {\n return false\n }\n}\n\n/** Match Node's upward dependency lookup, including DeepSpace worktrees nested in an app. */\nfunction installedPackageRoot(fromDir: string): string | null {\n let dir = fromDir\n for (;;) {\n const candidate = join(dir, 'node_modules', 'deepspace')\n if (existsSync(join(candidate, 'package.json'))) return candidate\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\nasync function targetInstaller(appDir: string): Promise<FeatureInstallerModule> {\n const installedRoot = installedPackageRoot(appDir)\n if (!installedRoot) {\n throw new Refusal(\n \"Could not resolve the app's installed deepspace package. Run your package manager, then retry.\",\n 'feature_installer_missing',\n )\n }\n\n // Tests and source checkouts commonly link this exact package. Avoid asking\n // them for an emitted build entry when the already-loaded typed owner is the\n // same package on disk.\n if (realpathSync(installedRoot) === realpathSync(featurePackageRoot())) {\n return { installFeature: runningInstaller }\n }\n\n const entry = join(installedRoot, 'dist', 'feature-installer.js')\n const catalog = join(installedRoot, 'features')\n if (!existsSync(entry) || !existsSync(catalog)) {\n throw new Refusal(\n \"The app's installed deepspace package does not contain the typed feature installer.\\n\" +\n `Expected: ${entry}\\n` +\n 'Install a current DeepSpace version in the app, then retry.',\n 'feature_installer_missing',\n )\n }\n\n let loaded: Partial<FeatureInstallerModule>\n try {\n loaded = (await import(pathToFileURL(entry).href)) as Partial<FeatureInstallerModule>\n } catch (error) {\n throw new Refusal(\n `Could not load the app's feature installer: ${\n error instanceof Error ? error.message : String(error)\n }`,\n 'feature_installer_invalid',\n )\n }\n if (typeof loaded.installFeature !== 'function') {\n throw new Refusal(`Invalid feature installer entry: ${entry}`, 'feature_installer_invalid')\n }\n return loaded as FeatureInstallerModule\n}\n\nfunction catalogRoot(): string {\n const root = featurePackageRoot()\n if (!hasFeatureCatalog(root)) {\n throw new Refusal(\n 'Could not find the deepspace feature catalog.\\n' +\n 'Reinstall deepspace or run inside a DeepSpace app.',\n 'feature_catalog_missing',\n )\n }\n return root\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'add',\n description: 'Add a feature to your DeepSpace app',\n },\n args: {\n list: {\n type: 'boolean',\n alias: 'l',\n description: 'List available features',\n required: false,\n },\n info: {\n type: 'string',\n description: 'Show details about a feature',\n required: false,\n },\n install: {\n type: 'boolean',\n description: 'Run your package manager after adding dependencies',\n required: false,\n },\n feature: {\n type: 'positional',\n description: 'Feature to install',\n required: false,\n },\n dir: {\n type: 'positional',\n description: 'App directory (default: current directory)',\n required: false,\n },\n },\n async run({ args }) {\n const feature = args.feature as string | undefined\n const info = args.info as string | undefined\n\n if (args.list || info || !feature) {\n const root = catalogRoot()\n if (info) {\n const config = readFeatureConfig(info, root)\n if (!config) {\n const suggestion = suggestFeature(info, root)\n throw new Refusal(\n [\n `Unknown feature: ${info}`,\n ...(suggestion ? [`Did you mean \"${suggestion}\"?`] : []),\n 'Run `deepspace add --list` to see available features.',\n ].join('\\n'),\n 'unknown_feature',\n { action: cliAction('deepspace', 'add', '--list') },\n )\n }\n if (!args.json) process.stdout.write(renderFeatureInfo(config))\n return { data: { feature: config } }\n }\n\n if (!args.json) {\n process.stdout.write(args.list ? renderFeatureList(root) : renderFeatureHelp(root))\n }\n return { data: { features: featureCatalog(root) } }\n }\n\n const appDir = resolve((args.dir as string | undefined) ?? '.')\n if (!existsSync(appDir)) {\n throw new Refusal(\n `Target directory not found: ${appDir}\\nCreate a new app first: deepspace app create <name>`,\n 'app_dir_not_found',\n )\n }\n if (!isDeepSpaceApp(appDir)) {\n throw new Refusal(\n `Not a DeepSpace app: ${appDir}\\n` +\n '(no wrangler.toml and no \"deepspace\" dependency found)\\n' +\n 'Create one with: deepspace app create <name>',\n 'not_a_deepspace_app',\n )\n }\n\n ensureInstallReady(appDir)\n const installer = await targetInstaller(appDir)\n let outcome: FeatureInstallOutcome\n try {\n outcome = installer.installFeature({\n feature,\n targetDir: appDir,\n installDependencies: Boolean(args.install),\n ...(!args.json\n ? {\n emit(line: string, stream: 'stdout' | 'stderr' = 'stdout') {\n if (stream === 'stderr') console.error(line)\n else console.log(line)\n },\n }\n : {}),\n })\n } catch (error) {\n throw new Refusal(\n `Installing '${feature}' failed: ${error instanceof Error ? error.message : String(error)}`,\n 'add_failed',\n )\n }\n if (!outcome || typeof outcome.ok !== 'boolean') {\n throw new Refusal(\n \"The app's feature installer returned an invalid result.\",\n 'feature_installer_invalid',\n )\n }\n\n if (!outcome.ok) {\n throw new Refusal(outcome.error, outcome.code, {\n ...('data' in outcome ? { extra: outcome.data } : {}),\n })\n }\n return {\n data: outcome.data,\n ...(outcome.action ? { action: outcome.action } : {}),\n }\n },\n})\n","/**\n * The feature catalog and installer.\n *\n * This is a separate build entry because `add` loads the copy shipped by the\n * target app's installed `deepspace` package. That keeps feature files,\n * manifest interpretation, and mutations on the app-pinned SDK version while\n * leaving the public command/output contract in add.ts.\n */\n\nimport {\n closeSync,\n copyFileSync,\n existsSync,\n fstatSync,\n mkdirSync,\n mkdtempSync,\n openSync,\n readFileSync,\n readSync,\n readdirSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { spawnSync } from 'node:child_process'\nimport { tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { detectPackageManager } from '../lib/package-manager'\n\nconst NAV_MARKER = '// ── Features add nav items below this line ──'\n\ninterface FeatureFile {\n src: string\n dest: string\n overwrite?: boolean\n}\n\ninterface FeatureSchema {\n exportName: string\n importPath: string\n spreadOperator?: boolean\n}\n\ninterface FeatureAction {\n exportName: string\n registerAs: string\n importPath: string\n}\n\nexport interface FeatureConfig {\n id: string\n name: string\n category?: string\n description?: string\n details?: string\n internal?: boolean\n files: FeatureFile[]\n route?: { path?: string; protected?: boolean }\n schema?: FeatureSchema\n actions?: FeatureAction[]\n css?: string[]\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n instructions?: string[]\n patterns?: string[]\n agentNotes?: string[]\n example?: string\n [key: string]: unknown\n}\n\nexport interface FeatureCatalogEntry {\n id: string\n name: string\n category: string | null\n description: string | null\n}\n\ntype DependencySection = 'dependencies' | 'devDependencies'\n\ninterface DependencyAddition {\n name: string\n section: DependencySection\n version: unknown\n}\n\ntype IntegrationArea = 'schema' | 'actions' | 'css' | 'nav'\n\ninterface UnresolvedIntegration {\n area: IntegrationArea\n reason: string\n steps: string[]\n}\n\ninterface InstallData extends Record<string, unknown> {\n feature: string\n dir: string\n installed: boolean\n observedChanges: {\n files: { created: string[]; preexisting: string[]; missing: string[] }\n dependencies: {\n added: DependencyAddition[]\n missingDeclarations: string[]\n installRequested: boolean\n diagnosticTail?: string\n }\n }\n unresolvedIntegrations: UnresolvedIntegration[]\n manifestGuidance: {\n instructions: string[]\n patterns: string[]\n agentNotes: string[]\n }\n}\n\ninterface InstallerAction {\n cwd: string\n argv: string[]\n}\n\nexport type FeatureInstallOutcome =\n | { ok: true; data: InstallData; action?: InstallerAction }\n | {\n ok: false\n code: 'unknown_feature'\n error: string\n data: {\n requestedFeature: string\n suggestedFeature: string | null\n availableFeatures: FeatureCatalogEntry[]\n }\n }\n | {\n ok: false\n code: 'dependency_install_failed' | 'manual_integration_required'\n error: string\n data: InstallData\n }\n\nexport type FeatureInstallerOutput = (line: string, stream?: 'stdout' | 'stderr') => void\n\nexport interface FeatureInstallOptions {\n feature: string\n targetDir: string\n installDependencies: boolean\n emit?: FeatureInstallerOutput\n}\n\n/** Find the package containing this source file or emitted build entry. */\nexport function featurePackageRoot(moduleUrl: string = import.meta.url): string {\n let dir = dirname(fileURLToPath(moduleUrl))\n for (;;) {\n const packagePath = join(dir, 'package.json')\n if (existsSync(packagePath)) {\n try {\n const pkg = JSON.parse(readFileSync(packagePath, 'utf-8')) as { name?: unknown }\n if (pkg.name === 'deepspace') return dir\n } catch {\n // Keep walking: a nearer unrelated package.json is not this package.\n }\n }\n const parent = dirname(dir)\n if (parent === dir) throw new Error('Could not locate the deepspace package root')\n dir = parent\n }\n}\n\nexport function hasFeatureCatalog(packageRoot: string = featurePackageRoot()): boolean {\n return existsSync(join(packageRoot, 'features'))\n}\n\nexport function readFeatureConfig(\n id: string,\n packageRoot: string = featurePackageRoot(),\n): FeatureConfig | null {\n const configPath = join(packageRoot, 'features', id, 'feature.json')\n if (!existsSync(configPath)) return null\n try {\n const config = JSON.parse(readFileSync(configPath, 'utf-8')) as Partial<FeatureConfig>\n if (\n typeof config.id !== 'string' ||\n typeof config.name !== 'string' ||\n !Array.isArray(config.files)\n ) {\n return null\n }\n return config as FeatureConfig\n } catch {\n return null\n }\n}\n\nexport function listFeatureConfigs(packageRoot: string = featurePackageRoot()): FeatureConfig[] {\n const featuresDir = join(packageRoot, 'features')\n if (!existsSync(featuresDir)) return []\n return readdirSync(featuresDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => readFeatureConfig(entry.name, packageRoot))\n .filter((config): config is FeatureConfig => config !== null && !config.internal)\n .sort((a, b) => a.id.localeCompare(b.id))\n}\n\nexport function featureCatalog(packageRoot: string = featurePackageRoot()): FeatureCatalogEntry[] {\n return listFeatureConfigs(packageRoot).map((config) => ({\n id: config.id,\n name: config.name,\n category: config.category ?? null,\n description: config.description ?? null,\n }))\n}\n\nfunction editDistance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, index) => index)\n for (let i = 1; i <= a.length; i++) {\n let previous = row[0]\n row[0] = i\n for (let j = 1; j <= b.length; j++) {\n const current = row[j]\n row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1))\n previous = current\n }\n }\n return row[b.length]\n}\n\nexport function suggestFeature(\n featureId: string,\n packageRoot: string = featurePackageRoot(),\n): string | null {\n let closest: string | null = null\n let closestDistance = Number.POSITIVE_INFINITY\n for (const feature of listFeatureConfigs(packageRoot)) {\n const distance = editDistance(featureId, feature.id)\n if (distance < closestDistance) {\n closest = feature.id\n closestDistance = distance\n }\n }\n const threshold = Math.max(2, Math.floor(featureId.length / 3))\n return closest !== null && closestDistance <= threshold ? closest : null\n}\n\nfunction resolveTargetDir(raw: string): string {\n return isAbsolute(raw) ? raw : resolve(raw)\n}\n\nexport function resolveFeatureDestPath(fileDest: string, route: FeatureConfig['route']): string {\n const pages = 'src/pages/'\n const appPages = 'src/pages/(app)/'\n if (!fileDest.startsWith(pages) || fileDest.startsWith(appPages)) return fileDest\n const rest = fileDest.slice(pages.length)\n return route?.protected === false ? `${appPages}${rest}` : `${appPages}(protected)/${rest}`\n}\n\nfunction copyFile(src: string, dest: string): void {\n mkdirSync(dirname(dest), { recursive: true })\n copyFileSync(src, dest)\n}\n\nfunction copyFileWithImportShift(src: string, dest: string, levels: number): void {\n mkdirSync(dirname(dest), { recursive: true })\n const prefix = '../'.repeat(levels)\n const shifted = readFileSync(src, 'utf-8').replace(\n /(from\\s+|import\\s+|import\\()(['\"])(\\.\\.\\/)/g,\n `$1$2${prefix}$3`,\n )\n writeFileSync(dest, shifted)\n}\n\nfunction installFiles(\n packageRoot: string,\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): {\n copied: number\n skipped: number\n files: { created: string[]; preexisting: string[]; missing: string[] }\n} {\n let copied = 0\n let skipped = 0\n const created: string[] = []\n const preexisting: string[] = []\n const missing: string[] = []\n\n for (const file of config.files) {\n const srcPath = join(packageRoot, 'features', config.id, file.src)\n const resolvedDest = resolveFeatureDestPath(file.dest, config.route)\n const destPath = join(targetDir, resolvedDest)\n const existed = existsSync(destPath)\n if (existed) preexisting.push(resolvedDest)\n\n if (!existsSync(srcPath)) {\n emit(` Warning: source not found: ${file.src}`, 'stderr')\n if (!existed) missing.push(resolvedDest)\n continue\n }\n\n if (existed && !file.overwrite) {\n emit(` Exists (skipped): ${resolvedDest}`)\n skipped++\n continue\n }\n\n const wasRedirected = resolvedDest !== file.dest\n const shiftLevels = resolvedDest.split('/').length - file.dest.split('/').length\n if (wasRedirected) copyFileWithImportShift(srcPath, destPath, shiftLevels)\n else copyFile(srcPath, destPath)\n emit(` ${existed ? 'Overwrote' : 'Copied'}: ${resolvedDest}`)\n if (!existed) created.push(resolvedDest)\n copied++\n }\n\n return { copied, skipped, files: { created, preexisting, missing } }\n}\n\nfunction unresolvedSchema(\n schema: FeatureSchema,\n reason: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration {\n const entry = schema.spreadOperator ? `...${schema.exportName}` : schema.exportName\n emit('')\n emit(' Add manually to src/schemas.ts:')\n emit(` import { ${schema.exportName} } from '${schema.importPath}'`)\n emit(` // then add ${entry} to the schemas array`)\n return {\n area: 'schema',\n reason,\n steps: [\n `Add import { ${schema.exportName} } from '${schema.importPath}' to src/schemas.ts.`,\n `Add ${entry} to the exported schemas array.`,\n ],\n }\n}\n\nfunction integrateSchema(\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration[] {\n if (!config.schema) return []\n const schemasPath = join(targetDir, 'src', 'schemas.ts')\n if (!existsSync(schemasPath)) {\n return [unresolvedSchema(config.schema, 'src/schemas.ts was not found.', emit)]\n }\n\n let content = readFileSync(schemasPath, 'utf-8')\n const { exportName, importPath, spreadOperator } = config.schema\n const importPattern = new RegExp(`^import\\\\s+\\\\{[^}]*\\\\b${exportName}\\\\b`, 'm')\n if (importPattern.test(content)) {\n emit(` Schema already present: ${exportName}`)\n return []\n }\n if (\n !content.includes('export const schemas') ||\n !/export const schemas:\\s*CollectionSchema\\[\\]\\s*=\\s*\\[/.test(content)\n ) {\n const reason = 'src/schemas.ts has an unexpected structure.'\n emit(` Could not auto-integrate schema (${reason})`)\n return [unresolvedSchema(config.schema, reason, emit)]\n }\n\n const importLine = `import { ${exportName} } from '${importPath}'`\n const withImport = content.replace(\n /export const schemas/,\n `${importLine}\\n\\nexport const schemas`,\n )\n const schemaEntry = spreadOperator ? `...${exportName}` : exportName\n const withEntry = withImport.replace(\n /export const schemas:\\s*CollectionSchema\\[\\]\\s*=\\s*\\[/,\n `export const schemas: CollectionSchema[] = [\\n ${schemaEntry},`,\n )\n if (withImport === content || withEntry === withImport) {\n const reason = 'src/schemas.ts could not be updated safely.'\n emit(` Could not auto-integrate schema (${reason})`)\n return [unresolvedSchema(config.schema, reason, emit)]\n }\n content = withEntry\n writeFileSync(schemasPath, content)\n emit(` Schema integrated: ${exportName} -> schemas.ts`)\n return []\n}\n\nfunction unresolvedActions(\n actions: FeatureAction[],\n reason: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration {\n emit('')\n emit(' Add manually to src/actions/index.ts:')\n for (const action of actions) {\n emit(` import { ${action.exportName} } from '${action.importPath}'`)\n emit(` // then add '${action.registerAs}': ${action.exportName} to the actions object`)\n }\n return {\n area: 'actions',\n reason,\n steps: actions.flatMap((action) => [\n `Add import { ${action.exportName} } from '${action.importPath}' to src/actions/index.ts.`,\n `Register '${action.registerAs}': ${action.exportName} in the exported actions object.`,\n ]),\n }\n}\n\nfunction integrateActions(\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration[] {\n if (!config.actions?.length) return []\n const actionsPath = join(targetDir, 'src', 'actions', 'index.ts')\n if (!existsSync(actionsPath)) {\n return [unresolvedActions(config.actions, 'src/actions/index.ts was not found.', emit)]\n }\n\n let content = readFileSync(actionsPath, 'utf-8')\n const registryPattern =\n /export const actions:\\s*Record<string,\\s*ActionHandler(?:<[^>]*>)?>\\s*=\\s*\\{/\n if (!registryPattern.test(content)) {\n const reason = 'src/actions/index.ts has an unexpected structure.'\n emit(` Could not auto-integrate actions (${reason})`)\n return [unresolvedActions(config.actions, reason, emit)]\n }\n\n let integrated = 0\n const unresolved: UnresolvedIntegration[] = []\n for (const action of config.actions) {\n const importPattern = new RegExp(`^import\\\\s+\\\\{[^}]*\\\\b${action.exportName}\\\\b`, 'm')\n if (importPattern.test(content)) {\n emit(` Action already present: ${action.registerAs}`)\n continue\n }\n const importLine = `import { ${action.exportName} } from '${action.importPath}'`\n const withImport = content.replace(\n /export const actions:/,\n `${importLine}\\n\\nexport const actions:`,\n )\n const registryEntry = ` '${action.registerAs}': ${action.exportName},`\n const withEntry = withImport.replace(registryPattern, (match) => `${match}\\n${registryEntry}`)\n if (withImport === content || withEntry === withImport) {\n emit(` Could not integrate action: ${action.registerAs}`)\n unresolved.push(\n unresolvedActions(\n [action],\n `Action '${action.registerAs}' could not be registered safely.`,\n emit,\n ),\n )\n continue\n }\n content = withEntry\n integrated++\n emit(` Action integrated: ${action.registerAs} (${action.exportName})`)\n }\n if (integrated > 0) writeFileSync(actionsPath, content)\n return unresolved\n}\n\nfunction integrateCss(\n packageRoot: string,\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration[] {\n if (!config.css?.length) return []\n const stylesPath = join(targetDir, 'src', 'styles.css')\n if (!existsSync(stylesPath)) {\n emit(' Warning: Cannot integrate CSS — src/styles.css not found')\n return [\n {\n area: 'css',\n reason: 'src/styles.css was not found.',\n steps: config.css.map(\n (cssFile) =>\n `Append node_modules/deepspace/features/${config.id}/${cssFile} to src/styles.css.`,\n ),\n },\n ]\n }\n\n let styles = readFileSync(stylesPath, 'utf-8')\n let integrated = 0\n const unresolved: UnresolvedIntegration[] = []\n for (const cssFile of config.css) {\n const srcPath = join(packageRoot, 'features', config.id, cssFile)\n if (!existsSync(srcPath)) {\n emit(` Warning: CSS source not found: ${cssFile}`, 'stderr')\n unresolved.push({\n area: 'css',\n reason: `Feature CSS source '${cssFile}' was not found in the installed package.`,\n steps: ['Reinstall the current deepspace package, then retry this feature installation.'],\n })\n continue\n }\n const css = readFileSync(srcPath, 'utf-8')\n const fingerprint = css.match(/\\.([\\w-]+)\\s*\\{|@keyframes\\s+([\\w-]+)/)\n const marker = fingerprint?.[1] ?? fingerprint?.[2]\n if (marker && styles.includes(marker)) {\n emit(` CSS already present: ${cssFile} (found .${marker})`)\n continue\n }\n styles += `\\n${css}`\n integrated++\n emit(` CSS integrated: ${cssFile} -> styles.css`)\n }\n if (integrated > 0) writeFileSync(stylesPath, styles)\n return unresolved\n}\n\nfunction unresolvedRoute(\n route: NonNullable<FeatureConfig['route']>,\n config: FeatureConfig,\n reason: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration {\n emit('')\n emit(' Add manually to src/nav.ts:')\n emit(` { path: '${route.path}', label: '${config.name}' },`)\n return {\n area: 'nav',\n reason,\n steps: [`Add { path: '${route.path}', label: '${config.name}' } to the exported nav array.`],\n }\n}\n\nfunction integrateRoute(\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): UnresolvedIntegration[] {\n if (!config.route) return []\n const navPath = join(targetDir, 'src', 'nav.ts')\n if (!existsSync(navPath)) {\n return [unresolvedRoute(config.route, config, 'src/nav.ts was not found.', emit)]\n }\n let content = readFileSync(navPath, 'utf-8')\n const routePath = config.route.path\n if (content.includes(`'${routePath}'`)) {\n emit(` Nav already present: ${routePath}`)\n return []\n }\n if (!content.includes(NAV_MARKER)) {\n emit(' Could not auto-wire nav (marker not found in nav.ts)')\n return [\n unresolvedRoute(\n config.route,\n config,\n 'The feature insertion marker was not found in src/nav.ts.',\n emit,\n ),\n ]\n }\n const roles = config.route.protected === false ? '' : \", roles: ['member' as Role]\"\n const entry = ` { path: '${routePath}', label: '${config.name}'${roles} },`\n content = content.replace(NAV_MARKER, `${NAV_MARKER}\\n${entry}`)\n writeFileSync(navPath, content)\n emit(` Nav wired: ${routePath} (${config.name})`)\n emit(' Route: automatic (file-based routing via src/pages/)')\n return []\n}\n\nconst INSTALL_DIAGNOSTIC_BYTES = 16 * 1024\n\ninterface PackageInstallRun {\n error?: Error\n status: number | null\n diagnosticTail?: string\n}\n\nfunction readDiagnosticTail(outputFd: number): string | undefined {\n const size = fstatSync(outputFd).size\n if (size === 0) return undefined\n const length = Math.min(size, INSTALL_DIAGNOSTIC_BYTES)\n const buffer = Buffer.alloc(length)\n readSync(outputFd, buffer, 0, length, size - length)\n const tail = buffer.toString('utf-8').trim()\n if (!tail) return undefined\n return size > length ? `[last ${length} bytes]\\n${tail}` : tail\n}\n\nfunction runPackageInstall(\n packageManager: string,\n targetDir: string,\n outputVisible: boolean,\n): PackageInstallRun {\n const options = {\n cwd: targetDir,\n shell: process.platform === 'win32',\n }\n if (outputVisible) {\n const child = spawnSync(packageManager, ['install'], { ...options, stdio: 'inherit' })\n return { error: child.error, status: child.status }\n }\n\n // Keep stdout reserved for the command's one-line JSON envelope. Both child\n // streams share a temporary file, then only a fixed-size tail enters memory.\n const captureDir = mkdtempSync(join(tmpdir(), 'deepspace-add-install-'))\n let outputFd: number | undefined\n try {\n outputFd = openSync(join(captureDir, 'output.log'), 'w+')\n const child = spawnSync(packageManager, ['install'], {\n ...options,\n stdio: ['ignore', outputFd, outputFd],\n })\n return {\n error: child.error,\n status: child.status,\n diagnosticTail: readDiagnosticTail(outputFd),\n }\n } finally {\n if (outputFd !== undefined) closeSync(outputFd)\n rmSync(captureDir, { recursive: true, force: true })\n }\n}\n\nfunction integrateDependencies(\n config: FeatureConfig,\n targetDir: string,\n runInstall: boolean,\n outputVisible: boolean,\n emit: FeatureInstallerOutput,\n): {\n added: DependencyAddition[]\n installRan: boolean\n installError?: string\n diagnosticTail?: string\n packageManager: string\n} {\n const packageManager = detectPackageManager(targetDir)\n const declarations: Array<{\n section: DependencySection\n values: Record<string, string> | undefined\n }> = [\n { section: 'dependencies', values: config.dependencies },\n { section: 'devDependencies', values: config.devDependencies },\n ]\n if (declarations.every(({ values }) => !values || Object.keys(values).length === 0)) {\n return { added: [], installRan: false, packageManager }\n }\n\n const packagePath = join(targetDir, 'package.json')\n if (!existsSync(packagePath)) {\n emit(' Could not patch package.json (file not found)')\n return { added: [], installRan: false, packageManager }\n }\n\n let pkg: Record<string, unknown> & {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n }\n try {\n pkg = JSON.parse(readFileSync(packagePath, 'utf-8')) as typeof pkg\n } catch (error) {\n emit(\n ` Could not patch package.json (parse error: ${error instanceof Error ? error.message : String(error)})`,\n )\n return { added: [], installRan: false, packageManager }\n }\n\n const added: DependencyAddition[] = []\n const skipped: string[] = []\n for (const { section, values } of declarations) {\n if (!values) continue\n pkg[section] ??= {}\n for (const [name, version] of Object.entries(values)) {\n if (pkg.dependencies?.[name] || pkg.devDependencies?.[name]) {\n if (!added.some((dependency) => dependency.name === name)) skipped.push(name)\n continue\n }\n pkg[section]![name] = version\n added.push({ name, section, version })\n }\n }\n\n if (added.length === 0) {\n emit(' Dependencies already present')\n } else {\n writeFileSync(packagePath, `${JSON.stringify(pkg, null, 2)}\\n`, 'utf-8')\n emit(` Added to package.json: ${added.map(({ name }) => name).join(', ')}`)\n if (skipped.length) emit(` Already present (kept your version): ${skipped.join(', ')}`)\n }\n\n if (!runInstall) return { added, installRan: false, packageManager }\n emit('')\n emit(` Installing dependencies with ${packageManager}...`)\n const child = runPackageInstall(packageManager, targetDir, outputVisible)\n if (child.error) {\n const error = child.error as NodeJS.ErrnoException\n const reason = error.code === 'ENOENT' ? `${packageManager} not found on PATH` : error.message\n return {\n added,\n installRan: false,\n installError: `Could not launch ${packageManager} (${reason}).`,\n diagnosticTail: child.diagnosticTail,\n packageManager,\n }\n }\n if (child.status !== 0) {\n const diagnostic = child.diagnosticTail ? `\\nDiagnostic tail:\\n${child.diagnosticTail}` : ''\n return {\n added,\n installRan: false,\n installError: `${packageManager} install did not complete (exit ${child.status ?? 'unknown'}).${diagnostic}`,\n diagnosticTail: child.diagnosticTail,\n packageManager,\n }\n }\n return { added, installRan: true, packageManager }\n}\n\nfunction dependencySnapshot(targetDir: string): {\n dependencies: Record<string, unknown>\n devDependencies: Record<string, unknown>\n} {\n try {\n const pkg = JSON.parse(readFileSync(join(targetDir, 'package.json'), 'utf-8')) as {\n dependencies?: Record<string, unknown>\n devDependencies?: Record<string, unknown>\n }\n return {\n dependencies: pkg.dependencies ?? {},\n devDependencies: pkg.devDependencies ?? {},\n }\n } catch {\n return { dependencies: {}, devDependencies: {} }\n }\n}\n\nfunction installedNavFeatures(packageRoot: string, targetDir: string): string[] {\n return listFeatureConfigs(packageRoot)\n .filter((feature) => feature.category === 'nav' && feature.files.length > 0)\n .filter((feature) => {\n const signature = resolveFeatureDestPath(feature.files[0].dest, feature.route)\n return existsSync(join(targetDir, signature))\n })\n .map((feature) => feature.id)\n}\n\nfunction warnNavConflicts(\n packageRoot: string,\n config: FeatureConfig,\n targetDir: string,\n emit: FeatureInstallerOutput,\n): void {\n if (config.category !== 'nav') return\n const present = installedNavFeatures(packageRoot, targetDir)\n if (present.length <= 1) return\n emit('')\n emit(`⚠ Multiple navigation features present (${present.join(', ')}).`)\n emit(' sidebar, topbar, and tree are mutually exclusive — keep one and remove the')\n emit(' others to avoid competing navigation in your layout.')\n}\n\nexport function installFeature(options: FeatureInstallOptions): FeatureInstallOutcome {\n const packageRoot = featurePackageRoot()\n const targetDir = resolveTargetDir(options.targetDir)\n const config = readFeatureConfig(options.feature, packageRoot)\n if (!config) {\n const suggestion = suggestFeature(options.feature, packageRoot)\n return {\n ok: false,\n code: 'unknown_feature',\n error: [\n `Unknown feature: ${options.feature}`,\n ...(suggestion ? [`Did you mean \"${suggestion}\"?`] : []),\n ].join('\\n'),\n data: {\n requestedFeature: options.feature,\n suggestedFeature: suggestion,\n availableFeatures: featureCatalog(packageRoot),\n },\n }\n }\n\n const emit: FeatureInstallerOutput = options.emit ?? (() => undefined)\n emit('')\n emit(`Installing: ${config.name}`)\n emit(` ${config.description ?? ''}`)\n emit(` Target: ${targetDir}`)\n\n const installedFiles = installFiles(packageRoot, config, targetDir, emit)\n emit('')\n emit(\n `Copied ${installedFiles.copied} file(s)${\n installedFiles.skipped > 0 ? `, skipped ${installedFiles.skipped} existing` : ''\n }`,\n )\n\n const unresolvedIntegrations = [\n ...integrateSchema(config, targetDir, emit),\n ...integrateActions(config, targetDir, emit),\n ...integrateCss(packageRoot, config, targetDir, emit),\n ...integrateRoute(config, targetDir, emit),\n ]\n const dependencyResult = integrateDependencies(\n config,\n targetDir,\n options.installDependencies,\n options.emit !== undefined,\n emit,\n )\n\n if (config.instructions?.length) {\n emit('')\n emit('--- Manual wiring needed ---')\n emit('')\n config.instructions.forEach((instruction, index) => {\n emit(`${index + 1}. ${instruction}`)\n emit('')\n })\n }\n if (config.patterns?.length) {\n emit('--- Key patterns ---')\n emit('')\n config.patterns.forEach((pattern) => emit(`- ${pattern}`))\n emit('')\n }\n warnNavConflicts(packageRoot, config, targetDir, emit)\n\n const dependenciesAfter = dependencySnapshot(targetDir)\n const declaredDependencies = [\n ...Object.keys(config.dependencies ?? {}),\n ...Object.keys(config.devDependencies ?? {}),\n ]\n const missingDeclarations = declaredDependencies.filter(\n (name) =>\n !(name in dependenciesAfter.dependencies) && !(name in dependenciesAfter.devDependencies),\n )\n const installed =\n installedFiles.files.missing.length === 0 &&\n missingDeclarations.length === 0 &&\n unresolvedIntegrations.length === 0 &&\n dependencyResult.installError === undefined\n const dependencyInstallRequired =\n installed &&\n dependencyResult.added.length > 0 &&\n !options.installDependencies &&\n !dependencyResult.installRan\n\n const data: InstallData = {\n feature: config.id,\n dir: targetDir,\n installed,\n observedChanges: {\n files: installedFiles.files,\n dependencies: {\n added: dependencyResult.added,\n missingDeclarations,\n installRequested: options.installDependencies,\n ...(dependencyResult.diagnosticTail\n ? { diagnosticTail: dependencyResult.diagnosticTail }\n : {}),\n },\n },\n unresolvedIntegrations,\n manifestGuidance: {\n instructions: config.instructions ?? [],\n patterns: config.patterns ?? [],\n agentNotes: config.agentNotes ?? [],\n },\n }\n if (dependencyResult.installError) {\n return {\n ok: false,\n code: 'dependency_install_failed',\n error: dependencyResult.installError,\n data,\n }\n }\n if (unresolvedIntegrations.length > 0) {\n const count = unresolvedIntegrations.length\n return {\n ok: false,\n code: 'manual_integration_required',\n error: `${count} app integration${count === 1 ? '' : 's'} require manual completion. Follow the unresolved integration steps, then run your checks.`,\n data,\n }\n }\n\n return {\n ok: true,\n data,\n ...(dependencyInstallRequired\n ? {\n action: {\n cwd: targetDir,\n argv: [dependencyResult.packageManager, 'install'],\n },\n }\n : {}),\n }\n}\n","/**\n * deepspace app domain — purchase and manage custom domains for your apps.\n *\n * Designed to be both human-friendly and agent/script-friendly:\n * - All destructive commands accept `--yes` to skip prompts.\n * - `--json` (injected by the command runtime) gives every subcommand a\n * single-line `{ ok, … }` document on stdout.\n * - `--app` accepts an app id or live name and defaults to the cwd's app id.\n * - `domain buy` opens Stripe Checkout in a browser and polls until live;\n * pass `--no-open` to print the URL only, `--no-wait` to skip polling.\n *\n * Subcommands:\n * search <query> — find available domains and prices\n * buy <domain> — buy a domain via Stripe Checkout (browser)\n * list — list domains you own\n * status <domain> — detail view for one domain\n * attach <domain> — re-point a domain at a different app\n * detach <domain> — stop routing the domain (keeps registration)\n * renew <domain> --auto X — toggle auto-renew on/off at the registrar\n *\n * Defined with the command runtime (lib/command.ts). Two deviations fixed\n * here: `buy --json` used to emit TWO JSON documents (the checkout session,\n * then the provisioning outcome), and the confirmation prompts in `buy` and\n * `detach` would hang a `--json` caller. See each subcommand.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { apiFetch } from '../lib/api'\nimport { openBrowser } from '../lib/open-browser'\nimport { resolveAppTarget } from '../lib/app-target'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\ninterface SearchResult {\n name: string\n registrable: boolean\n registrar?: 'cloudflare' | 'namesilo'\n pricing?: { currency: string; registrationCost: string; renewalCost: string }\n registrationCost?: number\n renewalCost?: number\n chargedCents?: number | null\n costCents?: number | null\n reason?: string\n premium?: boolean\n}\n\ninterface DomainPurchase {\n id: string\n domain: string\n appId: string\n status: string\n statusError?: string | null\n registeredAt?: string | null\n expiresAt?: string | null\n chargedCents: number\n autoRenew: boolean\n registrar: string\n}\n\nconst api = <T>(token: string, path: string, init?: RequestInit): Promise<T> =>\n apiFetch<T>(API_URL, token, path, init)\n\n/**\n * Strip internal-only pricing fields from any value before emitting it to\n * stdout. The api-worker exposes both the user-facing `chargedCents` and the\n * platform's at-cost `costCents`; only the former should reach the CLI user.\n */\nfunction scrubInternal<T>(value: T): T {\n if (Array.isArray(value)) return value.map(scrubInternal) as unknown as T\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (k === 'costCents') continue\n out[k] = scrubInternal(v)\n }\n return out as T\n }\n return value\n}\n\nfunction fmtCents(cents: number | null | undefined): string {\n if (cents === null || cents === undefined) return '—'\n return `$${(cents / 100).toFixed(2)}`\n}\n\nfunction fmtDate(iso: string | null | undefined): string {\n if (!iso) return '—'\n return iso.slice(0, 10)\n}\n\n/**\n * Plain stdin Y/N prompt — no clack. Only ever reached on the interactive\n * human path: callers refuse with `confirmation_required` when there is no\n * TTY or `--json` is set, so a prompt can never hang a machine caller.\n */\nasync function confirm(message: string): Promise<boolean> {\n process.stdout.write(`${message} [y/N] `)\n return new Promise((resolve) => {\n process.stdin.setEncoding('utf-8')\n process.stdin.once('data', (data) => {\n const answer = data.toString().trim().toLowerCase()\n resolve(answer === 'y' || answer === 'yes')\n })\n })\n}\n\n/** True when asking a question would hang the caller (agent, pipe, `--json`). */\nconst cannotPrompt = (json: boolean): boolean => json || !process.stdin.isTTY\n\n// ============================================================================\n// search\n// ============================================================================\n\nconst search = defineDeepspaceCommand({\n meta: { name: 'search', description: 'Search for available domains' },\n args: {\n query: { type: 'positional', description: 'Domain or keyword', required: true },\n limit: { type: 'string', description: 'Max results (default 10)', default: '10' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const limit = parseInt(String(args.limit ?? '10'), 10) || 10\n const result = await api<{ domains: SearchResult[] }>(\n token,\n `/api/domains/search?q=${encodeURIComponent(String(args.query))}&limit=${limit}`,\n )\n const scrubbed = scrubInternal(result)\n if (!args.json) {\n if (result.domains.length === 0) {\n console.log('No matches.')\n } else {\n for (const d of result.domains) {\n const tag = d.registrable ? '✓' : '✗'\n const price = d.registrable ? `${fmtCents(d.chargedCents)}/yr` : (d.reason ?? '—')\n // Annotate slow-path TLDs so users have realistic expectations.\n const slowFlag =\n d.registrar && d.registrar !== 'cloudflare' ? ' (15-60 min provisioning)' : ''\n console.log(`${tag} ${d.name.padEnd(40)} ${price}${slowFlag}`)\n }\n }\n }\n return { data: { domains: scrubbed.domains } }\n },\n})\n\n// ============================================================================\n// buy\n// ============================================================================\n\nconst buy = defineDeepspaceCommand({\n meta: { name: 'buy', description: 'Buy a domain and attach it to an app' },\n args: {\n domain: { type: 'positional', description: 'Domain to buy', required: true },\n app: { type: 'string', description: 'App id or live name (defaults to ./wrangler.toml)' },\n yes: { type: 'boolean', description: 'Skip the confirmation prompt', default: false },\n open: {\n type: 'boolean',\n description: 'Open browser at Stripe URL (use --no-open to print URL only)',\n default: true,\n },\n wait: {\n type: 'boolean',\n description:\n 'Poll until provisioning completes (use --no-wait to exit after session creation). ' +\n 'Implicitly off under --json, whose single document is the checkout session.',\n default: true,\n },\n },\n async run({ args }) {\n const domain = String(args.domain)\n const token = await ensureToken()\n const appId = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n\n // Re-check pricing\n const priceCheck = await api<{ domains: SearchResult[] }>(token, '/api/domains/check', {\n method: 'POST',\n body: JSON.stringify({ domains: [domain] }),\n })\n const result = priceCheck.domains[0]\n if (!result || !result.registrable) {\n throw new Refusal(`Not available: ${result?.reason ?? 'unknown'}`, 'domain_not_available', {\n action: cliAction('deepspace', 'app', 'domain', 'search', domain),\n })\n }\n\n const price = fmtCents(result.chargedCents)\n // Provisioning time depends on registrar:\n // CF Registrar (.com/.dev/.app/.xyz/etc): ~60-90s — registry publishes\n // CF nameservers atomically with registration.\n // Porkbun fallback (.ai/.io/.me/.co/etc + ccTLDs): 15-60 min — depends\n // on the destination registry (Verisign/.me, NIC.AI, etc) batch-\n // publishing our NS records to public DNS. The platform side is\n // done in <30s; the wait is registry-side.\n const expectedTime =\n result.registrar === 'cloudflare'\n ? '~60-90 seconds'\n : '15-60 minutes (registry NS propagation)'\n\n if (!args.yes) {\n // A purchase is irreversible, so it must be confirmed — but a prompt\n // would hang an agent or a `--json` caller. Refuse and name the flag.\n if (cannotPrompt(args.json)) {\n throw new Refusal(\n `Buying ${domain} for ${price}/yr (auto-renews; non-refundable) and attaching it to ` +\n `${appId} needs confirmation. Provisioning takes ${expectedTime}. Re-run with --yes.`,\n 'confirmation_required',\n )\n }\n const ok = await confirm(\n `Buy ${domain} for ${price}/yr (auto-renews; non-refundable), attach to ${appId}? Provisioning takes ${expectedTime}.`,\n )\n if (!ok) {\n console.log('Cancelled.')\n return { data: { domain, cancelled: true } }\n }\n }\n\n const checkout = await api<{\n purchaseId: string\n sessionId: string\n url: string\n chargedCents: number\n }>(token, '/api/domains/checkout', {\n method: 'POST',\n body: JSON.stringify({ domain, appId }),\n })\n\n if (!args.json) console.log(`Stripe Checkout: ${checkout.url}`)\n\n if (args.open && process.stdin.isTTY) {\n openBrowser(checkout.url)\n }\n\n // ONE document under --json. The checkout URL is the actionable outcome\n // and the caller needs it NOW (it has to be paid before provisioning even\n // starts) — so `--json` never polls; it returns the session and points at\n // `domain status` for the result. The human path keeps the live progress.\n if (!args.wait || args.json) {\n return {\n data: scrubInternal({ ...checkout, expectedTime, registrar: result.registrar, domain }),\n action: cliAction('deepspace', 'app', 'domain', 'status', domain),\n }\n }\n\n // Poll until active or failed.\n // Timeout depends on registrar — CF can take 5 min worst case, Porkbun\n // up to 60 min for slow registries. User can Ctrl-C and resume polling\n // later via `deepspace app domain status <domain>` — provisioning runs\n // server-side regardless.\n const timeoutMs = result.registrar === 'cloudflare' ? 5 * 60 * 1000 : 60 * 60 * 1000\n console.log(\n `Waiting for payment & provisioning (up to ${expectedTime}). Press Ctrl-C anytime —`,\n )\n console.log(\n `provisioning continues server-side; check later with \\`deepspace app domain status ${domain}\\`.`,\n )\n const deadline = Date.now() + timeoutMs\n let lastStatus = ''\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 5000))\n try {\n const detail = await api<{ domain: DomainPurchase }>(\n token,\n `/api/domains/${checkout.purchaseId}`,\n )\n if (detail.domain.status !== lastStatus) {\n lastStatus = detail.domain.status\n console.log(` → ${lastStatus}`)\n }\n if (detail.domain.status === 'active') {\n console.log(`✓ ${domain} is live and pointing at ${appId}`)\n return {\n data: scrubInternal({ ...checkout, status: 'active', domain, appId }),\n }\n }\n if (detail.domain.status.startsWith('failed:')) {\n throw new Refusal(\n `Provisioning failed: ${detail.domain.statusError ?? detail.domain.status}`,\n 'provisioning_failed',\n { action: cliAction('deepspace', 'app', 'domain', 'status', domain) },\n )\n }\n } catch (err) {\n if (err instanceof Refusal) throw err\n // Transient — keep polling\n console.error(`(poll error: ${err instanceof Error ? err.message : String(err)})`)\n }\n }\n throw new Refusal(\n `Polling timed out. Provisioning may still be in progress; check with: deepspace app domain status ${domain}`,\n 'provisioning_timeout',\n { action: cliAction('deepspace', 'app', 'domain', 'status', domain) },\n )\n },\n})\n\n// ============================================================================\n// list\n// ============================================================================\n\nconst list = defineDeepspaceCommand({\n meta: { name: 'list', description: 'List your domains' },\n async run({ args }) {\n const token = await ensureToken()\n const result = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const scrubbed = scrubInternal(result)\n if (result.domains.length === 0) {\n if (!args.json) console.log('No domains. Try `deepspace app domain search <name>`.')\n return { data: { domains: scrubbed.domains } }\n }\n if (!args.json) {\n console.log(\n `DOMAIN APP STATUS EXPIRES AUTO-RENEW`,\n )\n for (const d of result.domains) {\n console.log(\n `${d.domain.padEnd(35)} ${d.appId.padEnd(20)} ${d.status.padEnd(20)} ${fmtDate(d.expiresAt).padEnd(12)} ${d.autoRenew ? 'on' : 'off'}`,\n )\n }\n }\n return { data: { domains: scrubbed.domains } }\n },\n})\n\n// ============================================================================\n// status\n// ============================================================================\n\n/** The caller's domain, or a coded refusal naming how to list them. */\nasync function requireDomain(token: string, domain: string): Promise<DomainPurchase> {\n const all = await api<{ domains: DomainPurchase[] }>(token, '/api/domains')\n const found = all.domains.find((d) => d.domain === domain)\n if (!found) {\n throw new Refusal(`No domain ${domain} in your account`, 'domain_not_found', {\n action: cliAction('deepspace', 'app', 'domain', 'list'),\n })\n }\n return found\n}\n\nconst status = defineDeepspaceCommand({\n meta: { name: 'status', description: 'Show details for one domain' },\n args: {\n domain: { type: 'positional', description: 'Domain', required: true },\n },\n async run({ args }) {\n const token = await ensureToken()\n const found = await requireDomain(token, String(args.domain))\n if (!args.json) {\n console.log(`Domain: ${found.domain}`)\n console.log(\n `Status: ${found.status}${found.statusError ? ` (${found.statusError})` : ''}`,\n )\n console.log(`Attached app: ${found.appId}`)\n console.log(`Registrar: ${found.registrar}`)\n console.log(`Registered: ${fmtDate(found.registeredAt)}`)\n console.log(`Expires: ${fmtDate(found.expiresAt)}`)\n console.log(`Auto-renew: ${found.autoRenew ? 'on' : 'off'}`)\n console.log(`Charged: ${fmtCents(found.chargedCents)}/yr`)\n }\n return { data: scrubInternal({ ...found }) }\n },\n})\n\n// ============================================================================\n// attach\n// ============================================================================\n\nconst attach = defineDeepspaceCommand({\n meta: { name: 'attach', description: 'Re-point a domain at a different app' },\n args: {\n domain: { type: 'positional', description: 'Domain to re-point', required: true },\n app: { type: 'string', description: 'Target app id or live name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const domain = String(args.domain)\n const token = await ensureToken()\n const targetAppId = await resolveAppTarget(\n DEPLOY_URL,\n token,\n args.app as string | undefined,\n )\n const found = await requireDomain(token, domain)\n const result = await api<{ success: boolean; appId: string }>(\n token,\n `/api/domains/${found.id}/reattach`,\n {\n method: 'POST',\n body: JSON.stringify({ appId: targetAppId }),\n },\n )\n if (!args.json) console.log(`✓ ${domain} now points at ${targetAppId}`)\n // `success` is dropped: the envelope's `ok` already carries it.\n return { data: { domain, appId: result.appId } }\n },\n})\n\n// ============================================================================\n// detach\n// ============================================================================\n\nconst detach = defineDeepspaceCommand({\n meta: {\n name: 'detach',\n description: 'Stop routing the domain (keeps the registration; auto-renew unchanged)',\n },\n args: {\n domain: { type: 'positional', description: 'Domain to detach', required: true },\n yes: { type: 'boolean', description: 'Skip the confirmation prompt' },\n },\n async run({ args }) {\n const domain = String(args.domain)\n const token = await ensureToken()\n const found = await requireDomain(token, domain)\n if (!args.yes) {\n if (cannotPrompt(args.json)) {\n throw new Refusal(\n `Detaching ${domain} stops routing (the domain stays registered; auto-renew is ` +\n 'unchanged) and needs confirmation. Re-run with --yes.',\n 'confirmation_required',\n )\n }\n const ok = await confirm(\n `Detach ${domain}? Routing will stop; the domain stays registered (auto-renew is unchanged).`,\n )\n if (!ok) {\n console.log('Cancelled.')\n return { data: { domain, cancelled: true } }\n }\n }\n await api(token, `/api/domains/${found.id}`, { method: 'DELETE' })\n if (!args.json) {\n console.log(\n `✓ ${domain} detached. Use \\`deepspace app domain attach\\` to re-route, or \\`renew --auto off\\` to stop auto-renewal.`,\n )\n }\n return { data: { domain, detached: true } }\n },\n})\n\n// ============================================================================\n// renew\n// ============================================================================\n\nconst renew = defineDeepspaceCommand({\n meta: { name: 'renew', description: 'Toggle auto-renewal at the registrar' },\n args: {\n domain: { type: 'positional', description: 'Domain', required: true },\n auto: { type: 'string', description: '\"on\" or \"off\"', required: true },\n },\n async run({ args }) {\n const domain = String(args.domain)\n if (args.auto !== 'on' && args.auto !== 'off') {\n throw new Refusal('--auto must be \"on\" or \"off\"', 'invalid_auto')\n }\n const token = await ensureToken()\n const found = await requireDomain(token, domain)\n const enabled = args.auto === 'on'\n await api(token, `/api/domains/${found.id}/auto-renew`, {\n method: 'POST',\n body: JSON.stringify({ autoRenew: enabled }),\n })\n if (!args.json) console.log(`✓ ${domain} auto-renew ${enabled ? 'enabled' : 'disabled'}`)\n // Terminal toggle: nothing follows.\n return { data: { domain, autoRenew: enabled } }\n },\n})\n\n// ============================================================================\n// Top-level\n// ============================================================================\n\n// Note: no `run()` on the parent — citty otherwise calls it after every\n// subcommand finishes, which prints spurious help text.\n//\nexport default defineCommand({\n meta: { name: 'domain', description: 'Buy and manage custom domains' },\n subCommands: { search, buy, list, status, attach, detach, renew },\n})\n","/**\n * Manage app collaborators: users you authorize to deploy your app on your\n * behalf. A collaborator just runs `deepspace deploy`; the deploy keeps your\n * identity and billing. Collaborators have owner-equivalent deploy access, so\n * only add people you trust.\n *\n * Defined with the command runtime (lib/command.ts): `--json` (now a\n * single-line `{ ok, … }` envelope instead of each subcommand's own\n * pretty-printed blob), the slug, the `Next:` line and the exit codes come\n * from there. No subcommand prompts — `remove`/`cancel` refuse an unknown\n * target rather than asking.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { resolveAppTarget } from '../lib/app-target'\nimport { apiFetch } from '../lib/api'\nimport { isTestAccountEmail } from '../../server/auth/testAccounts'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\ninterface Collaborator {\n userId: string\n emailDisplay: string\n createdAt: string | number\n}\n\ninterface PendingInvite {\n email: string\n /** Epoch milliseconds. */\n expiresAt: number\n invitedAt: number\n}\n\ntype AddResponse =\n | { status: 'added'; collaborator: Collaborator }\n | { status: 'invited'; email: string; token: string; expiresAt: number }\n // A live invite already existed → the server did NOT re-charge or re-send.\n | { status: 'already_invited'; email: string; token: string; expiresAt: number }\n\nfunction api<T>(token: string, path: string, init?: RequestInit): Promise<T> {\n return apiFetch<T>(API_URL, token, path, init)\n}\n\nconst list = defineDeepspaceCommand({\n meta: { name: 'list', description: 'List collaborators on your app' },\n args: {\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n const { collaborators, pending = [] } = await api<{\n collaborators: Collaborator[]\n pending?: PendingInvite[]\n }>(token, `/api/app-collaborators/${encodeURIComponent(app)}`)\n if (!collaborators.length && !pending.length) {\n if (!args.json) {\n console.log(`No collaborators on ${app}. Add one with \\`deepspace app collaborators add <email>\\`.`)\n }\n return { data: { collaborators, pending } }\n }\n // COL-4: print a header and the resolved email (emailDisplay). The raw\n // userId is dropped from the human view — it's still in --json, a human\n // reads the email, and `collaborators remove <email>` matches on it.\n if (!args.json) {\n if (collaborators.length) {\n console.log(`COLLABORATORS ON ${app}`)\n for (const c of collaborators) {\n console.log(` ${c.emailDisplay}`)\n }\n }\n if (pending.length) {\n console.log(`PENDING INVITES ON ${app}`)\n for (const p of pending) {\n console.log(` ${p.email} (expires ${new Date(p.expiresAt).toLocaleDateString()})`)\n }\n }\n }\n return { data: { collaborators, pending } }\n },\n})\n\nconst add = defineDeepspaceCommand({\n meta: { name: 'add', description: 'Authorize someone to deploy your app' },\n args: {\n email: {\n type: 'positional',\n description: 'Collaborator email',\n required: true,\n },\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const email = String(args.email)\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n if (isTestAccountEmail(email)) {\n throw new Refusal(\n 'Test accounts (@deepspace.test) cannot be added as collaborators. Use a real DeepSpace account.',\n 'test_account_cannot_be_collaborator',\n )\n }\n // Failure slugs (insufficient_credits, test_account_cannot_be_collaborator,\n // ...) are translated centrally by wrapCommandErrors — just let them escape.\n // An email with no DeepSpace user is no longer an error: the server creates\n // a pending invite ({status:'invited'}) and emails the person.\n const res = await api<AddResponse>(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}`,\n { method: 'POST', body: JSON.stringify({ email }) },\n )\n if (res.status === 'invited' || res.status === 'already_invited') {\n const expires = new Date(res.expiresAt).toLocaleDateString()\n if (res.status === 'already_invited') {\n if (!args.json) {\n console.log(\n `• ${res.email} already has a pending invite (expires ${expires}). ` +\n `No new email was sent. Cancel it with \\`deepspace app collaborators cancel ${res.email}\\` to reset.`,\n )\n }\n return { data: { ...res } }\n }\n if (!args.json) {\n console.log(\n `✓ Invite sent to ${res.email} (expires ${expires}). ` +\n `They become a collaborator when they sign in.`,\n )\n }\n return { data: { ...res } }\n }\n if (!args.json) console.log(`✓ ${res.collaborator.emailDisplay} can now deploy ${app}`)\n return { data: { ...res } }\n },\n})\n\nconst remove = defineDeepspaceCommand({\n meta: { name: 'remove', description: 'Remove a collaborator from your app' },\n args: {\n email: { type: 'positional', description: 'Collaborator email', required: true },\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const email = String(args.email)\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n const { collaborators } = await api<{ collaborators: Collaborator[] }>(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}`,\n )\n const target = email.trim().toLowerCase()\n const found = collaborators.find((c) => c.emailDisplay.toLowerCase() === target)\n if (!found) {\n throw new Refusal(`${email} is not a collaborator on ${app}`, 'not_a_collaborator', {\n action: cliAction('deepspace', 'app', 'collaborators', 'list', '--app', app),\n })\n }\n await api(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}/${encodeURIComponent(found.userId)}`,\n { method: 'DELETE' },\n )\n if (!args.json) console.log(`✓ ${found.emailDisplay} can no longer deploy ${app}`)\n // Terminal: nothing follows a removal.\n return { data: { removed: found } }\n },\n})\n\nconst cancel = defineDeepspaceCommand({\n meta: { name: 'cancel', description: 'Cancel a pending (un-accepted) email invite' },\n args: {\n email: { type: 'positional', description: 'Invited email', required: true },\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const email = String(args.email)\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n // Match against the pending list (mirrors `remove`) so we can tell the user\n // when there's nothing to cancel rather than silently no-op'ing the DELETE.\n const { pending = [] } = await api<{ pending?: PendingInvite[] }>(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}`,\n )\n const target = email.trim().toLowerCase()\n const found = pending.find((p) => p.email.toLowerCase() === target)\n if (!found) {\n throw new Refusal(`${email} has no pending invite on ${app}`, 'no_pending_invite', {\n action: cliAction('deepspace', 'app', 'collaborators', 'list', '--app', app),\n })\n }\n await api(\n token,\n `/api/app-collaborators/${encodeURIComponent(app)}/pending/${encodeURIComponent(found.email)}`,\n { method: 'DELETE' },\n )\n if (!args.json) console.log(`✓ Cancelled the pending invite to ${found.email} on ${app}`)\n // Terminal: nothing follows a cancellation.\n return { data: { cancelled: found } }\n },\n})\n\n// No `run()` on the parent: citty otherwise cascades it after each subcommand,\n// printing spurious help text.\nexport default defineCommand({\n meta: { name: 'collaborators', description: 'Manage who can deploy your app' },\n subCommands: { list, add, remove, cancel },\n})\n","/**\n * Test-account identification, shared by every platform worker.\n *\n * Test accounts (created via `deepspace test accounts`) are real Better Auth\n * users demarcated three ways, and a caller may present as any of them\n * depending on where the check runs:\n * - their email always ends with @deepspace.test (enforced at creation)\n * - their JWTs carry `isTestAccount: true` (minted by the auth-worker,\n * the source of truth)\n * - their billing profile's subscription tier is 'test' (mirrored by the\n * api-worker on every authenticated request)\n *\n * Gate anything a test account must not do with these helpers rather than\n * hand-rolled string comparisons, so the policy stays in one place. Prefer\n * checking the claim when a verified JWT is at hand, and the tier as the\n * fallback for persisted state that may outlive a claim (e.g. rows written\n * before a guard existed).\n */\n\nimport type { JwtClaims } from './types'\n\nexport const TEST_ACCOUNT_EMAIL_SUFFIX = '@deepspace.test'\n\n/** True when the email belongs to a test account (case-insensitive). */\nexport function isTestAccountEmail(email: string | null | undefined): boolean {\n return !!email && email.trim().toLowerCase().endsWith(TEST_ACCOUNT_EMAIL_SUFFIX)\n}\n\n/** True when verified JWT claims identify the caller as a test account. */\nexport function isTestAccountClaims(\n claims: JwtClaims | Record<string, unknown> | null | undefined,\n): boolean {\n return claims?.isTestAccount === true\n}\n\n/** True when a billing subscription tier marks a test account. */\nexport function isTestAccountTier(tier: string | null | undefined): boolean {\n return tier === 'test'\n}\n","/**\n * Transfer app ownership — the GitHub-style offer/accept handshake.\n *\n * `deepspace app transfer offer <email>` creates (or replaces) a 7-day offer;\n * the recipient runs `deepspace app transfer accept --app <appId>` to commit.\n * Acceptance flips the registry owner and re-tags the deployed script for\n * billing in the same call. Either party can `cancel`. Data, secrets, and\n * routes travel with the app — only the owner (and billing) changes.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, the `Next:` line and the exit codes come from there. The one\n * confirmation prompt (`offer` over a pending offer to someone else) is\n * TTY-only: under `--json` a prompt is a hang, so it refuses with\n * `confirmation_required` and points at `--replace`.\n */\n\nimport { defineCommand } from 'citty'\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { requireAppIdArg, resolveAppTarget } from '../lib/app-target'\nimport { apiFetch as api } from '../lib/api'\nimport { InputError } from '../lib/cli-errors'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nconst offer = defineDeepspaceCommand({\n meta: { name: 'offer', description: 'Offer this app to another DeepSpace user' },\n args: {\n email: { type: 'positional', description: 'Recipient email', required: true },\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n replace: {\n type: 'boolean',\n description: 'Replace a pending offer to someone else without asking',\n },\n },\n async run({ args }) {\n const email = String(args.email)\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n\n // The server replaces a pending offer wholesale — a stray second `offer`\n // used to silently revoke the first with no signal to anyone, and the\n // original recipient's `accept` then failed with a mystery 404. Surface\n // the pending offer and make replacing it a deliberate choice.\n const pending = await api<{ transfer: { toEmailDisplay: string } | null }>(\n API_URL,\n token,\n `/api/app-transfers/${encodeURIComponent(app)}`,\n )\n const pendingTo = pending.transfer?.toEmailDisplay\n if (pendingTo && pendingTo.toLowerCase() !== email.trim().toLowerCase() && !args.replace) {\n // No TTY (agent, pipe) or `--json` — a prompt would hang. Refuse with the\n // flag that resolves it instead.\n if (!process.stdin.isTTY || args.json) {\n throw new Refusal(\n `A pending offer to ${pendingTo} already exists for ${app}. ` +\n 'Re-run with --replace to replace it, or `deepspace app transfer cancel` first.',\n 'confirmation_required',\n )\n }\n const yes = await p.confirm({\n message: `A pending offer to ${pendingTo} exists — replace it with ${email}?`,\n })\n if (p.isCancel(yes) || !yes) {\n throw new Refusal(`Kept the pending offer to ${pendingTo}.`, 'cancelled')\n }\n }\n\n const { expiresAt } = await api<{ toUserId: string; expiresAt: string }>(\n API_URL,\n token,\n `/api/app-transfers/${encodeURIComponent(app)}`,\n { method: 'POST', body: JSON.stringify({ email }) },\n )\n const replaced = pendingTo && pendingTo.toLowerCase() !== email.trim().toLowerCase()\n if (!args.json) {\n if (replaced) console.log(`▲ Replaced the pending offer to ${pendingTo}.`)\n console.log(\n `✓ Offered ${app} to ${email} (expires ${expiresAt}).\\n` +\n ` They accept with: deepspace app transfer accept --app ${app}`,\n )\n }\n return {\n data: {\n app,\n email,\n expiresAt,\n ...(replaced ? { replacedPendingTo: pendingTo } : {}),\n },\n }\n },\n})\n\nconst status = defineDeepspaceCommand({\n meta: { name: 'status', description: 'Show the pending transfer offer, if any' },\n args: {\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n const { transfer } = await api<{\n transfer: { toEmailDisplay: string; expiresAt: string } | null\n }>(API_URL, token, `/api/app-transfers/${encodeURIComponent(app)}`)\n if (!transfer) {\n if (!args.json) console.log(`No pending transfer for ${app}.`)\n return { data: { app, transfer: null } }\n }\n if (!args.json) {\n console.log(`Pending: ${app} → ${transfer.toEmailDisplay} (expires ${transfer.expiresAt}).`)\n }\n return { data: { app, transfer } }\n },\n})\n\nconst accept = defineDeepspaceCommand({\n meta: { name: 'accept', description: 'Accept a transfer offered to you' },\n args: {\n app: { type: 'string', alias: 'a', description: 'App id of the offered app', required: true },\n },\n async run({ args }) {\n const token = await ensureToken()\n // requireAppIdArg throws an UNCODED Error for a malformed/absent id; the\n // envelope needs a slug, so give it one here (its InputErrors already have\n // theirs).\n let app: string\n try {\n app = requireAppIdArg(args.app as string | undefined)\n } catch (err: unknown) {\n if (err instanceof InputError) throw err\n const msg = err instanceof Error ? err.message : String(err)\n throw new Refusal(msg, msg.startsWith('No app id') ? 'not_in_app_repo' : 'invalid_app')\n }\n await api(DEPLOY_URL, token, `/api/apps/${encodeURIComponent(app)}/transfer/accept`, {\n method: 'POST',\n })\n if (!args.json) {\n console.log(\n `✓ You now own ${app}. Run \\`deepspace app init\\` in a fresh clone (or set ` +\n `DEEPSPACE_APP_ID = \"${app}\" in wrangler.toml) and deploy.`,\n )\n }\n return { data: { app, accepted: true } }\n },\n})\n\nconst cancel = defineDeepspaceCommand({\n meta: { name: 'cancel', description: 'Cancel/decline the pending offer (either party)' },\n args: {\n app: { type: 'string', alias: 'a', description: 'App id or name (defaults to ./wrangler.toml)' },\n },\n async run({ args }) {\n const token = await ensureToken()\n const app = await resolveAppTarget(DEPLOY_URL, token, args.app as string | undefined)\n await api(API_URL, token, `/api/app-transfers/${encodeURIComponent(app)}`, { method: 'DELETE' })\n if (!args.json) console.log(`✓ Transfer offer for ${app} cancelled.`)\n // Terminal: nothing follows a cancellation.\n return { data: { app, cancelled: true } }\n },\n})\n\n// No `run()` on the parent: citty otherwise cascades it after each subcommand.\nexport default defineCommand({\n meta: { name: 'transfer', description: 'Transfer app ownership to another user' },\n subCommands: { offer, status, accept, cancel },\n})\n","/**\n * deepspace integrations <subcommand>\n *\n * Namespace for working with platform integrations from the command line.\n *\n * deepspace integrations # prints help\n * deepspace integrations list # list all\n * deepspace integrations info openai/chat-completion # schema + example\n * deepspace integrations invoke openai/chat-completion --body '{...}'\n *\n * All calls are made as the currently logged-in user (`deepspace auth whoami`).\n * That user is billed.\n *\n * Each subcommand is defined with the command runtime (lib/command.ts): the\n * `--json` flag, the `{ ok, … }` envelope, the refusal slug, the `Next:` line,\n * and the exit code come from there. Before that, the subcommands caught their\n * own errors and `console.error`'d the message — which meant a `--json` caller\n * got PLAIN PROSE on stderr and an empty stdout.\n *\n * No `run()` is defined on the parent — that matches the convention used\n * by `test-accounts` and prevents citty from firing both the parent and\n * a matched subcommand. Bare `deepspace integrations` (no subcommand)\n * prints citty's auto-generated help.\n */\n\nimport { defineCommand } from 'citty'\nimport { defineDeepspaceCommand } from '../lib/command'\nimport { runInvoke, runInfo, runList, parseTimeout } from './_invoke-impl'\n\nconst list = defineDeepspaceCommand({\n meta: {\n name: 'list',\n description: 'List all available integrations',\n },\n async run({ args }) {\n return runList({ json: args.json })\n },\n})\n\nconst info = defineDeepspaceCommand({\n meta: {\n name: 'info',\n description: 'Print schema + example body for an integration endpoint',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: true,\n },\n },\n async run({ args }) {\n return runInfo({ target: args.target as string, json: args.json })\n },\n})\n\nconst invoke = defineDeepspaceCommand({\n meta: {\n name: 'invoke',\n description: 'Invoke a platform integration as the logged-in user',\n },\n args: {\n target: {\n type: 'positional',\n description: \"<integration>/<endpoint> (e.g. 'openai/chat-completion')\",\n required: true,\n },\n body: {\n type: 'string',\n alias: 'd',\n description: 'Inline JSON body',\n required: false,\n },\n 'body-file': {\n type: 'string',\n alias: 'f',\n description: 'Read JSON body from file (use - for stdin)',\n required: false,\n },\n timeout: {\n type: 'string',\n description: 'Request timeout in milliseconds (default: 120000)',\n required: false,\n },\n yes: {\n type: 'boolean',\n alias: 'y',\n description: 'Skip the paid-call cost confirmation',\n default: false,\n },\n },\n async run({ args }) {\n return runInvoke({\n target: args.target as string,\n body: args.body as string | undefined,\n bodyFile: args['body-file'] as string | undefined,\n json: args.json,\n timeout: parseTimeout(args.timeout),\n yes: Boolean(args.yes),\n })\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'integrations',\n description: 'List, inspect, and invoke platform integrations',\n },\n subCommands: {\n list,\n info,\n invoke,\n },\n})\n","/**\n * Implementation for `deepspace integrations list`, `info`, and `invoke`.\n *\n * The CLI invokes platform integrations as the currently logged-in user\n * (the same identity shown by `deepspace auth whoami`). That user is billed.\n *\n * This module is the single source of truth for:\n * - listing the integration catalog\n * - showing per-endpoint info (schema + example body)\n * - making the actual POST call\n *\n * This module is NOT a citty command, so it does not wrap itself in the\n * command runtime. Instead every `run*` here RETURNS a {@link CommandResult}\n * and throws a {@link Refusal} — exactly what a `defineDeepspaceCommand` body\n * produces — so the command definitions can let the runtime own the envelope,\n * the slug, the `Next:` line, and the exit code.\n * Nothing in here prints an envelope or calls process.exit.\n */\n\nimport { readFileSync } from 'node:fs'\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { cliAction, Refusal, type CommandResult } from '../lib/command'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\nconst DEFAULT_TIMEOUT_MS = 120_000\n\ninterface EndpointInfo {\n endpoint: string\n billing: { model: string; baseCost: number; currency: string }\n inputSchema: Record<string, unknown> | null\n example: Record<string, unknown> | null\n}\n\ninterface Catalog {\n integrations: Record<string, EndpointInfo[]>\n}\n\nexport interface InvokeArgs {\n target: string\n body?: string\n bodyFile?: string\n json?: boolean\n timeout?: number\n yes?: boolean\n}\n\nexport interface InfoArgs {\n target: string\n json?: boolean\n}\n\nexport interface ListArgs {\n json?: boolean\n}\n\n/**\n * Parse \"<integration>/<endpoint>\" into its two segments.\n * Throws on malformed input.\n */\nfunction parseTarget(target: string): { integration: string; endpoint: string } {\n if (!target || typeof target !== 'string') {\n throw new Refusal(\n \"Missing target. Expected '<integration>/<endpoint>' (e.g. 'openai/chat-completion').\",\n 'missing_target',\n { action: cliAction('deepspace', 'integrations', 'list') },\n )\n }\n const parts = target.split('/')\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new Refusal(\n `Bad target '${target}'. Expected '<integration>/<endpoint>' (e.g. 'openai/chat-completion').`,\n 'bad_target',\n { action: cliAction('deepspace', 'integrations', 'list') },\n )\n }\n return { integration: parts[0], endpoint: parts[1] }\n}\n\n/**\n * Parse the `integrations invoke --timeout` value in milliseconds.\n */\nexport function parseTimeout(raw: unknown): number | undefined {\n if (raw == null) return undefined\n const timeout = Number(raw)\n if (!Number.isFinite(timeout) || timeout <= 0) {\n throw new Refusal(\n `Invalid --timeout '${String(raw)}'. Must be a positive number of milliseconds.`,\n 'invalid_timeout',\n )\n }\n return timeout\n}\n\n/**\n * Resolve the request body from --body, --body-file, or default to '{}'.\n * Errors if both --body and --body-file are provided, or the body isn't\n * valid JSON.\n */\nfunction resolveBody(opts: { body?: string; bodyFile?: string }): string {\n if (opts.body != null && opts.bodyFile != null) {\n throw new Refusal('Pass either --body or --body-file, not both.', 'conflicting_body_args')\n }\n\n let raw: string\n if (opts.body != null) {\n raw = opts.body\n } else if (opts.bodyFile != null) {\n raw = opts.bodyFile === '-' ? readFileSync(0, 'utf-8') : readFileSync(opts.bodyFile, 'utf-8')\n } else {\n return '{}'\n }\n\n // Validate it parses as JSON so we fail fast with a clear message.\n try {\n JSON.parse(raw)\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'invalid JSON'\n throw new Refusal(`Body is not valid JSON: ${msg}`, 'invalid_body_json')\n }\n return raw\n}\n\nasync function fetchCatalog(opts: { summary?: boolean } = {}): Promise<Catalog> {\n // `list` uses the summary view (names + billing); the full catalog with every\n // endpoint's schema is large enough to be truncated in an agent's terminal.\n // `info` omits the flag so it still gets the schema + example.\n const url = opts.summary ? `${API_URL}/api/integrations?summary=1` : `${API_URL}/api/integrations`\n const res = await fetch(url)\n if (!res.ok) {\n throw new Refusal(`Failed to fetch integration catalog (${res.status})`, 'catalog_unavailable')\n }\n return (await res.json()) as Catalog\n}\n\nfunction findEndpoint(\n catalog: Catalog,\n integration: string,\n endpoint: string,\n): EndpointInfo | null {\n const endpoints = catalog.integrations[integration]\n if (!endpoints) return null\n return endpoints.find((e) => e.endpoint === endpoint) ?? null\n}\n\nfunction formatCurrency(value: number, currency: string): string {\n if (currency === 'USD') return `$${value}`\n return `${value} ${currency}`\n}\n\n/**\n * Human-readable billing unit for a pricing model. `per_token` → \"per token\",\n * `per_call` → \"per call\". Unknown/future models render their raw `per_*` shape\n * (\"per foo\") or pass through, so we never mislabel one mode as another (INT-1).\n */\nexport function billingUnit(model: string): string {\n if (model === 'per_token') return 'per token'\n if (model === 'per_call') return 'per call'\n return model.startsWith('per_') ? model.replace(/^per_/, 'per ').replace(/_/g, ' ') : model\n}\n\n/**\n * Interactive only when BOTH streams are TTYs: p.confirm reads stdin and draws\n * to stdout, so a piped stdin (`echo {} | invoke … --body-file -`) must never\n * reach the prompt — it would hang waiting for input that can't arrive. Pure so\n * the both-streams rule is testable.\n */\nexport function isInteractive(\n stdin: { isTTY?: boolean },\n stdout: { isTTY?: boolean },\n): boolean {\n return Boolean(stdin.isTTY && stdout.isTTY)\n}\n\n/**\n * Whether to confirm a paid invoke before firing it (FEAT-13). Only on an\n * interactive terminal, for a non-free endpoint, when the caller hasn't asked\n * for machine output (--json) or pre-approved (--yes). Pure for testing.\n */\nexport function shouldConfirmCost(opts: {\n json: boolean\n yes: boolean\n isTTY: boolean\n baseCost: number\n}): boolean {\n return !opts.json && !opts.yes && opts.isTTY && opts.baseCost > 0\n}\n\n/**\n * `deepspace integrations list`\n * Prints the catalog grouped by integration.\n */\nexport async function runList(args: ListArgs): Promise<CommandResult> {\n const catalog = await fetchCatalog({ summary: true })\n const names = Object.keys(catalog.integrations).sort()\n\n if (!args.json) {\n if (names.length === 0) {\n console.log('No integrations available.')\n } else {\n for (const name of names) {\n console.log(name)\n const endpoints = [...catalog.integrations[name]].sort((a, b) =>\n a.endpoint.localeCompare(b.endpoint),\n )\n const widest = Math.max(...endpoints.map((e) => e.endpoint.length))\n for (const ep of endpoints) {\n const pad = ep.endpoint.padEnd(widest)\n const cost = formatCurrency(ep.billing.baseCost, ep.billing.currency)\n console.log(` ${pad} ${ep.billing.model.padEnd(12)} ${cost}`)\n }\n console.log()\n }\n }\n }\n\n return { data: catalog as unknown as Record<string, unknown> }\n}\n\n/**\n * `deepspace integrations info <target>`\n * Prints the schema + example body for a single endpoint.\n */\nexport async function runInfo(args: InfoArgs): Promise<CommandResult> {\n const { integration, endpoint } = parseTarget(args.target)\n const catalog = await fetchCatalog()\n const info = findEndpoint(catalog, integration, endpoint)\n\n if (!info) {\n const available = catalog.integrations[integration]\n if (!available) {\n const names = Object.keys(catalog.integrations).sort().join(', ')\n throw new Refusal(`Unknown integration '${integration}'. Available: ${names}`, 'unknown_integration', {\n action: cliAction('deepspace', 'integrations', 'list'),\n })\n }\n const endpoints = available.map((e) => e.endpoint).join(', ')\n throw new Refusal(\n `Unknown endpoint '${endpoint}' for '${integration}'. Available: ${endpoints}`,\n 'unknown_endpoint',\n { action: cliAction('deepspace', 'integrations', 'list') },\n )\n }\n\n if (!args.json) {\n console.log(`${integration}/${endpoint}`)\n console.log(\n ` billing: ${formatCurrency(info.billing.baseCost, info.billing.currency)} ${billingUnit(info.billing.model)}`,\n )\n console.log()\n console.log('Input schema:')\n console.log(\n info.inputSchema ? JSON.stringify(info.inputSchema, null, 2) : ' (no schema registered)',\n )\n console.log()\n console.log('Example body:')\n console.log(info.example ? JSON.stringify(info.example, null, 2) : ' (no example available)')\n }\n\n return { data: info as unknown as Record<string, unknown> }\n}\n\n/**\n * `deepspace integrations invoke <target>`\n * Performs the actual integration call.\n */\nexport async function runInvoke(args: InvokeArgs): Promise<CommandResult> {\n const { integration, endpoint } = parseTarget(args.target)\n const body = resolveBody({ body: args.body, bodyFile: args.bodyFile })\n const timeoutMs = args.timeout ?? DEFAULT_TIMEOUT_MS\n\n // FEAT-13: this fires a PAID call billed to the logged-in user. On a fully\n // interactive terminal, confirm the cost first (unless --yes or --json).\n // Gate on BOTH streams: p.confirm reads stdin and draws to stdout, so a piped\n // stdin (e.g. `echo {} | deepspace integrations invoke … --body-file -`) must never reach\n // the prompt — it would hang waiting for input that can't come.\n const interactive = isInteractive(process.stdin, process.stdout)\n if (!args.json && !args.yes && interactive) {\n let info: EndpointInfo | null = null\n try {\n info = findEndpoint(await fetchCatalog({ summary: true }), integration, endpoint)\n } catch {\n // Couldn't fetch billing — don't block the call, but say so, so a paid\n // call never fires completely silently. The POST still enforces\n // auth/existence and reports its own errors.\n console.error('Note: could not verify the call cost; proceeding. Pass --yes to skip this check.')\n info = null\n }\n if (\n info &&\n shouldConfirmCost({\n json: !!args.json,\n yes: !!args.yes,\n isTTY: interactive,\n baseCost: info.billing.baseCost,\n })\n ) {\n const cost = formatCurrency(info.billing.baseCost, info.billing.currency)\n const ok = await p.confirm({\n message: `${integration}/${endpoint} costs ${cost} ${billingUnit(info.billing.model)}, billed to your account. Continue?`,\n })\n if (p.isCancel(ok) || !ok) {\n p.cancel('Cancelled — no call made.')\n // Declining a paid call is a success, not a refusal: nothing was\n // billed and there is nothing to retry.\n return { data: { cancelled: true, integration, endpoint } }\n }\n }\n }\n\n let jwt: string\n try {\n jwt = await ensureToken()\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Refusal(msg, 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n const startedAt = Date.now()\n\n let res: Response\n try {\n res = await fetch(`${API_URL}/api/integrations/${integration}/${endpoint}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${jwt}`,\n },\n body,\n signal: controller.signal,\n })\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Refusal(`Request timed out after ${timeoutMs}ms`, 'request_timeout')\n }\n throw new Refusal(err instanceof Error ? err.message : 'Request failed', 'request_failed')\n } finally {\n clearTimeout(timer)\n }\n\n const elapsed = Date.now() - startedAt\n let payload: Record<string, unknown>\n try {\n payload = (await res.json()) as Record<string, unknown>\n } catch {\n throw new Refusal(`Request failed (${res.status}) with non-JSON response`, 'invalid_response')\n }\n\n const ok = payload?.success !== false && res.ok\n if (ok) {\n if (!args.json) {\n const data = 'data' in payload ? payload.data : payload\n console.log(JSON.stringify(data, null, 2))\n console.error(`\\n✓ ${integration}/${endpoint} (${elapsed}ms)`)\n }\n // The server payload is the machine result, but it is NOT an envelope —\n // hand it to the runtime as `data` so it goes out as `{ ok, …payload }`\n // like every other command instead of passing through unnormalized.\n return { data: payload }\n }\n\n // Error path. The issue list is part of the message (the human line must\n // carry every fact --json does) and rides along in the envelope via `extra`.\n const errMsg = (payload.error as string) ?? `Request failed (${res.status})`\n // No `✗` prefix: the runtime renders the failure marker, and it would read\n // as `■ ✗ …` (and land in the `--json` `error` string) if we kept ours.\n const lines = [`${integration}/${endpoint} (${res.status}, ${elapsed}ms): ${errMsg}`]\n if (Array.isArray(payload.issues)) {\n for (const issue of payload.issues as Array<{ path?: string[]; message: string }>) {\n const path = issue.path?.length ? issue.path.join('.') : '(root)'\n lines.push(` - ${path}: ${issue.message}`)\n }\n }\n // Prefer the server's own slug so an agent branches on the same code the API\n // returns; fall back to a stable generic one.\n const code = typeof payload.code === 'string' ? payload.code : 'integration_call_failed'\n // `error` would only restate the message the runtime already renders.\n const rest = { ...payload }\n delete rest.error\n throw new Refusal(lines.join('\\n'), code, {\n ...(res.status === 401 ? { action: cliAction('deepspace', 'auth', 'login') } : {}),\n extra: rest,\n })\n}\n","/**\n * deepspace app library [publish|unpublish] [options]\n *\n * Manage entries in the DeepSpace community library (lives at\n * deepdotspace-site.app.space by default; override with --library-app\n * or DEEPSPACE_LIBRARY_HOST). Subcommands POST to that app's\n * `library.publish` / `library.unpublish` actions as the currently\n * logged-in user.\n *\n * The publish action verifies the caller owns the deployed app (by\n * checking the deploy worker's `/api/apps` registry) before writing\n * the row, so publishing another user's app is rejected server-side.\n *\n * Defined with the command runtime (lib/command.ts). That fixes this file's\n * long-standing deviation: both subcommands used to write their `--json`\n * envelope to STDERR (and the success envelope as the server's raw\n * `{success,data}` blob). It is now a single-line `{ ok, … }` document on\n * STDOUT, like every other command.\n *\n * Usage:\n * deepspace app library publish (uses wrangler.toml)\n * deepspace app library publish --app my-cool-app --name \"My Cool App\"\n * deepspace app library publish --description \"...\" --category Productivity\n * deepspace app library publish --tags utility,ai --visibility unlisted\n * deepspace app library unpublish <handle>\n */\n\nimport { defineCommand } from 'citty'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport * as p from '@clack/prompts'\n\nimport { ensureToken } from '../auth'\nimport { parseAppArg } from '../lib/app-target'\nimport { resolveAppName } from '../../server/rooms/app-name'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst DEFAULT_LIBRARY_APP = 'deepdotspace-site'\n\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)\n\nconst publish = defineDeepspaceCommand({\n meta: {\n name: 'publish',\n description: 'Publish the current app to the DeepSpace library',\n },\n args: {\n dir: {\n type: 'string',\n description: 'App directory (default: current directory)',\n required: false,\n },\n app: {\n type: 'string',\n description: 'App name (default: read from wrangler.toml)',\n required: false,\n },\n name: {\n type: 'string',\n description: 'Display name (default: app name)',\n required: false,\n },\n description: {\n type: 'string',\n description: 'Short description',\n required: false,\n },\n category: {\n type: 'string',\n description: 'Category (e.g. Productivity, Finance, AI). Default: General',\n required: false,\n },\n tags: {\n type: 'string',\n description: 'Comma-separated tags',\n required: false,\n },\n visibility: {\n type: 'string',\n description: \"'public' (default), 'unlisted', or 'private'\",\n required: false,\n },\n screenshot: {\n type: 'string',\n description: 'Override the auto-captured preview with a public PNG URL',\n required: false,\n },\n 'library-app': {\n type: 'string',\n description: `Target library app subdomain (default: ${DEFAULT_LIBRARY_APP})`,\n required: false,\n },\n },\n async run({ args }) {\n const json = args.json\n const intro = (s: string) => { if (!json) p.intro(s) }\n const info = (s: string) => { if (!json) p.log.info(s) }\n\n intro('Publishing to the DeepSpace library')\n\n // An explicit blank --app must error, not silently fall back to the cwd app.\n const appErr = parseAppArg(str(args.app)).error\n if (appErr) throw new Refusal(appErr, 'invalid_app')\n let appName = str(args.app)?.trim()\n if (!appName) {\n const appDir = resolve(str(args.dir) ?? '.')\n const wranglerPath = join(appDir, 'wrangler.toml')\n if (!existsSync(wranglerPath)) {\n throw new Refusal(\n \"No --app provided and no wrangler.toml found. Either pass --app <name> or run from your app's directory.\",\n 'not_in_app_repo',\n )\n }\n const cfg = parseToml(readFileSync(wranglerPath, 'utf-8')) as { name?: string }\n const nameRes = resolveAppName(cfg.name)\n if (!nameRes.ok) throw new Refusal(`wrangler.toml: ${nameRes.reason}`, 'invalid_config')\n appName = nameRes.name\n }\n info(`App: ${appName}`)\n\n const visibility = (str(args.visibility) ?? 'public') as string\n if (!['public', 'private', 'unlisted'].includes(visibility)) {\n throw new Refusal(\"--visibility must be 'public', 'unlisted', or 'private'.\", 'invalid_visibility')\n }\n\n const tags = str(args.tags)\n ? String(args.tags).split(',').map((t) => t.trim()).filter(Boolean)\n : undefined\n\n const libraryApp = str(args['library-app']) ?? DEFAULT_LIBRARY_APP\n const libraryHost = process.env.DEEPSPACE_LIBRARY_HOST ?? `https://${libraryApp}.app.space`\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err) {\n throw new Refusal(err instanceof Error ? err.message : String(err), 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const payload: Record<string, unknown> = {\n appName,\n ...(args.name ? { name: args.name } : {}),\n ...(args.description ? { description: args.description } : {}),\n ...(args.category ? { category: args.category } : {}),\n ...(tags ? { tags } : {}),\n visibility,\n ...(args.screenshot ? { screenshotUrl: args.screenshot } : {}),\n }\n\n const url = `${libraryHost}/api/actions/library.publish`\n let res: Response\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(payload),\n })\n } catch (err) {\n throw new Refusal(\n `Network error reaching ${url}: ${err instanceof Error ? err.message : String(err)}`,\n 'network_error',\n )\n }\n\n const body = await res.text()\n let parsed: { success?: boolean; data?: { templateHandle?: string; url?: string; version?: number }; error?: string }\n try {\n parsed = JSON.parse(body)\n } catch {\n throw new Refusal(`Server returned non-JSON (${res.status}): ${body.slice(0, 400)}`, 'invalid_response')\n }\n\n if (!parsed.success) {\n throw new Refusal(parsed.error ?? `Publish failed (HTTP ${res.status}).`, 'publish_failed')\n }\n\n if (!json) {\n p.log.success(`Published ${appName} as ${parsed.data?.templateHandle} (v${parsed.data?.version})`)\n if (parsed.data?.url) p.log.message(parsed.data.url)\n p.outro('Done')\n }\n return {\n data: {\n appName,\n templateHandle: parsed.data?.templateHandle ?? null,\n url: parsed.data?.url ?? null,\n version: parsed.data?.version ?? null,\n visibility,\n },\n }\n },\n})\n\nconst unpublish = defineDeepspaceCommand({\n meta: {\n name: 'unpublish',\n description: 'Remove a library entry (owner or admin only)',\n },\n args: {\n handle: {\n type: 'positional',\n description: 'templateHandle to remove (usually your app name)',\n required: true,\n },\n 'library-app': {\n type: 'string',\n description: `Target library app subdomain (default: ${DEFAULT_LIBRARY_APP})`,\n required: false,\n },\n },\n async run({ args }) {\n const json = args.json\n if (!json) p.intro('Unpublishing library entry')\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err) {\n throw new Refusal(err instanceof Error ? err.message : String(err), 'not_authenticated', {\n action: cliAction('deepspace', 'auth', 'login'),\n })\n }\n\n const libraryApp = str(args['library-app']) ?? DEFAULT_LIBRARY_APP\n const libraryHost = process.env.DEEPSPACE_LIBRARY_HOST ?? `https://${libraryApp}.app.space`\n\n const res = await fetch(`${libraryHost}/api/actions/library.unpublish`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n body: JSON.stringify({ templateHandle: String(args.handle) }),\n })\n const body = await res.text()\n let parsed: { success?: boolean; error?: string; data?: { templateHandle?: string } }\n try {\n parsed = JSON.parse(body)\n } catch {\n throw new Refusal(`Server returned non-JSON (${res.status}): ${body.slice(0, 400)}`, 'invalid_response')\n }\n if (!parsed.success) {\n throw new Refusal(parsed.error ?? `HTTP ${res.status}`, 'unpublish_failed')\n }\n if (!json) {\n p.log.success(`Unpublished ${parsed.data?.templateHandle}`)\n p.outro('Done')\n }\n // Terminal: nothing follows an unpublish.\n return { data: { templateHandle: parsed.data?.templateHandle ?? String(args.handle) } }\n },\n})\n\nexport default defineCommand({\n meta: {\n name: 'library',\n description: 'Manage your DeepSpace library entries',\n },\n subCommands: {\n publish,\n unpublish,\n },\n})\n","/**\n * deepspace feedback\n *\n * Submit a bug report, feature request, or general feedback to the DeepSpace\n * team. The report is authenticated as the logged-in user and POSTed to the\n * api-worker, where it lands in the admin triage queue (dashboard ·\n * Admin · Feedback).\n *\n * Interactive when run in a TTY (prompts for type/title/details); flag-driven\n * for agents and CI. The title is a positional argument; the details go in\n * --message (-m). Both are required for non-interactive use.\n *\n * deepspace feedback # full interactive prompt\n * deepspace feedback \"Crash on deploy\" -m \"It explodes when…\" # quick, non-interactive\n * deepspace feedback -t feature \"Add dark mode\" -m \"…\" --yes --json\n *\n * Best-effort environment context (CLI version, Node version, OS, and the\n * current app name if run inside a scaffolded app) is attached automatically\n * so the team can reproduce issues without a round-trip.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * and the exit code come from there. Its old local `fail()` emitted\n * `{ ok:false, error }` with NO `code`, so a `--json` caller had nothing\n * stable to branch on — every refusal below now carries a slug.\n */\n\nimport * as p from '@clack/prompts'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { release } from 'node:os'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS, DASHBOARD_URL } from '../env'\nimport { apiFetch } from '../lib/api'\nimport { cliAction, defineDeepspaceCommand, Refusal } from '../lib/command'\nimport { hasWranglerConfig, readWranglerConfig } from '../lib/wrangler-env'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\nconst TYPES = ['bug', 'feature', 'other'] as const\ntype FeedbackType = (typeof TYPES)[number]\n\nconst TYPE_LABELS: Record<FeedbackType, string> = {\n bug: 'Bug report',\n feature: 'Feature request',\n other: 'Other feedback',\n}\n\n// Mirror the api-worker's limits so over-length input fails fast with a clear\n// field-specific message instead of a generic 400 after the round-trip.\nconst MAX_TITLE_LEN = 200\nconst MAX_BODY_LEN = 10_000\nconst MAX_CONTEXT_LEN = 200\n\ninterface FeedbackContext {\n cliVersion: string\n nodeVersion: string\n platform: string\n appName?: string\n}\n\ninterface FeedbackPayload extends FeedbackContext {\n type: FeedbackType\n title: string\n body: string\n}\n\ninterface FeedbackReport {\n id: string\n type: FeedbackType\n title: string\n status: string\n createdAt: string\n}\n\nconst api = <T>(token: string, path: string, init?: RequestInit): Promise<T> =>\n apiFetch<T>(API_URL, token, path, init)\n\n/** Normalize/validate a `--type` value. Throws on an unknown type. */\nexport function normalizeType(raw: string | undefined): FeedbackType {\n const value = (raw ?? 'bug').toLowerCase()\n if ((TYPES as readonly string[]).includes(value)) return value as FeedbackType\n throw new Error(`Invalid --type \"${raw}\". Use one of: ${TYPES.join(', ')}.`)\n}\n\n/** Read the deepspace CLI version from its own package.json. */\nfunction readCliVersion(): string {\n try {\n const here = dirname(fileURLToPath(import.meta.url))\n // Bundled output lives in <pkg>/dist (package.json one level up); the\n // source tree has it three levels up from src/cli/commands.\n const candidates = [\n join(here, '..', 'package.json'),\n join(here, '..', '..', '..', 'package.json'),\n ]\n for (const path of candidates) {\n if (!existsSync(path)) continue\n const pkg = JSON.parse(readFileSync(path, 'utf-8')) as {\n name?: string\n version?: string\n }\n if (pkg.name === 'deepspace' && pkg.version) return pkg.version\n }\n } catch {\n // fall through\n }\n return 'unknown'\n}\n\n/** Best-effort app name from the current dir's wrangler.toml, if any. */\nfunction detectAppName(): string | undefined {\n try {\n const cwd = process.cwd()\n if (!hasWranglerConfig(cwd)) return undefined\n const config = readWranglerConfig(cwd)\n return typeof config.name === 'string' ? config.name : undefined\n } catch {\n return undefined\n }\n}\n\n/** Clamp a best-effort context value so it can never block submission. */\nfunction clampContext(value: string): string {\n return value.length > MAX_CONTEXT_LEN ? value.slice(0, MAX_CONTEXT_LEN) : value\n}\n\n/** Collect the environment context attached to every report. */\nexport function collectContext(): FeedbackContext {\n const appName = detectAppName()\n return {\n cliVersion: clampContext(readCliVersion()),\n nodeVersion: clampContext(process.version),\n platform: clampContext(`${process.platform} ${release()}`),\n ...(appName ? { appName: clampContext(appName) } : {}),\n }\n}\n\n/** Assemble the request body. Trims and validates title/body are non-empty. */\nexport function buildFeedbackPayload(input: {\n type: string | undefined\n title: string\n body: string\n context: FeedbackContext\n}): FeedbackPayload {\n const title = input.title.trim()\n const body = input.body.trim()\n if (!title) throw new Error('A title is required.')\n if (!body) throw new Error('A message/description is required.')\n if (title.length > MAX_TITLE_LEN) {\n throw new Error(`Title must be ${MAX_TITLE_LEN} characters or fewer (got ${title.length}).`)\n }\n if (body.length > MAX_BODY_LEN) {\n throw new Error(`Description must be ${MAX_BODY_LEN} characters or fewer (got ${body.length}).`)\n }\n return {\n type: normalizeType(input.type),\n title,\n body,\n ...input.context,\n }\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'feedback',\n description: 'Submit a bug report, feature request, or feedback to DeepSpace',\n },\n args: {\n title: {\n type: 'positional',\n description: 'Short summary (prompted if omitted in a terminal)',\n required: false,\n },\n type: {\n type: 'string',\n alias: 't',\n description: `Report type: ${TYPES.join(' | ')} (default: bug)`,\n required: false,\n },\n message: {\n type: 'string',\n alias: 'm',\n description: 'Details / description (prompted if omitted in a terminal)',\n required: false,\n },\n yes: {\n type: 'boolean',\n description: 'Skip the confirmation prompt',\n default: false,\n },\n },\n async run({ args }) {\n const interactive = Boolean(process.stdin.isTTY) && !args.json\n\n let type: FeedbackType\n try {\n type = normalizeType(args.type ? String(args.type) : undefined)\n } catch (err) {\n throw new Refusal((err as Error).message, 'invalid_type')\n }\n\n let title = args.title ? String(args.title) : ''\n let body = args.message ? String(args.message) : ''\n\n // Non-interactive callers (agents/CI) must supply both fields up front.\n if ((!title || !body) && !interactive) {\n throw new Refusal(\n 'Provide a title and --message to submit non-interactively, ' +\n 'e.g. `deepspace feedback \"Title\" --message \"Details\"`.',\n 'missing_input',\n )\n }\n\n // Prompt for whatever is still missing — including the type, so an\n // interactive user who passed --title/--message but no --type is still\n // asked rather than having it silently default to \"bug\".\n if (interactive && (!args.type || !title || !body)) {\n p.intro('DeepSpace Feedback')\n\n if (!args.type) {\n const picked = await p.select({\n message: 'What kind of feedback is this?',\n options: TYPES.map((t) => ({ value: t, label: TYPE_LABELS[t] })),\n initialValue: type,\n })\n if (p.isCancel(picked)) {\n p.cancel('Cancelled.')\n return { data: { submitted: false, cancelled: true } }\n }\n type = picked as FeedbackType\n }\n\n if (!title) {\n const t = await p.text({\n message: 'Title',\n placeholder: 'Short summary of the issue',\n validate: (v) => {\n if (!v?.trim()) return 'Title is required'\n if (v.length > MAX_TITLE_LEN)\n return `Title must be ${MAX_TITLE_LEN} characters or fewer`\n return undefined\n },\n })\n if (p.isCancel(t)) {\n p.cancel('Cancelled.')\n return { data: { submitted: false, cancelled: true } }\n }\n title = String(t)\n }\n\n if (!body) {\n const m = await p.text({\n message: 'Details',\n placeholder: 'What happened? Steps to reproduce, what you expected…',\n validate: (v) => {\n if (!v?.trim()) return 'A description is required'\n if (v.length > MAX_BODY_LEN)\n return `Description must be ${MAX_BODY_LEN} characters or fewer`\n return undefined\n },\n })\n if (p.isCancel(m)) {\n p.cancel('Cancelled.')\n return { data: { submitted: false, cancelled: true } }\n }\n body = String(m)\n }\n }\n\n let payload: FeedbackPayload\n try {\n payload = buildFeedbackPayload({\n type,\n title,\n body,\n context: collectContext(),\n })\n } catch (err) {\n throw new Refusal((err as Error).message, 'invalid_input')\n }\n\n // Confirmation — only when interactive and not explicitly skipped.\n if (interactive && !args.yes) {\n p.note(\n `${TYPE_LABELS[payload.type]}\\n${payload.title}\\n\\n${payload.body}` +\n `\\n\\nContext: deepspace ${payload.cliVersion} · ${payload.nodeVersion} · ${payload.platform}` +\n (payload.appName ? ` · app ${payload.appName}` : ''),\n 'Review',\n )\n const ok = await p.confirm({ message: 'Send this to the DeepSpace team?' })\n if (p.isCancel(ok) || !ok) {\n p.cancel('Not sent.')\n return { data: { submitted: false, cancelled: true } }\n }\n }\n\n let token: string\n try {\n token = await ensureToken()\n } catch (err) {\n throw new Refusal(\n (err as Error).message ?? 'Not signed in. Run `deepspace auth login`.',\n 'not_authenticated',\n { action: cliAction('deepspace', 'auth', 'login') },\n )\n }\n\n // The POST is left uncaught on purpose: apiFetch throws a typed ApiError\n // whose `code` the runtime already lifts into the envelope, so wrapping it\n // here would only replace a real server slug with a made-up one.\n const result = await api<{ report: FeedbackReport }>(token, '/api/feedback', {\n method: 'POST',\n body: JSON.stringify(payload),\n })\n\n if (!args.json) {\n if (interactive) {\n p.outro(`Thanks! Submitted as ${result.report.id}.`)\n } else {\n console.log(`Submitted feedback ${result.report.id} (${result.report.type}).`)\n }\n console.log(`Track triage status at ${DASHBOARD_URL}.`)\n }\n\n // Terminal operation — nothing to run next, so no `next` (never filler).\n return { data: { report: result.report as unknown as Record<string, unknown> } }\n },\n})\n","/**\n * `deepspace secrets` — manage the app's secrets store.\n *\n * Every app has exactly one store, addressed by its immutable id (the\n * DEEPSPACE_APP_ID in wrangler.toml); configs follow the wrangler-env\n * convention (top-level → `prd`, `--env staging` → `staging`). There is no\n * project/link setup step: run the commands from the app directory (or pass\n * --app <appId>) and they just work — for the owner, collaborators, and\n * admin accounts alike.\n *\n * deepspace secrets list [-c prd]\n * deepspace secrets set KEY=value [KEY2=value2 …]\n * deepspace secrets get KEY [--plain]\n * deepspace secrets delete KEY [KEY2 …]\n * deepspace secrets upload <file> (dotenv or JSON; --replace)\n * deepspace secrets download [--format dotenv|json|shell]\n * deepspace secrets pull (refresh the .dev.vars cache)\n * deepspace secrets configs list|create|delete\n */\n\nimport { defineCommand } from 'citty'\nimport { readFileSync } from 'node:fs'\nimport { ensureToken } from '../auth'\nimport { decodeJwtPayload } from '../jwt'\nimport { PLATFORM_URLS } from '../env'\nimport { findAppDir } from '../lib/app-context'\nimport { writeDevVars } from '../lib/dev-vars'\nimport { parseAppArg } from '../lib/app-target'\nimport { InputError, renderCliError } from '../lib/cli-errors'\nimport { readAppId, APP_ID_RE } from '../lib/app-identity'\nimport { dedupePositionals } from '../lib/citty-args'\nimport {\n createConfig,\n defaultConfigNameForEnv,\n deleteConfig,\n deleteSecret,\n fetchSecretsValues,\n formatSecretsDownload,\n getSecretPlain,\n listConfigs,\n listSecrets,\n parseSecretsUpload,\n pullAppSecretsCache,\n renderSecretsCache,\n setSecret,\n uploadSecrets,\n validateConfigName,\n validateSecretName,\n validateSecretValue,\n type SecretsDownloadFormat,\n} from '../lib/secrets'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nconst COMMON_ARGS = {\n app: {\n type: 'string' as const,\n alias: 'a',\n description: 'App id (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n config: {\n type: 'string' as const,\n alias: 'c',\n description: 'Config name (default: the --env name, or \"prd\")',\n required: false,\n },\n env: {\n type: 'string' as const,\n alias: 'e',\n description: 'wrangler.toml [env.<name>] slot — selects that env’s app id and config',\n required: false,\n },\n json: {\n type: 'boolean' as const,\n description: 'Emit a single-line JSON result for scripts/agents',\n default: false,\n },\n}\n\ninterface Target {\n appId: string\n configName: string\n token: string\n}\n\nasync function resolveTarget(args: {\n app?: string\n config?: string\n env?: string\n}): Promise<Target> {\n const wranglerEnv = args.env?.trim() || undefined\n // An explicit blank --app must not silently fall back to the current dir's app\n // — secrets are written to the target app, so a wrong target leaks/overwrites.\n const { error: appErr } = parseAppArg(args.app)\n if (appErr) throw new InputError(appErr, 'invalid_app')\n let appId = args.app?.trim()\n if (appId && !APP_ID_RE.test(appId)) {\n throw new InputError(`Invalid app id \"${appId}\" — expected app_<26 chars>.`, 'invalid_app_id')\n }\n if (!appId) {\n const appDir = findAppDir()\n appId = (appDir && readAppId(appDir, wranglerEnv)) || undefined\n if (!appId) {\n // `--env <name>` selects a wrangler [env.<name>] slot with its OWN app id.\n // If the slot is missing but a top-level app id exists, the user almost\n // certainly wanted to pick a *config*, not an env — point them at `-c`.\n if (wranglerEnv && appDir && readAppId(appDir, undefined)) {\n throw new InputError(\n `No app id for env \"${wranglerEnv}\" — wrangler.toml has no [env.${wranglerEnv}] block with its own DEEPSPACE_APP_ID. ` +\n `To target the \"${wranglerEnv}\" config on this app, use \\`-c ${wranglerEnv}\\` instead of \\`--env ${wranglerEnv}\\`.`,\n 'no_app_id_for_env',\n )\n }\n throw new InputError(\n 'No app id. Run from an app directory whose wrangler.toml carries DEEPSPACE_APP_ID (`deepspace app init` mints one), or pass --app <appId>.',\n 'not_in_app_repo',\n )\n }\n }\n const configName = validateConfigName(args.config?.trim() || defaultConfigNameForEnv(wranglerEnv))\n const token = await ensureToken()\n return { appId, configName, token }\n}\n\nfunction fail(err: unknown): never {\n // Route through the shared renderer so `secrets` obeys the output contract\n // like every other command: `--json` gets the {ok,code,error} envelope on\n // stdout, the human path gets the message with its slug appended.\n renderCliError(err)\n}\n\n/**\n * A success result on the contract. Under `--json` it is the single\n * `{ ok: true, … }` line; otherwise it runs the human callback. Wires the\n * success paths that used to print prose regardless of `--json`.\n */\nfunction ok(json: boolean, data: Record<string, unknown>, human: () => void): void {\n if (json) console.log(JSON.stringify({ ok: true, ...data }))\n else human()\n}\n\n/**\n * Warn (once) when a write turns on the unauthenticated debug API. Applies to\n * every write path that can carry it — `set` and `upload` alike. Returns true\n * when it warned, so callers can skip the generic \"run deploy\" line (this\n * message already tells the user to redeploy).\n */\nfunction warnIfDebugRoutesEnabled(secrets: Record<string, string>): boolean {\n if (secrets.ALLOW_DEBUG_ROUTES !== 'true') return false\n console.warn(\n '\\n⚠ ALLOW_DEBUG_ROUTES=true exposes an UNAUTHENTICATED debug API on the deployed app —\\n' +\n ' anyone who can reach /api/debug/* can read and mutate any record. Redeploy to apply;\\n' +\n ' `deepspace secrets delete ALLOW_DEBUG_ROUTES` (then redeploy) turns it back off.',\n )\n return true\n}\n\nconst APPLY_HINT = 'Run `deepspace deploy` to apply — secrets take effect at deploy time.'\n// `deepspace dev start` regenerates .dev.vars from the store only at startup, so a\n// secret changed mid-session isn't picked up until dev restarts (DEV-4).\nconst LOCAL_DEV_HINT = 'Running `deepspace dev start`? Restart it to load the change locally.'\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List masked secrets in a config' },\n args: {\n ...COMMON_ARGS,\n 'only-names': {\n type: 'boolean',\n description: 'Only print secret names; omit values and metadata',\n default: false,\n },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const { secrets } = await listSecrets(DEPLOY_URL, t.token, t.appId, t.configName)\n if (args.json) {\n console.log(JSON.stringify({ ok: true, appId: t.appId, config: t.configName, secrets }))\n return\n }\n if (secrets.length === 0) {\n console.log(`No secrets in ${t.configName}.`)\n return\n }\n for (const s of secrets) {\n console.log(args['only-names'] ? s.key : `${s.key} (v${s.version}, ${s.updatedAt})`)\n }\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst set = defineCommand({\n meta: { name: 'set', description: 'Set secrets from KEY=value pairs' },\n args: {\n ...COMMON_ARGS,\n secret: { type: 'positional', description: 'KEY=value (repeatable)', required: true },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const pairs = dedupePositionals(args.secret, args._)\n const secrets: Record<string, string> = {}\n const dupes: string[] = []\n for (const pair of pairs) {\n const eq = pair.indexOf('=')\n if (eq <= 0) throw new InputError(`Expected KEY=value, got \"${pair}\"`, 'invalid_pair')\n const key = validateSecretName(pair.slice(0, eq))\n const value = pair.slice(eq + 1)\n validateSecretValue(key, value)\n // The same KEY given twice (with different values) silently keeps the\n // last — surface it instead of dropping a value without a word.\n if (key in secrets && !dupes.includes(key)) dupes.push(key)\n secrets[key] = value\n }\n if (dupes.length) {\n console.warn(\n `Warning: ${dupes.join(', ')} given more than once — kept the last value for each.`,\n )\n }\n if (Object.keys(secrets).length === 1) {\n const [[k, v]] = Object.entries(secrets)\n await setSecret(DEPLOY_URL, t.token, t.appId, t.configName, k, v)\n } else {\n await uploadSecrets(DEPLOY_URL, t.token, t.appId, t.configName, secrets, false)\n }\n const n = Object.keys(secrets).length\n ok(\n args.json === true,\n { appId: t.appId, config: t.configName, set: Object.keys(secrets) },\n () => {\n console.log(`Set ${n} secret${n === 1 ? '' : 's'} in ${t.configName}.`)\n if (!warnIfDebugRoutesEnabled(secrets)) {\n console.log(APPLY_HINT)\n console.log(LOCAL_DEV_HINT)\n }\n },\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst get = defineCommand({\n meta: { name: 'get', description: 'Get a secret; pass --plain to print the value' },\n args: {\n ...COMMON_ARGS,\n key: { type: 'positional', description: 'Secret name', required: true },\n plain: { type: 'boolean', description: 'Print the plaintext value', default: false },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const key = validateSecretName(args.key)\n if (args.plain) {\n const { value } = await getSecretPlain(DEPLOY_URL, t.token, t.appId, t.configName, key)\n // Raw value, byte-exact when piped (`… get --plain KEY > key.pem`) — a\n // --json wrapper would corrupt it, so --plain is a raw stream either\n // way (documented exception, like `download`). Trailing newline only\n // for a human at a TTY.\n process.stdout.write(process.stdout.isTTY ? value + '\\n' : value)\n return\n }\n const { secrets } = await listSecrets(DEPLOY_URL, t.token, t.appId, t.configName)\n const item = secrets.find((s) => s.key === key)\n if (!item)\n fail(new InputError(`Secret \"${key}\" not found in ${t.configName}`, 'secret_not_found'))\n ok(\n args.json === true,\n {\n appId: t.appId,\n config: t.configName,\n key: item!.key,\n version: item!.version,\n updatedAt: item!.updatedAt,\n },\n () => console.log(`${item!.key} (v${item!.version}, ${item!.updatedAt})`),\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst del = defineCommand({\n meta: { name: 'delete', description: 'Delete one or more secrets' },\n args: {\n ...COMMON_ARGS,\n key: { type: 'positional', description: 'Secret name (repeatable)', required: true },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const keys = dedupePositionals(args.key, args._)\n let deleted = 0\n let absent = 0\n for (const key of keys) {\n const name = validateSecretName(key)\n try {\n await deleteSecret(DEPLOY_URL, t.token, t.appId, t.configName, name)\n deleted++\n } catch (err) {\n // An already-absent key is a completed delete, not a failure: don't\n // let one missing key abort the rest, and keep retries idempotent.\n if ((err as { status?: number })?.status === 404) absent++\n else throw err\n }\n }\n const note = absent > 0 ? ` (${absent} already absent)` : ''\n ok(args.json === true, { appId: t.appId, config: t.configName, deleted, absent }, () => {\n console.log(\n `Deleted ${deleted} secret${deleted === 1 ? '' : 's'} from ${t.configName}.${note}`,\n )\n if (deleted > 0) console.log(APPLY_HINT)\n })\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst upload = defineCommand({\n meta: { name: 'upload', description: 'Upload secrets from a dotenv or JSON file' },\n args: {\n ...COMMON_ARGS,\n file: {\n type: 'positional',\n description: 'Path to a dotenv or JSON file (- for stdin)',\n required: true,\n },\n replace: {\n type: 'boolean',\n description: 'Replace the whole config (delete keys missing from the file)',\n default: false,\n },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const content =\n args.file === '-' ? readFileSync(0, 'utf-8') : readFileSync(args.file, 'utf-8')\n const secrets = parseSecretsUpload(content)\n if (Object.keys(secrets).length === 0)\n fail(new InputError('No secrets found in the input.', 'empty_input'))\n await uploadSecrets(DEPLOY_URL, t.token, t.appId, t.configName, secrets, args.replace)\n const uploaded = Object.keys(secrets)\n ok(\n args.json === true,\n { appId: t.appId, config: t.configName, uploaded, replaced: args.replace === true },\n () => {\n console.log(`Uploaded ${uploaded.length} secrets to ${t.configName}.`)\n // A file can turn on the debug API just like `set` can — warn either way.\n if (!warnIfDebugRoutesEnabled(secrets)) console.log(APPLY_HINT)\n },\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst download = defineCommand({\n meta: { name: 'download', description: 'Download a config’s secrets (dotenv/json/shell)' },\n args: {\n ...COMMON_ARGS,\n format: {\n type: 'string',\n description: 'dotenv (default) | json | shell',\n default: 'dotenv',\n },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const format = args.format as SecretsDownloadFormat\n if (!['dotenv', 'json', 'shell'].includes(format)) {\n fail(\n new InputError(\n `Unknown format \"${args.format}\" — use dotenv, json, or shell.`,\n 'invalid_format',\n ),\n )\n }\n const { secrets } = await fetchSecretsValues(DEPLOY_URL, t.token, t.appId, t.configName)\n process.stdout.write(formatSecretsDownload(secrets, format))\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst pull = defineCommand({\n meta: { name: 'pull', description: 'Refresh the .dev.vars cache from the app store' },\n args: { ...COMMON_ARGS },\n async run({ args }) {\n try {\n const wranglerEnv = args.env?.trim() || undefined\n const appDir = findAppDir()\n if (!appDir)\n fail(\n new InputError(\n 'Run from a DeepSpace app directory (one containing wrangler.toml).',\n 'not_in_app_repo',\n ),\n )\n const t = await resolveTarget(args)\n const ownerId = decodeJwtPayload<{ sub: string }>(t.token).sub\n const pulled = await pullAppSecretsCache(DEPLOY_URL, t.token, t.appId, t.configName)\n if (!pulled) {\n // A collaborator's first pull on a fresh clone often lands here —\n // point at how secrets get INTO the store, not just that it's empty.\n ok(args.json === true, { appId: t.appId, config: t.configName, pulled: 0 }, () =>\n console.log(\n `No secrets in ${t.configName} yet — nothing to pull. Whoever has them adds them with \\`deepspace secrets set KEY=value\\` (or \\`secrets upload <file>\\`); if the app truly needs none, you're ready as-is.`,\n ),\n )\n return\n }\n await writeDevVars(appDir, ownerId, t.token, wranglerEnv, {\n appId: t.appId,\n generatedSecretsCache: renderSecretsCache(pulled.values, pulled),\n sharedDevVarsCache: true,\n })\n const count = Object.keys(pulled.values).length\n ok(args.json === true, { appId: t.appId, config: t.configName, pulled: count }, () =>\n console.log(`Pulled ${count} secrets (${t.configName}) into .dev.vars.`),\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst configsList = defineCommand({\n meta: { name: 'list', description: 'List the app’s configs' },\n args: { ...COMMON_ARGS },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const { configs } = await listConfigs(DEPLOY_URL, t.token, t.appId)\n ok(args.json === true, { appId: t.appId, configs }, () => {\n if (configs.length === 0) {\n console.log('No configs yet — the first `secrets set` creates one.')\n return\n }\n for (const cfg of configs) {\n console.log(`${cfg.name} (${cfg.secretCount ?? 0} secrets, updated ${cfg.updatedAt})`)\n }\n })\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst configsCreate = defineCommand({\n meta: { name: 'create', description: 'Create a config (optionally copying another)' },\n args: {\n ...COMMON_ARGS,\n name: { type: 'positional', description: 'Config name', required: true },\n 'copy-from': { type: 'string', description: 'Copy secrets from this config', required: false },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const name = validateConfigName(args.name)\n const copyFrom = args['copy-from'] || undefined\n // Create is idempotent server-side, so a plain create of an existing\n // config used to print a false \"Created\". Distinguish the cases up front:\n // a bare re-create is a no-op (\"Already exists.\"); a --copy-from into an\n // existing config would clobber it, so refuse rather than silently create.\n const { configs } = await listConfigs(DEPLOY_URL, t.token, t.appId)\n if (configs.some((c) => c.name === name)) {\n if (copyFrom) {\n fail(\n new InputError(\n `Config \"${name}\" already exists — refusing to copy \"${copyFrom}\" over it. Delete it first, or pick a new name.`,\n 'config_exists',\n ),\n )\n }\n ok(args.json === true, { appId: t.appId, config: name, created: false }, () =>\n console.log(`Config ${name} already exists.`),\n )\n return\n }\n await createConfig(DEPLOY_URL, t.token, t.appId, name, copyFrom)\n ok(\n args.json === true,\n { appId: t.appId, config: name, created: true, ...(copyFrom ? { copyFrom } : {}) },\n () => console.log(`Created ${name}.`),\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst configsDelete = defineCommand({\n meta: { name: 'delete', description: 'Delete a config and all of its secrets' },\n args: {\n ...COMMON_ARGS,\n name: { type: 'positional', description: 'Config name', required: true },\n },\n async run({ args }) {\n try {\n const t = await resolveTarget(args)\n const name = validateConfigName(args.name)\n await deleteConfig(DEPLOY_URL, t.token, t.appId, name)\n ok(args.json === true, { appId: t.appId, config: name, deleted: true }, () =>\n console.log(`Deleted ${name}.`),\n )\n } catch (err) {\n fail(err)\n }\n },\n})\n\nconst configs = defineCommand({\n meta: { name: 'configs', description: 'Manage the app’s secrets configs' },\n subCommands: { list: configsList, create: configsCreate, delete: configsDelete },\n})\n\nexport default defineCommand({\n meta: { name: 'secrets', description: 'Manage the app’s secrets store' },\n subCommands: {\n list,\n set,\n get,\n delete: del,\n upload,\n download,\n pull,\n configs,\n },\n})\n","/**\n * Helpers for citty argument quirks.\n */\n\n/**\n * citty binds the first positional to its named arg AND *also* leaves the full\n * positional list in `args._`. A handler that naively unions `[named, ...args._]`\n * therefore processes the first positional twice — which silently broke\n * `secrets delete`: it deleted a key, re-attempted the same key, got a 404, and\n * aborted the rest (`delete A B` kept B; a single `delete A` exited 1 on success).\n *\n * Union + dedupe (dropping empties / non-strings) yields the caller's distinct\n * positionals exactly once, in first-seen order. Use this anywhere a command\n * accepts a repeatable positional.\n */\nexport function dedupePositionals(bound: unknown, rest: unknown): string[] {\n const restArr = Array.isArray(rest) ? rest : []\n return [...new Set([bound, ...restArr])].filter(\n (v): v is string => typeof v === 'string' && v.length > 0,\n )\n}\n\n// A page size / cursor is a plain base-10 non-negative integer — either a count\n// a human typed or, for a cursor, the exact token the server handed back.\n// Matching on the digit STRING (after trimming surrounding whitespace) rather\n// than coercing with Number() is deliberate: Number() is far too lenient here —\n// it maps whitespace-only input to 0 (`Number(\" \") === 0`, which silently\n// replayed history for a corrupted cursor), and accepts hex/binary/scientific/\n// float spellings (`0x10`, `1e3`, `5.0`) that the server never emits. `\\d+`\n// admits none of those, nor a sign, so negatives fall through to the error path.\n// Digits alone don't bound magnitude, so callers also require Number.isSafeInteger:\n// a value past 2^53 (e.g. `9007199254740993`) would round when parsed, and the\n// CLI echoes the cursor back to the server verbatim — a silently-rounded cursor\n// breaks the \"you get back the token you sent\" invariant. No legitimate page\n// size or cursor approaches 2^53, so rejecting the unsafe range costs nothing.\nconst NON_NEGATIVE_INT_RE = /^\\d+$/\n\n/**\n * Parse a user-supplied `--limit`. An absent flag yields `undefined` (the\n * server applies its own default page size). A present-but-invalid value —\n * non-numeric, fractional, signed, whitespace-only, past 2^53, or ≤ 0 — yields\n * an `error` string instead of silently collapsing to \"no limit\": the old\n * `args.limit ? Number(args.limit) : undefined` (and the `Number(x) || undefined`\n * variant) turned `--limit nope` and `--limit 0` into an UNBOUNDED request, so an\n * automation asking for a small page could get the entire list back without any\n * signal. Callers surface the error through their own `fail(...)` as\n * `code:\"invalid_limit\"`.\n */\nexport function parseLimitArg(raw: unknown): { limit?: number; error?: string } {\n if (raw === undefined || raw === null || raw === '') return {}\n const s = String(raw).trim()\n const n = Number(s)\n if (!NON_NEGATIVE_INT_RE.test(s) || !Number.isSafeInteger(n) || n <= 0) {\n return { error: `Invalid --limit: ${String(raw)} (expected a positive integer).` }\n }\n return { limit: n }\n}\n\n/**\n * Parse an activity `--since` cursor. An absent flag (or an empty string, the\n * shell idiom for \"no saved cursor yet\") yields cursor 0 (start of history). Any\n * other present value must be a non-negative integer the server handed back — a\n * fractional one like `1.9`, a whitespace-only one, or one past 2^53 yields an\n * `error` rather than being floored/coerced/rounded: silently replaying an\n * earlier page (or echoing back a rounded cursor) is exactly what an agent with\n * a corrupted saved cursor would mistake for new activity. Callers surface the\n * error as `code:\"invalid_cursor\"`.\n */\nexport function parseCursorArg(raw: unknown): { cursor: number; error?: string } {\n if (raw === undefined || raw === null || raw === '') return { cursor: 0 }\n const s = String(raw).trim()\n const n = Number(s)\n if (!NON_NEGATIVE_INT_RE.test(s) || !Number.isSafeInteger(n)) {\n return {\n cursor: 0,\n error: `Invalid --since cursor: ${String(raw)} (expected the integer cursor returned by a previous page).`,\n }\n }\n return { cursor: n }\n}\n","/**\n * `deepspace app init` — ensure this app carries its immutable identity.\n *\n * Mints DEEPSPACE_APP_ID into wrangler.toml (per wrangler env with --env).\n * Registration happens at the first deploy. `--new-id` replaces an existing\n * id, which FORKS the repo into a separate app: fresh registration, fresh\n * Durable Object data, fresh secrets store — the original app is untouched.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, the `Next:` line and the exit codes come from there.\n */\n\nimport { findAppDir } from '../lib/app-context'\nimport { mintAppId, readAppId, writeAppId } from '../lib/app-identity'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'init',\n description: 'Mint this app’s immutable DEEPSPACE_APP_ID into wrangler.toml',\n },\n args: {\n 'new-id': {\n type: 'boolean',\n description:\n 'Replace the existing id — forks this repo as a SEPARATE app (new data, new secrets, new registration). The original app keeps running.',\n default: false,\n },\n env: {\n type: 'string',\n alias: 'e',\n description: 'wrangler.toml [env.<name>] block to stamp (each env is its own app)',\n required: false,\n },\n },\n async run({ args }) {\n const appDir = findAppDir()\n if (!appDir) {\n throw new Refusal(\n 'No wrangler.toml here — `deepspace app init` stamps an app id into an existing ' +\n 'DeepSpace app. To create a new app, run `deepspace app create <name>` (or ' +\n '`npm create deepspace@latest <name>`), then run this from inside it.',\n 'not_an_app',\n )\n }\n const envName = (args.env as string) || undefined\n const existing = readAppId(appDir, envName)\n if (existing && !args['new-id']) {\n if (!args.json) {\n console.log(`Already initialized: ${existing}${envName ? ` (env: ${envName})` : ''}`)\n console.log(`App dir: ${appDir}`)\n }\n return {\n data: { status: 'already_initialized', appId: existing, appDir, env: envName ?? null },\n }\n }\n const appId = mintAppId()\n writeAppId(appDir, appId, { wranglerEnv: envName, force: Boolean(args['new-id']) })\n if (!args.json) {\n if (existing) {\n console.log(`Forked: ${existing} → ${appId}${envName ? ` (env: ${envName})` : ''}`)\n console.log('The next deploy registers this as a NEW app; the original is untouched.')\n } else {\n console.log(`Minted ${appId}${envName ? ` (env: ${envName})` : ''} — commit wrangler.toml.`)\n console.log('The first deploy registers it and claims the `name` subdomain.')\n }\n console.log(`App dir: ${appDir}`)\n }\n return {\n data: {\n status: existing ? 'forked' : 'minted',\n appId,\n ...(existing ? { previousAppId: existing } : {}),\n appDir,\n env: envName ?? null,\n },\n }\n },\n})\n","/**\n * `deepspace status` — one screenful of present-tense truth, so an agent\n * re-orients from a single command after any context loss instead of\n * reconstructing state from five reads and memory.\n *\n * State, not story: session, app, deps, branch/workspace position, live\n * and release. No narrative, no summarization — interpretation is the agent's\n * job. Recovery commands belong to the operation that refuses, not to a\n * centralized cross-product of every possible status fact. Live coordination\n * facts stream separately through `deepspace activity --follow`.\n *\n * Network sections are fetched in parallel and degrade PER LINE to\n * `(unreachable)` — status must never fail to report the local facts it has.\n * Informational throughout: exit 0 whenever the report itself was produced.\n */\n\nimport { defineCommand } from 'citty'\nimport * as p from '@clack/prompts'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { SESSION_PATH, TOKEN_PATH, ensureToken } from '../auth'\nimport { DEEPSPACE_ENV, effectivePlatformUrls } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { findAppDir, detectAppName } from '../lib/app-context'\nimport { readAppId } from '../lib/app-identity'\nimport { currentBranch, isAncestor, resolveCommit } from '../lib/git/repository'\nimport { statusFiles } from '../lib/git/safety'\nimport { workspaceIdFromBranch } from '../lib/workspace-id'\nimport { deployBaseUrl } from '../lib/vc-remote'\nimport { repoApi, type RemoteRelease, type RemoteWorkspaceView } from '../lib/repo-api'\nimport { errorCode } from '../lib/cli-errors'\nimport { installState } from '../lib/install-status'\nimport { installCommand } from '../lib/package-manager'\nimport { createSpinner } from '../lib/spinner'\n\nfunction timeAgo(iso: string): string {\n const ms = Date.now() - Date.parse(iso)\n if (!Number.isFinite(ms) || ms < 0) return iso\n const m = Math.floor(ms / 60_000)\n if (m < 1) return 'just now'\n if (m < 60) return `${m}m ago`\n const h = Math.floor(m / 60)\n if (h < 48) return `${h}h ago`\n return `${Math.floor(h / 24)}d ago`\n}\n\nconst UNREACHABLE = '(unreachable)'\n\ntype RemoteResult<T> = { ok: true; value: T } | { ok: false; error: unknown }\n\nconst observeRemote = <T>(promise: Promise<T>): Promise<RemoteResult<T>> =>\n promise.then(\n (value) => ({ ok: true, value }),\n (error: unknown) => ({ ok: false, error }),\n )\n\nexport function statusRemoteFailure(error: unknown): {\n human: string\n json: { state: 'unavailable'; error: string; code?: string }\n} {\n const message = error instanceof Error ? error.message : String(error)\n const code = errorCode(error)\n const suffix = code ? ` [${code}]` : ''\n return {\n human:\n code === 'network_error' ? `${UNREACHABLE} — ${message}${suffix}` : `${message}${suffix}`,\n json: { state: 'unavailable', error: message, ...(code ? { code } : {}) },\n }\n}\n\nexport default defineCommand({\n meta: {\n name: 'status',\n description: 'One screenful of current state: session, app, workspace, and live release',\n },\n args: {\n json: {\n type: 'boolean',\n description: 'Emit a single-line JSON result for scripts/agents',\n default: false,\n },\n },\n async run({ args }) {\n const lines: Array<[string, string]> = []\n const facts = {\n loggedIn: false,\n workspaceId: null as string | null,\n dirtyFiles: 0,\n unsynced: false,\n aheadOfBase: 0,\n trunkState: 'unknown' as\n | 'in_sync'\n | 'local_ahead'\n | 'local_behind'\n | 'diverged'\n | 'differs'\n | 'unknown',\n }\n const json: Record<string, unknown> = { ok: true }\n\n // ── environment (print ONLY when not plain prod — half of all staging\n // confusion is not being able to see which plane a command talks to) ──\n const urlOverrides = [\n 'DEEPSPACE_DEPLOY_URL',\n 'DEEPSPACE_AUTH_URL',\n 'DEEPSPACE_API_URL',\n 'DEEPSPACE_PLATFORM_URL',\n ].filter((k) => process.env[k])\n if (DEEPSPACE_ENV !== 'production' || urlOverrides.length > 0) {\n const urls = effectivePlatformUrls()\n const detail = [\n DEEPSPACE_ENV !== 'production' ? DEEPSPACE_ENV : null,\n ...urlOverrides.map((k) => `${k} set`),\n ]\n .filter(Boolean)\n .join(' · ')\n lines.push(['Env', detail])\n lines.push([\n 'Services',\n `auth ${urls.auth} · api ${urls.api} · platform ${urls.platform} · deploy ${urls.deploy}`,\n ])\n json.env = DEEPSPACE_ENV\n json.services = urls\n if (urlOverrides.length > 0) json.urlOverrides = urlOverrides\n }\n\n // ── session (local only — never blocks on the network) ──────────────\n facts.loggedIn = existsSync(SESSION_PATH)\n let userId: string | null = null\n if (!facts.loggedIn) {\n lines.push(['Session', 'not logged in'])\n json.loggedIn = false\n } else {\n let who = 'logged in'\n try {\n const payload = decodeJwtPayload<{ email?: string; sub?: string }>(\n readFileSync(TOKEN_PATH, 'utf-8').trim(),\n )\n if (payload.email) who = payload.email\n userId = payload.sub ?? null\n } catch {\n // token file absent/stale — the session still mints on next use\n }\n lines.push(['Session', `${who} · renews on use (re-login only after 30 idle days)`])\n json.loggedIn = true\n json.user = who\n }\n\n // ── app (local) ──────────────────────────────────────────────────────\n const appDir = findAppDir()\n if (!appDir) {\n lines.push(['App', 'not inside a DeepSpace app directory'])\n json.inApp = false\n } else {\n const appName = detectAppName(appDir) ?? '(unnamed)'\n const appId = readAppId(appDir)\n lines.push([\n 'App',\n `${appName}${appId ? ` (${appId})` : ' — no DEEPSPACE_APP_ID; run `deepspace app init`'}`,\n ])\n json.inApp = true\n json.appName = appName\n json.appId = appId\n\n const deps = installState(appDir)\n const depsInstallCommand = installCommand(appDir)\n lines.push([\n 'Deps',\n deps === 'ready'\n ? 'installed'\n : deps === 'installing'\n ? 'dependency installation is still running'\n : `${deps} — run ${depsInstallCommand}`,\n ])\n json.deps = deps\n\n // ── local git position ────────────────────────────────────────────\n let branch: string | null = null\n try {\n branch = currentBranch(appDir)\n facts.dirtyFiles = statusFiles(appDir).length\n facts.workspaceId = workspaceIdFromBranch(branch)\n lines.push([\n 'Branch',\n `${branch ?? '(detached)'}${facts.workspaceId ? ` → workspace ${facts.workspaceId}` : ''}`,\n ])\n lines.push([\n 'Worktree',\n facts.dirtyFiles === 0\n ? 'clean'\n : `${facts.dirtyFiles} uncommitted file${facts.dirtyFiles === 1 ? '' : 's'}`,\n ])\n json.branch = branch\n json.workspaceId = facts.workspaceId\n json.dirtyFiles = facts.dirtyFiles\n } catch {\n lines.push(['Branch', 'not a git repository'])\n json.branch = null\n }\n\n // ── network facts, in parallel, each degrading alone ──────────────\n if (facts.loggedIn && appId) {\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Checking cloud state…')\n let token: string | null = null\n try {\n token = await ensureToken()\n } catch (err) {\n // Offline is NOT a dead session. exchangeSession's fetch REJECTS\n // when the network is down, and reporting that as \"expired\" both\n // lies and obscures every local fact status already gathered. Only\n // a real auth failure clears loggedIn.\n const offline = err instanceof TypeError || errorCode(err) === 'network_error'\n if (offline) {\n lines.push(['Cloud', `${UNREACHABLE} — local facts only`])\n json.cloudUnreachable = true\n } else {\n lines.push(['Cloud', 'session expired — run `deepspace auth login`'])\n facts.loggedIn = false\n json.sessionExpired = true\n }\n }\n if (token) {\n const api = repoApi(deployBaseUrl(), token, appId)\n const [refsResult, wsResult, releaseResult] = await Promise.all([\n observeRemote(api.getRefs()),\n facts.workspaceId\n ? observeRemote(api.getWorkspace(facts.workspaceId).then((r) => r.view))\n : Promise.resolve({ ok: true, value: null } as const),\n observeRemote(api.latestRelease().then((r) => r.release)),\n ] as const)\n\n // workspace position\n if (facts.workspaceId) {\n if (!wsResult.ok) reportRemoteFailure('Workspace', 'workspace', wsResult.error)\n else if (wsResult.value) reportWorkspace(wsResult.value)\n }\n function reportWorkspace(view: RemoteWorkspaceView): void {\n const localTip = branch ? resolveCommit(appDir!, `refs/heads/${branch}`) : null\n facts.unsynced = localTip !== null && view.tipOid !== localTip\n facts.aheadOfBase = view.aheadOfBase?.count ?? 0\n const behind = view.behindTrunk?.count ?? 0\n lines.push([\n 'Workspace',\n `\"${view.workspace.task}\" · ${facts.unsynced ? 'has UNSYNCED local commits' : 'synced'} · ` +\n `${facts.aheadOfBase} commit${facts.aheadOfBase === 1 ? '' : 's'} ahead of base · ` +\n (behind === 0 ? 'trunk unchanged since base' : `trunk moved ${behind} since base`),\n ])\n json.workspace = {\n task: view.workspace.task,\n unsynced: facts.unsynced,\n aheadOfBase: facts.aheadOfBase,\n behindTrunk: behind,\n }\n }\n\n // trunk position (only meaningful off a workspace branch)\n const refs = refsResult.ok ? refsResult.value : undefined\n const trunkRef = refs?.refs.find((r) => `refs/heads/${branch}` === r.name)\n if (!facts.workspaceId && branch) {\n if (!refsResult.ok) reportRemoteFailure('Trunk', 'trunk', refsResult.error)\n else {\n const remoteOid = trunkRef?.oid ?? null\n const localOid = resolveCommit(appDir, `refs/heads/${branch}`)\n const remoteKnownLocally = remoteOid\n ? resolveCommit(appDir, remoteOid) !== null\n : false\n facts.trunkState =\n remoteOid === null && localOid === null\n ? 'unknown'\n : remoteOid === localOid\n ? 'in_sync'\n : remoteOid &&\n localOid &&\n remoteKnownLocally &&\n isAncestor(appDir, remoteOid, localOid)\n ? 'local_ahead'\n : remoteOid &&\n localOid &&\n remoteKnownLocally &&\n isAncestor(appDir, localOid, remoteOid)\n ? 'local_behind'\n : remoteOid && localOid && remoteKnownLocally\n ? 'diverged'\n : 'differs'\n lines.push([\n 'Trunk',\n remoteOid === null\n ? `cloud repo has no ${branch} yet`\n : facts.trunkState === 'in_sync'\n ? `${branch} in sync with the cloud repo (${remoteOid.slice(0, 10)})`\n : `${branch} ${facts.trunkState.replace('_', ' ')} relative to the cloud repo (local ${localOid?.slice(0, 10) ?? 'none'}, cloud ${remoteOid.slice(0, 10)})`,\n ])\n json.trunk = { state: facts.trunkState, localOid, remoteOid }\n }\n }\n\n // live release\n if (!releaseResult.ok) reportRemoteFailure('Live', 'live', releaseResult.error)\n else if (releaseResult.value === null) {\n lines.push(['Live', 'never deployed'])\n json.live = null\n } else {\n reportRelease(releaseResult.value)\n }\n function reportRemoteFailure(label: string, key: string, error: unknown): void {\n const failure = statusRemoteFailure(error)\n lines.push([label, failure.human])\n json[key] = failure.json\n }\n function reportRelease(rel: RemoteRelease): void {\n const byYou = userId !== null && rel.actor === userId\n lines.push([\n 'Live',\n `release #${rel.seq} (${rel.kind} of ${rel.commitOid?.slice(0, 10) ?? 'unknown source'}, ${timeAgo(rel.createdAt)}${byYou ? ', by you' : ''})` +\n (rel.url ? ` · ${rel.url}` : ''),\n ])\n json.live = {\n seq: rel.seq,\n kind: rel.kind,\n commitOid: rel.commitOid,\n createdAt: rel.createdAt,\n url: rel.url,\n byYou,\n }\n }\n }\n spinner?.stop('Cloud state checked.')\n }\n }\n\n if (args.json) {\n console.log(JSON.stringify(json))\n return\n }\n const width = Math.max(...lines.map(([k]) => k.length))\n for (const [k, v] of lines) p.log.message(`${k.padEnd(width)} ${v}`)\n },\n})\n","/**\n * `deepspace push` — sync local git history to the app's cloud repo.\n *\n * The cloud repo is the platform-native remote every DeepSpace app gets,\n * keyed by its immutable app id: collaborators pull/clone from it without\n * GitHub, and deploys link releases to its commits.\n * Local work stays plain `git` — this command only moves committed history,\n * and the transfer itself IS `git push` (the wrapper adds app resolution,\n * auth injection, and machine-readable output).\n *\n * Fast-forward only by default (like git). `deepspace push --force` is GUARDED\n * (see run()): it refuses a force that would orphan a peer's committed work. That\n * guard is CLIENT-SIDE, though — a plain `git push --force space` through the\n * installed credential helper bypasses it, and the server ref-CAS does NOT reject\n * a force (git relearns the advertised old-oid). Fully preventing a force-clobber\n * would require server-side enforcement in the deploy worker.\n */\n\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { findAppDir } from '../lib/app-context'\nimport { resolveAppTarget, warnIfPhantomApp, assertAppTargetResolvable } from '../lib/app-target'\nimport {\n assertSyncableRepo,\n currentBranch,\n isAncestor,\n isPlausibleBranchName,\n listWorktrees,\n resolveCommit,\n updateRef,\n} from '../lib/git/repository'\nimport { SECRET_IN_HISTORY_CODE, trackedSecretFiles } from '../lib/git/safety'\nimport { workspaceIdFromBranch } from '../lib/workspace-id'\nimport { shQuote } from '../lib/cli-format'\nimport {\n classifyPushTransportFailure,\n isRecoverablePushFailure,\n OVERSIZED_PUSH_RE,\n oversizedPushFix,\n pushToSpace,\n} from '../lib/vc-push'\nimport { deployBaseUrl, ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../lib/vc-remote'\nimport { createSpinner } from '../lib/spinner'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport type { CliAction } from '../lib/output'\n\nfunction pullRecoveryAction(cwd: string, appId: string, branch: string): CliAction {\n return {\n cwd,\n argv: ['deepspace', 'pull', '--app', appId, '--branch', branch],\n }\n}\n\nfunction selectedBranchCheckout(appDir: string, branch: string): string | null {\n if (currentBranch(appDir) === branch) return appDir\n return listWorktrees(appDir).find((worktree) => worktree.branch === branch)?.path ?? null\n}\n\n/**\n * Whether a `--force` push of `tipOid` onto a branch would ORPHAN work — i.e.\n * drop commits that only the current remote tip holds. Refuse (true) unless the\n * force is safe: the remote tip is unset (first publish), equals the tip (up to\n * date), equals our own last-pushed record (a rewrite of our OWN line — the\n * legitimate reason to force), or is already CONTAINED in the tip (a normal\n * advance / we integrated it). Any other remote tip = a peer advanced the\n * branch to commits we lack, so forcing would silently lose their work. Pure —\n * the ancestry test (`tipContainsRemoteTip`) is injected so this is\n * unit-testable.\n */\nexport function forcePushOrphansWork(\n lastPushed: string | null,\n remoteTip: string | null,\n tipOid: string,\n tipContainsRemoteTip: boolean,\n): boolean {\n if (remoteTip === null) return false // no remote line yet — first publish\n if (remoteTip === tipOid) return false // already up to date\n if (remoteTip === lastPushed) return false // rewrite of our own line (no peer advance)\n return !tipContainsRemoteTip // else safe only if the tip already contains it\n}\n\n/** A `ws/<id>` branch is a workspace line: a plain push writes the visible\n * `refs/heads/ws/<id>` while `workspace sync` publishes the hidden coordination\n * ref AND records metadata. Pushing here looks successful yet leaves the\n * workspace tip, overlap warnings, and activity stale — so refuse and send the\n * agent to sync. Null on any ordinary branch (no behavior change). Pure +\n * exported for tests. */\nexport function workspaceBranchPushRefusal(\n branch: string | null,\n): { code: 'workspace_branch'; error: string } | null {\n const id = workspaceIdFromBranch(branch)\n if (!id) return null\n return {\n code: 'workspace_branch',\n error:\n `\"${branch}\" is a workspace branch (${id}). A plain push moves only the visible ref and ` +\n `bypasses workspace coordination — the workspace tip, overlap warnings, and activity would go ` +\n `stale. Publish it with \\`deepspace workspace sync\\` instead.`,\n }\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'push',\n description: \"Push local git commits to the app's cloud repo\",\n },\n args: {\n branch: {\n type: 'string',\n alias: 'b',\n description: 'Branch to push (default: the current branch)',\n required: false,\n },\n app: {\n type: 'string',\n alias: 'a',\n description:\n 'App id or subdomain name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n force: {\n type: 'boolean',\n description:\n 'Allow a non-fast-forward ref move to rewrite history you previously pushed with `deepspace push`. Guarded: refuses whenever the remote tip is a commit your branch does not contain, so no work is silently dropped (a first force from a fresh clone/pull is refused until you re-integrate that tip).',\n default: false,\n },\n },\n async run({ args }) {\n const branchArg = args.branch === undefined ? undefined : String(args.branch)\n const appArg = typeof args.app === 'string' ? args.app : undefined\n const force = args.force === true\n try {\n const appDir = findAppDir()\n if (!appDir)\n throw new Refusal(\n 'No wrangler.toml found — run from inside an app directory.',\n 'not_in_app_repo',\n )\n\n assertSyncableRepo(appDir)\n // An explicitly-blank --branch must not silently fall back to the current\n // branch (an unset `--branch \"$VAR\"` would push the wrong ref).\n if (branchArg !== undefined) {\n const b = branchArg.trim()\n if (!b) throw new Refusal('--branch was given an empty branch name.', 'invalid_branch')\n if (!isPlausibleBranchName(b))\n throw new Refusal(`--branch \"${b}\" is not a valid git branch name.`, 'invalid_branch')\n }\n const branch = branchArg?.trim() || currentBranch(appDir)\n if (!branch) {\n throw new Refusal(\n 'HEAD is detached — pass --branch <name> to choose what to push.',\n 'detached_head',\n )\n }\n const tipOid = resolveCommit(appDir, `refs/heads/${branch}`)\n if (!tipOid) {\n // refs/heads/<branch> doesn't resolve. If the repo HAS commits (HEAD\n // resolves), the branch simply doesn't exist — a typo'd -b, not an empty\n // repo. \"commit first\" is wrong advice there (committing on the current\n // branch never makes the missing ref appear — an agent would loop), so\n // give it a distinct code + remedy. Reserve no_commits for a genuinely\n // unborn repo (no HEAD at all).\n if (resolveCommit(appDir, 'HEAD')) {\n throw new Refusal(\n `Branch \"${branch}\" does not exist — create or switch to it first (e.g. git switch -c ${shQuote(branch)}), then push.`,\n 'unknown_branch',\n )\n }\n throw new Refusal(\n `Branch \"${branch}\" has no commits yet — commit first, then push.`,\n 'no_commits',\n )\n }\n\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Checking ${branch} before push…`)\n const resolveTarget = async (): Promise<{ token: string; appId: string }> => {\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const token = await ensureToken()\n // Accepts an id OR a subdomain name — a raw name must never pass\n // through as a literal app id (it would register a phantom app).\n const appId = await resolveAppTarget(deployBaseUrl(), token, appArg)\n await warnIfPhantomApp(deployBaseUrl(), token, appId, appArg?.trim() || undefined)\n return { token, appId }\n }\n\n // A workspace branch must go through `workspace sync`, not a plain push.\n // Resolve the target before emitting the continuation so a name or local\n // default cannot drift to another app when an agent executes it later.\n const wsRefusal = workspaceBranchPushRefusal(branch)\n if (wsRefusal) {\n const { appId } = await resolveTarget()\n const checkoutPath = selectedBranchCheckout(appDir, branch)\n const workspaceId = workspaceIdFromBranch(branch)\n if (!workspaceId) throw new Error(`Workspace branch did not contain an id: ${branch}`)\n const syncCommand =\n `deepspace workspace sync --app ${shQuote(appId)} ` +\n `--workspace ${shQuote(workspaceId)}`\n const quotedSyncCommand = `\\`${syncCommand}\\``\n const message = checkoutPath\n ? `${wsRefusal.error} Run ${quotedSyncCommand} from its checkout at ${checkoutPath}.`\n : `${wsRefusal.error} ${branch} exists locally but is not checked out. Check it out in a clean worktree, then run ${quotedSyncCommand}.`\n const action: CliAction | undefined = checkoutPath\n ? {\n cwd: checkoutPath,\n argv: ['deepspace', 'workspace', 'sync', '--app', appId, '--workspace', workspaceId],\n }\n : undefined\n spinner?.stop('Workspace branch.')\n throw new Refusal(message, wsRefusal.code, {\n actionRequired: action !== undefined,\n action,\n extra: { appId, branch, ...(checkoutPath ? { worktreePath: checkoutPath } : {}) },\n })\n }\n\n // Push IS `git push`, so it sends whatever was committed — including a\n // force-committed `.dev.vars` that .gitignore would normally keep out.\n // The push wrapper refuses them early; the server independently enforces\n // the same case-insensitive basename contract for raw Git clients.\n const secretFiles = trackedSecretFiles(appDir, tipOid)\n if (secretFiles.length > 0) {\n const checkoutPath = selectedBranchCheckout(appDir, branch)\n const checkoutNote = checkoutPath\n ? ''\n : ` Check out ${shQuote(branch)} in a clean worktree before untracking it.`\n throw new Refusal(\n `Refusing to push: the branch tracks secret file(s) — ${secretFiles.join(', ')}. ` +\n `These hold local secrets and must not reach the cloud repo. Untrack with ` +\n `\\`git rm --cached ${shQuote(secretFiles[0])}\\`, ensure it's .gitignored, commit, then push.` +\n checkoutNote,\n SECRET_IN_HISTORY_CODE,\n {\n action: checkoutPath\n ? { cwd: checkoutPath, argv: ['git', 'rm', '--cached', secretFiles[0]] }\n : undefined,\n extra: { branch, ...(checkoutPath ? { worktreePath: checkoutPath } : {}) },\n },\n )\n }\n\n const { token, appId } = await resolveTarget()\n const pullRecoveryCwd = selectedBranchCheckout(appDir, branch) ?? appDir\n ensureSpaceRemote(appDir, appId)\n\n // A `--force` push moves the ref non-fast-forward. That's legitimate for\n // rewriting YOUR OWN line (amend/rebase), but it must NOT silently drop a\n // peer's commits that landed on the cloud branch since you last synced —\n // the orphan protection this file's header describes for `deepspace push\n // --force` (a plain `git push --force` is out of our reach — see header).\n // Two ingredients:\n // 1. lastPushed = a PRIVATE ref (refs/deepspace/pushed/<branch>) that ONLY\n // our own successful push writes (see below). The obvious candidate,\n // refs/remotes/space/<branch>, is force-advanced by `deepspace pull`,\n // deploy, workspace fetches, and a bare `git fetch space` — so using it\n // would let the pull-then-retry flow the refusal itself recommends\n // poison the baseline and wave a clobber through. The workspace path is\n // safe for exactly this reason: its hidden ref moves only on its own\n // successful push.\n // 2. the current remote tip, fetched into FETCH_HEAD with `--refmap=` so\n // this guard's own fetch can't advance the tracking ref either.\n // Refuse if force-pushing would orphan the peer's work.\n if (force) {\n spinner?.message(`Checking the cloud ${branch} tip before force-push…`)\n const lastPushed = resolveCommit(appDir, `refs/deepspace/pushed/${branch}`)\n let remoteTip: string | null = null\n try {\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n '--refmap=',\n SPACE_REMOTE,\n `refs/heads/${branch}`,\n ])\n remoteTip = resolveCommit(appDir, 'FETCH_HEAD')\n } catch {\n // The fetch failed. We must NOT fall through to a blind force — that\n // would silently orphan a peer who'd advanced the branch. Disambiguate\n // with ls-remote: an absent branch (exit 0, empty) is a first-touch\n // force (nothing to orphan, safe); anything else (a non-zero status, or\n // an advertised tip we couldn't fetch) means we can't verify the tip, so\n // refuse — fail CLOSED.\n const ls = runGitRemote(\n appDir,\n token,\n ['ls-remote', SPACE_REMOTE, `refs/heads/${branch}`],\n {\n allowFail: true,\n },\n )\n if (ls.status === 0 && ls.stdout.toString('utf-8').trim() === '') {\n remoteTip = null // no such remote branch yet — first push, safe to force\n } else {\n const error =\n `Couldn't reach the cloud repo to check ${branch} before force-pushing. ` +\n `Refusing --force so it can't silently drop a peer's commits — retry when connected, ` +\n `or run \\`deepspace pull --app ${shQuote(appId)} --branch ${shQuote(branch)}\\` ` +\n `to integrate first.`\n // No `Next:`/`next`: the fix is \"retry when connected\" (not a single\n // command), and `deepspace pull` needs the very connectivity that just\n // failed — so naming it would loop an agent.\n // Plain failure (exit 1): NOTHING worked and no local step\n // remains — actionRequired/exit-2 is reserved for \"the operation\n // succeeded, now it's your turn\", which this is not.\n throw new Refusal(error, 'force_unverified', { extra: { appId, branch } })\n }\n }\n if (\n remoteTip &&\n forcePushOrphansWork(lastPushed, remoteTip, tipOid, isAncestor(appDir, remoteTip, tipOid))\n ) {\n const error =\n `The cloud repo's ${branch} advanced since you last synced — a peer pushed commit(s) you don't have. ` +\n `Force-pushing now would DROP that work. Run ` +\n `\\`deepspace pull --app ${shQuote(appId)} --branch ${shQuote(branch)}\\` and merge ` +\n `(or rebase onto it), then push.`\n throw new Refusal(error, 'diverged', {\n actionRequired: true,\n action: pullRecoveryAction(pullRecoveryCwd, appId, branch),\n extra: { appId, branch },\n })\n }\n }\n\n spinner?.message(`Pushing ${branch} to the cloud repo…`)\n const result = pushToSpace(appDir, token, `refs/heads/${branch}:refs/heads/${branch}`, {\n force,\n })\n spinner?.stop(\n result.status === 'up_to_date'\n ? `${branch} is already up to date at ${tipOid.slice(0, 10)}.`\n : result.status === 'committed'\n ? `Pushed ${branch} → ${tipOid.slice(0, 10)}.`\n : `Push did not complete.`,\n )\n\n const ok = result.status === 'up_to_date' || result.status === 'committed'\n if (ok) {\n // Record what THIS client just published, in a PRIVATE ref that only our\n // own successful push writes — the \"last pushed by me\" baseline the\n // --force orphan guard above reads. A bare `git fetch` / `deepspace pull`\n // never advances it (unlike refs/remotes/space/<branch>), so the guard\n // can't be poisoned into misreading a peer's tip as our own line.\n updateRef(appDir, `refs/deepspace/pushed/${branch}`, tipOid)\n }\n // A moved/diverged ref is a recovery state, not a dead end: nothing was\n // pushed, and `deepspace pull` is the one re-entry command. Carry that as\n // structured fields so an agent doesn't have to scrape the prose (a\n // server-side `rejected` — oversize, policy — is NOT self-recoverable).\n const recoverable = isRecoverablePushFailure(result.status)\n const rejectReason = result.reason ?? result.summary\n const errorMsg = ok\n ? null\n : result.status === 'ref_conflict'\n ? `The cloud repo's ${branch} moved while you worked (${rejectReason}). ` +\n `Run \\`deepspace pull --app ${shQuote(appId)} --branch ${shQuote(branch)}\\` ` +\n `to integrate, then push again.`\n : result.status === 'rejected'\n ? `The cloud repo rejected ${branch}: ${rejectReason}.` +\n (OVERSIZED_PUSH_RE.test(rejectReason) ? ` ${oversizedPushFix(appDir)}` : '')\n : `The cloud repo's ${branch} has commit(s) your local ${branch} doesn't. ` +\n `Run \\`deepspace pull --app ${shQuote(appId)} --branch ${shQuote(branch)}\\` ` +\n `and merge (or rebase), then push. Avoid --force here — it's guarded and ` +\n `will refuse rather than silently drop a peer's commits.`\n\n // Completeness: `appId` is the one --json fact the spinner line doesn't\n // already carry (branch + oid are in it), so the human surface names it too.\n if (!args.json && ok) p.log.info(`App: ${appId}`)\n // A push that landed is terminal — whether to deploy or open a workspace is\n // the agent's call, and a `Next:` there would be filler. Only the recoverable\n // divergence has one true follow-up.\n const action = recoverable ? pullRecoveryAction(pullRecoveryCwd, appId, branch) : undefined\n // A recoverable divergence (non_fast_forward / ref_conflict) is the\n // action-required tier — it already carries `actionRequired:true` + a\n // `action` above, so exit 2 like `push --force` diverged / `pull` diverged /\n // `workspace land` dirty. A non-recoverable rejection (oversize, policy)\n // stays an ordinary exit 1.\n if (!ok) {\n throw new Refusal(errorMsg ?? `Push did not complete.`, result.status, {\n actionRequired: recoverable,\n action,\n extra: { status: result.status, appId, branch, oid: tipOid },\n })\n }\n return { data: { status: result.status, appId, branch, oid: tipOid } }\n } catch (err) {\n if (err instanceof Refusal) throw err\n const transportFailure = classifyPushTransportFailure(err)\n if (transportFailure) {\n throw new Refusal(transportFailure.error, transportFailure.code)\n }\n throw err\n }\n },\n})\n","/**\n * `deepspace pull` — bring cloud-repo history into the local git repo.\n *\n * A real `git fetch` moves what's missing into `.git/objects` and updates\n * the tracking ref (`refs/remotes/space/<branch>`); then integrate\n * conservatively: fast-forward when that's all it takes, otherwise leave the\n * merge to the caller (`git merge refs/remotes/space/<branch>` — the objects\n * are already local, so that merge needs no network). Never touches a dirty\n * worktree.\n */\n\nimport * as p from '@clack/prompts'\nimport { realpathSync } from 'node:fs'\nimport { ensureToken } from '../auth'\nimport { findAppDir } from '../lib/app-context'\nimport { resolveAppTarget, assertAppTargetResolvable } from '../lib/app-target'\nimport {\n assertSyncableRepo,\n checkoutHead,\n currentBranch,\n fastForwardCurrentBranch,\n isAncestor,\n isWorkTreeClean,\n listWorktrees,\n resolveCommit,\n updateRef,\n isPlausibleBranchName,\n} from '../lib/git/repository'\nimport { workspaceIdFromBranch } from '../lib/workspace-id'\nimport { shQuote } from '../lib/cli-format'\nimport { deployBaseUrl, ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../lib/vc-remote'\nimport { repoApi } from '../lib/repo-api'\nimport { createSpinner } from '../lib/spinner'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport type { CliAction } from '../lib/output'\n\ntype Integration =\n | 'up_to_date'\n | 'fast_forwarded'\n | 'branch_created'\n | 'fetched_only_diverged'\n | 'fetched_only_dirty'\n | 'fetched_only_unborn'\n | 'fetched_only_worktree'\n\nfunction targetedVcAction(\n command: 'push' | 'pull',\n cwd: string,\n appId: string,\n branch: string,\n): CliAction {\n return {\n cwd,\n argv: ['deepspace', command, '--app', appId, '--branch', branch],\n }\n}\n\nfunction targetedVcCommand(command: 'push' | 'pull', appId: string, branch: string): string {\n return `deepspace ${command} --app ${shQuote(appId)} --branch ${shQuote(branch)}`\n}\n\n/** A `ws/<id>` branch is a workspace line, not an ordinary branch: trunk does\n * not fast-forward into it — it integrates by MERGE, and the two lines stay\n * distinct until `workspace land`. A plain pull would either bypass that model\n * or fail confusingly, so refuse with the exact manual merge. Null on any\n * ordinary branch (no behavior change). Pure + exported for tests. */\nexport function workspaceBranchPullRefusal(\n branch: string | null,\n trunkBranch: string | null,\n): { code: 'workspace_branch'; trunk: string; error: string } | null {\n const id = workspaceIdFromBranch(branch)\n if (!id) return null\n const trunk = trunkBranch || 'main'\n // Git allows branch names with shell metacharacters ($(), ;, &, spaces); quote\n // the interpolated ref so an agent copy-pasting this \"run this\" line can't\n // shell-expand a collaborator-controlled name. Never a machine contract.\n const merge = `git merge refs/remotes/space/${shQuote(trunk)}`\n return {\n code: 'workspace_branch',\n trunk,\n error:\n `\"${branch}\" is a workspace branch (${id}). Trunk integrates into a workspace by MERGE, not ` +\n `fast-forward — the two lines stay distinct until \\`deepspace workspace land\\`. Bring trunk in ` +\n `with \\`${merge}\\` after it is fetched (then resolve/commit), or land the workspace when it's ready.`,\n }\n}\n\n/** The path of ANOTHER worktree (not `selfPath`) that has `branch` checked out,\n * or null. Pull must not move a branch ref while a linked worktree holds it:\n * that worktree's HEAD would advance while its index and files stay at the old\n * commit, fabricating deletions/modifications. Pure + exported for tests. */\nexport function worktreeHoldingBranch(\n worktrees: { path: string; branch: string | null }[],\n branch: string,\n selfPath: string,\n): string | null {\n const real = (pth: string): string => {\n try {\n return realpathSync(pth)\n } catch {\n return pth\n }\n }\n const self = real(selfPath)\n for (const w of worktrees) {\n if (w.branch === branch && real(w.path) !== self) return w.path\n }\n return null\n}\n\n/**\n * The next-step advice for a diverged pull. `git merge` always merges INTO\n * the checked-out branch. When the selected branch is checked out in ANY\n * worktree, merge there; only an unowned branch needs a checkout first. Pure +\n * exported for tests.\n */\nexport function divergedMergeAdvice(branch: string, hasSelectedCheckout: boolean): string {\n // Shell-quote the interpolated branch — Git permits $(), ;, &, and spaces in\n // branch names, so an unquoted \"run this\" line could mis-parse or expand a\n // collaborator-controlled name. Human rendering only, never a machine contract.\n const b = shQuote(branch)\n return hasSelectedCheckout\n ? `git merge refs/remotes/space/${b}`\n : `git checkout ${b} && git merge refs/remotes/space/${b}`\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'pull',\n description:\n \"Fetch the app's cloud repo and fast-forward the local branch \" +\n '(exit 2 only when one executable local continuation remains)',\n },\n args: {\n branch: {\n type: 'string',\n alias: 'b',\n description: 'Branch to pull (default: the current branch)',\n required: false,\n },\n app: {\n type: 'string',\n alias: 'a',\n description:\n 'App id or subdomain name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n },\n async run({ args }) {\n const branchArg = args.branch === undefined ? undefined : String(args.branch)\n const appArg = typeof args.app === 'string' ? args.app : undefined\n const appDir = findAppDir()\n if (!appDir)\n throw new Refusal(\n 'No wrangler.toml found — run from inside an app directory.',\n 'not_in_app_repo',\n )\n\n // An explicitly-blank --branch must not silently fall back to the current\n // branch (an unset `--branch \"$VAR\"` would pull the wrong ref). Validate\n // the argument before inspecting repository state so a shallow checkout\n // cannot mask this pre-repository input error.\n if (branchArg !== undefined) {\n const b = branchArg.trim()\n if (!b) throw new Refusal('--branch was given an empty branch name.', 'invalid_branch')\n if (!isPlausibleBranchName(b))\n throw new Refusal(`--branch \"${b}\" is not a valid git branch name.`, 'invalid_branch')\n }\n assertSyncableRepo(appDir)\n const branch = branchArg?.trim() || currentBranch(appDir)\n if (!branch)\n throw new Refusal(\n 'HEAD is detached — pass --branch <name> to choose what to pull.',\n 'detached_head',\n )\n const refName = `refs/heads/${branch}`\n const selectedBranchCheckout = (): { onCurrent: boolean; path: string | null } => {\n const onCurrent = currentBranch(appDir) === branch\n return {\n onCurrent,\n path: onCurrent ? appDir : worktreeHoldingBranch(listWorktrees(appDir), branch, appDir),\n }\n }\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Preparing to pull ${branch}…`)\n\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const token = await ensureToken()\n const deployUrl = deployBaseUrl()\n const appId = await resolveAppTarget(deployUrl, token, appArg)\n ensureSpaceRemote(appDir, appId)\n\n // JSON refs first: \"no repo\" and \"no such branch\" get actionable\n // messages instead of git's couldn't-find-remote-ref stderr.\n spinner?.message(`Checking the cloud ${branch} ref…`)\n const remote = await repoApi(deployUrl, token, appId).getRefs()\n if (!remote) {\n spinner?.stop('No cloud repo yet.')\n const pushCommand = targetedVcCommand('push', appId, branch)\n throw new Refusal(\n `This app has no cloud repo yet — run \\`${pushCommand}\\` from the repo that has the history.`,\n 'no_cloud_repo',\n { action: targetedVcAction('push', appDir, appId, branch) },\n )\n }\n\n // A workspace branch can't be pulled like an ordinary branch — refuse\n // BEFORE the branch-existence check (its visible ref usually doesn't even\n // exist on the cloud repo, which would otherwise print a confusing \"no\n // such branch\"). Exit 2 with the one manual merge to run instead.\n const trunkBranch = remote.head?.startsWith('refs/heads/')\n ? remote.head.slice('refs/heads/'.length)\n : null\n const wsRefusal = workspaceBranchPullRefusal(branch, trunkBranch)\n if (wsRefusal) {\n const trunkRef = `refs/heads/${wsRefusal.trunk}`\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+${trunkRef}:refs/remotes/space/${wsRefusal.trunk}`,\n ])\n spinner?.stop('Workspace branch.')\n const { path: branchWorktreePath } = selectedBranchCheckout()\n const workspaceId = workspaceIdFromBranch(branch)\n if (!workspaceId) throw new Error(`Workspace branch did not contain an id: ${branch}`)\n const pullCommand = targetedVcCommand('pull', appId, branch)\n const localBranchExists = resolveCommit(appDir, refName) !== null\n const selectedCheckoutClean =\n branchWorktreePath !== null && isWorkTreeClean(branchWorktreePath)\n const canCheckoutHere =\n branchWorktreePath === null && localBranchExists && isWorkTreeClean(appDir)\n const step = branchWorktreePath\n ? selectedCheckoutClean\n ? `Merge the fetched trunk in the checkout that owns ${branch} (${branchWorktreePath}).`\n : `The checkout that owns ${branch} (${branchWorktreePath}) is dirty. Commit or stash there, then rerun \\`${pullCommand}\\` from that checkout.`\n : localBranchExists\n ? canCheckoutHere\n ? `The branch is not checked out. Check it out here, then rerun \\`${pullCommand}\\` to receive the merge step.`\n : `The branch is not checked out and this checkout is dirty. Commit or stash first (or use a clean worktree), check out ${shQuote(branch)}, then rerun \\`${pullCommand}\\`.`\n : `This clone has not attached the workspace. Attach ${workspaceId}, then rerun \\`${pullCommand}\\` from its checkout.`\n const action: CliAction | undefined =\n branchWorktreePath && selectedCheckoutClean\n ? {\n cwd: branchWorktreePath,\n argv: ['git', 'merge', `refs/remotes/space/${wsRefusal.trunk}`],\n }\n : canCheckoutHere\n ? { cwd: appDir, argv: ['git', 'checkout', branch] }\n : !localBranchExists\n ? {\n cwd: appDir,\n argv: ['deepspace', 'workspace', 'attach', workspaceId, '--app', appId],\n }\n : undefined\n throw new Refusal(`${wsRefusal.error} ${step}`, wsRefusal.code, {\n actionRequired: action !== undefined,\n action,\n extra: {\n appId,\n branch,\n ...(branchWorktreePath ? { worktreePath: branchWorktreePath } : {}),\n },\n })\n }\n\n if (!remote.refs.some((r) => r.name === refName)) {\n spinner?.stop('Branch not found.')\n const branches = remote.refs\n .filter((r) => r.name.startsWith('refs/heads/'))\n .map((r) => r.name.slice('refs/heads/'.length))\n throw new Refusal(\n `The cloud repo has no branch \"${branch}\".` +\n (branches.length ? ` Available: ${branches.join(', ')}.` : ' It is empty — push first.'),\n 'branch_not_found',\n )\n }\n\n // Real git does the transfer; `+` force-updates the tracking ref (a\n // remote-tracking ref always mirrors the remote, rewrites included).\n spinner?.message(`Fetching ${branch} from the cloud repo…`)\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+${refName}:refs/remotes/space/${branch}`,\n ])\n const remoteOid = resolveCommit(appDir, `refs/remotes/space/${branch}`)\n if (!remoteOid) {\n spinner?.stop('Fetch failed.')\n throw new Refusal(\n `Fetched, but refs/remotes/space/${branch} did not materialize — retry; if it persists, report it with \\`deepspace feedback\\`.`,\n 'fetch_incomplete',\n )\n }\n\n // Integrate — conservatively.\n // Resolve the owner immediately after fetch, before BOTH fast-forward and\n // divergence handling, so the action reflects the live worktree layout.\n const { onCurrent, path: branchWorktreePath } = selectedBranchCheckout()\n const localOid = resolveCommit(appDir, refName)\n let integration: Integration\n if (localOid === remoteOid) {\n integration = 'up_to_date'\n } else if (localOid === null) {\n // The branch doesn't exist locally yet. Creating the ref is always\n // safe; materializing the worktree only is when nothing can collide.\n updateRef(appDir, refName, remoteOid)\n if (onCurrent && isWorkTreeClean(appDir)) {\n checkoutHead(appDir)\n integration = 'branch_created'\n } else {\n integration = onCurrent ? 'fetched_only_unborn' : 'branch_created'\n }\n } else if (isAncestor(appDir, localOid, remoteOid)) {\n if (onCurrent) {\n if (!isWorkTreeClean(appDir)) {\n integration = 'fetched_only_dirty'\n } else {\n fastForwardCurrentBranch(appDir, remoteOid)\n integration = 'fast_forwarded'\n }\n } else {\n // Fast-forwarding a NON-current branch writes its ref directly — but\n // if another linked worktree has it checked out, moving the ref\n // desyncs that worktree (its HEAD advances while its index/files stay\n // put, fabricating deletions). Leave the ref alone and send the agent\n // to pull from that worktree instead.\n if (branchWorktreePath) {\n integration = 'fetched_only_worktree'\n } else {\n updateRef(appDir, refName, remoteOid)\n integration = 'fast_forwarded'\n }\n }\n } else {\n integration = 'fetched_only_diverged'\n }\n\n // Render the integration once, exhaustively. Summary, refusal code, and\n // structured action belong to the same outcome branch so they cannot drift.\n const qBranch = shQuote(branch)\n const ffRef = `git merge --ff-only refs/remotes/space/${qBranch}`\n const mergeRef = `git merge refs/remotes/space/${qBranch}`\n const pullCommand = targetedVcCommand('pull', appId, branch)\n const pushCommand = targetedVcCommand('push', appId, branch)\n const selectedCheckoutClean = branchWorktreePath !== null && isWorkTreeClean(branchWorktreePath)\n const canCheckoutHere = branchWorktreePath === null && isWorkTreeClean(appDir)\n let line: string\n let codeForState: string | undefined\n let recoveryAction: CliAction | undefined\n switch (integration) {\n case 'up_to_date':\n line = `${branch} is already up to date.`\n break\n case 'fast_forwarded':\n line = `Fast-forwarded ${branch} to ${remoteOid.slice(0, 10)}.`\n break\n case 'branch_created':\n line = `Created ${branch} at ${remoteOid.slice(0, 10)}.`\n break\n case 'fetched_only_diverged':\n codeForState = 'diverged'\n if (branchWorktreePath && selectedCheckoutClean) {\n const mergeAdvice = divergedMergeAdvice(branch, true)\n line =\n `Fetched space/${branch}. ${branch} and the cloud repo diverged — run ` +\n `\\`${mergeAdvice}\\` in ${branchWorktreePath} (no network needed), then \\`${pushCommand}\\`.`\n recoveryAction = {\n cwd: branchWorktreePath,\n argv: ['git', 'merge', `refs/remotes/space/${branch}`],\n }\n } else if (branchWorktreePath) {\n line =\n `Fetched space/${branch}. ${branch} and the cloud repo diverged, but its checkout ` +\n `(${branchWorktreePath}) is dirty. Commit or stash there, then rerun ` +\n `\\`${pullCommand}\\` from that checkout.`\n } else if (canCheckoutHere) {\n line =\n `Fetched space/${branch}. ${branch} and the cloud repo diverged, but ${branch} is ` +\n `not checked out. Check it out here, then rerun \\`${pullCommand}\\` to receive the merge step.`\n recoveryAction = { cwd: appDir, argv: ['git', 'checkout', branch] }\n } else {\n line =\n `Fetched space/${branch}. ${branch} and the cloud repo diverged, but ${branch} is ` +\n `not checked out and this checkout is dirty. Commit or stash first (or use a clean ` +\n `worktree), check out ${qBranch}, then rerun \\`${pullCommand}\\`.`\n }\n break\n case 'fetched_only_dirty':\n codeForState = 'dirty_worktree'\n // A commit diverges the branch, while a stash preserves fast-forward.\n line =\n `Fetched space/${branch}, but the worktree is dirty. Either stash → \\`${ffRef}\\` → ` +\n `\\`git stash pop\\`, or commit first → \\`${mergeRef}\\` (or \\`git rebase\\`).`\n break\n case 'fetched_only_unborn':\n codeForState = 'dirty_worktree'\n line =\n `Fetched space/${branch} and created ${branch}, but the worktree has uncommitted files. ` +\n `Preserve them in a commit or stash (including untracked files), then restore the checkout; ` +\n `do not run reset --hard until \\`git status\\` confirms nothing worth keeping remains.`\n break\n case 'fetched_only_worktree':\n codeForState = 'branch_in_worktree'\n if (branchWorktreePath && selectedCheckoutClean) {\n line =\n `Fetched space/${branch}, but ${branch} is checked out in another worktree ` +\n `(${branchWorktreePath}) — its ref was left untouched to keep that worktree in sync. ` +\n `Run \\`${pullCommand}\\` from there.`\n recoveryAction = targetedVcAction('pull', branchWorktreePath, appId, branch)\n } else {\n line =\n `Fetched space/${branch}, but its checkout ` +\n `(${branchWorktreePath ?? 'a linked worktree'}) is dirty, so the ref and worktree were ` +\n `left untouched. Commit or stash there, then run \\`${pullCommand}\\` from that checkout.`\n }\n break\n default: {\n const exhaustive: never = integration\n throw new Error(`Unhandled pull integration: ${exhaustive}`)\n }\n }\n // Exit 2 is reserved for a single executable continuation. Dirty or\n // unavailable checkout states require judgment and remain ordinary,\n // actionless refusals even though the fetch itself succeeded.\n const actionRequired = recoveryAction !== undefined\n spinner?.stop(codeForState ? `Fetched space/${branch}.` : line)\n // Completeness: appId and the fetched remote oid are --json facts the\n // summary line doesn't always carry — say them in the text too.\n if (!args.json) p.log.info(`App: ${appId} · space/${branch} at ${remoteOid.slice(0, 10)}`)\n if (codeForState) {\n // Every blocked integration is ok:false. Only one with an executable\n // continuation adds actionRequired and exits 2; judgment states exit 1.\n throw new Refusal(line, codeForState, {\n actionRequired,\n action: recoveryAction,\n extra: {\n status: integration,\n ...(branchWorktreePath ? { worktreePath: branchWorktreePath } : {}),\n appId,\n branch,\n remoteOid,\n },\n })\n }\n return { data: { status: integration, appId, branch, remoteOid } }\n },\n})\n","/**\n * `deepspace clone <app> [dir]` — materialize an app's cloud repo locally.\n *\n * The collaborator on-ramp with no GitHub in the loop: resolve the app (id\n * or subdomain name), then let REAL git clone the platform's smart-HTTP\n * remote — full history, all branches, default branch checked out. The\n * remote comes out named `space` and the credential helper is configured,\n * so plain `git push space` / `git fetch space` work from here on. The\n * clone is deploy-ready because identity travels in the repo itself\n * (wrangler.toml carries DEEPSPACE_APP_ID); secrets come separately via\n * `deepspace secrets pull`.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport * as p from '@clack/prompts'\nimport { existsSync, readdirSync, rmSync } from 'node:fs'\nimport { resolve, basename, join } from 'node:path'\nimport { ensureToken } from '../auth'\nimport { resolveAppSelector, assertAppTargetResolvable } from '../lib/app-target'\nimport { currentBranch, resolveCommit } from '../lib/git/repository'\nimport {\n deployBaseUrl,\n ensureSpaceRemote,\n repoUrl,\n runGitRemote,\n SPACE_REMOTE,\n} from '../lib/vc-remote'\nimport { repoApi } from '../lib/repo-api'\nimport { createSpinner } from '../lib/spinner'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport { detectPackageManager } from '../lib/package-manager'\n\n/**\n * Tidy a PRE-EXISTING target dir after a failed clone. git removes a clone\n * target it CREATED, but a dir that already existed keeps whatever partial\n * content the failure left. The caller verified the dir was empty right\n * before cloning, so a leftover that is ONLY `.git` is unambiguously the\n * failed transfer's debris — remove it. Anything else (a partial checkout, a\n * concurrent writer) is left alone: never delete content we didn't watch git\n * create. Returns what remains (empty when the dir is clean again). Pure fs\n * + exported for tests.\n */\nexport function cleanFailedCloneDir(dir: string): string[] {\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n return existsSync(dir) ? ['<unreadable>'] : []\n }\n if (entries.length === 1 && entries[0] === '.git') {\n try {\n rmSync(join(dir, '.git'), { recursive: true, force: true })\n return []\n } catch {\n return entries\n }\n }\n return entries\n}\n\n/** Validate the target before authentication or network work. */\nexport function validateCloneTarget(dir: string): boolean {\n if (!existsSync(dir)) return false\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOTDIR') {\n throw new Refusal(`${dir} already exists and is not a directory.`, 'dir_exists')\n }\n throw new Refusal(`${dir} already exists but could not be read.`, 'dir_unreadable')\n }\n if (entries.length > 0) {\n throw new Refusal(`${dir} already exists and is not empty.`, 'dir_exists')\n }\n return true\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'clone',\n description: \"Clone an app's cloud repo into a new directory\",\n },\n args: {\n app: {\n type: 'positional',\n description: 'App id (app_…) or subdomain name',\n required: true,\n },\n dir: {\n type: 'positional',\n description: 'Target directory (default: the app name you passed)',\n required: false,\n },\n },\n async run({ args }) {\n // A blank app selector is a client-side error — reject it BEFORE the token\n // read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(String(args.app))\n const selector = String(args.app).trim()\n const dir = resolve(String(args.dir ?? selector))\n // Whether the target existed before the clone: git only removes a\n // failed clone's dir when IT created the dir, so a pre-existing (empty)\n // one is ours to tidy on failure.\n const dirPreexisted = validateCloneTarget(dir)\n\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Resolving ${selector}…`)\n const token = await ensureToken()\n const deployUrl = deployBaseUrl()\n const appId = await resolveAppSelector(deployUrl, token, selector)\n\n // Probe the JSON refs first: cloning an unregistered/empty repo would\n // \"succeed\" as an empty checkout — an actionable message beats that.\n spinner?.message(`Checking ${selector}'s cloud repo…`)\n const remote = await repoApi(deployUrl, token, appId).getRefs()\n const branches = (remote?.refs ?? []).filter((r) => r.name.startsWith('refs/heads/'))\n if (!remote || branches.length === 0) {\n spinner?.stop('Nothing to clone.')\n throw new Refusal(\n `${selector} has no cloud repo history yet. Its owner (or their agent) needs to run \\`deepspace push\\` from the app's repo first.`,\n 'no_cloud_repo',\n )\n }\n\n // Real git does the transfer; auth rides in env, never argv.\n spinner?.message(`Cloning ${selector}…`)\n try {\n runGitRemote(process.cwd(), token, [\n 'clone',\n '--quiet',\n '--origin',\n SPACE_REMOTE,\n repoUrl(appId),\n dir,\n ])\n } catch (err) {\n // A failed clone into a dir the user pre-created leaves the partial\n // transfer behind (git only cleans dirs it made). Reap the\n // unambiguous debris; report anything left.\n if (dirPreexisted) {\n const leftovers = cleanFailedCloneDir(dir)\n if (leftovers.length > 0 && !args.json) {\n process.stderr.write(\n `note: the failed clone left files in ${dir}: ${leftovers.join(', ')}\\n`,\n )\n }\n }\n // Rethrown as-is: the runtime keeps the machine code (a GitError slug,\n // not_authenticated, an ApiError slug) so a --json caller can branch on it.\n throw err\n }\n // The remote URL is already right — this installs the credential\n // helper so bare git works in this clone from now on.\n ensureSpaceRemote(dir, appId)\n\n const head = resolveCommit(dir, 'HEAD')\n const branch = currentBranch(dir)\n spinner?.stop(\n `Cloned ${selector} (${branches.length} ${branches.length === 1 ? 'branch' : 'branches'}) into ${basename(dir)}/ at ${head?.slice(0, 10) ?? '(unborn)'}.`,\n )\n\n if (!args.json && !branch) {\n p.log.warn('HEAD is detached — check `git branch -a`.')\n }\n return {\n data: {\n appId,\n dir,\n head,\n branch,\n remoteBranches: branches.map((r) => r.name.replace(/^refs\\/heads\\//, '')),\n },\n // One runnable follow-up instead of the old five-line \"Next steps\" block:\n // nothing else in the clone works until the deps are installed. Secrets\n // (`deepspace secrets pull`) and `dev` follow from there.\n action: { cwd: dir, argv: [detectPackageManager(dir), 'install'] },\n }\n },\n})\n","/**\n * `deepspace releases` — the app's immutable deploy history.\n *\n * Every deploy (and rollback) records a release: who shipped it, when, the\n * commit it was built from, and the retained bundle rollback re-ships. What\n * `deepspace rollback` reads its targets from.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { resolveAppTarget, assertAppTargetResolvable } from '../lib/app-target'\nimport { repoApi } from '../lib/repo-api'\nimport { parseLimitArg } from '../lib/citty-args'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport { createSpinner } from '../lib/spinner'\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'releases',\n description: \"List the app's deploy history (immutable releases)\",\n },\n args: {\n app: {\n type: 'string',\n alias: 'a',\n description: 'App id or subdomain name (default: the surrounding app directory)',\n required: false,\n },\n limit: {\n type: 'string',\n description: 'Max entries (default 20)',\n required: false,\n },\n },\n async run({ args }) {\n const appArg = args.app as string | undefined\n const { limit, error: limitError } = parseLimitArg(args.limit)\n if (limitError) throw new Refusal(limitError, 'invalid_limit')\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Loading release history…')\n const token = await ensureToken()\n const appId = await resolveAppTarget(DEPLOY_URL, token, appArg)\n const { releases } = await repoApi(DEPLOY_URL, token, appId).listReleases(limit)\n spinner?.stop(`Loaded ${releases.length} ${releases.length === 1 ? 'release' : 'releases'}.`)\n\n if (!args.json) {\n if (releases.length === 0) {\n p.log.info('No releases yet — the history starts with the next `deepspace deploy`.')\n } else {\n for (const r of releases) {\n const source = r.commitOid ? `commit ${r.commitOid.slice(0, 10)}` : '(no source recorded)'\n const rollback = r.rollbackAvailable ? 'rollback available' : 'rollback unavailable'\n console.log(\n `#${r.seq} ${r.id} ${r.kind.padEnd(8)} ${r.createdAt} ${r.actor} ${source} ${rollback}`,\n )\n }\n p.log.info('Roll back an available release with: deepspace rollback <release-id>')\n }\n }\n // No `next`: a listing is terminal — the follow-up depends on which row you\n // pick, and the human path already names `deepspace rollback <release-id>`.\n return { data: { appId, releases } }\n },\n})\n","/**\n * `deepspace rollback [release-id]` — restore a prior release, instantly.\n *\n * Re-ships the exact bundle that release deployed (retained server-side at\n * deploy time) — no rebuild, no local checkout needed. Secrets stay as they\n * are; only code moves. The rollback itself becomes the newest release, so\n * history is append-only and a rollback can be rolled back.\n *\n * With no argument, targets the release before the current one.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file.\n */\n\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { PLATFORM_URLS } from '../env'\nimport { resolveAppTarget, assertAppTargetResolvable } from '../lib/app-target'\nimport { apiFetch, ApiError } from '../lib/api'\nimport { mintIdempotencyKey, repoApi } from '../lib/repo-api'\nimport { createSpinner } from '../lib/spinner'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\n\nconst REL_ID_RE = /^rel_[0-9A-HJKMNP-TV-Z]{26}$/\n\nexport function unavailableDoGuardRefusal(message: string): Refusal {\n return new Refusal(\n `${message}\\nRetry in a moment, or re-run with --allow-do-deletion to accept the risk.`,\n 'do_guard_unavailable',\n )\n}\n\nconst DEPLOY_URL = process.env.DEEPSPACE_DEPLOY_URL ?? PLATFORM_URLS.deploy\n\n/**\n * Pick the default rollback target (the release before the current one) from\n * the two most-recent releases. Pure + exported for tests: the two rejection\n * states carry stable machine `code`s parallel to the explicit-id `not_found`,\n * so release automation distinguishes empty history from a single-release repo\n * without scraping the prose.\n */\nexport function pickPreviousRelease(\n releases: { id: string }[],\n): { releaseId: string } | { error: string; code: string } {\n if (releases.length === 0) {\n return { error: 'No releases recorded yet — nothing to roll back to.', code: 'no_releases' }\n }\n if (releases.length === 1) {\n return {\n error:\n 'Only one release exists — nothing earlier to roll back to. Pass an explicit release id once more history accrues.',\n code: 'no_previous_release',\n }\n }\n return { releaseId: releases[1].id }\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'rollback',\n description: \"Re-deploy a prior release's exact bundle (no rebuild)\",\n },\n args: {\n release: {\n type: 'positional',\n description: 'Release id (rel_…) from `deepspace releases` (default: the previous release)',\n required: false,\n },\n app: {\n type: 'string',\n alias: 'a',\n description: 'App id or subdomain name (default: the surrounding app directory)',\n required: false,\n },\n 'allow-do-deletion': {\n type: 'boolean',\n description:\n 'Proceed even though the target release declares fewer Durable Object classes than ' +\n 'the current one — THEIR STORED DATA IS DELETED.',\n default: false,\n },\n },\n async run({ args }) {\n const appArg = args.app as string | undefined\n // An explicitly-blank release id must not silently auto-pick the previous\n // release (a mutating op) — an unset `rollback \"$VAR\"` would roll back to an\n // unintended target. Absent (no positional) still auto-picks by design.\n if (args.release !== undefined) {\n const r = String(args.release).trim()\n if (!r) {\n throw new Refusal(\n '--release was given an empty release id — pass a rel_… id, or omit it to roll back to the previous release.',\n 'invalid_release',\n )\n }\n if (!REL_ID_RE.test(r)) {\n throw new Refusal(`Invalid release id: ${r} (expected rel_<ULID>).`, 'invalid_release')\n }\n }\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing rollback…')\n const token = await ensureToken()\n const appId = await resolveAppTarget(DEPLOY_URL, token, appArg)\n const api = repoApi(DEPLOY_URL, token, appId)\n\n let releaseId = args.release ? String(args.release).trim() : ''\n if (!releaseId) {\n const { releases } = await api.listReleases(2)\n const picked = pickPreviousRelease(releases)\n if ('error' in picked) throw new Refusal(picked.error, picked.code)\n releaseId = picked.releaseId\n }\n\n spinner?.message(`Rolling back to ${releaseId}…`)\n let result: {\n success: boolean\n url?: string\n versionId?: string\n rolledBackTo?: string\n releaseId?: string\n bundleRetained?: boolean\n // 'unverified' when --allow-do-deletion bypassed the DO-class guard, so\n // the platform did NOT check the rollback against the live DO classes.\n doClassGuard?: string\n }\n try {\n result = await apiFetch(DEPLOY_URL, token, `/api/deploy/${appId}/rollback`, {\n method: 'POST',\n body: JSON.stringify({\n releaseId,\n idempotencyKey: mintIdempotencyKey(),\n ...(args['allow-do-deletion'] ? { allowDoClassDeletion: true } : {}),\n }),\n })\n } catch (err) {\n // Data-loss consent is a user decision, never an executable action.\n if (err instanceof ApiError && err.code === 'do_class_deletion') {\n throw new Refusal(\n `${err.message}\\nRe-run with --allow-do-deletion to accept the data loss.`,\n err.code,\n )\n }\n // Fail-closed guard: the platform couldn't verify which Durable Object\n // classes are live, so it refused rather than risk deleting one's data.\n if (err instanceof ApiError && err.code === 'do_guard_unavailable') {\n throw unavailableDoGuardRefusal(err.message)\n }\n throw err\n }\n if (!result.success) {\n // A 2xx that isn't a well-formed rollback ack — e.g. a wrong/broken service\n // answering 200 {} — must NOT read as a successful (mutating) rollback. Code\n // it like the repo-API shape guard so a --json caller can classify it.\n throw new Refusal(\n 'The deploy service returned an unexpected response to the rollback — check DEEPSPACE_DEPLOY_URL (is this the service the app lives on?).',\n 'invalid_response',\n )\n }\n spinner?.stop(`Rolled back to ${result.rolledBackTo ?? releaseId}.`)\n // Degraded guard: --allow-do-deletion bypassed the DO-class check, so the\n // platform never verified this rollback against the live Durable Object\n // classes. Surface it in both modes — an agent branches on the field.\n const doClassGuard = result.doClassGuard === 'unverified' ? ('unverified' as const) : undefined\n if (!args.json) {\n if (result.url) p.log.success(`Live at: ${result.url}`)\n if (result.bundleRetained === false) {\n p.log.warn(\n 'The rollback is live, but its bundle was concurrently retired and is not available for a future rollback.',\n )\n }\n if (doClassGuard === 'unverified') {\n p.log.warn(\n 'DO-class guard bypassed (--allow-do-deletion): this rollback was NOT checked against the ' +\n \"live Durable Object classes — any class the target doesn't declare has been deleted with its data.\",\n )\n }\n p.log.info(\n 'This rollback is itself the newest release — `deepspace releases` shows the full history.',\n )\n }\n return {\n data: {\n appId,\n rolledBackTo: result.rolledBackTo ?? releaseId,\n newReleaseId: result.releaseId ?? null,\n bundleRetained: result.bundleRetained ?? null,\n url: result.url ?? null,\n versionId: result.versionId ?? null,\n ...(doClassGuard ? { doClassGuard } : {}),\n },\n }\n },\n})\n","/**\n * `deepspace workspace` — durable, named lines of work for parallel agents.\n *\n * Command implementations live beside this registry under `workspace/`.\n */\n\nimport { defineCommand } from 'citty'\nimport { newWorkspaceCommand } from './workspace/new'\nimport { attachWorkspaceCommand } from './workspace/attach'\nimport { syncWorkspaceCommand } from './workspace/sync'\nimport { listWorkspacesCommand } from './workspace/list'\nimport { workspaceStatusCommand } from './workspace/status'\nimport { landWorkspaceCommand } from './workspace/land'\nimport { dropWorkspaceCommand } from './workspace/drop'\n\nexport default defineCommand({\n meta: {\n name: 'workspace',\n description: 'Durable parallel-agent workspaces (new/attach/sync/list/status/land/drop)',\n },\n subCommands: {\n new: newWorkspaceCommand,\n attach: attachWorkspaceCommand,\n sync: syncWorkspaceCommand,\n list: listWorkspacesCommand,\n status: workspaceStatusCommand,\n land: landWorkspaceCommand,\n drop: dropWorkspaceCommand,\n },\n})\n","import * as p from '@clack/prompts'\nimport { isAbsolute, resolve } from 'node:path'\nimport { findAppDir } from '../../lib/app-context'\nimport { mintUlid } from '../../lib/app-identity'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport { resolveCommit } from '../../lib/git/repository'\nimport { workspaceBranchName } from '../../lib/workspace-id'\nimport { ensureSpaceRemote } from '../../lib/vc-remote'\nimport { mintIdempotencyKey } from '../../lib/repo-api'\nimport { createSpinner } from '../../lib/spinner'\nimport { detectPackageManager } from '../../lib/package-manager'\nimport type { CliAction } from '../../lib/output'\nimport { fetchTrunk } from './analysis'\nimport { appDirInWorktree, defaultWorkspaceRoot, materializeWorkspaceWorktree } from './local'\nimport { APP_ARG, resolveTarget } from './runtime'\n\nexport const newWorkspaceCommand = defineDeepspaceCommand({\n meta: { name: 'new', description: 'Create a workspace: server-side ref + local worktree' },\n args: {\n task: {\n type: 'string',\n alias: 't',\n // NOT citty-required: a missing required arg makes citty print human\n // usage text even under --json. Validated in run() for a JSON refusal.\n description: 'What this workspace is for (shown to every collaborator/agent; required)',\n required: false,\n },\n base: {\n type: 'string',\n description: 'Base revision (default: the cloud repo trunk tip)',\n required: false,\n },\n dir: {\n type: 'string',\n description: 'Worktree directory (default: .deepspace/ws/<id>)',\n required: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const task = typeof args.task === 'string' ? args.task.trim() : ''\n if (!task) {\n throw new Refusal(\n 'A workspace needs a task — pass -t \"<what this workspace is for>\" (it is shown to every collaborator and agent).',\n 'invalid_task',\n )\n }\n const baseArg = typeof args.base === 'string' ? args.base.trim() : ''\n // Validate an explicit --base before auth: it is a local input error.\n if (baseArg) {\n const baseDir = findAppDir()\n if (baseDir && !resolveCommit(baseDir, baseArg)) {\n throw new Refusal(\n `--base ${String(args.base)} does not resolve to a local commit.`,\n 'invalid_base',\n )\n }\n }\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing workspace…')\n const { appDir, appId, token, api } = await resolveTarget(\n typeof args.app === 'string' ? args.app : undefined,\n )\n spinner?.message('Creating workspace…')\n ensureSpaceRemote(appDir, appId)\n\n // Prefer the requested revision, then cloud trunk, then local HEAD for an empty cloud repo.\n let baseOid: string | null = null\n const refs = await api.getRefs()\n if (baseArg) {\n baseOid = resolveCommit(appDir, baseArg)\n if (!baseOid) {\n spinner?.stop('Base not found.')\n throw new Refusal(\n `--base ${String(args.base)} does not resolve to a local commit.`,\n 'invalid_base',\n )\n }\n } else {\n const trunk = refs?.head ? refs.refs.find((ref) => ref.name === refs.head) : undefined\n if (trunk) {\n baseOid = trunk.oid\n if (!resolveCommit(appDir, baseOid)) fetchTrunk(appDir, token, refs!.head)\n if (!resolveCommit(appDir, baseOid)) {\n spinner?.stop('Base not fetchable.')\n throw new Refusal(\n `Could not fetch the trunk tip ${baseOid.slice(0, 10)} from the cloud repo. Retry; if it persists, report it with \\`deepspace feedback\\`.`,\n 'fetch_failed',\n )\n }\n } else {\n baseOid = resolveCommit(appDir, 'HEAD')\n if (!baseOid) {\n spinner?.stop('No base.')\n throw new Refusal(\n 'The repo has no commits yet — commit first, then create a workspace.',\n 'no_commits',\n )\n }\n }\n }\n\n const id = `ws_${mintUlid()}`\n const branch = workspaceBranchName(id)\n const { view } = await api.createWorkspace({\n workspaceId: id,\n task,\n baseOid,\n idempotencyKey: mintIdempotencyKey(),\n })\n\n const dirInput = typeof args.dir === 'string' ? args.dir.trim() : ''\n const worktreeRoot = dirInput\n ? isAbsolute(dirInput)\n ? dirInput\n : resolve(appDir, dirInput)\n : defaultWorkspaceRoot(appDir, id)\n const dir = appDirInWorktree(appDir, worktreeRoot)\n try {\n materializeWorkspaceWorktree(appDir, worktreeRoot, branch, baseOid, id)\n } catch (error) {\n spinner?.stop('Worktree failed.')\n const reason = error instanceof Error ? error.message : String(error)\n throw new Refusal(\n `Workspace ${id} was created in the cloud, but the local worktree could not be set up: ${reason} — attach it with \\`deepspace workspace attach ${id} <dir>\\` (or drop it: \\`deepspace workspace drop ${id}\\`).`,\n 'worktree_setup_failed',\n { extra: { workspaceId: id, ref: view.workspace.ref, baseOid } },\n )\n }\n\n spinner?.stop(`Workspace ${id} created.`)\n if (!args.json) {\n p.log.info(`Work in: cd ${dir}`)\n p.log.info(\n `Then: commit as usual, \\`deepspace workspace sync\\` to publish, \\`deepspace workspace land\\` when done.`,\n )\n }\n const action: CliAction = { cwd: dir, argv: [detectPackageManager(dir), 'install'] }\n return {\n data: {\n workspaceId: id,\n appId,\n ref: view.workspace.ref,\n baseOid,\n branch,\n dir,\n worktreeRoot,\n },\n action,\n }\n },\n})\n","import * as p from '@clack/prompts'\nimport { findAppDir } from '../../lib/app-context'\nimport { readAppId } from '../../lib/app-identity'\nimport {\n assertSyncableRepo,\n diffNameOnly,\n isAncestor,\n mergeBase,\n resolveCommit,\n} from '../../lib/git/repository'\nimport type { RemoteRefsResult, RemoteWorkspaceView, RepoApi } from '../../lib/repo-api'\nimport { ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../../lib/vc-remote'\n\nconst MAX_OVERLAP_PATHS = 20\nconst PEER_REF_PREFIX = 'refs/deepspace/peers/'\n\nexport function peerWorkspaceRef(workspaceId: string): string {\n return `${PEER_REF_PREFIX}${workspaceId}`\n}\n\nexport interface WorkspaceOverlap {\n workspaceId: string\n task: string\n paths: string[]\n morePaths: number\n}\n\nexport function formatCount(count: { count: number; capped: boolean } | null): string {\n if (!count) return '?'\n return count.capped ? `${count.count}+` : String(count.count)\n}\n\nexport function fetchTrunk(\n appDir: string,\n token: string,\n head: string | null,\n): { branch: string; ref: string; oid: string } | null {\n if (!head?.startsWith('refs/heads/')) return null\n const branch = head.slice('refs/heads/'.length)\n const remoteRef = `refs/remotes/space/${branch}`\n runGitRemote(appDir, token, ['fetch', '--quiet', SPACE_REMOTE, `+${head}:${remoteRef}`])\n const oid = resolveCommit(appDir, remoteRef)\n return oid ? { branch, ref: remoteRef, oid } : null\n}\n\nexport function localTrunkOid(appDir: string, refs: RemoteRefsResult | null): string | null {\n const head = refs?.head\n if (!head?.startsWith('refs/heads/')) return null\n const advertised = refs?.refs.find((ref) => ref.name === head)?.oid ?? null\n if (advertised && resolveCommit(appDir, advertised)) return advertised\n return resolveCommit(appDir, `refs/remotes/space/${head.slice('refs/heads/'.length)}`)\n}\n\nfunction fetchPeerWorkspaceRefs(appDir: string, token: string): void {\n try {\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n '--prune',\n SPACE_REMOTE,\n `+refs/deepspace/ws/*:${PEER_REF_PREFIX}*`,\n ])\n } catch {\n // Overlap reporting is advisory and can use already-fetched refs offline.\n }\n}\n\nexport function lineChangedPaths(\n appDir: string,\n baseOid: string,\n tipOid: string,\n trunkOid: string | null,\n): { diffBase: string; paths: string[] } | null {\n if (!resolveCommit(appDir, baseOid) || !resolveCommit(appDir, tipOid)) return null\n let diffBase = baseOid\n if (trunkOid && resolveCommit(appDir, trunkOid)) {\n const candidate = mergeBase(appDir, tipOid, trunkOid)\n if (candidate && candidate !== diffBase && isAncestor(appDir, diffBase, candidate)) {\n diffBase = candidate\n }\n }\n return { diffBase, paths: diffNameOnly(appDir, diffBase, tipOid) }\n}\n\nexport function trunkOverlapPaths(\n appDir: string,\n diffBase: string,\n trunkOid: string | null,\n myPaths: string[],\n): string[] {\n if (!trunkOid || trunkOid === diffBase || myPaths.length === 0) return []\n if (!resolveCommit(appDir, trunkOid) || !isAncestor(appDir, diffBase, trunkOid)) return []\n const trunkChanged = new Set(diffNameOnly(appDir, diffBase, trunkOid))\n return myPaths.filter((path) => trunkChanged.has(path))\n}\n\nfunction changedPathsByWorkspace(\n appDir: string,\n views: RemoteWorkspaceView[],\n trunkOid: string | null,\n): Map<string, { task: string; paths: string[] }> {\n const lines = new Map<string, { task: string; paths: string[] }>()\n for (const view of views) {\n const workspace = view.workspace\n if (workspace.status !== 'active') continue\n const tip = resolveCommit(appDir, peerWorkspaceRef(workspace.id)) ?? view.tipOid\n if (!tip) continue\n const line = lineChangedPaths(appDir, workspace.baseOid, tip, trunkOid)\n if (line?.paths.length) lines.set(workspace.id, { task: workspace.task, paths: line.paths })\n }\n return lines\n}\n\nexport function overlapsWith(\n myPaths: string[],\n lines: Map<string, { task: string; paths: string[] }>,\n selfId: string | null,\n): WorkspaceOverlap[] {\n const mine = new Set(myPaths)\n const overlaps: WorkspaceOverlap[] = []\n for (const [workspaceId, line] of lines) {\n if (workspaceId === selfId) continue\n const shared = line.paths.filter((path) => mine.has(path))\n if (!shared.length) continue\n overlaps.push({\n workspaceId,\n task: line.task,\n paths: shared.slice(0, MAX_OVERLAP_PATHS),\n morePaths: Math.max(0, shared.length - MAX_OVERLAP_PATHS),\n })\n }\n return overlaps\n}\n\nexport async function loadWorkspaceLines(\n appDir: string,\n token: string,\n api: RepoApi,\n trunkOid: string | null,\n): Promise<Map<string, { task: string; paths: string[] }>> {\n try {\n const { views } = await api.listWorkspaces()\n fetchPeerWorkspaceRefs(appDir, token)\n return changedPathsByWorkspace(appDir, views, trunkOid)\n } catch {\n return new Map()\n }\n}\n\nexport async function listOverlaps(\n appId: string,\n token: string,\n api: RepoApi,\n views: RemoteWorkspaceView[],\n): Promise<Map<string, WorkspaceOverlap[]>> {\n const appDir = findAppDir()\n if (!appDir || readAppId(appDir) !== appId) return new Map()\n try {\n assertSyncableRepo(appDir)\n ensureSpaceRemote(appDir, appId)\n const refs = await api.getRefs().catch(() => null)\n try {\n fetchTrunk(appDir, token, refs?.head ?? null)\n } catch {\n // localTrunkOid tolerates a stale tracking ref.\n }\n fetchPeerWorkspaceRefs(appDir, token)\n const lines = changedPathsByWorkspace(appDir, views, localTrunkOid(appDir, refs))\n return new Map([...lines].map(([id, line]) => [id, overlapsWith(line.paths, lines, id)]))\n } catch {\n return new Map()\n }\n}\n\nexport function printOverlaps(overlaps: WorkspaceOverlap[], json: boolean): void {\n if (json) return\n for (const overlap of overlaps) {\n const sample = overlap.paths.slice(0, 5).join(', ')\n const more = overlap.paths.length - 5 + overlap.morePaths\n p.log.warn(\n `Overlap: ${overlap.workspaceId} (\"${overlap.task}\") also modified ${sample}${more > 0 ? ` (+${more} more)` : ''} — coordinate before landing.`,\n )\n }\n}\n","import * as p from '@clack/prompts'\nimport { mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname, isAbsolute, join, relative, sep } from 'node:path'\nimport { shQuote } from '../../lib/cli-format'\nimport { runGit } from '../../lib/git/process'\nimport {\n addWorktreeNewBranch,\n currentBranch,\n ensureLocalExclude,\n listWorktrees,\n repoToplevel,\n resolveCommit,\n} from '../../lib/git/repository'\nimport { workspaceBranchName, workspaceIdFromBranch } from '../../lib/workspace-id'\n\nconst WORKSPACE_MARKER = 'deepspace-workspace.json'\n\ninterface ManagedWorkspaceMarker {\n version: 1\n workspaceId: string\n mode: 'managed-linked'\n}\n\nexport function excludeWorktreeDir(appDir: string, dir: string): void {\n try {\n ensureLocalExclude(appDir, '.deepspace/')\n const realDir = realpathSync(dir)\n const rel = relative(realpathSync(repoToplevel(appDir)), realDir)\n if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return\n const pattern = rel.split(sep).join('/')\n if (pattern === '.deepspace' || pattern.startsWith('.deepspace/')) return\n const relApp = relative(realpathSync(appDir), realDir).split(sep).join('/')\n if (relApp === '.deepspace' || relApp.startsWith('.deepspace/')) return\n ensureLocalExclude(appDir, `/${pattern}/`)\n } catch {\n // Local exclusion is best-effort; failure only makes git status noisier.\n }\n}\n\nfunction worktreeMarkerPath(worktreeRoot: string): string | null {\n try {\n const result = runGit(worktreeRoot, ['rev-parse', '--absolute-git-dir'], { allowFail: true })\n if (result.status !== 0) return null\n const gitDir = result.stdout.toString('utf-8').trim()\n return isAbsolute(gitDir) ? join(gitDir, WORKSPACE_MARKER) : null\n } catch {\n return null\n }\n}\n\nfunction markManagedWorkspace(worktreeRoot: string, workspaceId: string): boolean {\n const markerPath = worktreeMarkerPath(worktreeRoot)\n if (!markerPath) return false\n const marker: ManagedWorkspaceMarker = { version: 1, workspaceId, mode: 'managed-linked' }\n const tempPath = `${markerPath}.${process.pid}.tmp`\n try {\n mkdirSync(dirname(markerPath), { recursive: true })\n writeFileSync(tempPath, JSON.stringify(marker) + '\\n')\n renameSync(tempPath, markerPath)\n return true\n } catch {\n return false\n }\n}\n\n/** Only a private Git-admin marker proves that DeepSpace owns this checkout. */\nexport function isManagedWorkspaceWorktree(worktreeRoot: string, workspaceId: string): boolean {\n const markerPath = worktreeMarkerPath(worktreeRoot)\n if (!markerPath) return false\n try {\n const marker = JSON.parse(readFileSync(markerPath, 'utf-8')) as Partial<ManagedWorkspaceMarker>\n return (\n marker.version === 1 && marker.workspaceId === workspaceId && marker.mode === 'managed-linked'\n )\n } catch {\n return false\n }\n}\n\n/** Stable default independent of whichever Codex/Claude/native checkout invoked us. */\nexport function defaultWorkspaceRoot(appDir: string, workspaceId: string): string {\n const primary = listWorktrees(appDir)[0]\n if (!primary) throw new Error('Git did not report a primary worktree')\n return join(primary.path, '.deepspace', 'ws', workspaceId.slice(3).toLowerCase())\n}\n\n/** Map the app's repo-relative location into a newly checked-out whole repository. */\nexport function appDirInWorktree(appDir: string, worktreeRoot: string): string {\n const appRelative = relative(realpathSync(repoToplevel(appDir)), realpathSync(appDir))\n return appRelative ? join(worktreeRoot, appRelative) : worktreeRoot\n}\n\n/** Create a local workspace checkout and apply its standard local setup. */\nexport function materializeWorkspaceWorktree(\n appDir: string,\n worktreeRoot: string,\n branch: string,\n startPoint: string,\n workspaceId: string,\n): void {\n addWorktreeNewBranch(appDir, worktreeRoot, branch, startPoint)\n excludeWorktreeDir(appDir, worktreeRoot)\n markManagedWorkspace(worktreeRoot, workspaceId)\n}\n\nexport function inOwnLinkedWorktree(appDir: string, id: string): boolean {\n if (workspaceIdFromBranch(currentBranch(appDir)) !== id) return false\n try {\n return statSync(join(repoToplevel(appDir), '.git')).isFile()\n } catch {\n return false\n }\n}\n\nexport interface CleanupOutcome {\n worktreeRemoved: string | null\n worktreeRetained: string | null\n branchDeleted: string | null\n mainDir?: string\n error?: string\n worktreeDir: string | null\n branch: string\n}\n\nexport function cleanupJson(outcome: CleanupOutcome): Record<string, unknown> {\n return {\n worktreeRemoved: outcome.worktreeRemoved,\n worktreeRetained: outcome.worktreeRetained,\n branchDeleted: outcome.branchDeleted,\n ...(outcome.mainDir ? { mainDir: outcome.mainDir } : {}),\n ...(outcome.error ? { error: outcome.error } : {}),\n }\n}\n\nfunction deleteWsBranch(cwd: string, branch: string, out: CleanupOutcome): void {\n const del = runGit(cwd, ['branch', '-D', branch], { allowFail: true })\n if (del.status === 0) out.branchDeleted = branch\n else\n out.error ??= `git branch -D ${branch} failed: ${del.stderr.toString('utf-8').trim() || 'unknown git error'}`\n}\n\nfunction switchOffWsBranch(mainDir: string, trunkBranch: string | null): boolean {\n if (trunkBranch) {\n if (resolveCommit(mainDir, `refs/heads/${trunkBranch}`)) {\n return runGit(mainDir, ['switch', '--quiet', trunkBranch], { allowFail: true }).status === 0\n }\n const remote = resolveCommit(mainDir, `refs/remotes/space/${trunkBranch}`)\n if (remote) {\n return (\n runGit(mainDir, ['switch', '--quiet', '-c', trunkBranch, remote], { allowFail: true })\n .status === 0\n )\n }\n }\n return runGit(mainDir, ['switch', '--quiet', '--detach'], { allowFail: true }).status === 0\n}\n\nexport function cleanupWorkspaceLocal(\n appDir: string,\n id: string,\n trunkBranch: string | null,\n): CleanupOutcome {\n const branch = workspaceBranchName(id)\n const out: CleanupOutcome = {\n worktreeRemoved: null,\n worktreeRetained: null,\n branchDeleted: null,\n worktreeDir: null,\n branch,\n }\n try {\n const worktrees = listWorktrees(appDir)\n const mainDir = worktrees[0]?.path ?? repoToplevel(appDir)\n const linked = worktrees.find((worktree, index) => index > 0 && worktree.branch === branch)\n if (linked) {\n out.worktreeDir = linked.path\n if (!isManagedWorkspaceWorktree(linked.path, id)) {\n out.worktreeRetained = linked.path\n return out\n }\n let inside = false\n try {\n inside = realpathSync(repoToplevel(appDir)) === realpathSync(linked.path)\n } catch {\n inside = false\n }\n if (inside) {\n process.chdir(mainDir)\n out.mainDir = mainDir\n }\n const remove = runGit(mainDir, ['worktree', 'remove', linked.path], { allowFail: true })\n if (remove.status !== 0) {\n out.error = `git worktree remove ${linked.path} failed: ${remove.stderr.toString('utf-8').trim() || 'unknown git error'}`\n return out\n }\n out.worktreeRemoved = linked.path\n deleteWsBranch(mainDir, branch, out)\n return out\n }\n if (currentBranch(mainDir) === branch && !switchOffWsBranch(mainDir, trunkBranch)) {\n out.error = `could not switch off ${branch} to delete it`\n return out\n }\n if (resolveCommit(mainDir, `refs/heads/${branch}`)) deleteWsBranch(mainDir, branch, out)\n return out\n } catch (err) {\n out.error = err instanceof Error ? err.message : String(err)\n return out\n }\n}\n\nexport function cleanupRefusalMessage(outcome: {\n error: string\n worktreeDir: string | null\n branch: string\n}): string {\n if (outcome.worktreeDir) {\n const dir = shQuote(outcome.worktreeDir)\n return (\n `Cleanup incomplete: ${outcome.error}. The worktree at ${dir} still holds uncommitted or untracked work — ` +\n `that's why the plain removal refused. Inspect it (\\`git -C ${dir} status\\`) and commit anything worth ` +\n `keeping to the workspace branch. Once it's clean, remove it from the main checkout: \\`git worktree remove ${dir}\\`.`\n )\n }\n return `Cleanup incomplete: ${outcome.error}. Finish it from the main checkout once ${shQuote(outcome.branch)} is safe to delete.`\n}\n\nexport function cleanupAction(outcome: { worktreeDir: string | null; branch: string }): {\n cwd: string\n argv: string[]\n} {\n return outcome.worktreeDir\n ? { cwd: outcome.worktreeDir, argv: ['git', 'status'] }\n : { cwd: process.cwd(), argv: ['git', 'branch', '--list', outcome.branch] }\n}\n\nexport function reportCleanupHuman(outcome: CleanupOutcome): void {\n if (outcome.error) {\n p.log.warn(\n cleanupRefusalMessage({\n error: outcome.error,\n worktreeDir: outcome.worktreeDir,\n branch: outcome.branch,\n }),\n )\n return\n }\n const parts = [\n outcome.worktreeRemoved ? 'worktree' : null,\n outcome.branchDeleted ? `branch ${outcome.branch}` : null,\n ].filter(Boolean)\n if (parts.length) p.log.success(`Removed ${parts.join(' + ')}.`)\n if (outcome.worktreeRetained) {\n p.log.info(`Retained externally managed worktree: ${outcome.worktreeRetained}`)\n }\n if (outcome.worktreeRemoved && outcome.mainDir) {\n p.log.info(`This directory was removed — run: cd ${shQuote(outcome.mainDir)}`)\n }\n}\n","import { ensureToken } from '../../auth'\nimport { findAppDir } from '../../lib/app-context'\nimport { resolveAppTarget, parseAppArg, assertAppTargetResolvable } from '../../lib/app-target'\nimport { Refusal } from '../../lib/command'\nimport type { CliAction } from '../../lib/output'\nimport { assertSyncableRepo, currentBranch, listWorktrees } from '../../lib/git/repository'\nimport { committedSecretRefusal } from '../../lib/git/safety'\nimport {\n isSelectedWorkspaceCheckout,\n isWorkspaceId,\n resolveWorkspaceWorktree,\n workspaceIdFromBranch,\n} from '../../lib/workspace-id'\nimport { pushFailureMessage, pushToSpace } from '../../lib/vc-push'\nimport { deployBaseUrl, SPACE_REMOTE } from '../../lib/vc-remote'\nimport { repoApi, type RepoApi } from '../../lib/repo-api'\n\nexport const APP_ARG = {\n type: 'string' as const,\n alias: 'a',\n description:\n 'App id or subdomain name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n}\n\ninterface Target {\n appDir: string\n appId: string\n token: string\n api: RepoApi\n}\n\nexport async function resolveTarget(appArg: string | undefined): Promise<Target> {\n const appDir = findAppDir()\n if (!appDir) {\n throw new Refusal(\n 'No wrangler.toml found — run from inside an app directory (or use -a <app> for list, and for drop with an explicit ws_ id).',\n 'not_in_app_repo',\n )\n }\n const { error: appErr } = parseAppArg(appArg)\n if (appErr) throw new Refusal(appErr, 'invalid_app')\n assertSyncableRepo(appDir)\n assertAppTargetResolvable(appArg)\n const token = await ensureToken()\n const appId = await resolveAppTarget(deployBaseUrl(), token, appArg)\n return { appDir, appId, token, api: repoApi(deployBaseUrl(), token, appId) }\n}\n\n/** Server-only resolution for list-style reads, including calls outside a checkout. */\nexport async function resolveApiOnly(\n appArg: string | undefined,\n): Promise<{ appId: string; api: RepoApi; token: string }> {\n assertAppTargetResolvable(appArg)\n const token = await ensureToken()\n const appId = await resolveAppTarget(deployBaseUrl(), token, appArg)\n return { appId, api: repoApi(deployBaseUrl(), token, appId), token }\n}\n\nexport function inferWorkspaceId(appDir: string, explicit: string | undefined): string {\n const id = explicit?.trim() || workspaceIdFromBranch(currentBranch(appDir))\n if (!id) {\n throw new Refusal(\n 'Not inside a workspace worktree (the branch is not ws/<id>). Pass the workspace id, or create one with `deepspace workspace new -t \"…\"`.',\n 'not_in_workspace',\n )\n }\n if (!isWorkspaceId(id)) {\n throw new Refusal(`Invalid workspace id: ${id} (expected ws_<ULID>).`, 'invalid_workspace')\n }\n return id\n}\n\n/** Mutating verbs must run from the selected workspace's own checkout. */\nexport function assertSelectedWorkspaceCheckout(\n appDir: string,\n id: string,\n resumeArgv: string[],\n): void {\n const branch = currentBranch(appDir)\n if (isSelectedWorkspaceCheckout(branch, id)) return\n const worktree = resolveWorkspaceWorktree(listWorktrees(appDir), id)\n const action: CliAction = worktree\n ? { cwd: worktree, argv: resumeArgv }\n : { cwd: appDir, argv: ['deepspace', 'workspace', 'attach', id] }\n throw new Refusal(\n `Workspace ${id} is not checked out here (current branch: ${branch ?? 'detached'}). ` +\n (worktree\n ? `Run this command from its checkout at ${worktree}.`\n : 'Attach it in this clone before mutating its published line.'),\n 'workspace_checkout_mismatch',\n {\n action,\n extra: worktree ? { workspaceDir: worktree } : undefined,\n },\n )\n}\n\n/** Reject malformed explicit ids before auth/network. */\nexport function assertExplicitWorkspaceId(explicit: string | undefined): void {\n if (explicit === undefined) return\n const id = explicit.trim()\n if (!id || !isWorkspaceId(id)) {\n throw new Refusal(\n `Invalid workspace id: ${explicit} (expected ws_<ULID>).`,\n 'invalid_workspace',\n )\n }\n}\n\n/** Publish a workspace line with Git's fast-forward rule as the lost-update guard. */\nexport function pushWorkspaceRef(\n appDir: string,\n token: string,\n ref: string,\n headOid: string,\n): void {\n const secret = committedSecretRefusal(appDir, headOid, {\n action: 'publish this workspace',\n then: 're-run the command',\n })\n if (secret) throw new Refusal(secret.message, secret.code)\n\n const push = pushToSpace(appDir, token, `${headOid}:${ref}`)\n if (push.status === 'committed' || push.status === 'up_to_date') return\n if (push.status === 'ref_conflict' || push.status === 'non_fast_forward') {\n throw new Refusal(\n `Another checkout advanced this workspace's line, so publishing yours is not a ` +\n `fast-forward — the push was refused rather than drop that work. Integrate its tip ` +\n `(\\`git pull ${SPACE_REMOTE} ${ref}\\`, or re-attach the workspace in a fresh dir), ` +\n `resolve any conflicts, then re-run the command. (Amended or rebased your own ` +\n `commits? Same refusal — merge your old tip back in.)`,\n push.status,\n {\n action: { cwd: appDir, argv: ['git', 'pull', SPACE_REMOTE, ref] },\n },\n )\n }\n throw new Refusal(pushFailureMessage('Workspace upload', push, appDir), push.status)\n}\n","import * as p from '@clack/prompts'\nimport { existsSync, readdirSync, rmSync } from 'node:fs'\nimport { isAbsolute, resolve } from 'node:path'\nimport { ensureToken } from '../../auth'\nimport { findAppDir } from '../../lib/app-context'\nimport { parseAppArg, resolveAppTarget } from '../../lib/app-target'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport { runGit } from '../../lib/git/process'\nimport { resolveCommit, switchToNewBranch } from '../../lib/git/repository'\nimport { isWorkspaceId, workspaceBranchName } from '../../lib/workspace-id'\nimport { deployBaseUrl, ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../../lib/vc-remote'\nimport { repoApi, type RemoteWorkspaceView } from '../../lib/repo-api'\nimport { createSpinner } from '../../lib/spinner'\nimport { errorCode } from '../../lib/cli-errors'\nimport type { CliAction } from '../../lib/output'\nimport { detectPackageManager } from '../../lib/package-manager'\nimport { appDirInWorktree, defaultWorkspaceRoot, materializeWorkspaceWorktree } from './local'\nimport { APP_ARG, resolveTarget } from './runtime'\n\n/** Explain why a finished workspace cannot be attached. */\nexport function finishedWorkspaceMessage(id: string, view: RemoteWorkspaceView): string {\n const workspace = view.workspace\n if (workspace.status === 'landed') {\n return (\n `Workspace ${id} landed at ${workspace.landedOid?.slice(0, 10) ?? 'an unrecorded commit'} and its ref was deleted — ` +\n `its whole line is reachable through that merge commit (\\`git log ${workspace.landedOid ?? '<oid>'}\\`). ` +\n `Attach only works on active workspaces; start a new one for follow-up work.`\n )\n }\n return (\n `Workspace ${id} is ${workspace.status} — its ref is retained briefly (fetch ${workspace.ref} to inspect), ` +\n `but attach only works on active workspaces.`\n )\n}\n\n/**\n * Reap a failed fresh attach only when the target still contains nothing but\n * the repository metadata this command created. Any checkout file or\n * concurrent write makes the directory user-owned and therefore untouchable.\n */\nexport function cleanFailedFreshAttachDir(dir: string): string[] {\n if (!existsSync(dir)) return []\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n return ['<unreadable>']\n }\n if (entries.length > 0 && !(entries.length === 1 && entries[0] === '.git')) {\n return entries\n }\n try {\n rmSync(dir, { recursive: true, force: true })\n return []\n } catch {\n return entries.length > 0 ? entries : ['<cleanup-failed>']\n }\n}\n\nexport const attachWorkspaceCommand = defineDeepspaceCommand({\n meta: {\n name: 'attach',\n description: 'Resume a workspace here (another machine or a fresh sandbox)',\n },\n args: {\n id: { type: 'positional', description: 'Workspace id (ws_…)', required: true },\n dir: {\n type: 'positional',\n description: 'Directory (worktree or fresh clone target)',\n required: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const id = String(args.id).trim()\n if (!isWorkspaceId(id)) {\n throw new Refusal(`Invalid workspace id: ${id} (expected ws_<ULID>).`, 'invalid_workspace')\n }\n const branch = workspaceBranchName(id)\n const insideRepo = findAppDir()\n const appArg = typeof args.app === 'string' ? args.app : undefined\n const { app: appSelector, error: appError } = parseAppArg(appArg)\n if (appError) throw new Refusal(appError, 'invalid_app')\n if (!insideRepo && appSelector === undefined) {\n throw new Refusal(\n 'Not inside an app repo — pass the app explicitly: deepspace workspace attach <ws_id> [dir] -a <app id or name>.',\n 'not_in_app_repo',\n )\n }\n\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Preparing to attach ${id}…`)\n\n if (insideRepo) {\n const { appDir, appId, api, token } = await resolveTarget(appArg)\n spinner?.message(`Attaching ${id}…`)\n const { view } = await api.getWorkspace(id)\n if (view.workspace.status !== 'active') {\n spinner?.stop('Workspace finished.')\n throw new Refusal(finishedWorkspaceMessage(id, view), 'workspace_not_active', {\n extra: { status: view.workspace.status },\n })\n }\n ensureSpaceRemote(appDir, appId)\n runGitRemote(appDir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+${view.workspace.ref}:${view.workspace.ref}`,\n ])\n const tip = view.tipOid ?? view.workspace.baseOid\n if (!resolveCommit(appDir, tip)) {\n spinner?.stop('Fetch failed.')\n throw new Refusal(\n `Could not fetch ${view.workspace.ref} from the cloud repo. Retry; if it persists, report it with \\`deepspace feedback\\`.`,\n 'fetch_failed',\n )\n }\n const requestedDir = typeof args.dir === 'string' ? args.dir.trim() : ''\n const worktreeRoot = requestedDir\n ? isAbsolute(requestedDir)\n ? requestedDir\n : resolve(appDir, requestedDir)\n : defaultWorkspaceRoot(appDir, id)\n const dir = appDirInWorktree(appDir, worktreeRoot)\n if (resolveCommit(appDir, `refs/heads/${branch}`)) {\n throw new Refusal(\n `Branch ${branch} already exists locally (this workspace has a worktree here). Find it with \\`git worktree list\\` and continue there.`,\n 'branch_exists',\n )\n }\n materializeWorkspaceWorktree(appDir, worktreeRoot, branch, tip, id)\n spinner?.stop(`Attached ${id}.`)\n if (!args.json) {\n p.log.info(`Task: ${view.workspace.task}`)\n p.log.info(`Work in: cd ${dir}`)\n }\n const action: CliAction = { cwd: dir, argv: [detectPackageManager(dir), 'install'] }\n return {\n data: {\n workspaceId: id,\n mode: 'worktree',\n dir,\n worktreeRoot,\n branch,\n tipOid: tip,\n task: view.workspace.task,\n },\n action,\n }\n }\n\n // Fresh-clone mode materializes only this workspace's hidden ref.\n const token = await ensureToken()\n const appId = await resolveAppTarget(deployBaseUrl(), token, appSelector)\n const api = repoApi(deployBaseUrl(), token, appId)\n spinner?.message(`Attaching ${id} into a fresh clone…`)\n const { view } = await api.getWorkspace(id)\n if (view.workspace.status !== 'active') {\n spinner?.stop('Workspace finished.')\n throw new Refusal(finishedWorkspaceMessage(id, view), 'workspace_not_active', {\n extra: { status: view.workspace.status },\n })\n }\n const dir = resolve(\n process.cwd(),\n (typeof args.dir === 'string' ? args.dir.trim() : '') || `ws-${id.slice(3).toLowerCase()}`,\n )\n if (existsSync(dir)) {\n spinner?.stop('Target exists.')\n throw new Refusal(`${dir} already exists — pass a different directory.`, 'dir_exists')\n }\n const failFreshAttach = (message: string, code?: string): never => {\n const leftovers = cleanFailedFreshAttachDir(dir)\n const cleanupNote =\n leftovers.length > 0\n ? ` The failed attach left ${dir} in place because it contains: ${leftovers.join(', ')}.`\n : ''\n throw new Refusal(message + cleanupNote, code ?? 'attach_failed', {\n extra: leftovers.length > 0 ? { leftovers } : undefined,\n })\n }\n let tip: string\n try {\n runGit(process.cwd(), ['init', '--quiet', dir])\n ensureSpaceRemote(dir, appId)\n runGitRemote(dir, token, [\n 'fetch',\n '--quiet',\n SPACE_REMOTE,\n `+${view.workspace.ref}:${view.workspace.ref}`,\n ])\n tip = view.tipOid ?? view.workspace.baseOid\n if (!resolveCommit(dir, tip)) {\n spinner?.stop('Fetch failed.')\n return failFreshAttach(\n `Could not fetch ${view.workspace.ref} from the cloud repo. Retry; if it persists, report it with \\`deepspace feedback\\`.`,\n 'fetch_failed',\n )\n }\n switchToNewBranch(dir, branch, tip)\n } catch (error) {\n if (error instanceof Refusal) throw error\n return failFreshAttach(\n error instanceof Error ? error.message : String(error),\n errorCode(error),\n )\n }\n spinner?.stop(`Attached ${id}.`)\n const action: CliAction = { cwd: dir, argv: [detectPackageManager(dir), 'install'] }\n if (!args.json) {\n p.log.info(`Task: ${view.workspace.task}`)\n p.log.info('Pull app secrets after install if this workspace needs them.')\n }\n return {\n data: {\n workspaceId: id,\n mode: 'clone',\n dir,\n branch,\n tipOid: tip,\n task: view.workspace.task,\n },\n action,\n }\n },\n})\n","import * as p from '@clack/prompts'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport { resolveCommit } from '../../lib/git/repository'\nimport { statusFiles } from '../../lib/git/safety'\nimport { ensureSpaceRemote } from '../../lib/vc-remote'\nimport { createSpinner } from '../../lib/spinner'\nimport {\n fetchTrunk,\n lineChangedPaths,\n loadWorkspaceLines,\n localTrunkOid,\n overlapsWith,\n printOverlaps,\n trunkOverlapPaths,\n} from './analysis'\nimport {\n APP_ARG,\n assertExplicitWorkspaceId,\n assertSelectedWorkspaceCheckout,\n inferWorkspaceId,\n pushWorkspaceRef,\n resolveTarget,\n} from './runtime'\n\nexport const syncWorkspaceCommand = defineDeepspaceCommand({\n meta: {\n name: 'sync',\n description: 'Publish this workspace: push its branch + report changed paths',\n },\n args: {\n workspace: {\n type: 'string',\n alias: 'w',\n description: 'Workspace id (default: inferred from the ws/<id> branch)',\n required: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const workspaceArg = typeof args.workspace === 'string' ? args.workspace : undefined\n assertExplicitWorkspaceId(workspaceArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing workspace sync…')\n const { appDir, appId, token, api } = await resolveTarget(\n typeof args.app === 'string' ? args.app : undefined,\n )\n const id = inferWorkspaceId(appDir, workspaceArg)\n assertSelectedWorkspaceCheckout(appDir, id, ['deepspace', 'workspace', 'sync'])\n const headOid = resolveCommit(appDir, 'HEAD')\n if (!headOid) {\n throw new Refusal('The workspace has no commits yet — commit first, then sync.', 'no_commits')\n }\n\n spinner?.message(`Syncing ${id}…`)\n const [{ view: before }, refs] = await Promise.all([\n api.getWorkspace(id),\n api.getRefs().catch(() => null),\n ])\n if (before.workspace.status !== 'active') {\n spinner?.stop('Workspace finished.')\n throw new Refusal(\n `Workspace ${id} is ${before.workspace.status} — create a new workspace to continue this line of work.`,\n 'workspace_not_active',\n { extra: { status: before.workspace.status } },\n )\n }\n ensureSpaceRemote(appDir, appId)\n pushWorkspaceRef(appDir, token, before.workspace.ref, headOid)\n\n // Keep advisory overlap math current without turning a transient fetch into a sync failure.\n try {\n fetchTrunk(appDir, token, refs?.head ?? null)\n } catch {\n // localTrunkOid can use the existing tracking ref.\n }\n\n const trunkOid = localTrunkOid(appDir, refs)\n const line = lineChangedPaths(appDir, before.workspace.baseOid, headOid, trunkOid)\n const changedPaths = line?.paths\n const trunkOverlap = line ? trunkOverlapPaths(appDir, line.diffBase, trunkOid, line.paths) : []\n const overlaps =\n changedPaths && changedPaths.length > 0\n ? overlapsWith(changedPaths, await loadWorkspaceLines(appDir, token, api, trunkOid), id)\n : []\n\n const upToDate = headOid === before.tipOid\n const view = upToDate ? before : (await api.syncWorkspace(id, { headOid })).view\n const dirty = statusFiles(appDir)\n spinner?.stop(\n upToDate\n ? `Already synced — ${id} is up to date at ${headOid.slice(0, 10)}.`\n : changedPaths !== undefined\n ? `Synced ${id} → ${headOid.slice(0, 10)} (${changedPaths.length} ${changedPaths.length === 1 ? 'file' : 'files'} vs base).`\n : `Synced ${id} → ${headOid.slice(0, 10)} (base not present locally — no overlap report).`,\n )\n printOverlaps(overlaps, args.json)\n if (!args.json && trunkOverlap.length > 0) {\n p.log.warn(\n `Trunk already changed ${trunkOverlap.length} file(s) you also touch — landed work you haven't merged: ` +\n `${trunkOverlap.slice(0, 5).join(', ')}${trunkOverlap.length > 5 ? ` (+${trunkOverlap.length - 5} more)` : ''}. ` +\n `Merge trunk before landing (\\`deepspace workspace status\\` shows the full picture).`,\n )\n }\n if (!args.json && dirty.length > 0) {\n p.log.warn(\n `${dirty.length} uncommitted ${dirty.length === 1 ? 'file' : 'files'} NOT synced — commit them to this workspace branch (WIP commits are fine — they land with the merge).`,\n )\n }\n return {\n data: {\n status: upToDate ? 'up_to_date' : 'synced',\n workspaceId: id,\n headOid,\n changedPaths: changedPaths ?? null,\n overlaps,\n trunkOverlap,\n uncommitted: dirty,\n view,\n },\n }\n },\n})\n","import * as p from '@clack/prompts'\nimport { parseLimitArg } from '../../lib/citty-args'\nimport { actorLabels } from '../../lib/actor-labels'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport type { RemoteWorkspaceView } from '../../lib/repo-api'\nimport { createSpinner } from '../../lib/spinner'\nimport { formatCount, listOverlaps, type WorkspaceOverlap } from './analysis'\nimport { APP_ARG, resolveApiOnly } from './runtime'\n\nexport function withWorkspaceOverlaps(\n views: RemoteWorkspaceView[],\n overlapsById: Map<string, WorkspaceOverlap[]>,\n) {\n return views.map((view) => ({\n ...view,\n overlaps: overlapsById.get(view.workspace.id) ?? [],\n }))\n}\n\nexport const listWorkspacesCommand = defineDeepspaceCommand({\n meta: { name: 'list', description: 'List workspaces on the cloud repo' },\n args: {\n all: { type: 'boolean', description: 'Include landed/dropped workspaces', default: false },\n limit: { type: 'string', description: 'Max entries (default 50)', required: false },\n app: APP_ARG,\n },\n async run({ args }) {\n const { limit, error: limitError } = parseLimitArg(args.limit)\n if (limitError) throw new Refusal(limitError, 'invalid_limit')\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Loading workspaces…')\n const { appId, api, token } = await resolveApiOnly(\n typeof args.app === 'string' ? args.app : undefined,\n )\n const all = Boolean(args.all)\n const { views } = await api.listWorkspaces({ all, limit })\n if (views.length === 0) {\n spinner?.stop('No workspaces found.')\n if (!args.json) {\n p.log.info(\n all\n ? 'No workspaces.'\n : 'No active workspaces. Create one with `deepspace workspace new -t \"…\"`.',\n )\n }\n return { data: { workspaces: views } }\n }\n\n spinner?.message('Checking workspace overlaps…')\n const overlapsPromise = listOverlaps(appId, token, api, views)\n if (args.json) {\n return {\n data: { workspaces: withWorkspaceOverlaps(views, await overlapsPromise) },\n }\n }\n const [actors, overlapsById] = await Promise.all([actorLabels(token, appId), overlapsPromise])\n const workspaces = withWorkspaceOverlaps(views, overlapsById)\n spinner?.stop(`Loaded ${views.length} ${views.length === 1 ? 'workspace' : 'workspaces'}.`)\n for (const view of workspaces) {\n const workspace = view.workspace\n const overlaps = view.overlaps\n const marker =\n workspace.status === 'active'\n ? overlaps.length > 0\n ? '⚠'\n : ' '\n : workspace.status === 'landed'\n ? '✓'\n : '✗'\n console.log(\n `${marker} ${workspace.id} ${workspace.status} ↑${formatCount(view.aheadOfBase)} ↓${formatCount(view.behindTrunk)} ${actors.get(workspace.createdBy) ?? workspace.createdBy} ${workspace.updatedAt} ${workspace.task}`,\n )\n for (const overlap of overlaps) {\n console.log(\n ` overlaps ${overlap.workspaceId}: ${overlap.paths.slice(0, 3).join(', ')}${overlap.paths.length + overlap.morePaths > 3 ? ` (+${overlap.paths.length + overlap.morePaths - 3} more)` : ''}`,\n )\n }\n }\n p.log.info('↑ commits ahead of base · ↓ trunk commits since base (staleness)')\n return { data: { workspaces } }\n },\n})\n","/**\n * Best-effort userId → human label map for the coordination read commands\n * (activity, workspace list). Raw actor ids are stable\n * API surface and stay in --json; the HUMAN views resolve them to emails\n * where the platform can: the caller's own id from the JWT (\"(you)\"), and\n * collaborators from the api-worker roster (owner-scoped — a collaborator's\n * view quietly falls back to raw ids). Any source failing degrades to ids,\n * never to a failed command.\n */\n\nimport { PLATFORM_URLS } from '../env'\nimport { decodeJwtPayload } from '../jwt'\nimport { apiFetch } from './api'\n\nconst API_URL = process.env.DEEPSPACE_API_URL ?? PLATFORM_URLS.api\n\nexport async function actorLabels(token: string, appId: string): Promise<Map<string, string>> {\n const labels = new Map<string, string>()\n try {\n const { sub, email } = decodeJwtPayload<{ sub?: string; email?: string }>(token)\n if (sub && email) labels.set(sub, `${email} (you)`)\n } catch {\n // unreadable token — ids only\n }\n try {\n const { collaborators } = await apiFetch<{\n collaborators: Array<{ userId: string; emailDisplay: string }>\n }>(API_URL, token, `/api/app-collaborators/${encodeURIComponent(appId)}`)\n for (const c of collaborators) {\n if (!labels.has(c.userId)) labels.set(c.userId, c.emailDisplay)\n }\n } catch {\n // not the owner / roster unavailable — ids only\n }\n return labels\n}\n","import * as p from '@clack/prompts'\nimport { defineDeepspaceCommand } from '../../lib/command'\nimport { listWorktrees, resolveCommit, revListCount } from '../../lib/git/repository'\nimport { statusFiles } from '../../lib/git/safety'\nimport { ensureSpaceRemote } from '../../lib/vc-remote'\nimport { createSpinner } from '../../lib/spinner'\nimport { resolveWorkspaceWorktree } from '../../lib/workspace-id'\nimport {\n fetchTrunk,\n lineChangedPaths,\n loadWorkspaceLines,\n overlapsWith,\n peerWorkspaceRef,\n printOverlaps,\n trunkOverlapPaths,\n} from './analysis'\nimport { APP_ARG, assertExplicitWorkspaceId, inferWorkspaceId, resolveTarget } from './runtime'\n\nexport const workspaceStatusCommand = defineDeepspaceCommand({\n meta: { name: 'status', description: 'This workspace: base staleness, overlaps, sync state' },\n args: {\n workspace: {\n type: 'string',\n alias: 'w',\n description: 'Workspace id (default: inferred from the ws/<id> branch)',\n required: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const workspaceArg = typeof args.workspace === 'string' ? args.workspace : undefined\n assertExplicitWorkspaceId(workspaceArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing workspace status…')\n const { appDir, appId, token, api } = await resolveTarget(\n typeof args.app === 'string' ? args.app : undefined,\n )\n const id = inferWorkspaceId(appDir, workspaceArg)\n spinner?.message(`Checking ${id}…`)\n ensureSpaceRemote(appDir, appId)\n const [{ view }, refs] = await Promise.all([api.getWorkspace(id), api.getRefs()])\n const workspace = view.workspace\n\n // Read checkout-only state from this workspace's actual worktree. Object-level\n // graph queries can safely use appDir even when status is invoked elsewhere.\n const workspaceDir = resolveWorkspaceWorktree(listWorktrees(appDir), id)\n const attached = workspaceDir !== null\n const headOid = workspaceDir ? resolveCommit(workspaceDir, 'HEAD') : null\n const trunk = fetchTrunk(appDir, token, refs?.head ?? null)\n const trunkOid = trunk?.oid ?? null\n const baseLocal = resolveCommit(appDir, workspace.baseOid) !== null\n const behindExact =\n trunk && baseLocal ? revListCount(appDir, workspace.baseOid, trunk.oid) : null\n const aheadExact =\n headOid && baseLocal ? revListCount(appDir, workspace.baseOid, headOid) : null\n const unsynced = headOid !== null && view.tipOid !== headOid\n const dirty = workspaceDir ? statusFiles(workspaceDir) : []\n\n const lines = await loadWorkspaceLines(appDir, token, api, trunkOid)\n const myTip = headOid ?? resolveCommit(appDir, peerWorkspaceRef(id)) ?? view.tipOid\n const line = myTip ? lineChangedPaths(appDir, workspace.baseOid, myTip, trunkOid) : null\n const trunkOverlap = line ? trunkOverlapPaths(appDir, line.diffBase, trunkOid, line.paths) : []\n const overlaps = overlapsWith(line?.paths ?? [], lines, id)\n\n spinner?.stop(`Workspace ${id} (${workspace.status}).`)\n const data = {\n workspaceId: id,\n task: workspace.task,\n status: workspace.status,\n baseOid: workspace.baseOid,\n syncedTip: view.tipOid,\n landedOid: workspace.landedOid,\n trunkCommitsSinceBase: behindExact,\n aheadOfBase:\n attached && aheadExact !== null ? { count: aheadExact, capped: false } : view.aheadOfBase,\n attached,\n ...(attached\n ? {\n headOid,\n unsynced,\n uncommitted: dirty,\n trunkOverlap,\n }\n : {}),\n overlaps,\n }\n if (!args.json) {\n p.log.info(`Task: ${workspace.task}`)\n p.log.info(\n `Base: ${workspace.baseOid.slice(0, 10)} · ahead ${aheadExact ?? '?'} commit(s) · trunk moved ${behindExact ?? '?'} commit(s) since your base`,\n )\n if (!attached) {\n p.log.info(\n `Not checked out in this clone — showing the published state (local HEAD/uncommitted unavailable). Attach it with \\`deepspace workspace attach ${id} <dir>\\`.`,\n )\n }\n if (unsynced)\n p.log.warn(\n `Local HEAD ${headOid?.slice(0, 10)} is not synced (server has ${view.tipOid?.slice(0, 10) ?? 'nothing'}) — run \\`deepspace workspace sync\\`.`,\n )\n if (dirty.length > 0) p.log.warn(`${dirty.length} uncommitted file(s) in the worktree.`)\n if (trunkOverlap.length > 0) {\n p.log.warn(\n `Trunk also modified: ${trunkOverlap.slice(0, 5).join(', ')}${trunkOverlap.length > 5 ? ` (+${trunkOverlap.length - 5} more)` : ''} — expect merge attention at land time.`,\n )\n }\n printOverlaps(overlaps, false)\n }\n return { data }\n },\n})\n","import * as p from '@clack/prompts'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport type { CliAction } from '../../lib/output'\nimport { runGit } from '../../lib/git/process'\nimport { isPlausibleBranchName, isWorkTreeClean, resolveCommit } from '../../lib/git/repository'\nimport { committedSecretRefusal } from '../../lib/git/safety'\nimport { pushToSpace } from '../../lib/vc-push'\nimport { ensureSpaceRemote, runGitRemote, SPACE_REMOTE } from '../../lib/vc-remote'\nimport { resolveValidationCommand, runValidationCommand } from '../../lib/validation'\nimport { createSpinner } from '../../lib/spinner'\nimport { humanCommand } from '../../lib/cli-format'\nimport {\n cleanupAction,\n cleanupJson,\n cleanupRefusalMessage,\n cleanupWorkspaceLocal,\n inOwnLinkedWorktree,\n reportCleanupHuman,\n} from './local'\nimport {\n APP_ARG,\n assertExplicitWorkspaceId,\n assertSelectedWorkspaceCheckout,\n inferWorkspaceId,\n pushWorkspaceRef,\n resolveTarget,\n} from './runtime'\n\nexport function hasLeftoverConflictMarkers(diffCheckOutput: string): boolean {\n return /leftover conflict marker/.test(diffCheckOutput)\n}\n\nexport interface LandArgs {\n workspace?: string\n into?: string\n validate?: boolean\n 'keep-worktree'?: boolean\n}\n\n/** Rebuild land argv so every resumable refusal preserves the caller's safety flags. */\nexport function landResumeArgv(args: LandArgs): string[] {\n const argv = ['deepspace', 'workspace', 'land']\n const workspace = args.workspace?.trim()\n if (workspace) argv.push('-w', workspace)\n const into = args.into?.trim()\n if (into) argv.push('--into', into)\n if (args.validate) argv.push('--validate')\n if (args['keep-worktree']) argv.push('--keep-worktree')\n return argv\n}\n\nexport const landWorkspaceCommand = defineDeepspaceCommand({\n meta: { name: 'land', description: 'Merge this workspace into trunk (both sides retained)' },\n args: {\n into: {\n type: 'string',\n description: 'Target branch (default: the cloud repo default branch)',\n required: false,\n },\n workspace: {\n type: 'string',\n alias: 'w',\n description: 'Workspace id (default: inferred from the ws/<id> branch)',\n required: false,\n },\n 'keep-worktree': {\n type: 'boolean',\n description: 'Keep the local worktree and branch after landing',\n default: false,\n },\n validate: {\n type: 'boolean',\n description:\n 'Run the project validation on the merged tree before publishing trunk (exit 2 on failure)',\n default: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const intoArg = typeof args.into === 'string' ? args.into : undefined\n const workspaceArg = typeof args.workspace === 'string' ? args.workspace : undefined\n const validate = Boolean(args.validate)\n const keepWorktree = Boolean(args['keep-worktree'])\n if (args.into !== undefined) {\n const branch = String(args.into).trim()\n if (!branch) {\n throw new Refusal('--into was given an empty branch name.', 'invalid_branch')\n }\n if (!isPlausibleBranchName(branch)) {\n throw new Refusal(`--into \"${branch}\" is not a valid git branch name.`, 'invalid_branch')\n }\n }\n assertExplicitWorkspaceId(workspaceArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start('Preparing workspace land…')\n const { appDir, appId, token, api } = await resolveTarget(\n typeof args.app === 'string' ? args.app : undefined,\n )\n const id = inferWorkspaceId(appDir, workspaceArg)\n const resumeArgv = landResumeArgv({\n workspace: workspaceArg,\n into: intoArg,\n validate,\n 'keep-worktree': keepWorktree,\n })\n const recoveryAction: CliAction = { cwd: appDir, argv: resumeArgv }\n const resumeNext = humanCommand(resumeArgv)\n assertSelectedWorkspaceCheckout(appDir, id, resumeArgv)\n const headBefore = resolveCommit(appDir, 'HEAD')\n if (!headBefore) {\n throw new Refusal('The workspace has no commits — nothing to land.', 'no_commits')\n }\n\n if (!isWorkTreeClean(appDir)) {\n throw new Refusal(\n `The worktree has uncommitted changes, and landing publishes committed HEAD only. Commit them to this workspace branch, then re-run \\`${resumeNext}\\`.`,\n 'dirty_worktree',\n { extra: { workspaceId: id } },\n )\n }\n\n spinner?.message(`Landing ${id}…`)\n const [{ view }, refs] = await Promise.all([api.getWorkspace(id), api.getRefs()])\n if (view.workspace.status !== 'active') {\n spinner?.stop('Workspace finished.')\n throw new Refusal(\n `Workspace ${id} is already ${view.workspace.status}.`,\n 'workspace_not_active',\n { extra: { status: view.workspace.status } },\n )\n }\n ensureSpaceRemote(appDir, appId)\n\n // A conflict retry keeps the pure workspace line immutable: HEAD's first parent is its tip.\n const isResumedMerge =\n resolveCommit(appDir, 'HEAD^2') !== null &&\n view.tipOid !== null &&\n resolveCommit(appDir, 'HEAD^') === view.tipOid\n if (!isResumedMerge) {\n pushWorkspaceRef(appDir, token, view.workspace.ref, headBefore)\n }\n\n const intoBranch =\n intoArg?.trim() ||\n (refs?.head?.startsWith('refs/heads/') ? refs.head.slice('refs/heads/'.length) : null)\n if (!intoBranch) {\n spinner?.stop('No trunk.')\n throw new Refusal(\n 'The cloud repo has no default branch yet — push trunk first (`deepspace push`), then land.',\n 'no_default_branch',\n )\n }\n const intoRef = `refs/heads/${intoBranch}`\n const remoteRef = `refs/remotes/space/${intoBranch}`\n runGitRemote(appDir, token, ['fetch', '--quiet', SPACE_REMOTE, `+${intoRef}:${remoteRef}`], {\n allowFail: true,\n })\n const remoteTip = resolveCommit(appDir, remoteRef)\n\n if (\n remoteTip &&\n runGit(appDir, ['merge-base', '--is-ancestor', remoteTip, 'HEAD'], { allowFail: true })\n .status !== 0\n ) {\n const hasIdent = runGit(appDir, ['config', 'user.email'], { allowFail: true }).status === 0\n const identEnv: Record<string, string> = hasIdent\n ? {}\n : {\n GIT_AUTHOR_NAME: 'DeepSpace Workspace',\n GIT_AUTHOR_EMAIL: 'workspace@deep.space',\n GIT_COMMITTER_NAME: 'DeepSpace Workspace',\n GIT_COMMITTER_EMAIL: 'workspace@deep.space',\n }\n const merge = runGit(appDir, ['merge', '--no-edit', remoteRef], {\n allowFail: true,\n env: identEnv,\n })\n if (merge.status !== 0) {\n const conflicted =\n runGit(appDir, ['ls-files', '-u'], { allowFail: true })\n .stdout.toString('utf-8')\n .trim() !== ''\n if (!conflicted) {\n runGit(appDir, ['merge', '--abort'], { allowFail: true })\n spinner?.stop('Merge failed.')\n throw new Refusal(\n `Merging trunk (${intoBranch}) failed (not a conflict): ${merge.stderr.toString('utf-8').trim() || 'unknown git error'}.`,\n 'merge_failed',\n )\n }\n spinner?.stop('Merge conflict.')\n throw new Refusal(\n `Merging trunk (${intoBranch}) hit conflicts. Resolve them, \\`git add\\` + \\`git commit\\` (validate the merged tree — a marker-free merge can still be semantically wrong), then re-run \\`${resumeNext}\\`. Your original line is safe on ${view.workspace.ref}.`,\n 'merge_conflict',\n {\n actionRequired: true,\n extra: { workspaceId: id, conflict: true },\n },\n )\n }\n }\n\n if (resolveCommit(appDir, 'HEAD^2') !== null) {\n const markerCheck = runGit(appDir, ['diff', '--check', 'HEAD^', 'HEAD'], {\n allowFail: true,\n })\n if (hasLeftoverConflictMarkers(markerCheck.stdout.toString('utf-8'))) {\n spinner?.stop('Conflict markers in merge.')\n throw new Refusal(\n `The merge commit still contains unresolved conflict markers (<<<<<<< / ======= / >>>>>>>). Fix the marked files, commit the correction, then re-run \\`${resumeNext}\\`. Nothing was pushed to ${intoBranch}.`,\n 'conflict_markers',\n {\n actionRequired: true,\n extra: { workspaceId: id, conflict: true },\n },\n )\n }\n }\n\n const landedOid = resolveCommit(appDir, 'HEAD')!\n let validationResult: {\n passed: boolean\n command: string\n durationMs: number\n outputTail?: string\n } | null = null\n if (validate) {\n const command = resolveValidationCommand(appDir)\n if (!command) {\n spinner?.stop('No validation command.')\n throw new Refusal(\n 'No validation command for --validate. Add a \"validate\" script to package.json (e.g. \"vitest run\"), or land without --validate.',\n 'no_validate_command',\n )\n }\n spinner?.message(`Validating: ${command}`)\n const run = runValidationCommand(appDir, command)\n const headAfter = resolveCommit(appDir, 'HEAD')\n const dirtyAfter = !isWorkTreeClean(appDir)\n const outputTail = run.output.slice(-2000) || run.summary || undefined\n validationResult = {\n passed: run.passed,\n command,\n durationMs: run.durationMs,\n ...(run.passed ? {} : { outputTail }),\n }\n if (!run.passed) {\n spinner?.stop('Validation failed.')\n throw new Refusal(\n `Validation FAILED on the merged tree (exit ${run.exitStatus ?? '?'}) — the merge is local and nothing was pushed to ${intoBranch}. Fix it, commit, then re-run \\`${resumeNext}\\`. Your original line is safe on ${view.workspace.ref}.`,\n 'validation_failed',\n {\n actionRequired: true,\n extra: { workspaceId: id, passed: false, outputTail },\n },\n )\n }\n if (headAfter !== landedOid || dirtyAfter) {\n spinner?.stop('Validation changed the tree.')\n throw new Refusal(\n `Validation modified the working tree or HEAD (a formatter, \\`eslint --fix\\`, codegen, or a snapshot update). ` +\n `Nothing was pushed to ${intoBranch}: landing would publish ${landedOid.slice(0, 10)} and exclude those changes. ` +\n `Review and commit them (or revert), then re-run \\`${resumeNext}\\`. Your original line is safe on ${view.workspace.ref}.`,\n 'validation_mutated_tree',\n {\n actionRequired: true,\n extra: { workspaceId: id },\n },\n )\n }\n }\n\n const trunkSecret = committedSecretRefusal(appDir, resolveCommit(appDir, 'HEAD'), {\n action: `land onto ${intoBranch}`,\n then: 're-run the land',\n })\n if (trunkSecret) {\n spinner?.stop('Secret in history.')\n throw new Refusal(trunkSecret.message, trunkSecret.code, {\n extra: { workspaceId: id },\n })\n }\n const push = pushToSpace(appDir, token, `HEAD:${intoRef}`)\n if (push.status === 'ref_conflict' || push.status === 'non_fast_forward') {\n spinner?.stop('Trunk moved.')\n throw new Refusal(\n `${intoBranch} moved while you merged (${push.reason ?? push.summary}). Re-run \\`${resumeNext}\\` to integrate the new tip.`,\n 'trunk_moved',\n {\n actionRequired: true,\n action: recoveryAction,\n extra: { workspaceId: id },\n },\n )\n }\n if (push.status === 'rejected') {\n spinner?.stop('Push rejected.')\n throw new Refusal(\n `The cloud repo rejected the land push: ${push.reason ?? push.summary}.`,\n 'push_rejected',\n )\n }\n\n await api.landWorkspace(id, { landedOid, intoRef })\n spinner?.stop(`Landed ${id} into ${intoBranch} at ${landedOid.slice(0, 10)}.`)\n const cleanup = keepWorktree ? null : cleanupWorkspaceLocal(appDir, id, intoBranch)\n const inOwnWorktree = !cleanup && inOwnLinkedWorktree(appDir, id)\n const retainedWorktree =\n cleanup?.worktreeRetained ?? (keepWorktree || inOwnWorktree ? appDir : null)\n const data = {\n workspaceId: id,\n into: intoBranch,\n landedOid,\n ...(validationResult ? { validation: validationResult } : {}),\n ...(retainedWorktree ? { worktree: retainedWorktree } : {}),\n ...(cleanup ? { cleanup: cleanupJson(cleanup) } : {}),\n }\n if (!args.json && cleanup && !cleanup.error) {\n reportCleanupHuman(cleanup)\n } else if (!args.json && retainedWorktree) {\n p.log.info(`Retained checkout: ${retainedWorktree}`)\n }\n if (cleanup?.error) {\n const action = cleanupAction({\n worktreeDir: cleanup.worktreeDir,\n branch: cleanup.branch,\n })\n throw new Refusal(\n cleanupRefusalMessage({\n error: cleanup.error,\n worktreeDir: cleanup.worktreeDir,\n branch: cleanup.branch,\n }),\n 'cleanup_incomplete',\n { actionRequired: true, action, extra: data },\n )\n }\n return { data }\n },\n})\n","/**\n * The project's own check, run locally — the machinery behind\n * `deepspace workspace land --validate`.\n *\n * A validation is a pure LOCAL GATE: it runs the project's check against the\n * merged tree and aborts the land on failure. Nothing is recorded anywhere —\n * \"tests were green\" is a fact about a tree, and the tree is right here.\n */\n\nimport { sync as spawnSync } from 'cross-spawn'\nimport { readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { detectPackageManager } from './package-manager'\n\nconst MAX_SUMMARY_CHARS = 4_000\nconst MAX_OUTPUT_BUFFER = 64 * 1024 * 1024\n\n/** The script runner matching the repo's lockfile (npm unless proven otherwise). */\nfunction configuredCommand(appDir: string): string | null {\n try {\n const pkg = JSON.parse(readFileSync(join(appDir, 'package.json'), 'utf-8')) as {\n scripts?: Record<string, string>\n }\n if (pkg.scripts?.validate) return `${detectPackageManager(appDir)} run --silent validate`\n } catch {\n // no/broken package.json — handled by the caller's advice\n }\n return null\n}\n\nexport interface ValidationRun {\n passed: boolean\n durationMs: number\n summary: string | null\n output: string\n exitStatus: number | null\n}\n\n/** Resolve the validation command: an explicit override, else the package.json\n * `validate` script (via the repo's package runner), else null. */\nexport function resolveValidationCommand(appDir: string, explicit?: string): string | null {\n return explicit?.trim() || configuredCommand(appDir)\n}\n\n/** Run a validation command and capture its outcome. Never throws on a non-zero\n * exit — a failed check is a well-formed result the caller turns into its own\n * refusal. */\nexport function runValidationCommand(appDir: string, command: string): ValidationRun {\n const started = Date.now()\n const res = spawnSync(command, [], {\n cwd: appDir,\n shell: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n maxBuffer: MAX_OUTPUT_BUFFER,\n env: { ...process.env, CI: process.env.CI ?? '1' },\n })\n const durationMs = Date.now() - started\n const passed = res.status === 0 && !res.error\n const output =\n `${res.stdout?.toString('utf-8') ?? ''}\\n${res.stderr?.toString('utf-8') ?? ''}`.trim()\n const summary = output.slice(-MAX_SUMMARY_CHARS) || (res.error ? res.error.message : null)\n return { passed, durationMs, summary, output, exitStatus: res.status ?? null }\n}\n","import * as p from '@clack/prompts'\nimport { findAppDir } from '../../lib/app-context'\nimport { defineDeepspaceCommand, Refusal } from '../../lib/command'\nimport { isWorkTreeClean } from '../../lib/git/repository'\nimport type { CliAction } from '../../lib/output'\nimport { humanCommand } from '../../lib/cli-format'\nimport { createSpinner } from '../../lib/spinner'\nimport {\n cleanupAction,\n cleanupRefusalMessage,\n cleanupJson,\n cleanupWorkspaceLocal,\n inOwnLinkedWorktree,\n isManagedWorkspaceWorktree,\n reportCleanupHuman,\n} from './local'\nimport {\n APP_ARG,\n assertExplicitWorkspaceId,\n inferWorkspaceId,\n resolveApiOnly,\n resolveTarget,\n} from './runtime'\n\nexport const dropWorkspaceCommand = defineDeepspaceCommand({\n meta: { name: 'drop', description: 'Abandon a workspace (ref retained briefly, then GC)' },\n args: {\n id: {\n type: 'positional',\n description: 'Workspace id (default: inferred from the ws/<id> branch)',\n required: false,\n },\n 'keep-worktree': {\n type: 'boolean',\n description: 'Keep the local worktree and branch after dropping',\n default: false,\n },\n app: APP_ARG,\n },\n async run({ args }) {\n const explicitId = typeof args.id === 'string' ? args.id.trim() : undefined\n assertExplicitWorkspaceId(explicitId)\n const appArg = typeof args.app === 'string' ? args.app : undefined\n const keepWorktree = Boolean(args['keep-worktree'])\n const spinner = args.json ? null : createSpinner()\n spinner?.start(`Preparing to drop ${explicitId ?? 'workspace'}…`)\n if (!findAppDir() && explicitId) {\n const { api } = await resolveApiOnly(appArg)\n const { view } = await api.dropWorkspace(explicitId)\n spinner?.stop()\n if (!args.json) {\n p.log.success(\n `Dropped ${explicitId}. Its ref sticks around briefly for undo, then is reaped.`,\n )\n }\n return { data: { workspaceId: explicitId, status: view.workspace.status } }\n }\n\n const { appDir, api } = await resolveTarget(appArg)\n const id = inferWorkspaceId(appDir, explicitId)\n const ownLinkedWorktree = inOwnLinkedWorktree(appDir, id)\n const cleanupOwnsCheckout = !ownLinkedWorktree || isManagedWorkspaceWorktree(appDir, id)\n if (!keepWorktree && cleanupOwnsCheckout && !isWorkTreeClean(appDir)) {\n const dropArgv = ['deepspace', 'workspace', 'drop', ...(explicitId ? [explicitId] : [])]\n const dropNext = humanCommand(dropArgv)\n throw new Refusal(\n `The worktree has uncommitted changes and cleanup would remove it. Commit them to the workspace branch and re-run \\`${dropNext}\\`, or pass \\`--keep-worktree\\` to drop while keeping the worktree. Nothing was dropped.`,\n 'dirty_worktree',\n { extra: { workspaceId: id } },\n )\n }\n\n const { view } = await api.dropWorkspace(id)\n spinner?.message(`Cleaning up ${id} locally…`)\n const cleanup = keepWorktree ? null : cleanupWorkspaceLocal(appDir, id, null)\n const inOwnWorktree = !cleanup && ownLinkedWorktree\n const retainedWorktree =\n cleanup?.worktreeRetained ?? (keepWorktree || inOwnWorktree ? appDir : null)\n const data = {\n workspaceId: id,\n status: view.workspace.status,\n ...(retainedWorktree ? { worktree: retainedWorktree } : {}),\n ...(cleanup ? { cleanup: cleanupJson(cleanup) } : {}),\n }\n spinner?.stop()\n if (!args.json) {\n p.log.success(`Dropped ${id}. Its ref sticks around briefly for undo, then is reaped.`)\n if (cleanup && !cleanup.error) reportCleanupHuman(cleanup)\n else if (retainedWorktree) p.log.info(`Retained checkout: ${retainedWorktree}`)\n }\n if (cleanup?.error) {\n const action: CliAction = cleanupAction({\n worktreeDir: cleanup.worktreeDir,\n branch: cleanup.branch,\n })\n throw new Refusal(\n cleanupRefusalMessage({\n error: cleanup.error,\n worktreeDir: cleanup.worktreeDir,\n branch: cleanup.branch,\n }),\n 'cleanup_incomplete',\n { actionRequired: true, action, extra: data },\n )\n }\n return { data }\n },\n})\n","/**\n * `deepspace activity` — the app's coordination feed: pushes, workspace\n * lifecycle and releases, merged and cursored. This is how an\n * agent answers \"did trunk move / did a workspace land / did someone\n * deploy?\" without cloning anything.\n *\n * deepspace activity [--since <cursor|now>] [--limit N] [--json]\n * deepspace activity --follow # poll loop (Ctrl-C to stop)\n *\n * Agents own their cursor: keep the returned value and pass it back as\n * `--since`. Follow starts at \"now\" unless an explicit cursor is supplied,\n * then streams one NDJSON record per fact. There is deliberately no shared\n * machine cursor for sibling agents to consume from each other.\n *\n * Defined with the command runtime (lib/command.ts): `--json`, the envelope,\n * the slug, and the exit codes come from there, not from this file. The one\n * exception is `--follow --json`, a documented NDJSON *stream* that never\n * returns — it emits a ready frame, then one frame per activity or transport\n * error.\n */\n\nimport * as p from '@clack/prompts'\nimport { ensureToken } from '../auth'\nimport { resolveAppTarget, assertAppTargetResolvable } from '../lib/app-target'\nimport { deployBaseUrl } from '../lib/vc-remote'\nimport { repoApi, type RemoteActivityEvent } from '../lib/repo-api'\nimport { actorLabels } from '../lib/actor-labels'\nimport { parseLimitArg, parseCursorArg } from '../lib/citty-args'\nimport { defineDeepspaceCommand, Refusal } from '../lib/command'\nimport { errorCode } from '../lib/cli-errors'\nimport { createSpinner } from '../lib/spinner'\n\nconst FOLLOW_INTERVAL_MS = 5_000\n\n/** landedOid → workspace id for a page of events. A land reaches the feed as\n * a trunk `push` followed by `workspace.landed`, and the undifferentiated\n * push reads as someone pushing directly to trunk (a live study's only\n * misreading of shared state). Correlating within the page labels it. */\nexport function landIndex(events: RemoteActivityEvent[]): Map<string, string> {\n const m = new Map<string, string>()\n for (const e of events) {\n if (e.kind !== 'workspace.landed') continue\n const s = (e.summary ?? {}) as Record<string, unknown>\n if (typeof s.landedOid === 'string' && e.subjectId) m.set(s.landedOid, e.subjectId)\n }\n return m\n}\n\nexport function formatEvent(\n e: RemoteActivityEvent,\n lands?: Map<string, string>,\n actors?: Map<string, string>,\n): string {\n const s = (e.summary ?? {}) as Record<string, unknown>\n const short = (oid: unknown) => (typeof oid === 'string' ? oid.slice(0, 10) : '?')\n const who = (id: unknown) =>\n typeof id === 'string' ? (actors?.get(id) ?? id) : String(id ?? '?')\n let detail = ''\n switch (e.kind) {\n case 'push': {\n const refs = Array.isArray(s.refs) ? (s.refs as Array<{ ref?: string; newOid?: string }>) : []\n detail = refs\n .map((r) => `${String(r.ref ?? '').replace('refs/heads/', '')} → ${short(r.newOid)}`)\n .join(', ')\n const landWs = refs\n .map((r) => (typeof r.newOid === 'string' ? lands?.get(r.newOid) : undefined))\n .find(Boolean)\n if (landWs) detail += ` (land of ${landWs})`\n break\n }\n case 'workspace.created':\n detail = `\"${String(s.task ?? '')}\" from ${short(s.baseOid)}`\n break\n case 'workspace.synced':\n detail = `→ ${short(s.headOid)} (${Number(s.files ?? 0)} files vs base)`\n break\n case 'workspace.landed':\n detail = `\"${String(s.task ?? '')}\" → ${short(s.landedOid)} on ${String(s.into ?? 'trunk')}`\n break\n case 'workspace.dropped':\n detail = `\"${String(s.task ?? '')}\"`\n break\n case 'release.deploy':\n case 'release.rollback':\n detail = `#${Number(s.seq ?? 0)} ${short(s.commitOid)}`\n break\n // Unknown kinds still print their kind + actor — never crash the feed.\n default:\n detail = ''\n }\n return `#${e.seq} ${e.createdAt} ${e.kind} ${who(e.actor)} ${detail}`.trimEnd()\n}\n\nexport default defineDeepspaceCommand({\n meta: {\n name: 'activity',\n description: \"The app's coordination feed (pushes, workspaces, releases)\",\n },\n args: {\n since: {\n type: 'string',\n description:\n 'Events after this cursor, or \"now\". One-shot defaults to 0; follow defaults to now',\n required: false,\n },\n limit: { type: 'string', description: 'Max events per page (default 50)', required: false },\n follow: {\n type: 'boolean',\n description: 'Keep polling for new events (Ctrl-C to stop)',\n default: false,\n },\n app: {\n type: 'string',\n alias: 'a',\n description:\n 'App id or subdomain name (default: DEEPSPACE_APP_ID from the nearest wrangler.toml)',\n required: false,\n },\n },\n async run({ args }) {\n const appArg = args.app as string | undefined\n // Validate cheap args before any auth/network round-trip. A malformed\n // cursor must FAIL, not silently coerce — an agent with a corrupted saved\n // cursor would otherwise replay full history and mistake it for new\n // activity (parseCursorArg also rejects a fractional cursor rather than\n // flooring it to an earlier page).\n const fromNow = args.since === 'now'\n const { cursor: startCursor, error: cursorError } = fromNow\n ? { cursor: 0, error: null }\n : parseCursorArg(args.since)\n if (cursorError) throw new Refusal(cursorError, 'invalid_cursor')\n const { limit, error: limitError } = parseLimitArg(args.limit)\n if (limitError) throw new Refusal(limitError, 'invalid_limit')\n // Blank --app / missing app context is a client-side error — reject it\n // BEFORE the token read so it never surfaces as not_authenticated.\n assertAppTargetResolvable(appArg)\n const spinner = args.json ? null : createSpinner()\n spinner?.start(args.follow ? 'Starting activity feed…' : 'Loading activity…')\n const token = await ensureToken()\n // Activity is a pure server read — usable from anywhere with -a; the\n // wrangler.toml default applies when run inside an app dir.\n const appId = await resolveAppTarget(deployBaseUrl(), token, appArg)\n const initialApi = repoApi(deployBaseUrl(), token, appId)\n // A follower starts after the latest committed event unless the caller\n // supplied a cursor. The tail read and later activity writes serialize in\n // the same repo DO, so an event cannot slip through the handoff.\n let cursor =\n fromNow || (args.follow && args.since === undefined)\n ? (await initialApi.listActivity({ tail: true })).cursor\n : startCursor\n\n // Human view only: resolve actor ids to emails once per invocation —\n // raw ids stay in --json (stable surface).\n const actors = args.json ? undefined : await actorLabels(token, appId)\n if (args.follow) {\n spinner?.stop(`Following activity after #${cursor} (Ctrl-C to stop).`)\n if (args.json) {\n console.log(JSON.stringify({ type: 'ready', appId, cursor }))\n }\n }\n for (;;) {\n try {\n // Refresh through the normal session path each iteration. A follow\n // process commonly outlives the short JWT it started with.\n const pageToken = args.follow ? await ensureToken() : token\n const page = await repoApi(deployBaseUrl(), pageToken, appId).listActivity({\n since: cursor,\n limit,\n })\n if (!args.follow) {\n spinner?.stop(\n `Loaded ${page.events.length} ${page.events.length === 1 ? 'event' : 'events'}.`,\n )\n }\n if (args.json) {\n // Follow is an NDJSON stream: one fact per line lets an agent react\n // immediately without unpacking page envelopes.\n if (args.follow) {\n for (const event of page.events) {\n console.log(JSON.stringify({ type: 'activity', appId, cursor: event.seq, event }))\n }\n }\n } else {\n const lands = landIndex(page.events)\n for (const e of page.events) console.log(formatEvent(e, lands, actors))\n if (page.events.length === 0 && !args.follow) {\n p.log.info(cursor > 0 ? `No activity after #${cursor}.` : 'No activity yet.')\n }\n }\n cursor = page.cursor\n const result = { data: { events: page.events, cursor: page.cursor, hasMore: page.hasMore } }\n if (args.json && !args.follow) {\n // Exactly one JSON document per one-shot invocation. The caller\n // pages explicitly while hasMore is true.\n return result\n }\n if (!args.follow) {\n if (page.events.length > 0) {\n p.log.info(\n `Cursor: ${cursor}` +\n (page.hasMore\n ? ` · more available (next page: --since ${cursor})`\n : ` (resume later with --since ${cursor})`),\n )\n }\n // A feed reports facts only. Recovery actions belong to the command\n // that actually refuses an operation.\n return result\n }\n if (page.hasMore) continue // a follower drains its backlog before sleeping\n } catch (error) {\n if (!args.follow) throw error\n const code = errorCode(error) ?? 'network_error'\n if (args.json) {\n console.log(\n JSON.stringify({\n type: 'transport',\n appId,\n state: 'retrying',\n cursor,\n retryInMs: FOLLOW_INTERVAL_MS,\n code,\n }),\n )\n } else {\n p.log.warn(`Activity feed interrupted (${code}); retrying in 5s.`)\n }\n }\n await new Promise((resolveSleep) => setTimeout(resolveSleep, FOLLOW_INTERVAL_MS))\n }\n },\n})\n","/**\n * `deepspace git-credential` — a standard git credential helper.\n *\n * `ensureSpaceRemote` installs it host-scoped\n * (`credential.<scheme>://<host>.helper`), so once any sync command has run,\n * plain `git push space` / `git fetch space` work in any terminal: git asks\n * this helper, and it answers with the logged-in DeepSpace bearer token as\n * the password (the server ignores the username).\n *\n * Protocol (git-credential(7)): the op arrives as argv (`get`/`store`/\n * `erase`), the request as `key=value` lines on stdin up to a blank line,\n * and the answer as `key=value` lines on stdout. This helper never prompts,\n * never logs the token, and always exits 0 — for a non-DeepSpace host or a\n * logged-out user its STDOUT stays silent so git falls through to its other\n * helpers (or fails the request with the server's 401). A declined `get`\n * leaves a one-line stderr breadcrumb, because the downstream git failure\n * (\"could not read Username\") never says WHY no credentials came back.\n */\n\nimport { defineCommand } from 'citty'\nimport { ensureToken } from '../auth'\nimport { deployBaseUrl } from '../lib/vc-remote'\n\nfunction parseFields(input: string): Map<string, string> {\n const fields = new Map<string, string>()\n for (const line of input.split('\\n')) {\n if (line === '') break // blank line terminates the request\n const eq = line.indexOf('=')\n if (eq > 0) fields.set(line.slice(0, eq), line.slice(eq + 1))\n }\n return fields\n}\n\n/** Does the credential request target the deploy worker (scheme + host,\n * port included — a localhost override carries one)? */\nexport function credentialHostMatches(input: string, deployUrl: string): boolean {\n let base: URL\n try {\n base = new URL(deployUrl)\n } catch {\n return false\n }\n const fields = parseFields(input)\n if (fields.get('host') !== base.host) return false\n // Fail closed on a missing protocol: git always sends one for HTTP remotes,\n // so its absence is anomalous — never hand a token to an unspecified scheme.\n const protocol = fields.get('protocol')\n return `${protocol}:` === base.protocol\n}\n\n/**\n * The helper's pure core: the exact stdout for one request. Empty string ⇒\n * print nothing (foreign host, store/erase, or no token available).\n */\nexport function respondCredential(\n op: string,\n input: string,\n token: string | null,\n deployUrl: string,\n): string {\n if (op !== 'get' || !token) return ''\n if (!credentialHostMatches(input, deployUrl)) return ''\n // Username is ignored by the server; \"deepspace\" by convention.\n return `username=deepspace\\npassword=${token}\\n`\n}\n\n/**\n * The stderr line for a declined `get` (empty string ⇒ nothing to say).\n * The helper is installed host-scoped, so a mismatch means the remote's host\n * WAS a deploy service when it was configured but the current environment\n * points elsewhere — name both so the fix (usually DEEPSPACE_DEPLOY_URL) is\n * self-evident. Never includes the token; stdout stays untouched.\n */\nexport function declineHint(\n op: string,\n input: string,\n token: string | null,\n deployUrl: string,\n): string {\n if (op !== 'get') return ''\n const host = parseFields(input).get('host')\n if (!host) return ''\n if (!credentialHostMatches(input, deployUrl)) {\n return `deepspace git-credential: no credentials for ${host} — the current deploy service is ${deployUrl}. If ${host} is your deploy service, export DEEPSPACE_DEPLOY_URL to match.\\n`\n }\n if (!token) {\n return 'deepspace git-credential: not logged in (or the session could not be refreshed) — run `deepspace auth login`.\\n'\n }\n return ''\n}\n\nasync function readStdin(): Promise<string> {\n // Git always pipes the request; a bare interactive invocation gets an\n // empty request instead of a hung read.\n if (process.stdin.isTTY) return ''\n process.stdin.setEncoding('utf-8')\n let data = ''\n for await (const chunk of process.stdin) data += chunk\n return data\n}\n\nexport default defineCommand({\n meta: {\n name: 'git-credential',\n description: 'Git credential helper (installed automatically; not for direct use)',\n },\n args: {\n op: {\n type: 'positional',\n description: 'Credential operation: get, store, or erase',\n required: false,\n },\n },\n async run({ args }) {\n const op = String(args.op ?? '')\n const input = await readStdin()\n // store/erase are silent no-ops — the token lives in ~/.deepspace, not in\n // git's credential storage.\n if (op !== 'get') return\n const url = deployBaseUrl()\n // Only touch auth for our own host: a foreign host must get an instant\n // empty answer, not a token-refresh round-trip.\n let token: string | null = null\n if (credentialHostMatches(input, url)) {\n try {\n token = await ensureToken()\n } catch {\n // Not logged in / session expired — stay silent (see header).\n }\n }\n const out = respondCredential(op, input, token, url)\n if (out) {\n process.stdout.write(out)\n } else {\n const hint = declineHint(op, input, token, url)\n if (hint) process.stderr.write(hint)\n }\n },\n})\n"],"mappings":";;;AAUA,SAAS,iBAAAA,iBAAe,SAAS,kBAAkB;AAKnD,SAAS,QAAQC,kBAAiB;AAClC,SAAS,gBAAAC,gBAAc,cAAAC,oBAAkB;AACzC,SAAS,WAAAC,WAAS,QAAAC,cAAY;AAC9B,SAAS,iBAAAC,sBAAqB;;;AClB9B,YAAY,OAAO;AAenB,IAAI,gBAAgC;AAO7B,SAAS,gBAAyB;AACvC,QAAM,OAAgB,QAAQ,OAAO,QAC/B,UAAQ,IACV;AAAA,IACE,OA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AAAA,IACF;AACA,YAAQ,IAAI,KAAK,UAAU,EAAE,IAAI,OAAO,OAAO,SAAS,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG,CAAC,CAAC;AACpF,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH,OAAO;AAEL,MAAI,CAAC,UAAW,wBAAuB,OAAO;AAC9C,UAAQ,kBAAkB,IAAI,CAAC;AACjC;","names":["defineCommand","spawnSync","readFileSync","existsSync","dirname","join","fileURLToPath","p","status","text","status","run","p","writeFileSync","mkdirSync","readFileSync","join","homedir","p","AUTH_URL","readFileSync","join","homedir","mkdirSync","writeFileSync","resolve","existsSync","readFileSync","AUTH_URL","SESSION_PATH","TOKEN_PATH","existsSync","readFileSync","existsSync","readFileSync","writeFileSync","join","join","existsSync","readFileSync","writeFileSync","resolve","basename","join","existsSync","readFileSync","join","resolve","parseToml","join","resolve","existsSync","parseToml","readFileSync","existsSync","readFileSync","writeFileSync","mkdirSync","join","resolve","dirname","isAbsolute","mkdirSync","readFileSync","dirname","join","resolve","status","resolve","join","readFileSync","mkdirSync","dirname","mkdirSync","dirname","writeFileSync","existsSync","readFileSync","join","resolve","isAbsolute","p","existsSync","readFileSync","out","writeFileSync","existsSync","readFileSync","rmSync","writeFileSync","join","parseToml","join","existsSync","writeFileSync","rmSync","readFileSync","parseToml","existsSync","readFileSync","existsSync","readFileSync","dirname","join","existsSync","readFileSync","join","pkg","join","existsSync","readFileSync","log","dirname","existsSync","resolve","status","readdirSync","rmSync","join","existsSync","join","p","join","existsSync","resolve","resolve","join","basename","spawnSync","readFileSync","readdirSync","spawnSync","readFileSync","readdirSync","resolve","spawnSync","spawnSync","DEPLOY_URL","resolve","spawnSync","spawnSync","resolve","resolve","spawnSync","defineCommand","p","readFileSync","writeFileSync","existsSync","mkdirSync","join","homedir","SESSION_COOKIE","AUTH_URL","DIR","join","homedir","existsSync","readFileSync","mkdirSync","writeFileSync","ok","defineCommand","p","defineCommand","resolve","p","execSync","existsSync","readFileSync","readdirSync","dirname","join","resolve","spinner","execSync","join","existsSync","readFileSync","resolve","dirname","readdirSync","p","existsSync","join","pathToFileURL","API_URL","errorMessage","join","existsSync","pathToFileURL","spinner","p","text","p","randomUUID","p","existsSync","isAbsolute","resolve","resolve","isAbsolute","existsSync","status","errorMessage","resolve","status","spinner","randomUUID","errorMessage","resolve","status","p","existsSync","readFileSync","errorMessage","existsSync","readFileSync","DEPLOY_URL","defineCommand","resolve","spinner","errorMessage","p","app","DEPLOY_URL","DEPLOY_URL","defineCommand","DEPLOY_URL","status","sleep","defineCommand","token","API_URL","existsSync","readFileSync","realpathSync","dirname","join","resolve","pathToFileURL","existsSync","mkdirSync","readFileSync","readdirSync","rmSync","writeFileSync","spawnSync","tmpdir","dirname","isAbsolute","join","resolve","dirname","join","existsSync","pkg","readFileSync","readdirSync","isAbsolute","resolve","mkdirSync","writeFileSync","spawnSync","tmpdir","rmSync","existsSync","join","pkg","readFileSync","dirname","realpathSync","pathToFileURL","info","resolve","defineCommand","API_URL","DEPLOY_URL","confirm","resolve","ok","list","defineCommand","defineCommand","API_URL","DEPLOY_URL","api","list","app","p","cancel","defineCommand","defineCommand","p","API_URL","DEPLOY_URL","app","status","cancel","defineCommand","defineCommand","readFileSync","p","API_URL","readFileSync","info","ok","list","defineCommand","defineCommand","existsSync","readFileSync","join","resolve","parseToml","p","intro","info","resolve","join","existsSync","parseToml","readFileSync","defineCommand","p","existsSync","readFileSync","dirname","join","fileURLToPath","API_URL","api","dirname","fileURLToPath","join","existsSync","pkg","readFileSync","detectAppName","ok","defineCommand","readFileSync","DEPLOY_URL","list","defineCommand","del","note","readFileSync","configs","defineCommand","p","existsSync","readFileSync","defineCommand","existsSync","readFileSync","spinner","reportWorkspace","reportRemoteFailure","reportRelease","api","p","spinner","resolveTarget","token","appId","action","ok","p","realpathSync","realpathSync","selectedBranchCheckout","onCurrent","spinner","pushCommand","branchWorktreePath","pullCommand","selectedCheckoutClean","canCheckoutHere","p","existsSync","readdirSync","rmSync","resolve","basename","join","readdirSync","existsSync","rmSync","join","resolve","spinner","basename","p","DEPLOY_URL","spinner","p","DEPLOY_URL","spinner","api","defineCommand","p","isAbsolute","resolve","p","api","p","mkdirSync","readFileSync","realpathSync","renameSync","writeFileSync","dirname","isAbsolute","join","relative","sep","realpathSync","relative","sep","isAbsolute","join","mkdirSync","dirname","writeFileSync","renameSync","readFileSync","del","remove","resolveTarget","spinner","api","resolveTarget","isAbsolute","resolve","p","existsSync","readdirSync","rmSync","isAbsolute","resolve","existsSync","readdirSync","rmSync","spinner","appId","api","token","resolveTarget","view","tip","isAbsolute","resolve","dir","action","p","spinner","api","resolveTarget","p","API_URL","spinner","api","p","spinner","api","resolveTarget","p","spawnSync","readFileSync","join","pkg","readFileSync","join","spawnSync","spinner","api","resolveTarget","run","p","spinner","api","view","resolveTarget","defineCommand","p","formatEvent","spinner","defineCommand","defineCommand","dirname","fileURLToPath","readFileSync","join","existsSync","create","defineCommand","rawArgs","spawnSync","editDistance"]}
|