@tinycloud/cli 0.6.0-beta.2 → 0.6.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +38 -10
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/output/errors.ts","../src/config/constants.ts","../src/output/formatter.ts","../src/output/theme.ts","../src/output/taglines.ts","../src/output/banner.ts","../src/config/profiles.ts","../src/config/storage.ts","../src/auth/local-key.ts","../src/auth/browser-auth.ts","../src/commands/init.ts","../src/commands/auth.ts","../src/config/types.ts","../src/lib/sdk.ts","../src/lib/permissions.ts","../src/lib/space.ts","../src/commands/kv.ts","../src/commands/space.ts","../src/lib/duration.ts","../src/commands/delegation.ts","../src/commands/share.ts","../src/commands/node.ts","../src/commands/profile.ts","../src/commands/completion.ts","../src/commands/vault.ts","../src/commands/secrets.ts","../src/commands/vars.ts","../src/commands/doctor.ts","../src/commands/sql.ts","../src/commands/duckdb.ts","../src/commands/manifest.ts","../src/commands/upgrade.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport { handleError } from \"./output/errors.js\";\nimport { emitBanner } from \"./output/banner.js\";\n\nconst { version } = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\")\n);\nimport { theme } from \"./output/theme.js\";\nimport { isInteractive } from \"./output/formatter.js\";\nimport { ProfileManager } from \"./config/profiles.js\";\nimport { registerInitCommand } from \"./commands/init.js\";\nimport { registerAuthCommand } from \"./commands/auth.js\";\nimport { registerKvCommand } from \"./commands/kv.js\";\nimport { registerSpaceCommand } from \"./commands/space.js\";\nimport { registerDelegationCommand } from \"./commands/delegation.js\";\nimport { registerShareCommand } from \"./commands/share.js\";\nimport { registerNodeCommand } from \"./commands/node.js\";\nimport { registerProfileCommand } from \"./commands/profile.js\";\nimport { registerCompletionCommand } from \"./commands/completion.js\";\nimport { registerVaultCommand } from \"./commands/vault.js\";\nimport { registerSecretsCommand } from \"./commands/secrets.js\";\nimport { registerVarsCommand } from \"./commands/vars.js\";\nimport { registerDoctorCommand } from \"./commands/doctor.js\";\nimport { registerSqlCommand } from \"./commands/sql.js\";\nimport { registerDuckdbCommand } from \"./commands/duckdb.js\";\nimport { registerManifestCommand } from \"./commands/manifest.js\";\nimport { registerUpgradeCommand } from \"./commands/upgrade.js\";\n\nconst program = new Command();\n\nprogram\n .name(\"tc\")\n .description(\"TinyCloud CLI — self-sovereign storage from the terminal\")\n .version(version)\n .option(\"-p, --profile <name>\", \"Profile to use\")\n .option(\"-H, --host <url>\", \"TinyCloud node URL\")\n .option(\"-v, --verbose\", \"Enable verbose output\")\n .option(\"--no-cache\", \"Disable caching\")\n .option(\"-q, --quiet\", \"Suppress non-essential output\")\n .option(\"--json\", \"Force JSON output\");\n\nprogram.hook(\"preAction\", async (thisCommand) => {\n const opts = thisCommand.optsWithGlobals();\n if (!opts.quiet) {\n emitBanner(version);\n }\n\n // Config guard — warn if not configured for auth-required commands\n const commandName = thisCommand.name();\n const parentName = thisCommand.parent?.name();\n const fullCommand = parentName && parentName !== \"tc\" ? `${parentName} ${commandName}` : commandName;\n const skipGuard = [\"tc\", \"init\", \"doctor\", \"completion\", \"help\", \"upgrade\"].includes(commandName) ||\n fullCommand === \"profile create\";\n if (!skipGuard && !opts.quiet && isInteractive()) {\n try {\n const config = await ProfileManager.getConfig();\n const profileName = opts.profile || config.defaultProfile;\n const hasProfile = await ProfileManager.profileExists(profileName);\n if (!hasProfile) {\n process.stderr.write(theme.warn(\"⚠ No profile configured.\") + \" \" + theme.muted(\"Run: tc init\") + \"\\n\\n\");\n } else {\n const key = await ProfileManager.getKey(profileName);\n if (!key) {\n process.stderr.write(theme.warn(\"⚠ No key found.\") + \" \" + theme.muted(\"Run: tc init\") + \"\\n\\n\");\n }\n }\n } catch {\n // Config dir doesn't exist yet — that's fine, commands will handle it\n }\n }\n});\n\nregisterInitCommand(program);\nregisterAuthCommand(program);\nregisterKvCommand(program);\nregisterSpaceCommand(program);\nregisterDelegationCommand(program);\nregisterShareCommand(program);\nregisterNodeCommand(program);\nregisterProfileCommand(program);\nregisterCompletionCommand(program);\nregisterVaultCommand(program);\nregisterSecretsCommand(program);\nregisterVarsCommand(program);\nregisterDoctorCommand(program);\nregisterSqlCommand(program);\nregisterDuckdbCommand(program);\nregisterManifestCommand(program);\nregisterUpgradeCommand(program);\n\nprogram.addHelpText(\"afterAll\", () => {\n if (!process.stdout.isTTY) return \"\";\n return `\n${theme.heading(\"Examples:\")}\n ${theme.command(\"tc init\")} ${theme.muted(\"Set up a profile and generate keys\")}\n ${theme.command(\"tc auth login\")} ${theme.muted(\"Authenticate via browser\")}\n ${theme.command('tc kv put greeting \"Hello\"')} ${theme.muted(\"Store a value\")}\n ${theme.command(\"tc kv list\")} ${theme.muted(\"List all keys\")}\n ${theme.command(\"tc secrets network init\")} ${theme.muted(\"Create the default secrets network\")}\n ${theme.command(\"tc delegation create --to did:pkh:...\")} ${theme.muted(\"Grant access to another user\")}\n ${theme.command(\"tc space list\")} ${theme.muted(\"Show your spaces\")}\n\n${theme.muted(\"Docs:\")} ${theme.accent(\"https://docs.tinycloud.xyz/cli\")}\n${theme.muted(\"Repo:\")} ${theme.accent(\"https://github.com/tinycloudlabs/web-sdk\")}\n`;\n});\n\ntry {\n await program.parseAsync(process.argv);\n} catch (error) {\n handleError(error);\n}\n","import { readFileSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { ExitCode, CONFIG_FILE, PROFILES_DIR, DEFAULT_PROFILE } from \"../config/constants.js\";\nimport { outputError } from \"./formatter.js\";\n\nlet activeProfileName: string | undefined;\n\n/** Recorded by ProfileManager.resolveContext so hints can name the right profile. */\nexport function setActiveProfileName(name: string): void {\n activeProfileName = name;\n}\n\nexport class CLIError extends Error {\n constructor(\n public code: string,\n message: string,\n public exitCode: number = ExitCode.ERROR,\n public metadata?: Record<string, unknown>,\n ) {\n super(message);\n this.name = \"CLIError\";\n }\n}\n\nexport function wrapError(error: unknown): CLIError {\n if (error instanceof CLIError) return error;\n\n const message = error instanceof Error ? error.message : String(error);\n\n // Map known error patterns to exit codes\n if (message.includes(\"Not signed in\") || message.includes(\"AUTH_EXPIRED\") || message.includes(\"Session expired\")) {\n return new CLIError(\"AUTH_REQUIRED\", message, ExitCode.AUTH_REQUIRED);\n }\n if (message.includes(\"NOT_FOUND\") || message.includes(\"KV_NOT_FOUND\")) {\n return new CLIError(\"NOT_FOUND\", message, ExitCode.NOT_FOUND);\n }\n if (message.includes(\"PERMISSION_DENIED\")) {\n return new CLIError(\"PERMISSION_DENIED\", message, ExitCode.PERMISSION_DENIED);\n }\n if (message.includes(\"ECONNREFUSED\") || message.includes(\"ETIMEDOUT\") || message.includes(\"fetch failed\")) {\n return new CLIError(\"NETWORK_ERROR\", message, ExitCode.NETWORK_ERROR);\n }\n\n return new CLIError(\"ERROR\", message, ExitCode.ERROR);\n}\n\nexport function handleError(error: unknown): never {\n const cliError = wrapError(error);\n const hint = buildAuthHint(cliError) ??\n (cliError.code === \"NETWORK_ERROR\" ? buildNetworkHint() : undefined);\n outputError(cliError.code, cliError.message, hint);\n process.exit(cliError.exitCode);\n}\n\nfunction buildAuthHint(error: CLIError): string | undefined {\n const resource = error.metadata?.resource;\n const requiredAction = error.metadata?.requiredAction;\n if (typeof resource !== \"string\" || typeof requiredAction !== \"string\") {\n return undefined;\n }\n\n const spec = capSpecFromAuthMeta(resource, requiredAction);\n if (!spec) return undefined;\n return [\n \"The active session is missing a TinyCloud capability.\",\n `Request it with: tc auth request --cap \"${spec}\"`,\n \"Then retry the original command.\",\n ].join(\"\\n\");\n}\n\nfunction capSpecFromAuthMeta(resource: string, action: string): string | undefined {\n const slash = resource.indexOf(\"/\");\n if (slash <= 0 || slash === resource.length - 1) return undefined;\n const spaceUri = resource.slice(0, slash);\n const rest = resource.slice(slash + 1);\n const nextSlash = rest.indexOf(\"/\");\n if (nextSlash <= 0) return undefined;\n\n const serviceShort = rest.slice(0, nextSlash);\n const path = rest.slice(nextSlash + 1);\n const actionName = action.includes(\"/\") ? action.slice(action.indexOf(\"/\") + 1) : action;\n const spaceName = spaceUri.startsWith(\"tinycloud:\")\n ? spaceUri.slice(spaceUri.lastIndexOf(\":\") + 1)\n : spaceUri;\n return `tinycloud.${serviceShort}:${spaceName}:${path}:${actionName}`;\n}\n\n/**\n * Suggests alternate profiles when the active profile's host is unreachable.\n * Sync fs reads keep handleError synchronous so call sites don't need to await.\n *\n * Silent fallback to a default host is intentionally NOT done: different hosts\n * back different data stores, so an automatic switch could split or clobber\n * user data without their knowledge.\n */\nfunction buildNetworkHint(): string | undefined {\n const readHost = (name: string): string | undefined => {\n try {\n const raw = readFileSync(join(PROFILES_DIR, name, \"profile.json\"), \"utf8\");\n return (JSON.parse(raw) as { host?: string }).host;\n } catch {\n return undefined;\n }\n };\n\n let activeName = activeProfileName ?? process.env.TC_PROFILE ?? DEFAULT_PROFILE;\n if (!activeProfileName) {\n try {\n const cfg = JSON.parse(readFileSync(CONFIG_FILE, \"utf8\")) as { defaultProfile?: string };\n activeName = process.env.TC_PROFILE ?? cfg.defaultProfile ?? DEFAULT_PROFILE;\n } catch {\n // Config file not present yet — fall through with env/default.\n }\n }\n\n let names: string[];\n try {\n names = readdirSync(PROFILES_DIR);\n } catch {\n return undefined;\n }\n\n const activeHost = readHost(activeName);\n const others = names\n .filter((n) => n !== activeName)\n .map((n) => ({ name: n, host: readHost(n) }))\n .filter((p): p is { name: string; host: string } => Boolean(p.host));\n\n const lines: string[] = [];\n lines.push(activeHost ? `Active profile \"${activeName}\" → ${activeHost}` : `Active profile \"${activeName}\"`);\n\n if (others.length === 0) {\n lines.push(`No other profiles configured. Run \\`tc profile create <name>\\` or \\`tc init\\`.`);\n } else {\n lines.push(`Switch to a reachable profile:`);\n const longest = Math.max(...others.map((p) => p.name.length));\n for (const { name, host } of others) {\n lines.push(` tc profile switch ${name.padEnd(longest)} # ${host}`);\n }\n }\n lines.push(`Or override per-command with --host or TC_HOST.`);\n return lines.join(\"\\n\");\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const CONFIG_DIR = join(homedir(), \".tinycloud\");\nexport const PROFILES_DIR = join(CONFIG_DIR, \"profiles\");\nexport const CONFIG_FILE = join(CONFIG_DIR, \"config.json\");\n\nexport const DEFAULT_HOST = \"https://node.tinycloud.xyz\";\nexport const DEFAULT_OPENKEY_HOST = \"https://openkey.so\";\nexport const DEFAULT_PROFILE = \"default\";\nexport const DEFAULT_CHAIN_ID = 1;\n\nexport const ExitCode = {\n SUCCESS: 0,\n ERROR: 1,\n USAGE_ERROR: 2,\n AUTH_REQUIRED: 3,\n NOT_FOUND: 4,\n PERMISSION_DENIED: 5,\n NETWORK_ERROR: 6,\n NODE_ERROR: 7,\n} as const;\n","import ora from \"ora\";\nimport { theme } from \"./theme.js\";\n\nexport function outputJson(data: unknown): void {\n process.stdout.write(JSON.stringify(data, null, 2) + \"\\n\");\n}\n\nexport function outputError(code: string, message: string, hint?: string): void {\n if (isInteractive()) {\n process.stderr.write(\n `${theme.error(\"✗\")} ${theme.label(code)}: ${message}\\n`\n );\n if (hint) {\n for (const line of hint.split(\"\\n\")) {\n process.stderr.write(` ${theme.hint(line)}\\n`);\n }\n }\n } else {\n const payload: { error: { code: string; message: string; hint?: string } } = {\n error: { code, message },\n };\n if (hint) payload.error.hint = hint;\n process.stderr.write(JSON.stringify(payload, null, 2) + \"\\n\");\n }\n}\n\nexport function isInteractive(): boolean {\n return Boolean(process.stdout.isTTY);\n}\n\nexport async function withSpinner<T>(label: string, fn: () => Promise<T>): Promise<T> {\n if (!isInteractive()) {\n return fn();\n }\n const spinner = ora(label).start();\n try {\n const result = await fn();\n spinner.succeed(label);\n return result;\n } catch (error) {\n spinner.fail(label);\n throw error;\n }\n}\n\n/** Check if output should be JSON (non-TTY or --json flag) */\nexport function shouldOutputJson(): boolean {\n return !isInteractive() || process.argv.includes(\"--json\");\n}\n\n/** Format a key-value pair for human display */\nexport function formatField(label: string, value: string | number | boolean | null | undefined): string {\n if (value === null || value === undefined) return ` ${theme.label(label + \":\")} ${theme.muted(\"—\")}`;\n if (typeof value === \"boolean\") {\n return ` ${theme.label(label + \":\")} ${value ? theme.success(\"yes\") : theme.muted(\"no\")}`;\n }\n return ` ${theme.label(label + \":\")} ${theme.value(String(value))}`;\n}\n\n/** Format a list of items as a simple table */\nexport function formatTable(headers: string[], rows: string[][]): string {\n // Calculate column widths\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map(r => (r[i] || \"\").length))\n );\n\n const headerLine = headers.map((h, i) => theme.label(h.padEnd(widths[i]))).join(\" \");\n const separator = widths.map(w => theme.dim(\"─\".repeat(w))).join(\" \");\n const dataLines = rows.map(row =>\n row.map((cell, i) => (cell || \"\").padEnd(widths[i])).join(\" \")\n );\n\n return [headerLine, separator, ...dataLines].join(\"\\n\");\n}\n\n/** Output data in either JSON or human-friendly format */\nexport function output(data: unknown, humanFormatter?: () => string): void {\n if (shouldOutputJson() || !humanFormatter) {\n outputJson(data);\n } else {\n process.stdout.write(humanFormatter() + \"\\n\");\n }\n}\n\n/** Format a status check line (for doctor command etc.) */\nexport function formatCheck(ok: boolean | \"warn\", label: string, detail?: string): string {\n const icon = ok === \"warn\" ? theme.warn(\"⚠\") : ok ? theme.success(\"✓\") : theme.error(\"✗\");\n const detailStr = detail ? ` ${theme.muted(`(${detail})`)}` : \"\";\n return `${icon} ${label}${detailStr}`;\n}\n\n/** Format a section heading */\nexport function formatSection(title: string): string {\n return `\\n${theme.heading(title)}`;\n}\n\n/** Format bytes to human readable */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/** Format relative time */\nexport function formatTimeAgo(date: Date | string): string {\n const d = typeof date === \"string\" ? new Date(date) : date;\n const seconds = Math.floor((Date.now() - d.getTime()) / 1000);\n if (seconds < 60) return \"just now\";\n if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;\n if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;\n return `${Math.floor(seconds / 86400)}d ago`;\n}\n","import chalk from \"chalk\";\n\nexport const TC_PALETTE = {\n primary: \"#4473b9\",\n accent: \"#5b9bd5\",\n success: \"#2fba6a\",\n warn: \"#e8a838\",\n error: \"#d94040\",\n muted: \"#808080\",\n dim: \"#5a5a5a\",\n} as const;\n\nexport const theme = {\n primary: chalk.hex(TC_PALETTE.primary),\n accent: chalk.hex(TC_PALETTE.accent),\n success: chalk.hex(TC_PALETTE.success),\n warn: chalk.hex(TC_PALETTE.warn),\n error: chalk.hex(TC_PALETTE.error),\n muted: chalk.hex(TC_PALETTE.muted),\n dim: chalk.hex(TC_PALETTE.dim),\n heading: chalk.bold.hex(TC_PALETTE.primary),\n command: chalk.hex(TC_PALETTE.accent),\n brand: chalk.bold.hex(TC_PALETTE.primary),\n label: chalk.bold,\n value: chalk.white,\n hint: chalk.italic.hex(TC_PALETTE.muted),\n};\n","interface HolidayTagline {\n month: number;\n day: number;\n range?: number; // days before/after to show\n tagline: string;\n}\n\nconst HOLIDAY_TAGLINES: HolidayTagline[] = [\n { month: 1, day: 1, range: 1, tagline: \"New year, new keys, same cloud.\" },\n { month: 2, day: 14, tagline: \"We love your data as much as you do.\" },\n { month: 3, day: 14, tagline: \"3.14159 reasons to encrypt everything.\" },\n { month: 5, day: 4, tagline: \"May the fourth be with your keys.\" },\n { month: 10, day: 31, tagline: \"Nothing scarier than plaintext secrets.\" },\n { month: 12, day: 25, range: 2, tagline: \"Unwrap your data, not your keys.\" },\n { month: 12, day: 31, tagline: \"Encrypt your resolutions.\" },\n];\n\nconst TAGLINES = [\n // Professional\n \"Your data, your keys, your cloud.\",\n \"Self-sovereign storage for the modern web.\",\n \"The cloud you actually own.\",\n \"Encrypted by default, decentralized by design.\",\n \"Where your data answers only to you.\",\n \"End-to-end encrypted. No exceptions.\",\n \"Like S3 but you hold the keys.\",\n \"Privacy isn't a feature. It's the architecture.\",\n \"Sovereign storage, zero knowledge.\",\n \"Your .env is safe here — we use real cryptography.\",\n // Playful / nerdy\n \"UCAN do anything.\",\n \"Keys generated, delegations granted, data liberated.\",\n \"Decentralized storage, centralized vibes.\",\n \"Trust nobody, delegate everything.\",\n \"sudo make me a sandwich, encrypted.\",\n \"Have you tried turning your keys off and on again?\",\n \"All your base are belong to you.\",\n \"In UCAN we trust.\",\n \"0 knowledge, 100% confidence.\",\n \"Keeping secrets since 2024.\",\n];\n\nfunction getHolidayTagline(): string | null {\n const now = new Date();\n const month = now.getMonth() + 1;\n const day = now.getDate();\n\n for (const h of HOLIDAY_TAGLINES) {\n const range = h.range ?? 0;\n if (h.month === month && Math.abs(day - h.day) <= range) {\n return h.tagline;\n }\n }\n return null;\n}\n\nexport function pickTagline(): string {\n const holiday = getHolidayTagline();\n if (holiday) return holiday;\n return TAGLINES[Math.floor(Math.random() * TAGLINES.length)];\n}\n","import { isInteractive } from \"./formatter.js\";\nimport { pickTagline } from \"./taglines.js\";\nimport { theme } from \"./theme.js\";\nimport { execSync } from \"node:child_process\";\n\nlet bannerEmitted = false;\n\nfunction resolveCommitHash(): string | null {\n try {\n return (\n execSync(\"git rev-parse --short HEAD\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim() || null\n );\n } catch {\n return null;\n }\n}\n\nfunction formatBannerLine(version: string): string {\n const commit = resolveCommitHash();\n const tagline = pickTagline();\n\n const versionPart = `tc v${version}`;\n const commitPart = commit ? ` (${commit})` : \"\";\n const separator = \" — \";\n\n if (!isInteractive()) {\n return `${versionPart}${commitPart}${separator}${tagline}`;\n }\n\n return [\n theme.brand(\"☁️ tc\"),\n \" \",\n theme.muted(`v${version}`),\n commit ? theme.dim(` (${commit})`) : \"\",\n theme.dim(separator),\n theme.primary(tagline),\n ].join(\"\");\n}\n\nexport function emitBanner(version: string): void {\n if (bannerEmitted) return;\n if (!isInteractive()) return;\n if (process.env.TC_HIDE_BANNER === \"1\") return;\n\n bannerEmitted = true;\n process.stderr.write(formatBannerLine(version) + \"\\n\\n\");\n}\n","import { join } from \"node:path\";\nimport {\n CONFIG_DIR,\n PROFILES_DIR,\n CONFIG_FILE,\n DEFAULT_PROFILE,\n DEFAULT_HOST,\n} from \"./constants.js\";\nimport { rm } from \"node:fs/promises\";\nimport {\n readJson,\n writeJson,\n fileExists,\n ensureDir,\n removeDir,\n listDirs,\n} from \"./storage.js\";\nimport type { GlobalConfig, ProfileConfig, CLIContext } from \"./types.js\";\nimport { CLIError, setActiveProfileName } from \"../output/errors.js\";\n\nexport class ProfileManager {\n // ── Initialization ──────────────────────────────────────────────────\n\n /**\n * Creates ~/.tinycloud/ and ~/.tinycloud/profiles/ if they don't exist.\n */\n static async ensureConfigDir(): Promise<void> {\n await ensureDir(CONFIG_DIR);\n await ensureDir(PROFILES_DIR);\n }\n\n // ── Global config ───────────────────────────────────────────────────\n\n /**\n * Reads config.json. Returns a default config if the file is missing.\n */\n static async getConfig(): Promise<GlobalConfig> {\n const config = await readJson<GlobalConfig>(CONFIG_FILE);\n if (!config) {\n return { defaultProfile: DEFAULT_PROFILE, version: 1 };\n }\n return config;\n }\n\n /**\n * Writes the global config to config.json.\n */\n static async setConfig(config: GlobalConfig): Promise<void> {\n await ProfileManager.ensureConfigDir();\n await writeJson(CONFIG_FILE, config);\n }\n\n // ── Profile CRUD ────────────────────────────────────────────────────\n\n /**\n * Returns the profile config for the given name.\n * Throws CLIError if the profile doesn't exist.\n */\n static async getProfile(name: string): Promise<ProfileConfig> {\n const profilePath = join(PROFILES_DIR, name, \"profile.json\");\n const profile = await readJson<ProfileConfig>(profilePath);\n if (!profile) {\n throw new CLIError(\n \"PROFILE_NOT_FOUND\",\n `Profile \"${name}\" does not exist. Run \\`tc init\\` or \\`tc profile create ${name}\\` first.`,\n );\n }\n return profile;\n }\n\n /**\n * Saves a profile config, creating the profile directory if needed.\n */\n static async setProfile(name: string, data: ProfileConfig): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"profile.json\"), data);\n }\n\n /**\n * Returns true if a profile directory exists.\n */\n static async profileExists(name: string): Promise<boolean> {\n return fileExists(join(PROFILES_DIR, name, \"profile.json\"));\n }\n\n /**\n * Returns an array of profile directory names.\n */\n static async listProfiles(): Promise<string[]> {\n return listDirs(PROFILES_DIR);\n }\n\n /**\n * Deletes a profile directory.\n * Throws if trying to delete the current default profile.\n */\n static async deleteProfile(name: string): Promise<void> {\n const config = await ProfileManager.getConfig();\n if (config.defaultProfile === name) {\n throw new CLIError(\n \"PROFILE_DELETE_DEFAULT\",\n `Cannot delete the default profile \"${name}\". Change the default first with \\`tc profile default <other>\\`.`,\n );\n }\n const profileDir = join(PROFILES_DIR, name);\n await removeDir(profileDir);\n }\n\n // ── Key management ──────────────────────────────────────────────────\n\n /**\n * Returns the parsed JWK for a profile, or null if no key exists.\n */\n static async getKey(name: string): Promise<object | null> {\n return readJson<object>(join(PROFILES_DIR, name, \"key.json\"));\n }\n\n /**\n * Saves a JWK key for a profile.\n */\n static async setKey(name: string, jwk: object): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"key.json\"), jwk);\n }\n\n // ── Session management ──────────────────────────────────────────────\n\n /**\n * Returns the parsed session for a profile, or null if none exists.\n */\n static async getSession(name: string): Promise<object | null> {\n return readJson<object>(join(PROFILES_DIR, name, \"session.json\"));\n }\n\n /**\n * Saves session data for a profile.\n */\n static async setSession(name: string, session: object): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"session.json\"), session);\n }\n\n /**\n * Removes the session file for a profile.\n */\n static async clearSession(name: string): Promise<void> {\n const sessionPath = join(PROFILES_DIR, name, \"session.json\");\n try {\n await rm(sessionPath);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw err;\n }\n }\n }\n\n // ── Cache management ────────────────────────────────────────────────\n\n /**\n * Returns the path to the profile's cache directory, creating it if needed.\n */\n static async getCacheDir(name: string): Promise<string> {\n const cacheDir = join(PROFILES_DIR, name, \"cache\");\n await ensureDir(cacheDir);\n return cacheDir;\n }\n\n // ── Resolution helpers ──────────────────────────────────────────────\n\n /**\n * Resolves the full CLI context from flags, env vars, and config.\n *\n * Profile resolution: options.profile > TC_PROFILE env > config.defaultProfile > \"default\"\n * Host resolution: options.host > TC_HOST env > profile.host > DEFAULT_HOST\n */\n static async resolveContext(options: {\n profile?: string;\n host?: string;\n verbose?: boolean;\n noCache?: boolean;\n quiet?: boolean;\n }): Promise<CLIContext> {\n // Resolve profile name\n const config = await ProfileManager.getConfig();\n const profile =\n options.profile ??\n process.env.TC_PROFILE ??\n config.defaultProfile ??\n DEFAULT_PROFILE;\n\n // Resolve host — try profile config if it exists, but don't fail if it doesn't\n let profileHost: string | undefined;\n try {\n const profileConfig = await ProfileManager.getProfile(profile);\n profileHost = profileConfig.host;\n } catch {\n // Profile may not exist yet (e.g., during `tc init`)\n }\n\n const host =\n options.host ??\n process.env.TC_HOST ??\n profileHost ??\n DEFAULT_HOST;\n\n setActiveProfileName(profile);\n\n return {\n profile,\n host,\n verbose: options.verbose ?? false,\n noCache: options.noCache ?? false,\n quiet: options.quiet ?? false,\n };\n }\n}\n","import { readFile, writeFile, stat, mkdir, rm, readdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\n/**\n * Read and parse a JSON file. Returns null if the file does not exist.\n * Throws on any other error (permission denied, invalid JSON, etc.).\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n const data = await readFile(filePath, \"utf-8\");\n return JSON.parse(data) as T;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n}\n\n/**\n * Write data as JSON to a file. Creates parent directories if needed.\n */\nexport async function writeJson(filePath: string, data: unknown): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, JSON.stringify(data, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Check if a file exists at the given path.\n */\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n await stat(filePath);\n return true;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw err;\n }\n}\n\n/**\n * Ensure a directory exists (mkdir -p).\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Remove a directory recursively (rm -rf).\n */\nexport async function removeDir(dirPath: string): Promise<void> {\n await rm(dirPath, { recursive: true, force: true });\n}\n\n/**\n * List directory names (not files) inside a directory.\n * Returns an empty array if the directory does not exist.\n */\nexport async function listDirs(dirPath: string): Promise<string[]> {\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return [];\n }\n throw err;\n }\n}\n","import { TCWSessionManager, importKey, initPanicHook } from \"@tinycloud/node-sdk-wasm\";\nimport { PrivateKeySigner } from \"@tinycloud/node-sdk\";\nimport { randomBytes } from \"node:crypto\";\n\nlet wasmInitialized = false;\n\nfunction ensureWasm(): void {\n if (!wasmInitialized) {\n initPanicHook();\n wasmInitialized = true;\n }\n}\n\n/**\n * Generate a new Ed25519 keypair. Returns the JWK.\n */\nexport function generateKey(): { jwk: object; did: string } {\n ensureWasm();\n const mgr = new TCWSessionManager();\n const keyId = mgr.createSessionKey(\"cli\");\n const jwkStr = mgr.jwk(keyId);\n if (!jwkStr) throw new Error(\"Failed to generate key\");\n const jwk = JSON.parse(jwkStr);\n const did = mgr.getDID(keyId);\n return { jwk, did };\n}\n\n/**\n * Get the DID from an existing JWK.\n */\nexport function keyToDID(jwk: object): string {\n ensureWasm();\n const mgr = new TCWSessionManager();\n const keyId = importKey(mgr, JSON.stringify(jwk), \"imported\");\n return mgr.getDID(keyId);\n}\n\n/**\n * Generate a new random Ethereum private key.\n * Returns the hex-encoded key with 0x prefix.\n */\nexport function generateEthereumPrivateKey(): string {\n const keyBytes = randomBytes(32);\n return \"0x\" + keyBytes.toString(\"hex\");\n}\n\n/**\n * Derive the Ethereum address from a private key.\n * Uses PrivateKeySigner from node-sdk.\n */\nexport async function deriveAddress(privateKey: string): Promise<string> {\n const signer = new PrivateKeySigner(privateKey);\n return signer.getAddress();\n}\n\n/**\n * Create a did:pkh DID from an Ethereum address.\n * Uses EIP-155 chain ID 1 (mainnet).\n */\nexport function addressToDID(address: string, chainId: number = 1): string {\n return `did:pkh:eip155:${chainId}:${address}`;\n}\n\n/**\n * Generate a new local Ethereum key and return all identity info.\n */\nexport async function generateLocalIdentity(chainId: number = 1): Promise<{\n privateKey: string;\n address: string;\n did: string;\n}> {\n const privateKey = generateEthereumPrivateKey();\n const address = await deriveAddress(privateKey);\n const did = addressToDID(address, chainId);\n return { privateKey, address, did };\n}\n\n/**\n * Sign in to TinyCloud using a local Ethereum private key.\n * Creates a TinyCloudNode with the private key and calls signIn().\n */\nexport async function localKeySignIn(options: {\n privateKey: string;\n host: string;\n}): Promise<{\n spaceId: string;\n address: string;\n chainId: number;\n delegationHeader: { Authorization: string };\n delegationCid: string;\n jwk: object;\n verificationMethod: string;\n siwe?: string;\n signature?: string;\n}> {\n const { TinyCloudNode } = await import(\"@tinycloud/node-sdk\");\n\n const node = new TinyCloudNode({\n privateKey: options.privateKey,\n host: options.host,\n autoCreateSpace: true,\n });\n\n await node.signIn();\n\n const address = await new PrivateKeySigner(options.privateKey).getAddress();\n const session = node.session;\n if (!session) {\n throw new Error(\"Local key sign-in did not produce a TinyCloud session\");\n }\n\n return {\n spaceId: session.spaceId,\n address,\n chainId: 1,\n delegationHeader: session.delegationHeader,\n delegationCid: session.delegationCid,\n jwk: session.jwk,\n verificationMethod: session.verificationMethod,\n siwe: session.siwe,\n signature: session.signature,\n };\n}\n","import type { PermissionEntry } from \"@tinycloud/node-sdk\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { isInteractive } from \"../output/formatter.js\";\nimport { createInterface } from \"node:readline\";\nimport { DEFAULT_OPENKEY_HOST } from \"../config/constants.js\";\n\ninterface DelegationData {\n delegationHeader: { Authorization: string };\n delegationCid: string;\n spaceId: string;\n [key: string]: unknown;\n}\n\ninterface AuthFlowOptions {\n paste?: boolean;\n jwk?: object;\n host?: string;\n permissions?: PermissionEntry[];\n /**\n * OpenKey base URL. Resolution order in callers: TC_OPENKEY_HOST env →\n * profile.openkeyHost → DEFAULT_OPENKEY_HOST. Threaded explicitly so this\n * module stays free of profile lookups.\n */\n openkeyHost?: string;\n /**\n * Lifetime hint for the resulting delegation. Encoded into the\n * `/delegate?expiry=<value>` URL parameter so OpenKey can sign for the\n * requested window instead of its hardcoded default. Forwarded as-is —\n * OpenKey does the parsing and clamping server-side.\n */\n expiry?: string | number;\n}\n\n/**\n * Start the browser auth flow.\n * Mode 1 (default): local HTTP callback server\n * Mode 2 (--paste): manual code paste\n */\nexport async function startAuthFlow(\n did: string,\n options: AuthFlowOptions = {}\n): Promise<DelegationData> {\n if (options.paste) {\n return pasteFlow(did, options);\n }\n\n try {\n return await callbackFlow(did, options);\n } catch {\n // Fallback to paste if browser can't open\n if (isInteractive()) {\n console.error(\"Could not open browser. Falling back to manual paste mode.\");\n return pasteFlow(did, options);\n }\n throw new Error(\"Cannot open browser in non-interactive mode. Use --paste flag.\");\n }\n}\n\nfunction buildAuthUrl(did: string, options: AuthFlowOptions & { callback?: string } = {}): string {\n const params = new URLSearchParams();\n params.set(\"did\", did);\n if (options.callback) {\n params.set(\"callback\", options.callback);\n }\n if (options.jwk) {\n // base64url-encode the JWK\n const jwkB64 = Buffer.from(JSON.stringify(options.jwk)).toString(\"base64url\");\n params.set(\"jwk\", jwkB64);\n }\n if (options.host) {\n params.set(\"host\", options.host);\n }\n if (options.permissions?.length) {\n params.set(\n \"permissions\",\n Buffer.from(JSON.stringify({ permissions: options.permissions })).toString(\"base64url\"),\n );\n }\n if (options.expiry !== undefined) {\n params.set(\"expiry\", String(options.expiry));\n }\n const base = options.openkeyHost ?? DEFAULT_OPENKEY_HOST;\n return `${base}/delegate?${params.toString()}`;\n}\n\nasync function callbackFlow(did: string, options: AuthFlowOptions = {}): Promise<DelegationData> {\n return new Promise((resolve, reject) => {\n let timeout: ReturnType<typeof setTimeout>;\n let settled = false;\n let rl: ReturnType<typeof createInterface> | undefined;\n\n function settle(result: { data?: DelegationData; error?: Error }) {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n server.close();\n if (rl) {\n rl.close();\n }\n if (result.data) {\n resolve(result.data);\n } else {\n reject(result.error);\n }\n }\n\n function parsePasteInput(input: string): DelegationData {\n const trimmed = input.trim();\n // Try parsing as JSON directly\n try {\n return JSON.parse(trimmed) as DelegationData;\n } catch {\n // Try base64 decoding first\n const decoded = Buffer.from(trimmed, \"base64\").toString(\"utf-8\");\n return JSON.parse(decoded) as DelegationData;\n }\n }\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n if (req.method === \"POST\" && req.url === \"/callback\") {\n let body = \"\";\n req.on(\"data\", (chunk: Buffer) => { body += chunk.toString(); });\n req.on(\"end\", () => {\n try {\n const data = JSON.parse(body) as DelegationData;\n // Send CORS headers and success response\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": \"*\",\n });\n res.end(JSON.stringify({ success: true }));\n settle({ data });\n } catch (err) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid JSON\" }));\n settle({ error: new Error(\"Invalid delegation data received\") });\n }\n });\n } else if (req.method === \"OPTIONS\") {\n // CORS preflight\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end();\n } else {\n res.writeHead(404);\n res.end();\n }\n });\n\n server.listen(0, \"127.0.0.1\", async () => {\n const addr = server.address();\n if (!addr || typeof addr === \"string\") {\n settle({ error: new Error(\"Failed to start callback server\") });\n return;\n }\n const port = addr.port;\n const callbackUrl = `http://127.0.0.1:${port}/callback`;\n const authUrl = buildAuthUrl(did, { ...options, callback: callbackUrl });\n\n if (isInteractive()) {\n console.error(`Opening browser for authentication...`);\n console.error(`If the browser doesn't open, visit: ${authUrl}`);\n }\n\n try {\n const open = (await import(\"open\")).default;\n await open(authUrl);\n } catch {\n server.close();\n throw new Error(\"Failed to open browser\");\n }\n\n // In interactive mode, also accept paste input while waiting for callback\n if (isInteractive()) {\n console.error(`\\nIf the browser can't connect back, paste the delegation code here:`);\n rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n rl.on(\"line\", (input) => {\n if (settled) return;\n try {\n const data = parsePasteInput(input);\n settle({ data });\n } catch {\n console.error(\"Invalid delegation code. Expected JSON or base64-encoded JSON. Try again:\");\n }\n });\n }\n });\n\n // Timeout after 5 minutes\n timeout = setTimeout(() => {\n settle({ error: new Error(\"Authentication timed out after 5 minutes\") });\n }, 5 * 60 * 1000);\n });\n}\n\nasync function pasteFlow(did: string, options: AuthFlowOptions = {}): Promise<DelegationData> {\n const authUrl = buildAuthUrl(did, options);\n\n console.error(`\\nOpen this URL in a browser to authenticate:\\n`);\n console.error(` ${authUrl}\\n`);\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n return new Promise((resolve, reject) => {\n rl.question(\"Paste delegation code: \", (input) => {\n rl.close();\n try {\n // Try parsing as JSON directly\n const data = JSON.parse(input.trim()) as DelegationData;\n resolve(data);\n } catch {\n // Try base64 decoding first\n try {\n const decoded = Buffer.from(input.trim(), \"base64\").toString(\"utf-8\");\n const data = JSON.parse(decoded) as DelegationData;\n resolve(data);\n } catch {\n reject(new Error(\"Invalid delegation code. Expected JSON or base64-encoded JSON.\"));\n }\n }\n });\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_HOST, DEFAULT_CHAIN_ID } from \"../config/constants.js\";\nimport { generateKey } from \"../auth/local-key.js\";\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\n\nexport function registerInitCommand(program: Command): void {\n program\n .command(\"init\")\n .description(\"Initialize a new TinyCloud profile\")\n .option(\"--name <profile>\", \"Profile name\", \"default\")\n .option(\"--key-only\", \"Only generate key, skip authentication\")\n .option(\"--host <url>\", \"TinyCloud node URL\")\n .option(\"--paste\", \"Use manual paste mode for authentication\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const profileName: string = options.name;\n const host: string = options.host ?? globalOpts.host ?? DEFAULT_HOST;\n\n // Check if profile already exists\n if (await ProfileManager.profileExists(profileName)) {\n throw new CLIError(\n \"PROFILE_EXISTS\",\n `Profile \"${profileName}\" already exists. Use \\`tc profile delete ${profileName}\\` first or choose a different name.`,\n ExitCode.ERROR,\n );\n }\n\n await ProfileManager.ensureConfigDir();\n\n // Generate key\n const { jwk, did } = await withSpinner(\"Generating key...\", async () => {\n return generateKey();\n });\n\n await ProfileManager.setKey(profileName, jwk);\n\n // Create initial profile\n const profileConfig = {\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n createdAt: new Date().toISOString(),\n };\n\n await ProfileManager.setProfile(profileName, profileConfig);\n\n // Set as default if this is \"default\" or no default exists\n const config = await ProfileManager.getConfig();\n if (profileName === \"default\" || !await ProfileManager.profileExists(config.defaultProfile)) {\n await ProfileManager.setConfig({ ...config, defaultProfile: profileName });\n }\n\n if (options.keyOnly) {\n outputJson({\n profile: profileName,\n did,\n host,\n authenticated: false,\n });\n return;\n }\n\n // Auth flow\n const delegationData = await startAuthFlow(did, {\n paste: options.paste,\n jwk,\n host,\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with auth data\n await ProfileManager.setProfile(profileName, {\n ...profileConfig,\n spaceId: delegationData.spaceId,\n ownerDid: delegationData.ownerDid as string | undefined,\n });\n\n outputJson({\n profile: profileName,\n did,\n host,\n spaceId: delegationData.spaceId,\n authenticated: true,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { get as httpGet } from \"node:http\";\nimport { get as httpsGet } from \"node:https\";\nimport { spawn } from \"node:child_process\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { PermissionEntry, PortableDelegation } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatField, formatTable, isInteractive, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_CHAIN_ID, DEFAULT_OPENKEY_HOST } from \"../config/constants.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type AuthMethod,\n type ProfileConfig,\n} from \"../config/types.js\";\n\n/**\n * Resolve the OpenKey base URL for a profile.\n * Order: TC_OPENKEY_HOST env override → profile.openkeyHost → default.\n *\n * No prompts, no migration. To use a self-hosted OpenKey for a profile,\n * edit `~/.tinycloud/profiles/<profile>/profile.json` and add an\n * \"openkeyHost\": \"https://openkey.localhost\" field.\n */\nfunction resolveOpenKeyHost(profile: ProfileConfig): string {\n return process.env.TC_OPENKEY_HOST ?? profile.openkeyHost ?? DEFAULT_OPENKEY_HOST;\n}\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\nimport {\n generateLocalIdentity,\n deriveAddress,\n addressToDID,\n localKeySignIn,\n generateKey,\n keyToDID,\n} from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport {\n appendAdditionalDelegation,\n appendPermissionRequestArtifact,\n createPermissionRequestArtifact,\n getLastPermissionRequestArtifact,\n getPermissionRequestArtifact,\n isDelegationImportArtifact,\n isPermissionRequestArtifact,\n appendGrantHistory,\n compactPermission,\n loadAdditionalDelegations,\n loadManifestPermissions,\n loadPermissionRequest,\n parseCapSpec,\n permissionsFromDelegation,\n readGrantHistory,\n storedAdditionalDelegation,\n type PermissionRequestArtifact,\n} from \"../lib/permissions.js\";\n\n/**\n * Prompt user to choose an auth method interactively.\n * Returns \"local\" for non-interactive (CI/headless) environments.\n */\nasync function promptAuthMethod(): Promise<AuthMethod> {\n if (!isInteractive()) {\n return \"local\";\n }\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n return new Promise<AuthMethod>((resolve) => {\n process.stderr.write(\"\\n\" + theme.heading(\"Choose authentication method:\") + \"\\n\");\n process.stderr.write(` ${theme.accent(\"1)\")} OpenKey ${theme.muted(\"(browser-based, for interactive use)\")}\\n`);\n process.stderr.write(` ${theme.accent(\"2)\")} Local key ${theme.muted(\"(Ethereum private key, for agents/CI)\")}\\n\\n`);\n\n rl.question(\"Enter choice [1]: \", (answer) => {\n rl.close();\n const trimmed = answer.trim();\n if (trimmed === \"2\" || trimmed.toLowerCase() === \"local\") {\n resolve(\"local\");\n } else {\n resolve(\"openkey\");\n }\n });\n });\n}\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program.command(\"auth\").description(\"Authentication management\");\n\n auth\n .command(\"login\")\n .description(\"Authenticate with TinyCloud\")\n .option(\"--paste\", \"Use manual paste mode instead of browser callback\")\n .option(\"--method <method>\", \"Authentication method: local or openkey\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n // Determine auth method\n let method: AuthMethod;\n if (options.method) {\n if (options.method !== \"local\" && options.method !== \"openkey\") {\n throw new CLIError(\n \"INVALID_METHOD\",\n `Invalid auth method \"${options.method}\". Use \"local\" or \"openkey\".`,\n ExitCode.USAGE_ERROR,\n );\n }\n method = options.method;\n } else {\n method = await promptAuthMethod();\n }\n\n if (method === \"local\") {\n await handleLocalAuth(ctx.profile, ctx.host);\n } else {\n await handleOpenKeyAuth(ctx.profile, ctx.host, options.paste);\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"logout\")\n .description(\"Clear session (keep key)\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n await ProfileManager.clearSession(ctx.profile);\n outputJson({ profile: ctx.profile, authenticated: false });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"status\")\n .description(\"Show current authentication state\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const hasKey = await ProfileManager.getKey(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile);\n let profile;\n try {\n profile = await ProfileManager.getProfile(ctx.profile);\n } catch {\n profile = null;\n }\n const posture = profile ? resolveProfilePosture(profile) : null;\n const operatorType = profile ? resolveProfileOperatorType(profile) : null;\n\n const authenticated = session !== null;\n\n if (shouldOutputJson()) {\n outputJson({\n authenticated,\n did: profile?.did ?? null,\n sessionDid: profile?.sessionDid ?? null,\n ownerDid: profile?.ownerDid ?? null,\n spaceId: profile?.spaceId ?? null,\n host: ctx.host,\n profile: ctx.profile,\n hasKey: hasKey !== null,\n authMethod: profile?.authMethod ?? null,\n posture,\n operatorType,\n address: profile?.address ?? null,\n });\n } else {\n process.stdout.write(theme.heading(\"Authentication Status\") + \"\\n\");\n process.stdout.write(formatField(\"Profile\", ctx.profile) + \"\\n\");\n process.stdout.write(formatField(\"Authenticated\", authenticated) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile?.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\n\");\n process.stdout.write(formatField(\"Host\", ctx.host) + \"\\n\");\n process.stdout.write(formatField(\"DID\", profile?.did ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Session DID\", profile?.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Owner DID\", profile?.ownerDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Address\", profile?.address ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Space ID\", profile?.spaceId ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Has Key\", hasKey !== null) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"request\")\n .description(\"Create a TinyCloud permission request artifact\")\n .option(\n \"--cap <spec>\",\n \"Capability spec: tinycloud.<service>:<space>:<path>:<actions-csv> (repeatable)\",\n (value, previous: string[]) => [...previous, value],\n [],\n )\n .option(\"--permission <file>\", \"JSON permission request: { \\\"permissions\\\": PermissionEntry[] }\")\n .option(\"--manifest <fileOrBase64>\", \"Manifest file, base64:<json>, or raw base64 JSON\")\n .option(\n \"--expiry <duration>\",\n \"Lifetime of the granted delegation. ms-format string (e.g. \\\"7d\\\", \\\"30m\\\") or raw milliseconds. Defaults to 7d, capped by the active session's expiry.\",\n )\n .option(\"--emit [file]\", \"Emit the request artifact to stdout, or write it to file when provided\")\n .option(\"--grant\", \"Grant the requested permissions immediately with this owner profile\")\n .option(\"--yes\", \"Skip local-key TTY confirmation\", false)\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profile = await ProfileManager.getProfile(ctx.profile);\n const requested = await collectRequestedPermissions(options, ctx.profile);\n const expiryOption = parseExpiryOption(options.expiry);\n\n if (requested.length === 0) {\n throw new CLIError(\n \"NO_CAPS_REQUESTED\",\n \"Provide at least one --cap, --permission, or --manifest.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n if (!options.grant) {\n const artifact = createPermissionRequestArtifact({\n profileName: ctx.profile,\n profile,\n host: ctx.host,\n requested,\n requestedExpiry: expiryOption,\n });\n await appendPermissionRequestArtifact(ctx.profile, artifact);\n await emitPermissionRequestArtifact(artifact, options.emit);\n return;\n }\n\n const node = await ensureAuthenticated(ctx);\n\n // Fast path: master's grantRuntimePermissions / hasRuntimePermissions\n // already does the diff against the live session + existing runtime\n // grants; no need to compute it ourselves.\n if (node.hasRuntimePermissions(requested)) {\n outputJson({ changed: false, missing: [], added: [] });\n return;\n }\n\n if (profile.authMethod === \"openkey\") {\n const key = await ProfileManager.getKey(ctx.profile);\n if (!key) {\n throw new CLIError(\"NO_KEY\", `No key found for profile \"${ctx.profile}\". Run \\`tc init\\` first.`, ExitCode.AUTH_REQUIRED);\n }\n const delegationCids: string[] = [];\n let expiry: string | undefined;\n const openkeyHost = resolveOpenKeyHost(profile);\n for (const group of groupPermissionsBySpace(requested)) {\n const delegationData = await startAuthFlow(profile.did, {\n jwk: key,\n host: ctx.host,\n permissions: group,\n openkeyHost,\n expiry: expiryOption,\n });\n const delegation = portableFromOpenKeyDelegation(delegationData, group, ctx.host);\n const stored = storedAdditionalDelegation(delegation, group);\n await appendAdditionalDelegation(ctx.profile, stored);\n await node.useRuntimeDelegation(delegation);\n delegationCids.push(delegation.cid);\n expiry = delegation.expiry.toISOString();\n await appendGrantHistory(ctx.profile, {\n addedCaps: group,\n source: options.manifest ? \"manifest\" : \"cli\",\n delegationCid: delegation.cid,\n expiry,\n });\n }\n outputJson({\n changed: delegationCids.length > 0,\n added: requested,\n delegationCid: delegationCids[0],\n delegationCids,\n expiry,\n });\n return;\n }\n\n if (isInteractive()) {\n if (!options.yes) {\n await confirmPermissionRequest(requested);\n }\n } else if (!options.yes) {\n throw new CLIError(\n \"CONFIRMATION_REQUIRED\",\n \"Local-key permission requests in non-interactive mode require --yes.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n // Local-key flow: master's grantRuntimePermissions handles signing\n // through the SDK's wallet-mode signer, groups by space, and skips\n // anything already covered by the session or an existing grant.\n const delegations = await node.grantRuntimePermissions(\n requested,\n expiryOption !== undefined ? { expiry: expiryOption } : undefined,\n );\n const delegationCids: string[] = [];\n let expiry: string | undefined;\n for (const delegation of delegations) {\n const covering = permissionsFromDelegation(delegation);\n const stored = storedAdditionalDelegation(delegation, covering);\n await appendAdditionalDelegation(ctx.profile, stored);\n delegationCids.push(delegation.cid);\n expiry = delegation.expiry.toISOString();\n await appendGrantHistory(ctx.profile, {\n addedCaps: covering,\n source: options.manifest ? \"manifest\" : \"cli\",\n delegationCid: delegation.cid,\n expiry,\n });\n }\n\n if (delegationCids.length === 0) {\n outputJson({ changed: false, missing: [], added: [] });\n return;\n }\n\n outputJson({\n changed: true,\n added: requested,\n delegationCid: delegationCids[0],\n delegationCids,\n expiry,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"import [source]\")\n .description(\"Import a TinyCloud delegation or permission request artifact\")\n .option(\"--stdin\", \"Read the JSON artifact from stdin\")\n .option(\"--paste\", \"Read the JSON artifact from stdin\")\n .action(async (source: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const raw = await readAuthArtifactSource(source, {\n stdin: options.stdin === true || options.paste === true,\n });\n const parsed = JSON.parse(raw) as unknown;\n\n if (isPermissionRequestArtifact(parsed)) {\n await appendPermissionRequestArtifact(ctx.profile, parsed);\n outputJson({\n imported: true,\n kind: parsed.kind,\n requestId: parsed.requestId,\n requested: parsed.requested,\n next: `tc auth retry ${parsed.requestId}`,\n });\n return;\n }\n\n const imported = normalizeDelegationImport(parsed);\n const node = await ensureAuthenticated(ctx);\n await appendAdditionalDelegation(ctx.profile, storedAdditionalDelegation(\n imported.delegation,\n imported.permissions,\n ));\n await node.useRuntimeDelegation(imported.delegation);\n await appendGrantHistory(ctx.profile, {\n addedCaps: imported.permissions,\n source: \"cli\",\n delegationCid: imported.delegation.cid,\n expiry: imported.delegation.expiry.toISOString(),\n });\n\n outputJson({\n imported: true,\n kind: \"tinycloud.auth.delegation\",\n requestId: imported.requestId ?? null,\n delegationCid: imported.delegation.cid,\n permissions: imported.permissions,\n expiry: imported.delegation.expiry.toISOString(),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"grant [request]\")\n .description(\"Grant a TinyCloud permission request artifact to its requester\")\n .option(\"--stdin\", \"Read the JSON request artifact from stdin\")\n .option(\"--paste\", \"Read the JSON request artifact from stdin\")\n .option(\"--yes\", \"Skip local-key TTY confirmation\", false)\n .action(async (source: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profile = await ProfileManager.getProfile(ctx.profile);\n const raw = await readAuthArtifactSource(source, {\n stdin: options.stdin === true || options.paste === true,\n });\n const parsed = JSON.parse(raw) as unknown;\n\n if (!isPermissionRequestArtifact(parsed)) {\n throw new CLIError(\n \"INVALID_AUTH_REQUEST\",\n \"Auth grant requires a tinycloud.auth.request artifact.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const node = await ensureAuthenticated(ctx);\n await ensureDelegationAuthority({\n ctx,\n profile,\n node,\n requested: parsed.requested,\n expiryOption: parsed.requestedExpiry,\n yes: options.yes === true,\n });\n const result = await node.delegateTo(\n parsed.sessionDid,\n parsed.requested,\n parsed.requestedExpiry !== undefined\n ? { expiry: parsed.requestedExpiry }\n : undefined,\n );\n\n outputJson({\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: parsed.requestId,\n delegationCid: result.delegation.cid,\n delegation: result.delegation,\n permissions: parsed.requested,\n expiry: result.delegation.expiry.toISOString(),\n prompted: result.prompted,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"retry [requestId]\")\n .description(\"Check whether a stored permission request is now satisfied\")\n .option(\"--last\", \"Use the latest stored permission request for this profile\")\n .option(\"--exec\", \"Run the captured command when the request is covered\")\n .action(async (requestId: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const artifact = options.last\n ? await getLastPermissionRequestArtifact(ctx.profile)\n : requestId\n ? await getPermissionRequestArtifact(ctx.profile, requestId)\n : null;\n\n if (!artifact) {\n throw new CLIError(\n \"REQUEST_NOT_FOUND\",\n options.last\n ? `No stored permission requests exist for profile \"${ctx.profile}\".`\n : \"Provide a requestId or use --last.\",\n ExitCode.NOT_FOUND,\n );\n }\n\n const node = await ensureAuthenticated(ctx);\n const covered = node.hasRuntimePermissions(artifact.requested);\n if (options.exec) {\n if (!covered) {\n throw new CLIError(\n \"PERMISSIONS_MISSING\",\n `Request ${artifact.requestId} is not covered yet. Import a delegation, then retry with --exec.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n if (!artifact.command?.argv?.length) {\n throw new CLIError(\n \"COMMAND_NOT_CAPTURED\",\n `Request ${artifact.requestId} does not include a captured command.`,\n ExitCode.USAGE_ERROR,\n );\n }\n await execCapturedCommand(artifact.command);\n return;\n }\n\n outputJson({\n requestId: artifact.requestId,\n covered,\n missing: covered ? [] : artifact.requested,\n command: artifact.command ?? null,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"caps\")\n .description(\"Show granted capabilities for the active session\")\n .option(\"--diff <spec>\", \"Show missing capabilities for a spec\")\n .option(\"--history\", \"Show recent permission grants\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n if (options.history) {\n const history = (await readGrantHistory(ctx.profile)).slice(-20);\n if (shouldOutputJson()) {\n outputJson({ grants: history });\n } else if (history.length === 0) {\n process.stdout.write(theme.muted(\"No grant history.\") + \"\\n\");\n } else {\n process.stdout.write(formatTable(\n [\"time\", \"source\", \"delegation\", \"caps\"],\n history.map((entry) => [\n entry.ts,\n entry.source,\n entry.delegationCid ?? \"\",\n entry.addedCaps.map(compactPermission).join(\"; \"),\n ]),\n ) + \"\\n\");\n }\n return;\n }\n\n const node = await ensureAuthenticated(ctx);\n const runtimeDelegations = node.getRuntimePermissionDelegations();\n // Granted view = permissions covered by appended runtime delegations.\n // The base-session SIWE recap isn't enumerated here because the\n // node-sdk doesn't expose it as a list — `hasRuntimePermissions()`\n // is the trusted answer for \"is this covered?\".\n const granted = runtimeDelegations.flatMap(permissionsFromDelegation);\n\n if (options.diff) {\n const requested = [await parseCapSpec(options.diff, ctx.profile)];\n const covered = node.hasRuntimePermissions(requested);\n outputJson({\n requested,\n changed: !covered,\n covered,\n // `missing` retained for backwards-compatible callers.\n missing: covered ? [] : requested,\n });\n return;\n }\n\n const appended = await loadAdditionalDelegations(ctx.profile);\n if (shouldOutputJson()) {\n outputJson({ granted, appendedDelegations: appended.length });\n } else if (granted.length === 0) {\n process.stdout.write(theme.muted(\"No appended runtime delegations on this profile.\") + \"\\n\");\n } else {\n process.stdout.write(formatTable(\n [\"service\", \"space\", \"path\", \"actions\"],\n granted.map((entry) => [\n entry.service,\n entry.space,\n entry.path,\n entry.actions.join(\", \"),\n ]),\n ) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"whoami\")\n .description(\"Show identity information\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile);\n const authenticated = session !== null;\n const posture = resolveProfilePosture(profile);\n const operatorType = resolveProfileOperatorType(profile);\n\n if (shouldOutputJson()) {\n outputJson({\n profile: ctx.profile,\n did: profile.did,\n sessionDid: profile.sessionDid ?? null,\n ownerDid: profile.ownerDid ?? null,\n spaceId: profile.spaceId ?? null,\n host: profile.host,\n authenticated,\n authMethod: profile.authMethod ?? null,\n posture,\n operatorType,\n address: profile.address ?? null,\n });\n } else {\n process.stdout.write(theme.heading(\"Identity\") + \"\\n\");\n process.stdout.write(formatField(\"Profile\", ctx.profile) + \"\\n\");\n process.stdout.write(formatField(\"DID\", profile.did) + \"\\n\");\n process.stdout.write(formatField(\"Session DID\", profile.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Owner DID\", profile.ownerDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\n\");\n process.stdout.write(formatField(\"Address\", profile.address ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Space ID\", profile.spaceId ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Host\", profile.host) + \"\\n\");\n process.stdout.write(formatField(\"Authenticated\", authenticated) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nasync function emitPermissionRequestArtifact(\n artifact: PermissionRequestArtifact,\n emitOption: unknown,\n): Promise<void> {\n if (typeof emitOption === \"string\" && emitOption.length > 0) {\n await mkdir(dirname(emitOption), { recursive: true });\n await writeFile(emitOption, JSON.stringify(artifact, null, 2) + \"\\n\", \"utf8\");\n outputJson({\n emitted: true,\n path: emitOption,\n requestId: artifact.requestId,\n requested: artifact.requested,\n });\n return;\n }\n outputJson(artifact);\n}\n\nasync function readAuthArtifactSource(\n source: string | undefined,\n options: { stdin: boolean },\n): Promise<string> {\n if (options.stdin || source === \"-\" || (!source && !isInteractive())) {\n return readStdin();\n }\n\n if (!source) {\n throw new CLIError(\n \"IMPORT_SOURCE_REQUIRED\",\n \"Provide an artifact file, URL, or use --stdin.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n if (source.startsWith(\"http://\") || source.startsWith(\"https://\")) {\n return readUrl(source);\n }\n\n return readFile(source, \"utf8\");\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction readUrl(source: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const getter = source.startsWith(\"https://\") ? httpsGet : httpGet;\n const request = getter(source, (response: IncomingMessage) => {\n const status = response.statusCode ?? 0;\n if (status >= 300 && status < 400 && response.headers.location) {\n response.resume();\n readUrl(new URL(response.headers.location, source).toString()).then(resolve, reject);\n return;\n }\n if (status < 200 || status >= 300) {\n response.resume();\n reject(new CLIError(\n \"IMPORT_FETCH_FAILED\",\n `Failed to fetch ${source}: HTTP ${status}.`,\n ExitCode.ERROR,\n ));\n return;\n }\n\n const chunks: Buffer[] = [];\n response.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n response.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n });\n request.on(\"error\", reject);\n });\n}\n\nfunction normalizeDelegationImport(value: unknown): {\n requestId?: string;\n delegation: PortableDelegation;\n permissions: PermissionEntry[];\n} {\n if (isDelegationImportArtifact(value)) {\n const delegation = normalizePortableDelegation(value.delegation);\n return {\n requestId: value.requestId,\n delegation,\n permissions: Array.isArray(value.permissions) && value.permissions.length > 0\n ? value.permissions\n : permissionsFromDelegation(delegation),\n };\n }\n\n if (isStoredDelegationLike(value)) {\n const delegation = normalizePortableDelegation(value.delegation);\n return {\n delegation,\n permissions: Array.isArray(value.permissions) && value.permissions.length > 0\n ? value.permissions\n : permissionsFromDelegation(delegation),\n };\n }\n\n if (isPortableDelegationLike(value)) {\n const delegation = normalizePortableDelegation(value);\n return {\n delegation,\n permissions: permissionsFromDelegation(delegation),\n };\n }\n\n throw new CLIError(\n \"INVALID_AUTH_IMPORT\",\n \"Auth import must be a tinycloud.auth.delegation artifact, a portable delegation, or a tinycloud.auth.request artifact.\",\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction isStoredDelegationLike(value: unknown): value is {\n delegation: PortableDelegation;\n permissions?: PermissionEntry[];\n} {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as { delegation?: unknown };\n return isPortableDelegationLike(candidate.delegation);\n}\n\nfunction isPortableDelegationLike(value: unknown): value is PortableDelegation {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<PortableDelegation>;\n return (\n typeof candidate.cid === \"string\" &&\n typeof candidate.spaceId === \"string\" &&\n typeof candidate.path === \"string\" &&\n Array.isArray(candidate.actions) &&\n candidate.delegationHeader !== undefined &&\n typeof candidate.delegationHeader === \"object\"\n );\n}\n\nfunction normalizePortableDelegation(delegation: PortableDelegation): PortableDelegation {\n const rawExpiry = (delegation as PortableDelegation & { expiry: unknown }).expiry;\n const expiry = rawExpiry instanceof Date ? rawExpiry : new Date(String(rawExpiry));\n if (Number.isNaN(expiry.getTime())) {\n throw new CLIError(\n \"INVALID_AUTH_IMPORT\",\n \"Imported delegation must include a valid expiry.\",\n ExitCode.USAGE_ERROR,\n );\n }\n return { ...delegation, expiry };\n}\n\nasync function ensureDelegationAuthority(params: {\n ctx: { profile: string; host: string };\n profile: ProfileConfig;\n node: Awaited<ReturnType<typeof ensureAuthenticated>>;\n requested: PermissionEntry[];\n expiryOption: string | number | undefined;\n yes: boolean;\n}): Promise<void> {\n if (params.node.hasRuntimePermissions(params.requested)) return;\n\n if (params.profile.authMethod === \"openkey\") {\n const key = await ProfileManager.getKey(params.ctx.profile);\n if (!key) {\n throw new CLIError(\n \"NO_KEY\",\n `No key found for profile \"${params.ctx.profile}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n const openkeyHost = resolveOpenKeyHost(params.profile);\n for (const group of groupPermissionsBySpace(params.requested)) {\n const delegationData = await startAuthFlow(params.profile.did, {\n jwk: key,\n host: params.ctx.host,\n permissions: group,\n openkeyHost,\n expiry: params.expiryOption,\n });\n const delegation = portableFromOpenKeyDelegation(delegationData, group, params.ctx.host);\n await appendAdditionalDelegation(\n params.ctx.profile,\n storedAdditionalDelegation(delegation, group),\n );\n await params.node.useRuntimeDelegation(delegation);\n await appendGrantHistory(params.ctx.profile, {\n addedCaps: group,\n source: \"cli\",\n delegationCid: delegation.cid,\n expiry: delegation.expiry.toISOString(),\n });\n }\n return;\n }\n\n if (isInteractive()) {\n if (!params.yes) {\n await confirmPermissionRequest(params.requested);\n }\n } else if (!params.yes) {\n throw new CLIError(\n \"CONFIRMATION_REQUIRED\",\n \"Local-key auth grants in non-interactive mode require --yes.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const delegations = await params.node.grantRuntimePermissions(\n params.requested,\n params.expiryOption !== undefined ? { expiry: params.expiryOption } : undefined,\n );\n for (const delegation of delegations) {\n const covering = permissionsFromDelegation(delegation);\n await appendAdditionalDelegation(\n params.ctx.profile,\n storedAdditionalDelegation(delegation, covering),\n );\n await appendGrantHistory(params.ctx.profile, {\n addedCaps: covering,\n source: \"cli\",\n delegationCid: delegation.cid,\n expiry: delegation.expiry.toISOString(),\n });\n }\n}\n\nfunction execCapturedCommand(command: { argv: string[]; cwd: string }): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(process.execPath, [process.argv[1], ...command.argv], {\n cwd: command.cwd,\n env: process.env,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code, signal) => {\n if (signal) {\n reject(new CLIError(\n \"COMMAND_SIGNAL\",\n `Captured command exited from signal ${signal}.`,\n ExitCode.ERROR,\n ));\n return;\n }\n if (code && code !== 0) {\n process.exitCode = code;\n }\n resolve();\n });\n });\n}\n\nasync function collectRequestedPermissions(\n options: {\n cap?: string[];\n permission?: string;\n manifest?: string;\n },\n profile: string,\n): Promise<PermissionEntry[]> {\n const permissions: PermissionEntry[] = [];\n for (const spec of options.cap ?? []) {\n permissions.push(await parseCapSpec(spec, profile));\n }\n if (options.permission) {\n permissions.push(...await loadPermissionRequest(options.permission, profile));\n }\n if (options.manifest) {\n permissions.push(...await loadManifestPermissions(options.manifest, profile));\n }\n return permissions;\n}\n\nasync function confirmPermissionRequest(permissions: PermissionEntry[]): Promise<void> {\n process.stderr.write(\"\\n\" + theme.heading(\"Additional Permissions\") + \"\\n\");\n for (const permission of permissions) {\n const dangerous = isDangerousPermission(permission);\n const line = ` ${compactPermission(permission)}`;\n process.stderr.write((dangerous ? theme.warn(line) : theme.value(line)) + \"\\n\");\n }\n process.stderr.write(\"\\n\");\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Approve local-key delegation? [y/N] \", resolve);\n });\n rl.close();\n\n if (!/^y(es)?$/i.test(answer.trim())) {\n throw new CLIError(\"REQUEST_CANCELLED\", \"Permission request cancelled.\", ExitCode.ERROR);\n }\n}\n\nfunction isDangerousPermission(permission: PermissionEntry): boolean {\n if (permission.path === \"\" || permission.path === \"/\") return true;\n return permission.actions.some((action) =>\n action.includes(\"*\") ||\n action.endsWith(\"/write\") ||\n action.endsWith(\"/admin\") ||\n action.endsWith(\"/ddl\") ||\n action.endsWith(\"/del\"),\n );\n}\n\n/**\n * Parse the `--expiry` flag into either a ms-format string (\"7d\", \"30m\") or\n * raw milliseconds. Returns undefined for missing input so the caller falls\n * back to the SDK's DEFAULT_DELEGATION_EXPIRY_MS.\n *\n * Pure-numeric strings are coerced to numbers so a shell-quoted ms count\n * (`--expiry 86400000`) works, but anything that contains a unit suffix\n * (`\"7d\"`, `\"30m\"`) is forwarded as-is to parseExpiry which understands\n * the ms-format vocabulary.\n */\nfunction parseExpiryOption(raw: unknown): string | number | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw new CLIError(\n \"INVALID_EXPIRY\",\n `--expiry must be a string (e.g. \"7d\", \"30m\") or a millisecond integer.`,\n ExitCode.USAGE_ERROR,\n );\n }\n if (/^\\d+$/.test(raw.trim())) {\n const ms = Number(raw.trim());\n if (!Number.isFinite(ms) || ms <= 0) {\n throw new CLIError(\"INVALID_EXPIRY\", `--expiry must be a positive integer when numeric.`, ExitCode.USAGE_ERROR);\n }\n return ms;\n }\n return raw;\n}\n\nfunction groupPermissionsBySpace(permissions: PermissionEntry[]): PermissionEntry[][] {\n const groups = new Map<string, PermissionEntry[]>();\n for (const permission of permissions) {\n const group = groups.get(permission.space) ?? [];\n group.push(permission);\n groups.set(permission.space, group);\n }\n return Array.from(groups.values());\n}\n\nfunction portableFromOpenKeyDelegation(\n data: Record<string, unknown>,\n permissions: PermissionEntry[],\n host: string,\n): PortableDelegation {\n const primary = permissions[0];\n const returnedSpace = String(data.spaceId ?? primary.space);\n const expectedSpaces = new Set(permissions.map((permission) => permission.space));\n if (expectedSpaces.size !== 1 || !expectedSpaces.has(returnedSpace)) {\n throw new CLIError(\n \"OPENKEY_SCOPE_MISMATCH\",\n `OpenKey returned delegation for ${returnedSpace}, expected ${Array.from(expectedSpaces).join(\", \")}.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n const expiry = inferDelegationExpiry(data);\n return {\n cid: String(data.delegationCid),\n delegationHeader: data.delegationHeader as { Authorization: string },\n spaceId: returnedSpace,\n path: primary.path,\n actions: primary.actions,\n resources: permissions.map((permission) => ({\n service: permission.service.startsWith(\"tinycloud.\")\n ? permission.service.slice(\"tinycloud.\".length)\n : permission.service,\n space: permission.space,\n path: permission.path,\n actions: [...permission.actions],\n })),\n expiry,\n delegateDID: String(data.verificationMethod),\n ownerAddress: String(data.address ?? \"\"),\n chainId: typeof data.chainId === \"number\" ? data.chainId : DEFAULT_CHAIN_ID,\n host,\n };\n}\n\nfunction inferDelegationExpiry(data: Record<string, unknown>): Date {\n const direct = data.expiry ?? data.expiresAt;\n if (typeof direct === \"string\") {\n const parsed = new Date(direct);\n if (!Number.isNaN(parsed.getTime())) return parsed;\n }\n return new Date(Date.now() + 60 * 60 * 1000);\n}\n\n/**\n * Handle local Ethereum key authentication.\n * Generates or reuses a local private key, creates a did:pkh identity,\n * and signs in to TinyCloud directly (no browser needed).\n */\nasync function handleLocalAuth(profileName: string, host: string): Promise<void> {\n const profile = await ProfileManager.getProfile(profileName).catch(() => null);\n\n let privateKey: string;\n let address: string;\n let did: string;\n let sessionDid = profile?.sessionDid;\n\n if (profile?.authMethod === \"local\" && profile.privateKey && profile.address) {\n // Reuse existing local key\n privateKey = profile.privateKey;\n address = profile.address;\n did = profile.did;\n\n if (isInteractive()) {\n process.stderr.write(theme.muted(\"Using existing local key\") + \"\\n\");\n process.stderr.write(formatField(\"Address\", address) + \"\\n\");\n }\n } else {\n // Generate new local identity\n const identity = await withSpinner(\"Generating Ethereum key...\", async () => {\n return generateLocalIdentity(DEFAULT_CHAIN_ID);\n });\n\n privateKey = identity.privateKey;\n address = identity.address;\n did = identity.did;\n\n if (isInteractive()) {\n process.stderr.write(\"\\n\" + theme.heading(\"Local Key Generated\") + \"\\n\");\n process.stderr.write(formatField(\"Address\", address) + \"\\n\");\n process.stderr.write(formatField(\"DID\", did) + \"\\n\\n\");\n }\n }\n\n // We also need a session key (Ed25519 JWK) for the profile\n const hasKey = await ProfileManager.getKey(profileName);\n if (!hasKey) {\n const { jwk, did: generatedSessionDid } = await withSpinner(\"Generating session key...\", async () => {\n return generateKey();\n });\n await ProfileManager.setKey(profileName, jwk);\n sessionDid = generatedSessionDid;\n } else if (!sessionDid) {\n sessionDid = keyToDID(hasKey);\n }\n\n // Sign in using the private key\n const sessionResult = await withSpinner(\"Signing in...\", async () => {\n return localKeySignIn({ privateKey, host });\n });\n\n // Store session data\n await ProfileManager.setSession(profileName, {\n authMethod: \"local\",\n address,\n chainId: DEFAULT_CHAIN_ID,\n spaceId: sessionResult.spaceId,\n delegationHeader: sessionResult.delegationHeader,\n delegationCid: sessionResult.delegationCid,\n jwk: sessionResult.jwk,\n verificationMethod: sessionResult.verificationMethod,\n siwe: sessionResult.siwe,\n signature: sessionResult.signature,\n });\n sessionDid = sessionResult.verificationMethod;\n\n // Update profile\n await ProfileManager.setProfile(profileName, {\n ...profile,\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n sessionDid,\n ownerDid: did,\n spaceId: sessionResult.spaceId,\n createdAt: profile?.createdAt ?? new Date().toISOString(),\n posture: profile?.posture ?? \"local-owner-key\",\n operatorType: profile?.operatorType ?? \"human\",\n authMethod: \"local\",\n privateKey,\n address,\n });\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did,\n sessionDid,\n address,\n spaceId: sessionResult.spaceId,\n authMethod: \"local\",\n });\n}\n\n/**\n * Handle OpenKey (browser-based) authentication.\n * This is the original auth flow.\n */\nasync function handleOpenKeyAuth(profileName: string, host: string, paste?: boolean): Promise<void> {\n const key = await ProfileManager.getKey(profileName);\n if (!key) {\n throw new CLIError(\n \"NO_KEY\",\n `No key found for profile \"${profileName}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n // Get DID from profile\n const profile = await ProfileManager.getProfile(profileName);\n\n // Start browser auth flow\n const delegationData = await startAuthFlow(profile.did, {\n paste,\n jwk: key,\n host,\n openkeyHost: resolveOpenKeyHost(profile),\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with owner DID if present\n const updatedProfile = {\n ...profile,\n sessionDid: profile.sessionDid ?? profile.did,\n posture: profile.posture ?? \"owner-openkey\",\n operatorType: profile.operatorType ?? \"human\",\n authMethod: \"openkey\" as const,\n };\n\n if (delegationData.spaceId) {\n updatedProfile.spaceId = delegationData.spaceId;\n updatedProfile.ownerDid = delegationData.ownerDid as string | undefined;\n }\n\n await ProfileManager.setProfile(profileName, updatedProfile);\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did: profile.did,\n spaceId: delegationData.spaceId,\n authMethod: \"openkey\",\n });\n}\n","export interface GlobalConfig {\n defaultProfile: string;\n version: number;\n}\n\nexport type AuthMethod = \"openkey\" | \"local\";\n\nexport const CLI_PROFILE_POSTURES = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n] as const;\n\nexport type CLIProfilePosture = typeof CLI_PROFILE_POSTURES[number];\n\nexport const CLI_OPERATOR_TYPES = [\"human\", \"agent\"] as const;\n\nexport type CLIOperatorType = typeof CLI_OPERATOR_TYPES[number];\n\nexport function isCLIProfilePosture(value: unknown): value is CLIProfilePosture {\n return typeof value === \"string\" && CLI_PROFILE_POSTURES.includes(value as CLIProfilePosture);\n}\n\nexport function isCLIOperatorType(value: unknown): value is CLIOperatorType {\n return typeof value === \"string\" && CLI_OPERATOR_TYPES.includes(value as CLIOperatorType);\n}\n\nexport function resolveProfilePosture(profile: {\n posture?: unknown;\n authMethod?: AuthMethod;\n}): CLIProfilePosture {\n if (isCLIProfilePosture(profile.posture)) return profile.posture;\n if (profile.authMethod === \"local\") return \"local-owner-key\";\n return \"owner-openkey\";\n}\n\nexport function resolveProfileOperatorType(profile: {\n operatorType?: unknown;\n}): CLIOperatorType {\n if (isCLIOperatorType(profile.operatorType)) return profile.operatorType;\n return \"human\";\n}\n\nexport interface ProfileConfig {\n name: string;\n host: string;\n chainId: number;\n spaceName: string;\n did: string;\n sessionDid?: string;\n ownerDid?: string;\n spaceId?: string;\n createdAt: string;\n posture?: CLIProfilePosture;\n operatorType?: CLIOperatorType;\n authMethod?: AuthMethod;\n /** Hex-encoded Ethereum private key (only present when authMethod is \"local\") */\n privateKey?: string;\n /** Ethereum address derived from privateKey (only present when authMethod is \"local\") */\n address?: string;\n /**\n * Optional OpenKey host override. Used for testing accounts or running\n * against a self-hosted OpenKey (e.g. https://openkey.localhost). Falls\n * back to DEFAULT_OPENKEY_HOST when unset. Edit profile.json directly\n * to change.\n */\n openkeyHost?: string;\n}\n\nexport interface CLIContext {\n profile: string;\n host: string;\n verbose: boolean;\n noCache: boolean;\n quiet: boolean;\n}\n","import { TinyCloudNode } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport type { CLIContext } from \"../config/types.js\";\nimport { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { replayAdditionalDelegations } from \"./permissions.js\";\n\n/**\n * Create a TinyCloudNode instance from the current CLI context.\n * Uses the profile's persisted session and key.\n *\n * Supports both auth methods:\n * - \"local\": Uses the stored Ethereum private key directly\n * - \"openkey\": Restores session from stored delegation data (browser auth flow)\n */\nexport async function createSDKInstance(\n ctx: CLIContext,\n options?: { privateKey?: string }\n): Promise<TinyCloudNode> {\n const profile = await ProfileManager.getProfile(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile) as Record<string, unknown> | null;\n const key = await ProfileManager.getKey(ctx.profile);\n\n // For local auth, use the stored private key\n const effectivePrivateKey = options?.privateKey ?? profile.privateKey;\n\n if (!key && !effectivePrivateKey) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n `No key found for profile \"${ctx.profile}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n if (profile.authMethod === \"local\" && effectivePrivateKey) {\n // Local key auth: prefer the persisted TinyCloud session so the CLI\n // keeps the same session key DID across request/grant/import flows.\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: effectivePrivateKey,\n });\n\n if (session && session.delegationHeader && session.delegationCid && session.spaceId) {\n await node.restoreSession({\n delegationHeader: session.delegationHeader as { Authorization: string },\n delegationCid: session.delegationCid as string,\n spaceId: session.spaceId as string,\n jwk: (session.jwk as object) ?? key,\n verificationMethod: (session.verificationMethod as string) ?? profile.sessionDid ?? profile.did,\n address: session.address as string | undefined,\n chainId: session.chainId as number | undefined,\n siwe: session.siwe as string | undefined,\n signature: session.signature as string | undefined,\n });\n } else {\n await node.signIn();\n }\n await replayAdditionalDelegations(node, ctx.profile);\n return node;\n }\n\n // OpenKey / delegation-based auth\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: options?.privateKey,\n });\n\n if (options?.privateKey) {\n // Sign in with private key (existing behavior)\n await node.signIn();\n } else if (session && session.delegationHeader && session.delegationCid && session.spaceId) {\n // Restore session from stored delegation data (browser auth flow)\n await node.restoreSession({\n delegationHeader: session.delegationHeader as { Authorization: string },\n delegationCid: session.delegationCid as string,\n spaceId: session.spaceId as string,\n jwk: (session.jwk as object) ?? key,\n verificationMethod: (session.verificationMethod as string) ?? profile.did,\n address: session.address as string | undefined,\n chainId: session.chainId as number | undefined,\n siwe: session.siwe as string | undefined,\n signature: session.signature as string | undefined,\n });\n }\n\n await replayAdditionalDelegations(node, ctx.profile);\n return node;\n}\n\n/**\n * Ensure the user is authenticated.\n * Throws AUTH_REQUIRED if no session exists.\n */\nexport async function ensureAuthenticated(\n ctx: CLIContext,\n options?: { privateKey?: string }\n): Promise<TinyCloudNode> {\n const profile = await ProfileManager.getProfile(ctx.profile).catch(() => null);\n\n // For local auth, we can sign in directly without a stored session\n if (profile?.authMethod === \"local\" && profile.privateKey) {\n return createSDKInstance(ctx, { privateKey: profile.privateKey });\n }\n\n const session = await ProfileManager.getSession(ctx.profile);\n\n if (!session) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n `Not authenticated. Run \\`tc auth login\\` or \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n return createSDKInstance(ctx, options);\n}\n","import { randomBytes } from \"node:crypto\";\nimport { appendFile, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n expandActionShortNames,\n isCapabilitySubset,\n resolveManifest,\n type PermissionEntry,\n type PortableDelegation,\n type TinyCloudNode,\n} from \"@tinycloud/node-sdk\";\nimport { PROFILES_DIR } from \"../config/constants.js\";\nimport { fileExists, readJson, writeJson, ensureDir } from \"../config/storage.js\";\nimport { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { resolveSpaceUri } from \"./space.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type CLIOperatorType,\n type CLIProfilePosture,\n type ProfileConfig,\n} from \"../config/types.js\";\n\n/**\n * Stored shape for a runtime delegation appended to a profile.\n * `permissions` mirrors the request that produced this delegation so\n * `tc auth caps` can surface the originally-asked-for entries even after\n * the delegation has been baked into a recap.\n */\nexport interface StoredAdditionalDelegation {\n delegation: PortableDelegation;\n permissions: PermissionEntry[];\n}\n\nexport interface GrantHistoryEntry {\n ts: string;\n profile: string;\n addedCaps: PermissionEntry[];\n source: \"cli\" | \"401-hint\" | \"manifest\";\n delegationCid?: string;\n expiry?: string;\n}\n\nexport interface PermissionRequestArtifact {\n kind: \"tinycloud.auth.request\";\n version: 1;\n requestId: string;\n createdAt: string;\n profile: string;\n posture: CLIProfilePosture;\n operatorType: CLIOperatorType;\n host: string;\n sessionDid: string;\n ownerDid?: string;\n spaceId?: string;\n requestedExpiry?: string | number;\n requested: PermissionEntry[];\n command?: {\n argv: string[];\n cwd: string;\n };\n}\n\nexport interface DelegationImportArtifact {\n kind: \"tinycloud.auth.delegation\";\n version: 1;\n requestId?: string;\n delegation: PortableDelegation;\n permissions?: PermissionEntry[];\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n // Sibling file keeps legacy session.json schema unchanged for existing readers.\n return join(PROFILES_DIR, profile, \"additional-delegations.json\");\n}\n\nexport function permissionRequestsPath(profile: string): string {\n return join(PROFILES_DIR, profile, \"auth-requests.json\");\n}\n\nexport function grantHistoryPath(profile: string): string {\n return join(PROFILES_DIR, profile, \"auth-grants.jsonl\");\n}\n\nexport function createPermissionRequestArtifact(params: {\n profileName: string;\n profile: ProfileConfig;\n host: string;\n requested: PermissionEntry[];\n requestedExpiry?: string | number;\n argv?: string[];\n cwd?: string;\n}): PermissionRequestArtifact {\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: `req_${Date.now().toString(36)}_${randomBytes(4).toString(\"hex\")}`,\n createdAt: new Date().toISOString(),\n profile: params.profileName,\n posture: resolveProfilePosture(params.profile),\n operatorType: resolveProfileOperatorType(params.profile),\n host: params.host,\n sessionDid: didWithoutFragment(params.profile.sessionDid ?? params.profile.did),\n ownerDid: params.profile.ownerDid,\n spaceId: params.profile.spaceId,\n requestedExpiry: params.requestedExpiry,\n requested: params.requested,\n command: {\n argv: params.argv ?? process.argv.slice(2),\n cwd: params.cwd ?? process.cwd(),\n },\n };\n}\n\nfunction didWithoutFragment(did: string): string {\n const fragment = did.indexOf(\"#\");\n return fragment === -1 ? did : did.slice(0, fragment);\n}\n\nexport async function loadAdditionalDelegations(\n profile: string,\n): Promise<StoredAdditionalDelegation[]> {\n const raw = await readJson<StoredAdditionalDelegation[]>(\n additionalDelegationsPath(profile),\n );\n return Array.isArray(raw) ? raw : [];\n}\n\nexport async function saveAdditionalDelegations(\n profile: string,\n entries: StoredAdditionalDelegation[],\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n await writeJson(additionalDelegationsPath(profile), entries);\n}\n\nexport async function appendAdditionalDelegation(\n profile: string,\n entry: StoredAdditionalDelegation,\n): Promise<void> {\n const existing = await loadAdditionalDelegations(profile);\n const next = existing.filter((item) => item.delegation.cid !== entry.delegation.cid);\n next.push(entry);\n await saveAdditionalDelegations(profile, next);\n}\n\nexport async function loadPermissionRequestArtifacts(\n profile: string,\n): Promise<PermissionRequestArtifact[]> {\n const raw = await readJson<PermissionRequestArtifact[]>(\n permissionRequestsPath(profile),\n );\n return Array.isArray(raw) ? raw.filter(isPermissionRequestArtifact) : [];\n}\n\nexport async function savePermissionRequestArtifacts(\n profile: string,\n entries: PermissionRequestArtifact[],\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n await writeJson(permissionRequestsPath(profile), entries);\n}\n\nexport async function appendPermissionRequestArtifact(\n profile: string,\n artifact: PermissionRequestArtifact,\n): Promise<void> {\n const existing = await loadPermissionRequestArtifacts(profile);\n const next = existing.filter((item) => item.requestId !== artifact.requestId);\n next.push(artifact);\n await savePermissionRequestArtifacts(profile, next);\n}\n\nexport async function getPermissionRequestArtifact(\n profile: string,\n requestId: string,\n): Promise<PermissionRequestArtifact | null> {\n const existing = await loadPermissionRequestArtifacts(profile);\n return existing.find((item) => item.requestId === requestId) ?? null;\n}\n\nexport async function getLastPermissionRequestArtifact(\n profile: string,\n): Promise<PermissionRequestArtifact | null> {\n const existing = await loadPermissionRequestArtifacts(profile);\n return existing.at(-1) ?? null;\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<PermissionRequestArtifact>;\n return (\n candidate.kind === \"tinycloud.auth.request\" &&\n candidate.version === 1 &&\n typeof candidate.requestId === \"string\" &&\n Array.isArray(candidate.requested)\n );\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<DelegationImportArtifact>;\n return (\n candidate.kind === \"tinycloud.auth.delegation\" &&\n candidate.version === 1 &&\n candidate.delegation !== undefined &&\n typeof candidate.delegation === \"object\"\n );\n}\n\nexport async function replayAdditionalDelegations(\n node: TinyCloudNode,\n profile: string,\n): Promise<void> {\n const entries = await loadAdditionalDelegations(profile);\n for (const entry of entries) {\n // Skip expired delegations rather than letting useRuntimeDelegation throw.\n const expiry = entry.delegation.expiry instanceof Date\n ? entry.delegation.expiry\n : new Date(entry.delegation.expiry as unknown as string);\n if (expiry.getTime() <= Date.now()) continue;\n try {\n await node.useRuntimeDelegation({ ...entry.delegation, expiry });\n } catch (err) {\n // A stored delegation can be invalid for several benign reasons (host\n // unreachable, key rotated). Don't fail the whole CLI invocation —\n // the user can re-run `tc auth request` to refresh the grant.\n if (process.env.TC_DEBUG_REPLAY === \"1\") {\n process.stderr.write(`[replay] skipping ${entry.delegation.cid}: ${(err as Error).message}\\n`);\n }\n }\n }\n}\n\n/**\n * Helper for `tc auth request` to construct the persisted record that\n * follows the runtime grant. Keeps the \"PortableDelegation + originating\n * permissions\" pair together so future `tc auth caps` output can show the\n * caller-friendly entries we agreed to grant.\n */\nexport function storedAdditionalDelegation(\n delegation: PortableDelegation,\n permissions: PermissionEntry[],\n): StoredAdditionalDelegation {\n return { delegation, permissions };\n}\n\nexport async function appendGrantHistory(\n profile: string,\n entry: Omit<GrantHistoryEntry, \"ts\" | \"profile\">,\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n const line = JSON.stringify({\n ts: new Date().toISOString(),\n profile,\n ...entry,\n }) + \"\\n\";\n await appendFile(grantHistoryPath(profile), line, \"utf8\");\n}\n\nexport async function readGrantHistory(\n profile: string,\n): Promise<GrantHistoryEntry[]> {\n const path = grantHistoryPath(profile);\n if (!(await fileExists(path))) return [];\n const raw = await readFile(path, \"utf8\");\n return raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => JSON.parse(line) as GrantHistoryEntry);\n}\n\nexport async function parseCapSpec(\n spec: string,\n profile: string,\n): Promise<PermissionEntry> {\n const firstColon = spec.indexOf(\":\");\n const lastColon = spec.lastIndexOf(\":\");\n if (firstColon <= 0 || lastColon <= firstColon) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Invalid --cap \"${spec}\". Expected tinycloud.<service>:<space>:<path>:<actions-csv>.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const service = normalizeService(spec.slice(0, firstColon));\n const actionsCsv = spec.slice(lastColon + 1);\n const spaceAndPath = spec.slice(firstColon + 1, lastColon);\n const { space, path } = splitSpaceAndPath(spaceAndPath);\n const resolvedSpace = await resolveSpaceUri(space, profile) ?? space;\n const actions = expandActionShortNames(\n service,\n actionsCsv.split(\",\").map((action) => action.trim()).filter(Boolean),\n );\n\n if (actions.length === 0) {\n throw new CLIError(\"INVALID_CAP\", `Capability \"${spec}\" has no actions.`, ExitCode.USAGE_ERROR);\n }\n\n return { service, space: resolvedSpace, path, actions };\n}\n\nexport async function loadPermissionRequest(\n source: string,\n profile: string,\n): Promise<PermissionEntry[]> {\n const raw = JSON.parse(await readFile(source, \"utf8\")) as { permissions?: PermissionEntry[] };\n if (!Array.isArray(raw.permissions)) {\n throw new CLIError(\n \"INVALID_PERMISSION_REQUEST\",\n `Permission request ${source} must contain { \"permissions\": [...] }.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return resolvePermissionSpaces(raw.permissions, profile);\n}\n\nexport async function loadManifestPermissions(\n source: string,\n profile: string,\n): Promise<PermissionEntry[]> {\n const raw = await loadManifestText(source);\n const manifest = JSON.parse(raw) as Record<string, unknown>;\n\n if (typeof manifest.id === \"string\") {\n const resolved = resolveManifest(manifest as Parameters<typeof resolveManifest>[0]);\n return resolvePermissionSpaces(resolved.resources, profile);\n }\n\n if (typeof manifest.app_id === \"string\") {\n const permissions = ((manifest.permissions as unknown[]) ?? [])\n .filter((entry): entry is Record<string, unknown> => entry !== null && typeof entry === \"object\")\n .map((entry) => {\n const service = normalizeService(String(entry.service ?? \"\"));\n const path = String(entry.path ?? \"\");\n const skipPrefix = entry.skipPrefix === true;\n const resolvedPath = skipPrefix\n ? path\n : prefixAppManifestPath(path, manifest.app_id as string);\n return {\n service,\n space: String(manifest.space ?? \"applications\"),\n path: resolvedPath,\n actions: expandActionShortNames(\n service,\n Array.isArray(entry.actions)\n ? entry.actions.map(String)\n : [],\n ),\n };\n });\n return resolvePermissionSpaces(permissions, profile);\n }\n\n throw new CLIError(\n \"INVALID_MANIFEST\",\n \"Manifest must contain either SDK field \\\"id\\\" or app manifest field \\\"app_id\\\".\",\n ExitCode.USAGE_ERROR,\n );\n}\n\nexport function diffPermissions(\n requested: PermissionEntry[],\n granted: PermissionEntry[],\n): PermissionEntry[] {\n return isCapabilitySubset(requested, granted).missing;\n}\n\nexport function permissionsFromDelegation(\n delegation: PortableDelegation,\n): PermissionEntry[] {\n if (delegation.resources?.length) {\n return delegation.resources.map((resource) => ({\n service: resource.service.startsWith(\"tinycloud.\")\n ? resource.service\n : `tinycloud.${resource.service}`,\n space: resource.space,\n path: resource.path,\n actions: [...resource.actions],\n }));\n }\n return [{\n service: serviceFromActions(delegation.actions),\n space: delegation.spaceId,\n path: delegation.path,\n actions: [...delegation.actions],\n }];\n}\n\nexport function compactPermission(permission: PermissionEntry): string {\n const service = permission.service;\n const space = permission.space.startsWith(\"tinycloud:\")\n ? permission.space.slice(permission.space.lastIndexOf(\":\") + 1)\n : permission.space;\n const actions = permission.actions\n .map((action) => action.startsWith(`${service}/`) ? action.slice(service.length + 1) : action)\n .join(\",\");\n return `${service}:${space}:${permission.path}:${actions}`;\n}\n\nasync function resolvePermissionSpaces(\n entries: PermissionEntry[],\n profile: string,\n): Promise<PermissionEntry[]> {\n const resolved: PermissionEntry[] = [];\n for (const entry of entries) {\n const service = normalizeService(entry.service);\n resolved.push({\n ...entry,\n service,\n space: await resolveSpaceUri(entry.space, profile) ?? entry.space,\n actions: expandActionShortNames(service, entry.actions),\n });\n }\n return resolved;\n}\n\nasync function loadManifestText(source: string): Promise<string> {\n if (source.startsWith(\"base64:\")) {\n return Buffer.from(source.slice(\"base64:\".length), \"base64\").toString(\"utf8\");\n }\n if (await fileExists(source)) {\n return readFile(source, \"utf8\");\n }\n try {\n const decoded = Buffer.from(source, \"base64\").toString(\"utf8\");\n JSON.parse(decoded);\n return decoded;\n } catch {\n return readFile(source, \"utf8\");\n }\n}\n\nfunction normalizeService(service: string): string {\n if (!service) {\n throw new CLIError(\"INVALID_CAP\", \"Capability service is required.\", ExitCode.USAGE_ERROR);\n }\n return service.startsWith(\"tinycloud.\") ? service : `tinycloud.${service}`;\n}\n\nfunction splitSpaceAndPath(input: string): { space: string; path: string } {\n if (input.startsWith(\"tinycloud:\")) {\n const parts = input.split(\":\");\n if (parts.length < 7) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Full tinycloud space specs must include a path after the space URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return {\n space: parts.slice(0, 6).join(\":\"),\n path: parts.slice(6).join(\":\"),\n };\n }\n\n const colon = input.indexOf(\":\");\n if (colon <= 0) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Capability must include both space and path.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return {\n space: input.slice(0, colon),\n path: input.slice(colon + 1),\n };\n}\n\nfunction prefixAppManifestPath(path: string, appId: string): string {\n const slash = path.indexOf(\"/\");\n if (slash === -1) return `${appId}/${path}`;\n return `${path.slice(0, slash)}/${appId}/${path.slice(slash + 1)}`;\n}\n\nfunction serviceFromActions(actions: string[]): string {\n const first = actions[0] ?? \"tinycloud.unknown/read\";\n return first.includes(\"/\") ? first.slice(0, first.indexOf(\"/\")) : \"tinycloud.unknown\";\n}\n","import { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport type { ProfileConfig } from \"../config/types.js\";\n\n/**\n * Resolve the active profile's Ethereum address. Source priority matches\n * what TinyCloudNode.signIn / restoreSession actually populates:\n * 1) session.address (set by both local-key and OpenKey auth flows)\n * 2) profile.address (local-key auth only)\n * 3) the address segment of profile.ownerDid (did:pkh:eip155:<chain>:<addr>)\n */\nfunction resolveAddress(profile: ProfileConfig, session: Record<string, unknown> | null): string {\n const sessAddr = session?.address;\n if (typeof sessAddr === \"string\" && sessAddr.length > 0) return sessAddr;\n\n if (profile.address) return profile.address;\n\n if (profile.ownerDid) {\n const match = profile.ownerDid.match(/^did:pkh:eip155:\\d+:(0x[a-fA-F0-9]{40})$/);\n if (match) return match[1];\n }\n\n throw new CLIError(\n \"ADDRESS_UNKNOWN\",\n `Cannot determine Ethereum address for profile \"${profile.name}\". Run \\`tc auth login\\` to refresh the session.`,\n ExitCode.AUTH_REQUIRED,\n );\n}\n\nfunction resolveChainId(profile: ProfileConfig, session: Record<string, unknown> | null): number {\n const sessChain = session?.chainId;\n if (typeof sessChain === \"number\" && Number.isFinite(sessChain)) return sessChain;\n return profile.chainId;\n}\n\n/**\n * Resolve a --space CLI argument into a full TinyCloud space URI.\n *\n * - undefined → undefined (caller falls back to node.spaceId)\n * - \"tinycloud:...\" → returned verbatim\n * - bare name → tinycloud:pkh:eip155:<chain>:<address>:<name>\n */\nexport async function resolveSpaceUri(\n input: string | undefined,\n profileName: string,\n): Promise<string | undefined> {\n if (!input) return undefined;\n if (input.startsWith(\"tinycloud:\")) return input;\n\n if (!/^[A-Za-z0-9_-]+$/.test(input)) {\n throw new CLIError(\n \"INVALID_SPACE\",\n `Invalid --space \"${input}\". Use a short name ([A-Za-z0-9_-]) or a full tinycloud:... URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const profile = await ProfileManager.getProfile(profileName);\n const session = (await ProfileManager.getSession(profileName)) as Record<string, unknown> | null;\n\n const address = resolveAddress(profile, session);\n const chainId = resolveChainId(profile, session);\n return `tinycloud:pkh:eip155:${chainId}:${address}:${input}`;\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes, formatTimeAgo } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\nexport function registerKvCommand(program: Command): void {\n const kv = program.command(\"kv\").description(\"Key-value store operations\");\n\n // tc kv get <key>\n kv\n .command(\"get <key>\")\n .description(\"Get a value by key\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Getting ${key}...`, () => node.kv.get(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Key \"${key}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data;\n const metadata = result.data.headers ?? {};\n\n if (options.output) {\n // Write to file\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n await writeFile(options.output, content);\n outputJson({ key, written: options.output });\n return;\n }\n\n if (options.raw) {\n // Raw output - write directly to stdout\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content);\n return;\n }\n\n // Output value\n if (shouldOutputJson()) {\n outputJson({\n key,\n data,\n metadata,\n });\n } else {\n // Just output the raw value for get - useful for piping\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv put <key> [value]\n kv\n .command(\"put <key> [value]\")\n .description(\"Set a value\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .action(async (key: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n // Determine value source\n let putValue: string | Buffer;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n putValue = await readFile(options.file);\n } else if (options.stdin) {\n putValue = await readStdin();\n } else {\n // Try to parse as JSON, fall back to string\n try {\n putValue = JSON.parse(value!);\n } catch {\n putValue = value!;\n }\n }\n\n const result = await withSpinner(`Writing ${key}...`, () => node.kv.put(key, putValue)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv delete <key>\n kv\n .command(\"delete <key>\")\n .description(\"Delete a key\")\n .action(async (key: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Deleting ${key}...`, () => node.kv.delete(key)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv list\n kv\n .command(\"list\")\n .description(\"List keys\")\n .option(\"--prefix <prefix>\", \"Filter by key prefix\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing keys...\", () => node.kv.list(listOptions)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const rawData = result.data.data ?? result.data;\n const keyList = Array.isArray(rawData) ? rawData : (rawData?.keys ?? []);\n\n if (shouldOutputJson()) {\n outputJson({\n keys: keyList,\n count: keyList.length,\n prefix: options.prefix ?? null,\n });\n } else {\n if (keyList.length === 0) {\n process.stdout.write(theme.muted(\"No keys found.\") + \"\\n\");\n } else {\n const rows = keyList.map((e: any) => [\n e.key || e,\n e.contentLength ? formatBytes(e.contentLength) : \"—\",\n e.updatedAt ? formatTimeAgo(e.updatedAt) : \"—\",\n ]);\n process.stdout.write(formatTable([\"Key\", \"Size\", \"Updated\"], rows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv head <key>\n kv\n .command(\"head <key>\")\n .description(\"Get metadata for a key (no body)\")\n .action(async (key: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Checking ${key}...`, () => node.kv.head(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n outputJson({ key, exists: false, metadata: {} });\n return;\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n key,\n exists: true,\n metadata: result.data.headers ?? {},\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatTable } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerSpaceCommand(program: Command): void {\n const space = program.command(\"space\").description(\"Space management\");\n\n space\n .command(\"list\")\n .description(\"List spaces\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.spaces.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n if (shouldOutputJson()) {\n outputJson({ spaces: result.data, count: result.data.length });\n } else {\n if (result.data.length === 0) {\n process.stdout.write(theme.muted(\"No spaces found.\") + \"\\n\");\n } else {\n const rows = result.data.map((s: any) => [\n s.id || s.spaceId || \"—\",\n s.name || \"—\",\n s.owner || \"—\",\n ]);\n process.stdout.write(formatTable([\"Space ID\", \"Name\", \"Owner\"], rows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"create <name>\")\n .description(\"Create a new space\")\n .action(async (name: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.spaces.create(name);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n outputJson({ spaceId: result.data.id, name });\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"info [space-id]\")\n .description(\"Get space info\")\n .action(async (spaceId: string | undefined, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const targetId = spaceId ?? node.spaceId;\n if (!targetId) {\n throw new CLIError(\"NO_SPACE\", \"No space ID specified and no active space\", ExitCode.ERROR);\n }\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n outputJson({\n spaceId: targetId,\n name: profile.spaceName,\n owner: node.did,\n host: ctx.host,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"switch <name>\")\n .description(\"Switch active space\")\n .action(async (name: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n await ProfileManager.setProfile(ctx.profile, { ...profile, spaceName: name });\n\n outputJson({ profile: ctx.profile, spaceName: name, switched: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","/**\n * Parse a duration string into milliseconds.\n * Supports: \"1h\", \"30m\", \"7d\", \"1w\", or ISO date string.\n */\nexport function parseDuration(input: string): number {\n const match = input.match(/^(\\d+)(m|h|d|w)$/);\n if (match) {\n const value = parseInt(match[1], 10);\n const unit = match[2];\n const multipliers: Record<string, number> = {\n m: 60 * 1000,\n h: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n w: 7 * 24 * 60 * 60 * 1000,\n };\n return value * multipliers[unit];\n }\n\n // Try as ISO date\n const date = new Date(input);\n if (!isNaN(date.getTime())) {\n const ms = date.getTime() - Date.now();\n if (ms <= 0) {\n throw new Error(`Expiry date \"${input}\" is in the past`);\n }\n return ms;\n }\n\n throw new Error(`Invalid duration: \"${input}\". Use format like \"1h\", \"7d\", or an ISO date.`);\n}\n\n/**\n * Parse duration to an expiry Date.\n */\nexport function parseExpiry(input: string): Date {\n return new Date(Date.now() + parseDuration(input));\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { parseExpiry } from \"../lib/duration.js\";\n\nexport function registerDelegationCommand(program: Command): void {\n const delegation = program.command(\"delegation\").description(\"Manage delegations\");\n\n delegation\n .command(\"create\")\n .description(\"Create a delegation\")\n .requiredOption(\"--to <did>\", \"Recipient DID\")\n .requiredOption(\"--path <path>\", \"KV path scope\")\n .requiredOption(\"--actions <actions>\", \"Comma-separated actions (e.g., kv/get,kv/list)\")\n .option(\"--expiry <duration>\", \"Expiry duration (e.g., 1h, 7d, ISO date)\", \"1h\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const actions = options.actions.split(\",\").map((a: string) => {\n const trimmed = a.trim();\n return trimmed.startsWith(\"tinycloud.\") ? trimmed : `tinycloud.${trimmed}`;\n });\n\n const expiry = parseExpiry(options.expiry);\n\n const result = await node.delegationManager.create({\n delegateDID: options.to,\n path: options.path,\n actions,\n expiry,\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n cid: result.data.cid,\n delegateDid: options.to,\n path: options.path,\n actions,\n expiry: expiry.toISOString(),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"list\")\n .description(\"List delegations\")\n .option(\"--granted\", \"Show only delegations I've granted\")\n .option(\"--received\", \"Show only delegations I've received\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n let delegations: any[] = result.data;\n\n // Filter if requested\n if (options.granted) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => d.delegatorDID === myDid);\n } else if (options.received) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => d.delegateDID === myDid || d.delegateDID?.includes(myDid));\n }\n\n outputJson({\n delegations: delegations.map((d: any) => ({\n cid: d.cid,\n delegatee: d.delegateDID,\n delegator: d.delegatorDID,\n path: d.path,\n actions: d.actions,\n expiry: d.expiry instanceof Date ? d.expiry.toISOString() : d.expiry,\n })),\n count: delegations.length,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"info <cid>\")\n .description(\"Get delegation details\")\n .action(async (cid: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.get(cid);\n if (!result.ok) {\n throw new CLIError(\"NOT_FOUND\", `Delegation \"${cid}\" not found`, ExitCode.NOT_FOUND);\n }\n\n outputJson(result.data);\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"revoke <cid>\")\n .description(\"Revoke a delegation\")\n .action(async (cid: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.revoke(cid);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ cid, revoked: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { parseExpiry } from \"../lib/duration.js\";\n\nexport function registerShareCommand(program: Command): void {\n const share = program.command(\"share\").description(\"Share data with others\");\n\n share\n .command(\"create\")\n .description(\"Create a share link\")\n .requiredOption(\"--path <path>\", \"KV path scope\")\n .option(\"--actions <actions>\", \"Comma-separated actions\", \"kv/get\")\n .option(\"--expiry <duration>\", \"Expiry duration\", \"7d\")\n .option(\"--web-link\", \"Generate a web UI link for non-technical recipients\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const actions = options.actions.split(\",\").map((a: string) => {\n const trimmed = a.trim();\n return trimmed.startsWith(\"tinycloud.\") ? trimmed : `tinycloud.${trimmed}`;\n });\n\n const expiry = parseExpiry(options.expiry);\n\n const result = await node.sharing.generate({\n path: options.path,\n actions,\n expiry,\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const output: Record<string, unknown> = {\n token: result.data.token ?? result.data.cid,\n shareData: result.data.encodedData ?? result.data.url,\n path: options.path,\n actions,\n expiry: expiry.toISOString(),\n };\n\n if (options.webLink) {\n const shareData = result.data.encodedData ?? result.data.url ?? \"\";\n output.webLink = `https://openkey.cloud/share?data=${encodeURIComponent(shareData)}`;\n }\n\n outputJson(output);\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"receive [data]\")\n .description(\"Receive a share\")\n .option(\"--stdin\", \"Read share data from stdin\")\n .action(async (data: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n let shareData: string;\n if (options.stdin) {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n shareData = Buffer.concat(chunks).toString(\"utf-8\").trim();\n } else if (data) {\n shareData = data;\n } else {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide share data or use --stdin\", ExitCode.USAGE_ERROR);\n }\n\n const result = await node.sharing.receive(shareData);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n received: true,\n spaceId: result.data.spaceId,\n path: result.data.path,\n actions: result.data.actions,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"list\")\n .description(\"List active shares\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.sharing.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ shares: result.data, count: result.data.length });\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"revoke <token>\")\n .description(\"Revoke a share\")\n .action(async (token: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.sharing.revoke(token);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ token, revoked: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\n\nexport function registerNodeCommand(program: Command): void {\n const node = program.command(\"node\").description(\"Node health and info\");\n\n node\n .command(\"health\")\n .description(\"Check node health\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const start = Date.now();\n const response = await fetch(`${ctx.host}/healthz`);\n const latencyMs = Date.now() - start;\n\n outputJson({\n healthy: response.ok,\n host: ctx.host,\n latencyMs,\n });\n } catch (error) {\n if (error instanceof TypeError && (error as Error).message.includes(\"fetch\")) {\n outputJson({ healthy: false, host: (await ProfileManager.resolveContext(cmd.optsWithGlobals())).host, error: \"Connection refused\" });\n } else {\n handleError(error);\n }\n }\n });\n\n node\n .command(\"version\")\n .description(\"Get node version\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const response = await fetch(`${ctx.host}/info`);\n if (!response.ok) {\n throw new CLIError(\"NODE_ERROR\", `Node returned ${response.status}`, ExitCode.NODE_ERROR);\n }\n\n const data = await response.json() as Record<string, unknown>;\n outputJson({ ...data, host: ctx.host });\n } catch (error) {\n handleError(error);\n }\n });\n\n node\n .command(\"status\")\n .description(\"Combined health and version info\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const start = Date.now();\n\n // Fetch health and version in parallel\n const [healthRes, versionRes] = await Promise.allSettled([\n fetch(`${ctx.host}/healthz`),\n fetch(`${ctx.host}/info`),\n ]);\n\n const latencyMs = Date.now() - start;\n const healthy = healthRes.status === \"fulfilled\" && healthRes.value.ok;\n\n let versionData: Record<string, unknown> = {};\n if (versionRes.status === \"fulfilled\" && versionRes.value.ok) {\n versionData = await versionRes.value.json() as Record<string, unknown>;\n }\n\n outputJson({\n healthy,\n host: ctx.host,\n latencyMs,\n ...versionData,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, isInteractive, shouldOutputJson, formatField } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { generateKey } from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\nimport {\n CLI_OPERATOR_TYPES,\n CLI_PROFILE_POSTURES,\n isCLIOperatorType,\n isCLIProfilePosture,\n resolveProfileOperatorType,\n resolveProfilePosture,\n type CLIOperatorType,\n type CLIProfilePosture,\n} from \"../config/types.js\";\n\nexport function registerProfileCommand(program: Command): void {\n const profile = program.command(\"profile\").description(\"Profile management\");\n\n profile\n .command(\"list\")\n .description(\"List all profiles\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const config = await ProfileManager.getConfig();\n const names = await ProfileManager.listProfiles();\n\n const profiles = await Promise.all(\n names.map(async (name) => {\n try {\n const p = await ProfileManager.getProfile(name);\n return {\n name: p.name,\n host: p.host,\n did: p.did,\n posture: resolveProfilePosture(p),\n operatorType: resolveProfileOperatorType(p),\n active: name === config.defaultProfile,\n };\n } catch {\n return {\n name,\n host: null,\n did: null,\n posture: null,\n operatorType: null,\n active: name === config.defaultProfile,\n };\n }\n })\n );\n\n if (shouldOutputJson()) {\n outputJson({\n profiles,\n defaultProfile: config.defaultProfile,\n });\n } else {\n for (const p of profiles) {\n const marker = p.active ? theme.success(\"● \") : \" \";\n const name = p.active ? theme.brand(p.name) : p.name;\n const host = theme.muted(p.host || \"no host\");\n const posture = p.posture ? theme.muted(String(p.posture)) : theme.muted(\"no posture\");\n process.stdout.write(`${marker}${name} ${host} ${posture}\\n`);\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"create <name>\")\n .description(\"Create a new profile\")\n .option(\"--host <url>\", \"TinyCloud node URL\")\n .option(\n \"--posture <posture>\",\n `Profile posture: ${CLI_PROFILE_POSTURES.join(\", \")}. Defaults to owner-openkey.`,\n )\n .option(\n \"--operator <type>\",\n `Operator type: ${CLI_OPERATOR_TYPES.join(\", \")}. Defaults to human.`,\n )\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const host = options.host ?? globalOpts.host ?? \"https://node.tinycloud.xyz\";\n const posture = parseProfilePosture(options.posture);\n const operatorType = parseOperatorType(options.operator);\n\n if (await ProfileManager.profileExists(name)) {\n throw new CLIError(\"PROFILE_EXISTS\", `Profile \"${name}\" already exists`, ExitCode.ERROR);\n }\n\n await ProfileManager.ensureConfigDir();\n const { jwk, did } = generateKey();\n await ProfileManager.setKey(name, jwk);\n await ProfileManager.setProfile(name, {\n name,\n host,\n chainId: 1,\n spaceName: \"default\",\n did,\n sessionDid: did,\n createdAt: new Date().toISOString(),\n posture,\n operatorType,\n });\n\n outputJson({ profile: name, did, host, posture, operatorType, created: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"show [name]\")\n .description(\"Show profile details\")\n .action(async (name: string | undefined, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profileName = name ?? ctx.profile;\n\n const p = await ProfileManager.getProfile(profileName);\n const hasKey = (await ProfileManager.getKey(profileName)) !== null;\n const hasSession = (await ProfileManager.getSession(profileName)) !== null;\n const config = await ProfileManager.getConfig();\n const isDefault = profileName === config.defaultProfile;\n const posture = resolveProfilePosture(p);\n const operatorType = resolveProfileOperatorType(p);\n\n if (shouldOutputJson()) {\n outputJson({\n ...p,\n posture,\n operatorType,\n hasKey,\n hasSession,\n isDefault,\n });\n } else {\n process.stdout.write(`${theme.heading(p.name)}${isDefault ? theme.success(\" (default)\") : \"\"}\\n`);\n process.stdout.write(formatField(\"Host\", p.host) + \"\\n\");\n process.stdout.write(formatField(\"DID\", p.did) + \"\\n\");\n process.stdout.write(formatField(\"Session DID\", p.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\n\");\n process.stdout.write(formatField(\"Space\", p.spaceId || null) + \"\\n\");\n process.stdout.write(formatField(\"Key\", hasKey) + \"\\n\");\n process.stdout.write(formatField(\"Session\", hasSession) + \"\\n\");\n process.stdout.write(formatField(\"Created\", p.createdAt) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"switch <name>\")\n .description(\"Set default profile\")\n .action(async (name: string, _options, cmd) => {\n try {\n if (!(await ProfileManager.profileExists(name))) {\n throw new CLIError(\"PROFILE_NOT_FOUND\", `Profile \"${name}\" does not exist`, ExitCode.NOT_FOUND);\n }\n\n const config = await ProfileManager.getConfig();\n await ProfileManager.setConfig({ ...config, defaultProfile: name });\n\n outputJson({ defaultProfile: name, switched: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"delete <name>\")\n .description(\"Delete a profile\")\n .action(async (name: string, _options, cmd) => {\n try {\n // Confirmation prompt if interactive\n if (isInteractive()) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Delete profile \"${name}\"? This cannot be undone. [y/N] `, resolve);\n });\n rl.close();\n if (answer.toLowerCase() !== \"y\") {\n outputJson({ profile: name, deleted: false, reason: \"Cancelled by user\" });\n return;\n }\n }\n\n await ProfileManager.deleteProfile(name);\n outputJson({ profile: name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nfunction parseProfilePosture(raw: unknown): CLIProfilePosture {\n if (raw === undefined || raw === null || raw === \"\") return \"owner-openkey\";\n if (isCLIProfilePosture(raw)) return raw;\n throw new CLIError(\n \"INVALID_POSTURE\",\n `Invalid posture \"${String(raw)}\". Use one of: ${CLI_PROFILE_POSTURES.join(\", \")}.`,\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction parseOperatorType(raw: unknown): CLIOperatorType {\n if (raw === undefined || raw === null || raw === \"\") return \"human\";\n if (isCLIOperatorType(raw)) return raw;\n throw new CLIError(\n \"INVALID_OPERATOR\",\n `Invalid operator \"${String(raw)}\". Use one of: ${CLI_OPERATOR_TYPES.join(\", \")}.`,\n ExitCode.USAGE_ERROR,\n );\n}\n","import { Command } from \"commander\";\n\nexport function registerCompletionCommand(program: Command): void {\n const completion = program.command(\"completion\").description(\"Generate shell completions\");\n\n completion\n .command(\"bash\")\n .description(\"Output bash completions\")\n .action(() => {\n const script = generateBashCompletion();\n process.stdout.write(script);\n });\n\n completion\n .command(\"zsh\")\n .description(\"Output zsh completions\")\n .action(() => {\n const script = generateZshCompletion();\n process.stdout.write(script);\n });\n\n completion\n .command(\"fish\")\n .description(\"Output fish completions\")\n .action(() => {\n const script = generateFishCompletion();\n process.stdout.write(script);\n });\n}\n\nfunction generateBashCompletion(): string {\n return `# tc bash completion\n_tc_completions() {\n local cur prev commands subcommands\n COMPREPLY=()\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\n\n commands=\"init auth kv space delegation share node profile completion\"\n\n case \"\\${COMP_WORDS[1]}\" in\n auth) subcommands=\"login logout status whoami\" ;;\n kv) subcommands=\"get put delete list head\" ;;\n space) subcommands=\"list create info switch\" ;;\n delegation) subcommands=\"create list info revoke\" ;;\n share) subcommands=\"create receive list revoke\" ;;\n node) subcommands=\"health version status\" ;;\n profile) subcommands=\"list create show switch delete\" ;;\n completion) subcommands=\"bash zsh fish\" ;;\n *) COMPREPLY=( $(compgen -W \"\\${commands}\" -- \"\\${cur}\") ); return ;;\n esac\n\n if [ \\${COMP_CWORD} -eq 2 ]; then\n COMPREPLY=( $(compgen -W \"\\${subcommands}\" -- \"\\${cur}\") )\n fi\n}\ncomplete -F _tc_completions tc\n`;\n}\n\nfunction generateZshCompletion(): string {\n return `#compdef tc\n\n_tc() {\n local -a commands\n commands=(\n 'init:Initialize a new TinyCloud profile'\n 'auth:Authentication management'\n 'kv:Key-value store operations'\n 'space:Space management'\n 'delegation:Manage delegations'\n 'share:Share data with others'\n 'node:Node health and info'\n 'profile:Profile management'\n 'completion:Generate shell completions'\n )\n\n _arguments -C \\\\\n '(-p --profile)'{-p,--profile}'[Profile to use]:profile:' \\\\\n '(-H --host)'{-H,--host}'[TinyCloud node URL]:url:' \\\\\n '(-v --verbose)'{-v,--verbose}'[Enable verbose output]' \\\\\n '--no-cache[Disable caching]' \\\\\n '(-q --quiet)'{-q,--quiet}'[Suppress non-essential output]' \\\\\n '1:command:->cmd' \\\\\n '*::arg:->args'\n\n case $state in\n cmd)\n _describe 'command' commands\n ;;\n args)\n case $words[1] in\n auth) _values 'subcommand' login logout status whoami ;;\n kv) _values 'subcommand' get put delete list head ;;\n space) _values 'subcommand' list create info switch ;;\n delegation) _values 'subcommand' create list info revoke ;;\n share) _values 'subcommand' create receive list revoke ;;\n node) _values 'subcommand' health version status ;;\n profile) _values 'subcommand' list create show switch delete ;;\n completion) _values 'subcommand' bash zsh fish ;;\n esac\n ;;\n esac\n}\n\n_tc\n`;\n}\n\nfunction generateFishCompletion(): string {\n return `# tc fish completion\nset -l commands init auth kv space delegation share node profile completion\n\n# Disable file completion by default\ncomplete -c tc -f\n\n# Top-level commands\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a init -d \"Initialize a new TinyCloud profile\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a auth -d \"Authentication management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a kv -d \"Key-value store operations\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a space -d \"Space management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a delegation -d \"Manage delegations\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a share -d \"Share data with others\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a node -d \"Node health and info\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a profile -d \"Profile management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a completion -d \"Generate shell completions\"\n\n# Subcommands\ncomplete -c tc -n \"__fish_seen_subcommand_from auth\" -a \"login logout status whoami\"\ncomplete -c tc -n \"__fish_seen_subcommand_from kv\" -a \"get put delete list head\"\ncomplete -c tc -n \"__fish_seen_subcommand_from space\" -a \"list create info switch\"\ncomplete -c tc -n \"__fish_seen_subcommand_from delegation\" -a \"create list info revoke\"\ncomplete -c tc -n \"__fish_seen_subcommand_from share\" -a \"create receive list revoke\"\ncomplete -c tc -n \"__fish_seen_subcommand_from node\" -a \"health version status\"\ncomplete -c tc -n \"__fish_seen_subcommand_from profile\" -a \"list create show switch delete\"\ncomplete -c tc -n \"__fish_seen_subcommand_from completion\" -a \"bash zsh fish\"\n\n# Global options\ncomplete -c tc -l profile -s p -d \"Profile to use\"\ncomplete -c tc -l host -s H -d \"TinyCloud node URL\"\ncomplete -c tc -l verbose -s v -d \"Enable verbose output\"\ncomplete -c tc -l no-cache -d \"Disable caching\"\ncomplete -c tc -l quiet -s q -d \"Suppress non-essential output\"\n`;\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { PrivateKeySigner } from \"@tinycloud/node-sdk\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\n/**\n * Unlock the vault on a TinyCloudNode instance.\n */\nasync function unlockVault(\n node: { vault: { unlock(signer: { signMessage(message: string): Promise<string> }): Promise<any> } },\n privateKey: string,\n): Promise<void> {\n const signer = new PrivateKeySigner(privateKey);\n const result = await node.vault.unlock(signer);\n if (result && !result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n}\n\nexport function registerVaultCommand(program: Command): void {\n const vault = program.command(\"vault\").description(\"Encrypted vault operations\");\n\n // tc vault unlock\n vault\n .command(\"unlock\")\n .description(\"Verify vault unlock works\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n outputJson({ unlocked: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault put <key> [value]\n vault\n .command(\"put <key> [value]\")\n .description(\"Encrypt and store a value\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n // Determine value source\n let putValue: string | Uint8Array;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n putValue = new Uint8Array(await readFile(options.file));\n } else if (options.stdin) {\n putValue = new Uint8Array(await readStdin());\n } else {\n putValue = value!;\n }\n\n const result = await withSpinner(`Writing ${key}...`, () => node.vault.put(key, putValue)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault get <key>\n vault\n .command(\"get <key>\")\n .description(\"Decrypt and retrieve a value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Getting ${key}...`, () => node.vault.get(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Key \"${key}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data ?? result.data;\n\n if (options.output) {\n const content = data instanceof Uint8Array ? Buffer.from(data) : typeof data === \"string\" ? data : JSON.stringify(data);\n await writeFile(options.output, content);\n outputJson({ key, written: options.output });\n return;\n }\n\n if (options.raw) {\n const content = data instanceof Uint8Array ? Buffer.from(data) : typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content);\n return;\n }\n\n outputJson({\n key,\n data: data instanceof Uint8Array ? Buffer.from(data).toString(\"base64\") : data,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault delete <key>\n vault\n .command(\"delete <key>\")\n .description(\"Delete an encrypted key\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Deleting ${key}...`, () => node.vault.delete(key)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault list\n vault\n .command(\"list\")\n .description(\"List vault keys\")\n .option(\"--prefix <prefix>\", \"Filter by key prefix\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing vault keys...\", () => node.vault.list(listOptions)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const keys = result.data.data ?? result.data;\n const keyList = Array.isArray(keys) ? keys : [];\n\n outputJson({\n keys: keyList,\n count: keyList.length,\n prefix: options.prefix ?? null,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault head <key>\n vault\n .command(\"head <key>\")\n .description(\"Get metadata for a vault key\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Checking ${key}...`, () => node.vault.head(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n outputJson({ key, exists: false, metadata: {} });\n return;\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n key,\n exists: true,\n metadata: result.data.headers ?? result.data,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\nfunction authOptions(options: { privateKey?: string }): { privateKey?: string } | undefined {\n const privateKey = options.privateKey || process.env.TC_PRIVATE_KEY;\n return privateKey ? { privateKey } : undefined;\n}\n\nfunction resolveSecretScope(options: { scope?: string; space?: string }): { scope?: string } | undefined {\n const scope = options.scope ?? options.space;\n return scope ? { scope } : undefined;\n}\n\nexport function registerSecretsCommand(program: Command): void {\n const secrets = program.command(\"secrets\").description(\"Encrypted secrets management\");\n\n const network = secrets\n .command(\"network\")\n .description(\"Manage the default secrets encryption network\");\n\n network\n .command(\"show [nameOrNetworkId]\")\n .description(\"Show a secrets encryption network\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (nameOrNetworkId: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const requested = nameOrNetworkId ?? \"default\";\n const networkId = requested.startsWith(\"urn:tinycloud:encryption:\")\n ? requested\n : node.getDefaultEncryptionNetworkId(requested);\n const descriptor = await withSpinner(\n \"Fetching encryption network...\",\n () => node.getEncryptionNetwork(requested),\n );\n outputJson({\n networkId,\n exists: descriptor !== null,\n ...(descriptor ? { descriptor } : {}),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n network\n .command(\"init [name]\")\n .description(\"Create a secrets encryption network if needed\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (name: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const descriptor = await withSpinner(\n \"Ensuring encryption network...\",\n () => node.ensureEncryptionNetwork(name ?? \"default\"),\n );\n outputJson({\n networkId: descriptor.networkId,\n state: descriptor.state,\n descriptor,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets list\n secrets\n .command(\"list\")\n .description(\"List secrets\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const scopeOptions = resolveSecretScope(options);\n const result = await withSpinner(\n \"Listing secrets...\",\n () => node.secrets.list(scopeOptions),\n );\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const secretNames = Array.isArray(result.data) ? result.data : [];\n const scope = options.scope ?? options.space;\n\n outputJson({\n secrets: secretNames,\n count: secretNames.length,\n ...(scope ? { scope } : {}),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets get <name>\n secrets\n .command(\"get <name>\")\n .description(\"Get a secret value\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const scopeOptions = resolveSecretScope(options);\n const result = await withSpinner(\n `Getting secret ${name}...`,\n () => node.secrets.get(name, scopeOptions),\n );\n\n if (!result.ok) {\n if (\n result.error.code === \"NOT_FOUND\" ||\n result.error.code === \"KEY_NOT_FOUND\"\n ) {\n throw new CLIError(\"NOT_FOUND\", `Secret \"${name}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const value = String(result.data);\n\n if (options.output) {\n await writeFile(options.output, value);\n outputJson({ name, written: options.output });\n return;\n }\n\n if (options.raw) {\n process.stdout.write(value);\n return;\n }\n\n outputJson({ name, value });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets put <name> [value]\n secrets\n .command(\"put <name> [value]\")\n .description(\"Store a secret\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n\n // Determine value source\n let secretValue: string;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n secretValue = (await readFile(options.file, \"utf-8\")) as string;\n } else if (options.stdin) {\n secretValue = (await readStdin()).toString(\"utf-8\");\n } else {\n secretValue = value!;\n }\n\n const scopeOptions = resolveSecretScope(options);\n const result = await withSpinner(\n `Storing secret ${name}...`,\n () => node.secrets.put(name, secretValue, scopeOptions),\n );\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets delete <name>\n secrets\n .command(\"delete <name>\")\n .description(\"Delete a secret\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const scopeOptions = resolveSecretScope(options);\n const result = await withSpinner(\n `Deleting secret ${name}...`,\n () => node.secrets.delete(name, scopeOptions),\n );\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n network\n .command(\"grant <recipientDid> [name]\")\n .description(\"Grant decrypt permission for a secrets encryption network\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (recipientDid: string, name: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const networkName = name ?? \"default\";\n const descriptor = await withSpinner(\n \"Ensuring encryption network...\",\n () => node.ensureEncryptionNetwork(networkName),\n );\n const permission = {\n service: \"tinycloud.encryption\",\n path: descriptor.networkId,\n actions: [\"decrypt\"],\n };\n const result = await withSpinner(\n `Granting decrypt permission to ${recipientDid}...`,\n () => node.delegateTo(recipientDid, [permission]),\n );\n\n outputJson({\n networkId: descriptor.networkId,\n recipientDid,\n cid: result.delegation.cid,\n prompted: result.prompted,\n path: result.delegation.path,\n actions: result.delegation.actions,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets manage\n secrets\n .command(\"manage\")\n .description(\"Open the TinyCloud Secrets Manager in your browser\")\n .action(async () => {\n try {\n const open = (await import(\"open\")).default;\n await open(\"https://secrets.tinycloud.xyz\");\n outputJson({ opened: \"https://secrets.tinycloud.xyz\" });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\n\nconst VARIABLES_PREFIX = \"variables/\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\nexport function registerVarsCommand(program: Command): void {\n const vars = program.command(\"vars\").description(\"Plaintext variable management\");\n\n // tc vars list\n vars\n .command(\"list\")\n .description(\"List variables\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(\"Listing variables...\", () => prefixedKv.list()) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const rawData = result.data.data ?? result.data;\n const keyList = Array.isArray(rawData) ? rawData : (rawData?.keys ?? []);\n\n outputJson({\n variables: keyList,\n count: keyList.length,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars get <name>\n vars\n .command(\"get <name>\")\n .description(\"Get a variable value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Getting variable ${name}...`, () => prefixedKv.get(name)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Variable \"${name}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data;\n\n // Extract value from the stored payload\n let value: string;\n if (typeof data === \"string\") {\n try {\n const parsed = JSON.parse(data);\n value = parsed.value;\n } catch {\n value = data;\n }\n } else if (data && typeof data === \"object\" && \"value\" in data) {\n value = data.value;\n } else {\n value = typeof data === \"string\" ? data : JSON.stringify(data);\n }\n\n if (options.output) {\n await writeFile(options.output, value);\n outputJson({ name, written: options.output });\n return;\n }\n\n if (options.raw) {\n process.stdout.write(value);\n return;\n }\n\n outputJson({ name, value });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars put <name> [value]\n vars\n .command(\"put <name> [value]\")\n .description(\"Set a variable\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n // Determine value source\n let varValue: string;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n varValue = (await readFile(options.file, \"utf-8\")) as string;\n } else if (options.stdin) {\n varValue = (await readStdin()).toString(\"utf-8\");\n } else {\n varValue = value!;\n }\n\n const payload = {\n value: varValue,\n createdAt: new Date().toISOString(),\n };\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Setting variable ${name}...`, () => prefixedKv.put(name, payload)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars delete <name>\n vars\n .command(\"delete <name>\")\n .description(\"Delete a variable\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Deleting variable ${name}...`, () => prefixedKv.delete(name)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { DEFAULT_HOST } from \"../config/constants.js\";\nimport { outputJson, shouldOutputJson, formatCheck, formatSection } from \"../output/formatter.js\";\nimport { theme } from \"../output/theme.js\";\nimport { handleError } from \"../output/errors.js\";\n\ninterface DoctorResult {\n checks: Array<{ name: string; ok: boolean; detail?: string }>;\n healthy: boolean;\n}\n\nexport function registerDoctorCommand(program: Command): void {\n program\n .command(\"doctor\")\n .description(\"Run diagnostic checks\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const checks: DoctorResult[\"checks\"] = [];\n\n // 1. Node.js version\n const nodeVersion = process.version;\n const nodeOk = parseInt(nodeVersion.slice(1)) >= 18;\n checks.push({ name: \"Node.js\", ok: nodeOk, detail: nodeVersion });\n\n // 2. Profile configured\n let profileName = globalOpts.profile;\n let profileOk = false;\n let profileDetail = \"\";\n try {\n const config = await ProfileManager.getConfig();\n profileName = profileName || config.defaultProfile;\n const profile = await ProfileManager.getProfile(profileName);\n profileOk = true;\n profileDetail = `\"${profileName}\" at ${profile.host}`;\n } catch {\n profileDetail = profileName ? `\"${profileName}\" not found` : \"no profiles configured\";\n }\n checks.push({ name: \"Profile\", ok: profileOk, detail: profileDetail });\n\n // 3. Key exists\n let keyOk = false;\n let keyDetail = \"\";\n if (profileOk && profileName) {\n try {\n const key = await ProfileManager.getKey(profileName);\n keyOk = key !== null;\n if (keyOk) {\n const profile = await ProfileManager.getProfile(profileName);\n keyDetail = profile.did ? `${profile.did.slice(0, 20)}...` : \"key found\";\n } else {\n keyDetail = \"no key — run tc init\";\n }\n } catch {\n keyDetail = \"error reading key\";\n }\n } else {\n keyDetail = \"skipped (no profile)\";\n }\n checks.push({ name: \"Key\", ok: keyOk, detail: keyDetail });\n\n // 4. Session active\n let sessionOk = false;\n let sessionDetail = \"\";\n if (profileOk && profileName) {\n try {\n const session = await ProfileManager.getSession(profileName);\n sessionOk = session !== null;\n sessionDetail = sessionOk ? \"active\" : \"no session — run tc auth login\";\n } catch {\n sessionDetail = \"error reading session\";\n }\n } else {\n sessionDetail = \"skipped (no profile)\";\n }\n checks.push({ name: \"Session\", ok: sessionOk, detail: sessionDetail });\n\n // 5. Node reachable\n let nodeReachable = false;\n let nodeDetail = \"\";\n try {\n const host = profileOk && profileName\n ? (await ProfileManager.getProfile(profileName)).host\n : globalOpts.host || DEFAULT_HOST;\n const start = Date.now();\n const response = await fetch(`${host}/health`);\n const latency = Date.now() - start;\n nodeReachable = response.ok;\n nodeDetail = nodeReachable\n ? `${host} (${latency}ms)`\n : `${host} returned ${response.status}`;\n } catch (e) {\n nodeDetail = `unreachable — ${e instanceof Error ? e.message : \"connection failed\"}`;\n }\n checks.push({ name: \"Node\", ok: nodeReachable, detail: nodeDetail });\n\n // 6. Space exists (only if session active)\n let spaceOk = false;\n let spaceDetail = \"\";\n if (sessionOk && profileName) {\n try {\n const profile = await ProfileManager.getProfile(profileName);\n spaceOk = Boolean(profile.spaceId);\n spaceDetail = spaceOk\n ? `${profile.spaceId!.slice(0, 16)}...`\n : \"no space — run tc space create\";\n } catch {\n spaceDetail = \"error checking space\";\n }\n } else {\n spaceDetail = \"skipped (no session)\";\n }\n checks.push({ name: \"Space\", ok: spaceOk, detail: spaceDetail });\n\n const result: DoctorResult = {\n checks,\n healthy: checks.every((c) => c.ok),\n };\n\n if (shouldOutputJson()) {\n outputJson(result);\n } else {\n process.stderr.write(formatSection(\"Diagnostics\") + \"\\n\");\n for (const check of checks) {\n process.stdout.write(formatCheck(check.ok, check.name, check.detail) + \"\\n\");\n }\n process.stdout.write(\"\\n\");\n if (result.healthy) {\n process.stdout.write(theme.success(\"All checks passed.\") + \"\\n\");\n } else {\n const failed = checks.filter((c) => !c.ok).length;\n process.stdout.write(theme.warn(`${failed} check${failed > 1 ? \"s\" : \"\"} need attention.`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport type { TinyCloudNode, IDatabaseHandle } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { resolveSpaceUri } from \"../lib/space.js\";\nimport { theme } from \"../output/theme.js\";\n\n/**\n * Pick a database handle for the requested space + db name.\n *\n * `--space` is optional; when omitted, ops route through the node's\n * primary-space SQL service (preserves prior behavior). When present,\n * we use TinyCloudNode.sqlForSpace, which clones the active service\n * context with a session whose spaceId points at the target space.\n */\nasync function dbHandle(\n node: TinyCloudNode,\n dbName: string,\n spaceInput: string | undefined,\n profileName: string,\n): Promise<IDatabaseHandle> {\n const spaceUri = await resolveSpaceUri(spaceInput, profileName);\n const sql = spaceUri ? node.sqlForSpace(spaceUri) : node.sql;\n return sql.db(dbName);\n}\n\nexport function registerSqlCommand(program: Command): void {\n const sql = program\n .command(\"sql\")\n .description(\"SQLite database operations for your TinyCloud space\")\n .addHelpText(\"after\", `\n\nTinyCloud SQL gives each space isolated SQLite databases. Use the default\ndatabase for simple apps, or pass --db to target a named database. Pass\n--space to target a non-primary space (e.g. the manifest \"applications\" space).\n\nCommon workflows:\n $ tc sql execute \"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)\"\n $ tc sql execute \"INSERT INTO notes (body) VALUES (?)\" --params '[\"ship docs\"]'\n $ tc sql query \"SELECT id, body FROM notes ORDER BY id\"\n $ tc sql query \"SELECT * FROM events WHERE type = ?\" --db analytics --params '[\"signup\"]'\n $ tc sql query \"SELECT count(*) FROM conversation\" --space applications --db xyz.tinycloud.listen/conversations\n $ tc sql export --db analytics --output analytics.db\n\nCommands:\n query Read rows with SELECT statements\n execute Run writes and schema changes such as INSERT, UPDATE, DELETE, CREATE, DROP\n export Download the raw SQLite database file\n copy Copy rows between databases (optionally across spaces)\n\nTips:\n - SQL strings should usually be quoted so your shell passes them as one argument.\n - --params accepts a JSON array and binds values to ? placeholders.\n - --space accepts a short name (\"applications\") or full URI (\"tinycloud:pkh:eip155:1:0x...:applications\").\n - Add --json for scripting-friendly output.\n`);\n\n // tc sql query <sql>\n sql\n .command(\"query <sql>\")\n .description(\"Run a read-only SELECT query\")\n .option(\"--db <name>\", \"SQLite database name within the current space\", \"default\")\n .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\n .option(\"--params <json>\", \"Bind parameters as a JSON array for ? placeholders\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql query \"SELECT * FROM notes ORDER BY id\"\n $ tc sql query \"SELECT * FROM notes WHERE id = ?\" --params '[42]'\n $ tc sql query \"SELECT count(*) AS total FROM events\" --db analytics --json\n $ tc sql query \"SELECT count(*) FROM conversation\" --space applications --db xyz.tinycloud.listen/conversations\n\nOutput:\n Human output is formatted as a table. Piped output or --json returns\n { \"columns\": string[], \"rows\": unknown[][], \"rowCount\": number }.\n`)\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Running query...\", () =>\n handle.query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\n }\n\n const { columns, rows, rowCount } = result.data;\n\n if (shouldOutputJson()) {\n outputJson({ columns, rows, rowCount });\n } else {\n if (rows.length === 0) {\n process.stdout.write(theme.muted(\"No rows returned.\") + \"\\n\");\n } else {\n const stringRows = rows.map((row: unknown[]) =>\n row.map((v: unknown) => v === null ? \"NULL\" : String(v))\n );\n process.stdout.write(formatTable(columns, stringRows) + \"\\n\");\n process.stdout.write(theme.muted(`\\n${rowCount} row${rowCount === 1 ? \"\" : \"s\"} returned`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql execute <sql>\n sql\n .command(\"execute <sql>\")\n .description(\"Run a write or schema statement\")\n .option(\"--db <name>\", \"SQLite database name within the current space\", \"default\")\n .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\n .option(\"--params <json>\", \"Bind parameters as a JSON array for ? placeholders\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql execute \"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)\"\n $ tc sql execute \"INSERT INTO notes (body) VALUES (?)\" --params '[\"first note\"]'\n $ tc sql execute \"UPDATE notes SET body = ? WHERE id = ?\" --params '[\"edited\", 1]'\n $ tc sql execute \"DROP TABLE old_notes\" --db archive\n $ tc sql execute \"DELETE FROM conversation WHERE id = ?\" --space applications --db xyz.tinycloud.listen/conversations --params '[\"abc\"]'\n\nOutput:\n Returns JSON with the changed row count and last inserted row id when available.\n`)\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Executing statement...\", () =>\n handle.execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\n }\n\n outputJson({\n changes: result.data.changes,\n lastInsertRowId: result.data.lastInsertRowId,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql export\n sql\n .command(\"export\")\n .description(\"Export a SQLite database as a binary .db file\")\n .option(\"--db <name>\", \"SQLite database name within the current space\", \"default\")\n .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\n .option(\"-o, --output <file>\", \"Output file path\", \"export.db\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql export\n $ tc sql export --db analytics --output analytics.db\n $ tc sql export --space applications --db xyz.tinycloud.listen/conversations --output listen.db\n\nOutput:\n Writes the database file locally and returns JSON with the path and size.\n`)\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n handle.export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\n }\n\n const blob: Blob = result.data;\n const buffer = Buffer.from(await blob.arrayBuffer());\n const outputPath = resolve(options.output);\n await writeFile(outputPath, buffer);\n\n outputJson({\n file: outputPath,\n size: blob.size,\n sizeHuman: formatBytes(blob.size),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql copy\n sql\n .command(\"copy\")\n .description(\"Copy rows between SQL databases (optionally across spaces)\")\n .requiredOption(\"--from-db <name>\", \"Source database name\")\n .requiredOption(\"--to-db <name>\", \"Destination database name\")\n .option(\"--from-space <name|uri>\", \"Source space (defaults to primary)\")\n .option(\"--to-space <name|uri>\", \"Destination space (defaults to primary)\")\n .option(\"--table <name...>\", \"Restrict copy to specific tables (repeat or comma-separated)\")\n .option(\"--dry-run\", \"Print the plan without writing\", false)\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql copy --from-db com.tinycloud.conversation-sync/conversations \\\\\n --to-db xyz.tinycloud.listen/conversations \\\\\n --space applications --dry-run\n $ tc sql copy --from-space applications --from-db com.foo/data \\\\\n --to-space applications --to-db com.bar/data \\\\\n --table conversation --table participant\n\nNotes:\n - Refuses to run when (resolved space, db) is identical for source and destination.\n - Does NOT create destination tables. Run the target app once (or use \\`tc sql execute\\`)\n to materialize the schema before copying.\n - One row at a time; suitable for small/medium datasets. Large copies should\n use \\`tc sql export\\` + bulk import.\n - Authorization: the active session/delegation must cover sql/read on source\n AND sql/write on destination. Otherwise the relevant operation will fail.\n`)\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n // commander's `--space` shorthand supports both --from-space and a default.\n const fromSpaceInput: string | undefined = options.fromSpace ?? options.space;\n const toSpaceInput: string | undefined = options.toSpace ?? options.space;\n\n const fromSpaceUri = (await resolveSpaceUri(fromSpaceInput, ctx.profile)) ?? \"<primary>\";\n const toSpaceUri = (await resolveSpaceUri(toSpaceInput, ctx.profile)) ?? \"<primary>\";\n\n if (fromSpaceUri === toSpaceUri && options.fromDb === options.toDb) {\n throw new CLIError(\n \"SELF_COPY\",\n `Refusing to copy: source and destination resolve to the same (space, db) — ${fromSpaceUri} / ${options.fromDb}.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const fromHandle = await dbHandle(node, options.fromDb, fromSpaceInput, ctx.profile);\n const toHandle = await dbHandle(node, options.toDb, toSpaceInput, ctx.profile);\n\n // Resolve target tables: explicit list, or all user tables in source.\n let tables: string[];\n if (options.table && options.table.length > 0) {\n tables = options.table.flatMap((t: string) => t.split(\",\").map((s) => s.trim()).filter(Boolean));\n } else {\n const listing = await fromHandle.query(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n ) as any;\n if (!listing.ok) {\n throw new CLIError(listing.error.code, `Cannot list source tables: ${listing.error.message}`, ExitCode.ERROR, listing.error.meta);\n }\n tables = (listing.data.rows as unknown[][]).map((r) => String(r[0]));\n }\n\n if (tables.length === 0) {\n throw new CLIError(\n \"EMPTY_PLAN\",\n `No tables to copy. Use --table to specify tables, or check that the source database has user tables.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const plan: Array<{ table: string; rows: number; copied: number; skipped: number }> = [];\n\n for (const table of tables) {\n const safe = quoteIdent(table);\n const countResult = await fromHandle.query(`SELECT count(*) AS n FROM ${safe}`) as any;\n if (!countResult.ok) {\n throw new CLIError(\n countResult.error.code,\n `Cannot count rows in source table \"${table}\": ${countResult.error.message}`,\n ExitCode.ERROR,\n countResult.error.meta,\n );\n }\n const rows = Number(countResult.data.rows[0]?.[0] ?? 0);\n plan.push({ table, rows, copied: 0, skipped: 0 });\n }\n\n if (options.dryRun) {\n outputJson({\n dryRun: true,\n from: { space: fromSpaceUri, db: options.fromDb },\n to: { space: toSpaceUri, db: options.toDb },\n tables: plan.map((p) => ({ table: p.table, rows: p.rows })),\n });\n return;\n }\n\n for (const entry of plan) {\n const safe = quoteIdent(entry.table);\n const fetched = await fromHandle.query(`SELECT * FROM ${safe}`) as any;\n if (!fetched.ok) {\n throw new CLIError(fetched.error.code, `Failed to read \"${entry.table}\": ${fetched.error.message}`, ExitCode.ERROR, fetched.error.meta);\n }\n const columns: string[] = fetched.data.columns;\n const rows: unknown[][] = fetched.data.rows;\n\n if (rows.length === 0) continue;\n\n const colList = columns.map(quoteIdent).join(\", \");\n const placeholders = columns.map(() => \"?\").join(\", \");\n const insertSql = `INSERT INTO ${safe} (${colList}) VALUES (${placeholders})`;\n\n for (const row of rows) {\n const writeResult = await toHandle.execute(insertSql, row as any) as any;\n if (!writeResult.ok) {\n throw new CLIError(\n writeResult.error.code,\n `Insert into \"${entry.table}\" failed after ${entry.copied} row(s): ${writeResult.error.message}`,\n ExitCode.ERROR,\n writeResult.error.meta,\n );\n }\n entry.copied += writeResult.data.changes ?? 1;\n }\n }\n\n outputJson({\n from: { space: fromSpaceUri, db: options.fromDb },\n to: { space: toSpaceUri, db: options.toDb },\n tables: plan.map((p) => ({ table: p.table, rowsRead: p.rows, rowsWritten: p.copied })),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\n/** Quote a SQLite identifier defensively (table/column names). */\nfunction quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n","import { Command } from \"commander\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerDuckdbCommand(program: Command): void {\n const duckdb = program.command(\"duckdb\").description(\"DuckDB database operations\");\n\n // tc duckdb query <sql>\n duckdb\n .command(\"query <sql>\")\n .description(\"Run a SELECT query\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Running query...\", () =>\n node.duckdb.db(options.db).query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const { columns, rows, rowCount } = result.data;\n\n if (shouldOutputJson()) {\n outputJson({ columns, rows, rowCount });\n } else {\n if (rows.length === 0) {\n process.stdout.write(theme.muted(\"No rows returned.\") + \"\\n\");\n } else {\n const stringRows = rows.map((row: unknown[]) =>\n row.map((v: unknown) => v === null ? \"NULL\" : String(v))\n );\n process.stdout.write(formatTable(columns, stringRows) + \"\\n\");\n process.stdout.write(theme.muted(`\\n${rowCount} row${rowCount === 1 ? \"\" : \"s\"} returned`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb execute <sql>\n duckdb\n .command(\"execute <sql>\")\n .description(\"Run INSERT/UPDATE/DELETE/DDL statement\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Executing statement...\", () =>\n node.duckdb.db(options.db).execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ changes: result.data.changes });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb describe\n duckdb\n .command(\"describe\")\n .description(\"Show database schema (tables, columns, views)\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Describing schema...\", () =>\n node.duckdb.db(options.db).describe()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const schema = result.data;\n\n if (shouldOutputJson()) {\n outputJson(schema);\n } else {\n const { tables, views } = schema;\n\n if (tables.length === 0 && views.length === 0) {\n process.stdout.write(theme.muted(\"No tables or views found.\") + \"\\n\");\n return;\n }\n\n if (tables.length > 0) {\n process.stdout.write(theme.label(\"Tables:\") + \"\\n\\n\");\n for (const table of tables) {\n process.stdout.write(` ${theme.value(table.name)}\\n`);\n const colRows = table.columns.map((col: any) => [\n col.name,\n col.type,\n col.nullable ? \"YES\" : \"NO\",\n ]);\n const colTable = formatTable([\"Column\", \"Type\", \"Nullable\"], colRows);\n process.stdout.write(colTable.split(\"\\n\").map((l: string) => \" \" + l).join(\"\\n\") + \"\\n\\n\");\n }\n }\n\n if (views.length > 0) {\n process.stdout.write(theme.label(\"Views:\") + \"\\n\\n\");\n const viewRows = views.map((v: any) => [v.name, v.sql]);\n process.stdout.write(formatTable([\"View\", \"SQL\"], viewRows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb export\n duckdb\n .command(\"export\")\n .description(\"Export database as binary file\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"-o, --output <file>\", \"Output file path\", \"export.duckdb\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n node.duckdb.db(options.db).export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const blob: Blob = result.data;\n const buffer = Buffer.from(await blob.arrayBuffer());\n const outputPath = resolve(options.output);\n await writeFile(outputPath, buffer);\n\n outputJson({\n file: outputPath,\n size: blob.size,\n sizeHuman: formatBytes(blob.size),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb import <file>\n duckdb\n .command(\"import <file>\")\n .description(\"Import a DuckDB database file\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .action(async (file: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const filePath = resolve(file);\n const bytes = new Uint8Array(await readFile(filePath));\n\n const result = await withSpinner(\"Importing database...\", () =>\n node.duckdb.db(options.db).import(bytes)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n file: filePath,\n size: bytes.byteLength,\n sizeHuman: formatBytes(bytes.byteLength),\n imported: true,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { resolveSpaceUri } from \"../lib/space.js\";\nimport { outputJson, shouldOutputJson, formatTable } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { theme } from \"../output/theme.js\";\n\ninterface ManifestPermission {\n service: string;\n path: string;\n actions: string[];\n skipPrefix?: boolean;\n description?: string;\n}\n\ninterface Manifest {\n manifest_version?: number;\n app_id?: string;\n name?: string;\n description?: string;\n space?: string;\n defaults?: boolean;\n permissions?: ManifestPermission[];\n}\n\n/**\n * Default space for app data when the manifest omits `space`.\n * Mirrors the manifest spec at repositories/listen/SPEC-manifest-and-capability-chain.md.\n */\nconst DEFAULT_APP_SPACE = \"applications\";\n\nexport function registerManifestCommand(program: Command): void {\n const manifest = program\n .command(\"manifest\")\n .description(\"Inspect TinyCloud app manifests\");\n\n manifest\n .command(\"resolve <source>\")\n .description(\"Resolve a manifest file or URL to its effective space, paths, and DB basenames\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc manifest resolve ./manifest.json\n $ tc manifest resolve https://app.example.com/manifest.json --json\n\nWhat it shows:\n - app_id, name, manifest_version\n - effective space name (default: \"applications\") and full space URI for the active profile\n - per-permission: service, fully-qualified path, actions\n - inferred SQL database basenames for sql/<db>/... paths\n\nThis command is read-only and does NOT contact the node — it just resolves\nthe manifest against the active profile's address/chain so you know which\n\\`--space\\` and \\`--db\\` values to pass to other tc commands.\n`)\n .action(async (source: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const raw = await loadManifestSource(source);\n const parsed: Manifest = JSON.parse(raw);\n\n if (!parsed.app_id) {\n throw new CLIError(\n \"INVALID_MANIFEST\",\n `Manifest is missing required field \"app_id\".`,\n ExitCode.ERROR,\n );\n }\n\n // Make sure we have an authenticated profile so we can resolve\n // the user's space URI. We don't use the node — just the profile.\n await ensureAuthenticated(ctx);\n\n const spaceName = parsed.space ?? DEFAULT_APP_SPACE;\n const spaceUri = await resolveSpaceUri(spaceName, ctx.profile);\n\n const permissions = (parsed.permissions ?? []).map((p) => {\n const resolvedPath = p.skipPrefix ? p.path : prefixWithAppId(p.path, parsed.app_id!);\n return {\n service: p.service,\n path: resolvedPath,\n actions: p.actions,\n sqlDb: extractSqlDbName(resolvedPath),\n };\n });\n\n const sqlDbs = unique(\n permissions\n .map((p) => p.sqlDb)\n .filter((db): db is string => Boolean(db)),\n );\n\n const summary = {\n source,\n app_id: parsed.app_id,\n name: parsed.name,\n manifest_version: parsed.manifest_version,\n space: {\n name: spaceName,\n uri: spaceUri,\n },\n permissions,\n sqlDatabases: sqlDbs,\n };\n\n if (shouldOutputJson()) {\n outputJson(summary);\n return;\n }\n\n process.stdout.write(`${theme.heading(\"Manifest\")}: ${theme.value(parsed.app_id)}`);\n if (parsed.name) process.stdout.write(theme.muted(` (${parsed.name})`));\n process.stdout.write(\"\\n\");\n\n process.stdout.write(`${theme.label(\"Space\")}: ${theme.value(spaceName)}\\n`);\n if (spaceUri) {\n process.stdout.write(`${theme.label(\"Space URI\")}: ${theme.value(spaceUri)}\\n`);\n }\n\n if (sqlDbs.length > 0) {\n process.stdout.write(`\\n${theme.heading(\"SQL databases\")}\\n`);\n for (const db of sqlDbs) {\n process.stdout.write(` ${theme.value(db)}\\n`);\n }\n process.stdout.write(theme.muted(`\\nUse with: tc sql query --space ${spaceName} --db <db> \"...\"\\n`));\n }\n\n if (permissions.length > 0) {\n process.stdout.write(`\\n${theme.heading(\"Permissions\")}\\n`);\n const rows = permissions.map((p) => [p.service, p.path, p.actions.join(\", \")]);\n process.stdout.write(formatTable([\"service\", \"path\", \"actions\"], rows) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nasync function loadManifestSource(source: string): Promise<string> {\n if (/^https?:\\/\\//i.test(source)) {\n const response = await fetch(source);\n if (!response.ok) {\n throw new CLIError(\n \"MANIFEST_FETCH_FAILED\",\n `Failed to fetch manifest from ${source}: ${response.status} ${response.statusText}`,\n ExitCode.NETWORK_ERROR,\n );\n }\n return response.text();\n }\n return readFile(source, \"utf8\");\n}\n\nfunction prefixWithAppId(path: string, appId: string): string {\n // Manifest paths are usually `<service-prefix>/<resource>`, e.g. `sql/foo/bar`.\n // When skipPrefix is false the app_id is inserted between the service prefix\n // and the resource, matching how resolveAppPath() lays out keys at runtime.\n const slash = path.indexOf(\"/\");\n if (slash === -1) return `${appId}/${path}`;\n const head = path.slice(0, slash);\n const tail = path.slice(slash + 1);\n return `${head}/${appId}/${tail}`;\n}\n\n/**\n * For a path like `sql/<db-name>/<table>/...`, return `<db-name>`.\n * `<db-name>` itself may contain slashes when the app namespaces it\n * (e.g. `sql/xyz.tinycloud.listen/conversations/conversation`), so we drop\n * the trailing table segment(s) and reassemble.\n */\nfunction extractSqlDbName(path: string): string | undefined {\n if (!path.startsWith(\"sql/\")) return undefined;\n const rest = path.slice(4);\n const segments = rest.split(\"/\");\n if (segments.length < 2) return rest;\n // Drop the last segment (table name); the rest is the db name.\n return segments.slice(0, -1).join(\"/\");\n}\n\nfunction unique<T>(arr: T[]): T[] {\n return Array.from(new Set(arr));\n}\n","import { Command } from \"commander\";\nimport { execSync } from \"child_process\";\nimport { readFileSync } from \"fs\";\nimport { theme } from \"../output/theme.js\";\nimport { handleError } from \"../output/errors.js\";\n\nconst PACKAGE_NAME = \"@tinycloud/cli\";\n\nfunction getCurrentVersion(): string {\n const pkg = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\")\n );\n return pkg.version;\n}\n\nasync function getLatestVersion(): Promise<string> {\n const res = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`);\n if (!res.ok) {\n throw new Error(`Failed to fetch latest version: ${res.status} ${res.statusText}`);\n }\n const data = (await res.json()) as { version: string };\n return data.version;\n}\n\nfunction detectPackageManager(): \"bun\" | \"npm\" {\n // Check if bun installed the package globally\n try {\n const bunGlobals = execSync(\"bun pm ls -g\", { encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n if (bunGlobals.includes(PACKAGE_NAME)) {\n return \"bun\";\n }\n } catch {\n // bun not available or failed\n }\n\n // Check if npm installed the package globally\n try {\n const npmGlobals = execSync(\"npm ls -g --depth=0\", { encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n if (npmGlobals.includes(PACKAGE_NAME)) {\n return \"npm\";\n }\n } catch {\n // npm not available or failed\n }\n\n // Fallback to bun since the CLI shebang uses it\n return \"bun\";\n}\n\nexport function registerUpgradeCommand(program: Command): void {\n program\n .command(\"upgrade\")\n .description(\"Upgrade the TinyCloud CLI to the latest version\")\n .action(async () => {\n try {\n const current = getCurrentVersion();\n\n process.stderr.write(theme.muted(\"Checking for updates...\") + \"\\n\");\n const latest = await getLatestVersion();\n\n if (current === latest) {\n process.stdout.write(theme.success(`Already on latest version (${current})`) + \"\\n\");\n return;\n }\n\n process.stdout.write(`Current: ${theme.warn(current)} → Latest: ${theme.success(latest)}\\n`);\n\n const pm = detectPackageManager();\n const cmd = pm === \"bun\"\n ? `bun install -g ${PACKAGE_NAME}@latest`\n : `npm install -g ${PACKAGE_NAME}@latest`;\n\n process.stderr.write(theme.muted(`Upgrading via ${pm}...`) + \"\\n\\n\");\n\n try {\n execSync(cmd, { stdio: \"inherit\" });\n process.stdout.write(\"\\n\" + theme.success(`Upgraded to ${latest}`) + \"\\n\");\n } catch {\n process.stderr.write(\"\\n\" + theme.warn(\"Automatic upgrade failed.\") + \"\\n\");\n process.stderr.write(theme.muted(\"Try running manually:\") + \"\\n\");\n process.stderr.write(` ${theme.command(`bun install -g ${PACKAGE_NAME}@latest`)}\\n`);\n process.stderr.write(theme.muted(\" or\") + \"\\n\");\n process.stderr.write(` ${theme.command(`npm install -g ${PACKAGE_NAME}@latest`)}\\n`);\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,qBAAoB;AAC7B,SAAS,eAAe;;;ACDxB,SAAS,cAAc,mBAAmB;AAC1C,SAAS,QAAAC,aAAY;;;ACDrB,SAAS,eAAe;AACxB,SAAS,YAAY;AAEd,IAAM,aAAa,KAAK,QAAQ,GAAG,YAAY;AAC/C,IAAM,eAAe,KAAK,YAAY,UAAU;AAChD,IAAM,cAAc,KAAK,YAAY,aAAa;AAElD,IAAM,eAAe;AACrB,IAAM,uBAAuB;AAC7B,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAEzB,IAAM,WAAW;AAAA,EACtB,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,eAAe;AAAA,EACf,WAAW;AAAA,EACX,mBAAmB;AAAA,EACnB,eAAe;AAAA,EACf,YAAY;AACd;;;ACrBA,OAAO,SAAS;;;ACAhB,OAAO,WAAW;AAEX,IAAM,aAAa;AAAA,EACxB,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,KAAK;AACP;AAEO,IAAM,QAAQ;AAAA,EACnB,SAAS,MAAM,IAAI,WAAW,OAAO;AAAA,EACrC,QAAQ,MAAM,IAAI,WAAW,MAAM;AAAA,EACnC,SAAS,MAAM,IAAI,WAA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CAAC;AAAA;AAAA,EAE1F,MAAM,MAAM,OAAO,CAAC,IAAI,MAAM,OAAO,gCAAgC,CAAC;AAAA,EACtE,MAAM,MAAM,OAAO,CAAC,IAAI,MAAM,OAAO,0CAA0C,CAAC;AAAA;AAElF,CAAC;AAED,IAAI;AACF,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC,SAAS,OAAO;AACd,cAAY,KAAK;AACnB;","names":["readFileSync","join","join","version","join","rm","join","rm","TinyCloudNode","resolve","program","mkdir","readFile","writeFile","dirname","createInterface","randomBytes","readFile","join","join","randomBytes","readFile","readFile","node","createInterface","resolve","program","delegationCids","expiry","mkdir","dirname","writeFile","readFile","readFile","writeFile","readStdin","program","writeFile","readFile","program","program","program","program","createInterface","program","createInterface","resolve","program","readFile","writeFile","PrivateKeySigner","readStdin","program","readFile","writeFile","readFile","writeFile","readStdin","program","writeFile","readFile","readFile","writeFile","readStdin","resolvePrivateKey","program","writeFile","readFile","program","writeFile","program","writeFile","readFile","writeFile","resolve","program","resolve","writeFile","readFile","readFile","program","readFile","execSync","readFileSync","readFileSync","execSync","program","readFileSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/output/errors.ts","../src/config/constants.ts","../src/output/formatter.ts","../src/output/theme.ts","../src/output/taglines.ts","../src/output/banner.ts","../src/config/profiles.ts","../src/config/storage.ts","../src/auth/local-key.ts","../src/auth/browser-auth.ts","../src/commands/init.ts","../src/commands/auth.ts","../src/config/types.ts","../src/lib/sdk.ts","../src/lib/permissions.ts","../src/lib/space.ts","../src/commands/kv.ts","../src/commands/space.ts","../src/lib/duration.ts","../src/commands/delegation.ts","../src/commands/share.ts","../src/commands/node.ts","../src/commands/profile.ts","../src/commands/completion.ts","../src/commands/vault.ts","../src/commands/secrets.ts","../src/commands/vars.ts","../src/commands/doctor.ts","../src/commands/sql.ts","../src/commands/duckdb.ts","../src/commands/manifest.ts","../src/commands/upgrade.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport { handleError } from \"./output/errors.js\";\nimport { emitBanner } from \"./output/banner.js\";\n\nconst { version } = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\")\n);\nimport { theme } from \"./output/theme.js\";\nimport { isInteractive } from \"./output/formatter.js\";\nimport { ProfileManager } from \"./config/profiles.js\";\nimport { registerInitCommand } from \"./commands/init.js\";\nimport { registerAuthCommand } from \"./commands/auth.js\";\nimport { registerKvCommand } from \"./commands/kv.js\";\nimport { registerSpaceCommand } from \"./commands/space.js\";\nimport { registerDelegationCommand } from \"./commands/delegation.js\";\nimport { registerShareCommand } from \"./commands/share.js\";\nimport { registerNodeCommand } from \"./commands/node.js\";\nimport { registerProfileCommand } from \"./commands/profile.js\";\nimport { registerCompletionCommand } from \"./commands/completion.js\";\nimport { registerVaultCommand } from \"./commands/vault.js\";\nimport { registerSecretsCommand } from \"./commands/secrets.js\";\nimport { registerVarsCommand } from \"./commands/vars.js\";\nimport { registerDoctorCommand } from \"./commands/doctor.js\";\nimport { registerSqlCommand } from \"./commands/sql.js\";\nimport { registerDuckdbCommand } from \"./commands/duckdb.js\";\nimport { registerManifestCommand } from \"./commands/manifest.js\";\nimport { registerUpgradeCommand } from \"./commands/upgrade.js\";\n\nconst program = new Command();\n\nprogram\n .name(\"tc\")\n .description(\"TinyCloud CLI — self-sovereign storage from the terminal\")\n .version(version)\n .option(\"-p, --profile <name>\", \"Profile to use\")\n .option(\"-H, --host <url>\", \"TinyCloud node URL\")\n .option(\"-v, --verbose\", \"Enable verbose output\")\n .option(\"--no-cache\", \"Disable caching\")\n .option(\"-q, --quiet\", \"Suppress non-essential output\")\n .option(\"--json\", \"Force JSON output\");\n\nprogram.hook(\"preAction\", async (thisCommand) => {\n const opts = thisCommand.optsWithGlobals();\n if (!opts.quiet) {\n emitBanner(version);\n }\n\n // Config guard — warn if not configured for auth-required commands\n const commandName = thisCommand.name();\n const parentName = thisCommand.parent?.name();\n const fullCommand = parentName && parentName !== \"tc\" ? `${parentName} ${commandName}` : commandName;\n const skipGuard = [\"tc\", \"init\", \"doctor\", \"completion\", \"help\", \"upgrade\"].includes(commandName) ||\n fullCommand === \"profile create\";\n if (!skipGuard && !opts.quiet && isInteractive()) {\n try {\n const config = await ProfileManager.getConfig();\n const profileName = opts.profile || config.defaultProfile;\n const hasProfile = await ProfileManager.profileExists(profileName);\n if (!hasProfile) {\n process.stderr.write(theme.warn(\"⚠ No profile configured.\") + \" \" + theme.muted(\"Run: tc init\") + \"\\n\\n\");\n } else {\n const key = await ProfileManager.getKey(profileName);\n if (!key) {\n process.stderr.write(theme.warn(\"⚠ No key found.\") + \" \" + theme.muted(\"Run: tc init\") + \"\\n\\n\");\n }\n }\n } catch {\n // Config dir doesn't exist yet — that's fine, commands will handle it\n }\n }\n});\n\nregisterInitCommand(program);\nregisterAuthCommand(program);\nregisterKvCommand(program);\nregisterSpaceCommand(program);\nregisterDelegationCommand(program);\nregisterShareCommand(program);\nregisterNodeCommand(program);\nregisterProfileCommand(program);\nregisterCompletionCommand(program);\nregisterVaultCommand(program);\nregisterSecretsCommand(program);\nregisterVarsCommand(program);\nregisterDoctorCommand(program);\nregisterSqlCommand(program);\nregisterDuckdbCommand(program);\nregisterManifestCommand(program);\nregisterUpgradeCommand(program);\n\nprogram.addHelpText(\"afterAll\", () => {\n if (!process.stdout.isTTY) return \"\";\n return `\n${theme.heading(\"Examples:\")}\n ${theme.command(\"tc init\")} ${theme.muted(\"Set up a profile and generate keys\")}\n ${theme.command(\"tc auth login\")} ${theme.muted(\"Authenticate via browser\")}\n ${theme.command('tc kv put greeting \"Hello\"')} ${theme.muted(\"Store a value\")}\n ${theme.command(\"tc kv list\")} ${theme.muted(\"List all keys\")}\n ${theme.command(\"tc secrets network init\")} ${theme.muted(\"Create the default secrets network\")}\n ${theme.command(\"tc delegation create --to did:pkh:...\")} ${theme.muted(\"Grant access to another user\")}\n ${theme.command(\"tc space list\")} ${theme.muted(\"Show your spaces\")}\n\n${theme.muted(\"Docs:\")} ${theme.accent(\"https://docs.tinycloud.xyz/cli\")}\n${theme.muted(\"Repo:\")} ${theme.accent(\"https://github.com/tinycloudlabs/web-sdk\")}\n`;\n});\n\ntry {\n await program.parseAsync(process.argv);\n} catch (error) {\n handleError(error);\n}\n","import { readFileSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { ExitCode, CONFIG_FILE, PROFILES_DIR, DEFAULT_PROFILE } from \"../config/constants.js\";\nimport { outputError } from \"./formatter.js\";\n\nlet activeProfileName: string | undefined;\n\n/** Recorded by ProfileManager.resolveContext so hints can name the right profile. */\nexport function setActiveProfileName(name: string): void {\n activeProfileName = name;\n}\n\nexport class CLIError extends Error {\n constructor(\n public code: string,\n message: string,\n public exitCode: number = ExitCode.ERROR,\n public metadata?: Record<string, unknown>,\n ) {\n super(message);\n this.name = \"CLIError\";\n }\n}\n\nexport function wrapError(error: unknown): CLIError {\n if (error instanceof CLIError) return error;\n\n const message = error instanceof Error ? error.message : String(error);\n\n // Map known error patterns to exit codes\n if (message.includes(\"Not signed in\") || message.includes(\"AUTH_EXPIRED\") || message.includes(\"Session expired\")) {\n return new CLIError(\"AUTH_REQUIRED\", message, ExitCode.AUTH_REQUIRED);\n }\n if (message.includes(\"NOT_FOUND\") || message.includes(\"KV_NOT_FOUND\")) {\n return new CLIError(\"NOT_FOUND\", message, ExitCode.NOT_FOUND);\n }\n if (message.includes(\"PERMISSION_DENIED\")) {\n return new CLIError(\"PERMISSION_DENIED\", message, ExitCode.PERMISSION_DENIED);\n }\n if (message.includes(\"ECONNREFUSED\") || message.includes(\"ETIMEDOUT\") || message.includes(\"fetch failed\")) {\n return new CLIError(\"NETWORK_ERROR\", message, ExitCode.NETWORK_ERROR);\n }\n\n return new CLIError(\"ERROR\", message, ExitCode.ERROR);\n}\n\nexport function handleError(error: unknown): never {\n const cliError = wrapError(error);\n const hint = buildAuthHint(cliError) ??\n (cliError.code === \"NETWORK_ERROR\" ? buildNetworkHint() : undefined);\n outputError(cliError.code, cliError.message, hint);\n process.exit(cliError.exitCode);\n}\n\nfunction buildAuthHint(error: CLIError): string | undefined {\n const resource = error.metadata?.resource;\n const requiredAction = error.metadata?.requiredAction;\n if (typeof resource !== \"string\" || typeof requiredAction !== \"string\") {\n return undefined;\n }\n\n const spec = capSpecFromAuthMeta(resource, requiredAction);\n if (!spec) return undefined;\n return [\n \"The active session is missing a TinyCloud capability.\",\n `Request it with: tc auth request --cap \"${spec}\"`,\n \"Then retry the original command.\",\n ].join(\"\\n\");\n}\n\nfunction capSpecFromAuthMeta(resource: string, action: string): string | undefined {\n const slash = resource.indexOf(\"/\");\n if (slash <= 0 || slash === resource.length - 1) return undefined;\n const spaceUri = resource.slice(0, slash);\n const rest = resource.slice(slash + 1);\n const nextSlash = rest.indexOf(\"/\");\n if (nextSlash <= 0) return undefined;\n\n const serviceShort = rest.slice(0, nextSlash);\n const path = rest.slice(nextSlash + 1);\n const actionName = action.includes(\"/\") ? action.slice(action.indexOf(\"/\") + 1) : action;\n const spaceName = spaceUri.startsWith(\"tinycloud:\")\n ? spaceUri.slice(spaceUri.lastIndexOf(\":\") + 1)\n : spaceUri;\n return `tinycloud.${serviceShort}:${spaceName}:${path}:${actionName}`;\n}\n\n/**\n * Suggests alternate profiles when the active profile's host is unreachable.\n * Sync fs reads keep handleError synchronous so call sites don't need to await.\n *\n * Silent fallback to a default host is intentionally NOT done: different hosts\n * back different data stores, so an automatic switch could split or clobber\n * user data without their knowledge.\n */\nfunction buildNetworkHint(): string | undefined {\n const readHost = (name: string): string | undefined => {\n try {\n const raw = readFileSync(join(PROFILES_DIR, name, \"profile.json\"), \"utf8\");\n return (JSON.parse(raw) as { host?: string }).host;\n } catch {\n return undefined;\n }\n };\n\n let activeName = activeProfileName ?? process.env.TC_PROFILE ?? DEFAULT_PROFILE;\n if (!activeProfileName) {\n try {\n const cfg = JSON.parse(readFileSync(CONFIG_FILE, \"utf8\")) as { defaultProfile?: string };\n activeName = process.env.TC_PROFILE ?? cfg.defaultProfile ?? DEFAULT_PROFILE;\n } catch {\n // Config file not present yet — fall through with env/default.\n }\n }\n\n let names: string[];\n try {\n names = readdirSync(PROFILES_DIR);\n } catch {\n return undefined;\n }\n\n const activeHost = readHost(activeName);\n const others = names\n .filter((n) => n !== activeName)\n .map((n) => ({ name: n, host: readHost(n) }))\n .filter((p): p is { name: string; host: string } => Boolean(p.host));\n\n const lines: string[] = [];\n lines.push(activeHost ? `Active profile \"${activeName}\" → ${activeHost}` : `Active profile \"${activeName}\"`);\n\n if (others.length === 0) {\n lines.push(`No other profiles configured. Run \\`tc profile create <name>\\` or \\`tc init\\`.`);\n } else {\n lines.push(`Switch to a reachable profile:`);\n const longest = Math.max(...others.map((p) => p.name.length));\n for (const { name, host } of others) {\n lines.push(` tc profile switch ${name.padEnd(longest)} # ${host}`);\n }\n }\n lines.push(`Or override per-command with --host or TC_HOST.`);\n return lines.join(\"\\n\");\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const CONFIG_DIR = join(homedir(), \".tinycloud\");\nexport const PROFILES_DIR = join(CONFIG_DIR, \"profiles\");\nexport const CONFIG_FILE = join(CONFIG_DIR, \"config.json\");\n\nexport const DEFAULT_HOST = \"https://node.tinycloud.xyz\";\nexport const DEFAULT_OPENKEY_HOST = \"https://openkey.so\";\nexport const DEFAULT_PROFILE = \"default\";\nexport const DEFAULT_CHAIN_ID = 1;\n\nexport const ExitCode = {\n SUCCESS: 0,\n ERROR: 1,\n USAGE_ERROR: 2,\n AUTH_REQUIRED: 3,\n NOT_FOUND: 4,\n PERMISSION_DENIED: 5,\n NETWORK_ERROR: 6,\n NODE_ERROR: 7,\n} as const;\n","import ora from \"ora\";\nimport { theme } from \"./theme.js\";\n\nexport function outputJson(data: unknown): void {\n process.stdout.write(JSON.stringify(data, null, 2) + \"\\n\");\n}\n\nexport function outputError(code: string, message: string, hint?: string): void {\n if (isInteractive()) {\n process.stderr.write(\n `${theme.error(\"✗\")} ${theme.label(code)}: ${message}\\n`\n );\n if (hint) {\n for (const line of hint.split(\"\\n\")) {\n process.stderr.write(` ${theme.hint(line)}\\n`);\n }\n }\n } else {\n const payload: { error: { code: string; message: string; hint?: string } } = {\n error: { code, message },\n };\n if (hint) payload.error.hint = hint;\n process.stderr.write(JSON.stringify(payload, null, 2) + \"\\n\");\n }\n}\n\nexport function isInteractive(): boolean {\n return Boolean(process.stdout.isTTY);\n}\n\nexport async function withSpinner<T>(label: string, fn: () => Promise<T>): Promise<T> {\n if (!isInteractive()) {\n return fn();\n }\n const spinner = ora(label).start();\n try {\n const result = await fn();\n spinner.succeed(label);\n return result;\n } catch (error) {\n spinner.fail(label);\n throw error;\n }\n}\n\n/** Check if output should be JSON (non-TTY or --json flag) */\nexport function shouldOutputJson(): boolean {\n return !isInteractive() || process.argv.includes(\"--json\");\n}\n\n/** Format a key-value pair for human display */\nexport function formatField(label: string, value: string | number | boolean | null | undefined): string {\n if (value === null || value === undefined) return ` ${theme.label(label + \":\")} ${theme.muted(\"—\")}`;\n if (typeof value === \"boolean\") {\n return ` ${theme.label(label + \":\")} ${value ? theme.success(\"yes\") : theme.muted(\"no\")}`;\n }\n return ` ${theme.label(label + \":\")} ${theme.value(String(value))}`;\n}\n\n/** Format a list of items as a simple table */\nexport function formatTable(headers: string[], rows: string[][]): string {\n // Calculate column widths\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map(r => (r[i] || \"\").length))\n );\n\n const headerLine = headers.map((h, i) => theme.label(h.padEnd(widths[i]))).join(\" \");\n const separator = widths.map(w => theme.dim(\"─\".repeat(w))).join(\" \");\n const dataLines = rows.map(row =>\n row.map((cell, i) => (cell || \"\").padEnd(widths[i])).join(\" \")\n );\n\n return [headerLine, separator, ...dataLines].join(\"\\n\");\n}\n\n/** Output data in either JSON or human-friendly format */\nexport function output(data: unknown, humanFormatter?: () => string): void {\n if (shouldOutputJson() || !humanFormatter) {\n outputJson(data);\n } else {\n process.stdout.write(humanFormatter() + \"\\n\");\n }\n}\n\n/** Format a status check line (for doctor command etc.) */\nexport function formatCheck(ok: boolean | \"warn\", label: string, detail?: string): string {\n const icon = ok === \"warn\" ? theme.warn(\"⚠\") : ok ? theme.success(\"✓\") : theme.error(\"✗\");\n const detailStr = detail ? ` ${theme.muted(`(${detail})`)}` : \"\";\n return `${icon} ${label}${detailStr}`;\n}\n\n/** Format a section heading */\nexport function formatSection(title: string): string {\n return `\\n${theme.heading(title)}`;\n}\n\n/** Format bytes to human readable */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/** Format relative time */\nexport function formatTimeAgo(date: Date | string): string {\n const d = typeof date === \"string\" ? new Date(date) : date;\n const seconds = Math.floor((Date.now() - d.getTime()) / 1000);\n if (seconds < 60) return \"just now\";\n if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;\n if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;\n return `${Math.floor(seconds / 86400)}d ago`;\n}\n","import chalk from \"chalk\";\n\nexport const TC_PALETTE = {\n primary: \"#4473b9\",\n accent: \"#5b9bd5\",\n success: \"#2fba6a\",\n warn: \"#e8a838\",\n error: \"#d94040\",\n muted: \"#808080\",\n dim: \"#5a5a5a\",\n} as const;\n\nexport const theme = {\n primary: chalk.hex(TC_PALETTE.primary),\n accent: chalk.hex(TC_PALETTE.accent),\n success: chalk.hex(TC_PALETTE.success),\n warn: chalk.hex(TC_PALETTE.warn),\n error: chalk.hex(TC_PALETTE.error),\n muted: chalk.hex(TC_PALETTE.muted),\n dim: chalk.hex(TC_PALETTE.dim),\n heading: chalk.bold.hex(TC_PALETTE.primary),\n command: chalk.hex(TC_PALETTE.accent),\n brand: chalk.bold.hex(TC_PALETTE.primary),\n label: chalk.bold,\n value: chalk.white,\n hint: chalk.italic.hex(TC_PALETTE.muted),\n};\n","interface HolidayTagline {\n month: number;\n day: number;\n range?: number; // days before/after to show\n tagline: string;\n}\n\nconst HOLIDAY_TAGLINES: HolidayTagline[] = [\n { month: 1, day: 1, range: 1, tagline: \"New year, new keys, same cloud.\" },\n { month: 2, day: 14, tagline: \"We love your data as much as you do.\" },\n { month: 3, day: 14, tagline: \"3.14159 reasons to encrypt everything.\" },\n { month: 5, day: 4, tagline: \"May the fourth be with your keys.\" },\n { month: 10, day: 31, tagline: \"Nothing scarier than plaintext secrets.\" },\n { month: 12, day: 25, range: 2, tagline: \"Unwrap your data, not your keys.\" },\n { month: 12, day: 31, tagline: \"Encrypt your resolutions.\" },\n];\n\nconst TAGLINES = [\n // Professional\n \"Your data, your keys, your cloud.\",\n \"Self-sovereign storage for the modern web.\",\n \"The cloud you actually own.\",\n \"Encrypted by default, decentralized by design.\",\n \"Where your data answers only to you.\",\n \"End-to-end encrypted. No exceptions.\",\n \"Like S3 but you hold the keys.\",\n \"Privacy isn't a feature. It's the architecture.\",\n \"Sovereign storage, zero knowledge.\",\n \"Your .env is safe here — we use real cryptography.\",\n // Playful / nerdy\n \"UCAN do anything.\",\n \"Keys generated, delegations granted, data liberated.\",\n \"Decentralized storage, centralized vibes.\",\n \"Trust nobody, delegate everything.\",\n \"sudo make me a sandwich, encrypted.\",\n \"Have you tried turning your keys off and on again?\",\n \"All your base are belong to you.\",\n \"In UCAN we trust.\",\n \"0 knowledge, 100% confidence.\",\n \"Keeping secrets since 2024.\",\n];\n\nfunction getHolidayTagline(): string | null {\n const now = new Date();\n const month = now.getMonth() + 1;\n const day = now.getDate();\n\n for (const h of HOLIDAY_TAGLINES) {\n const range = h.range ?? 0;\n if (h.month === month && Math.abs(day - h.day) <= range) {\n return h.tagline;\n }\n }\n return null;\n}\n\nexport function pickTagline(): string {\n const holiday = getHolidayTagline();\n if (holiday) return holiday;\n return TAGLINES[Math.floor(Math.random() * TAGLINES.length)];\n}\n","import { isInteractive } from \"./formatter.js\";\nimport { pickTagline } from \"./taglines.js\";\nimport { theme } from \"./theme.js\";\nimport { execSync } from \"node:child_process\";\n\nlet bannerEmitted = false;\n\nfunction resolveCommitHash(): string | null {\n try {\n return (\n execSync(\"git rev-parse --short HEAD\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim() || null\n );\n } catch {\n return null;\n }\n}\n\nfunction formatBannerLine(version: string): string {\n const commit = resolveCommitHash();\n const tagline = pickTagline();\n\n const versionPart = `tc v${version}`;\n const commitPart = commit ? ` (${commit})` : \"\";\n const separator = \" — \";\n\n if (!isInteractive()) {\n return `${versionPart}${commitPart}${separator}${tagline}`;\n }\n\n return [\n theme.brand(\"☁️ tc\"),\n \" \",\n theme.muted(`v${version}`),\n commit ? theme.dim(` (${commit})`) : \"\",\n theme.dim(separator),\n theme.primary(tagline),\n ].join(\"\");\n}\n\nexport function emitBanner(version: string): void {\n if (bannerEmitted) return;\n if (!isInteractive()) return;\n if (process.env.TC_HIDE_BANNER === \"1\") return;\n\n bannerEmitted = true;\n process.stderr.write(formatBannerLine(version) + \"\\n\\n\");\n}\n","import { join } from \"node:path\";\nimport {\n CONFIG_DIR,\n PROFILES_DIR,\n CONFIG_FILE,\n DEFAULT_PROFILE,\n DEFAULT_HOST,\n} from \"./constants.js\";\nimport { rm } from \"node:fs/promises\";\nimport {\n readJson,\n writeJson,\n fileExists,\n ensureDir,\n removeDir,\n listDirs,\n} from \"./storage.js\";\nimport type { GlobalConfig, ProfileConfig, CLIContext } from \"./types.js\";\nimport { CLIError, setActiveProfileName } from \"../output/errors.js\";\n\nexport class ProfileManager {\n // ── Initialization ──────────────────────────────────────────────────\n\n /**\n * Creates ~/.tinycloud/ and ~/.tinycloud/profiles/ if they don't exist.\n */\n static async ensureConfigDir(): Promise<void> {\n await ensureDir(CONFIG_DIR);\n await ensureDir(PROFILES_DIR);\n }\n\n // ── Global config ───────────────────────────────────────────────────\n\n /**\n * Reads config.json. Returns a default config if the file is missing.\n */\n static async getConfig(): Promise<GlobalConfig> {\n const config = await readJson<GlobalConfig>(CONFIG_FILE);\n if (!config) {\n return { defaultProfile: DEFAULT_PROFILE, version: 1 };\n }\n return config;\n }\n\n /**\n * Writes the global config to config.json.\n */\n static async setConfig(config: GlobalConfig): Promise<void> {\n await ProfileManager.ensureConfigDir();\n await writeJson(CONFIG_FILE, config);\n }\n\n // ── Profile CRUD ────────────────────────────────────────────────────\n\n /**\n * Returns the profile config for the given name.\n * Throws CLIError if the profile doesn't exist.\n */\n static async getProfile(name: string): Promise<ProfileConfig> {\n const profilePath = join(PROFILES_DIR, name, \"profile.json\");\n const profile = await readJson<ProfileConfig>(profilePath);\n if (!profile) {\n throw new CLIError(\n \"PROFILE_NOT_FOUND\",\n `Profile \"${name}\" does not exist. Run \\`tc init\\` or \\`tc profile create ${name}\\` first.`,\n );\n }\n return profile;\n }\n\n /**\n * Saves a profile config, creating the profile directory if needed.\n */\n static async setProfile(name: string, data: ProfileConfig): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"profile.json\"), data);\n }\n\n /**\n * Returns true if a profile directory exists.\n */\n static async profileExists(name: string): Promise<boolean> {\n return fileExists(join(PROFILES_DIR, name, \"profile.json\"));\n }\n\n /**\n * Returns an array of profile directory names.\n */\n static async listProfiles(): Promise<string[]> {\n return listDirs(PROFILES_DIR);\n }\n\n /**\n * Deletes a profile directory.\n * Throws if trying to delete the current default profile.\n */\n static async deleteProfile(name: string): Promise<void> {\n const config = await ProfileManager.getConfig();\n if (config.defaultProfile === name) {\n throw new CLIError(\n \"PROFILE_DELETE_DEFAULT\",\n `Cannot delete the default profile \"${name}\". Change the default first with \\`tc profile default <other>\\`.`,\n );\n }\n const profileDir = join(PROFILES_DIR, name);\n await removeDir(profileDir);\n }\n\n // ── Key management ──────────────────────────────────────────────────\n\n /**\n * Returns the parsed JWK for a profile, or null if no key exists.\n */\n static async getKey(name: string): Promise<object | null> {\n return readJson<object>(join(PROFILES_DIR, name, \"key.json\"));\n }\n\n /**\n * Saves a JWK key for a profile.\n */\n static async setKey(name: string, jwk: object): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"key.json\"), jwk);\n }\n\n // ── Session management ──────────────────────────────────────────────\n\n /**\n * Returns the parsed session for a profile, or null if none exists.\n */\n static async getSession(name: string): Promise<object | null> {\n return readJson<object>(join(PROFILES_DIR, name, \"session.json\"));\n }\n\n /**\n * Saves session data for a profile.\n */\n static async setSession(name: string, session: object): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"session.json\"), session);\n }\n\n /**\n * Removes the session file for a profile.\n */\n static async clearSession(name: string): Promise<void> {\n const sessionPath = join(PROFILES_DIR, name, \"session.json\");\n try {\n await rm(sessionPath);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw err;\n }\n }\n }\n\n // ── Cache management ────────────────────────────────────────────────\n\n /**\n * Returns the path to the profile's cache directory, creating it if needed.\n */\n static async getCacheDir(name: string): Promise<string> {\n const cacheDir = join(PROFILES_DIR, name, \"cache\");\n await ensureDir(cacheDir);\n return cacheDir;\n }\n\n // ── Resolution helpers ──────────────────────────────────────────────\n\n /**\n * Resolves the full CLI context from flags, env vars, and config.\n *\n * Profile resolution: options.profile > TC_PROFILE env > config.defaultProfile > \"default\"\n * Host resolution: options.host > TC_HOST env > profile.host > DEFAULT_HOST\n */\n static async resolveContext(options: {\n profile?: string;\n host?: string;\n verbose?: boolean;\n noCache?: boolean;\n quiet?: boolean;\n }): Promise<CLIContext> {\n // Resolve profile name\n const config = await ProfileManager.getConfig();\n const profile =\n options.profile ??\n process.env.TC_PROFILE ??\n config.defaultProfile ??\n DEFAULT_PROFILE;\n\n // Resolve host — try profile config if it exists, but don't fail if it doesn't\n let profileHost: string | undefined;\n try {\n const profileConfig = await ProfileManager.getProfile(profile);\n profileHost = profileConfig.host;\n } catch {\n // Profile may not exist yet (e.g., during `tc init`)\n }\n\n const host =\n options.host ??\n process.env.TC_HOST ??\n profileHost ??\n DEFAULT_HOST;\n\n setActiveProfileName(profile);\n\n return {\n profile,\n host,\n verbose: options.verbose ?? false,\n noCache: options.noCache ?? false,\n quiet: options.quiet ?? false,\n };\n }\n}\n","import { readFile, writeFile, stat, mkdir, rm, readdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\n/**\n * Read and parse a JSON file. Returns null if the file does not exist.\n * Throws on any other error (permission denied, invalid JSON, etc.).\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n const data = await readFile(filePath, \"utf-8\");\n return JSON.parse(data) as T;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n}\n\n/**\n * Write data as JSON to a file. Creates parent directories if needed.\n */\nexport async function writeJson(filePath: string, data: unknown): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, JSON.stringify(data, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Check if a file exists at the given path.\n */\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n await stat(filePath);\n return true;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw err;\n }\n}\n\n/**\n * Ensure a directory exists (mkdir -p).\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Remove a directory recursively (rm -rf).\n */\nexport async function removeDir(dirPath: string): Promise<void> {\n await rm(dirPath, { recursive: true, force: true });\n}\n\n/**\n * List directory names (not files) inside a directory.\n * Returns an empty array if the directory does not exist.\n */\nexport async function listDirs(dirPath: string): Promise<string[]> {\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return [];\n }\n throw err;\n }\n}\n","import { TCWSessionManager, importKey, initPanicHook } from \"@tinycloud/node-sdk-wasm\";\nimport { PrivateKeySigner, pkhDid } from \"@tinycloud/node-sdk\";\nimport { randomBytes } from \"node:crypto\";\n\nlet wasmInitialized = false;\n\nfunction ensureWasm(): void {\n if (!wasmInitialized) {\n initPanicHook();\n wasmInitialized = true;\n }\n}\n\n/**\n * Generate a new Ed25519 keypair. Returns the JWK.\n */\nexport function generateKey(): { jwk: object; did: string } {\n ensureWasm();\n const mgr = new TCWSessionManager();\n const keyId = mgr.createSessionKey(\"cli\");\n const jwkStr = mgr.jwk(keyId);\n if (!jwkStr) throw new Error(\"Failed to generate key\");\n const jwk = JSON.parse(jwkStr);\n const did = mgr.getDID(keyId);\n return { jwk, did };\n}\n\n/**\n * Get the DID from an existing JWK.\n */\nexport function keyToDID(jwk: object): string {\n ensureWasm();\n const mgr = new TCWSessionManager();\n const keyId = importKey(mgr, JSON.stringify(jwk), \"imported\");\n return mgr.getDID(keyId);\n}\n\n/**\n * Generate a new random Ethereum private key.\n * Returns the hex-encoded key with 0x prefix.\n */\nexport function generateEthereumPrivateKey(): string {\n const keyBytes = randomBytes(32);\n return \"0x\" + keyBytes.toString(\"hex\");\n}\n\n/**\n * Derive the Ethereum address from a private key.\n * Uses PrivateKeySigner from node-sdk.\n */\nexport async function deriveAddress(privateKey: string): Promise<string> {\n const signer = new PrivateKeySigner(privateKey);\n return signer.getAddress();\n}\n\n/**\n * Create a did:pkh DID from an Ethereum address.\n * Uses EIP-155 chain ID 1 (mainnet).\n */\nexport function addressToDID(address: string, chainId: number = 1): string {\n return pkhDid(address, chainId);\n}\n\n/**\n * Generate a new local Ethereum key and return all identity info.\n */\nexport async function generateLocalIdentity(chainId: number = 1): Promise<{\n privateKey: string;\n address: string;\n did: string;\n}> {\n const privateKey = generateEthereumPrivateKey();\n const address = await deriveAddress(privateKey);\n const did = addressToDID(address, chainId);\n return { privateKey, address, did };\n}\n\n/**\n * Sign in to TinyCloud using a local Ethereum private key.\n * Creates a TinyCloudNode with the private key and calls signIn().\n */\nexport async function localKeySignIn(options: {\n privateKey: string;\n host: string;\n}): Promise<{\n spaceId: string;\n address: string;\n chainId: number;\n delegationHeader: { Authorization: string };\n delegationCid: string;\n jwk: object;\n verificationMethod: string;\n siwe?: string;\n signature?: string;\n}> {\n const { TinyCloudNode } = await import(\"@tinycloud/node-sdk\");\n\n const node = new TinyCloudNode({\n privateKey: options.privateKey,\n host: options.host,\n autoCreateSpace: true,\n });\n\n await node.signIn();\n\n const address = await new PrivateKeySigner(options.privateKey).getAddress();\n const session = node.session;\n if (!session) {\n throw new Error(\"Local key sign-in did not produce a TinyCloud session\");\n }\n\n return {\n spaceId: session.spaceId,\n address,\n chainId: 1,\n delegationHeader: session.delegationHeader,\n delegationCid: session.delegationCid,\n jwk: session.jwk,\n verificationMethod: session.verificationMethod,\n siwe: session.siwe,\n signature: session.signature,\n };\n}\n","import type { PermissionEntry } from \"@tinycloud/node-sdk\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { isInteractive } from \"../output/formatter.js\";\nimport { createInterface } from \"node:readline\";\nimport { DEFAULT_OPENKEY_HOST } from \"../config/constants.js\";\n\ninterface DelegationData {\n delegationHeader: { Authorization: string };\n delegationCid: string;\n spaceId: string;\n [key: string]: unknown;\n}\n\ninterface AuthFlowOptions {\n paste?: boolean;\n jwk?: object;\n host?: string;\n permissions?: PermissionEntry[];\n /**\n * OpenKey base URL. Resolution order in callers: TC_OPENKEY_HOST env →\n * profile.openkeyHost → DEFAULT_OPENKEY_HOST. Threaded explicitly so this\n * module stays free of profile lookups.\n */\n openkeyHost?: string;\n /**\n * Lifetime hint for the resulting delegation. Encoded into the\n * `/delegate?expiry=<value>` URL parameter so OpenKey can sign for the\n * requested window instead of its hardcoded default. Forwarded as-is —\n * OpenKey does the parsing and clamping server-side.\n */\n expiry?: string | number;\n}\n\n/**\n * Start the browser auth flow.\n * Mode 1 (default): local HTTP callback server\n * Mode 2 (--paste): manual code paste\n */\nexport async function startAuthFlow(\n did: string,\n options: AuthFlowOptions = {}\n): Promise<DelegationData> {\n if (options.paste) {\n return pasteFlow(did, options);\n }\n\n try {\n return await callbackFlow(did, options);\n } catch {\n // Fallback to paste if browser can't open\n if (isInteractive()) {\n console.error(\"Could not open browser. Falling back to manual paste mode.\");\n return pasteFlow(did, options);\n }\n throw new Error(\"Cannot open browser in non-interactive mode. Use --paste flag.\");\n }\n}\n\nfunction buildAuthUrl(did: string, options: AuthFlowOptions & { callback?: string } = {}): string {\n const params = new URLSearchParams();\n params.set(\"did\", did);\n if (options.callback) {\n params.set(\"callback\", options.callback);\n }\n if (options.jwk) {\n // base64url-encode the JWK\n const jwkB64 = Buffer.from(JSON.stringify(options.jwk)).toString(\"base64url\");\n params.set(\"jwk\", jwkB64);\n }\n if (options.host) {\n params.set(\"host\", options.host);\n }\n if (options.permissions?.length) {\n params.set(\n \"permissions\",\n Buffer.from(JSON.stringify({ permissions: options.permissions })).toString(\"base64url\"),\n );\n }\n if (options.expiry !== undefined) {\n params.set(\"expiry\", String(options.expiry));\n }\n const base = options.openkeyHost ?? DEFAULT_OPENKEY_HOST;\n return `${base}/delegate?${params.toString()}`;\n}\n\nasync function callbackFlow(did: string, options: AuthFlowOptions = {}): Promise<DelegationData> {\n return new Promise((resolve, reject) => {\n let timeout: ReturnType<typeof setTimeout>;\n let settled = false;\n let rl: ReturnType<typeof createInterface> | undefined;\n\n function settle(result: { data?: DelegationData; error?: Error }) {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n server.close();\n if (rl) {\n rl.close();\n }\n if (result.data) {\n resolve(result.data);\n } else {\n reject(result.error);\n }\n }\n\n function parsePasteInput(input: string): DelegationData {\n const trimmed = input.trim();\n // Try parsing as JSON directly\n try {\n return JSON.parse(trimmed) as DelegationData;\n } catch {\n // Try base64 decoding first\n const decoded = Buffer.from(trimmed, \"base64\").toString(\"utf-8\");\n return JSON.parse(decoded) as DelegationData;\n }\n }\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n if (req.method === \"POST\" && req.url === \"/callback\") {\n let body = \"\";\n req.on(\"data\", (chunk: Buffer) => { body += chunk.toString(); });\n req.on(\"end\", () => {\n try {\n const data = JSON.parse(body) as DelegationData;\n // Send CORS headers and success response\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": \"*\",\n });\n res.end(JSON.stringify({ success: true }));\n settle({ data });\n } catch (err) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid JSON\" }));\n settle({ error: new Error(\"Invalid delegation data received\") });\n }\n });\n } else if (req.method === \"OPTIONS\") {\n // CORS preflight\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end();\n } else {\n res.writeHead(404);\n res.end();\n }\n });\n\n server.listen(0, \"127.0.0.1\", async () => {\n const addr = server.address();\n if (!addr || typeof addr === \"string\") {\n settle({ error: new Error(\"Failed to start callback server\") });\n return;\n }\n const port = addr.port;\n const callbackUrl = `http://127.0.0.1:${port}/callback`;\n const authUrl = buildAuthUrl(did, { ...options, callback: callbackUrl });\n\n if (isInteractive()) {\n console.error(`Opening browser for authentication...`);\n console.error(`If the browser doesn't open, visit: ${authUrl}`);\n }\n\n try {\n const open = (await import(\"open\")).default;\n await open(authUrl);\n } catch {\n server.close();\n throw new Error(\"Failed to open browser\");\n }\n\n // In interactive mode, also accept paste input while waiting for callback\n if (isInteractive()) {\n console.error(`\\nIf the browser can't connect back, paste the delegation code here:`);\n rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n rl.on(\"line\", (input) => {\n if (settled) return;\n try {\n const data = parsePasteInput(input);\n settle({ data });\n } catch {\n console.error(\"Invalid delegation code. Expected JSON or base64-encoded JSON. Try again:\");\n }\n });\n }\n });\n\n // Timeout after 5 minutes\n timeout = setTimeout(() => {\n settle({ error: new Error(\"Authentication timed out after 5 minutes\") });\n }, 5 * 60 * 1000);\n });\n}\n\nasync function pasteFlow(did: string, options: AuthFlowOptions = {}): Promise<DelegationData> {\n const authUrl = buildAuthUrl(did, options);\n\n console.error(`\\nOpen this URL in a browser to authenticate:\\n`);\n console.error(` ${authUrl}\\n`);\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n return new Promise((resolve, reject) => {\n rl.question(\"Paste delegation code: \", (input) => {\n rl.close();\n try {\n // Try parsing as JSON directly\n const data = JSON.parse(input.trim()) as DelegationData;\n resolve(data);\n } catch {\n // Try base64 decoding first\n try {\n const decoded = Buffer.from(input.trim(), \"base64\").toString(\"utf-8\");\n const data = JSON.parse(decoded) as DelegationData;\n resolve(data);\n } catch {\n reject(new Error(\"Invalid delegation code. Expected JSON or base64-encoded JSON.\"));\n }\n }\n });\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_HOST, DEFAULT_CHAIN_ID } from \"../config/constants.js\";\nimport { generateKey } from \"../auth/local-key.js\";\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\n\nexport function registerInitCommand(program: Command): void {\n program\n .command(\"init\")\n .description(\"Initialize a new TinyCloud profile\")\n .option(\"--name <profile>\", \"Profile name\", \"default\")\n .option(\"--key-only\", \"Only generate key, skip authentication\")\n .option(\"--host <url>\", \"TinyCloud node URL\")\n .option(\"--paste\", \"Use manual paste mode for authentication\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const profileName: string = options.name;\n const host: string = options.host ?? globalOpts.host ?? DEFAULT_HOST;\n\n // Check if profile already exists\n if (await ProfileManager.profileExists(profileName)) {\n throw new CLIError(\n \"PROFILE_EXISTS\",\n `Profile \"${profileName}\" already exists. Use \\`tc profile delete ${profileName}\\` first or choose a different name.`,\n ExitCode.ERROR,\n );\n }\n\n await ProfileManager.ensureConfigDir();\n\n // Generate key\n const { jwk, did } = await withSpinner(\"Generating key...\", async () => {\n return generateKey();\n });\n\n await ProfileManager.setKey(profileName, jwk);\n\n // Create initial profile\n const profileConfig = {\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n createdAt: new Date().toISOString(),\n };\n\n await ProfileManager.setProfile(profileName, profileConfig);\n\n // Set as default if this is \"default\" or no default exists\n const config = await ProfileManager.getConfig();\n if (profileName === \"default\" || !await ProfileManager.profileExists(config.defaultProfile)) {\n await ProfileManager.setConfig({ ...config, defaultProfile: profileName });\n }\n\n if (options.keyOnly) {\n outputJson({\n profile: profileName,\n did,\n host,\n authenticated: false,\n });\n return;\n }\n\n // Auth flow\n const delegationData = await startAuthFlow(did, {\n paste: options.paste,\n jwk,\n host,\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with auth data\n await ProfileManager.setProfile(profileName, {\n ...profileConfig,\n spaceId: delegationData.spaceId,\n ownerDid: delegationData.ownerDid as string | undefined,\n });\n\n outputJson({\n profile: profileName,\n did,\n host,\n spaceId: delegationData.spaceId,\n authenticated: true,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { get as httpGet } from \"node:http\";\nimport { get as httpsGet } from \"node:https\";\nimport { spawn } from \"node:child_process\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { PermissionEntry, PortableDelegation } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatField, formatTable, isInteractive, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_CHAIN_ID, DEFAULT_OPENKEY_HOST } from \"../config/constants.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type AuthMethod,\n type ProfileConfig,\n} from \"../config/types.js\";\n\n/**\n * Resolve the OpenKey base URL for a profile.\n * Order: TC_OPENKEY_HOST env override → profile.openkeyHost → default.\n *\n * No prompts, no migration. To use a self-hosted OpenKey for a profile,\n * edit `~/.tinycloud/profiles/<profile>/profile.json` and add an\n * \"openkeyHost\": \"https://openkey.localhost\" field.\n */\nfunction resolveOpenKeyHost(profile: ProfileConfig): string {\n return process.env.TC_OPENKEY_HOST ?? profile.openkeyHost ?? DEFAULT_OPENKEY_HOST;\n}\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\nimport {\n generateLocalIdentity,\n deriveAddress,\n addressToDID,\n localKeySignIn,\n generateKey,\n keyToDID,\n} from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport {\n appendAdditionalDelegation,\n appendPermissionRequestArtifact,\n createPermissionRequestArtifact,\n getLastPermissionRequestArtifact,\n getPermissionRequestArtifact,\n isDelegationImportArtifact,\n isPermissionRequestArtifact,\n appendGrantHistory,\n compactPermission,\n loadAdditionalDelegations,\n loadManifestPermissions,\n loadPermissionRequest,\n parseCapSpec,\n permissionsFromDelegation,\n readGrantHistory,\n storedAdditionalDelegation,\n type PermissionRequestArtifact,\n} from \"../lib/permissions.js\";\n\n/**\n * Prompt user to choose an auth method interactively.\n * Returns \"local\" for non-interactive (CI/headless) environments.\n */\nasync function promptAuthMethod(): Promise<AuthMethod> {\n if (!isInteractive()) {\n return \"local\";\n }\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n return new Promise<AuthMethod>((resolve) => {\n process.stderr.write(\"\\n\" + theme.heading(\"Choose authentication method:\") + \"\\n\");\n process.stderr.write(` ${theme.accent(\"1)\")} OpenKey ${theme.muted(\"(browser-based, for interactive use)\")}\\n`);\n process.stderr.write(` ${theme.accent(\"2)\")} Local key ${theme.muted(\"(Ethereum private key, for agents/CI)\")}\\n\\n`);\n\n rl.question(\"Enter choice [1]: \", (answer) => {\n rl.close();\n const trimmed = answer.trim();\n if (trimmed === \"2\" || trimmed.toLowerCase() === \"local\") {\n resolve(\"local\");\n } else {\n resolve(\"openkey\");\n }\n });\n });\n}\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program.command(\"auth\").description(\"Authentication management\");\n\n auth\n .command(\"login\")\n .description(\"Authenticate with TinyCloud\")\n .option(\"--paste\", \"Use manual paste mode instead of browser callback\")\n .option(\"--method <method>\", \"Authentication method: local or openkey\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n // Determine auth method\n let method: AuthMethod;\n if (options.method) {\n if (options.method !== \"local\" && options.method !== \"openkey\") {\n throw new CLIError(\n \"INVALID_METHOD\",\n `Invalid auth method \"${options.method}\". Use \"local\" or \"openkey\".`,\n ExitCode.USAGE_ERROR,\n );\n }\n method = options.method;\n } else {\n method = await promptAuthMethod();\n }\n\n if (method === \"local\") {\n await handleLocalAuth(ctx.profile, ctx.host);\n } else {\n await handleOpenKeyAuth(ctx.profile, ctx.host, options.paste);\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"logout\")\n .description(\"Clear session (keep key)\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n await ProfileManager.clearSession(ctx.profile);\n outputJson({ profile: ctx.profile, authenticated: false });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"status\")\n .description(\"Show current authentication state\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const hasKey = await ProfileManager.getKey(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile);\n let profile;\n try {\n profile = await ProfileManager.getProfile(ctx.profile);\n } catch {\n profile = null;\n }\n const posture = profile ? resolveProfilePosture(profile) : null;\n const operatorType = profile ? resolveProfileOperatorType(profile) : null;\n\n const authenticated = session !== null;\n\n if (shouldOutputJson()) {\n outputJson({\n authenticated,\n did: profile?.did ?? null,\n sessionDid: profile?.sessionDid ?? null,\n ownerDid: profile?.ownerDid ?? null,\n spaceId: profile?.spaceId ?? null,\n host: ctx.host,\n profile: ctx.profile,\n hasKey: hasKey !== null,\n authMethod: profile?.authMethod ?? null,\n posture,\n operatorType,\n address: profile?.address ?? null,\n });\n } else {\n process.stdout.write(theme.heading(\"Authentication Status\") + \"\\n\");\n process.stdout.write(formatField(\"Profile\", ctx.profile) + \"\\n\");\n process.stdout.write(formatField(\"Authenticated\", authenticated) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile?.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\n\");\n process.stdout.write(formatField(\"Host\", ctx.host) + \"\\n\");\n process.stdout.write(formatField(\"DID\", profile?.did ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Session DID\", profile?.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Owner DID\", profile?.ownerDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Address\", profile?.address ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Space ID\", profile?.spaceId ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Has Key\", hasKey !== null) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"request\")\n .description(\"Create a TinyCloud permission request artifact\")\n .option(\n \"--cap <spec>\",\n \"Capability spec: tinycloud.<service>:<space>:<path>:<actions-csv> (repeatable)\",\n (value, previous: string[]) => [...previous, value],\n [],\n )\n .option(\"--permission <file>\", \"JSON permission request: { \\\"permissions\\\": PermissionEntry[] }\")\n .option(\"--manifest <fileOrBase64>\", \"Manifest file, base64:<json>, or raw base64 JSON\")\n .option(\n \"--expiry <duration>\",\n \"Lifetime of the granted delegation. ms-format string (e.g. \\\"7d\\\", \\\"30m\\\") or raw milliseconds. Defaults to 7d, capped by the active session's expiry.\",\n )\n .option(\"--emit [file]\", \"Emit the request artifact to stdout, or write it to file when provided\")\n .option(\"--grant\", \"Grant the requested permissions immediately with this owner profile\")\n .option(\"--yes\", \"Skip local-key TTY confirmation\", false)\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profile = await ProfileManager.getProfile(ctx.profile);\n const requested = await collectRequestedPermissions(options, ctx.profile);\n const expiryOption = parseExpiryOption(options.expiry);\n\n if (requested.length === 0) {\n throw new CLIError(\n \"NO_CAPS_REQUESTED\",\n \"Provide at least one --cap, --permission, or --manifest.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n if (!options.grant) {\n const artifact = createPermissionRequestArtifact({\n profileName: ctx.profile,\n profile,\n host: ctx.host,\n requested,\n requestedExpiry: expiryOption,\n });\n await appendPermissionRequestArtifact(ctx.profile, artifact);\n await emitPermissionRequestArtifact(artifact, options.emit);\n return;\n }\n\n const node = await ensureAuthenticated(ctx);\n\n // Fast path: master's grantRuntimePermissions / hasRuntimePermissions\n // already does the diff against the live session + existing runtime\n // grants; no need to compute it ourselves.\n if (node.hasRuntimePermissions(requested)) {\n outputJson({ changed: false, missing: [], added: [] });\n return;\n }\n\n if (profile.authMethod === \"openkey\") {\n const key = await ProfileManager.getKey(ctx.profile);\n if (!key) {\n throw new CLIError(\"NO_KEY\", `No key found for profile \"${ctx.profile}\". Run \\`tc init\\` first.`, ExitCode.AUTH_REQUIRED);\n }\n const delegationCids: string[] = [];\n let expiry: string | undefined;\n const openkeyHost = resolveOpenKeyHost(profile);\n for (const group of groupPermissionsBySpace(requested)) {\n const delegationData = await startAuthFlow(profile.did, {\n jwk: key,\n host: ctx.host,\n permissions: group,\n openkeyHost,\n expiry: expiryOption,\n });\n const delegation = portableFromOpenKeyDelegation(delegationData, group, ctx.host);\n const stored = storedAdditionalDelegation(delegation, group);\n await appendAdditionalDelegation(ctx.profile, stored);\n await node.useRuntimeDelegation(delegation);\n delegationCids.push(delegation.cid);\n expiry = delegation.expiry.toISOString();\n await appendGrantHistory(ctx.profile, {\n addedCaps: group,\n source: options.manifest ? \"manifest\" : \"cli\",\n delegationCid: delegation.cid,\n expiry,\n });\n }\n outputJson({\n changed: delegationCids.length > 0,\n added: requested,\n delegationCid: delegationCids[0],\n delegationCids,\n expiry,\n });\n return;\n }\n\n if (isInteractive()) {\n if (!options.yes) {\n await confirmPermissionRequest(requested);\n }\n } else if (!options.yes) {\n throw new CLIError(\n \"CONFIRMATION_REQUIRED\",\n \"Local-key permission requests in non-interactive mode require --yes.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n // Local-key flow: master's grantRuntimePermissions handles signing\n // through the SDK's wallet-mode signer, groups by space, and skips\n // anything already covered by the session or an existing grant.\n const delegations = await node.grantRuntimePermissions(\n requested,\n expiryOption !== undefined ? { expiry: expiryOption } : undefined,\n );\n const delegationCids: string[] = [];\n let expiry: string | undefined;\n for (const delegation of delegations) {\n const covering = permissionsFromDelegation(delegation);\n const stored = storedAdditionalDelegation(delegation, covering);\n await appendAdditionalDelegation(ctx.profile, stored);\n delegationCids.push(delegation.cid);\n expiry = delegation.expiry.toISOString();\n await appendGrantHistory(ctx.profile, {\n addedCaps: covering,\n source: options.manifest ? \"manifest\" : \"cli\",\n delegationCid: delegation.cid,\n expiry,\n });\n }\n\n if (delegationCids.length === 0) {\n outputJson({ changed: false, missing: [], added: [] });\n return;\n }\n\n outputJson({\n changed: true,\n added: requested,\n delegationCid: delegationCids[0],\n delegationCids,\n expiry,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"import [source]\")\n .description(\"Import a TinyCloud delegation or permission request artifact\")\n .option(\"--stdin\", \"Read the JSON artifact from stdin\")\n .option(\"--paste\", \"Read the JSON artifact from stdin\")\n .action(async (source: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const raw = await readAuthArtifactSource(source, {\n stdin: options.stdin === true || options.paste === true,\n });\n const parsed = JSON.parse(raw) as unknown;\n\n if (isPermissionRequestArtifact(parsed)) {\n await appendPermissionRequestArtifact(ctx.profile, parsed);\n outputJson({\n imported: true,\n kind: parsed.kind,\n requestId: parsed.requestId,\n requested: parsed.requested,\n next: `tc auth retry ${parsed.requestId}`,\n });\n return;\n }\n\n const imported = normalizeDelegationImport(parsed);\n const node = await ensureAuthenticated(ctx);\n await appendAdditionalDelegation(ctx.profile, storedAdditionalDelegation(\n imported.delegation,\n imported.permissions,\n ));\n await node.useRuntimeDelegation(imported.delegation);\n await appendGrantHistory(ctx.profile, {\n addedCaps: imported.permissions,\n source: \"cli\",\n delegationCid: imported.delegation.cid,\n expiry: imported.delegation.expiry.toISOString(),\n });\n\n outputJson({\n imported: true,\n kind: \"tinycloud.auth.delegation\",\n requestId: imported.requestId ?? null,\n delegationCid: imported.delegation.cid,\n permissions: imported.permissions,\n expiry: imported.delegation.expiry.toISOString(),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"grant [request]\")\n .description(\"Grant a TinyCloud permission request artifact to its requester\")\n .option(\"--stdin\", \"Read the JSON request artifact from stdin\")\n .option(\"--paste\", \"Read the JSON request artifact from stdin\")\n .option(\"--yes\", \"Skip local-key TTY confirmation\", false)\n .action(async (source: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profile = await ProfileManager.getProfile(ctx.profile);\n const raw = await readAuthArtifactSource(source, {\n stdin: options.stdin === true || options.paste === true,\n });\n const parsed = JSON.parse(raw) as unknown;\n\n if (!isPermissionRequestArtifact(parsed)) {\n throw new CLIError(\n \"INVALID_AUTH_REQUEST\",\n \"Auth grant requires a tinycloud.auth.request artifact.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const node = await ensureAuthenticated(ctx);\n await ensureDelegationAuthority({\n ctx,\n profile,\n node,\n requested: parsed.requested,\n expiryOption: parsed.requestedExpiry,\n yes: options.yes === true,\n });\n const result = await node.delegateTo(\n parsed.sessionDid,\n parsed.requested,\n parsed.requestedExpiry !== undefined\n ? { expiry: parsed.requestedExpiry }\n : undefined,\n );\n\n outputJson({\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: parsed.requestId,\n delegationCid: result.delegation.cid,\n delegation: result.delegation,\n permissions: parsed.requested,\n expiry: result.delegation.expiry.toISOString(),\n prompted: result.prompted,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"retry [requestId]\")\n .description(\"Check whether a stored permission request is now satisfied\")\n .option(\"--last\", \"Use the latest stored permission request for this profile\")\n .option(\"--exec\", \"Run the captured command when the request is covered\")\n .action(async (requestId: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const artifact = options.last\n ? await getLastPermissionRequestArtifact(ctx.profile)\n : requestId\n ? await getPermissionRequestArtifact(ctx.profile, requestId)\n : null;\n\n if (!artifact) {\n throw new CLIError(\n \"REQUEST_NOT_FOUND\",\n options.last\n ? `No stored permission requests exist for profile \"${ctx.profile}\".`\n : \"Provide a requestId or use --last.\",\n ExitCode.NOT_FOUND,\n );\n }\n\n const node = await ensureAuthenticated(ctx);\n const covered = node.hasRuntimePermissions(artifact.requested);\n if (options.exec) {\n if (!covered) {\n throw new CLIError(\n \"PERMISSIONS_MISSING\",\n `Request ${artifact.requestId} is not covered yet. Import a delegation, then retry with --exec.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n if (!artifact.command?.argv?.length) {\n throw new CLIError(\n \"COMMAND_NOT_CAPTURED\",\n `Request ${artifact.requestId} does not include a captured command.`,\n ExitCode.USAGE_ERROR,\n );\n }\n await execCapturedCommand(artifact.command);\n return;\n }\n\n outputJson({\n requestId: artifact.requestId,\n covered,\n missing: covered ? [] : artifact.requested,\n command: artifact.command ?? null,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"caps\")\n .description(\"Show granted capabilities for the active session\")\n .option(\"--diff <spec>\", \"Show missing capabilities for a spec\")\n .option(\"--history\", \"Show recent permission grants\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n if (options.history) {\n const history = (await readGrantHistory(ctx.profile)).slice(-20);\n if (shouldOutputJson()) {\n outputJson({ grants: history });\n } else if (history.length === 0) {\n process.stdout.write(theme.muted(\"No grant history.\") + \"\\n\");\n } else {\n process.stdout.write(formatTable(\n [\"time\", \"source\", \"delegation\", \"caps\"],\n history.map((entry) => [\n entry.ts,\n entry.source,\n entry.delegationCid ?? \"\",\n entry.addedCaps.map(compactPermission).join(\"; \"),\n ]),\n ) + \"\\n\");\n }\n return;\n }\n\n const node = await ensureAuthenticated(ctx);\n const runtimeDelegations = node.getRuntimePermissionDelegations();\n // Granted view = permissions covered by appended runtime delegations.\n // The base-session SIWE recap isn't enumerated here because the\n // node-sdk doesn't expose it as a list — `hasRuntimePermissions()`\n // is the trusted answer for \"is this covered?\".\n const granted = runtimeDelegations.flatMap(permissionsFromDelegation);\n\n if (options.diff) {\n const requested = [await parseCapSpec(options.diff, ctx.profile)];\n const covered = node.hasRuntimePermissions(requested);\n outputJson({\n requested,\n changed: !covered,\n covered,\n // `missing` retained for backwards-compatible callers.\n missing: covered ? [] : requested,\n });\n return;\n }\n\n const appended = await loadAdditionalDelegations(ctx.profile);\n if (shouldOutputJson()) {\n outputJson({ granted, appendedDelegations: appended.length });\n } else if (granted.length === 0) {\n process.stdout.write(theme.muted(\"No appended runtime delegations on this profile.\") + \"\\n\");\n } else {\n process.stdout.write(formatTable(\n [\"service\", \"space\", \"path\", \"actions\"],\n granted.map((entry) => [\n entry.service,\n entry.space,\n entry.path,\n entry.actions.join(\", \"),\n ]),\n ) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"whoami\")\n .description(\"Show identity information\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile);\n const authenticated = session !== null;\n const posture = resolveProfilePosture(profile);\n const operatorType = resolveProfileOperatorType(profile);\n\n if (shouldOutputJson()) {\n outputJson({\n profile: ctx.profile,\n did: profile.did,\n sessionDid: profile.sessionDid ?? null,\n ownerDid: profile.ownerDid ?? null,\n spaceId: profile.spaceId ?? null,\n host: profile.host,\n authenticated,\n authMethod: profile.authMethod ?? null,\n posture,\n operatorType,\n address: profile.address ?? null,\n });\n } else {\n process.stdout.write(theme.heading(\"Identity\") + \"\\n\");\n process.stdout.write(formatField(\"Profile\", ctx.profile) + \"\\n\");\n process.stdout.write(formatField(\"DID\", profile.did) + \"\\n\");\n process.stdout.write(formatField(\"Session DID\", profile.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Owner DID\", profile.ownerDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\n\");\n process.stdout.write(formatField(\"Address\", profile.address ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Space ID\", profile.spaceId ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Host\", profile.host) + \"\\n\");\n process.stdout.write(formatField(\"Authenticated\", authenticated) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nasync function emitPermissionRequestArtifact(\n artifact: PermissionRequestArtifact,\n emitOption: unknown,\n): Promise<void> {\n if (typeof emitOption === \"string\" && emitOption.length > 0) {\n await mkdir(dirname(emitOption), { recursive: true });\n await writeFile(emitOption, JSON.stringify(artifact, null, 2) + \"\\n\", \"utf8\");\n outputJson({\n emitted: true,\n path: emitOption,\n requestId: artifact.requestId,\n requested: artifact.requested,\n });\n return;\n }\n outputJson(artifact);\n}\n\nasync function readAuthArtifactSource(\n source: string | undefined,\n options: { stdin: boolean },\n): Promise<string> {\n if (options.stdin || source === \"-\" || (!source && !isInteractive())) {\n return readStdin();\n }\n\n if (!source) {\n throw new CLIError(\n \"IMPORT_SOURCE_REQUIRED\",\n \"Provide an artifact file, URL, or use --stdin.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n if (source.startsWith(\"http://\") || source.startsWith(\"https://\")) {\n return readUrl(source);\n }\n\n return readFile(source, \"utf8\");\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction readUrl(source: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const getter = source.startsWith(\"https://\") ? httpsGet : httpGet;\n const request = getter(source, (response: IncomingMessage) => {\n const status = response.statusCode ?? 0;\n if (status >= 300 && status < 400 && response.headers.location) {\n response.resume();\n readUrl(new URL(response.headers.location, source).toString()).then(resolve, reject);\n return;\n }\n if (status < 200 || status >= 300) {\n response.resume();\n reject(new CLIError(\n \"IMPORT_FETCH_FAILED\",\n `Failed to fetch ${source}: HTTP ${status}.`,\n ExitCode.ERROR,\n ));\n return;\n }\n\n const chunks: Buffer[] = [];\n response.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n response.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n });\n request.on(\"error\", reject);\n });\n}\n\nfunction normalizeDelegationImport(value: unknown): {\n requestId?: string;\n delegation: PortableDelegation;\n permissions: PermissionEntry[];\n} {\n if (isDelegationImportArtifact(value)) {\n const delegation = normalizePortableDelegation(value.delegation);\n return {\n requestId: value.requestId,\n delegation,\n permissions: Array.isArray(value.permissions) && value.permissions.length > 0\n ? value.permissions\n : permissionsFromDelegation(delegation),\n };\n }\n\n if (isStoredDelegationLike(value)) {\n const delegation = normalizePortableDelegation(value.delegation);\n return {\n delegation,\n permissions: Array.isArray(value.permissions) && value.permissions.length > 0\n ? value.permissions\n : permissionsFromDelegation(delegation),\n };\n }\n\n if (isPortableDelegationLike(value)) {\n const delegation = normalizePortableDelegation(value);\n return {\n delegation,\n permissions: permissionsFromDelegation(delegation),\n };\n }\n\n throw new CLIError(\n \"INVALID_AUTH_IMPORT\",\n \"Auth import must be a tinycloud.auth.delegation artifact, a portable delegation, or a tinycloud.auth.request artifact.\",\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction isStoredDelegationLike(value: unknown): value is {\n delegation: PortableDelegation;\n permissions?: PermissionEntry[];\n} {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as { delegation?: unknown };\n return isPortableDelegationLike(candidate.delegation);\n}\n\nfunction isPortableDelegationLike(value: unknown): value is PortableDelegation {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<PortableDelegation>;\n return (\n typeof candidate.cid === \"string\" &&\n typeof candidate.spaceId === \"string\" &&\n typeof candidate.path === \"string\" &&\n Array.isArray(candidate.actions) &&\n candidate.delegationHeader !== undefined &&\n typeof candidate.delegationHeader === \"object\"\n );\n}\n\nfunction normalizePortableDelegation(delegation: PortableDelegation): PortableDelegation {\n const rawExpiry = (delegation as PortableDelegation & { expiry: unknown }).expiry;\n const expiry = rawExpiry instanceof Date ? rawExpiry : new Date(String(rawExpiry));\n if (Number.isNaN(expiry.getTime())) {\n throw new CLIError(\n \"INVALID_AUTH_IMPORT\",\n \"Imported delegation must include a valid expiry.\",\n ExitCode.USAGE_ERROR,\n );\n }\n return { ...delegation, expiry };\n}\n\nasync function ensureDelegationAuthority(params: {\n ctx: { profile: string; host: string };\n profile: ProfileConfig;\n node: Awaited<ReturnType<typeof ensureAuthenticated>>;\n requested: PermissionEntry[];\n expiryOption: string | number | undefined;\n yes: boolean;\n}): Promise<void> {\n if (params.node.hasRuntimePermissions(params.requested)) return;\n\n if (params.profile.authMethod === \"openkey\") {\n const key = await ProfileManager.getKey(params.ctx.profile);\n if (!key) {\n throw new CLIError(\n \"NO_KEY\",\n `No key found for profile \"${params.ctx.profile}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n const openkeyHost = resolveOpenKeyHost(params.profile);\n for (const group of groupPermissionsBySpace(params.requested)) {\n const delegationData = await startAuthFlow(params.profile.did, {\n jwk: key,\n host: params.ctx.host,\n permissions: group,\n openkeyHost,\n expiry: params.expiryOption,\n });\n const delegation = portableFromOpenKeyDelegation(delegationData, group, params.ctx.host);\n await appendAdditionalDelegation(\n params.ctx.profile,\n storedAdditionalDelegation(delegation, group),\n );\n await params.node.useRuntimeDelegation(delegation);\n await appendGrantHistory(params.ctx.profile, {\n addedCaps: group,\n source: \"cli\",\n delegationCid: delegation.cid,\n expiry: delegation.expiry.toISOString(),\n });\n }\n return;\n }\n\n if (isInteractive()) {\n if (!params.yes) {\n await confirmPermissionRequest(params.requested);\n }\n } else if (!params.yes) {\n throw new CLIError(\n \"CONFIRMATION_REQUIRED\",\n \"Local-key auth grants in non-interactive mode require --yes.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const delegations = await params.node.grantRuntimePermissions(\n params.requested,\n params.expiryOption !== undefined ? { expiry: params.expiryOption } : undefined,\n );\n for (const delegation of delegations) {\n const covering = permissionsFromDelegation(delegation);\n await appendAdditionalDelegation(\n params.ctx.profile,\n storedAdditionalDelegation(delegation, covering),\n );\n await appendGrantHistory(params.ctx.profile, {\n addedCaps: covering,\n source: \"cli\",\n delegationCid: delegation.cid,\n expiry: delegation.expiry.toISOString(),\n });\n }\n}\n\nfunction execCapturedCommand(command: { argv: string[]; cwd: string }): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(process.execPath, [process.argv[1], ...command.argv], {\n cwd: command.cwd,\n env: process.env,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code, signal) => {\n if (signal) {\n reject(new CLIError(\n \"COMMAND_SIGNAL\",\n `Captured command exited from signal ${signal}.`,\n ExitCode.ERROR,\n ));\n return;\n }\n if (code && code !== 0) {\n process.exitCode = code;\n }\n resolve();\n });\n });\n}\n\nasync function collectRequestedPermissions(\n options: {\n cap?: string[];\n permission?: string;\n manifest?: string;\n },\n profile: string,\n): Promise<PermissionEntry[]> {\n const permissions: PermissionEntry[] = [];\n for (const spec of options.cap ?? []) {\n permissions.push(await parseCapSpec(spec, profile));\n }\n if (options.permission) {\n permissions.push(...await loadPermissionRequest(options.permission, profile));\n }\n if (options.manifest) {\n permissions.push(...await loadManifestPermissions(options.manifest, profile));\n }\n return permissions;\n}\n\nasync function confirmPermissionRequest(permissions: PermissionEntry[]): Promise<void> {\n process.stderr.write(\"\\n\" + theme.heading(\"Additional Permissions\") + \"\\n\");\n for (const permission of permissions) {\n const dangerous = isDangerousPermission(permission);\n const line = ` ${compactPermission(permission)}`;\n process.stderr.write((dangerous ? theme.warn(line) : theme.value(line)) + \"\\n\");\n }\n process.stderr.write(\"\\n\");\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Approve local-key delegation? [y/N] \", resolve);\n });\n rl.close();\n\n if (!/^y(es)?$/i.test(answer.trim())) {\n throw new CLIError(\"REQUEST_CANCELLED\", \"Permission request cancelled.\", ExitCode.ERROR);\n }\n}\n\nfunction isDangerousPermission(permission: PermissionEntry): boolean {\n if (permission.path === \"\" || permission.path === \"/\") return true;\n return permission.actions.some((action) =>\n action.includes(\"*\") ||\n action.endsWith(\"/write\") ||\n action.endsWith(\"/admin\") ||\n action.endsWith(\"/ddl\") ||\n action.endsWith(\"/del\"),\n );\n}\n\n/**\n * Parse the `--expiry` flag into either a ms-format string (\"7d\", \"30m\") or\n * raw milliseconds. Returns undefined for missing input so the caller falls\n * back to the SDK's DEFAULT_DELEGATION_EXPIRY_MS.\n *\n * Pure-numeric strings are coerced to numbers so a shell-quoted ms count\n * (`--expiry 86400000`) works, but anything that contains a unit suffix\n * (`\"7d\"`, `\"30m\"`) is forwarded as-is to parseExpiry which understands\n * the ms-format vocabulary.\n */\nfunction parseExpiryOption(raw: unknown): string | number | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw new CLIError(\n \"INVALID_EXPIRY\",\n `--expiry must be a string (e.g. \"7d\", \"30m\") or a millisecond integer.`,\n ExitCode.USAGE_ERROR,\n );\n }\n if (/^\\d+$/.test(raw.trim())) {\n const ms = Number(raw.trim());\n if (!Number.isFinite(ms) || ms <= 0) {\n throw new CLIError(\"INVALID_EXPIRY\", `--expiry must be a positive integer when numeric.`, ExitCode.USAGE_ERROR);\n }\n return ms;\n }\n return raw;\n}\n\nfunction groupPermissionsBySpace(permissions: PermissionEntry[]): PermissionEntry[][] {\n const groups = new Map<string, PermissionEntry[]>();\n for (const permission of permissions) {\n const group = groups.get(permission.space) ?? [];\n group.push(permission);\n groups.set(permission.space, group);\n }\n return Array.from(groups.values());\n}\n\nfunction portableFromOpenKeyDelegation(\n data: Record<string, unknown>,\n permissions: PermissionEntry[],\n host: string,\n): PortableDelegation {\n const primary = permissions[0];\n const returnedSpace = String(data.spaceId ?? primary.space);\n const expectedSpaces = new Set(permissions.map((permission) => permission.space));\n if (expectedSpaces.size !== 1 || !expectedSpaces.has(returnedSpace)) {\n throw new CLIError(\n \"OPENKEY_SCOPE_MISMATCH\",\n `OpenKey returned delegation for ${returnedSpace}, expected ${Array.from(expectedSpaces).join(\", \")}.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n const expiry = inferDelegationExpiry(data);\n return {\n cid: String(data.delegationCid),\n delegationHeader: data.delegationHeader as { Authorization: string },\n spaceId: returnedSpace,\n path: primary.path,\n actions: primary.actions,\n resources: permissions.map((permission) => ({\n service: permission.service.startsWith(\"tinycloud.\")\n ? permission.service.slice(\"tinycloud.\".length)\n : permission.service,\n space: permission.space,\n path: permission.path,\n actions: [...permission.actions],\n })),\n expiry,\n delegateDID: String(data.verificationMethod),\n ownerAddress: String(data.address ?? \"\"),\n chainId: typeof data.chainId === \"number\" ? data.chainId : DEFAULT_CHAIN_ID,\n host,\n };\n}\n\nfunction inferDelegationExpiry(data: Record<string, unknown>): Date {\n const direct = data.expiry ?? data.expiresAt;\n if (typeof direct === \"string\") {\n const parsed = new Date(direct);\n if (!Number.isNaN(parsed.getTime())) return parsed;\n }\n return new Date(Date.now() + 60 * 60 * 1000);\n}\n\n/**\n * Handle local Ethereum key authentication.\n * Generates or reuses a local private key, creates a did:pkh identity,\n * and signs in to TinyCloud directly (no browser needed).\n */\nasync function handleLocalAuth(profileName: string, host: string): Promise<void> {\n const profile = await ProfileManager.getProfile(profileName).catch(() => null);\n\n let privateKey: string;\n let address: string;\n let did: string;\n let sessionDid = profile?.sessionDid;\n\n if (profile?.authMethod === \"local\" && profile.privateKey && profile.address) {\n // Reuse existing local key\n privateKey = profile.privateKey;\n address = profile.address;\n did = profile.did;\n\n if (isInteractive()) {\n process.stderr.write(theme.muted(\"Using existing local key\") + \"\\n\");\n process.stderr.write(formatField(\"Address\", address) + \"\\n\");\n }\n } else {\n // Generate new local identity\n const identity = await withSpinner(\"Generating Ethereum key...\", async () => {\n return generateLocalIdentity(DEFAULT_CHAIN_ID);\n });\n\n privateKey = identity.privateKey;\n address = identity.address;\n did = identity.did;\n\n if (isInteractive()) {\n process.stderr.write(\"\\n\" + theme.heading(\"Local Key Generated\") + \"\\n\");\n process.stderr.write(formatField(\"Address\", address) + \"\\n\");\n process.stderr.write(formatField(\"DID\", did) + \"\\n\\n\");\n }\n }\n\n // We also need a session key (Ed25519 JWK) for the profile\n const hasKey = await ProfileManager.getKey(profileName);\n if (!hasKey) {\n const { jwk, did: generatedSessionDid } = await withSpinner(\"Generating session key...\", async () => {\n return generateKey();\n });\n await ProfileManager.setKey(profileName, jwk);\n sessionDid = generatedSessionDid;\n } else if (!sessionDid) {\n sessionDid = keyToDID(hasKey);\n }\n\n // Sign in using the private key\n const sessionResult = await withSpinner(\"Signing in...\", async () => {\n return localKeySignIn({ privateKey, host });\n });\n\n // Store session data\n await ProfileManager.setSession(profileName, {\n authMethod: \"local\",\n address,\n chainId: DEFAULT_CHAIN_ID,\n spaceId: sessionResult.spaceId,\n delegationHeader: sessionResult.delegationHeader,\n delegationCid: sessionResult.delegationCid,\n jwk: sessionResult.jwk,\n verificationMethod: sessionResult.verificationMethod,\n siwe: sessionResult.siwe,\n signature: sessionResult.signature,\n });\n sessionDid = sessionResult.verificationMethod;\n\n // Update profile\n await ProfileManager.setProfile(profileName, {\n ...profile,\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n sessionDid,\n ownerDid: did,\n spaceId: sessionResult.spaceId,\n createdAt: profile?.createdAt ?? new Date().toISOString(),\n posture: profile?.posture ?? \"local-owner-key\",\n operatorType: profile?.operatorType ?? \"human\",\n authMethod: \"local\",\n privateKey,\n address,\n });\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did,\n sessionDid,\n address,\n spaceId: sessionResult.spaceId,\n authMethod: \"local\",\n });\n}\n\n/**\n * Handle OpenKey (browser-based) authentication.\n * This is the original auth flow.\n */\nasync function handleOpenKeyAuth(profileName: string, host: string, paste?: boolean): Promise<void> {\n const key = await ProfileManager.getKey(profileName);\n if (!key) {\n throw new CLIError(\n \"NO_KEY\",\n `No key found for profile \"${profileName}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n // Get DID from profile\n const profile = await ProfileManager.getProfile(profileName);\n\n // Start browser auth flow\n const delegationData = await startAuthFlow(profile.did, {\n paste,\n jwk: key,\n host,\n openkeyHost: resolveOpenKeyHost(profile),\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with owner DID if present\n const updatedProfile = {\n ...profile,\n sessionDid: profile.sessionDid ?? profile.did,\n posture: profile.posture ?? \"owner-openkey\",\n operatorType: profile.operatorType ?? \"human\",\n authMethod: \"openkey\" as const,\n };\n\n if (delegationData.spaceId) {\n updatedProfile.spaceId = delegationData.spaceId;\n updatedProfile.ownerDid = delegationData.ownerDid as string | undefined;\n }\n\n await ProfileManager.setProfile(profileName, updatedProfile);\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did: profile.did,\n spaceId: delegationData.spaceId,\n authMethod: \"openkey\",\n });\n}\n","export interface GlobalConfig {\n defaultProfile: string;\n version: number;\n}\n\nexport type AuthMethod = \"openkey\" | \"local\";\n\nexport const CLI_PROFILE_POSTURES = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n] as const;\n\nexport type CLIProfilePosture = typeof CLI_PROFILE_POSTURES[number];\n\nexport const CLI_OPERATOR_TYPES = [\"human\", \"agent\"] as const;\n\nexport type CLIOperatorType = typeof CLI_OPERATOR_TYPES[number];\n\nexport function isCLIProfilePosture(value: unknown): value is CLIProfilePosture {\n return typeof value === \"string\" && CLI_PROFILE_POSTURES.includes(value as CLIProfilePosture);\n}\n\nexport function isCLIOperatorType(value: unknown): value is CLIOperatorType {\n return typeof value === \"string\" && CLI_OPERATOR_TYPES.includes(value as CLIOperatorType);\n}\n\nexport function resolveProfilePosture(profile: {\n posture?: unknown;\n authMethod?: AuthMethod;\n}): CLIProfilePosture {\n if (isCLIProfilePosture(profile.posture)) return profile.posture;\n if (profile.authMethod === \"local\") return \"local-owner-key\";\n return \"owner-openkey\";\n}\n\nexport function resolveProfileOperatorType(profile: {\n operatorType?: unknown;\n}): CLIOperatorType {\n if (isCLIOperatorType(profile.operatorType)) return profile.operatorType;\n return \"human\";\n}\n\nexport interface ProfileConfig {\n name: string;\n host: string;\n chainId: number;\n spaceName: string;\n did: string;\n sessionDid?: string;\n ownerDid?: string;\n spaceId?: string;\n createdAt: string;\n posture?: CLIProfilePosture;\n operatorType?: CLIOperatorType;\n authMethod?: AuthMethod;\n /** Hex-encoded Ethereum private key (only present when authMethod is \"local\") */\n privateKey?: string;\n /** Ethereum address derived from privateKey (only present when authMethod is \"local\") */\n address?: string;\n /**\n * Optional OpenKey host override. Used for testing accounts or running\n * against a self-hosted OpenKey (e.g. https://openkey.localhost). Falls\n * back to DEFAULT_OPENKEY_HOST when unset. Edit profile.json directly\n * to change.\n */\n openkeyHost?: string;\n}\n\nexport interface CLIContext {\n profile: string;\n host: string;\n verbose: boolean;\n noCache: boolean;\n quiet: boolean;\n}\n","import { TinyCloudNode } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport type { CLIContext } from \"../config/types.js\";\nimport { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { replayAdditionalDelegations } from \"./permissions.js\";\n\n/**\n * Create a TinyCloudNode instance from the current CLI context.\n * Uses the profile's persisted session and key.\n *\n * Supports both auth methods:\n * - \"local\": Uses the stored Ethereum private key directly\n * - \"openkey\": Restores session from stored delegation data (browser auth flow)\n */\nexport async function createSDKInstance(\n ctx: CLIContext,\n options?: { privateKey?: string }\n): Promise<TinyCloudNode> {\n const profile = await ProfileManager.getProfile(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile) as Record<string, unknown> | null;\n const key = await ProfileManager.getKey(ctx.profile);\n\n // For local auth, use the stored private key\n const effectivePrivateKey = options?.privateKey ?? profile.privateKey;\n\n if (!key && !effectivePrivateKey) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n `No key found for profile \"${ctx.profile}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n if (profile.authMethod === \"local\" && effectivePrivateKey) {\n // Local key auth: prefer the persisted TinyCloud session so the CLI\n // keeps the same session key DID across request/grant/import flows.\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: effectivePrivateKey,\n });\n\n if (session && session.delegationHeader && session.delegationCid && session.spaceId) {\n await node.restoreSession({\n delegationHeader: session.delegationHeader as { Authorization: string },\n delegationCid: session.delegationCid as string,\n spaceId: session.spaceId as string,\n jwk: (session.jwk as object) ?? key,\n verificationMethod: (session.verificationMethod as string) ?? profile.sessionDid ?? profile.did,\n address: session.address as string | undefined,\n chainId: session.chainId as number | undefined,\n siwe: session.siwe as string | undefined,\n signature: session.signature as string | undefined,\n });\n } else {\n await node.signIn();\n }\n await replayAdditionalDelegations(node, ctx.profile);\n return node;\n }\n\n // OpenKey / delegation-based auth\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: options?.privateKey,\n });\n\n if (options?.privateKey) {\n // Sign in with private key (existing behavior)\n await node.signIn();\n } else if (session && session.delegationHeader && session.delegationCid && session.spaceId) {\n // Restore session from stored delegation data (browser auth flow)\n await node.restoreSession({\n delegationHeader: session.delegationHeader as { Authorization: string },\n delegationCid: session.delegationCid as string,\n spaceId: session.spaceId as string,\n jwk: (session.jwk as object) ?? key,\n verificationMethod: (session.verificationMethod as string) ?? profile.did,\n address: session.address as string | undefined,\n chainId: session.chainId as number | undefined,\n siwe: session.siwe as string | undefined,\n signature: session.signature as string | undefined,\n });\n }\n\n await replayAdditionalDelegations(node, ctx.profile);\n return node;\n}\n\n/**\n * Ensure the user is authenticated.\n * Throws AUTH_REQUIRED if no session exists.\n */\nexport async function ensureAuthenticated(\n ctx: CLIContext,\n options?: { privateKey?: string }\n): Promise<TinyCloudNode> {\n const profile = await ProfileManager.getProfile(ctx.profile).catch(() => null);\n\n // For local auth, we can sign in directly without a stored session\n if (profile?.authMethod === \"local\" && profile.privateKey) {\n return createSDKInstance(ctx, { privateKey: profile.privateKey });\n }\n\n const session = await ProfileManager.getSession(ctx.profile);\n\n if (!session) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n `Not authenticated. Run \\`tc auth login\\` or \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n return createSDKInstance(ctx, options);\n}\n","import { randomBytes } from \"node:crypto\";\nimport { appendFile, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n expandActionShortNames,\n isCapabilitySubset,\n resolveManifest,\n type PermissionEntry,\n type PortableDelegation,\n type TinyCloudNode,\n} from \"@tinycloud/node-sdk\";\nimport { PROFILES_DIR } from \"../config/constants.js\";\nimport { fileExists, readJson, writeJson, ensureDir } from \"../config/storage.js\";\nimport { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { resolveSpaceUri } from \"./space.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type CLIOperatorType,\n type CLIProfilePosture,\n type ProfileConfig,\n} from \"../config/types.js\";\n\n/**\n * Stored shape for a runtime delegation appended to a profile.\n * `permissions` mirrors the request that produced this delegation so\n * `tc auth caps` can surface the originally-asked-for entries even after\n * the delegation has been baked into a recap.\n */\nexport interface StoredAdditionalDelegation {\n delegation: PortableDelegation;\n permissions: PermissionEntry[];\n}\n\nexport interface GrantHistoryEntry {\n ts: string;\n profile: string;\n addedCaps: PermissionEntry[];\n source: \"cli\" | \"401-hint\" | \"manifest\";\n delegationCid?: string;\n expiry?: string;\n}\n\nexport interface PermissionRequestArtifact {\n kind: \"tinycloud.auth.request\";\n version: 1;\n requestId: string;\n createdAt: string;\n profile: string;\n posture: CLIProfilePosture;\n operatorType: CLIOperatorType;\n host: string;\n sessionDid: string;\n ownerDid?: string;\n spaceId?: string;\n requestedExpiry?: string | number;\n requested: PermissionEntry[];\n command?: {\n argv: string[];\n cwd: string;\n };\n}\n\nexport interface DelegationImportArtifact {\n kind: \"tinycloud.auth.delegation\";\n version: 1;\n requestId?: string;\n delegation: PortableDelegation;\n permissions?: PermissionEntry[];\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n // Sibling file keeps legacy session.json schema unchanged for existing readers.\n return join(PROFILES_DIR, profile, \"additional-delegations.json\");\n}\n\nexport function permissionRequestsPath(profile: string): string {\n return join(PROFILES_DIR, profile, \"auth-requests.json\");\n}\n\nexport function grantHistoryPath(profile: string): string {\n return join(PROFILES_DIR, profile, \"auth-grants.jsonl\");\n}\n\nexport function createPermissionRequestArtifact(params: {\n profileName: string;\n profile: ProfileConfig;\n host: string;\n requested: PermissionEntry[];\n requestedExpiry?: string | number;\n argv?: string[];\n cwd?: string;\n}): PermissionRequestArtifact {\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: `req_${Date.now().toString(36)}_${randomBytes(4).toString(\"hex\")}`,\n createdAt: new Date().toISOString(),\n profile: params.profileName,\n posture: resolveProfilePosture(params.profile),\n operatorType: resolveProfileOperatorType(params.profile),\n host: params.host,\n sessionDid: didWithoutFragment(params.profile.sessionDid ?? params.profile.did),\n ownerDid: params.profile.ownerDid,\n spaceId: params.profile.spaceId,\n requestedExpiry: params.requestedExpiry,\n requested: params.requested,\n command: {\n argv: params.argv ?? process.argv.slice(2),\n cwd: params.cwd ?? process.cwd(),\n },\n };\n}\n\nfunction didWithoutFragment(did: string): string {\n const fragment = did.indexOf(\"#\");\n return fragment === -1 ? did : did.slice(0, fragment);\n}\n\nexport async function loadAdditionalDelegations(\n profile: string,\n): Promise<StoredAdditionalDelegation[]> {\n const raw = await readJson<StoredAdditionalDelegation[]>(\n additionalDelegationsPath(profile),\n );\n return Array.isArray(raw) ? raw : [];\n}\n\nexport async function saveAdditionalDelegations(\n profile: string,\n entries: StoredAdditionalDelegation[],\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n await writeJson(additionalDelegationsPath(profile), entries);\n}\n\nexport async function appendAdditionalDelegation(\n profile: string,\n entry: StoredAdditionalDelegation,\n): Promise<void> {\n const existing = await loadAdditionalDelegations(profile);\n const next = existing.filter((item) => item.delegation.cid !== entry.delegation.cid);\n next.push(entry);\n await saveAdditionalDelegations(profile, next);\n}\n\nexport async function loadPermissionRequestArtifacts(\n profile: string,\n): Promise<PermissionRequestArtifact[]> {\n const raw = await readJson<PermissionRequestArtifact[]>(\n permissionRequestsPath(profile),\n );\n return Array.isArray(raw) ? raw.filter(isPermissionRequestArtifact) : [];\n}\n\nexport async function savePermissionRequestArtifacts(\n profile: string,\n entries: PermissionRequestArtifact[],\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n await writeJson(permissionRequestsPath(profile), entries);\n}\n\nexport async function appendPermissionRequestArtifact(\n profile: string,\n artifact: PermissionRequestArtifact,\n): Promise<void> {\n const existing = await loadPermissionRequestArtifacts(profile);\n const next = existing.filter((item) => item.requestId !== artifact.requestId);\n next.push(artifact);\n await savePermissionRequestArtifacts(profile, next);\n}\n\nexport async function getPermissionRequestArtifact(\n profile: string,\n requestId: string,\n): Promise<PermissionRequestArtifact | null> {\n const existing = await loadPermissionRequestArtifacts(profile);\n return existing.find((item) => item.requestId === requestId) ?? null;\n}\n\nexport async function getLastPermissionRequestArtifact(\n profile: string,\n): Promise<PermissionRequestArtifact | null> {\n const existing = await loadPermissionRequestArtifacts(profile);\n return existing.at(-1) ?? null;\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<PermissionRequestArtifact>;\n return (\n candidate.kind === \"tinycloud.auth.request\" &&\n candidate.version === 1 &&\n typeof candidate.requestId === \"string\" &&\n Array.isArray(candidate.requested)\n );\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<DelegationImportArtifact>;\n return (\n candidate.kind === \"tinycloud.auth.delegation\" &&\n candidate.version === 1 &&\n candidate.delegation !== undefined &&\n typeof candidate.delegation === \"object\"\n );\n}\n\nexport async function replayAdditionalDelegations(\n node: TinyCloudNode,\n profile: string,\n): Promise<void> {\n const entries = await loadAdditionalDelegations(profile);\n for (const entry of entries) {\n // Skip expired delegations rather than letting useRuntimeDelegation throw.\n const expiry = entry.delegation.expiry instanceof Date\n ? entry.delegation.expiry\n : new Date(entry.delegation.expiry as unknown as string);\n if (expiry.getTime() <= Date.now()) continue;\n try {\n await node.useRuntimeDelegation({ ...entry.delegation, expiry });\n } catch (err) {\n // A stored delegation can be invalid for several benign reasons (host\n // unreachable, key rotated). Don't fail the whole CLI invocation —\n // the user can re-run `tc auth request` to refresh the grant.\n if (process.env.TC_DEBUG_REPLAY === \"1\") {\n process.stderr.write(`[replay] skipping ${entry.delegation.cid}: ${(err as Error).message}\\n`);\n }\n }\n }\n}\n\n/**\n * Helper for `tc auth request` to construct the persisted record that\n * follows the runtime grant. Keeps the \"PortableDelegation + originating\n * permissions\" pair together so future `tc auth caps` output can show the\n * caller-friendly entries we agreed to grant.\n */\nexport function storedAdditionalDelegation(\n delegation: PortableDelegation,\n permissions: PermissionEntry[],\n): StoredAdditionalDelegation {\n return { delegation, permissions };\n}\n\nexport async function appendGrantHistory(\n profile: string,\n entry: Omit<GrantHistoryEntry, \"ts\" | \"profile\">,\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n const line = JSON.stringify({\n ts: new Date().toISOString(),\n profile,\n ...entry,\n }) + \"\\n\";\n await appendFile(grantHistoryPath(profile), line, \"utf8\");\n}\n\nexport async function readGrantHistory(\n profile: string,\n): Promise<GrantHistoryEntry[]> {\n const path = grantHistoryPath(profile);\n if (!(await fileExists(path))) return [];\n const raw = await readFile(path, \"utf8\");\n return raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => JSON.parse(line) as GrantHistoryEntry);\n}\n\nexport async function parseCapSpec(\n spec: string,\n profile: string,\n): Promise<PermissionEntry> {\n const firstColon = spec.indexOf(\":\");\n const lastColon = spec.lastIndexOf(\":\");\n if (firstColon <= 0 || lastColon <= firstColon) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Invalid --cap \"${spec}\". Expected tinycloud.<service>:<space>:<path>:<actions-csv>.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const service = normalizeService(spec.slice(0, firstColon));\n const actionsCsv = spec.slice(lastColon + 1);\n const spaceAndPath = spec.slice(firstColon + 1, lastColon);\n const { space, path } = splitSpaceAndPath(spaceAndPath);\n const resolvedSpace = await resolveSpaceUri(space, profile) ?? space;\n const actions = expandActionShortNames(\n service,\n actionsCsv.split(\",\").map((action) => action.trim()).filter(Boolean),\n );\n\n if (actions.length === 0) {\n throw new CLIError(\"INVALID_CAP\", `Capability \"${spec}\" has no actions.`, ExitCode.USAGE_ERROR);\n }\n\n return { service, space: resolvedSpace, path, actions };\n}\n\nexport async function loadPermissionRequest(\n source: string,\n profile: string,\n): Promise<PermissionEntry[]> {\n const raw = JSON.parse(await readFile(source, \"utf8\")) as { permissions?: PermissionEntry[] };\n if (!Array.isArray(raw.permissions)) {\n throw new CLIError(\n \"INVALID_PERMISSION_REQUEST\",\n `Permission request ${source} must contain { \"permissions\": [...] }.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return resolvePermissionSpaces(raw.permissions, profile);\n}\n\nexport async function loadManifestPermissions(\n source: string,\n profile: string,\n): Promise<PermissionEntry[]> {\n const raw = await loadManifestText(source);\n const manifest = JSON.parse(raw) as Record<string, unknown>;\n\n if (typeof manifest.id === \"string\") {\n const resolved = resolveManifest(manifest as Parameters<typeof resolveManifest>[0]);\n return resolvePermissionSpaces(resolved.resources, profile);\n }\n\n if (typeof manifest.app_id === \"string\") {\n const permissions = ((manifest.permissions as unknown[]) ?? [])\n .filter((entry): entry is Record<string, unknown> => entry !== null && typeof entry === \"object\")\n .map((entry) => {\n const service = normalizeService(String(entry.service ?? \"\"));\n const path = String(entry.path ?? \"\");\n const skipPrefix = entry.skipPrefix === true;\n const resolvedPath = skipPrefix\n ? path\n : prefixAppManifestPath(path, manifest.app_id as string);\n return {\n service,\n space: String(manifest.space ?? \"applications\"),\n path: resolvedPath,\n actions: expandActionShortNames(\n service,\n Array.isArray(entry.actions)\n ? entry.actions.map(String)\n : [],\n ),\n };\n });\n return resolvePermissionSpaces(permissions, profile);\n }\n\n throw new CLIError(\n \"INVALID_MANIFEST\",\n \"Manifest must contain either SDK field \\\"id\\\" or app manifest field \\\"app_id\\\".\",\n ExitCode.USAGE_ERROR,\n );\n}\n\nexport function diffPermissions(\n requested: PermissionEntry[],\n granted: PermissionEntry[],\n): PermissionEntry[] {\n return isCapabilitySubset(requested, granted).missing;\n}\n\nexport function permissionsFromDelegation(\n delegation: PortableDelegation,\n): PermissionEntry[] {\n if (delegation.resources?.length) {\n return delegation.resources.map((resource) => ({\n service: resource.service.startsWith(\"tinycloud.\")\n ? resource.service\n : `tinycloud.${resource.service}`,\n space: resource.space,\n path: resource.path,\n actions: [...resource.actions],\n }));\n }\n return [{\n service: serviceFromActions(delegation.actions),\n space: delegation.spaceId,\n path: delegation.path,\n actions: [...delegation.actions],\n }];\n}\n\nexport function compactPermission(permission: PermissionEntry): string {\n const service = permission.service;\n const space = permission.space.startsWith(\"tinycloud:\")\n ? permission.space.slice(permission.space.lastIndexOf(\":\") + 1)\n : permission.space;\n const actions = permission.actions\n .map((action) => action.startsWith(`${service}/`) ? action.slice(service.length + 1) : action)\n .join(\",\");\n return `${service}:${space}:${permission.path}:${actions}`;\n}\n\nasync function resolvePermissionSpaces(\n entries: PermissionEntry[],\n profile: string,\n): Promise<PermissionEntry[]> {\n const resolved: PermissionEntry[] = [];\n for (const entry of entries) {\n const service = normalizeService(entry.service);\n resolved.push({\n ...entry,\n service,\n space: await resolveSpaceUri(entry.space, profile) ?? entry.space,\n actions: expandActionShortNames(service, entry.actions),\n });\n }\n return resolved;\n}\n\nasync function loadManifestText(source: string): Promise<string> {\n if (source.startsWith(\"base64:\")) {\n return Buffer.from(source.slice(\"base64:\".length), \"base64\").toString(\"utf8\");\n }\n if (await fileExists(source)) {\n return readFile(source, \"utf8\");\n }\n try {\n const decoded = Buffer.from(source, \"base64\").toString(\"utf8\");\n JSON.parse(decoded);\n return decoded;\n } catch {\n return readFile(source, \"utf8\");\n }\n}\n\nfunction normalizeService(service: string): string {\n if (!service) {\n throw new CLIError(\"INVALID_CAP\", \"Capability service is required.\", ExitCode.USAGE_ERROR);\n }\n return service.startsWith(\"tinycloud.\") ? service : `tinycloud.${service}`;\n}\n\nfunction splitSpaceAndPath(input: string): { space: string; path: string } {\n if (input.startsWith(\"tinycloud:\")) {\n const parts = input.split(\":\");\n if (parts.length < 7) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Full tinycloud space specs must include a path after the space URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return {\n space: parts.slice(0, 6).join(\":\"),\n path: parts.slice(6).join(\":\"),\n };\n }\n\n const colon = input.indexOf(\":\");\n if (colon <= 0) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Capability must include both space and path.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return {\n space: input.slice(0, colon),\n path: input.slice(colon + 1),\n };\n}\n\nfunction prefixAppManifestPath(path: string, appId: string): string {\n const slash = path.indexOf(\"/\");\n if (slash === -1) return `${appId}/${path}`;\n return `${path.slice(0, slash)}/${appId}/${path.slice(slash + 1)}`;\n}\n\nfunction serviceFromActions(actions: string[]): string {\n const first = actions[0] ?? \"tinycloud.unknown/read\";\n return first.includes(\"/\") ? first.slice(0, first.indexOf(\"/\")) : \"tinycloud.unknown\";\n}\n","import { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport type { ProfileConfig } from \"../config/types.js\";\nimport {\n buildSpaceUri,\n canonicalizeAddress,\n makePkhSpaceId,\n parsePkhDid,\n parseSpaceUri,\n} from \"@tinycloud/node-sdk\";\n\n/**\n * Resolve the active profile's Ethereum address. Source priority matches\n * what TinyCloudNode.signIn / restoreSession actually populates:\n * 1) session.address (set by both local-key and OpenKey auth flows)\n * 2) profile.address (local-key auth only)\n * 3) the address segment of profile.ownerDid (did:pkh:eip155:<chain>:<addr>)\n */\nfunction resolveAddress(profile: ProfileConfig, session: Record<string, unknown> | null): string {\n const sessAddr = session?.address;\n if (typeof sessAddr === \"string\" && sessAddr.length > 0) {\n return canonicalizeAddress(sessAddr);\n }\n\n if (profile.address) return canonicalizeAddress(profile.address);\n\n if (profile.ownerDid) {\n const pkh = parsePkhDid(profile.ownerDid);\n if (pkh) return pkh.address;\n }\n\n throw new CLIError(\n \"ADDRESS_UNKNOWN\",\n `Cannot determine Ethereum address for profile \"${profile.name}\". Run \\`tc auth login\\` to refresh the session.`,\n ExitCode.AUTH_REQUIRED,\n );\n}\n\nfunction resolveChainId(profile: ProfileConfig, session: Record<string, unknown> | null): number {\n const sessChain = session?.chainId;\n if (typeof sessChain === \"number\" && Number.isFinite(sessChain)) return sessChain;\n return profile.chainId;\n}\n\n/**\n * Resolve a --space CLI argument into a full TinyCloud space URI.\n *\n * - undefined → undefined (caller falls back to node.spaceId)\n * - \"tinycloud:...\" → returned verbatim\n * - bare name → tinycloud:pkh:eip155:<chain>:<address>:<name>\n */\nexport async function resolveSpaceUri(\n input: string | undefined,\n profileName: string,\n): Promise<string | undefined> {\n if (!input) return undefined;\n if (input.startsWith(\"tinycloud:\")) {\n const parsed = parseSpaceUri(input);\n if (!parsed) {\n throw new CLIError(\n \"INVALID_SPACE\",\n `Invalid --space \"${input}\". Use a short name ([A-Za-z0-9_-]) or a full tinycloud:... URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return buildSpaceUri(parsed.owner, parsed.name);\n }\n\n if (!/^[A-Za-z0-9_-]+$/.test(input)) {\n throw new CLIError(\n \"INVALID_SPACE\",\n `Invalid --space \"${input}\". Use a short name ([A-Za-z0-9_-]) or a full tinycloud:... URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const profile = await ProfileManager.getProfile(profileName);\n const session = (await ProfileManager.getSession(profileName)) as Record<string, unknown> | null;\n\n const address = resolveAddress(profile, session);\n const chainId = resolveChainId(profile, session);\n return makePkhSpaceId(address, chainId, input);\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes, formatTimeAgo } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\nexport function registerKvCommand(program: Command): void {\n const kv = program.command(\"kv\").description(\"Key-value store operations\");\n\n // tc kv get <key>\n kv\n .command(\"get <key>\")\n .description(\"Get a value by key\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Getting ${key}...`, () => node.kv.get(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Key \"${key}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data;\n const metadata = result.data.headers ?? {};\n\n if (options.output) {\n // Write to file\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n await writeFile(options.output, content);\n outputJson({ key, written: options.output });\n return;\n }\n\n if (options.raw) {\n // Raw output - write directly to stdout\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content);\n return;\n }\n\n // Output value\n if (shouldOutputJson()) {\n outputJson({\n key,\n data,\n metadata,\n });\n } else {\n // Just output the raw value for get - useful for piping\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv put <key> [value]\n kv\n .command(\"put <key> [value]\")\n .description(\"Set a value\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .action(async (key: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n // Determine value source\n let putValue: string | Buffer;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n putValue = await readFile(options.file);\n } else if (options.stdin) {\n putValue = await readStdin();\n } else {\n // Try to parse as JSON, fall back to string\n try {\n putValue = JSON.parse(value!);\n } catch {\n putValue = value!;\n }\n }\n\n const result = await withSpinner(`Writing ${key}...`, () => node.kv.put(key, putValue)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv delete <key>\n kv\n .command(\"delete <key>\")\n .description(\"Delete a key\")\n .action(async (key: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Deleting ${key}...`, () => node.kv.delete(key)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv list\n kv\n .command(\"list\")\n .description(\"List keys\")\n .option(\"--prefix <prefix>\", \"Filter by key prefix\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing keys...\", () => node.kv.list(listOptions)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const rawData = result.data.data ?? result.data;\n const keyList = Array.isArray(rawData) ? rawData : (rawData?.keys ?? []);\n\n if (shouldOutputJson()) {\n outputJson({\n keys: keyList,\n count: keyList.length,\n prefix: options.prefix ?? null,\n });\n } else {\n if (keyList.length === 0) {\n process.stdout.write(theme.muted(\"No keys found.\") + \"\\n\");\n } else {\n const rows = keyList.map((e: any) => [\n e.key || e,\n e.contentLength ? formatBytes(e.contentLength) : \"—\",\n e.updatedAt ? formatTimeAgo(e.updatedAt) : \"—\",\n ]);\n process.stdout.write(formatTable([\"Key\", \"Size\", \"Updated\"], rows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv head <key>\n kv\n .command(\"head <key>\")\n .description(\"Get metadata for a key (no body)\")\n .action(async (key: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Checking ${key}...`, () => node.kv.head(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n outputJson({ key, exists: false, metadata: {} });\n return;\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n key,\n exists: true,\n metadata: result.data.headers ?? {},\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatTable } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerSpaceCommand(program: Command): void {\n const space = program.command(\"space\").description(\"Space management\");\n\n space\n .command(\"list\")\n .description(\"List spaces\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.spaces.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n if (shouldOutputJson()) {\n outputJson({ spaces: result.data, count: result.data.length });\n } else {\n if (result.data.length === 0) {\n process.stdout.write(theme.muted(\"No spaces found.\") + \"\\n\");\n } else {\n const rows = result.data.map((s: any) => [\n s.id || s.spaceId || \"—\",\n s.name || \"—\",\n s.owner || \"—\",\n ]);\n process.stdout.write(formatTable([\"Space ID\", \"Name\", \"Owner\"], rows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"create <name>\")\n .description(\"Create a new space\")\n .action(async (name: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.spaces.create(name);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n outputJson({ spaceId: result.data.id, name });\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"info [space-id]\")\n .description(\"Get space info\")\n .action(async (spaceId: string | undefined, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const targetId = spaceId ?? node.spaceId;\n if (!targetId) {\n throw new CLIError(\"NO_SPACE\", \"No space ID specified and no active space\", ExitCode.ERROR);\n }\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n outputJson({\n spaceId: targetId,\n name: profile.spaceName,\n owner: node.did,\n host: ctx.host,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"switch <name>\")\n .description(\"Switch active space\")\n .action(async (name: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n await ProfileManager.setProfile(ctx.profile, { ...profile, spaceName: name });\n\n outputJson({ profile: ctx.profile, spaceName: name, switched: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","/**\n * Parse a duration string into milliseconds.\n * Supports: \"1h\", \"30m\", \"7d\", \"1w\", or ISO date string.\n */\nexport function parseDuration(input: string): number {\n const match = input.match(/^(\\d+)(m|h|d|w)$/);\n if (match) {\n const value = parseInt(match[1], 10);\n const unit = match[2];\n const multipliers: Record<string, number> = {\n m: 60 * 1000,\n h: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n w: 7 * 24 * 60 * 60 * 1000,\n };\n return value * multipliers[unit];\n }\n\n // Try as ISO date\n const date = new Date(input);\n if (!isNaN(date.getTime())) {\n const ms = date.getTime() - Date.now();\n if (ms <= 0) {\n throw new Error(`Expiry date \"${input}\" is in the past`);\n }\n return ms;\n }\n\n throw new Error(`Invalid duration: \"${input}\". Use format like \"1h\", \"7d\", or an ISO date.`);\n}\n\n/**\n * Parse duration to an expiry Date.\n */\nexport function parseExpiry(input: string): Date {\n return new Date(Date.now() + parseDuration(input));\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { parseExpiry } from \"../lib/duration.js\";\nimport { principalDidEquals } from \"@tinycloud/node-sdk\";\n\nfunction didMatches(actual: string | undefined, expected: string): boolean {\n if (!actual) return false;\n try {\n return principalDidEquals(actual, expected);\n } catch {\n return actual === expected;\n }\n}\n\nexport function registerDelegationCommand(program: Command): void {\n const delegation = program.command(\"delegation\").description(\"Manage delegations\");\n\n delegation\n .command(\"create\")\n .description(\"Create a delegation\")\n .requiredOption(\"--to <did>\", \"Recipient DID\")\n .requiredOption(\"--path <path>\", \"KV path scope\")\n .requiredOption(\"--actions <actions>\", \"Comma-separated actions (e.g., kv/get,kv/list)\")\n .option(\"--expiry <duration>\", \"Expiry duration (e.g., 1h, 7d, ISO date)\", \"1h\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const actions = options.actions.split(\",\").map((a: string) => {\n const trimmed = a.trim();\n return trimmed.startsWith(\"tinycloud.\") ? trimmed : `tinycloud.${trimmed}`;\n });\n\n const expiry = parseExpiry(options.expiry);\n\n const result = await node.delegationManager.create({\n delegateDID: options.to,\n path: options.path,\n actions,\n expiry,\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n cid: result.data.cid,\n delegateDid: options.to,\n path: options.path,\n actions,\n expiry: expiry.toISOString(),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"list\")\n .description(\"List delegations\")\n .option(\"--granted\", \"Show only delegations I've granted\")\n .option(\"--received\", \"Show only delegations I've received\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n let delegations: any[] = result.data;\n\n // Filter if requested\n if (options.granted) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => didMatches(d.delegatorDID, myDid));\n } else if (options.received) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => didMatches(d.delegateDID, myDid));\n }\n\n outputJson({\n delegations: delegations.map((d: any) => ({\n cid: d.cid,\n delegatee: d.delegateDID,\n delegator: d.delegatorDID,\n path: d.path,\n actions: d.actions,\n expiry: d.expiry instanceof Date ? d.expiry.toISOString() : d.expiry,\n })),\n count: delegations.length,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"info <cid>\")\n .description(\"Get delegation details\")\n .action(async (cid: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.get(cid);\n if (!result.ok) {\n throw new CLIError(\"NOT_FOUND\", `Delegation \"${cid}\" not found`, ExitCode.NOT_FOUND);\n }\n\n outputJson(result.data);\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"revoke <cid>\")\n .description(\"Revoke a delegation\")\n .action(async (cid: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.revoke(cid);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ cid, revoked: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { parseExpiry } from \"../lib/duration.js\";\n\nexport function registerShareCommand(program: Command): void {\n const share = program.command(\"share\").description(\"Share data with others\");\n\n share\n .command(\"create\")\n .description(\"Create a share link\")\n .requiredOption(\"--path <path>\", \"KV path scope\")\n .option(\"--actions <actions>\", \"Comma-separated actions\", \"kv/get\")\n .option(\"--expiry <duration>\", \"Expiry duration\", \"7d\")\n .option(\"--web-link\", \"Generate a web UI link for non-technical recipients\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const actions = options.actions.split(\",\").map((a: string) => {\n const trimmed = a.trim();\n return trimmed.startsWith(\"tinycloud.\") ? trimmed : `tinycloud.${trimmed}`;\n });\n\n const expiry = parseExpiry(options.expiry);\n\n const result = await node.sharing.generate({\n path: options.path,\n actions,\n expiry,\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const output: Record<string, unknown> = {\n token: result.data.token ?? result.data.cid,\n shareData: result.data.encodedData ?? result.data.url,\n path: options.path,\n actions,\n expiry: expiry.toISOString(),\n };\n\n if (options.webLink) {\n const shareData = result.data.encodedData ?? result.data.url ?? \"\";\n output.webLink = `https://openkey.cloud/share?data=${encodeURIComponent(shareData)}`;\n }\n\n outputJson(output);\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"receive [data]\")\n .description(\"Receive a share\")\n .option(\"--stdin\", \"Read share data from stdin\")\n .action(async (data: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n let shareData: string;\n if (options.stdin) {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n shareData = Buffer.concat(chunks).toString(\"utf-8\").trim();\n } else if (data) {\n shareData = data;\n } else {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide share data or use --stdin\", ExitCode.USAGE_ERROR);\n }\n\n const result = await node.sharing.receive(shareData);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n received: true,\n spaceId: result.data.spaceId,\n path: result.data.path,\n actions: result.data.actions,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"list\")\n .description(\"List active shares\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.sharing.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ shares: result.data, count: result.data.length });\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"revoke <token>\")\n .description(\"Revoke a share\")\n .action(async (token: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.sharing.revoke(token);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ token, revoked: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\n\nexport function registerNodeCommand(program: Command): void {\n const node = program.command(\"node\").description(\"Node health and info\");\n\n node\n .command(\"health\")\n .description(\"Check node health\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const start = Date.now();\n const response = await fetch(`${ctx.host}/healthz`);\n const latencyMs = Date.now() - start;\n\n outputJson({\n healthy: response.ok,\n host: ctx.host,\n latencyMs,\n });\n } catch (error) {\n if (error instanceof TypeError && (error as Error).message.includes(\"fetch\")) {\n outputJson({ healthy: false, host: (await ProfileManager.resolveContext(cmd.optsWithGlobals())).host, error: \"Connection refused\" });\n } else {\n handleError(error);\n }\n }\n });\n\n node\n .command(\"version\")\n .description(\"Get node version\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const response = await fetch(`${ctx.host}/info`);\n if (!response.ok) {\n throw new CLIError(\"NODE_ERROR\", `Node returned ${response.status}`, ExitCode.NODE_ERROR);\n }\n\n const data = await response.json() as Record<string, unknown>;\n outputJson({ ...data, host: ctx.host });\n } catch (error) {\n handleError(error);\n }\n });\n\n node\n .command(\"status\")\n .description(\"Combined health and version info\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const start = Date.now();\n\n // Fetch health and version in parallel\n const [healthRes, versionRes] = await Promise.allSettled([\n fetch(`${ctx.host}/healthz`),\n fetch(`${ctx.host}/info`),\n ]);\n\n const latencyMs = Date.now() - start;\n const healthy = healthRes.status === \"fulfilled\" && healthRes.value.ok;\n\n let versionData: Record<string, unknown> = {};\n if (versionRes.status === \"fulfilled\" && versionRes.value.ok) {\n versionData = await versionRes.value.json() as Record<string, unknown>;\n }\n\n outputJson({\n healthy,\n host: ctx.host,\n latencyMs,\n ...versionData,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, isInteractive, shouldOutputJson, formatField } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { generateKey } from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\nimport {\n CLI_OPERATOR_TYPES,\n CLI_PROFILE_POSTURES,\n isCLIOperatorType,\n isCLIProfilePosture,\n resolveProfileOperatorType,\n resolveProfilePosture,\n type CLIOperatorType,\n type CLIProfilePosture,\n} from \"../config/types.js\";\n\nexport function registerProfileCommand(program: Command): void {\n const profile = program.command(\"profile\").description(\"Profile management\");\n\n profile\n .command(\"list\")\n .description(\"List all profiles\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const config = await ProfileManager.getConfig();\n const names = await ProfileManager.listProfiles();\n\n const profiles = await Promise.all(\n names.map(async (name) => {\n try {\n const p = await ProfileManager.getProfile(name);\n return {\n name: p.name,\n host: p.host,\n did: p.did,\n posture: resolveProfilePosture(p),\n operatorType: resolveProfileOperatorType(p),\n active: name === config.defaultProfile,\n };\n } catch {\n return {\n name,\n host: null,\n did: null,\n posture: null,\n operatorType: null,\n active: name === config.defaultProfile,\n };\n }\n })\n );\n\n if (shouldOutputJson()) {\n outputJson({\n profiles,\n defaultProfile: config.defaultProfile,\n });\n } else {\n for (const p of profiles) {\n const marker = p.active ? theme.success(\"● \") : \" \";\n const name = p.active ? theme.brand(p.name) : p.name;\n const host = theme.muted(p.host || \"no host\");\n const posture = p.posture ? theme.muted(String(p.posture)) : theme.muted(\"no posture\");\n process.stdout.write(`${marker}${name} ${host} ${posture}\\n`);\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"create <name>\")\n .description(\"Create a new profile\")\n .option(\"--host <url>\", \"TinyCloud node URL\")\n .option(\n \"--posture <posture>\",\n `Profile posture: ${CLI_PROFILE_POSTURES.join(\", \")}. Defaults to owner-openkey.`,\n )\n .option(\n \"--operator <type>\",\n `Operator type: ${CLI_OPERATOR_TYPES.join(\", \")}. Defaults to human.`,\n )\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const host = options.host ?? globalOpts.host ?? \"https://node.tinycloud.xyz\";\n const posture = parseProfilePosture(options.posture);\n const operatorType = parseOperatorType(options.operator);\n\n if (await ProfileManager.profileExists(name)) {\n throw new CLIError(\"PROFILE_EXISTS\", `Profile \"${name}\" already exists`, ExitCode.ERROR);\n }\n\n await ProfileManager.ensureConfigDir();\n const { jwk, did } = generateKey();\n await ProfileManager.setKey(name, jwk);\n await ProfileManager.setProfile(name, {\n name,\n host,\n chainId: 1,\n spaceName: \"default\",\n did,\n sessionDid: did,\n createdAt: new Date().toISOString(),\n posture,\n operatorType,\n });\n\n outputJson({ profile: name, did, host, posture, operatorType, created: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"show [name]\")\n .description(\"Show profile details\")\n .action(async (name: string | undefined, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profileName = name ?? ctx.profile;\n\n const p = await ProfileManager.getProfile(profileName);\n const hasKey = (await ProfileManager.getKey(profileName)) !== null;\n const hasSession = (await ProfileManager.getSession(profileName)) !== null;\n const config = await ProfileManager.getConfig();\n const isDefault = profileName === config.defaultProfile;\n const posture = resolveProfilePosture(p);\n const operatorType = resolveProfileOperatorType(p);\n\n if (shouldOutputJson()) {\n outputJson({\n ...p,\n posture,\n operatorType,\n hasKey,\n hasSession,\n isDefault,\n });\n } else {\n process.stdout.write(`${theme.heading(p.name)}${isDefault ? theme.success(\" (default)\") : \"\"}\\n`);\n process.stdout.write(formatField(\"Host\", p.host) + \"\\n\");\n process.stdout.write(formatField(\"DID\", p.did) + \"\\n\");\n process.stdout.write(formatField(\"Session DID\", p.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\n\");\n process.stdout.write(formatField(\"Space\", p.spaceId || null) + \"\\n\");\n process.stdout.write(formatField(\"Key\", hasKey) + \"\\n\");\n process.stdout.write(formatField(\"Session\", hasSession) + \"\\n\");\n process.stdout.write(formatField(\"Created\", p.createdAt) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"switch <name>\")\n .description(\"Set default profile\")\n .action(async (name: string, _options, cmd) => {\n try {\n if (!(await ProfileManager.profileExists(name))) {\n throw new CLIError(\"PROFILE_NOT_FOUND\", `Profile \"${name}\" does not exist`, ExitCode.NOT_FOUND);\n }\n\n const config = await ProfileManager.getConfig();\n await ProfileManager.setConfig({ ...config, defaultProfile: name });\n\n outputJson({ defaultProfile: name, switched: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"delete <name>\")\n .description(\"Delete a profile\")\n .action(async (name: string, _options, cmd) => {\n try {\n // Confirmation prompt if interactive\n if (isInteractive()) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Delete profile \"${name}\"? This cannot be undone. [y/N] `, resolve);\n });\n rl.close();\n if (answer.toLowerCase() !== \"y\") {\n outputJson({ profile: name, deleted: false, reason: \"Cancelled by user\" });\n return;\n }\n }\n\n await ProfileManager.deleteProfile(name);\n outputJson({ profile: name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nfunction parseProfilePosture(raw: unknown): CLIProfilePosture {\n if (raw === undefined || raw === null || raw === \"\") return \"owner-openkey\";\n if (isCLIProfilePosture(raw)) return raw;\n throw new CLIError(\n \"INVALID_POSTURE\",\n `Invalid posture \"${String(raw)}\". Use one of: ${CLI_PROFILE_POSTURES.join(\", \")}.`,\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction parseOperatorType(raw: unknown): CLIOperatorType {\n if (raw === undefined || raw === null || raw === \"\") return \"human\";\n if (isCLIOperatorType(raw)) return raw;\n throw new CLIError(\n \"INVALID_OPERATOR\",\n `Invalid operator \"${String(raw)}\". Use one of: ${CLI_OPERATOR_TYPES.join(\", \")}.`,\n ExitCode.USAGE_ERROR,\n );\n}\n","import { Command } from \"commander\";\n\nexport function registerCompletionCommand(program: Command): void {\n const completion = program.command(\"completion\").description(\"Generate shell completions\");\n\n completion\n .command(\"bash\")\n .description(\"Output bash completions\")\n .action(() => {\n const script = generateBashCompletion();\n process.stdout.write(script);\n });\n\n completion\n .command(\"zsh\")\n .description(\"Output zsh completions\")\n .action(() => {\n const script = generateZshCompletion();\n process.stdout.write(script);\n });\n\n completion\n .command(\"fish\")\n .description(\"Output fish completions\")\n .action(() => {\n const script = generateFishCompletion();\n process.stdout.write(script);\n });\n}\n\nfunction generateBashCompletion(): string {\n return `# tc bash completion\n_tc_completions() {\n local cur prev commands subcommands\n COMPREPLY=()\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\n\n commands=\"init auth kv space delegation share node profile completion\"\n\n case \"\\${COMP_WORDS[1]}\" in\n auth) subcommands=\"login logout status whoami\" ;;\n kv) subcommands=\"get put delete list head\" ;;\n space) subcommands=\"list create info switch\" ;;\n delegation) subcommands=\"create list info revoke\" ;;\n share) subcommands=\"create receive list revoke\" ;;\n node) subcommands=\"health version status\" ;;\n profile) subcommands=\"list create show switch delete\" ;;\n completion) subcommands=\"bash zsh fish\" ;;\n *) COMPREPLY=( $(compgen -W \"\\${commands}\" -- \"\\${cur}\") ); return ;;\n esac\n\n if [ \\${COMP_CWORD} -eq 2 ]; then\n COMPREPLY=( $(compgen -W \"\\${subcommands}\" -- \"\\${cur}\") )\n fi\n}\ncomplete -F _tc_completions tc\n`;\n}\n\nfunction generateZshCompletion(): string {\n return `#compdef tc\n\n_tc() {\n local -a commands\n commands=(\n 'init:Initialize a new TinyCloud profile'\n 'auth:Authentication management'\n 'kv:Key-value store operations'\n 'space:Space management'\n 'delegation:Manage delegations'\n 'share:Share data with others'\n 'node:Node health and info'\n 'profile:Profile management'\n 'completion:Generate shell completions'\n )\n\n _arguments -C \\\\\n '(-p --profile)'{-p,--profile}'[Profile to use]:profile:' \\\\\n '(-H --host)'{-H,--host}'[TinyCloud node URL]:url:' \\\\\n '(-v --verbose)'{-v,--verbose}'[Enable verbose output]' \\\\\n '--no-cache[Disable caching]' \\\\\n '(-q --quiet)'{-q,--quiet}'[Suppress non-essential output]' \\\\\n '1:command:->cmd' \\\\\n '*::arg:->args'\n\n case $state in\n cmd)\n _describe 'command' commands\n ;;\n args)\n case $words[1] in\n auth) _values 'subcommand' login logout status whoami ;;\n kv) _values 'subcommand' get put delete list head ;;\n space) _values 'subcommand' list create info switch ;;\n delegation) _values 'subcommand' create list info revoke ;;\n share) _values 'subcommand' create receive list revoke ;;\n node) _values 'subcommand' health version status ;;\n profile) _values 'subcommand' list create show switch delete ;;\n completion) _values 'subcommand' bash zsh fish ;;\n esac\n ;;\n esac\n}\n\n_tc\n`;\n}\n\nfunction generateFishCompletion(): string {\n return `# tc fish completion\nset -l commands init auth kv space delegation share node profile completion\n\n# Disable file completion by default\ncomplete -c tc -f\n\n# Top-level commands\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a init -d \"Initialize a new TinyCloud profile\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a auth -d \"Authentication management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a kv -d \"Key-value store operations\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a space -d \"Space management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a delegation -d \"Manage delegations\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a share -d \"Share data with others\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a node -d \"Node health and info\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a profile -d \"Profile management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a completion -d \"Generate shell completions\"\n\n# Subcommands\ncomplete -c tc -n \"__fish_seen_subcommand_from auth\" -a \"login logout status whoami\"\ncomplete -c tc -n \"__fish_seen_subcommand_from kv\" -a \"get put delete list head\"\ncomplete -c tc -n \"__fish_seen_subcommand_from space\" -a \"list create info switch\"\ncomplete -c tc -n \"__fish_seen_subcommand_from delegation\" -a \"create list info revoke\"\ncomplete -c tc -n \"__fish_seen_subcommand_from share\" -a \"create receive list revoke\"\ncomplete -c tc -n \"__fish_seen_subcommand_from node\" -a \"health version status\"\ncomplete -c tc -n \"__fish_seen_subcommand_from profile\" -a \"list create show switch delete\"\ncomplete -c tc -n \"__fish_seen_subcommand_from completion\" -a \"bash zsh fish\"\n\n# Global options\ncomplete -c tc -l profile -s p -d \"Profile to use\"\ncomplete -c tc -l host -s H -d \"TinyCloud node URL\"\ncomplete -c tc -l verbose -s v -d \"Enable verbose output\"\ncomplete -c tc -l no-cache -d \"Disable caching\"\ncomplete -c tc -l quiet -s q -d \"Suppress non-essential output\"\n`;\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { PrivateKeySigner } from \"@tinycloud/node-sdk\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\n/**\n * Unlock the vault on a TinyCloudNode instance.\n */\nasync function unlockVault(\n node: { vault: { unlock(signer: { signMessage(message: string): Promise<string> }): Promise<any> } },\n privateKey: string,\n): Promise<void> {\n const signer = new PrivateKeySigner(privateKey);\n const result = await node.vault.unlock(signer);\n if (result && !result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n}\n\nexport function registerVaultCommand(program: Command): void {\n const vault = program.command(\"vault\").description(\"Encrypted vault operations\");\n\n // tc vault unlock\n vault\n .command(\"unlock\")\n .description(\"Verify vault unlock works\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n outputJson({ unlocked: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault put <key> [value]\n vault\n .command(\"put <key> [value]\")\n .description(\"Encrypt and store a value\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n // Determine value source\n let putValue: string | Uint8Array;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n putValue = new Uint8Array(await readFile(options.file));\n } else if (options.stdin) {\n putValue = new Uint8Array(await readStdin());\n } else {\n putValue = value!;\n }\n\n const result = await withSpinner(`Writing ${key}...`, () => node.vault.put(key, putValue)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault get <key>\n vault\n .command(\"get <key>\")\n .description(\"Decrypt and retrieve a value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Getting ${key}...`, () => node.vault.get(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Key \"${key}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data ?? result.data;\n\n if (options.output) {\n const content = data instanceof Uint8Array ? Buffer.from(data) : typeof data === \"string\" ? data : JSON.stringify(data);\n await writeFile(options.output, content);\n outputJson({ key, written: options.output });\n return;\n }\n\n if (options.raw) {\n const content = data instanceof Uint8Array ? Buffer.from(data) : typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content);\n return;\n }\n\n outputJson({\n key,\n data: data instanceof Uint8Array ? Buffer.from(data).toString(\"base64\") : data,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault delete <key>\n vault\n .command(\"delete <key>\")\n .description(\"Delete an encrypted key\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Deleting ${key}...`, () => node.vault.delete(key)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault list\n vault\n .command(\"list\")\n .description(\"List vault keys\")\n .option(\"--prefix <prefix>\", \"Filter by key prefix\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing vault keys...\", () => node.vault.list(listOptions)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const keys = result.data.data ?? result.data;\n const keyList = Array.isArray(keys) ? keys : [];\n\n outputJson({\n keys: keyList,\n count: keyList.length,\n prefix: options.prefix ?? null,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault head <key>\n vault\n .command(\"head <key>\")\n .description(\"Get metadata for a vault key\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Checking ${key}...`, () => node.vault.head(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n outputJson({ key, exists: false, metadata: {} });\n return;\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n key,\n exists: true,\n metadata: result.data.headers ?? result.data,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\nfunction authOptions(options: { privateKey?: string }): { privateKey?: string } | undefined {\n const privateKey = options.privateKey || process.env.TC_PRIVATE_KEY;\n return privateKey ? { privateKey } : undefined;\n}\n\nfunction resolveSecretScope(options: { scope?: string; space?: string }): { scope?: string } | undefined {\n const scope = options.scope ?? options.space;\n return scope ? { scope } : undefined;\n}\n\nexport function registerSecretsCommand(program: Command): void {\n const secrets = program.command(\"secrets\").description(\"Encrypted secrets management\");\n\n const network = secrets\n .command(\"network\")\n .description(\"Manage the default secrets encryption network\");\n\n network\n .command(\"show [nameOrNetworkId]\")\n .description(\"Show a secrets encryption network\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (nameOrNetworkId: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const requested = nameOrNetworkId ?? \"default\";\n const networkId = requested.startsWith(\"urn:tinycloud:encryption:\")\n ? requested\n : node.getDefaultEncryptionNetworkId(requested);\n const descriptor = await withSpinner(\n \"Fetching encryption network...\",\n () => node.getEncryptionNetwork(requested),\n );\n outputJson({\n networkId,\n exists: descriptor !== null,\n ...(descriptor ? { descriptor } : {}),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n network\n .command(\"init [name]\")\n .description(\"Create a secrets encryption network if needed\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (name: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const descriptor = await withSpinner(\n \"Ensuring encryption network...\",\n () => node.ensureEncryptionNetwork(name ?? \"default\"),\n );\n outputJson({\n networkId: descriptor.networkId,\n state: descriptor.state,\n descriptor,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets list\n secrets\n .command(\"list\")\n .description(\"List secrets\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const scopeOptions = resolveSecretScope(options);\n const result = await withSpinner(\n \"Listing secrets...\",\n () => node.secrets.list(scopeOptions),\n );\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const secretNames = Array.isArray(result.data) ? result.data : [];\n const scope = options.scope ?? options.space;\n\n outputJson({\n secrets: secretNames,\n count: secretNames.length,\n ...(scope ? { scope } : {}),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets get <name>\n secrets\n .command(\"get <name>\")\n .description(\"Get a secret value\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const scopeOptions = resolveSecretScope(options);\n const result = await withSpinner(\n `Getting secret ${name}...`,\n () => node.secrets.get(name, scopeOptions),\n );\n\n if (!result.ok) {\n if (\n result.error.code === \"NOT_FOUND\" ||\n result.error.code === \"KEY_NOT_FOUND\"\n ) {\n throw new CLIError(\"NOT_FOUND\", `Secret \"${name}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const value = String(result.data);\n\n if (options.output) {\n await writeFile(options.output, value);\n outputJson({ name, written: options.output });\n return;\n }\n\n if (options.raw) {\n process.stdout.write(value);\n return;\n }\n\n outputJson({ name, value });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets put <name> [value]\n secrets\n .command(\"put <name> [value]\")\n .description(\"Store a secret\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n\n // Determine value source\n let secretValue: string;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n secretValue = (await readFile(options.file, \"utf-8\")) as string;\n } else if (options.stdin) {\n secretValue = (await readStdin()).toString(\"utf-8\");\n } else {\n secretValue = value!;\n }\n\n const scopeOptions = resolveSecretScope(options);\n const result = await withSpinner(\n `Storing secret ${name}...`,\n () => node.secrets.put(name, secretValue, scopeOptions),\n );\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets delete <name>\n secrets\n .command(\"delete <name>\")\n .description(\"Delete a secret\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const scopeOptions = resolveSecretScope(options);\n const result = await withSpinner(\n `Deleting secret ${name}...`,\n () => node.secrets.delete(name, scopeOptions),\n );\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n network\n .command(\"grant <recipientDid> [name]\")\n .description(\"Grant decrypt permission for a secrets encryption network\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (recipientDid: string, name: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const networkName = name ?? \"default\";\n const descriptor = await withSpinner(\n \"Ensuring encryption network...\",\n () => node.ensureEncryptionNetwork(networkName),\n );\n const permission = {\n service: \"tinycloud.encryption\",\n path: descriptor.networkId,\n actions: [\"decrypt\"],\n };\n const result = await withSpinner(\n `Granting decrypt permission to ${recipientDid}...`,\n () => node.delegateTo(recipientDid, [permission]),\n );\n\n outputJson({\n networkId: descriptor.networkId,\n recipientDid,\n cid: result.delegation.cid,\n prompted: result.prompted,\n path: result.delegation.path,\n actions: result.delegation.actions,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets manage\n secrets\n .command(\"manage\")\n .description(\"Open the TinyCloud Secrets Manager in your browser\")\n .action(async () => {\n try {\n const open = (await import(\"open\")).default;\n await open(\"https://secrets.tinycloud.xyz\");\n outputJson({ opened: \"https://secrets.tinycloud.xyz\" });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\n\nconst VARIABLES_PREFIX = \"variables/\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\nexport function registerVarsCommand(program: Command): void {\n const vars = program.command(\"vars\").description(\"Plaintext variable management\");\n\n // tc vars list\n vars\n .command(\"list\")\n .description(\"List variables\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(\"Listing variables...\", () => prefixedKv.list()) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const rawData = result.data.data ?? result.data;\n const keyList = Array.isArray(rawData) ? rawData : (rawData?.keys ?? []);\n\n outputJson({\n variables: keyList,\n count: keyList.length,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars get <name>\n vars\n .command(\"get <name>\")\n .description(\"Get a variable value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Getting variable ${name}...`, () => prefixedKv.get(name)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Variable \"${name}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data;\n\n // Extract value from the stored payload\n let value: string;\n if (typeof data === \"string\") {\n try {\n const parsed = JSON.parse(data);\n value = parsed.value;\n } catch {\n value = data;\n }\n } else if (data && typeof data === \"object\" && \"value\" in data) {\n value = data.value;\n } else {\n value = typeof data === \"string\" ? data : JSON.stringify(data);\n }\n\n if (options.output) {\n await writeFile(options.output, value);\n outputJson({ name, written: options.output });\n return;\n }\n\n if (options.raw) {\n process.stdout.write(value);\n return;\n }\n\n outputJson({ name, value });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars put <name> [value]\n vars\n .command(\"put <name> [value]\")\n .description(\"Set a variable\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n // Determine value source\n let varValue: string;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n varValue = (await readFile(options.file, \"utf-8\")) as string;\n } else if (options.stdin) {\n varValue = (await readStdin()).toString(\"utf-8\");\n } else {\n varValue = value!;\n }\n\n const payload = {\n value: varValue,\n createdAt: new Date().toISOString(),\n };\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Setting variable ${name}...`, () => prefixedKv.put(name, payload)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars delete <name>\n vars\n .command(\"delete <name>\")\n .description(\"Delete a variable\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Deleting variable ${name}...`, () => prefixedKv.delete(name)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { DEFAULT_HOST } from \"../config/constants.js\";\nimport { outputJson, shouldOutputJson, formatCheck, formatSection } from \"../output/formatter.js\";\nimport { theme } from \"../output/theme.js\";\nimport { handleError } from \"../output/errors.js\";\n\ninterface DoctorResult {\n checks: Array<{ name: string; ok: boolean; detail?: string }>;\n healthy: boolean;\n}\n\nexport function registerDoctorCommand(program: Command): void {\n program\n .command(\"doctor\")\n .description(\"Run diagnostic checks\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const checks: DoctorResult[\"checks\"] = [];\n\n // 1. Node.js version\n const nodeVersion = process.version;\n const nodeOk = parseInt(nodeVersion.slice(1)) >= 18;\n checks.push({ name: \"Node.js\", ok: nodeOk, detail: nodeVersion });\n\n // 2. Profile configured\n let profileName = globalOpts.profile;\n let profileOk = false;\n let profileDetail = \"\";\n try {\n const config = await ProfileManager.getConfig();\n profileName = profileName || config.defaultProfile;\n const profile = await ProfileManager.getProfile(profileName);\n profileOk = true;\n profileDetail = `\"${profileName}\" at ${profile.host}`;\n } catch {\n profileDetail = profileName ? `\"${profileName}\" not found` : \"no profiles configured\";\n }\n checks.push({ name: \"Profile\", ok: profileOk, detail: profileDetail });\n\n // 3. Key exists\n let keyOk = false;\n let keyDetail = \"\";\n if (profileOk && profileName) {\n try {\n const key = await ProfileManager.getKey(profileName);\n keyOk = key !== null;\n if (keyOk) {\n const profile = await ProfileManager.getProfile(profileName);\n keyDetail = profile.did ? `${profile.did.slice(0, 20)}...` : \"key found\";\n } else {\n keyDetail = \"no key — run tc init\";\n }\n } catch {\n keyDetail = \"error reading key\";\n }\n } else {\n keyDetail = \"skipped (no profile)\";\n }\n checks.push({ name: \"Key\", ok: keyOk, detail: keyDetail });\n\n // 4. Session active\n let sessionOk = false;\n let sessionDetail = \"\";\n if (profileOk && profileName) {\n try {\n const session = await ProfileManager.getSession(profileName);\n sessionOk = session !== null;\n sessionDetail = sessionOk ? \"active\" : \"no session — run tc auth login\";\n } catch {\n sessionDetail = \"error reading session\";\n }\n } else {\n sessionDetail = \"skipped (no profile)\";\n }\n checks.push({ name: \"Session\", ok: sessionOk, detail: sessionDetail });\n\n // 5. Node reachable\n let nodeReachable = false;\n let nodeDetail = \"\";\n try {\n const host = profileOk && profileName\n ? (await ProfileManager.getProfile(profileName)).host\n : globalOpts.host || DEFAULT_HOST;\n const start = Date.now();\n const response = await fetch(`${host}/health`);\n const latency = Date.now() - start;\n nodeReachable = response.ok;\n nodeDetail = nodeReachable\n ? `${host} (${latency}ms)`\n : `${host} returned ${response.status}`;\n } catch (e) {\n nodeDetail = `unreachable — ${e instanceof Error ? e.message : \"connection failed\"}`;\n }\n checks.push({ name: \"Node\", ok: nodeReachable, detail: nodeDetail });\n\n // 6. Space exists (only if session active)\n let spaceOk = false;\n let spaceDetail = \"\";\n if (sessionOk && profileName) {\n try {\n const profile = await ProfileManager.getProfile(profileName);\n spaceOk = Boolean(profile.spaceId);\n spaceDetail = spaceOk\n ? `${profile.spaceId!.slice(0, 16)}...`\n : \"no space — run tc space create\";\n } catch {\n spaceDetail = \"error checking space\";\n }\n } else {\n spaceDetail = \"skipped (no session)\";\n }\n checks.push({ name: \"Space\", ok: spaceOk, detail: spaceDetail });\n\n const result: DoctorResult = {\n checks,\n healthy: checks.every((c) => c.ok),\n };\n\n if (shouldOutputJson()) {\n outputJson(result);\n } else {\n process.stderr.write(formatSection(\"Diagnostics\") + \"\\n\");\n for (const check of checks) {\n process.stdout.write(formatCheck(check.ok, check.name, check.detail) + \"\\n\");\n }\n process.stdout.write(\"\\n\");\n if (result.healthy) {\n process.stdout.write(theme.success(\"All checks passed.\") + \"\\n\");\n } else {\n const failed = checks.filter((c) => !c.ok).length;\n process.stdout.write(theme.warn(`${failed} check${failed > 1 ? \"s\" : \"\"} need attention.`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport type { TinyCloudNode, IDatabaseHandle } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { resolveSpaceUri } from \"../lib/space.js\";\nimport { theme } from \"../output/theme.js\";\n\n/**\n * Pick a database handle for the requested space + db name.\n *\n * `--space` is optional; when omitted, ops route through the node's\n * primary-space SQL service (preserves prior behavior). When present,\n * we use TinyCloudNode.sqlForSpace, which clones the active service\n * context with a session whose spaceId points at the target space.\n */\nasync function dbHandle(\n node: TinyCloudNode,\n dbName: string,\n spaceInput: string | undefined,\n profileName: string,\n): Promise<IDatabaseHandle> {\n const spaceUri = await resolveSpaceUri(spaceInput, profileName);\n const sql = spaceUri ? node.sqlForSpace(spaceUri) : node.sql;\n return sql.db(dbName);\n}\n\nexport function registerSqlCommand(program: Command): void {\n const sql = program\n .command(\"sql\")\n .description(\"SQLite database operations for your TinyCloud space\")\n .addHelpText(\"after\", `\n\nTinyCloud SQL gives each space isolated SQLite databases. Use the default\ndatabase for simple apps, or pass --db to target a named database. Pass\n--space to target a non-primary space (e.g. the manifest \"applications\" space).\n\nCommon workflows:\n $ tc sql execute \"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)\"\n $ tc sql execute \"INSERT INTO notes (body) VALUES (?)\" --params '[\"ship docs\"]'\n $ tc sql query \"SELECT id, body FROM notes ORDER BY id\"\n $ tc sql query \"SELECT * FROM events WHERE type = ?\" --db analytics --params '[\"signup\"]'\n $ tc sql query \"SELECT count(*) FROM conversation\" --space applications --db xyz.tinycloud.listen/conversations\n $ tc sql export --db analytics --output analytics.db\n\nCommands:\n query Read rows with SELECT statements\n execute Run writes and schema changes such as INSERT, UPDATE, DELETE, CREATE, DROP\n export Download the raw SQLite database file\n copy Copy rows between databases (optionally across spaces)\n\nTips:\n - SQL strings should usually be quoted so your shell passes them as one argument.\n - --params accepts a JSON array and binds values to ? placeholders.\n - --space accepts a short name (\"applications\") or full URI (\"tinycloud:pkh:eip155:1:0x...:applications\").\n - Add --json for scripting-friendly output.\n`);\n\n // tc sql query <sql>\n sql\n .command(\"query <sql>\")\n .description(\"Run a read-only SELECT query\")\n .option(\"--db <name>\", \"SQLite database name within the current space\", \"default\")\n .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\n .option(\"--params <json>\", \"Bind parameters as a JSON array for ? placeholders\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql query \"SELECT * FROM notes ORDER BY id\"\n $ tc sql query \"SELECT * FROM notes WHERE id = ?\" --params '[42]'\n $ tc sql query \"SELECT count(*) AS total FROM events\" --db analytics --json\n $ tc sql query \"SELECT count(*) FROM conversation\" --space applications --db xyz.tinycloud.listen/conversations\n\nOutput:\n Human output is formatted as a table. Piped output or --json returns\n { \"columns\": string[], \"rows\": unknown[][], \"rowCount\": number }.\n`)\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Running query...\", () =>\n handle.query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\n }\n\n const { columns, rows, rowCount } = result.data;\n\n if (shouldOutputJson()) {\n outputJson({ columns, rows, rowCount });\n } else {\n if (rows.length === 0) {\n process.stdout.write(theme.muted(\"No rows returned.\") + \"\\n\");\n } else {\n const stringRows = rows.map((row: unknown[]) =>\n row.map((v: unknown) => v === null ? \"NULL\" : String(v))\n );\n process.stdout.write(formatTable(columns, stringRows) + \"\\n\");\n process.stdout.write(theme.muted(`\\n${rowCount} row${rowCount === 1 ? \"\" : \"s\"} returned`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql execute <sql>\n sql\n .command(\"execute <sql>\")\n .description(\"Run a write or schema statement\")\n .option(\"--db <name>\", \"SQLite database name within the current space\", \"default\")\n .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\n .option(\"--params <json>\", \"Bind parameters as a JSON array for ? placeholders\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql execute \"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)\"\n $ tc sql execute \"INSERT INTO notes (body) VALUES (?)\" --params '[\"first note\"]'\n $ tc sql execute \"UPDATE notes SET body = ? WHERE id = ?\" --params '[\"edited\", 1]'\n $ tc sql execute \"DROP TABLE old_notes\" --db archive\n $ tc sql execute \"DELETE FROM conversation WHERE id = ?\" --space applications --db xyz.tinycloud.listen/conversations --params '[\"abc\"]'\n\nOutput:\n Returns JSON with the changed row count and last inserted row id when available.\n`)\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Executing statement...\", () =>\n handle.execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\n }\n\n outputJson({\n changes: result.data.changes,\n lastInsertRowId: result.data.lastInsertRowId,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql export\n sql\n .command(\"export\")\n .description(\"Export a SQLite database as a binary .db file\")\n .option(\"--db <name>\", \"SQLite database name within the current space\", \"default\")\n .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\n .option(\"-o, --output <file>\", \"Output file path\", \"export.db\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql export\n $ tc sql export --db analytics --output analytics.db\n $ tc sql export --space applications --db xyz.tinycloud.listen/conversations --output listen.db\n\nOutput:\n Writes the database file locally and returns JSON with the path and size.\n`)\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n handle.export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\n }\n\n const blob: Blob = result.data;\n const buffer = Buffer.from(await blob.arrayBuffer());\n const outputPath = resolve(options.output);\n await writeFile(outputPath, buffer);\n\n outputJson({\n file: outputPath,\n size: blob.size,\n sizeHuman: formatBytes(blob.size),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql copy\n sql\n .command(\"copy\")\n .description(\"Copy rows between SQL databases (optionally across spaces)\")\n .requiredOption(\"--from-db <name>\", \"Source database name\")\n .requiredOption(\"--to-db <name>\", \"Destination database name\")\n .option(\"--from-space <name|uri>\", \"Source space (defaults to primary)\")\n .option(\"--to-space <name|uri>\", \"Destination space (defaults to primary)\")\n .option(\"--table <name...>\", \"Restrict copy to specific tables (repeat or comma-separated)\")\n .option(\"--dry-run\", \"Print the plan without writing\", false)\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql copy --from-db com.tinycloud.conversation-sync/conversations \\\\\n --to-db xyz.tinycloud.listen/conversations \\\\\n --space applications --dry-run\n $ tc sql copy --from-space applications --from-db com.foo/data \\\\\n --to-space applications --to-db com.bar/data \\\\\n --table conversation --table participant\n\nNotes:\n - Refuses to run when (resolved space, db) is identical for source and destination.\n - Does NOT create destination tables. Run the target app once (or use \\`tc sql execute\\`)\n to materialize the schema before copying.\n - One row at a time; suitable for small/medium datasets. Large copies should\n use \\`tc sql export\\` + bulk import.\n - Authorization: the active session/delegation must cover sql/read on source\n AND sql/write on destination. Otherwise the relevant operation will fail.\n`)\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n // commander's `--space` shorthand supports both --from-space and a default.\n const fromSpaceInput: string | undefined = options.fromSpace ?? options.space;\n const toSpaceInput: string | undefined = options.toSpace ?? options.space;\n\n const fromSpaceUri = (await resolveSpaceUri(fromSpaceInput, ctx.profile)) ?? \"<primary>\";\n const toSpaceUri = (await resolveSpaceUri(toSpaceInput, ctx.profile)) ?? \"<primary>\";\n\n if (fromSpaceUri === toSpaceUri && options.fromDb === options.toDb) {\n throw new CLIError(\n \"SELF_COPY\",\n `Refusing to copy: source and destination resolve to the same (space, db) — ${fromSpaceUri} / ${options.fromDb}.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const fromHandle = await dbHandle(node, options.fromDb, fromSpaceInput, ctx.profile);\n const toHandle = await dbHandle(node, options.toDb, toSpaceInput, ctx.profile);\n\n // Resolve target tables: explicit list, or all user tables in source.\n let tables: string[];\n if (options.table && options.table.length > 0) {\n tables = options.table.flatMap((t: string) => t.split(\",\").map((s) => s.trim()).filter(Boolean));\n } else {\n const listing = await fromHandle.query(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n ) as any;\n if (!listing.ok) {\n throw new CLIError(listing.error.code, `Cannot list source tables: ${listing.error.message}`, ExitCode.ERROR, listing.error.meta);\n }\n tables = (listing.data.rows as unknown[][]).map((r) => String(r[0]));\n }\n\n if (tables.length === 0) {\n throw new CLIError(\n \"EMPTY_PLAN\",\n `No tables to copy. Use --table to specify tables, or check that the source database has user tables.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const plan: Array<{ table: string; rows: number; copied: number; skipped: number }> = [];\n\n for (const table of tables) {\n const safe = quoteIdent(table);\n const countResult = await fromHandle.query(`SELECT count(*) AS n FROM ${safe}`) as any;\n if (!countResult.ok) {\n throw new CLIError(\n countResult.error.code,\n `Cannot count rows in source table \"${table}\": ${countResult.error.message}`,\n ExitCode.ERROR,\n countResult.error.meta,\n );\n }\n const rows = Number(countResult.data.rows[0]?.[0] ?? 0);\n plan.push({ table, rows, copied: 0, skipped: 0 });\n }\n\n if (options.dryRun) {\n outputJson({\n dryRun: true,\n from: { space: fromSpaceUri, db: options.fromDb },\n to: { space: toSpaceUri, db: options.toDb },\n tables: plan.map((p) => ({ table: p.table, rows: p.rows })),\n });\n return;\n }\n\n for (const entry of plan) {\n const safe = quoteIdent(entry.table);\n const fetched = await fromHandle.query(`SELECT * FROM ${safe}`) as any;\n if (!fetched.ok) {\n throw new CLIError(fetched.error.code, `Failed to read \"${entry.table}\": ${fetched.error.message}`, ExitCode.ERROR, fetched.error.meta);\n }\n const columns: string[] = fetched.data.columns;\n const rows: unknown[][] = fetched.data.rows;\n\n if (rows.length === 0) continue;\n\n const colList = columns.map(quoteIdent).join(\", \");\n const placeholders = columns.map(() => \"?\").join(\", \");\n const insertSql = `INSERT INTO ${safe} (${colList}) VALUES (${placeholders})`;\n\n for (const row of rows) {\n const writeResult = await toHandle.execute(insertSql, row as any) as any;\n if (!writeResult.ok) {\n throw new CLIError(\n writeResult.error.code,\n `Insert into \"${entry.table}\" failed after ${entry.copied} row(s): ${writeResult.error.message}`,\n ExitCode.ERROR,\n writeResult.error.meta,\n );\n }\n entry.copied += writeResult.data.changes ?? 1;\n }\n }\n\n outputJson({\n from: { space: fromSpaceUri, db: options.fromDb },\n to: { space: toSpaceUri, db: options.toDb },\n tables: plan.map((p) => ({ table: p.table, rowsRead: p.rows, rowsWritten: p.copied })),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\n/** Quote a SQLite identifier defensively (table/column names). */\nfunction quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n","import { Command } from \"commander\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerDuckdbCommand(program: Command): void {\n const duckdb = program.command(\"duckdb\").description(\"DuckDB database operations\");\n\n // tc duckdb query <sql>\n duckdb\n .command(\"query <sql>\")\n .description(\"Run a SELECT query\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Running query...\", () =>\n node.duckdb.db(options.db).query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const { columns, rows, rowCount } = result.data;\n\n if (shouldOutputJson()) {\n outputJson({ columns, rows, rowCount });\n } else {\n if (rows.length === 0) {\n process.stdout.write(theme.muted(\"No rows returned.\") + \"\\n\");\n } else {\n const stringRows = rows.map((row: unknown[]) =>\n row.map((v: unknown) => v === null ? \"NULL\" : String(v))\n );\n process.stdout.write(formatTable(columns, stringRows) + \"\\n\");\n process.stdout.write(theme.muted(`\\n${rowCount} row${rowCount === 1 ? \"\" : \"s\"} returned`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb execute <sql>\n duckdb\n .command(\"execute <sql>\")\n .description(\"Run INSERT/UPDATE/DELETE/DDL statement\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Executing statement...\", () =>\n node.duckdb.db(options.db).execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ changes: result.data.changes });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb describe\n duckdb\n .command(\"describe\")\n .description(\"Show database schema (tables, columns, views)\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Describing schema...\", () =>\n node.duckdb.db(options.db).describe()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const schema = result.data;\n\n if (shouldOutputJson()) {\n outputJson(schema);\n } else {\n const { tables, views } = schema;\n\n if (tables.length === 0 && views.length === 0) {\n process.stdout.write(theme.muted(\"No tables or views found.\") + \"\\n\");\n return;\n }\n\n if (tables.length > 0) {\n process.stdout.write(theme.label(\"Tables:\") + \"\\n\\n\");\n for (const table of tables) {\n process.stdout.write(` ${theme.value(table.name)}\\n`);\n const colRows = table.columns.map((col: any) => [\n col.name,\n col.type,\n col.nullable ? \"YES\" : \"NO\",\n ]);\n const colTable = formatTable([\"Column\", \"Type\", \"Nullable\"], colRows);\n process.stdout.write(colTable.split(\"\\n\").map((l: string) => \" \" + l).join(\"\\n\") + \"\\n\\n\");\n }\n }\n\n if (views.length > 0) {\n process.stdout.write(theme.label(\"Views:\") + \"\\n\\n\");\n const viewRows = views.map((v: any) => [v.name, v.sql]);\n process.stdout.write(formatTable([\"View\", \"SQL\"], viewRows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb export\n duckdb\n .command(\"export\")\n .description(\"Export database as binary file\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"-o, --output <file>\", \"Output file path\", \"export.duckdb\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n node.duckdb.db(options.db).export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const blob: Blob = result.data;\n const buffer = Buffer.from(await blob.arrayBuffer());\n const outputPath = resolve(options.output);\n await writeFile(outputPath, buffer);\n\n outputJson({\n file: outputPath,\n size: blob.size,\n sizeHuman: formatBytes(blob.size),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb import <file>\n duckdb\n .command(\"import <file>\")\n .description(\"Import a DuckDB database file\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .action(async (file: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const filePath = resolve(file);\n const bytes = new Uint8Array(await readFile(filePath));\n\n const result = await withSpinner(\"Importing database...\", () =>\n node.duckdb.db(options.db).import(bytes)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n file: filePath,\n size: bytes.byteLength,\n sizeHuman: formatBytes(bytes.byteLength),\n imported: true,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { resolveSpaceUri } from \"../lib/space.js\";\nimport { outputJson, shouldOutputJson, formatTable } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { theme } from \"../output/theme.js\";\n\ninterface ManifestPermission {\n service: string;\n path: string;\n actions: string[];\n skipPrefix?: boolean;\n description?: string;\n}\n\ninterface Manifest {\n manifest_version?: number;\n app_id?: string;\n name?: string;\n description?: string;\n space?: string;\n defaults?: boolean;\n permissions?: ManifestPermission[];\n}\n\n/**\n * Default space for app data when the manifest omits `space`.\n * Mirrors the manifest spec at repositories/listen/SPEC-manifest-and-capability-chain.md.\n */\nconst DEFAULT_APP_SPACE = \"applications\";\n\nexport function registerManifestCommand(program: Command): void {\n const manifest = program\n .command(\"manifest\")\n .description(\"Inspect TinyCloud app manifests\");\n\n manifest\n .command(\"resolve <source>\")\n .description(\"Resolve a manifest file or URL to its effective space, paths, and DB basenames\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc manifest resolve ./manifest.json\n $ tc manifest resolve https://app.example.com/manifest.json --json\n\nWhat it shows:\n - app_id, name, manifest_version\n - effective space name (default: \"applications\") and full space URI for the active profile\n - per-permission: service, fully-qualified path, actions\n - inferred SQL database basenames for sql/<db>/... paths\n\nThis command is read-only and does NOT contact the node — it just resolves\nthe manifest against the active profile's address/chain so you know which\n\\`--space\\` and \\`--db\\` values to pass to other tc commands.\n`)\n .action(async (source: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const raw = await loadManifestSource(source);\n const parsed: Manifest = JSON.parse(raw);\n\n if (!parsed.app_id) {\n throw new CLIError(\n \"INVALID_MANIFEST\",\n `Manifest is missing required field \"app_id\".`,\n ExitCode.ERROR,\n );\n }\n\n // Make sure we have an authenticated profile so we can resolve\n // the user's space URI. We don't use the node — just the profile.\n await ensureAuthenticated(ctx);\n\n const spaceName = parsed.space ?? DEFAULT_APP_SPACE;\n const spaceUri = await resolveSpaceUri(spaceName, ctx.profile);\n\n const permissions = (parsed.permissions ?? []).map((p) => {\n const resolvedPath = p.skipPrefix ? p.path : prefixWithAppId(p.path, parsed.app_id!);\n return {\n service: p.service,\n path: resolvedPath,\n actions: p.actions,\n sqlDb: extractSqlDbName(resolvedPath),\n };\n });\n\n const sqlDbs = unique(\n permissions\n .map((p) => p.sqlDb)\n .filter((db): db is string => Boolean(db)),\n );\n\n const summary = {\n source,\n app_id: parsed.app_id,\n name: parsed.name,\n manifest_version: parsed.manifest_version,\n space: {\n name: spaceName,\n uri: spaceUri,\n },\n permissions,\n sqlDatabases: sqlDbs,\n };\n\n if (shouldOutputJson()) {\n outputJson(summary);\n return;\n }\n\n process.stdout.write(`${theme.heading(\"Manifest\")}: ${theme.value(parsed.app_id)}`);\n if (parsed.name) process.stdout.write(theme.muted(` (${parsed.name})`));\n process.stdout.write(\"\\n\");\n\n process.stdout.write(`${theme.label(\"Space\")}: ${theme.value(spaceName)}\\n`);\n if (spaceUri) {\n process.stdout.write(`${theme.label(\"Space URI\")}: ${theme.value(spaceUri)}\\n`);\n }\n\n if (sqlDbs.length > 0) {\n process.stdout.write(`\\n${theme.heading(\"SQL databases\")}\\n`);\n for (const db of sqlDbs) {\n process.stdout.write(` ${theme.value(db)}\\n`);\n }\n process.stdout.write(theme.muted(`\\nUse with: tc sql query --space ${spaceName} --db <db> \"...\"\\n`));\n }\n\n if (permissions.length > 0) {\n process.stdout.write(`\\n${theme.heading(\"Permissions\")}\\n`);\n const rows = permissions.map((p) => [p.service, p.path, p.actions.join(\", \")]);\n process.stdout.write(formatTable([\"service\", \"path\", \"actions\"], rows) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nasync function loadManifestSource(source: string): Promise<string> {\n if (/^https?:\\/\\//i.test(source)) {\n const response = await fetch(source);\n if (!response.ok) {\n throw new CLIError(\n \"MANIFEST_FETCH_FAILED\",\n `Failed to fetch manifest from ${source}: ${response.status} ${response.statusText}`,\n ExitCode.NETWORK_ERROR,\n );\n }\n return response.text();\n }\n return readFile(source, \"utf8\");\n}\n\nfunction prefixWithAppId(path: string, appId: string): string {\n // Manifest paths are usually `<service-prefix>/<resource>`, e.g. `sql/foo/bar`.\n // When skipPrefix is false the app_id is inserted between the service prefix\n // and the resource, matching how resolveAppPath() lays out keys at runtime.\n const slash = path.indexOf(\"/\");\n if (slash === -1) return `${appId}/${path}`;\n const head = path.slice(0, slash);\n const tail = path.slice(slash + 1);\n return `${head}/${appId}/${tail}`;\n}\n\n/**\n * For a path like `sql/<db-name>/<table>/...`, return `<db-name>`.\n * `<db-name>` itself may contain slashes when the app namespaces it\n * (e.g. `sql/xyz.tinycloud.listen/conversations/conversation`), so we drop\n * the trailing table segment(s) and reassemble.\n */\nfunction extractSqlDbName(path: string): string | undefined {\n if (!path.startsWith(\"sql/\")) return undefined;\n const rest = path.slice(4);\n const segments = rest.split(\"/\");\n if (segments.length < 2) return rest;\n // Drop the last segment (table name); the rest is the db name.\n return segments.slice(0, -1).join(\"/\");\n}\n\nfunction unique<T>(arr: T[]): T[] {\n return Array.from(new Set(arr));\n}\n","import { Command } from \"commander\";\nimport { execSync } from \"child_process\";\nimport { readFileSync } from \"fs\";\nimport { theme } from \"../output/theme.js\";\nimport { handleError } from \"../output/errors.js\";\n\nconst PACKAGE_NAME = \"@tinycloud/cli\";\n\nfunction getCurrentVersion(): string {\n const pkg = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\")\n );\n return pkg.version;\n}\n\nasync function getLatestVersion(): Promise<string> {\n const res = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`);\n if (!res.ok) {\n throw new Error(`Failed to fetch latest version: ${res.status} ${res.statusText}`);\n }\n const data = (await res.json()) as { version: string };\n return data.version;\n}\n\nfunction detectPackageManager(): \"bun\" | \"npm\" {\n // Check if bun installed the package globally\n try {\n const bunGlobals = execSync(\"bun pm ls -g\", { encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n if (bunGlobals.includes(PACKAGE_NAME)) {\n return \"bun\";\n }\n } catch {\n // bun not available or failed\n }\n\n // Check if npm installed the package globally\n try {\n const npmGlobals = execSync(\"npm ls -g --depth=0\", { encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n if (npmGlobals.includes(PACKAGE_NAME)) {\n return \"npm\";\n }\n } catch {\n // npm not available or failed\n }\n\n // Fallback to bun since the CLI shebang uses it\n return \"bun\";\n}\n\nexport function registerUpgradeCommand(program: Command): void {\n program\n .command(\"upgrade\")\n .description(\"Upgrade the TinyCloud CLI to the latest version\")\n .action(async () => {\n try {\n const current = getCurrentVersion();\n\n process.stderr.write(theme.muted(\"Checking for updates...\") + \"\\n\");\n const latest = await getLatestVersion();\n\n if (current === latest) {\n process.stdout.write(theme.success(`Already on latest version (${current})`) + \"\\n\");\n return;\n }\n\n process.stdout.write(`Current: ${theme.warn(current)} → Latest: ${theme.success(latest)}\\n`);\n\n const pm = detectPackageManager();\n const cmd = pm === \"bun\"\n ? `bun install -g ${PACKAGE_NAME}@latest`\n : `npm install -g ${PACKAGE_NAME}@latest`;\n\n process.stderr.write(theme.muted(`Upgrading via ${pm}...`) + \"\\n\\n\");\n\n try {\n execSync(cmd, { stdio: \"inherit\" });\n process.stdout.write(\"\\n\" + theme.success(`Upgraded to ${latest}`) + \"\\n\");\n } catch {\n process.stderr.write(\"\\n\" + theme.warn(\"Automatic upgrade failed.\") + \"\\n\");\n process.stderr.write(theme.muted(\"Try running manually:\") + \"\\n\");\n process.stderr.write(` ${theme.command(`bun install -g ${PACKAGE_NAME}@latest`)}\\n`);\n process.stderr.write(theme.muted(\" or\") + \"\\n\");\n process.stderr.write(` ${theme.command(`npm install -g ${PACKAGE_NAME}@latest`)}\\n`);\n }\n }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AM,MAAM,8BAA8B,CAAC;AAAA,IACtG,MAAM,QAAQ,eAAe,CAAC,2BAA2B,MAAM,MAAM,kBAAkB,CAAC;AAAA;AAAA,EAE1F,MAAM,MAAM,OAAO,CAAC,IAAI,MAAM,OAAO,gCAAgC,CAAC;AAAA,EACtE,MAAM,MAAM,OAAO,CAAC,IAAI,MAAM,OAAO,0CAA0C,CAAC;AAAA;AAElF,CAAC;AAED,IAAI;AACF,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC,SAAS,OAAO;AACd,cAAY,KAAK;AACnB;","names":["readFileSync","join","join","version","join","rm","join","rm","TinyCloudNode","resolve","program","mkdir","readFile","writeFile","dirname","createInterface","randomBytes","readFile","join","join","randomBytes","readFile","readFile","node","createInterface","resolve","program","delegationCids","expiry","mkdir","dirname","writeFile","readFile","readFile","writeFile","readStdin","program","writeFile","readFile","program","program","program","program","createInterface","program","createInterface","resolve","program","readFile","writeFile","PrivateKeySigner","readStdin","program","readFile","writeFile","readFile","writeFile","readStdin","program","writeFile","readFile","readFile","writeFile","readStdin","resolvePrivateKey","program","writeFile","readFile","program","writeFile","program","writeFile","readFile","writeFile","resolve","program","resolve","writeFile","readFile","readFile","program","readFile","execSync","readFileSync","readFileSync","execSync","program","readFileSync"]}
|