clawnify 0.11.3 → 0.11.4
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/cli-ISABP4ZI.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/commands/login.ts","../src/commands/deploy.ts","../src/lib/sync-schema.ts","../src/commands/ls.ts","../src/commands/logs.ts","../src/lib/servers.ts","../src/commands/sessions.ts","../src/commands/agents.ts","../src/commands/servers.ts","../src/commands/env.ts","../src/commands/api.ts","../src/commands/rm.ts","../src/commands/open.ts","../src/commands/whoami.ts","../src/commands/init.ts","../src/lib/skills/detect.ts","../src/lib/skills/content.gen.ts","../src/lib/skills/install.ts","../src/lib/ai-files/rules.ts","../src/lib/ai-files/mcp.ts","../src/commands/ai-files.ts","../src/commands/dev.ts","../src/commands/link.ts","../src/commands/pull.ts","../src/commands/org.ts","../src/commands/connections.ts","../src/commands/workspace.ts","../src/commands/execute.ts","../src/lib/mcp-client.ts","../src/commands/docs.ts","../src/commands/mcp-bridge.ts","../src/commands/sdk.ts","../src/commands/skills.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { loginCommand } from \"./commands/login.js\";\nimport { deployCommand } from \"./commands/deploy.js\";\nimport { lsCommand } from \"./commands/ls.js\";\nimport { logsCommand } from \"./commands/logs.js\";\nimport { sessionsListCommand, sessionsHistoryCommand } from \"./commands/sessions.js\";\nimport { agentsListCommand, agentsPullCommand, agentsPushCommand, agentsSkillsCommand, agentsGrantSkillCommand, agentsCreateCommand } from \"./commands/agents.js\";\nimport { serversListCommand } from \"./commands/servers.js\";\nimport { envSetCommand, envUnsetCommand } from \"./commands/env.js\";\nimport { apiCommand } from \"./commands/api.js\";\nimport { rmCommand } from \"./commands/rm.js\";\nimport { openCommand } from \"./commands/open.js\";\nimport { whoamiCommand } from \"./commands/whoami.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { devCommand } from \"./commands/dev.js\";\nimport { linkCommand } from \"./commands/link.js\";\nimport { pullSchemaCommand } from \"./commands/pull.js\";\nimport { orgListCommand, orgUseCommand } from \"./commands/org.js\";\nimport { connectionsListCommand, connectionsConnectCommand } from \"./commands/connections.js\";\nimport { workspaceInitCommand, workspaceStatusCommand } from \"./commands/workspace.js\";\nimport { executeCommand } from \"./commands/execute.js\";\nimport { docsCommand } from \"./commands/docs.js\";\nimport { mcpBridgeCommand } from \"./commands/mcp-bridge.js\";\nimport { sdkInspectCommand, sdkLoginCommand, sdkInstallCommand } from \"./commands/sdk.js\";\nimport {\n skillsAddCommand,\n skillsListCommand,\n skillsRemoveCommand,\n} from \"./commands/skills.js\";\nimport {\n aiFilesInstallCommand,\n aiFilesUninstallCommand,\n} from \"./commands/ai-files.js\";\n\nexport async function runCli() {\n const program = new Command();\n\n program\n .name(\"clawnify\")\n .description(\"Deploy apps to Clawnify\")\n .version(\"0.1.0\")\n .addHelpText(\n \"after\",\n \"\\nCoding agent? Start with `clawnify workspace` — it prints the org's synced\\nGitHub repo, what maps where, and how local editing works.\\n\",\n );\n\n program\n .command(\"init [dir]\")\n .description(\"Scaffold a new Clawnify project (app, website, or agent)\")\n .option(\"--type <type>\", \"Project type: app, website, or agent (skips prompt)\")\n .option(\"--name <name>\", \"Project name (skips prompt)\")\n .option(\"--template <template>\", \"App template: blank or crud (apps only)\")\n .option(\"--storage\", \"Enable file uploads (R2) — apps only\")\n .option(\"-y, --yes\", \"Non-interactive: use all defaults (app, blank, no storage)\")\n .option(\"--no-ai-files\", \"Skip installing AI files (rules + skills + MCP) after scaffolding\")\n .action(initCommand);\n\n program\n .command(\"dev [dir]\")\n .description(\"Start local dev server\")\n .option(\"--port <port>\", \"API server port (default: 8787)\")\n .action(devCommand);\n\n program\n .command(\"login\")\n .description(\"Authenticate with Clawnify\")\n .action(loginCommand);\n\n program\n .command(\"deploy [dir]\")\n .description(\"Deploy an app, website, or agent to Clawnify\")\n .option(\"--from <repo>\", \"Deploy from a GitHub repo (owner/repo)\")\n .option(\"--server <server-id>\", \"Agent deploy: the server hosting the target agent (saved as a link)\")\n .option(\"--agent <name>\", \"Agent deploy: the named agent to push to (default: main)\")\n .option(\"--path <subdir>\", \"Subdirectory within the --from repo that holds the app (monorepo)\")\n .option(\"--name <name>\", \"Override app name\")\n .option(\"--org <slug-or-id>\", \"Deploy to a specific org (overrides active org)\")\n .option(\"-y, --yes\", \"Non-interactive: on slug conflict, update existing app\")\n .option(\"--update-existing\", \"Non-interactive: on slug conflict, overwrite existing app\")\n .option(\"--create-new\", \"Non-interactive: on slug conflict, create a new app with the suggested slug\")\n .option(\"--dry-run\", \"List files that would be uploaded; do not deploy\")\n .option(\"--no-sync\", \"Skip the post-deploy schema.sql sync into the local working directory\")\n .action(deployCommand);\n\n program\n .command(\"link <app-id-or-slug>\")\n .description(\"Link the current directory to an existing Clawnify app (accepts id or slug)\")\n .option(\"--dir <dir>\", \"Directory to link (default: cwd)\")\n .option(\"--org <slug-or-id>\", \"Restrict the app lookup to a specific org\")\n .action(linkCommand);\n\n // `clawnify pull` — sync deployed-app artifacts back into the local\n // working directory. Currently only `schema` is supported; future\n // subcommands (migrations, manifest, etc.) can slot in here.\n const pull = program\n .command(\"pull\")\n .description(\"Pull artifacts from a deployed app into the current directory\");\n\n pull\n .command(\"schema\")\n .description(\"Fetch the deployed app's current schema.sql snapshot into the local repo\")\n .option(\"--from <app-id-or-slug>\", \"App to fetch from (required)\")\n .option(\"--out <path>\", \"Where to write (default: ./schema.sql)\")\n .option(\"--force\", \"Overwrite a locally-modified or uncommitted schema.sql\")\n .option(\"--org <slug-or-id>\", \"Restrict the app lookup to a specific org\")\n .action(pullSchemaCommand);\n\n const org = program.command(\"org\").description(\"Manage organizations\");\n org.command(\"list\").description(\"List orgs you belong to\").action(orgListCommand);\n org\n .command(\"use <slug-or-id>\")\n .description(\"Set the active org for global commands (ls, whoami, etc.)\")\n .action(orgUseCommand);\n\n // `clawnify connections` — the org's naming catalog (docs §3.5): canonical\n // integration ids, provider-key names, custom env. The read to make before\n // declaring `requires` — never invent an identifier.\n const connections = program\n .command(\"connections\")\n .description(\"Org integrations & the naming catalog\");\n connections\n .command(\"list\")\n .description(\"List canonical integration ids, provider keys, and custom env for the active org\")\n .option(\"--json\", \"Print the full catalog payload (includes docs + spec_url per integration)\")\n .action(connectionsListCommand);\n connections\n .command(\"connect <id>\")\n .description(\"Explain how to connect an integration (OAuth in the dashboard — the CLI/agent can't do it for you)\")\n .option(\"--json\", \"Print the steps as JSON\")\n .action(connectionsConnectCommand);\n\n // `clawnify workspace` — a monorepo hosting one org's apps. Apps scaffolded\n // inside it land under apps/ and inherit the org on deploy. Bare invocation\n // prints orientation (org, synced repo, subdir↔target map, editing contract)\n // — the entry point for coding agents.\n const workspace = program\n .command(\"workspace\")\n .description(\"Show the org's workspace: synced GitHub repo, targets, and how to edit locally\")\n .option(\"--json\", \"Machine-readable output\")\n .action(workspaceStatusCommand);\n workspace\n .command(\"init [dir]\")\n .description(\"Scaffold a workspace monorepo bound to an org\")\n .option(\"--org <slug-or-id>\", \"Org to bind the workspace to (defaults to active org)\")\n .option(\"--name <name>\", \"Workspace display name (defaults to the org name)\")\n .action(workspaceInitCommand);\n\n program\n .command(\"ls\")\n .description(\"List deployed apps\")\n .action(lsCommand);\n\n program\n .command(\"logs <app-id>\")\n .description(\"Show build logs for an app\")\n .action(logsCommand);\n\n // `clawnify servers` — list the org's agent servers (an org can have several,\n // e.g. an agency managing multiple client boxes). Top of the FDE discovery\n // tree: servers → agents → sessions.\n const servers = program\n .command(\"servers\")\n .description(\"List the org's agent servers\");\n servers\n .command(\"list\", { isDefault: true })\n .description(\"List the org's agent servers\")\n .action(serversListCommand);\n\n // `clawnify sessions` — the FDE observe verb: list stored sessions across\n // ALL agents on the org's server (main + specialists), and read one\n // session's transcript. See docs/internal/fde-strategy.md.\n const sessions = program\n .command(\"sessions\")\n .description(\"Observe agent sessions (list + read transcripts)\");\n sessions\n .command(\"list\", { isDefault: true })\n .description(\"List stored sessions across all agents on the server\")\n .option(\"--server <id>\", \"Target server (default: the org's server, or a linked project)\")\n .option(\"--agent <slug>\", \"Only this agent's sessions\")\n .option(\"--active <minutes>\", \"Only sessions active within N minutes\")\n .option(\"--limit <n>\", \"Max rows (default 100)\")\n .option(\"--json\", \"Print the raw JSON payload\")\n .action(sessionsListCommand);\n sessions\n .command(\"history <key>\")\n .description(\"Read one session's transcript by key (e.g. agent:dnz---theo:lead:row_8268)\")\n .option(\"--server <id>\", \"Target server (default: the org's server, or a linked project)\")\n .option(\"--agent <slug>\", \"Owning agent (else derived from the key prefix)\")\n .option(\"--limit <n>\", \"Max transcript entries (default 100)\")\n .option(\"--json\", \"Print the raw JSON payload\")\n .action(sessionsHistoryCommand);\n\n // `clawnify agents` — the FDE's agent-management verbs: list the agents on the\n // server, pull an agent's AGENTS.md/skills/flows to edit, push edits back.\n // See docs/internal/fde-strategy.md.\n const agents = program\n .command(\"agents\")\n .description(\"Manage agents: list, pull config to edit, push edits back\");\n agents\n .command(\"list\", { isDefault: true })\n .description(\"List the agents on the org's server\")\n .option(\"--server <id>\", \"Target server (default: the org's server)\")\n .action(agentsListCommand);\n agents\n .command(\"pull [dir]\")\n .description(\"Fetch an agent's AGENTS.md + skills/ + flows/ into a directory to edit\")\n .option(\"--server <id>\", \"Target server (default: the org's server)\")\n .option(\"--agent <slug>\", \"Which agent (default: main)\")\n .action(agentsPullCommand);\n agents\n .command(\"push [dir]\")\n .description(\"Push edited AGENTS.md + skills/ + flows/ back (additive; picked up next session)\")\n .option(\"--server <id>\", \"Target server (default: the linked/org's server)\")\n .option(\"--agent <slug>\", \"Which agent (default: the pulled agent, else main)\")\n .action(agentsPushCommand);\n agents\n .command(\"skills [agent]\")\n .description(\"Show an agent's effective skill inventory (what it can actually run, not just its workspace)\")\n .option(\"--server <id>\", \"Target server (default: the org's server)\")\n .action(agentsSkillsCommand);\n agents\n .command(\"grant-skill <skill>\")\n .description(\"Grant an existing (main-authored) skill to one agent (--to) or every agent (--all)\")\n .option(\"--server <id>\", \"Target server (default: the org's server)\")\n .option(\"--to <agent>\", \"Grant to one specialist agent\")\n .option(\"--all\", \"Grant to every agent (shared managed root; includes future agents)\")\n .action(agentsGrantSkillCommand);\n agents\n .command(\"create <slug>\")\n .description(\"Create a new specialist agent (RESTARTS the gateway — needs --yes)\")\n .option(\"--server <id>\", \"Target server (default: the org's server)\")\n .option(\"--name <name>\", \"Display name (default: the slug)\")\n .option(\"--description <role>\", \"The agent's role/specialization (seeded into its AGENTS.md)\")\n .option(\"--yes\", \"Confirm — proceed with the gateway restart\")\n .action(agentsCreateCommand);\n\n // `clawnify env` — the org's custom environment variables (all agents). Read\n // via `connections list`; set/unset here. NOT for secrets — those go in the\n // dashboard (Settings → Environment Variables / API Keys).\n const env = program\n .command(\"env\")\n .description(\"Org custom environment variables (read via `connections list`)\");\n env\n .command(\"set <key> <value>\")\n .description(\"Set an org-wide custom env var (NON-SECRET config; restarts the gateway to apply)\")\n .action(envSetCommand);\n env\n .command(\"unset <key>\")\n .description(\"Remove an org-wide custom env var (restarts the gateway to apply)\")\n .action(envUnsetCommand);\n\n // `clawnify api` — raw authenticated request; the escape hatch so the\n // porcelain never has to be complete (see gh api / stripe get).\n program\n .command(\"api <path>\")\n .description(\"Raw authenticated request to the Clawnify API — for anything without a dedicated command\")\n .option(\"-X, --method <method>\", \"HTTP method (default GET, or POST when -d is given)\")\n .option(\"-d, --data <json>\", \"JSON request body\")\n .option(\"--org <slug-or-id>\", \"Org to scope the request to\")\n .action(apiCommand);\n\n program\n .command(\"rm <app-id>\")\n .description(\"Delete an app\")\n .action(rmCommand);\n\n program\n .command(\"open <slug>\")\n .description(\"Open an app in the browser\")\n .action(openCommand);\n\n program\n .command(\"whoami\")\n .description(\"Show current user info\")\n .action(whoamiCommand);\n\n program\n .command(\"execute [file]\")\n .description(\"Run TypeScript code on the active org's substrate via mcp.clawnify.com\")\n .option(\"-c, --code <inline>\", \"Inline code instead of a file path\")\n .option(\"--timeout <seconds>\", \"Execution timeout in seconds (default 30)\")\n .action(executeCommand);\n\n program\n .command(\"docs [slug]\")\n .description(\"Fetch the skill-convention README for an app (or org index if slug omitted)\")\n .option(\"--caller <hint>\", \"Caller density hint: internal | dashboard | external\", \"external\")\n .action(docsCommand);\n\n program\n .command(\"mcp\")\n .description(\"Run a stdio MCP bridge that proxies to mcp.clawnify.com (for Claude Desktop / ChatGPT / bash-less clients)\")\n .action(mcpBridgeCommand);\n\n // `clawnify skills` — install Clawnify-curated skills (build-a-clawnify-app, ...)\n // into whichever coding agents have rules dirs in cwd (.claude, .cursor,\n // .openclaw, .codex, Aider CONVENTIONS.md). Skill contents are bundled in\n // the CLI; upgrade by bumping the CLI and re-running.\n const skills = program.command(\"skills\").description(\"Install Clawnify-curated skills into your coding agent(s)\");\n skills.command(\"list\").description(\"List available skills\").action(skillsListCommand);\n skills\n .command(\"add [name]\")\n .description(\"Install a skill into every detected agent (Claude, Cursor, OpenClaw, Codex, Aider)\")\n .option(\"--all\", \"Install every available skill\")\n .option(\"--agent <agent>\", \"Force a specific target (claude | cursor | openclaw | codex | aider)\")\n .action((name, opts) => skillsAddCommand(name, opts));\n skills\n .command(\"remove [name]\")\n .description(\"Remove a previously-installed skill from detected agents\")\n .option(\"--all\", \"Remove every installed skill\")\n .option(\"--agent <agent>\", \"Restrict to a specific agent\")\n .action((name, opts) => skillsRemoveCommand(name, opts));\n\n // `clawnify ai-files` — one step to make a project agent-ready: writes\n // the always-on Clawnify rules block into each detected agent's rules\n // file, installs the bundled skills, and wires the MCP server into\n // .mcp.json. Mirrors `npx convex ai-files install`.\n const aiFiles = program\n .command(\"ai-files\")\n .description(\"Install Clawnify rules + skills + MCP into your coding agent(s)\");\n aiFiles\n .command(\"install\")\n .description(\"Write rules, install skills, and wire the MCP server (defaults to Claude if no agent is detected)\")\n .option(\"--agent <agent>\", \"Force a specific target (claude | cursor | openclaw | codex | aider)\")\n .option(\"--no-mcp\", \"Skip writing .mcp.json\")\n .action((opts) => aiFilesInstallCommand(opts));\n aiFiles\n .command(\"uninstall\")\n .description(\"Remove the Clawnify rules block, skills, and MCP server entry\")\n .option(\"--agent <agent>\", \"Restrict to a specific agent\")\n .action((opts) => aiFilesUninstallCommand(opts));\n\n const sdk = program.command(\"sdk\").description(\"Inspect and manage the per-org SDK surface\");\n sdk\n .command(\"inspect <slug>\")\n .description(\"Show the typed-procedure README for an app (external density)\")\n .option(\"--caller <hint>\", \"Caller density hint: internal | dashboard | external\", \"external\")\n .action(sdkInspectCommand);\n sdk\n .command(\"login\")\n .description(\"Authenticate / rotate the OAuth grant (alias of `clawnify login`)\")\n .action(sdkLoginCommand);\n sdk\n .command(\"install\")\n .description(\"(Deferred) Install @clawnify/sdk locally — pending Phase 5b\")\n .action(sdkInstallCommand);\n\n try {\n await program.parseAsync();\n } catch (err) {\n console.error((err as Error)?.message ?? err);\n process.exitCode = 1;\n }\n\n // Force a prompt exit once a one-shot command finishes. Node's global\n // `fetch` (undici) keeps HTTP connections alive in a pool, which holds the\n // event loop open for several seconds after the command is actually done —\n // that's the \"deploy printed ✓ but the prompt doesn't come back\" hang.\n // Long-running commands (`dev`, `mcp`) never resolve `parseAsync`, so they\n // never reach this and keep running. Flush stdout first (the empty write's\n // callback fires after all prior writes drain) so piped/non-TTY output isn't\n // truncated by the exit.\n await new Promise<void>((resolve) => process.stdout.write(\"\", () => resolve()));\n process.exit(process.exitCode ?? 0);\n}\n","import crypto from \"node:crypto\";\nimport http from \"node:http\";\nimport readline from \"node:readline\";\nimport open from \"open\";\nimport {\n saveAuth,\n generatePkce,\n OAUTH_AUTHORIZE_URL,\n OAUTH_TOKEN_URL,\n OAUTH_CLIENT_ID,\n} from \"../lib/auth.js\";\n\nconst CALLBACK_PORT = 19823;\nconst LOCAL_REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/callback`;\nconst HOSTED_REDIRECT_URI = \"https://app.clawnify.com/oauth/cli\";\nconst WEB_ORIGIN = \"https://app.clawnify.com\";\n\ninterface AuthCode {\n code: string;\n redirectUri: string; // the redirect_uri the code was issued for\n}\n\n/**\n * Waits for the authorization code from whichever source responds first:\n * - the local server receiving the OAuth redirect directly (the browser\n * we opened uses the localhost redirect_uri — classic seamless flow)\n * - the local server receiving a notify fetch from the hosted /oauth/cli\n * page (user opened the printed URL in a same-machine browser)\n * - the \"Paste code here\" prompt (any browser, e.g. over SSH)\n *\n * The two flows use distinct `state` values, which is how we know which\n * redirect_uri to use in the token exchange.\n */\nfunction waitForCode(stateLocal: string, stateRemote: string): Promise<AuthCode> {\n return new Promise((resolve, reject) => {\n let done = false;\n let rl: readline.Interface | null = null;\n\n const server = http.createServer((req, res) => {\n const url = new URL(req.url!, `http://127.0.0.1:${CALLBACK_PORT}`);\n\n // Chrome sends a private-network CORS preflight before the https\n // page may fetch a 127.0.0.1 URL.\n const corsHeaders: Record<string, string> = {\n \"Access-Control-Allow-Origin\": WEB_ORIGIN,\n \"Access-Control-Allow-Methods\": \"GET, OPTIONS\",\n \"Access-Control-Allow-Private-Network\": \"true\",\n };\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204, corsHeaders);\n res.end();\n return;\n }\n\n if (url.pathname !== \"/callback\") {\n res.writeHead(404, corsHeaders);\n res.end(\"Not found\");\n return;\n }\n\n const code = url.searchParams.get(\"code\");\n const returnedState = url.searchParams.get(\"state\");\n const error = url.searchParams.get(\"error\");\n\n // Direct OAuth redirect (browser we opened, localhost redirect_uri):\n // respond with human-facing HTML.\n if (returnedState === stateLocal) {\n if (error || !code) {\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n \"<html><body><h2>Authorization denied.</h2><p>You can close this window.</p></body></html>\"\n );\n finish(new Error(`Authorization denied: ${error ?? \"no code returned\"}`));\n return;\n }\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n \"<html><body><h2>Logged in!</h2><p>You can close this window and return to the terminal.</p></body></html>\"\n );\n finish(null, { code, redirectUri: LOCAL_REDIRECT_URI });\n return;\n }\n\n // Notify fetch from the hosted /oauth/cli page (hosted redirect_uri):\n // respond with JSON for the page's script.\n if (returnedState === stateRemote && code) {\n res.writeHead(200, { ...corsHeaders, \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ ok: true }));\n finish(null, { code, redirectUri: HOSTED_REDIRECT_URI });\n return;\n }\n\n res.writeHead(400, { ...corsHeaders, \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ ok: false }));\n });\n\n const timeout = setTimeout(() => {\n finish(new Error(\"Timed out waiting for authorization.\"));\n }, 5 * 60 * 1000);\n\n function finish(err: Error | null, result?: AuthCode) {\n if (done) return;\n done = true;\n clearTimeout(timeout);\n server.close();\n rl?.close();\n if (err) reject(err);\n else resolve(result!);\n }\n\n // If the port is taken (another login, another tool), the paste\n // prompt still works — don't fail the whole flow.\n server.on(\"error\", () => {});\n server.listen(CALLBACK_PORT);\n\n rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n rl.question(\"Paste code here if prompted > \", (answer) => {\n const input = answer.trim();\n if (!input) {\n finish(new Error(\"No code provided.\"));\n return;\n }\n const [code, pastedState] = input.split(\"#\");\n if (!code || pastedState !== stateRemote) {\n finish(new Error(\"Invalid code. Run `clawnify login` to try again.\"));\n return;\n }\n finish(null, { code, redirectUri: HOSTED_REDIRECT_URI });\n });\n });\n}\n\nexport async function loginCommand(): Promise<void> {\n const { codeVerifier: verifier, codeChallenge: challenge } = generatePkce();\n const stateLocal = crypto.randomBytes(16).toString(\"hex\");\n const stateRemote = crypto.randomBytes(16).toString(\"hex\");\n\n const buildAuthUrl = (redirectUri: string, state: string): string => {\n const url = new URL(OAUTH_AUTHORIZE_URL);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", OAUTH_CLIENT_ID);\n url.searchParams.set(\"redirect_uri\", redirectUri);\n url.searchParams.set(\"code_challenge\", challenge);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n url.searchParams.set(\"scope\", \"openid email\");\n url.searchParams.set(\"state\", state);\n return url.toString();\n };\n\n // The browser we open completes via the localhost redirect (seamless);\n // the printed URL works from any browser via the hosted code page.\n const localAuthUrl = buildAuthUrl(LOCAL_REDIRECT_URI, stateLocal);\n const hostedAuthUrl = buildAuthUrl(HOSTED_REDIRECT_URI, stateRemote);\n\n console.log(\"Opening browser to authorize...\");\n console.log(\"\\nBrowser didn't open? Use the url below to sign in:\\n\");\n console.log(` ${hostedAuthUrl}\\n`);\n open(localAuthUrl).catch(() => {\n // No browser available (SSH/headless) — the printed URL is the fallback\n });\n\n const { code, redirectUri } = await waitForCode(stateLocal, stateRemote);\n\n const tokenRes = await fetch(OAUTH_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"authorization_code\",\n code,\n client_id: OAUTH_CLIENT_ID,\n redirect_uri: redirectUri,\n code_verifier: verifier,\n }),\n });\n\n if (!tokenRes.ok) {\n const err = await tokenRes.text();\n throw new Error(`Token exchange failed: ${err}`);\n }\n\n const result = (await tokenRes.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n token_type: string;\n };\n\n // Decode JWT to get email\n let email = \"unknown\";\n try {\n const payload = JSON.parse(\n Buffer.from(result.access_token.split(\".\")[1], \"base64\").toString()\n );\n email = payload.email || \"unknown\";\n } catch {\n // ignore decode errors\n }\n\n const expiresAt = Math.floor(Date.now() / 1000) + result.expires_in;\n\n // Org linking is lazy: the first command that needs an org prompts once\n // (ensureOrg in lib/api.ts) and persists it. `clawnify org use` switches.\n saveAuth({\n access_token: result.access_token,\n refresh_token: result.refresh_token,\n expires_at: expiresAt,\n });\n\n console.log(`Logged in as ${email}`);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport readline from \"node:readline\";\nimport { spawn } from \"node:child_process\";\nimport { api, listMyOrgs } from \"../lib/api.js\";\nimport { createArchive } from \"../lib/archive.js\";\nimport {\n findWorkspaceRoot,\n manifestKind,\n readManifest,\n readProject,\n readWorkspaceConfig,\n saveProject,\n type ProjectConfig,\n} from \"../lib/config.js\";\nimport { pollUntilReady } from \"../lib/poll.js\";\nimport { fetchSchema, writeSchema } from \"../lib/sync-schema.js\";\n\ninterface DeploySuccess {\n app_id: string;\n slug: string;\n app_token: string;\n}\n\ninterface SlugConflict {\n error: \"slug_exists_in_org\";\n existing_app_id: string;\n existing_app_name: string;\n slug: string;\n suggested_slug: string;\n}\n\nexport interface DeployOptions {\n from?: string;\n path?: string;\n name?: string;\n org?: string;\n yes?: boolean;\n updateExisting?: boolean;\n createNew?: boolean;\n dryRun?: boolean;\n noSync?: boolean;\n /** Agent deploy: the server + named agent to push this member to. Saved as a\n * link on first deploy, then reused. */\n server?: string;\n agent?: string;\n}\n\n// Exit codes: keep separate ones so CI/agents can branch on outcome.\nconst EXIT_USAGE = 64;\nconst EXIT_CONFLICT_NEEDS_DECISION = 75;\n\nfunction ask(question: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nasync function uploadDeploy(\n archive: Buffer,\n name: string,\n framework: string,\n orgId?: string,\n): Promise<{ ok: true; data: DeploySuccess } | { ok: false; conflict: SlugConflict } | { ok: false; error: string }> {\n const formData = new FormData();\n formData.append(\"source\", new Blob([archive]), \"source.tar.gz\");\n formData.append(\"name\", name);\n formData.append(\"framework\", framework);\n\n const res = await api.postForm(\"/v1/apps/deploy\", formData, { orgId });\n if (res.ok) {\n const data = (await res.json()) as DeploySuccess;\n return { ok: true, data };\n }\n if (res.status === 409) {\n const conflict = (await res.json()) as SlugConflict;\n return { ok: false, conflict };\n }\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n return { ok: false, error: err.error || res.statusText };\n}\n\nasync function uploadRedeploy(\n appId: string,\n archive: Buffer,\n orgId?: string,\n): Promise<{ ok: true; data: DeploySuccess } | { ok: false; error: string }> {\n const formData = new FormData();\n formData.append(\"source\", new Blob([archive]), \"source.tar.gz\");\n\n const res = await api.postForm(`/v1/apps/${appId}/redeploy`, formData, { orgId });\n if (res.ok) {\n const data = (await res.json()) as DeploySuccess;\n return { ok: true, data };\n }\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n return { ok: false, error: err.error || res.statusText };\n}\n\nfunction assertNodeVersion() {\n const [major] = process.versions.node.split(\".\").map(Number);\n if (major < 22) {\n console.error(\n `\\n Clawnify requires Node.js v22 or later.\\n` +\n ` You are using v${process.versions.node}.\\n\\n` +\n ` Install a newer version: https://nodejs.org\\n` +\n ` Or use a version manager: nvm use 22\\n`\n );\n process.exit(1);\n }\n}\n\nasync function resolveOrgId(\n options: DeployOptions,\n linkedProject: ProjectConfig | null,\n resolvedDir?: string,\n): Promise<string | undefined> {\n if (options.org) {\n const orgs = await listMyOrgs();\n const match = orgs.find((o) => o.id === options.org || o.slug === options.org);\n if (!match) {\n console.error(\n `No org matched \"${options.org}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(EXIT_USAGE);\n }\n if (linkedProject?.org_id && linkedProject.org_id !== match.id) {\n console.error(\n `This folder is linked to a different org (${linkedProject.org_slug ?? linkedProject.org_id}).\\n` +\n ` --org ${options.org} resolves to ${match.id}.\\n` +\n ` Re-link with \\`clawnify link\\`, or deploy from another directory.`,\n );\n process.exit(1);\n }\n return match.id;\n }\n // Honor the folder link's org_id whenever present (app linked or not). A\n // truly unlinked folder falls through to the workspace org (below), then the\n // global active org.\n if (linkedProject?.org_id) {\n return linkedProject.org_id;\n }\n // A fresh (unlinked) target inside a workspace deploys to the workspace's\n // org, not whatever global active org happens to be set. Once linked (above),\n // that link wins and this is skipped.\n if (resolvedDir) {\n const wsOrg = await workspaceOrgId(resolvedDir);\n if (wsOrg) return wsOrg;\n }\n return undefined;\n}\n\n/**\n * Resolve the org a workspace is bound to (slug or id in its clawnify.json),\n * or undefined if `resolvedDir` is not inside a workspace. Exits with a clear\n * error if the workspace names an org the user can't access.\n */\nasync function workspaceOrgId(resolvedDir: string): Promise<string | undefined> {\n const ws = findWorkspaceRoot(resolvedDir);\n if (!ws?.org) return undefined;\n const orgs = await listMyOrgs();\n const match = orgs.find((o) => o.id === ws.org || o.slug === ws.org);\n if (!match) {\n console.error(\n `This workspace is bound to org \"${ws.org}\", but you're not a member of it ` +\n `(or it no longer exists).\\n Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(EXIT_USAGE);\n }\n return match.id;\n}\n\ntype ConflictDecision = \"update\" | \"create\" | \"cancel\";\n\nasync function resolveConflictDecision(\n options: DeployOptions,\n conflict: SlugConflict,\n): Promise<ConflictDecision> {\n if (options.updateExisting) return \"update\";\n if (options.createNew) return \"create\";\n if (options.yes) return \"update\";\n\n if (!process.stdin.isTTY) {\n console.error(\n `\\n Slug '${conflict.slug}' is taken in this organization.\\n` +\n ` Pass one of:\\n` +\n ` --update-existing overwrite the existing app\\n` +\n ` --create-new deploy as '${conflict.suggested_slug}'\\n` +\n ` --yes default to update (safest)\\n`,\n );\n process.exit(EXIT_CONFLICT_NEEDS_DECISION);\n }\n\n console.log(\n `\\n Slug '${conflict.slug}' is taken in this organization` +\n ` (currently held by an app named '${conflict.existing_app_name}').\\n`,\n );\n console.log(` 1) Update that app — deploy this source over it`);\n console.log(` 2) Create a new app at slug '${conflict.suggested_slug}'\\n`);\n const answer = await ask(\" Choose [1/2] (default 1): \");\n\n if (answer === \"\" || answer === \"1\") return \"update\";\n if (answer === \"2\") return \"create\";\n\n console.error(\n `\\n Cancelled. Received '${answer}' — expected 1 or 2.\\n` +\n ` For non-interactive use, pass --update-existing or --create-new.\\n`,\n );\n return \"cancel\";\n}\n\nfunction summarizeArchive(buf: Buffer, files: string[], framework: string, name: string) {\n const sizeKB = (buf.length / 1024).toFixed(1);\n console.log(`\\n Dry run — would deploy '${name}' (${framework})`);\n console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped\\n`);\n const preview = files.slice(0, 25);\n for (const f of preview) console.log(` ${f}`);\n if (files.length > preview.length) {\n console.log(` ... and ${files.length - preview.length} more`);\n }\n console.log();\n}\n\ninterface WebsiteDeployResponse {\n website_id: string;\n slug: string;\n status: string;\n url: string;\n}\n\nasync function uploadWebsiteDeploy(\n archive: Buffer,\n name: string | undefined,\n orgId?: string,\n): Promise<\n | { ok: true; data: WebsiteDeployResponse }\n | { ok: false; error: string }\n> {\n const formData = new FormData();\n formData.append(\"source\", new Blob([archive]), \"source.tar.gz\");\n if (name) formData.append(\"name\", name);\n\n const res = await api.postForm(\"/v1/websites/deploy\", formData, { orgId });\n if (res.ok) {\n const data = (await res.json()) as WebsiteDeployResponse;\n return { ok: true, data };\n }\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n return { ok: false, error: err.error || res.statusText };\n}\n\nasync function deployWebsite(dir: string | undefined, options: DeployOptions): Promise<void> {\n if (options.from) {\n console.error(\"--from is app-only for now. Run `clawnify deploy` inside the website project directory.\");\n process.exit(EXIT_USAGE);\n }\n\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n const manifest = readManifest(resolvedDir);\n const baseName = options.name || manifest?.name || path.basename(resolvedDir);\n const linkedProject = readProject(resolvedDir);\n const { archive, files } = createArchive(resolvedDir);\n\n // Org resolution mirrors the app path. A linked website's org_id wins\n // unless the user passed --org explicitly.\n let orgId: string | undefined;\n if (options.org) {\n const orgs = await listMyOrgs();\n const match = orgs.find((o) => o.id === options.org || o.slug === options.org);\n if (!match) {\n console.error(\n `No org matched \"${options.org}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(EXIT_USAGE);\n }\n if (linkedProject?.website_id && linkedProject.org_id && linkedProject.org_id !== match.id) {\n console.error(\n `This project is linked to a different org (${linkedProject.org_id}).\\n` +\n ` --org ${options.org} resolves to ${match.id}.`,\n );\n process.exit(1);\n }\n orgId = match.id;\n } else if (linkedProject?.website_id && linkedProject.org_id) {\n orgId = linkedProject.org_id;\n } else {\n // Fresh website inside a workspace → deploy to the workspace's org.\n orgId = await workspaceOrgId(resolvedDir);\n }\n\n if (options.dryRun) {\n const sizeKB = (archive.length / 1024).toFixed(1);\n console.log(`\\n Dry run — would deploy website '${baseName}' (astro)`);\n console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped\\n`);\n const preview = files.slice(0, 25);\n for (const f of preview) console.log(` ${f}`);\n if (files.length > preview.length) {\n console.log(` ... and ${files.length - preview.length} more`);\n }\n console.log();\n return;\n }\n\n console.log(linkedProject?.website_id ? `Updating ${baseName}...` : `Deploying ${baseName}...`);\n const result = await uploadWebsiteDeploy(archive, baseName, orgId);\n if (!result.ok) {\n console.error(`Deploy failed: ${result.error}`);\n process.exit(1);\n }\n\n saveProject(resolvedDir, {\n kind: \"website\",\n org_id: orgId,\n website_id: result.data.website_id,\n slug: result.data.slug,\n });\n\n const polled = await pollUntilReady(result.data.website_id, {\n kind: \"website\",\n orgId,\n });\n if (polled.status === \"error\") {\n console.error(`\\n Deploy failed: ${polled.error || \"Unknown error\"}\\n`);\n process.exit(1);\n }\n\n // Draft-first: the deploy lands on the draft tier (status 'preview').\n // Publishing to the live URL is an explicit action from the dashboard.\n if (polled.status === \"live\") {\n console.log(`\\n ✓ Published! ${result.data.url}\\n`);\n } else {\n console.log(\n `\\n ✓ Deployed to draft.\\n` +\n ` Review it in the dashboard, then \"Publish to live\" when ready.\\n`,\n );\n }\n}\n\ninterface AgentFile {\n path: string;\n content: string;\n}\n\n/** Recursively collect files under `root`, yielding each with a forward-slash\n * path relative to `root`. Silent no-op if `root` doesn't exist. */\nfunction walkFiles(root: string, cb: (rel: string, abs: string) => void): void {\n if (!fs.existsSync(root)) return;\n const walk = (cur: string, prefix: string) => {\n for (const name of fs.readdirSync(cur)) {\n const abs = path.join(cur, name);\n const rel = prefix ? `${prefix}/${name}` : name;\n if (fs.statSync(abs).isDirectory()) walk(abs, rel);\n else cb(rel, abs);\n }\n };\n walk(root, \"\");\n}\n\n/** Assemble an agent member's deployable payload: AGENT.md → AGENTS.md (the\n * file OpenClaw loads as instructions), every file under skills/, and the\n * top-level flows/*.json. Paths use forward slashes to match the hook's\n * allowlist. .gitkeep placeholders are skipped. */\nfunction assembleAgentFiles(dir: string): AgentFile[] {\n const out: AgentFile[] = [];\n\n const agentMd = path.join(dir, \"AGENT.md\");\n if (fs.existsSync(agentMd)) {\n out.push({ path: \"AGENTS.md\", content: fs.readFileSync(agentMd, \"utf8\") });\n }\n\n walkFiles(path.join(dir, \"skills\"), (rel, abs) => {\n if (path.basename(abs) === \".gitkeep\") return;\n out.push({ path: `skills/${rel}`, content: fs.readFileSync(abs, \"utf8\") });\n });\n\n const flowsDir = path.join(dir, \"flows\");\n if (fs.existsSync(flowsDir)) {\n for (const name of fs.readdirSync(flowsDir)) {\n if (!name.endsWith(\".json\")) continue;\n out.push({ path: `flows/${name}`, content: fs.readFileSync(path.join(flowsDir, name), \"utf8\") });\n }\n }\n\n return out;\n}\n\n/**\n * Deploy a workspace agent member: push AGENTS.md + skills/ + flows/ to a\n * named agent on a linked server. The link (server + agent name) is provided\n * once via --server/--agent and saved to .clawnify/project.json, then reused.\n * The push is additive on the VPS — it never deletes agent-authored files.\n */\nasync function deployAgent(dir: string | undefined, options: DeployOptions): Promise<void> {\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n const linked = readProject(resolvedDir);\n\n const serverId = options.server || linked?.server_id;\n const agentName = options.agent || linked?.agent_name || \"main\";\n if (!serverId) {\n console.error(\n \"This agent isn't linked to a server yet.\\n\" +\n \" Link it on first deploy:\\n\" +\n \" clawnify deploy --server <server-id> --agent <name>\\n\" +\n \" (agent defaults to \\\"main\\\" if omitted).\",\n );\n process.exit(EXIT_USAGE);\n }\n\n const files = assembleAgentFiles(resolvedDir);\n if (files.length === 0) {\n console.error(\n `Nothing to deploy — no AGENT.md, skills/, or flows/ found in ${resolvedDir}.`,\n );\n process.exit(EXIT_USAGE);\n }\n\n // Org: explicit --org wins, else the saved link's org, else the workspace's.\n let orgId: string | undefined;\n if (options.org) {\n const orgs = await listMyOrgs();\n const match = orgs.find((o) => o.id === options.org || o.slug === options.org);\n if (!match) {\n console.error(\n `No org matched \"${options.org}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(EXIT_USAGE);\n }\n orgId = match.id;\n } else {\n orgId = linked?.org_id || (await workspaceOrgId(resolvedDir));\n }\n\n if (options.dryRun) {\n console.log(`\\n Dry run — would deploy to server ${serverId}, agent \"${agentName}\"`);\n for (const f of files) {\n console.log(` ${f.path} (${Buffer.byteLength(f.content, \"utf8\")} bytes)`);\n }\n console.log();\n return;\n }\n\n console.log(`Deploying agent → server ${serverId}, agent \"${agentName}\"...`);\n const res = await api.post(\n `/servers/${serverId}/deploy-agent`,\n { agent: agentName, files },\n { orgId },\n );\n const data = (await res.json().catch(() => ({}))) as {\n error?: string;\n written?: string[];\n rejected?: string[];\n };\n if (!res.ok) {\n console.error(`Deploy failed: ${data.error || res.statusText}`);\n process.exit(1);\n }\n\n saveProject(resolvedDir, {\n kind: \"agent\",\n org_id: orgId,\n server_id: serverId,\n agent_name: agentName,\n });\n\n const written = data.written ?? [];\n const rejected = (data.rejected ?? []).filter(Boolean);\n console.log(`\\n ✓ Deployed ${written.length} file(s) to agent \"${agentName}\".`);\n if (rejected.length) {\n console.log(` Skipped (outside the agent payload allowlist): ${rejected.join(\", \")}`);\n }\n console.log();\n}\n\nexport async function deployCommand(\n dir?: string,\n options: DeployOptions = {},\n): Promise<void> {\n assertNodeVersion();\n\n // Dispatch on manifest kind early — websites take a completely different\n // path (no slug conflicts, no schema sync, different API endpoint).\n if (!options.from) {\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n const manifest = readManifest(resolvedDir);\n // A workspace root is a monorepo of apps, not a deployable app itself.\n // Refuse to tar the whole tree; point the user at a specific app.\n if (!manifest && readWorkspaceConfig(resolvedDir)) {\n console.error(\n \"This is a Clawnify workspace root, not an app.\\n\" +\n \" Deploy a specific app: clawnify deploy apps/<name>\\n\" +\n \" Or cd into one: cd apps/<name> && clawnify deploy\",\n );\n process.exit(EXIT_USAGE);\n }\n if (manifest) {\n try {\n const kind = manifestKind(manifest);\n if (kind === \"website\") {\n return deployWebsite(dir, options);\n }\n if (kind === \"agent\") {\n return deployAgent(dir, options);\n }\n } catch (err) {\n console.error(`${(err as Error).message}`);\n process.exit(EXIT_USAGE);\n }\n }\n // No manifest → fall through to the app path (it tolerates a missing\n // manifest by defaulting framework to vite-preact).\n }\n\n let appId: string;\n let slug: string;\n let appToken: string;\n let resolvedOrgId: string | undefined;\n let syncTargetDir: string | undefined;\n\n if (options.from) {\n const repo = options.from.replace(/^github:/, \"\");\n const subdir = options.path?.trim().replace(/^\\/+|\\/+$/g, \"\") || undefined;\n if (options.dryRun) {\n console.log(\n `\\n Dry run — would deploy from GitHub repo '${repo}' (branch: main${subdir ? `, path: ${subdir}` : \"\"})\\n`,\n );\n return;\n }\n console.log(`Deploying from ${repo}${subdir ? `/${subdir}` : \"\"}...`);\n\n const orgId = options.org ? (await resolveOrgId(options, null)) : undefined;\n const res = await api.post(\"/v1/apps/deploy\", { repo, branch: \"main\", subdir }, { orgId });\n if (!res.ok) {\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n console.error(`Deploy failed: ${err.error || res.statusText}`);\n process.exit(1);\n }\n\n const data = (await res.json()) as DeploySuccess;\n appId = data.app_id;\n slug = data.slug;\n appToken = data.app_token;\n resolvedOrgId = orgId;\n // syncTargetDir intentionally left undefined: deploying from a remote\n // repo has no canonical local directory to mirror back into.\n } else {\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n syncTargetDir = resolvedDir;\n const manifest = readManifest(resolvedDir);\n const baseName = options.name || manifest?.name || path.basename(resolvedDir);\n const framework = manifest?.app?.framework || \"vite-preact\";\n const linkedProject = readProject(resolvedDir);\n await regenerateDrizzleMigrations(resolvedDir);\n const { archive, files } = createArchive(resolvedDir);\n const orgId = await resolveOrgId(options, linkedProject, resolvedDir);\n\n if (options.dryRun) {\n summarizeArchive(archive, files, framework, baseName);\n if (linkedProject?.app_id) {\n console.log(` Would update existing app: ${linkedProject.slug ?? linkedProject.app_id}\\n`);\n } else {\n console.log(` Would create new app: ${baseName}\\n`);\n }\n return;\n }\n\n if (linkedProject?.app_id) {\n console.log(`Updating ${baseName} (${linkedProject.slug ?? linkedProject.app_id})...`);\n const result = await uploadRedeploy(linkedProject.app_id, archive, orgId);\n if (!result.ok) {\n console.error(`Deploy failed: ${result.error}`);\n process.exit(1);\n }\n appId = result.data.app_id;\n slug = result.data.slug;\n appToken = result.data.app_token;\n saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });\n } else {\n console.log(`Deploying ${baseName}...`);\n let result = await uploadDeploy(archive, baseName, framework, orgId);\n\n if (!result.ok && \"conflict\" in result) {\n const decision = await resolveConflictDecision(options, result.conflict);\n\n if (decision === \"update\") {\n const redeployResult = await uploadRedeploy(result.conflict.existing_app_id, archive, orgId);\n if (!redeployResult.ok) {\n console.error(`Deploy failed: ${redeployResult.error}`);\n process.exit(1);\n }\n appId = redeployResult.data.app_id;\n slug = redeployResult.data.slug;\n appToken = redeployResult.data.app_token;\n } else if (decision === \"create\") {\n result = await uploadDeploy(archive, result.conflict.suggested_slug, framework, orgId);\n if (!result.ok) {\n const errMsg = \"conflict\" in result ? \"Slug still conflicts\" : result.error;\n console.error(`Deploy failed: ${errMsg}`);\n process.exit(1);\n }\n appId = result.data.app_id;\n slug = result.data.slug;\n appToken = result.data.app_token;\n } else {\n process.exit(EXIT_CONFLICT_NEEDS_DECISION);\n }\n } else if (!result.ok) {\n console.error(`Deploy failed: ${result.error}`);\n process.exit(1);\n } else {\n appId = result.data.app_id;\n slug = result.data.slug;\n appToken = result.data.app_token;\n }\n\n saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });\n resolvedOrgId = orgId;\n }\n }\n\n const result = await pollUntilReady(appId);\n\n if (result.status === \"error\") {\n console.error(`\\n Deploy failed: ${result.error || \"Unknown error\"}\\n`);\n process.exit(1);\n }\n\n const url = `https://${slug}.apps.clawnify.com`;\n console.log(`\\n ✓ Deployed! ${url}\\n`);\n console.log(` Open: clawnify open ${slug}\\n`);\n\n // Auto-sync schema.sql from the deployed app back into the local repo\n // so the local copy mirrors the deployed schema after migrations apply.\n // Skipped when deploying from a remote --from <repo> (no local dir to\n // sync into) or when --no-sync is passed. Failures here don't fail the\n // deploy — the deploy itself already succeeded.\n if (syncTargetDir && !options.noSync && resolvedOrgId) {\n try {\n const schema = await fetchSchema({ appId, orgId: resolvedOrgId });\n const target = path.join(syncTargetDir, \"schema.sql\");\n const writeResult = await writeSchema(target, schema);\n const rel = path.relative(process.cwd(), writeResult.path) || writeResult.path;\n switch (writeResult.status) {\n case \"written\":\n console.log(` Synced ${rel} (${writeResult.bytes} bytes)\\n`);\n break;\n case \"refused-uncommitted\":\n console.log(\n ` ${rel} has uncommitted changes — not overwriting.\\n` +\n ` Run \\`clawnify pull schema --force --from ${slug}\\` to overwrite.\\n`,\n );\n break;\n case \"refused-different\":\n console.log(\n ` ${rel} differs from the deployed copy (not in git).\\n` +\n ` Run \\`clawnify pull schema --force --from ${slug}\\` to overwrite.\\n`,\n );\n break;\n case \"no-schema\":\n case \"unchanged\":\n // Silent — nothing to report.\n break;\n }\n } catch (err) {\n console.log(` (schema sync skipped: ${(err as Error).message})\\n`);\n }\n }\n}\n\n/**\n * Run `drizzle-kit generate` so .clawnify/drizzle/*.sql is current\n * with src/server/schema.ts. archive.ts auto-includes those files\n * remapped to `drizzle/<file>` in the uploaded tar; the deploy\n * pipeline (PR #444) reads them from R2 and applies via the\n * existing applyPendingMigrations path.\n *\n * No-op for apps that don't use the drizzle path (legacy schema.sql,\n * no schema.ts, or no drizzle.config.ts). Failure is non-fatal:\n * we warn and continue, so a deploy never silently breaks just\n * because a user hasn't set up drizzle-kit yet.\n */\nasync function regenerateDrizzleMigrations(resolvedDir: string): Promise<void> {\n const schemaTs = path.join(resolvedDir, \"src/server/schema.ts\");\n const drizzleConfig = path.join(resolvedDir, \"drizzle.config.ts\");\n if (!fs.existsSync(schemaTs) || !fs.existsSync(drizzleConfig)) return;\n\n await new Promise<void>((resolve) => {\n const proc = spawn(\"npx\", [\"drizzle-kit\", \"generate\"], {\n cwd: resolvedDir,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env },\n });\n let stderr = \"\";\n proc.stderr?.on(\"data\", (d: Buffer) => { stderr += d.toString(); });\n proc.on(\"exit\", (code) => {\n if (code !== 0) {\n console.warn(\n ` warning: drizzle-kit generate failed (${stderr.trim().slice(0, 200)}). ` +\n `Continuing with existing .clawnify/drizzle/ contents.`,\n );\n }\n resolve();\n });\n proc.on(\"error\", () => resolve());\n });\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { api, listMyOrgs, type Org } from \"./api.js\";\n\ninterface AppRef {\n org: Org;\n appId: string;\n slug: string;\n}\n\ninterface AppSummary {\n id: string;\n slug: string;\n name?: string;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Resolve an app id-or-slug against the user's orgs, returning the org +\n * app id/slug. Mirrors the resolution in link.ts so `pull` can be used\n * without a pre-existing `clawnify link`.\n */\nexport async function resolveApp(idOrSlug: string, orgFilter?: string): Promise<AppRef | null> {\n const orgs = await listMyOrgs();\n if (orgs.length === 0) return null;\n\n const candidates = orgFilter\n ? orgs.filter((o) => o.id === orgFilter || o.slug === orgFilter)\n : orgs;\n if (candidates.length === 0) return null;\n\n const isUuid = UUID_RE.test(idOrSlug);\n if (isUuid) {\n for (const org of candidates) {\n const res = await api.get(`/v1/apps/${idOrSlug}`, { orgId: org.id });\n if (res.ok) {\n const app = (await res.json()) as AppSummary;\n return { org, appId: app.id, slug: app.slug };\n }\n }\n return null;\n }\n\n for (const org of candidates) {\n const res = await api.get(`/v1/apps`, { orgId: org.id });\n if (!res.ok) continue;\n const payload = (await res.json()) as { apps?: AppSummary[] } | AppSummary[];\n const apps = Array.isArray(payload) ? payload : payload.apps ?? [];\n const match = apps.find((a) => a.slug === idOrSlug);\n if (match) return { org, appId: match.id, slug: match.slug };\n }\n return null;\n}\n\n/**\n * Fetch the deployed app's current schema.sql snapshot from the API.\n * Returns null if the app has no schema.sql (pre-backfill / no DB).\n *\n * Accepts either a full AppRef (from resolveApp) or a minimal\n * { appId, orgId } pair (from deploy, which already knows both).\n */\nexport async function fetchSchema(\n ref: AppRef | { appId: string; orgId: string },\n): Promise<string | null> {\n const appId = \"appId\" in ref ? ref.appId : (ref as AppRef).appId;\n const orgId = \"orgId\" in ref ? ref.orgId : (ref as AppRef).org.id;\n const res = await api.get(`/v1/apps/${appId}/schema`, { orgId });\n if (!res.ok) {\n if (res.status === 404) return null;\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n throw new Error(`Schema fetch failed: ${err.error ?? res.statusText}`);\n }\n const data = (await res.json()) as { schema_sql: string | null };\n return data.schema_sql;\n}\n\nexport type WriteResult =\n | { status: \"written\"; path: string; bytes: number }\n | { status: \"unchanged\"; path: string }\n | { status: \"no-schema\"; path: string }\n | { status: \"refused-uncommitted\"; path: string }\n | { status: \"refused-different\"; path: string };\n\n/**\n * Write a fetched schema to disk with safety guards.\n *\n * - \"unchanged\" : on-disk file already matches what we'd\n * write; no-op.\n * - \"refused-uncommitted\" : the target file has uncommitted git\n * changes — refuse unless force=true.\n * - \"refused-different\" : the target file differs and we're not\n * in a git repo — refuse unless force=true\n * (otherwise we'd silently clobber unknown\n * local edits).\n * - \"no-schema\" : the deployed app has no schema.sql to\n * fetch; nothing written.\n * - \"written\" : wrote the file.\n */\nexport async function writeSchema(\n targetPath: string,\n schema: string | null,\n options: { force?: boolean } = {},\n): Promise<WriteResult> {\n if (schema === null) {\n return { status: \"no-schema\", path: targetPath };\n }\n\n let existing: string | null = null;\n try {\n existing = await fs.readFile(targetPath, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n\n if (existing === schema) {\n return { status: \"unchanged\", path: targetPath };\n }\n\n if (existing !== null && !options.force) {\n const dir = path.dirname(path.resolve(targetPath));\n if (isInsideGitRepo(dir)) {\n if (hasUncommittedChanges(dir, targetPath)) {\n return { status: \"refused-uncommitted\", path: targetPath };\n }\n } else {\n // Outside git, can't tell intent — be conservative.\n return { status: \"refused-different\", path: targetPath };\n }\n }\n\n await fs.mkdir(path.dirname(targetPath), { recursive: true });\n await fs.writeFile(targetPath, schema, \"utf8\");\n return { status: \"written\", path: targetPath, bytes: schema.length };\n}\n\nfunction isInsideGitRepo(dir: string): boolean {\n try {\n execSync(\"git rev-parse --is-inside-work-tree\", {\n cwd: dir,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction hasUncommittedChanges(dir: string, filePath: string): boolean {\n try {\n const relative = path.relative(dir, path.resolve(filePath));\n const status = execSync(`git status --porcelain -- \"${relative}\"`, {\n cwd: dir,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n return status.length > 0;\n } catch {\n // git not available or other error — treat as uncommitted for safety.\n return true;\n }\n}\n","import { api } from \"../lib/api.js\";\n\ninterface App {\n id: string;\n name: string;\n slug: string;\n status: string;\n}\n\nexport async function lsCommand(): Promise<void> {\n const res = await api.get(\"/v1/apps\");\n if (!res.ok) {\n console.error(\"Failed to list apps.\");\n process.exit(1);\n }\n\n const payload = (await res.json()) as { apps: App[] } | App[];\n const apps = Array.isArray(payload) ? payload : payload.apps;\n\n if (apps.length === 0) {\n console.log(\"No apps deployed yet.\");\n return;\n }\n\n const nameWidth = Math.max(4, ...apps.map((a) => a.name.length));\n const slugWidth = Math.max(4, ...apps.map((a) => a.slug.length));\n\n console.log(\n `${\"Name\".padEnd(nameWidth)} ${\"Slug\".padEnd(slugWidth)} ${\"Status\".padEnd(8)} URL`\n );\n console.log(\n `${\"─\".repeat(nameWidth)} ${\"─\".repeat(slugWidth)} ${\"─\".repeat(8)} ${\"─\".repeat(30)}`\n );\n\n for (const app of apps) {\n const url = `https://${app.slug}.apps.clawnify.com`;\n console.log(\n `${app.name.padEnd(nameWidth)} ${app.slug.padEnd(slugWidth)} ${app.status.padEnd(8)} ${url}`\n );\n }\n}\n","import { api } from \"../lib/api.js\";\n\ninterface AppLogs {\n status: string;\n status_message?: string;\n logs?: string;\n}\n\nexport async function logsCommand(appId: string): Promise<void> {\n const res = await api.get(`/v1/apps/${appId}/logs`);\n if (!res.ok) {\n console.error(\"Failed to fetch logs.\");\n process.exit(1);\n }\n\n const data = (await res.json()) as AppLogs;\n\n console.log(`Status: ${data.status}`);\n if (data.status_message) {\n console.log(`Message: ${data.status_message}`);\n }\n if (data.logs) {\n console.log(\"\\n--- Build Logs ---\\n\");\n console.log(data.logs);\n }\n}\n","import { api } from \"./api.js\";\nimport { readProject } from \"./config.js\";\n\ninterface ServerRow {\n id: string;\n name: string | null;\n status: string;\n}\n\n/**\n * Resolve which agent server to target: --server wins, then a linked project\n * (.clawnify/project.json), then the org's single server. Exits with a clear\n * message when the org has zero or several servers and none was specified.\n * Shared by the `sessions` and `agents` commands.\n */\nexport async function resolveServerId(explicit: string | undefined): Promise<string> {\n if (explicit) return explicit;\n const linked = readProject()?.server_id;\n if (linked) return linked;\n\n const res = await api.get(\"/servers\");\n if (!res.ok) {\n console.error(\"Failed to list servers. Run `clawnify login` and try again.\");\n process.exit(1);\n }\n const { servers } = (await res.json()) as { servers: ServerRow[] };\n if (!servers || servers.length === 0) {\n console.error(\n \"No agent server in this org yet. Provision one at https://app.clawnify.com.\",\n );\n process.exit(1);\n }\n if (servers.length === 1) return servers[0].id;\n\n console.error(\n \"This org has multiple servers — pick one with --server <id> (or run `clawnify servers`):\\n\",\n );\n for (const s of servers) {\n console.error(` ${s.id} ${s.name ?? \"(unnamed)\"} [${s.status}]`);\n }\n process.exit(1);\n}\n","/**\n * `clawnify sessions` — the FDE's observe verb.\n *\n * clawnify sessions [list] list stored sessions across ALL agents on\n * the org's server (main + specialists)\n * clawnify sessions history <key> read one session's transcript by key\n *\n * Backed by the org-scoped GET /servers/:id/sessions[/history] API (read-only,\n * ownership-checked). See docs/internal/fde-strategy.md.\n */\n\nimport { api } from \"../lib/api.js\";\nimport { resolveServerId } from \"../lib/servers.js\";\n\ninterface SessionRow {\n agentId: string;\n key: string;\n sessionId: string | null;\n updatedAt: string | null;\n model: string | null;\n}\n\ninterface ListOptions {\n server?: string;\n agent?: string;\n active?: string;\n limit?: string;\n json?: boolean;\n}\n\ninterface HistoryOptions {\n server?: string;\n agent?: string;\n limit?: string;\n json?: boolean;\n}\n\nexport async function sessionsListCommand(opts: ListOptions): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n\n const params = new URLSearchParams();\n if (opts.agent) params.set(\"agentId\", opts.agent);\n if (opts.active) params.set(\"activeMinutes\", opts.active);\n if (opts.limit) params.set(\"limit\", opts.limit);\n const qs = params.toString();\n\n const res = await api.get(`/servers/${serverId}/sessions${qs ? `?${qs}` : \"\"}`);\n if (!res.ok) {\n console.error(`Failed to list sessions (${res.status}).`);\n process.exit(1);\n }\n const data = (await res.json()) as {\n sessions: SessionRow[];\n totalCount?: number;\n hasMore?: boolean;\n };\n const sessions = data.sessions ?? [];\n\n if (opts.json) {\n console.log(JSON.stringify(data, null, 2));\n return;\n }\n if (sessions.length === 0) {\n console.log(\"No sessions found.\");\n return;\n }\n\n const agentW = Math.max(5, ...sessions.map((s) => (s.agentId ?? \"\").length));\n const keyW = Math.max(3, ...sessions.map((s) => (s.key ?? \"\").length));\n console.log(\n `${\"Agent\".padEnd(agentW)} ${\"Key\".padEnd(keyW)} ${\"Updated\".padEnd(19)} Model`,\n );\n console.log(\n `${\"─\".repeat(agentW)} ${\"─\".repeat(keyW)} ${\"─\".repeat(19)} ${\"─\".repeat(20)}`,\n );\n for (const s of sessions) {\n const updated = (s.updatedAt ?? \"\").replace(\"T\", \" \").slice(0, 19);\n console.log(\n `${(s.agentId ?? \"\").padEnd(agentW)} ${(s.key ?? \"\").padEnd(keyW)} ${updated.padEnd(19)} ${s.model ?? \"\"}`,\n );\n }\n if (data.hasMore) {\n console.log(\n `\\n… more available — raise --limit (showing ${sessions.length}${data.totalCount ? ` of ${data.totalCount}` : \"\"}).`,\n );\n }\n}\n\nexport async function sessionsHistoryCommand(\n key: string,\n opts: HistoryOptions,\n): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n\n const params = new URLSearchParams();\n params.set(\"key\", key);\n if (opts.agent) params.set(\"agentId\", opts.agent);\n if (opts.limit) params.set(\"limit\", opts.limit);\n\n const res = await api.get(\n `/servers/${serverId}/sessions/history?${params.toString()}`,\n );\n if (!res.ok) {\n if (res.status === 404) {\n console.error(\n `No session found for key \"${key}\". List sessions with \\`clawnify sessions\\`.`,\n );\n } else {\n console.error(`Failed to read session (${res.status}).`);\n }\n process.exit(1);\n }\n const data = (await res.json()) as {\n agentId: string;\n key: string;\n sessionId: string | null;\n entries: unknown[];\n entryCount: number;\n totalLines: number;\n hasMore?: boolean;\n };\n\n if (opts.json) {\n console.log(JSON.stringify(data, null, 2));\n return;\n }\n console.log(\n `agent: ${data.agentId} key: ${data.key} session: ${data.sessionId ?? \"?\"}`,\n );\n console.log(\n `${data.entryCount} entr${data.entryCount === 1 ? \"y\" : \"ies\"}${data.hasMore ? ` (of ${data.totalLines}; raise --limit for more)` : \"\"}\\n`,\n );\n // Raw JSONL transcript entries — one per line, so a coding agent can parse\n // them and a human can `| jq`.\n for (const entry of data.entries) {\n console.log(JSON.stringify(entry));\n }\n}\n","/**\n * `clawnify agents` — the FDE's agent-management verbs.\n *\n * clawnify agents [list] list the agents on the org's server\n * clawnify agents pull [dir] fetch an agent's AGENTS.md + skills/ (+ flows/\n * for main only — flows are box-level) to edit\n * clawnify agents push [dir] push the edited files back (additive; the\n * agent picks them up next session, no restart)\n *\n * Backed by GET /servers/:id/agents, GET /servers/:id/agent-config, and\n * POST /servers/:id/deploy-agent. See docs/internal/fde-strategy.md.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { api } from \"../lib/api.js\";\nimport { resolveServerId } from \"../lib/servers.js\";\nimport { readProject, saveProject } from \"../lib/config.js\";\n\ninterface AgentRow {\n id: string;\n name?: string;\n status?: string;\n sessionCount?: number;\n}\n\ninterface AgentFile {\n path: string;\n content: string;\n}\n\ninterface CommonOpts {\n server?: string;\n agent?: string;\n}\n\nexport async function agentsListCommand(opts: { server?: string }): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n const res = await api.get(`/servers/${serverId}/agents`);\n if (!res.ok) {\n console.error(`Failed to list agents (${res.status}).`);\n process.exit(1);\n }\n const payload = (await res.json()) as { agents: AgentRow[] } | AgentRow[];\n const agents = Array.isArray(payload) ? payload : payload.agents;\n if (!agents || agents.length === 0) {\n console.log(\"No agents on this server.\");\n return;\n }\n\n const idW = Math.max(2, ...agents.map((a) => (a.id ?? \"\").length));\n const nameW = Math.max(4, ...agents.map((a) => (a.name ?? \"\").length));\n console.log(`${\"ID\".padEnd(idW)} ${\"Name\".padEnd(nameW)} ${\"Status\".padEnd(8)} Sessions`);\n console.log(`${\"─\".repeat(idW)} ${\"─\".repeat(nameW)} ${\"─\".repeat(8)} ${\"─\".repeat(8)}`);\n for (const a of agents) {\n console.log(\n `${(a.id ?? \"\").padEnd(idW)} ${(a.name ?? \"\").padEnd(nameW)} ${(a.status ?? \"\").padEnd(8)} ${a.sessionCount ?? 0}`,\n );\n }\n}\n\nexport async function agentsPullCommand(dir: string | undefined, opts: CommonOpts): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n const agent = opts.agent || \"main\";\n\n const res = await api.get(`/servers/${serverId}/agent-config?agent=${encodeURIComponent(agent)}`);\n if (!res.ok) {\n if (res.status === 404) console.error(`Agent \"${agent}\" not found on this server.`);\n else console.error(`Failed to read agent config (${res.status}).`);\n process.exit(1);\n }\n const { files } = (await res.json()) as { files: AgentFile[] };\n\n const target = dir ? path.resolve(dir) : process.cwd();\n fs.mkdirSync(target, { recursive: true });\n let written = 0;\n for (const f of files ?? []) {\n // The API only returns AGENTS.md / skills/** / flows/*.json, but guard the\n // returned path against traversal before writing to disk.\n const norm = path.posix.normalize(f.path);\n if (norm.startsWith(\"/\") || norm.split(\"/\").includes(\"..\")) continue;\n const abs = path.join(target, norm);\n fs.mkdirSync(path.dirname(abs), { recursive: true });\n fs.writeFileSync(abs, f.content);\n written++;\n }\n\n // Remember server + agent so `clawnify agents push` targets the same place.\n const existing = readProject(target) ?? {};\n saveProject(target, { ...existing, kind: \"agent\", server_id: serverId, agent_name: agent });\n\n console.log(`Pulled ${written} file(s) for agent \"${agent}\" → ${target}`);\n console.log(`Edit AGENTS.md / skills / flows, then push: clawnify agents push${dir ? ` ${dir}` : \"\"}`);\n}\n\nexport async function agentsPushCommand(dir: string | undefined, opts: CommonOpts): Promise<void> {\n const target = dir ? path.resolve(dir) : process.cwd();\n const linked = readProject(target);\n const serverId = await resolveServerId(opts.server || linked?.server_id);\n const agent = opts.agent || linked?.agent_name || \"main\";\n\n const files: AgentFile[] = [];\n const add = (rel: string) => {\n try {\n files.push({ path: rel, content: fs.readFileSync(path.join(target, rel), \"utf8\") });\n } catch {\n /* file absent — skip */\n }\n };\n add(\"AGENTS.md\");\n const walk = (relDir: string) => {\n let names: string[];\n try {\n names = fs.readdirSync(path.join(target, relDir));\n } catch {\n return;\n }\n for (const name of names) {\n const rel = `${relDir}/${name}`;\n let isDir = false;\n try {\n isDir = fs.statSync(path.join(target, rel)).isDirectory();\n } catch {\n continue;\n }\n if (isDir) walk(rel);\n else add(rel);\n }\n };\n walk(\"skills\");\n let flowNames: string[] = [];\n try {\n flowNames = fs.readdirSync(path.join(target, \"flows\"));\n } catch {\n /* no flows dir */\n }\n for (const name of flowNames) if (name.endsWith(\".json\")) add(`flows/${name}`);\n\n if (files.length === 0) {\n console.error(`No agent files (AGENTS.md / skills / flows) found in ${target}. Run \\`clawnify agents pull\\` first.`);\n process.exit(1);\n }\n\n const res = await api.post(`/servers/${serverId}/deploy-agent`, { agent, files });\n if (!res.ok) {\n console.error(`Failed to push (${res.status}).`);\n process.exit(1);\n }\n console.log(\n `Pushed ${files.length} file(s) to agent \"${agent}\". Additive — the agent picks them up on its next session (no restart).`,\n );\n}\n\nexport async function agentsSkillsCommand(\n agent: string | undefined,\n opts: { server?: string },\n): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n const who = agent || \"main\";\n\n const res = await api.get(`/servers/${serverId}/agent-skills?agent=${encodeURIComponent(who)}`);\n if (!res.ok) {\n if (res.status === 404) console.error(`Agent \"${who}\" not found on this server.`);\n else console.error(`Failed to read skills (${res.status}).`);\n process.exit(1);\n }\n const data = (await res.json()) as { agent: string; skills: unknown };\n\n // The EFFECTIVE inventory (workspace + shared managed-root + bundled, with\n // eligibility) as OpenClaw's loader reports it — richer than what's in the\n // agent's own workspace. Printed as JSON (the shape is OpenClaw's): a coding\n // agent parses it, a human can `| jq`.\n console.log(JSON.stringify(data.skills, null, 2));\n}\n\nexport async function agentsGrantSkillCommand(\n skill: string,\n opts: { server?: string; to?: string; all?: boolean },\n): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n if (!opts.all && !opts.to) {\n console.error(\n \"Specify who gets the skill: --to <agent> (one specialist) or --all (every agent on the box).\",\n );\n process.exit(1);\n }\n const scope = opts.all ? \"tree\" : \"agent\";\n const payload: Record<string, unknown> = { skill, action: \"grant\", scope };\n if (scope === \"agent\") payload.slug = opts.to;\n\n const res = await api.post(`/servers/${serverId}/agent-skills`, payload);\n const data = (await res.json().catch(() => ({}))) as { error?: string };\n if (!res.ok) {\n // Grant symlinks an EXISTING main-workspace skill; a 404 means it isn't\n // authored yet, so point the FDE at the author step instead of a bare error.\n if (res.status === 404 && /source skill not found/i.test(data.error ?? \"\")) {\n console.error(\n `Skill \"${skill}\" isn't in the main agent's workspace, so there's nothing to grant yet.\\n` +\n `Author it first: clawnify agents pull ./main --agent main → add skills/${skill}/SKILL.md → clawnify agents push ./main`,\n );\n } else {\n console.error(`Failed to grant skill (${res.status})${data.error ? `: ${data.error}` : \"\"}.`);\n }\n process.exit(1);\n }\n\n const who = opts.all ? \"every agent (shared managed root; includes future agents)\" : `agent \"${opts.to}\"`;\n console.log(`Granted skill \"${skill}\" to ${who}. Picked up on the agent's next session (no restart). Reversible.`);\n}\n\nexport async function agentsCreateCommand(\n slug: string,\n opts: { server?: string; name?: string; description?: string; yes?: boolean },\n): Promise<void> {\n const serverId = await resolveServerId(opts.server);\n\n // Creating an agent runs several openclaw calls and a synchronous gateway\n // restart (~20-40s) that briefly interrupts every agent on the box. Gate it\n // behind --yes so an autonomous FDE has to consciously confirm the disruption.\n if (!opts.yes) {\n console.error(\n `This creates agent \"${slug}\" and RESTARTS the gateway (~20-40s), briefly interrupting every agent on the server.\\n` +\n `Re-run with --yes once the user has confirmed: clawnify agents create ${slug} --yes`,\n );\n process.exit(1);\n }\n\n const payload: Record<string, unknown> = { slug };\n if (opts.name) payload.name = opts.name;\n if (opts.description) payload.description = opts.description;\n\n const res = await api.post(`/servers/${serverId}/agents`, payload);\n const data = (await res.json().catch(() => ({}))) as { error?: string };\n if (!res.ok) {\n console.error(`Failed to create agent (${res.status})${data.error ? `: ${data.error}` : \"\"}.`);\n process.exit(1);\n }\n console.log(\n `Created agent \"${slug}\". The gateway was restarted and it onboards shortly. ` +\n `Author it with: clawnify agents pull ./${slug} --agent ${slug}`,\n );\n}\n","/**\n * `clawnify servers` — list the org's agent servers. An org can have several\n * (e.g. an agency managing multiple client boxes). This is the top of the\n * discovery tree the FDE walks: servers → `agents` → `sessions`. Backed by\n * GET /servers (org-scoped).\n */\n\nimport { api } from \"../lib/api.js\";\n\ninterface ServerRow {\n id: string;\n name: string | null;\n status: string;\n region?: string | null;\n}\n\nexport async function serversListCommand(): Promise<void> {\n const res = await api.get(\"/servers\");\n if (!res.ok) {\n console.error(`Failed to list servers (${res.status}).`);\n process.exit(1);\n }\n const { servers } = (await res.json()) as { servers: ServerRow[] };\n if (!servers || servers.length === 0) {\n console.log(\"No servers in this org yet. Provision one at https://app.clawnify.com.\");\n return;\n }\n\n const idW = Math.max(2, ...servers.map((s) => s.id.length));\n const nameW = Math.max(4, ...servers.map((s) => (s.name ?? \"\").length));\n console.log(`${\"ID\".padEnd(idW)} ${\"Name\".padEnd(nameW)} ${\"Status\".padEnd(10)} Region`);\n console.log(`${\"─\".repeat(idW)} ${\"─\".repeat(nameW)} ${\"─\".repeat(10)} ${\"─\".repeat(10)}`);\n for (const s of servers) {\n console.log(\n `${s.id.padEnd(idW)} ${(s.name ?? \"\").padEnd(nameW)} ${s.status.padEnd(10)} ${s.region ?? \"\"}`,\n );\n }\n}\n","/**\n * `clawnify env` — the org's custom environment variables, injected into every\n * agent's gateway. Reading is `clawnify connections list` (the customEnv\n * section); this sets/unsets. Org-scoped; setting or removing one restarts the\n * gateway to apply, so agents briefly reconnect.\n *\n * NOT for secrets: don't pass a real API key / secret here from an agent — it\n * exposes the value in the command line and the agent's context. Secrets belong\n * in the dashboard (Settings → Environment Variables / API Keys). Use this only\n * for non-secret config (a flag, a default, a public URL).\n */\n\nimport { api } from \"../lib/api.js\";\n\nexport async function envSetCommand(key: string, value: string): Promise<void> {\n const res = await api.post(\"/settings/custom-keys\", { key_name: key, key_value: value });\n const data = (await res.json().catch(() => ({}))) as { error?: string };\n if (!res.ok) {\n console.error(`Failed to set ${key} (${res.status})${data.error ? `: ${data.error}` : \"\"}.`);\n process.exit(1);\n }\n console.log(`Set ${key} org-wide. The gateway restarts to apply — agents briefly reconnect.`);\n}\n\nexport async function envUnsetCommand(key: string): Promise<void> {\n const res = await api.del(`/settings/custom-keys/${encodeURIComponent(key)}`);\n if (!res.ok) {\n const data = (await res.json().catch(() => ({}))) as { error?: string };\n console.error(`Failed to unset ${key} (${res.status})${data.error ? `: ${data.error}` : \"\"}.`);\n process.exit(1);\n }\n console.log(`Removed ${key} org-wide. The gateway restarts to apply.`);\n}\n","/**\n * `clawnify api <path>` — a raw authenticated request to the Clawnify API.\n * The escape hatch (à la `gh api` / `stripe get`): the porcelain covers the\n * common paths; this reaches anything without a dedicated command, so the CLI\n * never has to be complete to be useful. Same auth + org scoping as every other\n * command — it can only do what you can do.\n *\n * clawnify api /servers\n * clawnify api /servers/<id>/agents\n * clawnify api /servers/<id>/deploy-agent -X POST -d '{\"agent\":\"main\",\"files\":[...]}'\n */\n\nimport { api } from \"../lib/api.js\";\n\nexport async function apiCommand(\n path: string,\n opts: { method?: string; data?: string; org?: string },\n): Promise<void> {\n const method = (opts.method || (opts.data !== undefined ? \"POST\" : \"GET\")).toUpperCase();\n\n let body: unknown;\n if (opts.data !== undefined) {\n try {\n body = JSON.parse(opts.data);\n } catch {\n console.error(\"-d/--data must be valid JSON.\");\n process.exit(1);\n }\n }\n\n const p = path.startsWith(\"/\") ? path : `/${path}`;\n const res = await api.call(method, p, { body, orgId: opts.org });\n\n const text = await res.text();\n let out = text;\n try {\n out = JSON.stringify(JSON.parse(text), null, 2);\n } catch {\n /* not JSON — pass through verbatim */\n }\n\n if (!res.ok) {\n console.error(`HTTP ${res.status}`);\n if (out) console.error(out);\n process.exit(1);\n }\n if (out) console.log(out);\n}\n","import readline from \"node:readline\";\nimport { api } from \"../lib/api.js\";\n\ninterface App {\n name: string;\n}\n\nexport async function rmCommand(appId: string): Promise<void> {\n const res = await api.get(`/v1/apps/${appId}`);\n if (!res.ok) {\n console.error(\"App not found.\");\n process.exit(1);\n }\n\n const app = (await res.json()) as App;\n\n const confirmed = await new Promise<boolean>((resolve) => {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n rl.question(`Delete ${app.name}? (y/N) `, (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === \"y\");\n });\n });\n\n if (!confirmed) {\n console.log(\"Cancelled.\");\n return;\n }\n\n const delRes = await api.del(`/v1/apps/${appId}`);\n if (!delRes.ok) {\n console.error(\"Failed to delete app.\");\n process.exit(1);\n }\n\n console.log(`Deleted ${app.name}`);\n}\n","import open from \"open\";\nimport { readProject } from \"../lib/config.js\";\nimport { api } from \"../lib/api.js\";\n\ninterface App {\n slug: string;\n app_token?: string;\n}\n\nexport async function openCommand(slug: string): Promise<void> {\n let appToken: string | undefined;\n\n const project = readProject();\n if (project?.slug === slug && project.app_token) {\n appToken = project.app_token;\n }\n\n if (!appToken) {\n const res = await api.get(\"/v1/apps\");\n if (res.ok) {\n const apps = (await res.json()) as App[];\n const app = apps.find((a) => a.slug === slug);\n appToken = app?.app_token;\n }\n }\n\n let url = `https://${slug}.apps.clawnify.com`;\n if (appToken) {\n url += `?token=${appToken}`;\n }\n\n await open(url);\n console.log(\"Opened in browser\");\n}\n","import { loadAuth, getEmailFromToken, getValidToken } from \"../lib/auth.js\";\nimport { api } from \"../lib/api.js\";\n\nexport async function whoamiCommand(): Promise<void> {\n const envToken = process.env.CLAWNIFY_TOKEN;\n const auth = loadAuth();\n\n if (!auth && !envToken) {\n console.log(\"Not logged in\");\n return;\n }\n\n const email = getEmailFromToken(envToken ?? auth!.access_token) ?? \"unknown\";\n console.log(`Email: ${email}`);\n const orgId = auth?.org_id ?? process.env.CLAWNIFY_ORG_ID;\n if (orgId) {\n console.log(`Org: ${orgId}`);\n }\n\n // A local JWT decode is NOT a liveness check — the refresh-token family can be\n // revoked while the cached access token still decodes fine, so `whoami` would\n // print a healthy identity while every real call 401s. Verify against the\n // server (this also self-heals a locally-expired token via getValidToken).\n const token = await getValidToken();\n if (!token) {\n console.log(\"Status: session expired — run `clawnify login`\");\n process.exitCode = 1;\n return;\n }\n\n try {\n const res = await api.request(\"GET\", \"/v1/orgs\", { token });\n if (res.ok) {\n console.log(\"Status: active\");\n } else if (res.status === 401) {\n console.log(\"Status: session expired — run `clawnify login`\");\n process.exitCode = 1;\n } else {\n console.log(`Status: could not verify (HTTP ${res.status})`);\n process.exitCode = 1;\n }\n } catch {\n // Network unreachable — the identity above is still valid locally; we just\n // couldn't confirm liveness. Don't crash or claim the session is dead.\n console.log(\"Status: could not reach the server (offline?)\");\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport readline from \"node:readline\";\nimport { findWorkspaceRoot } from \"../lib/config.js\";\nimport { detectAgents, agentByName } from \"../lib/skills/detect.js\";\nimport { installAiFiles } from \"./ai-files.js\";\n\nfunction ask(question: string): Promise<string> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n return new Promise((resolve) => {\n rl.question(question, (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n}\n\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 30);\n}\n\nconst TEMPLATES = {\n blank: \"Empty app with a single API route and page\",\n crud: \"CRUD app with a database table, list, and form\",\n};\n\ntype ProjectType = \"app\" | \"website\" | \"agent\";\n\ninterface InitOptions {\n name?: string;\n template?: string;\n storage?: boolean;\n type?: string;\n /** Non-interactive: take all defaults (app / blank / no storage / dir-based name).\n * Matches the `--yes` convention used by `npm create next-app` etc. */\n yes?: boolean;\n /** commander sets this false for `--no-ai-files`; default (undefined) installs. */\n aiFiles?: boolean;\n}\n\nasync function askProjectType(opts?: InitOptions): Promise<ProjectType> {\n if (opts?.type === \"app\" || opts?.type === \"website\" || opts?.type === \"agent\") {\n return opts.type;\n }\n if (opts?.type) {\n console.error(`Unknown --type '${opts.type}' (expected 'app', 'website', or 'agent').`);\n process.exit(1);\n }\n if (opts?.yes) return \"app\";\n console.log();\n console.log(\" What are you creating?\");\n console.log(\" 1) app — full-stack project (React + Hono + D1)\");\n console.log(\" 2) website — public site (Astro)\");\n console.log(\" 3) agent — an OpenClaw agent (instructions, skills, flows)\");\n console.log();\n const choice = (await ask(\"Type [1]: \")) || \"1\";\n if (choice === \"2\") return \"website\";\n if (choice === \"3\") return \"agent\";\n return \"app\";\n}\n\n/**\n * Detect which package manager invoked us. npm/pnpm/yarn/bun all set\n * `npm_config_user_agent` to something like `pnpm/10.15.1 npm/? ...`\n * before exec'ing the create-* package. We mirror that PM in our\n * post-scaffold \"Get started\" hints so users don't see `pnpm dev`\n * after running `yarn create`.\n */\nfunction detectPackageManager(): \"pnpm\" | \"npm\" | \"yarn\" | \"bun\" {\n const ua = process.env.npm_config_user_agent ?? \"\";\n if (ua.startsWith(\"pnpm\")) return \"pnpm\";\n if (ua.startsWith(\"yarn\")) return \"yarn\";\n if (ua.startsWith(\"bun\")) return \"bun\";\n return \"npm\";\n}\n\nexport async function initCommand(dir?: string, opts?: InitOptions): Promise<void> {\n const type = await askProjectType(opts);\n if (type === \"website\") {\n return initWebsite(dir, opts);\n }\n if (type === \"agent\") {\n return initAgent(dir, opts);\n }\n return initApp(dir, opts);\n}\n\nasync function initApp(dir?: string, opts?: InitOptions): Promise<void> {\n // --yes auto-fills everything: name from dir arg or \"my-app\", template\n // blank, no storage. Matches `npm create next-app -y` behavior.\n const yes = !!opts?.yes;\n const dirArgName = dir ? path.basename(path.resolve(dir)) : undefined;\n const name = opts?.name || (yes ? (dirArgName ?? \"my-app\") : (await ask(\"App name: \")) || \"my-app\");\n const slug = slugify(name);\n // Inside a workspace (and with no explicit dir), drop the app under apps/<slug>\n // so the monorepo stays tidy. An explicit dir arg always wins.\n let targetDir: string;\n if (dir) {\n targetDir = path.resolve(dir);\n } else {\n const ws = findWorkspaceRoot(process.cwd());\n targetDir = ws ? path.join(ws.dir, \"apps\", slug) : path.resolve(slug);\n }\n\n let template: string;\n if (opts?.template) {\n template = opts.template === \"crud\" ? \"crud\" : \"blank\";\n } else if (yes) {\n template = \"blank\";\n } else {\n console.log();\n console.log(\" Templates:\");\n console.log(\" 1) blank — Empty app with a single API route and page\");\n console.log(\" 2) crud — CRUD app with database, list, and form\");\n console.log();\n const templateChoice = (await ask(\"Template [1]: \")) || \"1\";\n template = templateChoice === \"2\" ? \"crud\" : \"blank\";\n }\n\n if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {\n console.error(`Directory ${targetDir} is not empty.`);\n process.exit(1);\n }\n\n fs.mkdirSync(path.join(targetDir, \"src/server\"), { recursive: true });\n fs.mkdirSync(path.join(targetDir, \"src/client\"), { recursive: true });\n\n let storage: boolean;\n if (opts?.storage !== undefined) {\n storage = opts.storage;\n } else if (yes) {\n storage = false;\n } else {\n const storageChoice = (await ask(\"Enable file uploads? [y/N]: \")) || \"n\";\n storage = storageChoice.toLowerCase() === \"y\";\n }\n\n // clawnify.json\n write(targetDir, \"clawnify.json\", JSON.stringify({\n $schema: \"https://app.clawnify.com/schema/v1/clawnify.json\",\n version: 1,\n name,\n description: \"\",\n app: { framework: \"react+hono\", database: true, storage },\n }, null, 2));\n\n // package.json\n const devDeps: Record<string, string> = {\n \"@cloudflare/workers-types\": \"^4.0.0\",\n \"@tailwindcss/vite\": \"^4.0.0\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.0\",\n \"@vitejs/plugin-react\": \"^4.0.0\",\n clawnify: \"^0.3.0\",\n \"drizzle-kit\": \"^0.31.0\",\n tailwindcss: \"^4.0.0\",\n vite: \"^6.0.0\",\n wrangler: \"^4.0.0\",\n };\n write(targetDir, \"package.json\", JSON.stringify({\n name: slug,\n private: true,\n type: \"module\",\n scripts: {\n dev: \"clawnify dev\",\n build: \"vite build\",\n deploy: \"clawnify deploy\",\n },\n dependencies: {\n \"@clawnify/app\": \"^0.1.1\",\n \"@clawnify/db\": \"^0.4.1\",\n \"@hono/zod-openapi\": \"^0.19.0\",\n hono: \"^4.0.0\",\n react: \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n zod: \"^3.0.0\",\n },\n devDependencies: devDeps,\n engines: { node: \">=22\" },\n pnpm: { onlyBuiltDependencies: [\"esbuild\"] },\n }, null, 2));\n\n // tsconfig.json\n write(targetDir, \"tsconfig.json\", JSON.stringify({\n compilerOptions: {\n target: \"ESNext\",\n module: \"ESNext\",\n moduleResolution: \"Bundler\",\n strict: true,\n lib: [\"ESNext\", \"DOM\", \"DOM.Iterable\"],\n jsx: \"react-jsx\",\n noEmit: true,\n skipLibCheck: true,\n resolveJsonModule: true,\n isolatedModules: true,\n },\n include: [\"src/**/*.ts\", \"src/**/*.tsx\"],\n exclude: [\"node_modules\", \"dist\"],\n }, null, 2));\n\n // vite.config.ts\n write(targetDir, \"vite.config.ts\", `import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\nimport tailwindcss from \"@tailwindcss/vite\";\n\nexport default defineConfig({\n plugins: [react(), tailwindcss()],\n build: {\n outDir: \"dist\",\n emptyOutDir: true,\n },\n server: {\n proxy: {\n \"/api\": {\n target: \"http://localhost:8787\",\n changeOrigin: true,\n },\n },\n },\n});\n`);\n\n // index.html\n write(targetDir, \"index.html\", `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>${name}</title>\n</head>\n<body>\n <div id=\"app\"></div>\n <script type=\"module\" src=\"/src/client/main.tsx\"></script>\n</body>\n</html>\n`);\n\n // .gitignore\n write(targetDir, \".gitignore\", `node_modules\ndist\n.wrangler\n.clawnify\n.env*\n!.env.example\n.dev.vars\ndata.db\ndata.db-wal\ndata.db-shm\n`);\n\n // src/server/worker-env.d.ts — Cloudflare Workers types\n write(targetDir, \"src/server/worker-env.d.ts\", `/// <reference types=\"@cloudflare/workers-types\" />\n`);\n\n // src/server/schema.ts — Drizzle DSL, the single source of truth for tables.\n // Edit this file to evolve the schema; run `pnpm db:generate` to emit a\n // new migration file under drizzle/, then commit and deploy.\n write(targetDir, \"src/server/schema.ts\", `import { sqliteTable, text, integer } from \"@clawnify/db\";\n\n/**\n * Example table. Replace with your own.\n *\n * Multi-tenancy reminder: every user-facing table should carry an\n * \\`org_id\\` column and every query should filter by it — read the org\n * with \\`orgId(c)\\` from \\`@clawnify/app\\` (never parse headers yourself).\n * See https://github.com/clawnify/skills/tree/main/skills/build-a-clawnify-app\n */\nexport const items = sqliteTable(\"items\", {\n id: integer(\"id\").primaryKey({ autoIncrement: true }),\n name: text(\"name\").notNull(),\n createdAt: text(\"created_at\").notNull().$default(() => new Date().toISOString()),\n});\n`);\n\n // drizzle.config.ts — points drizzle-kit at schema.ts. Migrations\n // are emitted to .clawnify/drizzle/ (gitignored). The CLI runs\n // drizzle-kit generate transparently on `clawnify dev` and\n // `clawnify deploy` — the user never has to think about it. Edit\n // schema.ts; that's it.\n write(targetDir, \"drizzle.config.ts\", `import { defineConfig } from \"drizzle-kit\";\n\nexport default defineConfig({\n schema: \"./src/server/schema.ts\",\n out: \"./.clawnify/drizzle\",\n dialect: \"sqlite\",\n});\n`);\n\n // src/server/index.ts\n if (storage) {\n write(targetDir, \"src/server/index.ts\", `import { OpenAPIHono } from \"@hono/zod-openapi\";\nimport { initUploads } from \"./uploads\";\nimport api from \"./routes\";\n\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.use(\"*\", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route(\"/\", api);\n\napp.doc(\"/api/openapi.json\", {\n openapi: \"3.0.0\",\n info: { title: \"${name}\", version: \"1.0.0\" },\n});\n\nexport default app;\n`);\n\n // src/server/uploads.ts\n write(targetDir, \"src/server/uploads.ts\", `let _bucket: R2Bucket;\n\nexport function initUploads(bucket: R2Bucket) {\n _bucket = bucket;\n}\n\nexport async function putUpload(\n filename: string,\n data: ArrayBuffer | Uint8Array,\n contentType: string,\n): Promise<string> {\n await _bucket.put(filename, data, { httpMetadata: { contentType } });\n return \\`/api/uploads/\\${filename}\\`;\n}\n\nexport async function getUpload(\n filename: string,\n): Promise<{ data: ArrayBuffer; contentType: string } | null> {\n const obj = await _bucket.get(filename);\n if (!obj) return null;\n return {\n data: await obj.arrayBuffer(),\n contentType: obj.httpMetadata?.contentType || \"application/octet-stream\",\n };\n}\n\nexport async function deleteUpload(filename: string): Promise<void> {\n await _bucket.delete(filename);\n}\n\nexport async function readUploadAsBase64DataUrl(\n filename: string,\n): Promise<string | null> {\n const result = await getUpload(filename);\n if (!result) return null;\n const bytes = new Uint8Array(result.data);\n let binary = \"\";\n for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);\n return \\`data:\\${result.contentType};base64,\\${btoa(binary)}\\`;\n}\n`);\n } else {\n write(targetDir, \"src/server/index.ts\", `import { OpenAPIHono } from \"@hono/zod-openapi\";\nimport api from \"./routes\";\n\ntype Env = { Bindings: { DB: D1Database } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.route(\"/\", api);\n\napp.doc(\"/api/openapi.json\", {\n openapi: \"3.0.0\",\n info: { title: \"${name}\", version: \"1.0.0\" },\n});\n\nexport default app;\n`);\n }\n\n // src/client/index.css\n write(targetDir, \"src/client/index.css\", `@import \"tailwindcss\";\n`);\n\n // src/client/main.tsx\n write(targetDir, \"src/client/main.tsx\", `import { StrictMode } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { App } from \"./app\";\nimport \"./index.css\";\n\ncreateRoot(document.getElementById(\"app\")!).render(\n <StrictMode>\n <App />\n </StrictMode>\n);\n`);\n\n if (template === \"crud\") {\n writeCrudTemplate(targetDir, name);\n } else {\n writeBlankTemplate(targetDir, name);\n }\n\n // Make the scaffolded app agent-ready: rules + skills + MCP config.\n // Fresh dir has no agent marker, so default to Claude. Opt out with\n // `clawnify init --no-ai-files`.\n if (opts?.aiFiles !== false) {\n const detected = detectAgents(targetDir);\n const agents = detected.length > 0 ? detected : [agentByName(\"claude\")];\n console.log();\n console.log(\" Installing AI files (rules + skills + MCP):\");\n installAiFiles(targetDir, agents, { mcp: true });\n }\n\n const pm = detectPackageManager();\n console.log();\n console.log(` Created ${name} in ${path.relative(process.cwd(), targetDir)}/`);\n console.log();\n console.log(\" Get started:\");\n console.log(` cd ${path.relative(process.cwd(), targetDir)}`);\n console.log(` ${pm} install`);\n console.log(` ${pm} ${pm === \"npm\" ? \"run \" : \"\"}dev # local dev at http://localhost:5173`);\n console.log(` ${pm} ${pm === \"npm\" ? \"run \" : \"\"}deploy # deploy to production`);\n console.log();\n}\n\nasync function initWebsite(dir?: string, opts?: InitOptions): Promise<void> {\n const name = opts?.name || (await ask(\"Site name: \")) || \"my-site\";\n const slug = slugify(name);\n // Inside a workspace (and with no explicit dir), the org's single website\n // lives at website/. An explicit dir arg always wins.\n let targetDir: string;\n if (dir) {\n targetDir = path.resolve(dir);\n } else {\n const ws = findWorkspaceRoot(process.cwd());\n targetDir = ws ? path.join(ws.dir, \"website\") : path.resolve(slug);\n }\n\n if (fs.existsSync(targetDir)) {\n // The workspace scaffold pre-creates website/.gitkeep — tolerate that lone\n // placeholder (and clear it), but refuse any other existing content.\n const entries = fs.readdirSync(targetDir);\n const onlyGitkeep = entries.length === 1 && entries[0] === \".gitkeep\";\n if (entries.length > 0 && !onlyGitkeep) {\n console.error(`Directory ${targetDir} is not empty.`);\n process.exit(1);\n }\n if (onlyGitkeep) fs.rmSync(path.join(targetDir, \".gitkeep\"));\n }\n\n fs.mkdirSync(targetDir, { recursive: true });\n\n write(targetDir, \"clawnify.json\", JSON.stringify({\n $schema: \"https://app.clawnify.com/schema/v1/clawnify.json\",\n version: 1,\n name,\n description: \"\",\n website: { framework: \"astro\" },\n }, null, 2));\n\n write(targetDir, \"package.json\", JSON.stringify({\n name: slug,\n private: true,\n type: \"module\",\n scripts: {\n dev: \"astro dev\",\n build: \"astro build\",\n preview: \"astro preview\",\n deploy: \"clawnify deploy\",\n },\n dependencies: {\n \"@astrojs/cloudflare\": \"^12.0.0\",\n \"@tailwindcss/vite\": \"^4.0.0\",\n astro: \"^5.0.0\",\n tailwindcss: \"^4.0.0\",\n },\n devDependencies: {\n clawnify: \"^0.1.15\",\n \"wrangler\": \"^4.0.0\",\n },\n engines: { node: \">=22\" },\n }, null, 2));\n\n write(targetDir, \"tsconfig.json\", JSON.stringify({\n extends: \"astro/tsconfigs/strict\",\n include: [\"src/**/*\", \".astro/types.d.ts\"],\n exclude: [\"dist\", \"node_modules\"],\n }, null, 2));\n\n write(targetDir, \"astro.config.mjs\", `import { defineConfig } from \"astro/config\";\nimport cloudflare from \"@astrojs/cloudflare\";\nimport tailwindcss from \"@tailwindcss/vite\";\n\nexport default defineConfig({\n output: \"server\",\n adapter: cloudflare(),\n vite: {\n plugins: [tailwindcss()],\n },\n});\n`);\n\n write(targetDir, \".gitignore\", `node_modules\ndist\n.astro\n.wrangler\n.clawnify\n.env*\n!.env.example\n.dev.vars\n`);\n\n write(targetDir, \"src/styles/global.css\", `@import \"tailwindcss\";\n\n:root {\n --color-primary: oklch(0.55 0.18 250);\n --color-ink: oklch(0.2 0.02 250);\n --color-canvas: oklch(0.99 0 0);\n}\n\nbody {\n background-color: var(--color-canvas);\n color: var(--color-ink);\n font-family: ui-sans-serif, system-ui, sans-serif;\n}\n`);\n\n write(targetDir, \"src/layouts/BaseLayout.astro\", `---\ninterface Props {\n title?: string;\n description?: string;\n}\n\nconst { title = \"${name}\", description = \"\" } = Astro.props;\n---\n<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>{title}</title>\n {description && <meta name=\"description\" content={description} />}\n <link rel=\"stylesheet\" href=\"/src/styles/global.css\" />\n </head>\n <body>\n <slot />\n </body>\n</html>\n`);\n\n write(targetDir, \"src/pages/index.astro\", `---\nimport BaseLayout from \"../layouts/BaseLayout.astro\";\n---\n<BaseLayout title=\"${name}\">\n <main class=\"mx-auto max-w-3xl px-6 py-24\">\n <h1 class=\"text-5xl font-semibold tracking-tight\">${name}</h1>\n <p class=\"mt-4 text-lg opacity-70\">\n Edit <code>src/pages/index.astro</code> to get started.\n </p>\n <p class=\"mt-8\">\n <a class=\"underline\" href=\"https://docs.astro.build\" target=\"_blank\" rel=\"noreferrer\">\n Astro docs →\n </a>\n </p>\n </main>\n</BaseLayout>\n`);\n\n console.log();\n console.log(` Created ${name} in ${path.relative(process.cwd(), targetDir)}/`);\n console.log();\n console.log(\" Get started:\");\n console.log(` cd ${path.relative(process.cwd(), targetDir)}`);\n console.log(\" pnpm install\");\n console.log(\" pnpm dev # local dev at http://localhost:4321\");\n console.log(\" pnpm deploy # deploy as your org's website\");\n console.log();\n}\n\nasync function initAgent(dir?: string, opts?: InitOptions): Promise<void> {\n const yes = !!opts?.yes;\n const dirArgName = dir ? path.basename(path.resolve(dir)) : undefined;\n const name =\n opts?.name ||\n (yes ? (dirArgName ?? \"my-agent\") : (await ask(\"Agent name: \")) || \"my-agent\");\n const slug = slugify(name);\n // Inside a workspace (and with no explicit dir), agents live under agents/.\n // An explicit dir arg always wins.\n let targetDir: string;\n if (dir) {\n targetDir = path.resolve(dir);\n } else {\n const ws = findWorkspaceRoot(process.cwd());\n targetDir = ws ? path.join(ws.dir, \"agents\", slug) : path.resolve(slug);\n }\n\n if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {\n console.error(`Directory ${targetDir} is not empty.`);\n process.exit(1);\n }\n\n // clawnify.json — the `agent` block discriminates the kind (mirrors\n // app/website/workspace); `harness` selects the runtime adapter.\n write(targetDir, \"clawnify.json\", JSON.stringify({\n $schema: \"https://app.clawnify.com/schema/v1/clawnify.json\",\n version: 1,\n name,\n description: \"\",\n agent: { harness: \"openclaw\" },\n }, null, 2));\n\n // AGENT.md — the agent's instructions (its \"system prompt\" as prose).\n write(targetDir, \"AGENT.md\", `# ${name}\n\nYou are ${name}, an OpenClaw agent.\n\nDescribe the agent's role, tone, and boundaries here. This file is the\nagent's primary instructions — edit it to shape behavior.\n\n## Skills\n\nReusable procedures live under \\`skills/<name>/\\`: a \\`SKILL.md\\` the agent\nreads when triggered, plus a \\`skill.json\\` describing when it runs.\n\n## Flows\n\nAutomations live under \\`flows/<name>.json\\` — ClawFlow definitions that run\non triggers (webhooks, schedules) without a full agent turn.\n`);\n\n // Payload dirs the OpenClaw adapter deploys (see ADR § Layer 1). Kept in\n // git even when empty so the layout is discoverable.\n write(targetDir, \"skills/.gitkeep\", \"\");\n write(targetDir, \"flows/.gitkeep\", \"\");\n\n // .gitignore — the ADR's hard secret-exclusion guard: credentials, env, and\n // runtime state (memories, sessions, logs) are never shipped with the agent.\n // Each installer brings their own keys.\n write(targetDir, \".gitignore\", `node_modules\n.clawnify\n.env*\n!.env.example\n.dev.vars\n# Runtime state — never shipped with the agent (ADR § secret-exclusion)\nmemories/\nsessions/\nlogs/\n`);\n\n const rel = path.relative(process.cwd(), targetDir) || \".\";\n console.log();\n console.log(` Created agent ${name} in ${rel}/`);\n console.log();\n console.log(\" Layout:\");\n console.log(\" AGENT.md — the agent's instructions\");\n console.log(\" skills/ — reusable procedures (SKILL.md + skill.json)\");\n console.log(\" flows/ — ClawFlow automations (<name>.json)\");\n console.log();\n console.log(\" Author here and commit. Deploying this (config push to the\");\n console.log(\" running agent via CAP) lands in a follow-up.\");\n console.log();\n}\n\nfunction writeBlankTemplate(dir: string, name: string) {\n // No schema.sql — the build pipeline reads drizzle/*.sql (emitted\n // by drizzle-kit generate) instead. schema.ts is the single source.\n\n write(dir, \"src/server/routes.ts\", `import { OpenAPIHono, createRoute, z } from \"@hono/zod-openapi\";\nimport { getDB, desc } from \"@clawnify/db\";\nimport * as schema from \"./schema\";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi(\"Item\");\n\napi.openapi(\n createRoute({\n method: \"get\",\n path: \"/api/items\",\n summary: \"List items\",\n responses: {\n 200: {\n description: \"List of items\",\n content: { \"application/json\": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\nexport default api;\n`);\n\n write(dir, \"src/client/app.tsx\", `export function App() {\n return (\n <main className=\"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 px-6\">\n <div className=\"max-w-xl w-full text-center\">\n <div className=\"inline-flex items-center gap-2 rounded-full bg-white/80 backdrop-blur px-3 py-1 text-xs font-medium text-slate-600 ring-1 ring-slate-200\">\n <span className=\"size-1.5 rounded-full bg-emerald-500\" />\n Clawnify · live\n </div>\n\n <h1 className=\"mt-6 text-4xl font-semibold tracking-tight text-slate-900\">\n Welcome to ${name}\n </h1>\n <p className=\"mt-3 text-base text-slate-600\">\n Edit <code className=\"rounded bg-slate-200/70 px-1.5 py-0.5 text-sm\">src/client/app.tsx</code> to get started.\n </p>\n\n <ul className=\"mt-8 grid gap-3 text-left text-sm text-slate-700\">\n <li className=\"rounded-lg border border-slate-200 bg-white px-4 py-3\">\n <span className=\"font-medium text-slate-900\">Try the API.</span> Open <code>/api/items</code> — empty list to start.\n </li>\n <li className=\"rounded-lg border border-slate-200 bg-white px-4 py-3\">\n <span className=\"font-medium text-slate-900\">Evolve the schema.</span> Edit <code>src/server/schema.ts</code>, then run <code>pnpm db:generate</code>.\n </li>\n <li className=\"rounded-lg border border-slate-200 bg-white px-4 py-3\">\n <span className=\"font-medium text-slate-900\">Deploy.</span> Run <code>pnpm deploy</code> to push live.\n </li>\n </ul>\n\n <p className=\"mt-8 text-xs text-slate-500\">\n Read{\" \"}\n <a href=\"https://github.com/clawnify/skills/tree/main/skills/build-a-clawnify-app\" target=\"_blank\" rel=\"noreferrer\" className=\"underline underline-offset-2\">\n the build-a-clawnify-app skill\n </a>{\" \"}\n for the full gold-standard guide.\n </p>\n </div>\n </main>\n );\n}\n`);\n}\n\nfunction writeCrudTemplate(dir: string, name: string) {\n // CRUD template extends the default schema with title + status.\n // Overwrites the schema.ts that initApp wrote (a minimal items\n // table). drizzle-kit generates the matching migration on first\n // `clawnify dev` / `clawnify deploy` — no SQL file shipped here.\n write(dir, \"src/server/schema.ts\", `import { sqliteTable, text, integer } from \"@clawnify/db\";\n\nexport const items = sqliteTable(\"items\", {\n id: integer(\"id\").primaryKey({ autoIncrement: true }),\n title: text(\"title\").notNull(),\n status: text(\"status\").notNull().default(\"active\"),\n createdAt: text(\"created_at\").notNull().$default(() => new Date().toISOString()),\n});\n`);\n\n write(dir, \"src/server/routes.ts\", `import { OpenAPIHono, createRoute, z } from \"@hono/zod-openapi\";\nimport { getDB, eq, desc } from \"@clawnify/db\";\nimport * as schema from \"./schema\";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi(\"Item\");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi(\"CreateItem\");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi(\"UpdateItem\");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi(\"Ok\");\n\napi.openapi(\n createRoute({\n method: \"get\",\n path: \"/api/items\",\n summary: \"List items\",\n responses: {\n 200: {\n description: \"List of items\",\n content: { \"application/json\": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\napi.openapi(\n createRoute({\n method: \"post\",\n path: \"/api/items\",\n summary: \"Create item\",\n request: { body: { content: { \"application/json\": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: \"Created item\",\n content: { \"application/json\": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid(\"json\");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: \"patch\",\n path: \"/api/items/:id\",\n summary: \"Update item\",\n request: {\n params: IdParamSchema,\n body: { content: { \"application/json\": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: \"Updated\", content: { \"application/json\": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid(\"param\");\n const body = c.req.valid(\"json\");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: \"delete\",\n path: \"/api/items/:id\",\n summary: \"Delete item\",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: \"Deleted\", content: { \"application/json\": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid(\"param\");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n`);\n\n write(dir, \"src/client/app.tsx\", `import { useState, useEffect } from \"react\";\n\ninterface Item {\n id: number;\n title: string;\n status: string;\n createdAt: string;\n}\n\nexport function App() {\n const [items, setItems] = useState<Item[]>([]);\n const [title, setTitle] = useState(\"\");\n\n async function load() {\n const res = await fetch(\"/api/items\");\n setItems(await res.json());\n }\n\n useEffect(() => { load(); }, []);\n\n async function addItem(e: React.FormEvent) {\n e.preventDefault();\n if (!title.trim()) return;\n await fetch(\"/api/items\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ title }),\n });\n setTitle(\"\");\n load();\n }\n\n async function toggleStatus(item: Item) {\n const next = item.status === \"active\" ? \"done\" : \"active\";\n await fetch(\\`/api/items/\\${item.id}\\`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ status: next }),\n });\n load();\n }\n\n async function deleteItem(id: number) {\n await fetch(\\`/api/items/\\${id}\\`, { method: \"DELETE\" });\n load();\n }\n\n return (\n <div className=\"max-w-xl mx-auto mt-10 px-4\">\n <h1 className=\"text-2xl font-semibold mb-6\">${name}</h1>\n <form onSubmit={addItem} className=\"flex gap-2 mb-6\">\n <input\n value={title}\n onChange={(e) => setTitle(e.target.value)}\n placeholder=\"Add an item...\"\n className=\"flex-1 px-3 py-2 rounded-lg border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-black\"\n />\n <button\n type=\"submit\"\n className=\"px-4 py-2 rounded-lg bg-black text-white text-sm font-medium hover:bg-gray-800\"\n >\n Add\n </button>\n </form>\n <ul className=\"divide-y divide-gray-100\">\n {items.map((item) => (\n <li key={item.id} className=\"flex items-center gap-3 py-2\">\n <input\n type=\"checkbox\"\n checked={item.status === \"done\"}\n onChange={() => toggleStatus(item)}\n className=\"rounded\"\n />\n <span\n className={\\`flex-1 text-sm \\${item.status === \"done\" ? \"line-through text-gray-400\" : \"text-gray-800\"}\\`}\n >\n {item.title}\n </span>\n <button\n onClick={() => deleteItem(item.id)}\n className=\"text-gray-300 hover:text-gray-600 text-lg leading-none\"\n >\n ×\n </button>\n </li>\n ))}\n </ul>\n {items.length === 0 && (\n <p className=\"text-gray-400 text-sm mt-4\">No items yet. Add one above.</p>\n )}\n </div>\n );\n}\n`);\n}\n\nfunction write(dir: string, file: string, content: string) {\n const fullPath = path.join(dir, file);\n fs.mkdirSync(path.dirname(fullPath), { recursive: true });\n fs.writeFileSync(fullPath, content);\n}\n","/**\n * Detect which coding agents have rules/skills directories in `cwd`.\n * `clawnify skills add` installs into ALL detected agents simultaneously\n * (per Riccardo's rule), so this returns every agent whose marker is\n * present rather than picking one.\n *\n * Agent priority order doesn't matter for installation, but listing\n * matches the priority for \"no agent detected\" diagnostics.\n */\n\nimport { existsSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport type Agent = \"claude\" | \"cursor\" | \"openclaw\" | \"codex\" | \"aider\";\n\nexport interface DetectedAgent {\n agent: Agent;\n /** Where we'll write the skill. Relative to cwd. */\n target: string;\n /** Why this agent was detected. Shown in `--verbose` output. */\n marker: string;\n}\n\ninterface Detector {\n agent: Agent;\n /** Files/dirs whose presence triggers detection. */\n markers: string[];\n /** Where the skill goes — directory or file path, relative to cwd. */\n target: string;\n}\n\nconst DETECTORS: Detector[] = [\n { agent: \"claude\", markers: [\".claude\", \".claude.json\", \"CLAUDE.md\"], target: \".claude/skills\" },\n { agent: \"cursor\", markers: [\".cursor\", \".cursorrules\"], target: \".cursor/rules\" },\n { agent: \"openclaw\", markers: [\".openclaw\", \"openclaw.json\"], target: \".openclaw/skills\" },\n { agent: \"codex\", markers: [\".codex\", \"AGENTS.md\"], target: \".codex/skills\" },\n { agent: \"aider\", markers: [\"CONVENTIONS.md\", \".aider.conf.yml\"], target: \"CONVENTIONS.md\" },\n];\n\nfunction exists(cwd: string, name: string): boolean {\n const path = join(cwd, name);\n try {\n statSync(path);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function detectAgents(cwd: string): DetectedAgent[] {\n const found: DetectedAgent[] = [];\n for (const d of DETECTORS) {\n const hit = d.markers.find((m) => exists(cwd, m));\n if (hit) {\n found.push({ agent: d.agent, target: d.target, marker: hit });\n }\n }\n return found;\n}\n\n/**\n * Force-detect a specific agent by name (used by `--agent` override).\n * Returns the detector entry even if no marker is present — the caller\n * is opting in explicitly.\n */\nexport function agentByName(name: Agent): DetectedAgent {\n const d = DETECTORS.find((x) => x.agent === name);\n if (!d) throw new Error(`Unknown agent: ${name}`);\n return { agent: d.agent, target: d.target, marker: \"(forced)\" };\n}\n\nexport const ALL_AGENTS: Agent[] = DETECTORS.map((d) => d.agent);\n","// GENERATED by scripts/bundle-skills.mjs — do not edit by hand.\n// Source: ../../docs/<name>.md\n\nexport interface BundledSkill {\n name: string;\n description: string;\n content: string;\n}\n\nexport const CLI_VERSION = \"0.11.3\";\n\nexport const BUNDLED_SKILLS: readonly BundledSkill[] = [\n {\n name: \"build-a-clawnify-app\",\n description: \"Author a Clawnify app end-to-end — the canonical Hono + React + Vite + @hono/zod-openapi + @clawnify/db (Drizzle) stack, schema.ts (typed queries) kept in sync with schema.sql (the DDL the deploy applies), OpenAPIHono routes (createRoute) that auto-generate an OpenAPI spec, and platform-injected identity via user()/orgId()/caller(). Use when building or modifying an app that deploys to the Clawnify platform.\",\n content: \"# Build a Clawnify app\\n\\nCanonical skill: how to author a Clawnify app end-to-end. Same content\\nfor humans reading the docs and for AI coding agents injecting this as\\ninstructions during an app build.\\n\\nIf you're an agent: this document is enough context to produce a\\nworking app from scratch. Follow it literally. The patterns here\\nare exactly what `clawnify init` scaffolds and what the platform\\nexpects.\\n\\n## TL;DR\\n\\n- **One stack.** Hono + React + Vite + `@hono/zod-openapi` +\\n `@clawnify/db` (Drizzle) + `@clawnify/app` (entry, routing,\\n identity) + Tailwind v4. Nothing else.\\n- **Schema lives in two files kept in sync** — `schema.ts` (Drizzle\\n DSL, the typed view your queries use) and `schema.sql` (the DDL the\\n deploy applies to your app's D1). Change one, change the other.\\n- **Queries through `getDB`** — `import { getDB, eq } from\\n \\\"@clawnify/db\\\"`. JSON columns auto-serialize.\\n- **API routes are `OpenAPIHono` + `createRoute`** — Zod-validated\\n request/response.\\n- **`createApp()`** (from `@clawnify/app`) builds the entry — it returns an\\n `OpenAPIHono` with API discovery already mounted (`/api/openapi.json` +\\n `/llms.txt`, generated from your live routes). That descriptor *is* the\\n tool surface agents discover. Never hand-write those routes.\\n- **One import.** `@clawnify/app` re-exports `createRoute`, `z` and\\n `OpenAPIHono`, and adds `user` / `orgId` / `caller`. Import from it, not\\n from `@clawnify/routes` directly.\\n- **`clawnify.json`** declares framework, env, and public routes.\\n There is no `api.tools[]` — the agent discovers and calls your\\n endpoints via `/llms.txt` (and the OpenAPI spec).\\n- **Identity is injected by the platform** — read it with `user(c)` /\\n `orgId(c)` / `caller(c)` from `@clawnify/app`. Your app never\\n authenticates anyone.\\n\\n## Stack rationale\\n\\nOne template, one set of decisions. Don't deviate unless the user has\\nexplicitly asked. `clawnify init` (type `app`) scaffolds either a\\n`blank` template (one GET route + a page) or a `crud` template (a\\ntable with list/create/update/delete + a form). Both share the exact\\nsame stack below.\\n\\n## File layout\\n\\n```\\nmy-app/\\n clawnify.json ← Manifest (validated against /schema/v1/clawnify.json)\\n package.json\\n tsconfig.json\\n vite.config.ts ← @vitejs/plugin-react + @tailwindcss/vite; proxies /api → :8787\\n index.html\\n .gitignore\\n .clawnify/ ← CLI cache (gitignored)\\n wrangler.toml ← Generated per-dev wrangler config\\n src/\\n server/\\n index.ts ← OpenAPIHono entry — mounts routes, serves /api/openapi.json\\n routes.ts ← OpenAPIHono + createRoute definitions — the API surface\\n schema.ts ← Drizzle table definitions (typed view for queries)\\n schema.sql ← canonical DDL the deploy applies — keep in sync with schema.ts\\n worker-env.d.ts ← Cloudflare Workers types reference\\n uploads.ts ← R2 helpers (only when storage is enabled)\\n client/\\n main.tsx ← React mount point\\n app.tsx ← Root component (plain fetch against /api/*)\\n index.css ← @import \\\"tailwindcss\\\"\\n```\\n\\n## Schema — `schema.ts` + `schema.sql`, kept in sync\\n\\nTwo files describe the same tables. `schema.ts` (Drizzle DSL) is the\\ntyped view your queries compile against; `schema.sql` is the DDL the\\ndeploy applies to your app's D1. **When you change one, update the\\nother** — they must describe the same tables.\\n\\nThe scaffold's starter table (blank template):\\n\\n```ts\\n// src/server/schema.ts\\nimport { sqliteTable, text, integer } from \\\"@clawnify/db\\\";\\n\\nexport const items = sqliteTable(\\\"items\\\", {\\n id: integer(\\\"id\\\").primaryKey({ autoIncrement: true }),\\n name: text(\\\"name\\\").notNull(),\\n createdAt: text(\\\"created_at\\\").notNull().$default(() => new Date().toISOString()),\\n});\\n```\\n\\nReal apps are multi-tenant. Every user-facing table carries an\\n`org_id`, every query filters by it. JSON columns and indexes use the\\nDrizzle DSL re-exported from `@clawnify/db`:\\n\\n```ts\\nimport { sqliteTable, text, integer, index } from \\\"@clawnify/db\\\";\\n\\nexport const notes = sqliteTable(\\n \\\"notes\\\",\\n {\\n id: integer(\\\"id\\\").primaryKey({ autoIncrement: true }),\\n orgId: text(\\\"org_id\\\").notNull(), // ALWAYS filter by this in queries\\n title: text(\\\"title\\\").notNull(),\\n body: text(\\\"body\\\").notNull().default(\\\"\\\"),\\n tags: text(\\\"tags\\\", { mode: \\\"json\\\" }).$type<string[]>().notNull().default([]),\\n createdAt: text(\\\"created_at\\\").notNull().$default(() => new Date().toISOString()),\\n },\\n (t) => ({\\n byOrg: index(\\\"notes_by_org\\\").on(t.orgId, t.createdAt),\\n }),\\n);\\n```\\n\\nRules:\\n- JSON columns: `text(col, { mode: \\\"json\\\" }).$type<T>()` — Drizzle\\n serializes on write and parses on read.\\n- Multi-tenancy: every user-facing table has `org_id`. Every query\\n filters by it. No exceptions.\\n- Identifiers: snake_case in SQL, camelCase in TS (Drizzle bridges).\\n\\n## `schema.sql` — the DDL the deploy applies\\n\\nAlongside `schema.ts`, keep a `schema.sql` describing the same tables.\\nThis is the DDL applied to your app's database on deploy.\\n\\n```sql\\n-- src/server/schema.sql (mirror of the schema.ts tables)\\nCREATE TABLE IF NOT EXISTS notes (\\n id INTEGER PRIMARY KEY AUTOINCREMENT,\\n org_id TEXT NOT NULL,\\n title TEXT NOT NULL,\\n body TEXT NOT NULL DEFAULT '',\\n tags TEXT NOT NULL DEFAULT '[]', -- JSON column\\n created_at TEXT NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS notes_by_org ON notes(org_id, created_at);\\n```\\n\\nRules:\\n- Always `CREATE TABLE IF NOT EXISTS` — the apply is additive and\\n re-run-safe.\\n- Add a new column with `ALTER TABLE <t> ADD COLUMN …` at the **end** of\\n `schema.sql`, and reflect it in `schema.ts`. The deploy adds it.\\n- Deploys are **additive**: new tables and columns are added\\n automatically. Destructive changes (dropping or retyping a column) are\\n not applied automatically — do those deliberately, and never drop a\\n table with user data unless explicitly asked.\\n- **Never let `schema.ts` and `schema.sql` drift.** Change one, change\\n the other — they must describe the same tables.\\n\\n## `src/server/index.ts` — the entry\\n\\n```ts\\nimport { createApp } from \\\"@clawnify/app\\\";\\nimport api from \\\"./routes\\\";\\n\\ntype Env = { Bindings: { DB: D1Database } };\\n\\n// db:false — this app reads the database per request via getDB(c.env),\\n// which needs no init middleware.\\nconst app = createApp<Env>({ title: \\\"My app\\\", version: \\\"1.0.0\\\", db: false });\\n\\napp.route(\\\"/\\\", api);\\n\\nexport default app;\\n```\\n\\nThe entry is thin: `createApp()` then mount your routes. `createApp`\\nreturns an `OpenAPIHono` with **API discovery already mounted** — it\\nserves both `/api/openapi.json` (generated from your `createRoute`\\ndefinitions, with schemas) **and** `/llms.txt` (the same, agent-readable).\\nAny `/api/*` route written as a plain `app.get` with no `createRoute` is\\nstill listed from the live route table, so the endpoint inventory is\\nalways complete. **Never hand-write a `/openapi.json` or `/llms.txt`\\nhandler** — and don't call `mountDiscovery` yourself; `createApp` did it.\\n\\nWhen storage (file uploads) is enabled, the entry also wires the R2\\nbucket in a middleware before mounting routes:\\n\\n```ts\\nimport { createApp } from \\\"@clawnify/app\\\";\\nimport { initUploads } from \\\"./uploads\\\";\\nimport api from \\\"./routes\\\";\\n\\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\\n\\nconst app = createApp<Env>({ title: \\\"My app\\\", version: \\\"1.0.0\\\", db: false });\\n\\napp.use(\\\"*\\\", async (c, next) => {\\n initUploads(c.env.UPLOADS);\\n await next();\\n});\\n\\napp.route(\\\"/\\\", api);\\n\\nexport default app;\\n```\\n\\n## `src/server/routes.ts` — routes with `createRoute`\\n\\nEach endpoint is a `createRoute({ method, path, summary, request, responses })`\\ndefinition paired with a handler via `api.openapi(route, handler)`.\\nRequest bodies and params are Zod-validated (`c.req.valid(\\\"json\\\")`,\\n`c.req.valid(\\\"param\\\")`); response shapes are declared with\\n`.openapi(\\\"Name\\\")` Zod schemas so they land in the generated spec.\\n\\nBlank template — one read route:\\n\\n```ts\\nimport { OpenAPIHono, createRoute, z } from \\\"@clawnify/app\\\";\\nimport { getDB, desc } from \\\"@clawnify/db\\\";\\nimport * as schema from \\\"./schema\\\";\\n\\ntype Env = { Bindings: { DB: D1Database } };\\nconst api = new OpenAPIHono<Env>();\\n\\nconst ItemSchema = z.object({\\n id: z.number(),\\n name: z.string(),\\n createdAt: z.string(),\\n}).openapi(\\\"Item\\\");\\n\\napi.openapi(\\n createRoute({\\n method: \\\"get\\\",\\n path: \\\"/api/items\\\",\\n summary: \\\"List items\\\",\\n responses: {\\n 200: {\\n description: \\\"List of items\\\",\\n content: { \\\"application/json\\\": { schema: z.array(ItemSchema) } },\\n },\\n },\\n }),\\n async (c) => {\\n const db = getDB(c.env, { schema });\\n const items = await db\\n .select()\\n .from(schema.items)\\n .orderBy(desc(schema.items.createdAt));\\n return c.json(items);\\n },\\n);\\n\\nexport default api;\\n```\\n\\nCRUD template — the full list/create/update/delete surface:\\n\\n```ts\\nimport { OpenAPIHono, createRoute, z } from \\\"@clawnify/app\\\";\\nimport { getDB, eq, desc } from \\\"@clawnify/db\\\";\\nimport * as schema from \\\"./schema\\\";\\n\\ntype Env = { Bindings: { DB: D1Database } };\\nconst api = new OpenAPIHono<Env>();\\n\\nconst ItemSchema = z.object({\\n id: z.number(),\\n title: z.string(),\\n status: z.string(),\\n createdAt: z.string(),\\n}).openapi(\\\"Item\\\");\\n\\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi(\\\"CreateItem\\\");\\nconst UpdateItemSchema = z.object({\\n title: z.string().min(1).optional(),\\n status: z.string().optional(),\\n}).openapi(\\\"UpdateItem\\\");\\nconst IdParamSchema = z.object({ id: z.string() });\\nconst OkSchema = z.object({ ok: z.boolean() }).openapi(\\\"Ok\\\");\\n\\napi.openapi(\\n createRoute({\\n method: \\\"get\\\",\\n path: \\\"/api/items\\\",\\n summary: \\\"List items\\\",\\n responses: {\\n 200: {\\n description: \\\"List of items\\\",\\n content: { \\\"application/json\\\": { schema: z.array(ItemSchema) } },\\n },\\n },\\n }),\\n async (c) => {\\n const db = getDB(c.env, { schema });\\n const items = await db\\n .select()\\n .from(schema.items)\\n .orderBy(desc(schema.items.createdAt));\\n return c.json(items);\\n },\\n);\\n\\napi.openapi(\\n createRoute({\\n method: \\\"post\\\",\\n path: \\\"/api/items\\\",\\n summary: \\\"Create item\\\",\\n request: { body: { content: { \\\"application/json\\\": { schema: CreateItemSchema } } } },\\n responses: {\\n 201: {\\n description: \\\"Created item\\\",\\n content: { \\\"application/json\\\": { schema: ItemSchema } },\\n },\\n },\\n }),\\n async (c) => {\\n const { title } = c.req.valid(\\\"json\\\");\\n const db = getDB(c.env, { schema });\\n const [row] = await db\\n .insert(schema.items)\\n .values({ title: title.trim() })\\n .returning();\\n return c.json(row, 201);\\n },\\n);\\n\\napi.openapi(\\n createRoute({\\n method: \\\"patch\\\",\\n path: \\\"/api/items/:id\\\",\\n summary: \\\"Update item\\\",\\n request: {\\n params: IdParamSchema,\\n body: { content: { \\\"application/json\\\": { schema: UpdateItemSchema } } },\\n },\\n responses: {\\n 200: { description: \\\"Updated\\\", content: { \\\"application/json\\\": { schema: OkSchema } } },\\n },\\n }),\\n async (c) => {\\n const { id } = c.req.valid(\\\"param\\\");\\n const body = c.req.valid(\\\"json\\\");\\n const patch: Partial<typeof schema.items.$inferInsert> = {};\\n if (body.title !== undefined) patch.title = body.title;\\n if (body.status !== undefined) patch.status = body.status;\\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\\n const db = getDB(c.env, { schema });\\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\\n return c.json({ ok: true });\\n },\\n);\\n\\napi.openapi(\\n createRoute({\\n method: \\\"delete\\\",\\n path: \\\"/api/items/:id\\\",\\n summary: \\\"Delete item\\\",\\n request: { params: IdParamSchema },\\n responses: {\\n 200: { description: \\\"Deleted\\\", content: { \\\"application/json\\\": { schema: OkSchema } } },\\n },\\n }),\\n async (c) => {\\n const { id } = c.req.valid(\\\"param\\\");\\n const db = getDB(c.env, { schema });\\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\\n return c.json({ ok: true });\\n },\\n);\\n\\nexport default api;\\n```\\n\\nPatterns to follow:\\n- **Give every route a clear `summary`/`description`.** The generated\\n OpenAPI spec is what the agent reads to decide which endpoint to\\n call — a vague summary makes your endpoint invisible in practice.\\n- **Validate input with Zod** via `request.body` / `request.params`\\n and read it with `c.req.valid(\\\"json\\\")` / `c.req.valid(\\\"param\\\")`.\\n Never parse `c.req.raw` by hand.\\n- **Declare response shapes** with `.openapi(\\\"Name\\\")` schemas — they\\n become the documented return type in the spec.\\n- **Filter by the org** on every user-facing query (see \\\"who is\\n calling\\\" below). No exceptions.\\n\\n## `src/server` — who is calling\\n\\nThe platform authenticates every caller at its perimeter and injects a\\nverified identity onto the request (it strips any client-supplied\\nversion first, so it can't be spoofed). Your app never authenticates\\nanyone: no `Authorization`, no cookies, no JWT, no login screen.\\n\\nRead it with the helpers from `@clawnify/app` — don't parse headers\\nyourself:\\n\\n```ts\\nimport { user, orgId, caller } from \\\"@clawnify/app\\\";\\n\\napp.get(\\\"/api/notes\\\", async (c) => {\\n const org = orgId(c);\\n if (!org) return c.json({ error: \\\"unauthorized\\\" }, 401);\\n\\n const db = getDB(c.env, { schema });\\n return c.json(\\n await db.select().from(schema.notes).where(eq(schema.notes.orgId, org)),\\n );\\n});\\n```\\n\\n| Helper | Returns |\\n|--------|---------|\\n| `orgId(c)` | Organization UUID — the tenant key. Filter every user-facing query by it. |\\n| `user(c)` | `{ id, email, name, avatarUrl, firstName, lastName }` — or **`null`** when the caller isn't a person. |\\n| `caller(c)` | `user`, `api`, `agent`, `agent-browser`, `public`, `bypass`, `system`, or `app`. |\\n\\nTwo rules that catch people out:\\n\\n- **`user(c)` is null for five of the eight caller kinds**\\n (`agent-browser`, `public`, `bypass`, `system`, `app`). Always handle\\n the null case — don't assume a person is present just because a\\n request arrived. For per-user rows, store `user(c).id` in a `user_id`\\n column and filter on it, exactly as you filter on `org_id`.\\n- **`firstName` / `lastName` are a heuristic** split of a single stored\\n full name (first word / the rest). Fine for a greeting; never persist\\n them or treat them as someone's legal name — store `name`.\\n\\nDon't build app-level users, roles, or permissions. Authorization\\nalready happened at the perimeter.\\n\\n## `src/client` — React + plain fetch\\n\\nThe client mounts React and talks to the API with plain `fetch`\\nagainst the `/api/*` routes. No data-layer library is scaffolded.\\n\\n```tsx\\n// src/client/main.tsx\\nimport { StrictMode } from \\\"react\\\";\\nimport { createRoot } from \\\"react-dom/client\\\";\\nimport { App } from \\\"./app\\\";\\nimport \\\"./index.css\\\";\\n\\ncreateRoot(document.getElementById(\\\"app\\\")!).render(\\n <StrictMode>\\n <App />\\n </StrictMode>\\n);\\n```\\n\\n```tsx\\n// src/client/app.tsx (CRUD template shape)\\nimport { useState, useEffect } from \\\"react\\\";\\n\\ninterface Item {\\n id: number;\\n title: string;\\n status: string;\\n createdAt: string;\\n}\\n\\nexport function App() {\\n const [items, setItems] = useState<Item[]>([]);\\n const [title, setTitle] = useState(\\\"\\\");\\n\\n async function load() {\\n const res = await fetch(\\\"/api/items\\\");\\n setItems(await res.json());\\n }\\n\\n useEffect(() => { load(); }, []);\\n\\n async function addItem(e: React.FormEvent) {\\n e.preventDefault();\\n if (!title.trim()) return;\\n await fetch(\\\"/api/items\\\", {\\n method: \\\"POST\\\",\\n headers: { \\\"Content-Type\\\": \\\"application/json\\\" },\\n body: JSON.stringify({ title }),\\n });\\n setTitle(\\\"\\\");\\n load();\\n }\\n\\n // ...toggleStatus / deleteItem call PATCH/DELETE the same way.\\n\\n return (\\n <div className=\\\"max-w-xl mx-auto mt-10 px-4\\\">\\n {/* form + list */}\\n </div>\\n );\\n}\\n```\\n\\nIn local dev, Vite proxies `/api` to the Worker on `:8787` (see\\n`vite.config.ts`), so the same relative fetch paths work in dev and\\nin production. The API is the one contract: the UI calls it over\\n`fetch`, and the agent calls it over the OpenAPI spec.\\n\\n## Design\\n\\nIf the project contains a `DESIGN.md`, it is the single source of\\ntruth for visuals — follow its tokens, don't restyle around it. The\\nscaffold ships Tailwind v4 (via `@tailwindcss/vite`, imported with\\n`@import \\\"tailwindcss\\\";` in `index.css`) and nothing else — no\\ncomponent library. The rules every Clawnify app follows:\\n\\n- **Neutral chrome.** White canvas and surfaces, one text ramp\\n (foreground → muted → faint), hairline borders. Color is for\\n meaning, not decoration.\\n- **One primary CTA per screen.** Blue is reserved for links and\\n focus rings; never a second accent.\\n- **Status colors are muted pairs** — never pure-saturated fills.\\n- **Style with Tailwind utilities.** Don't install another component\\n library or write a bespoke CSS system unless the user asks.\\n- **Sizes in rem**, so browser zoom and font settings are respected.\\n\\n## `clawnify.json` — the manifest\\n\\n```json\\n{\\n \\\"$schema\\\": \\\"https://app.clawnify.com/schema/v1/clawnify.json\\\",\\n \\\"version\\\": 1,\\n \\\"name\\\": \\\"Notes\\\",\\n \\\"description\\\": \\\"Take and organize notes. Searchable by tag.\\\",\\n \\\"app\\\": {\\n \\\"framework\\\": \\\"react+hono\\\",\\n \\\"database\\\": true,\\n \\\"storage\\\": false\\n },\\n \\\"env\\\": {\\n \\\"optional\\\": [\\\"OPENROUTER_API_KEY\\\"]\\n },\\n \\\"api\\\": {\\n \\\"public_routes\\\": [\\n { \\\"path\\\": \\\"/api/feed\\\", \\\"methods\\\": [\\\"GET\\\"] }\\n ]\\n }\\n}\\n```\\n\\n`clawnify init` writes the minimal form:\\n`{ app: { framework: \\\"react+hono\\\", database: true, storage } }`. Add\\nthe rest as needed.\\n\\nIf the app talks to third-party services the user has connected\\n(ads platforms, CRMs, messaging), declare them:\\n\\n```json\\n{ \\\"app\\\": { \\\"credentials\\\": [\\\"metaads\\\", \\\"googleads\\\"] } }\\n```\\n\\nGet the ids and names from `clawnify connections list` — see the\\nnaming rule below.\\n\\n`env` supports `required` (deploy warns if missing), `optional`\\n(injected when available), and `oneOf` (at least one per group).\\n\\nRules:\\n- **There is no `api.tools[]`.** The manifest's `api` object only\\n accepts `public_routes` and `automation_bypass`. Your API surface\\n is discovered from the generated OpenAPI spec, not a hand-authored\\n tools list (see the next section).\\n- **Public routes are the exception**, not the default. Every route\\n is behind the Clawnify perimeter (auth-required) unless you\\n explicitly add a matching path to `api.public_routes`. Use only for\\n webhooks, RSS, embedded feeds.\\n- **`framework: \\\"react+hono\\\"`** for new apps. Never `preact+hono` or\\n `vite-preact` — those are legacy.\\n- **`database: true`** if the app uses a DB. Ship both `schema.ts`\\n (typed) and `schema.sql` (the applied DDL), kept in sync.\\n\\n## How the agent reaches your API (no `api.tools[]`)\\n\\nThe old tRPC stack emitted an `api.tools[]` array from procedure meta.\\nThat mechanism is gone. Today the flow is:\\n\\n1. Your `createRoute` definitions + `app.doc(\\\"/api/openapi.json\\\", …)`\\n auto-generate a live OpenAPI 3.0 spec. The platform still reads this\\n internally (e.g. `update_app` triage decides whether an existing\\n endpoint can serve a request instead of a rebuild), so keep it\\n accurate — but it is **not** the agent's discovery channel.\\n2. The agent discovers your endpoints from the app's **`agent.md`**\\n (extracted into `agent_instructions`, returned by `get_app`) and, for\\n the exact routes, `get_app_source`. It then drives them with the\\n built-in `call_app_api` tool (invoke a `method` + `path` on the live\\n app). No per-app MCP registration, no manifest tools array, and no\\n raw-OpenAPI tool — a generated spec is only as complete as its\\n annotations, so `agent.md` is the authored contract of record.\\n\\nSo you make an endpoint \\\"agent-callable\\\" by describing it in `agent.md`\\n(what it does, method + path, when to use it) and shipping it with a\\nclear `summary`/`description` and Zod-typed request/response. The\\nclearer both are, the more reliably the agent uses it.\\n\\n## Connections & secrets — `@clawnify/connections`\\n\\n**The naming rule — never invent an identifier.** Before declaring\\n`credentials` or env names, run `clawnify connections list`: it shows\\nthe org's canonical integration ids (`googleads`, never `google_ads`),\\nthe fixed provider-key names (`OPENROUTER_API_KEY`, never\\n`OPENROUTER_KEY`), and custom env vars already defined — each with\\nconnected/set state. Reuse those exact identifiers; a misspelled one\\ndoesn't fail the build, it silently resolves to nothing at runtime. If\\nyou need a custom secret that isn't listed, pick a clear name and tell\\nthe user to set it in the dashboard.\\n\\nIf the app needs a third-party service or a provider API key, use\\nthe `@clawnify/connections` SDK. Never read credential bindings\\ndirectly, never paste API keys, never hardcode a token or endpoint.\\n\\n```ts\\nimport { connect, secret, describe, searchActions } from \\\"@clawnify/connections\\\";\\n\\n// A connected integration:\\nconst meta = connect(\\\"metaads\\\", env);\\nconst accounts = await meta.adAccounts(\\\"name,currency\\\");\\n\\n// A provider key the user supplied (null if absent):\\nconst key = secret(\\\"OPENROUTER_API_KEY\\\", env);\\n\\n// What's wired vs missing — drive your setup/empty state from this:\\nconst status = await describe(env, undefined, REQUIRES);\\n```\\n\\nHow to call a connected service — the mistake that silently breaks\\nintegration apps, so get it right:\\n\\n- **Prefer the typed client's semantic methods** where they exist\\n (`meta.adAccounts(...)`, `googleads.query(gaql)`).\\n- **For anything else, discover and run an action:**\\n ```ts\\n const [best] = await searchActions(\\\"list google ads campaigns\\\", env);\\n const data = await connect(best.service, env).run(best.slug, body);\\n ```\\n- Some integrations also expose a raw REST client\\n (`connect(\\\"bird\\\", env).get(\\\"/path\\\")`) — but if `.get()`/`.post()`\\n throws for a service, that service only supports semantic methods\\n and `run()`. When unsure, use `run()`.\\n- **Need exact paths/arguments for a raw-REST provider?** Some carry\\n a `spec_url` (the provider's published OpenAPI spec) —\\n `clawnify connections list --json` shows it. Download and query it —\\n `curl -s <spec_url> -o spec.json && jq '.paths | keys' spec.json` —\\n never read a whole spec into context (they run to 10+ MB).\\n- **Never fall back to raw `fetch`** against a provider API, and\\n never invent endpoints or guess tokens.\\n\\n**The one exception — a service we don't support at all.** If a\\nprovider isn't in the connections registry (nothing to `connect()`\\nto, and `clawnify connections list` doesn't show it), the sanctioned\\npath *is* a raw call with a user-supplied key: declare the key(s) it\\nneeds in `clawnify.json` `env` (`required`/`optional`/`oneOf`), tell\\nthe user to set them in the dashboard, read them with\\n`secret(\\\"THAT_KEY\\\", env)`, and `fetch` the provider's documented\\nendpoints directly. This is the escape hatch for the long tail of\\nintegrations we don't model yet — it does **not** apply to a service\\nwe *do* support (use `connect()` / `run()` for those, always). Keep\\nthe endpoint and token server-side, never in the client bundle.\\n\\nBuild a `describe()`-driven setup state instead of assuming\\nconnections exist — show the user what's missing and where to\\nconnect it.\\n\\n## Scheduling & deferred work — the managed queue\\n\\nA deployed app **cannot bind Cloudflare Queues, Durable Objects, or cron\\ntriggers** (the platform builds every app with a fixed binding set: `DB` +\\n`ASSETS` + `UPLOADS`). To run work later — a scheduled publish, a reminder, a\\nretry, a \\\"do this in 10 minutes\\\" — use the **Clawnify managed queue service**\\nover HTTP. It owns the clock, retries, and at-least-once delivery, then calls an\\nendpoint on *your own app* back at the scheduled time.\\n\\nIt's a thin seam over a platform primitive, same shape as `@clawnify/db` /\\n`@clawnify/connections` (a `@clawnify/queue` package is coming; inline the seam\\nuntil then). Auth is the build-injected `env.CLAWNIFY_TOKEN`; with no token\\n(local dev) the seam degrades to a no-op.\\n\\n**Enqueue** a deferred call to your own endpoint:\\n\\n```ts\\n// POST https://services.clawnify.com/queue/enqueue (Bearer CLAWNIFY_TOKEN)\\nconst res = await fetch(\\\"https://services.clawnify.com/queue/enqueue\\\", {\\n method: \\\"POST\\\",\\n headers: { Authorization: `Bearer ${env.CLAWNIFY_TOKEN}`, \\\"Content-Type\\\": \\\"application/json\\\" },\\n body: JSON.stringify({\\n target_url: `${origin}/api/internal/publish`, // an endpoint on THIS app\\n payload: { post_id: id }, // echoed back to you on fire\\n run_at: new Date(whenMs).toISOString(),\\n idempotency_key: `post:${id}:${whenMs}`, // same key dedupes; new time = new job\\n }),\\n});\\nconst { job_id } = await res.json(); // store it to cancel/reschedule\\n```\\n\\nPersist `job_id` on the row (e.g. `posts.queue_job_id`). **Cancel / reschedule**:\\n`DELETE https://services.clawnify.com/queue/jobs/{job_id}` (Bearer token);\\nreschedule = cancel + a fresh enqueue.\\n\\n**The callback endpoint is a public, signature-verified route.** The queue calls\\n`target_url` from outside the perimeter, so the endpoint must be declared in\\n`clawnify.json` `public_routes` **and** verify the delivery signature itself —\\nthe signature *is* its auth (never trust an unsigned call):\\n\\n```jsonc\\n// clawnify.json\\n\\\"api\\\": { \\\"public_routes\\\": [ { \\\"path\\\": \\\"/api/internal/publish\\\", \\\"methods\\\": [\\\"POST\\\"] } ] }\\n```\\n\\nDeliveries are signed with the platform's **ECDSA P-256 (ES256)** key,\\nStripe-style over `${timestamp}.${rawBody}`, verified against\\n`https://services.clawnify.com/.well-known/jwks.json` (public key — nothing\\nbreaks on token rotation). Read the raw body, check the signature + a timestamp\\ntolerance (~5 min) before doing anything:\\n\\n```ts\\napp.post(\\\"/api/internal/publish\\\", async (c) => {\\n const raw = await c.req.text();\\n const ok = await verifyDelivery(raw, {\\n signature: c.req.header(\\\"x-clawnify-signature\\\"),\\n timestamp: c.req.header(\\\"x-clawnify-timestamp\\\"),\\n keyId: c.req.header(\\\"x-clawnify-key-id\\\"),\\n });\\n if (!ok) return c.json({ error: \\\"bad signature\\\" }, 401);\\n const { post_id } = JSON.parse(raw);\\n // …do the deferred work (short: it's one normal Worker invocation)…\\n return c.json({ ok: true });\\n});\\n```\\n\\nEach fire is a normal Worker request — size the work to one invocation (publish a\\npost, send a digest). For long compute *now* (not deferred), hold the request\\nopen and return when done; don't fire-and-forget past the response.\\n\\n## Migrations\\n\\nKeep `schema.ts` and `schema.sql` in sync by hand. The workflow is:\\n\\n1. Edit `src/server/schema.ts` for the new shape (types + queries).\\n2. Make the matching edit in `src/server/schema.sql` — a new\\n `CREATE TABLE IF NOT EXISTS`, or `ALTER TABLE … ADD COLUMN …` at the\\n **end** of the file for a new column.\\n3. Run `clawnify dev` locally, then `clawnify deploy`.\\n\\nOn deploy your schema changes are applied to the app's database — new\\ntables and columns are added automatically.\\n\\nDestructive changes (drop column, rename) are not applied automatically;\\ndo them deliberately, and only when the user explicitly asks. Renames\\nare risky on production data — prefer \\\"add new column, backfill, switch\\nqueries, drop old column\\\" over a single-step rename.\\n\\n## What the agent must NOT do\\n\\n- Author a `/openapi.json` handler by hand. `app.doc(\\\"/api/openapi.json\\\", …)`\\n generates it from your `createRoute` definitions.\\n- Let `schema.ts` and `schema.sql` drift. They describe the same\\n tables — change both, every time.\\n- Hand-author migration SQL files. Make schema changes in `schema.sql`\\n (and mirror them in `schema.ts`); the deploy applies them.\\n- Invent an `api.tools[]` array in the manifest. It isn't a valid\\n field — the OpenAPI spec is the tool surface.\\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\\n via Drizzle. The raw SQL API has `json()` as a helper.\\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\\n leak is the worst-class bug we can ship.\\n- Read auth from `Authorization` / cookies / `Bearer` tokens, or\\n hand-parse `X-Clawnify-*` headers. Use `user(c)` / `orgId(c)` /\\n `caller(c)` from `@clawnify/app`.\\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\\n through `@clawnify/connections` (`connect` / `secret` / `run`).\\n- Install `drizzle-orm` as a separate top-level dependency.\\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\\n need to pin a specific version (rare).\\n\\n## What the agent SHOULD do\\n\\n- Import everything from `@clawnify/db` where possible\\n (`getDB`, `eq`, `and`, `desc`, `sql`, `sqliteTable`, `text`,\\n `integer`, `index`, etc. are all re-exported there). Drop to\\n `drizzle-orm` directly only for things not re-exported.\\n- Give every route a clear `summary`/`description` and Zod-typed\\n request/response so the agent can discover and call it via the\\n OpenAPI spec.\\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\\n publishing — the preview tier catches schema drift and type errors\\n at build time.\\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\\n README for the current API + version notes.\\n\\n## Schema-as-data exception\\n\\nApps that let END users define data shapes at runtime (CMS, no-code\\ntable editor) can't model their schema in `schema.ts` — the table\\ndefinitions live in rows. Those apps fall back to the raw SQL API\\nfrom `@clawnify/db` (`query`, `get`, `run`, `json`). Open-cms is\\nthe canonical example.\\n\\nIf you're building this kind of app, you still use Drizzle's\\n`schema.ts` for the **registry** tables (content types, field\\ndefinitions). Only the dynamically-spawned per-collection tables\\nneed raw SQL. See open-cms's `src/server/schema-sync.ts` for the\\nruntime DDL pattern.\\n\",\n },\n {\n name: \"use-the-clawnify-cli\",\n description: \"Use the Clawnify CLI end-to-end — authenticate, scaffold, run locally, deploy apps and websites, link projects, manage orgs, and inspect deployed apps. Use when deploying to Clawnify from a terminal or wiring the CLI into scripts and coding agents.\",\n content: \"# Use the Clawnify CLI\\n\\nCanonical skill: how to drive the `clawnify` CLI. Same content for\\nhumans and for AI coding agents operating a terminal.\\n\\nFor **authoring app code** (stack, schema, tRPC patterns), use the\\n`build-a-clawnify-app` skill — this one covers the tooling around it.\\n\\n## TL;DR\\n\\n```bash\\nnpm i -g clawnify # or: npx clawnify@latest <command>\\nclawnify login # browser sign-in, paste-code fallback\\nclawnify init my-app # scaffold an app or website\\ncd my-app && clawnify dev\\nclawnify deploy # → https://<slug>.apps.clawnify.com\\n```\\n\\n- **Auth once, org lazily.** `login` only signs you in; the first\\n command that needs an organization asks once and remembers it.\\n- **A directory links to one app.** `deploy` from a linked directory\\n updates that app; `clawnify link <id-or-slug>` adopts an existing one.\\n- **Non-interactive flags exist for every prompt** — use them in\\n scripts and CI (`-y`, `--update-existing`, `--create-new`, `--org`).\\n\\n## Authenticate\\n\\n```bash\\nclawnify login # opens the browser; also prints the sign-in URL\\nclawnify whoami # current user, active org (if linked)\\n```\\n\\n`login` works from any browser: if the browser runs on the same\\nmachine, sign-in completes automatically; otherwise the page shows a\\ncode to paste back at the `Paste code here if prompted >` prompt\\n(useful over SSH — no port forwarding needed).\\n\\n**Headless / CI / agents — skip `login` entirely.** Set `CLAWNIFY_TOKEN` (a\\nSupabase access token) and it wins over any stored session, reading/writing no\\nfiles; `CLAWNIFY_ORG_ID` (or a per-command `--org`) pins the org. This is how a\\ncoding agent runs the CLI without a browser.\\n\\n### Organizations\\n\\nYou belong to one or more orgs; apps live inside an org.\\n\\n```bash\\nclawnify org list # orgs you belong to (* marks active)\\nclawnify org use <slug-or-id> # switch the active org\\n```\\n\\nNo need to pick one up front — the first org-scoped command prompts\\nonce and persists the choice. Any single command can override with\\n`--org <slug-or-id>`.\\n\\n## Create and run locally\\n\\n```bash\\nclawnify init [dir] # interactive: app or website\\nclawnify init my-app -y # non-interactive defaults (blank app)\\nclawnify init --type app --template crud --name my-app\\nclawnify init --type website --name my-site\\nclawnify dev [dir] [--port 8787] # local dev server\\n```\\n\\n`init` also installs AI files (rules + skills + MCP config) for any\\ncoding agents detected in the project; skip with `--no-ai-files`.\\n\\n## Deploy\\n\\n```bash\\nclawnify deploy # deploy the current directory\\nclawnify deploy path/to/app\\nclawnify deploy --from owner/repo # deploy straight from GitHub\\nclawnify deploy --from owner/repo --path apps/web # monorepo subdir\\nclawnify deploy --dry-run # list files that would upload\\n```\\n\\nFirst deploy creates the app and links the directory (writes a local\\nproject file); later deploys update the same app. On a slug conflict\\nyou'll be asked — or decide up front:\\n\\n```bash\\nclawnify deploy -y # reuse/update the existing app\\nclawnify deploy --update-existing # same, explicit\\nclawnify deploy --create-new # take the suggested new slug\\n```\\n\\nLink an existing deployed app to the current directory instead of\\ncreating a new one:\\n\\n```bash\\nclawnify link <app-id-or-slug>\\n```\\n\\n## Inspect and manage deployed apps\\n\\n```bash\\nclawnify ls # list deployed apps in the active org\\nclawnify logs <app-id> # build logs\\nclawnify open <slug> # open the live app in the browser\\nclawnify rm <app-id> # delete an app\\nclawnify pull schema --from <app-id-or-slug> # fetch live schema.sql\\nclawnify docs [slug] # usage README for an app (org index if omitted)\\n```\\n\\n`pull schema` refuses to clobber local uncommitted changes unless you\\npass `--force`.\\n\\n## Manage agents (the FDE surface)\\n\\nDrive an org's AI agents from the terminal — observe them and fix them. See the\\n`fix-a-clawnify-agent` skill for the workflow; this is the command list. All\\norg-scoped and **repo-independent** (reads session data + the box, never a\\nGitHub repo). Add `--server <id>` when the org has more than one server.\\n\\n```bash\\nclawnify servers list # the org's servers (an org can have several)\\nclawnify agents list # agents on a server (main + specialists)\\nclawnify agents skills [agent] # what an agent can ACTUALLY run (not just its workspace)\\nclawnify sessions --agent <slug> --json # stored sessions + token counters (contextTokens = bloat)\\nclawnify sessions history <key> --json # one session's transcript — where it veered\\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/ to edit (flows/ come with main only — flows are box-level)\\nclawnify agents push [dir] # push edits back (additive; next session, no restart)\\nclawnify agents grant-skill <s> --to <a> # share a main-authored skill (or --all for every agent)\\nclawnify agents create <slug> --yes # new specialist (RESTARTS the gateway)\\nclawnify env set <KEY> <VALUE> # org custom env — NON-SECRET only (restarts gateway)\\nclawnify connections connect <id> # how to connect an integration (dashboard OAuth; you can't)\\n```\\n\\n**Boundary:** everything above is autonomous *except* the human-auth actions —\\nconnecting an integration (OAuth) and handing over a secret/API key. For those,\\nexplain the dashboard steps; never fake them. `agents create` / `env set`\\nrestart the gateway, so confirm before running them on a busy box.\\n\\n## Connections & env names\\n\\n```bash\\nclawnify connections list # the org's naming catalog (● connected / ○ not)\\nclawnify connections connect <id> # how to connect one — dashboard OAuth; the CLI/agent can't do it for you\\n```\\n\\nLists the active org's integrations (canonical ids + connected state),\\nprovider API keys (fixed names + set state), and custom env vars. Read\\nit before declaring `credentials` or env names in `clawnify.json` and\\nreuse the exact identifiers it shows — a misspelled id or key name\\ndoesn't fail the build, it silently resolves to nothing at runtime.\\n\\n## Workspaces (one repo, one org's apps)\\n\\n```bash\\nclawnify workspace init [dir] [--org <slug-or-id>]\\n```\\n\\nScaffolds a monorepo bound to an org; apps scaffolded inside land\\nunder `apps/` and inherit the org on deploy.\\n\\n## Wire up coding agents\\n\\n```bash\\nclawnify ai-files install # rules + skills + MCP server in one step\\nclawnify skills list # bundled skills\\nclawnify skills add <name> # install one into detected agents\\nclawnify mcp # stdio MCP bridge (Claude Desktop, etc.)\\n```\\n\\n`ai-files install` detects agent config dirs in the project (Claude\\nCode, Cursor, OpenClaw, Codex, Aider) and writes the always-on rules\\nblock, installs bundled skills, and adds the Clawnify MCP server to\\n`.mcp.json`. Target one agent with `--agent <name>`; undo with\\n`clawnify ai-files uninstall`.\\n\\n## The raw escape hatch\\n\\n```bash\\nclawnify api /servers # any GET\\nclawnify api /servers/<id>/agents -X POST -d '{…}' # any method + JSON body\\n```\\n\\n`clawnify api <path>` makes an authenticated request to any Clawnify API path —\\nsame auth and org scoping as every other command (it can only do what you can).\\nUse it for anything the porcelain doesn't wrap; the curated commands stay small\\nbecause this is always there.\\n\\n## Tips\\n\\n- `npx clawnify@latest <command>` always runs the newest release.\\n- Every org-scoped command accepts `--org` — prefer it in scripts over\\n relying on the saved active org.\\n- If sign-in ever fails mid-flow, just run `clawnify login` again; it\\n is safe to repeat.\\n\",\n },\n {\n name: \"fix-a-clawnify-agent\",\n description: \"Diagnose and fix a Clawnify AI agent that veers off its instructions, ignores specific rules, forgets things, repeats the same mistake, or burns a lot of API credits. Use when someone says their agent (e.g. \\\"Ash\\\") won't follow instructions, keeps going off-path, or is expensive — read the agent's own sessions, find the real cause, and fix the instructions / sessions / flow instead of patching blind.\",\n content: \"# Fix a misbehaving Clawnify agent\\n\\nYou are the planner and thinker. The Clawnify agent — the customer's\\nWhatsApp / Telegram / Slack / email \\\"AI employee\\\", running OpenClaw on their\\nserver — is the executor. When it misbehaves your job is to **read what it\\nactually did, find the real cause, and change the durable inputs.** Not to\\npatch instructions blind, and not to burn the agent's own (expensive) model\\ntokens on trial-and-error.\\n\\nThe person you're helping is often **not** an AI specialist. So: diagnose\\nfirst, then **explain the cause in plain language and correct the\\nmisconception** before you change anything.\\n\\n## The one rule: don't debug blind\\n\\n\\\"Veers off / ignores instructions\\\" has **three different causes with three\\ndifferent fixes.** You can only tell which one by reading the agent's actual\\nsession. Patching instructions without looking is exactly why it \\\"isn't\\nheading in the right direction\\\" — and every blind test run costs model tokens.\\n\\n| Cause | What you'll see in the session | Fix |\\n|---|---|---|\\n| **1. Session bloat** | Was fine early, degrades over a long-running chat; forgets/repeats; high `contextTokens`; compaction/truncation in the transcript; the rule is simply *absent* from recent context | Scope a **fresh session per task**; reset/retire the bloated one |\\n| **2. Instruction patchwork** | The rule *was* in context but a **contradicting or older** rule won, or it's buried in a wall of text | **Restructure** `AGENTS.md` (don't add another patch) |\\n| **3. Wrong structure** | A repeatable multi-step task the agent improvises differently each time | Move it to a **flow** (deterministic rails) |\\n\\nBloat and patchwork also explain most **surprise API costs**: a bloated\\nsession re-sends a huge context on *every* turn, and the patch-and-rerun loop\\nitself burns tokens. Measure it — don't guess (Step 1).\\n\\n## Step 1 — Observe (read what actually happened)\\n\\n```bash\\nclawnify sessions # every agent's sessions on the server, newest first\\nclawnify sessions --agent ash --json # ash only, with token counters (contextTokens = bloat signal)\\nclawnify sessions history <key> --json # the transcript of one run — where it actually veered\\nclawnify agents skills ash # what ash can ACTUALLY run (workspace + shared skills)\\n```\\n\\nLook for, in order:\\n- **Which failure mode** (table above): was the instruction *present and\\n ignored* (→ patchwork/structure) or *compacted away / absent* (→ bloat)?\\n- **`contextTokens`** on the session — large and growing = bloat.\\n- **A missing skill** — if the instruction says \\\"use skill X\\\" but `agents\\n skills` doesn't list it, the agent literally can't. The fix is to grant it\\n (`clawnify agents grant-skill X --to ash`, or `--all` for every agent) if it's\\n already authored in main, else author it first (`agents pull main` → add\\n `skills/X/SKILL.md` → `agents push`) — not to reword the instruction. (Note:\\n what's in the agent's *workspace* is only part of it — `agents skills` shows\\n the effective set incl. shared managed-root skills.)\\n- **Where the tokens go** — one giant session, or repeated retries after a\\n veer? That's your cost answer, from data, not a hypothesis.\\n\\n> If `clawnify sessions` isn't available yet in this org, fall back: ask the\\n> person to describe (or paste) one failing run, and read the current\\n> `AGENTS.md` from the org's synced repo. You still diagnose before you fix.\\n\\n## Step 2 — Explain, then fix\\n\\nTell the person, plainly, which of the three it is and why. Then:\\n\\n**Bloat →** don't reuse one ever-growing chat for the same task. Start a fresh\\nsession per task/topic (or `/reset` the runaway one). This fixes the veer\\n*and* the cost.\\n\\n**Patchwork →** rewrite `AGENTS.md`, don't append to it. Structure it: **role\\n→ a short list of hard rules up front → the steps → one example of right vs\\nwrong.** Delete contradictions. A tight, prioritized instruction set is\\nfollowed far better than a long patched one.\\n\\n**Structure →** author a **flow** for the repeatable task: deterministic steps,\\neach with a narrow instruction, and the heavy/deterministic parts (fetch data,\\nfill a template, render the deck) run *without* the model — less veer, less cost.\\n\\nWhere instructions live and how edits land:\\n- Edit **`AGENTS.md`** (and `skills/`, `flows/`). Push via the org's **GitHub\\n sync repo** (auto-deploys to the box) or `clawnify deploy`. See the\\n `use-the-clawnify-cli` skill for the commands.\\n- **No gateway restart needed** — the agent picks up new `AGENTS.md` / skills /\\n flows on its **next session**.\\n- **Never edit any `CLAWNIFY-*.md`** file (`CLAWNIFY-SOUL/AGENTS/TOOLS.md`) —\\n those are platform-owned and Clawnify overwrites them on every sync. Your\\n edits there vanish.\\n\\n## How Clawnify agents actually work (what people get wrong)\\n\\nPreempt these — they cause \\\"I set it up but the agent ignores it\\\":\\n\\n- **Adding a document to Knowledge does NOT mean the agent reads it.**\\n (1) A doc must be **published by a human** — an agent \\\"proposing\\\" it only\\n creates a draft. (2) Once published, the agent only *automatically* sees its\\n **title + one-line description** (a capped, ~30-item index); the **actual\\n content is fetched only when the agent chooses to search** it\\n (`company_knowledge_search`). So if the agent ignores a doc, check: is it\\n published? not hidden? still in the index? does its `AGENTS.md` tell it to\\n search? — **re-uploading won't help.** Depth: the `organize-company-knowledge` skill.\\n- **Memory** is written by the agent via a tool (`memory_write`) and surfaced\\n as an index + per-turn recall — it is **not** a file/folder you drop notes\\n into.\\n- **The dashboard \\\"recurring skill\\\" cards are manual-click only** — the\\n cron/every/at schedule shown is **not wired to a scheduler.** For real\\n scheduled or event-driven work use a **cron job or a flow/webhook**, not a\\n recurring-skill card.\\n- **Native channels** (WhatsApp/Telegram/Slack) receive messages \\\"for free\\\"\\n via the allowlist — there is **no trigger/webhook to set up** for incoming\\n messages. (Only Clawnify *integrations* have dashboard triggers.)\\n\\n## Answering \\\"would a different agent / a flow help?\\\"\\n\\n- **Same agent for the same task → confusion?** The agent identity isn't the\\n problem; a reused, ever-growing **session** is (bloat, above). A second agent\\n doesn't fix the mechanism and doubles what you manage. Fresh sessions do.\\n- **Would a flow be better?** Yes *if* the task is repeatable and structured —\\n it constrains the agent and moves deterministic work off-model (less veer,\\n less cost). No if the underlying step instructions are vague — a flow\\n structures, it doesn't clarify.\\n\\n## Guardrails\\n\\n- **Diagnose before you change anything.** One transcript read beats five blind\\n patches.\\n- **Never** edit `CLAWNIFY-*.md` (overwritten) — edit `AGENTS.md`.\\n- **Confirm with the human before anything irreversible or outward-facing:**\\n sending messages on the agent's live channels, deleting an agent or app,\\n billing/plan changes, rotating credentials. Self-service is not unattended\\n autonomy.\\n- **Connecting an integration is a hard stop, not a confirm.** If a fix needs a\\n Clawnify integration that `clawnify connections list` shows as not connected\\n (○), you *cannot* connect it — that needs the user's OAuth sign-in in a\\n browser. Run `clawnify connections connect <id>` and relay the steps to the\\n user; never attempt it yourself or ask for their password.\\n- **Never put a secret through `clawnify env set`** — it exposes the value in\\n the command and your context. Secrets and API keys go in the dashboard\\n (Settings → Environment Variables / API Keys); guide the user there. Use\\n `env set` only for non-secret config. And remember `agents create` / `env set`\\n **restart the gateway** — confirm with the user before you run them on a live,\\n busy box.\\n- Prefer the **smallest durable fix** (a session habit, a tightened `AGENTS.md`,\\n one flow) over more instructions.\\n\",\n }\n];\n\nexport const RULES_CONTENT = \"You are working inside a **Clawnify app** — a full-stack project that deploys to\\nCloudflare through the Clawnify platform. Follow these rules.\\n\\n## Stack (fixed — do not swap)\\n\\n- **Frontend:** React 19 + Tailwind v4, built with Vite.\\n- **API:** Hono (`@hono/zod-openapi`) running on Cloudflare Workers.\\n- **Database:** D1 (SQLite at the edge) via `@clawnify/db` (Drizzle).\\n\\nOne app = one `clawnify.json` manifest at the repo root. Don't introduce other\\nframeworks, ORMs, or hosting targets.\\n\\n## The schema lives in `src/server/schema.ts`\\n\\n- Define tables with the Drizzle DSL there — it is the single source of truth.\\n- **Never** hand-write SQL migrations or edit a `schema.sql` by hand. `clawnify\\n dev` and `clawnify deploy` run `drizzle-kit generate` for you.\\n- Every user-facing table needs an `org_id` column, and every query must filter\\n by the `X-Clawnify-Org-Id` request header. This is how multi-tenancy works —\\n there are no exceptions.\\n\\n## Identity comes from request headers, never the client\\n\\nThe platform injects identity headers the client cannot forge:\\n`X-Clawnify-User-Id`, `X-Clawnify-Org-Id`, `X-Clawnify-User-Email`,\\n`X-Clawnify-Caller`. Read them server-side. Never trust a client-supplied user\\nor org id.\\n\\n## Integrations: use `@clawnify/connections`\\n\\nDon't store per-service API keys or OAuth secrets in the app. Declare what the\\napp needs under `app.credentials` in `clawnify.json`, then call\\n`connect(service, env)` and `secret(name, env)` from the SDK. Off-platform\\n(local dev, scripts), put a `clw_` org service token in `.dev.vars` as\\n`CLAWNIFY_TOKEN` — the SDK then resolves your **real** org connections over HTTP\\nwith no per-service secrets.\\n\\n## Commands\\n\\n- `clawnify dev` — local dev server. D1 runs as local SQLite, identical to\\n production. Leave it running in a separate terminal so generated types stay\\n fresh.\\n- `clawnify deploy` — ships the app live at `https://<slug>.apps.clawnify.com`.\\n- Don't invoke raw `wrangler` or `drizzle-kit` — the CLI wraps them. Editing\\n `schema.ts` and running `clawnify dev`/`deploy` is the whole workflow.\\n\\n## Going deeper\\n\\nFor the full gold-standard structure — routing, OpenAPI route definitions,\\nclient data-fetching patterns, file uploads — read the **build-a-clawnify-app**\\nskill installed alongside these rules.\\n\";\n","/**\n * Write a bundled skill into an agent's expected location, formatted\n * for that agent's convention. Each agent ships skills slightly\n * differently — same content underneath, different wrapper.\n *\n * Version pinning: every installed file carries an HTML comment header\n * `<!-- clawnify-skill: <name> v<X.Y.Z> -->`. On reinstall we read that\n * header; if the version matches the CLI's current version, we skip\n * (no-op idempotency). If it differs, we overwrite — the user is\n * implicitly upgrading by re-running after a CLI bump.\n */\n\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n statSync,\n rmSync,\n unlinkSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CLI_VERSION, type BundledSkill } from \"./content.gen.js\";\nimport type { DetectedAgent } from \"./detect.js\";\n\nconst VERSION_HEADER_RE = /<!--\\s*clawnify-skill:\\s*([\\w-]+)\\s+v([\\d.]+)\\s*-->/;\n\nfunction versionHeader(name: string): string {\n return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;\n}\n\nfunction readExistingVersion(path: string): string | null {\n if (!existsSync(path)) return null;\n try {\n const head = readFileSync(path, \"utf8\").slice(0, 500);\n const match = head.match(VERSION_HEADER_RE);\n return match ? match[2] : null;\n } catch {\n return null;\n }\n}\n\nexport type InstallStatus =\n | { status: \"installed\"; path: string }\n | { status: \"updated\"; path: string; previousVersion: string }\n | { status: \"skipped\"; path: string; reason: string };\n\nexport function installSkill(\n skill: BundledSkill,\n agent: DetectedAgent,\n cwd: string,\n): InstallStatus {\n switch (agent.agent) {\n case \"claude\":\n return writeSkillDir(skill, cwd, agent.target, formatClaudeSkill);\n case \"codex\":\n return writeSkillDir(skill, cwd, agent.target, formatCodexSkill);\n case \"openclaw\":\n return writeOpenclawSkill(skill, cwd, agent.target);\n case \"cursor\":\n return writeCursorRule(skill, cwd, agent.target);\n case \"aider\":\n return writeAiderSection(skill, cwd, agent.target);\n }\n}\n\n// ── Claude Code / Codex: <target>/<name>/SKILL.md ─────────────────────\n// Both follow the same convention: a skill directory containing\n// SKILL.md. Frontmatter carries name + description so the agent's\n// indexer picks it up.\n\nfunction formatClaudeSkill(skill: BundledSkill): string {\n return `${versionHeader(skill.name)}\n---\nname: ${skill.name}\ndescription: ${JSON.stringify(skill.description)}\n---\n\n${skill.content}`;\n}\n\nfunction formatCodexSkill(skill: BundledSkill): string {\n // Codex SKILL.md uses the same frontmatter shape as Claude — keeps the\n // wrapper consistent so the underlying doc stays portable.\n return formatClaudeSkill(skill);\n}\n\nfunction writeSkillDir(\n skill: BundledSkill,\n cwd: string,\n targetDir: string,\n format: (s: BundledSkill) => string,\n): InstallStatus {\n const skillDir = join(cwd, targetDir, skill.name);\n const filePath = join(skillDir, \"SKILL.md\");\n const existing = readExistingVersion(filePath);\n if (existing === CLI_VERSION) {\n return { status: \"skipped\", path: filePath, reason: `already at v${CLI_VERSION}` };\n }\n mkdirSync(skillDir, { recursive: true });\n writeFileSync(filePath, format(skill));\n return existing\n ? { status: \"updated\", path: filePath, previousVersion: existing }\n : { status: \"installed\", path: filePath };\n}\n\n// ── OpenClaw: <target>/<name>/SKILL.md + skill.json ───────────────────\n\nfunction writeOpenclawSkill(\n skill: BundledSkill,\n cwd: string,\n targetDir: string,\n): InstallStatus {\n const skillDir = join(cwd, targetDir, skill.name);\n const mdPath = join(skillDir, \"SKILL.md\");\n const jsonPath = join(skillDir, \"skill.json\");\n const existing = readExistingVersion(mdPath);\n if (existing === CLI_VERSION) {\n return { status: \"skipped\", path: mdPath, reason: `already at v${CLI_VERSION}` };\n }\n mkdirSync(skillDir, { recursive: true });\n writeFileSync(mdPath, `${versionHeader(skill.name)}\n${skill.content}`);\n writeFileSync(\n jsonPath,\n JSON.stringify(\n {\n name: skill.name,\n displayName: skill.name\n .split(\"-\")\n .map((p) => p[0].toUpperCase() + p.slice(1))\n .join(\" \"),\n description: skill.description,\n trigger: \"manual\",\n inputs: [],\n },\n null,\n 2,\n ),\n );\n return existing\n ? { status: \"updated\", path: mdPath, previousVersion: existing }\n : { status: \"installed\", path: mdPath };\n}\n\n// ── Cursor: .cursor/rules/<name>.mdc ──────────────────────────────────\n\nfunction writeCursorRule(\n skill: BundledSkill,\n cwd: string,\n targetDir: string,\n): InstallStatus {\n const dir = join(cwd, targetDir);\n const filePath = join(dir, `${skill.name}.mdc`);\n const existing = readExistingVersion(filePath);\n if (existing === CLI_VERSION) {\n return { status: \"skipped\", path: filePath, reason: `already at v${CLI_VERSION}` };\n }\n mkdirSync(dir, { recursive: true });\n const body = `${versionHeader(skill.name)}\n---\ndescription: ${JSON.stringify(skill.description)}\nalwaysApply: false\n---\n\n${skill.content}`;\n writeFileSync(filePath, body);\n return existing\n ? { status: \"updated\", path: filePath, previousVersion: existing }\n : { status: \"installed\", path: filePath };\n}\n\n// ── Aider: append a section to CONVENTIONS.md ─────────────────────────\n// Aider doesn't have a per-skill directory model — its convention is a\n// single CONVENTIONS.md the user --reads into context. We append a\n// marker-delimited section so reruns replace cleanly.\n\nfunction writeAiderSection(\n skill: BundledSkill,\n cwd: string,\n targetFile: string,\n): InstallStatus {\n const filePath = join(cwd, targetFile);\n const startMarker = `<!-- clawnify-skill-start: ${skill.name} -->`;\n const endMarker = `<!-- clawnify-skill-end: ${skill.name} -->`;\n const section = `${startMarker}\n${versionHeader(skill.name)}\n${skill.content}\n${endMarker}\n`;\n\n let existing = \"\";\n let existingVersion: string | null = null;\n if (existsSync(filePath)) {\n existing = readFileSync(filePath, \"utf8\");\n const sectionRe = new RegExp(\n `${escapeRe(startMarker)}[\\\\s\\\\S]*?${escapeRe(endMarker)}\\\\n?`,\n );\n const sectionMatch = existing.match(sectionRe);\n if (sectionMatch) {\n const headMatch = sectionMatch[0].match(VERSION_HEADER_RE);\n existingVersion = headMatch ? headMatch[2] : null;\n if (existingVersion === CLI_VERSION) {\n return { status: \"skipped\", path: filePath, reason: `already at v${CLI_VERSION}` };\n }\n // Replace the existing section in place.\n const next = existing.replace(sectionRe, section);\n mkdirSync(dirname(filePath), { recursive: true });\n writeFileSync(filePath, next);\n return existingVersion\n ? { status: \"updated\", path: filePath, previousVersion: existingVersion }\n : { status: \"installed\", path: filePath };\n }\n }\n\n // No existing section — append (creating the file if needed).\n mkdirSync(dirname(filePath), { recursive: true });\n const prefix = existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n writeFileSync(filePath, existing + prefix + section);\n return { status: \"installed\", path: filePath };\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Remove a skill installation from an agent's target. Returns true if\n * something was removed.\n */\nexport function removeSkill(\n skillName: string,\n agent: DetectedAgent,\n cwd: string,\n): boolean {\n if (agent.agent === \"aider\") {\n const filePath = join(cwd, agent.target);\n if (!existsSync(filePath)) return false;\n const content = readFileSync(filePath, \"utf8\");\n const startMarker = `<!-- clawnify-skill-start: ${skillName} -->`;\n const endMarker = `<!-- clawnify-skill-end: ${skillName} -->`;\n const sectionRe = new RegExp(\n `${escapeRe(startMarker)}[\\\\s\\\\S]*?${escapeRe(endMarker)}\\\\n?`,\n );\n if (!sectionRe.test(content)) return false;\n writeFileSync(filePath, content.replace(sectionRe, \"\"));\n return true;\n }\n\n if (agent.agent === \"cursor\") {\n const candidate = join(cwd, agent.target, `${skillName}.mdc`);\n if (!existsSync(candidate)) return false;\n unlinkSync(candidate);\n return true;\n }\n\n // Directory-based agents (claude, codex, openclaw): blow away the whole\n // skill dir. Small contents (SKILL.md + maybe skill.json), safe to rm -r.\n const dir = join(cwd, agent.target, skillName);\n if (!existsSync(dir)) return false;\n try {\n const s = statSync(dir);\n if (!s.isDirectory()) return false;\n } catch {\n return false;\n }\n rmSync(dir, { recursive: true, force: true });\n return true;\n}\n","/**\n * Write Clawnify's always-on \"rules\" block into an agent's main rules\n * file (CLAUDE.md, AGENTS.md, …). This is the always-in-context layer —\n * distinct from `clawnify skills add`, which installs on-demand skills.\n *\n * The block is marker-delimited and version-pinned so reruns replace it\n * in place rather than appending duplicates. Like skills, the content is\n * bundled in the CLI and only changes when the CLI version changes —\n * re-run `ai-files install` after `npm i -g clawnify@latest` to upgrade.\n */\n\nimport { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { CLI_VERSION, RULES_CONTENT } from \"../skills/content.gen.js\";\nimport type { Agent } from \"../skills/detect.js\";\n\n/** Where each agent reads its always-on instructions. */\nexport const RULES_FILE: Record<Agent, string> = {\n claude: \"CLAUDE.md\",\n cursor: \".cursorrules\",\n openclaw: \"AGENTS.md\",\n codex: \"AGENTS.md\",\n aider: \"CONVENTIONS.md\",\n};\n\nconst START = \"<!-- clawnify:rules:start -->\";\nconst END = \"<!-- clawnify:rules:end -->\";\nconst VERSION_RE = /<!--\\s*clawnify:rules\\s+v([\\d.]+)\\s*-->/;\n\nfunction block(): string {\n return `${START}\n<!-- clawnify:rules v${CLI_VERSION} -->\n${RULES_CONTENT.trimEnd()}\n${END}\n`;\n}\n\nexport type RulesStatus =\n | { status: \"installed\"; file: string }\n | { status: \"updated\"; file: string; previousVersion: string }\n | { status: \"skipped\"; file: string; reason: string };\n\n/**\n * Insert or refresh the rules block in `<cwd>/<file>`. Creates the file\n * if it doesn't exist.\n */\nexport function writeRules(cwd: string, file: string): RulesStatus {\n const filePath = join(cwd, file);\n const section = block();\n const sectionRe = new RegExp(`${escapeRe(START)}[\\\\s\\\\S]*?${escapeRe(END)}\\\\n?`);\n\n if (existsSync(filePath)) {\n const existing = readFileSync(filePath, \"utf8\");\n const match = existing.match(sectionRe);\n if (match) {\n const versionMatch = match[0].match(VERSION_RE);\n const previousVersion = versionMatch ? versionMatch[1] : null;\n if (previousVersion === CLI_VERSION) {\n return { status: \"skipped\", file: filePath, reason: `already at v${CLI_VERSION}` };\n }\n writeFileSync(filePath, existing.replace(sectionRe, section));\n return previousVersion\n ? { status: \"updated\", file: filePath, previousVersion }\n : { status: \"installed\", file: filePath };\n }\n // File exists but has no block — append after a blank line.\n const prefix = existing.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n writeFileSync(filePath, existing + prefix + section);\n return { status: \"installed\", file: filePath };\n }\n\n mkdirSync(dirname(filePath), { recursive: true });\n writeFileSync(filePath, section);\n return { status: \"installed\", file: filePath };\n}\n\n/** Strip the rules block from `<cwd>/<file>`. Returns true if removed. */\nexport function removeRules(cwd: string, file: string): boolean {\n const filePath = join(cwd, file);\n if (!existsSync(filePath)) return false;\n const existing = readFileSync(filePath, \"utf8\");\n const sectionRe = new RegExp(`\\\\n?${escapeRe(START)}[\\\\s\\\\S]*?${escapeRe(END)}\\\\n?`);\n if (!sectionRe.test(existing)) return false;\n const next = existing.replace(sectionRe, \"\\n\").replace(/^\\n+/, \"\").trimEnd();\n if (next) {\n writeFileSync(filePath, next + \"\\n\");\n } else {\n // Our block was the file's only content — don't leave a 0-byte file.\n unlinkSync(filePath);\n }\n return true;\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","/**\n * Wire the Clawnify MCP server into a project-scoped `.mcp.json` so\n * Claude Code (and other clients that read project MCP config) pick it\n * up automatically — no hand-running `claude mcp add`.\n *\n * The server entry runs the CLI's bundled local MCP server\n * (`clawnify --mcp`), which exposes deploy / list_apps / get_app /\n * delete_app. Merge is idempotent: an existing `.mcp.json` is preserved,\n * only the `clawnify` server is added or refreshed.\n */\n\nimport { existsSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nconst FILE = \".mcp.json\";\n\nconst SERVER = {\n command: \"npx\",\n args: [\"clawnify\", \"--mcp\"],\n};\n\nexport type McpStatus =\n | { status: \"installed\"; file: string }\n | { status: \"updated\"; file: string }\n | { status: \"skipped\"; file: string; reason: string };\n\ninterface McpConfig {\n mcpServers?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport function writeMcpConfig(cwd: string): McpStatus {\n const filePath = join(cwd, FILE);\n\n let config: McpConfig = {};\n let existed = false;\n if (existsSync(filePath)) {\n existed = true;\n try {\n config = JSON.parse(readFileSync(filePath, \"utf8\")) as McpConfig;\n } catch {\n return { status: \"skipped\", file: filePath, reason: \"existing .mcp.json is not valid JSON\" };\n }\n }\n\n config.mcpServers ??= {};\n const current = config.mcpServers[\"clawnify\"];\n if (current && JSON.stringify(current) === JSON.stringify(SERVER)) {\n return { status: \"skipped\", file: filePath, reason: \"already configured\" };\n }\n\n const wasPresent = current !== undefined;\n config.mcpServers[\"clawnify\"] = SERVER;\n writeFileSync(filePath, JSON.stringify(config, null, 2) + \"\\n\");\n return existed && wasPresent\n ? { status: \"updated\", file: filePath }\n : { status: \"installed\", file: filePath };\n}\n\n/** Remove the clawnify server from `.mcp.json`. Returns true if removed. */\nexport function removeMcpConfig(cwd: string): boolean {\n const filePath = join(cwd, FILE);\n if (!existsSync(filePath)) return false;\n let config: McpConfig;\n try {\n config = JSON.parse(readFileSync(filePath, \"utf8\")) as McpConfig;\n } catch {\n return false;\n }\n if (!config.mcpServers || !((\"clawnify\") in config.mcpServers)) return false;\n delete config.mcpServers[\"clawnify\"];\n // Drop an empty mcpServers object so we don't leave clutter behind.\n if (Object.keys(config.mcpServers).length === 0) delete config.mcpServers;\n // If nothing else is left, our entry was the file's only content — remove it\n // rather than leaving a meaningless `{}`.\n if (Object.keys(config).length === 0) {\n unlinkSync(filePath);\n } else {\n writeFileSync(filePath, JSON.stringify(config, null, 2) + \"\\n\");\n }\n return true;\n}\n","/**\n * `clawnify ai-files install` — make a project agent-ready in one step.\n *\n * Mirrors the `npx convex ai-files install` pattern: writes Clawnify's\n * always-on rules block into each detected agent's rules file, installs\n * the bundled Clawnify skills, and wires the Clawnify MCP server into a\n * project `.mcp.json`. Re-running after a CLI upgrade refreshes all three\n * in place. `ai-files uninstall` strips them back out.\n */\n\nimport { SKILLS, CLI_VERSION } from \"../lib/skills/registry.js\";\nimport {\n agentByName,\n detectAgents,\n ALL_AGENTS,\n type Agent,\n type DetectedAgent,\n} from \"../lib/skills/detect.js\";\nimport { installSkill, removeSkill } from \"../lib/skills/install.js\";\nimport { writeRules, removeRules, RULES_FILE } from \"../lib/ai-files/rules.js\";\nimport { writeMcpConfig, removeMcpConfig } from \"../lib/ai-files/mcp.js\";\n\ninterface InstallOptions {\n agent?: string;\n mcp?: boolean; // commander sets this false for --no-mcp\n}\n\ninterface UninstallOptions {\n agent?: string;\n}\n\n/**\n * Resolve which agents to target. Explicit `--agent` wins; otherwise we\n * detect agents in the directory; if none are present we default to\n * Claude (writing CLAUDE.md) so a freshly-scaffolded app still becomes\n * agent-ready — matching Convex's CLAUDE.md-centric default.\n */\nfunction resolveAgents(cwd: string, forced: string | undefined): { agents: DetectedAgent[]; defaulted: boolean } {\n if (forced) {\n if (!ALL_AGENTS.includes(forced as Agent)) {\n console.error(`Unknown agent: ${forced}\\nValid: ${ALL_AGENTS.join(\", \")}`);\n process.exit(1);\n }\n return { agents: [agentByName(forced as Agent)], defaulted: false };\n }\n const detected = detectAgents(cwd);\n if (detected.length > 0) return { agents: detected, defaulted: false };\n return { agents: [agentByName(\"claude\")], defaulted: true };\n}\n\ninterface InstallResult {\n rules: number;\n skills: number;\n mcp: boolean;\n}\n\n/**\n * Core install logic, shared by the command and by `clawnify init`'s\n * post-scaffold hook. Writes rules + skills + (optionally) MCP config,\n * logging each touched path. Returns a small tally.\n */\nexport function installAiFiles(\n cwd: string,\n agents: DetectedAgent[],\n opts: { mcp: boolean },\n): InstallResult {\n // Rules — dedupe by target file (codex + openclaw both use AGENTS.md).\n const rulesFiles = [...new Set(agents.map((a) => RULES_FILE[a.agent]))];\n let rules = 0;\n for (const file of rulesFiles) {\n const r = writeRules(cwd, file);\n if (r.status === \"skipped\") {\n console.log(` · rules → ${r.file} (${r.reason})`);\n } else if (r.status === \"updated\") {\n console.log(` ↑ rules → ${r.file} (v${r.previousVersion} → v${CLI_VERSION})`);\n rules++;\n } else {\n console.log(` ✓ rules → ${r.file}`);\n rules++;\n }\n }\n\n // Skills — install every bundled skill into every target agent.\n let skills = 0;\n for (const skill of SKILLS) {\n for (const agent of agents) {\n const s = installSkill(skill, agent, cwd);\n if (s.status === \"skipped\") {\n console.log(` · skill ${skill.name} → ${s.path} (${s.reason})`);\n } else if (s.status === \"updated\") {\n console.log(` ↑ skill ${skill.name} → ${s.path} (v${s.previousVersion} → v${CLI_VERSION})`);\n skills++;\n } else {\n console.log(` ✓ skill ${skill.name} → ${s.path}`);\n skills++;\n }\n }\n }\n\n // MCP server config.\n let mcp = false;\n if (opts.mcp) {\n const m = writeMcpConfig(cwd);\n if (m.status === \"skipped\") {\n console.log(` · mcp → ${m.file} (${m.reason})`);\n } else {\n console.log(` ${m.status === \"updated\" ? \"↑\" : \"✓\"} mcp → ${m.file}`);\n mcp = true;\n }\n }\n\n return { rules, skills, mcp };\n}\n\nexport async function aiFilesInstallCommand(opts: InstallOptions): Promise<void> {\n const cwd = process.cwd();\n const { agents, defaulted } = resolveAgents(cwd, opts.agent);\n\n console.log(`Installing Clawnify AI files (CLI v${CLI_VERSION}):`);\n if (defaulted) {\n console.log(\" No coding agent detected — defaulting to Claude (CLAUDE.md).\");\n }\n console.log(` Agents: ${agents.map((a) => a.agent).join(\", \")}\\n`);\n\n installAiFiles(cwd, agents, { mcp: opts.mcp !== false });\n\n console.log(\"\\nDone. Your project is agent-ready.\");\n console.log(\"Tip: leave `clawnify dev` running so generated types stay fresh.\");\n}\n\nexport async function aiFilesUninstallCommand(opts: UninstallOptions): Promise<void> {\n const cwd = process.cwd();\n // For uninstall, only touch what's actually present — detect, plus the\n // explicit override. Don't default to claude (nothing to guess at).\n const agents = opts.agent\n ? resolveAgents(cwd, opts.agent).agents\n : detectAgents(cwd);\n\n let removed = 0;\n const rulesFiles = [...new Set(agents.map((a) => RULES_FILE[a.agent]))];\n for (const file of rulesFiles) {\n if (removeRules(cwd, file)) {\n console.log(` ✗ rules removed from ${file}`);\n removed++;\n }\n }\n for (const skill of SKILLS) {\n for (const agent of agents) {\n if (removeSkill(skill.name, agent, cwd)) {\n console.log(` ✗ skill ${skill.name} removed from ${agent.agent}`);\n removed++;\n }\n }\n }\n if (removeMcpConfig(cwd)) {\n console.log(\" ✗ clawnify server removed from .mcp.json\");\n removed++;\n }\n\n console.log(`\\nDone — removed ${removed} item${removed === 1 ? \"\" : \"s\"}.`);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { readManifest } from \"../lib/config.js\";\n\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 30);\n}\n\nfunction generateWranglerToml(slug: string, opts: { database: boolean; storage: boolean }): string {\n let toml = `name = \"${slug}\"\nmain = \"../src/server/index.ts\"\ncompatibility_date = \"2025-04-01\"\ncompatibility_flags = [\"nodejs_compat\"]\n`;\n if (opts.database) {\n toml += `\n[[d1_databases]]\nbinding = \"DB\"\ndatabase_name = \"${slug}-db\"\ndatabase_id = \"local\"\n`;\n }\n if (opts.storage) {\n toml += `\n[[r2_buckets]]\nbinding = \"UPLOADS\"\nbucket_name = \"${slug}-uploads\"\n`;\n }\n return toml;\n}\n\nfunction assertNodeVersion() {\n const [major] = process.versions.node.split(\".\").map(Number);\n if (major < 22) {\n console.error(\n `\\n Clawnify requires Node.js v22 or later.\\n` +\n ` You are using v${process.versions.node}.\\n\\n` +\n ` Install a newer version: https://nodejs.org\\n` +\n ` Or use a version manager: nvm use 22\\n`\n );\n process.exit(1);\n }\n}\n\nexport async function devCommand(dir?: string, options?: { port?: string }): Promise<void> {\n assertNodeVersion();\n const resolvedDir = dir ? path.resolve(dir) : process.cwd();\n const manifest = readManifest(resolvedDir);\n\n if (!manifest) {\n console.error(\"No clawnify.json found. Run `clawnify init` first.\");\n process.exit(1);\n }\n\n if (!manifest.app) {\n console.error(\n \"`clawnify dev` is for app projects only. For a website, run `pnpm dev` (astro dev) directly.\",\n );\n process.exit(1);\n }\n\n const slug = slugify(manifest.name);\n const database = manifest.app.database !== false;\n const storage = manifest.app.storage === true;\n const apiPort = options?.port || \"8787\";\n\n // Generate wrangler config in .clawnify/\n const clawnifyDir = path.join(resolvedDir, \".clawnify\");\n fs.mkdirSync(clawnifyDir, { recursive: true });\n const wranglerPath = path.join(clawnifyDir, \"wrangler.toml\");\n fs.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));\n\n // Apply schema to local D1. Two paths, preferred order:\n //\n // 1. schema.ts + drizzle.config.ts (new, gold-standard):\n // Run drizzle-kit generate to emit migrations into\n // .clawnify/drizzle/, then apply unapplied .sql files via\n // wrangler d1 execute --local. Track applied state in\n // .clawnify/applied-migrations.json so reruns are idempotent.\n // The user/agent only ever edits schema.ts.\n //\n // 2. schema.sql (legacy): apply directly. This is what older\n // scaffolds shipped before drizzle support. Kept so existing\n // apps don't regress.\n if (database) {\n const schemaTsPath = path.join(resolvedDir, \"src/server/schema.ts\");\n const drizzleConfigPath = path.join(resolvedDir, \"drizzle.config.ts\");\n if (fs.existsSync(schemaTsPath) && fs.existsSync(drizzleConfigPath)) {\n await syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath);\n } else {\n const schemaCandidates = [\n path.join(resolvedDir, \"schema.sql\"),\n path.join(resolvedDir, \"src/server/schema.sql\"),\n ];\n const schemaPath = schemaCandidates.find((p) => fs.existsSync(p));\n if (schemaPath) {\n await runQuiet(resolvedDir, \"npx\", [\n \"wrangler\", \"d1\", \"execute\", `${slug}-db`,\n \"--local\", `--file=${schemaPath}`,\n `--config=${wranglerPath}`,\n ]);\n }\n }\n }\n\n console.log();\n console.log(` ${manifest.name} dev server`);\n console.log();\n console.log(` UI: http://localhost:5173`);\n console.log(` API: http://localhost:${apiPort}`);\n console.log();\n\n // Spawn vite (frontend) and wrangler dev (API) in parallel\n const vite = spawn(\"npx\", [\"vite\"], {\n cwd: resolvedDir,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env },\n });\n\n const wrangler = spawn(\"npx\", [\n \"wrangler\", \"dev\",\n `--port=${apiPort}`,\n `--config=${wranglerPath}`,\n ], {\n cwd: resolvedDir,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env },\n });\n\n // Filter output — suppress noisy wrangler/vite startup lines, show errors\n const filterVite = createFilter(\"ui\");\n const filterWrangler = createFilter(\"api\");\n\n vite.stdout?.on(\"data\", filterVite);\n vite.stderr?.on(\"data\", filterVite);\n wrangler.stdout?.on(\"data\", filterWrangler);\n wrangler.stderr?.on(\"data\", filterWrangler);\n\n // Handle exit\n const cleanup = () => {\n vite.kill();\n wrangler.kill();\n };\n\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Exit when either process exits\n const exitPromise = Promise.race([\n new Promise<number>((resolve) => vite.on(\"exit\", (code) => resolve(code ?? 1))),\n new Promise<number>((resolve) => wrangler.on(\"exit\", (code) => resolve(code ?? 1))),\n ]);\n\n const code = await exitPromise;\n cleanup();\n process.exit(code);\n}\n\nfunction createFilter(label: string): (data: Buffer) => void {\n // Suppress wrangler banner, version lines, \"Ready on\" (we already printed URLs)\n const suppress = [\n /^\\s*⛅️/,\n /^\\s*wrangler\\s/,\n /^Starting local server/,\n /^Ready on http/,\n /^\\s*\\[mf:inf\\]/,\n /^\\s*╭/,\n /^\\s*│/,\n /^\\s*╰/,\n /^\\s*$/,\n // Vite startup noise\n /VITE v/,\n /ready in \\d+/,\n /Local:\\s+http/,\n /Network:/,\n /press h \\+ enter/,\n ];\n\n return (data: Buffer) => {\n const lines = data.toString().split(\"\\n\");\n for (const line of lines) {\n if (!line.trim()) continue;\n if (suppress.some((re) => re.test(line))) continue;\n // Show meaningful output with label\n console.log(` ${label} │ ${line}`);\n }\n };\n}\n\nfunction runQuiet(cwd: string, cmd: string, args: string[]): Promise<void> {\n return new Promise((resolve, reject) => {\n const proc = spawn(cmd, args, {\n cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { ...process.env },\n });\n\n let stderr = \"\";\n proc.stderr?.on(\"data\", (d: Buffer) => { stderr += d.toString(); });\n\n proc.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else {\n console.error(` Schema init failed: ${stderr.trim()}`);\n reject(new Error(`Command exited with code ${code}`));\n }\n });\n });\n}\n\n/**\n * Ensure local D1 matches the current schema.ts via drizzle-kit.\n *\n * The contract we expose to the user is: edit schema.ts, run\n * `pnpm dev`, it just works. They never touch migration SQL by hand.\n *\n * Flow:\n * 1. `drizzle-kit generate` (writes new migrations under\n * .clawnify/drizzle/ per drizzle.config.ts). No-op if schema.ts\n * hasn't changed since the last generate.\n * 2. Read .clawnify/applied-migrations.json (or []) — the list of\n * .sql files we've already applied to this local D1.\n * 3. For each .sql file in .clawnify/drizzle/ not yet in the list,\n * apply via `wrangler d1 execute --local`, then record it.\n * 4. Write the updated list back.\n *\n * Per-app local state. Each dev's local D1 has its own applied list;\n * production D1 has its own tracking in __clawnify_migrations\n * (handled server-side by the deploy pipeline).\n */\nasync function syncDrizzleToLocalD1(\n resolvedDir: string,\n clawnifyDir: string,\n slug: string,\n wranglerPath: string,\n): Promise<void> {\n try {\n await runQuiet(resolvedDir, \"npx\", [\"drizzle-kit\", \"generate\"]);\n } catch (err) {\n console.error(\n ` drizzle-kit generate failed. Is \\`drizzle-kit\\` in devDependencies?\\n ${(err as Error).message}`,\n );\n throw err;\n }\n\n const drizzleDir = path.join(clawnifyDir, \"drizzle\");\n if (!fs.existsSync(drizzleDir)) return; // nothing to apply yet\n\n const sqlFiles = fs\n .readdirSync(drizzleDir)\n .filter((name) => name.endsWith(\".sql\"))\n .sort();\n if (sqlFiles.length === 0) return;\n\n const appliedPath = path.join(clawnifyDir, \"applied-migrations.json\");\n let applied: string[] = [];\n if (fs.existsSync(appliedPath)) {\n try {\n applied = JSON.parse(fs.readFileSync(appliedPath, \"utf8\")) as string[];\n if (!Array.isArray(applied)) applied = [];\n } catch {\n applied = [];\n }\n }\n const appliedSet = new Set(applied);\n\n for (const file of sqlFiles) {\n if (appliedSet.has(file)) continue;\n const filePath = path.join(drizzleDir, file);\n await runQuiet(resolvedDir, \"npx\", [\n \"wrangler\", \"d1\", \"execute\", `${slug}-db`,\n \"--local\", `--file=${filePath}`,\n `--config=${wranglerPath}`,\n ]);\n applied.push(file);\n }\n\n fs.writeFileSync(appliedPath, JSON.stringify(applied, null, 2) + \"\\n\");\n}\n","import path from \"node:path\";\nimport { api, listMyOrgs, type Org } from \"../lib/api.js\";\nimport { saveProject } from \"../lib/config.js\";\n\ninterface AppDetail {\n id: string;\n name: string;\n slug: string;\n app_token: string;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nasync function findByAppId(orgs: Org[], appId: string) {\n for (const org of orgs) {\n const res = await api.get(`/v1/apps/${appId}`, { orgId: org.id });\n if (res.ok) {\n return { app: (await res.json()) as AppDetail, org };\n }\n if (res.status !== 404) {\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n console.error(`Link failed (${org.name}): ${err.error || res.statusText}`);\n process.exit(1);\n }\n }\n return null;\n}\n\nasync function findBySlug(orgs: Org[], slug: string) {\n for (const org of orgs) {\n const res = await api.get(`/v1/apps`, { orgId: org.id });\n if (!res.ok) {\n if (res.status === 404) continue;\n const err = (await res.json().catch(() => ({}))) as { error?: string };\n console.error(`Link failed (${org.name}): ${err.error || res.statusText}`);\n process.exit(1);\n }\n const payload = (await res.json()) as { apps: AppDetail[] } | AppDetail[];\n const apps = Array.isArray(payload) ? payload : payload.apps;\n const match = apps.find((a) => a.slug === slug);\n if (match) {\n // Re-fetch by id to get app_token (list endpoint may omit it).\n const detailRes = await api.get(`/v1/apps/${match.id}`, { orgId: org.id });\n if (detailRes.ok) {\n return { app: (await detailRes.json()) as AppDetail, org };\n }\n return { app: match, org };\n }\n }\n return null;\n}\n\nexport async function linkCommand(\n appIdOrSlug: string,\n options?: { dir?: string; org?: string },\n): Promise<void> {\n const dir = options?.dir ? path.resolve(options.dir) : process.cwd();\n\n const orgs = await listMyOrgs();\n if (orgs.length === 0) {\n console.error(\"No organizations found. Run `clawnify login` first.\");\n process.exit(1);\n }\n\n const candidates = options?.org\n ? orgs.filter((o) => o.id === options.org || o.slug === options.org)\n : orgs;\n\n if (candidates.length === 0) {\n console.error(\n `No org matched \"${options?.org}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(1);\n }\n\n const isUuid = UUID_RE.test(appIdOrSlug);\n const matched = isUuid\n ? await findByAppId(candidates, appIdOrSlug)\n : await findBySlug(candidates, appIdOrSlug);\n\n if (!matched) {\n const kind = isUuid ? \"id\" : \"slug\";\n console.error(\n `App with ${kind} '${appIdOrSlug}' not found in ${candidates.map((o) => o.slug).join(\", \")}.`,\n );\n process.exit(1);\n }\n\n saveProject(dir, {\n org_id: matched.org.id,\n org_slug: matched.org.slug,\n app_id: matched.app.id,\n slug: matched.app.slug,\n app_token: matched.app.app_token,\n });\n\n const rel = path.relative(process.cwd(), dir) || \".\";\n console.log(` Linked ${matched.app.name} (${matched.app.slug}) in ${matched.org.name}`);\n console.log(` Wrote ${rel}/.clawnify/project.json`);\n console.log(` Run \\`clawnify deploy\\` to push the current source to this app.`);\n}\n","import path from \"node:path\";\nimport { fetchSchema, resolveApp, writeSchema } from \"../lib/sync-schema.js\";\n\ninterface PullSchemaOptions {\n from?: string;\n out?: string;\n force?: boolean;\n org?: string;\n}\n\n/**\n * `clawnify pull schema --from <app-id-or-slug>`\n *\n * Fetch the deployed app's current schema.sql snapshot and write it to\n * the local working directory. Used to back-port a deployed instance's\n * evolved schema into an open-source template repo, or to refresh a\n * developer's local copy after agent-driven schema changes.\n *\n * Refuses to overwrite a locally-modified schema.sql unless --force is\n * passed. Refusal is git-aware: if the local file has uncommitted\n * changes (or we're outside git and the file differs), we bail with a\n * helpful message instead of silently clobbering work.\n */\nexport async function pullSchemaCommand(options: PullSchemaOptions): Promise<void> {\n if (!options.from) {\n console.error(\"Usage: clawnify pull schema --from <app-id-or-slug>\");\n process.exit(64);\n }\n\n const ref = await resolveApp(options.from, options.org);\n if (!ref) {\n console.error(`App '${options.from}' not found in your orgs.`);\n process.exit(1);\n }\n\n let schema: string | null;\n try {\n schema = await fetchSchema(ref);\n } catch (err) {\n console.error(`Failed to fetch schema: ${(err as Error).message}`);\n process.exit(1);\n }\n\n const targetPath = path.resolve(options.out ?? \"schema.sql\");\n\n const result = await writeSchema(targetPath, schema, { force: options.force });\n const rel = path.relative(process.cwd(), result.path) || result.path;\n\n switch (result.status) {\n case \"no-schema\":\n console.log(` ${ref.slug}: no schema.sql in R2 (pre-backfill app, or no database)`);\n process.exit(0);\n\n case \"unchanged\":\n console.log(` ${rel} is already up to date`);\n process.exit(0);\n\n case \"written\":\n console.log(` ✓ wrote ${rel} (${result.bytes} bytes, from ${ref.slug})`);\n process.exit(0);\n\n case \"refused-uncommitted\":\n console.error(\n ` ${rel} has uncommitted changes — refusing to overwrite.\\n` +\n ` Commit/stash first, or rerun with --force.`,\n );\n process.exit(1);\n\n case \"refused-different\":\n console.error(\n ` ${rel} exists locally and differs from the deployed copy.\\n` +\n ` Not inside a git repo — can't tell intent. Rerun with --force to overwrite.`,\n );\n process.exit(1);\n }\n}\n","import { listMyOrgs } from \"../lib/api.js\";\nimport { loadAuth, saveAuth } from \"../lib/auth.js\";\n\nexport async function orgListCommand(): Promise<void> {\n const orgs = await listMyOrgs();\n if (orgs.length === 0) {\n console.log(\"No organizations.\");\n return;\n }\n const auth = loadAuth();\n const nameWidth = Math.max(4, ...orgs.map((o) => o.name.length));\n const slugWidth = Math.max(4, ...orgs.map((o) => o.slug.length));\n console.log(`${\"Name\".padEnd(nameWidth)} ${\"Slug\".padEnd(slugWidth)} Role Active`);\n console.log(`${\"─\".repeat(nameWidth)} ${\"─\".repeat(slugWidth)} ─────── ──────`);\n for (const o of orgs) {\n const active = auth?.org_id === o.id ? \" *\" : \"\";\n console.log(\n `${o.name.padEnd(nameWidth)} ${o.slug.padEnd(slugWidth)} ${o.role.padEnd(7)}${active}`\n );\n }\n}\n\nexport async function orgUseCommand(slugOrId: string): Promise<void> {\n const orgs = await listMyOrgs();\n const match = orgs.find((o) => o.id === slugOrId || o.slug === slugOrId);\n if (!match) {\n console.error(\n `No org matched \"${slugOrId}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`\n );\n process.exit(1);\n }\n const auth = loadAuth();\n if (!auth) {\n console.error(\"Not logged in. Run `clawnify login` first.\");\n process.exit(1);\n }\n saveAuth({ ...auth, org_id: match.id, org_slug: match.slug });\n console.log(` Active org set to ${match.name} (${match.slug})`);\n}\n","import { api } from \"../lib/api.js\";\n\n// The §3.5 naming catalog — the \"wrangler secret list\" of Clawnify. One read\n// returns the union of static canon and this org's live state so callers reuse\n// canonical identifiers instead of inventing them.\ninterface Catalog {\n integrations: Array<{\n id: string;\n label: string;\n connected: boolean;\n kind: string;\n accessor: string;\n description?: string;\n hasTriggers?: boolean;\n }>;\n providerKeys: Array<{ name: string; provider: string; set: boolean; accessor: string }>;\n customEnv: Array<{ name: string; set: boolean; hint?: string }>;\n}\n\nexport async function connectionsListCommand(opts?: { json?: boolean }): Promise<void> {\n const res = await api.get(\"/v1/connections/catalog\");\n if (!res.ok) {\n console.error(\"Failed to fetch the connections catalog.\");\n process.exit(1);\n }\n\n const catalog = (await res.json()) as Catalog;\n\n // Agent-consumable form: the full catalog payload, including fields the\n // table omits (docs, spec_url — the provider's published OpenAPI spec).\n if (opts?.json) {\n console.log(JSON.stringify(catalog, null, 2));\n return;\n }\n\n const idWidth = Math.max(2, ...catalog.integrations.map((i) => i.id.length));\n const labelWidth = Math.max(5, ...catalog.integrations.map((i) => i.label.length));\n\n console.log(\"Integrations (use the exact id — never invent a slug)\\n\");\n console.log(\n ` ${\"Id\".padEnd(idWidth)} ${\"Label\".padEnd(labelWidth)} ${\"State\".padEnd(9)} Accessor`\n );\n console.log(\n ` ${\"─\".repeat(idWidth)} ${\"─\".repeat(labelWidth)} ${\"─\".repeat(9)} ${\"─\".repeat(30)}`\n );\n for (const i of catalog.integrations) {\n const state = i.connected ? \"● active\" : \"○ —\";\n console.log(\n ` ${i.id.padEnd(idWidth)} ${i.label.padEnd(labelWidth)} ${state.padEnd(9)} ${i.accessor}`\n );\n }\n\n const keyWidth = Math.max(4, ...catalog.providerKeys.map((k) => k.name.length));\n console.log(\"\\nProvider keys (fixed names, set in Settings → API Keys)\\n\");\n for (const k of catalog.providerKeys) {\n console.log(` ${k.name.padEnd(keyWidth)} ${k.set ? \"● set\" : \"○ unset\"}`);\n }\n\n console.log(\"\\nCustom env (this org's user-defined vars)\\n\");\n if (catalog.customEnv.length === 0) {\n console.log(\" (none set)\");\n } else {\n const envWidth = Math.max(4, ...catalog.customEnv.map((e) => e.name.length));\n for (const e of catalog.customEnv) {\n console.log(` ${e.name.padEnd(envWidth)} ● set${e.hint ? ` (${e.hint})` : \"\"}`);\n }\n }\n}\n\nconst INTEGRATIONS_URL = \"https://app.clawnify.com/settings/integrations\";\n\n/**\n * `clawnify connections connect <id>` — explain how to connect an integration.\n * Connecting is an OAuth flow that needs the user's authorization in a browser;\n * neither the CLI nor an agent can do it. This validates the id against the\n * catalog and prints the canonical steps (so the FDE relays correct guidance\n * instead of improvising a dashboard path) — it never attempts the connect.\n */\nexport async function connectionsConnectCommand(\n id: string,\n opts?: { json?: boolean },\n): Promise<void> {\n const res = await api.get(\"/v1/connections/catalog\");\n if (!res.ok) {\n console.error(\"Failed to fetch the connections catalog.\");\n process.exit(1);\n }\n const catalog = (await res.json()) as Catalog;\n const match = catalog.integrations.find((i) => i.id === id);\n\n if (!match) {\n console.error(\n `No integration with id \"${id}\". Run \\`clawnify connections list\\` for valid ids.\\n` +\n `(Provider API keys are set in Settings → API Keys; custom env in Settings → Environment Variables.)`,\n );\n process.exit(1);\n }\n if (match.connected) {\n console.log(`\"${match.label}\" (${id}) is already connected (● active). Nothing to do.`);\n return;\n }\n\n const steps = [\n `Open ${INTEGRATIONS_URL}`,\n `Find \"${match.label}\" and click Connect`,\n `Complete the sign-in / authorization in the browser`,\n `Re-run your command once it shows connected`,\n ];\n if (opts?.json) {\n console.log(\n JSON.stringify(\n { id, label: match.label, connected: false, connect_url: INTEGRATIONS_URL, steps },\n null,\n 2,\n ),\n );\n return;\n }\n console.log(`\"${match.label}\" (${id}) is not connected.\\n`);\n console.log(\n \"Connecting it needs your authorization in a browser — the CLI and the agent can't do it for you. To connect it:\\n\",\n );\n steps.forEach((s, n) => console.log(` ${n + 1}. ${s}`));\n console.log(`\\n ${INTEGRATIONS_URL}`);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { api, listMyOrgs, type Org } from \"../lib/api.js\";\nimport { getValidToken, loadAuth } from \"../lib/auth.js\";\n\ninterface WorkspaceInitOptions {\n org?: string;\n name?: string;\n}\n\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 30);\n}\n\n/**\n * Resolve which org the workspace binds to: an explicit --org wins, otherwise\n * the active org, otherwise the sole org if the user only belongs to one.\n * Errors (rather than guessing) when the choice is ambiguous.\n */\nasync function resolveOrg(opts?: WorkspaceInitOptions): Promise<Org> {\n const orgs = await listMyOrgs();\n if (orgs.length === 0) {\n console.error(\"No organizations on your account. Run `clawnify login` first.\");\n process.exit(1);\n }\n\n if (opts?.org) {\n const match = orgs.find((o) => o.id === opts.org || o.slug === opts.org);\n if (!match) {\n console.error(\n `No org matched \"${opts.org}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(1);\n }\n return match;\n }\n\n const auth = loadAuth();\n const active = orgs.find((o) => o.id === auth?.org_id);\n if (active) return active;\n if (orgs.length === 1) return orgs[0]!;\n\n console.error(\n \"Multiple orgs — pick one with `--org <slug>` (or set a default: `clawnify org use <slug>`).\\n\" +\n ` Available: ${orgs.map((o) => o.slug).join(\", \")}`,\n );\n process.exit(1);\n}\n\nfunction write(dir: string, file: string, content: string) {\n const fullPath = path.join(dir, file);\n fs.mkdirSync(path.dirname(fullPath), { recursive: true });\n fs.writeFileSync(fullPath, content);\n}\n\nexport async function workspaceInitCommand(\n dir?: string,\n opts?: WorkspaceInitOptions,\n): Promise<void> {\n const org = await resolveOrg(opts);\n const name = opts?.name || org.name;\n const targetDir = dir ? path.resolve(dir) : path.resolve(slugify(org.slug));\n\n if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {\n console.error(`Directory ${targetDir} is not empty.`);\n process.exit(1);\n }\n\n // clawnify.json — workspace root. No app/website block; binds the org.\n // The org is stored as a slug (human-readable, matches `--org` semantics);\n // deploy resolves it to an id at push time.\n write(targetDir, \"clawnify.json\", JSON.stringify({\n $schema: \"https://app.clawnify.com/schema/v1/clawnify.json\",\n version: 1,\n name,\n workspace: { org: org.slug },\n }, null, 2));\n\n // pnpm workspace so one `pnpm install` hoists deps across every app, plus\n // the org's single website.\n write(targetDir, \"pnpm-workspace.yaml\", `packages:\n - \"apps/*\"\n - \"website\"\n`);\n\n write(targetDir, \"package.json\", JSON.stringify({\n name: slugify(org.slug),\n private: true,\n type: \"module\",\n }, null, 2));\n\n // Root .gitignore — per-app link state (.clawnify) and secrets stay local;\n // the org binding in clawnify.json is the only thing committed for routing.\n write(targetDir, \".gitignore\", `node_modules\ndist\n.wrangler\n.clawnify\n.env*\n!.env.example\n.dev.vars\ndata.db\ndata.db-wal\ndata.db-shm\n`);\n\n write(targetDir, \"README.md\", `# ${name}\n\nClawnify workspace for the **${org.name}** org (\\`${org.slug}\\`).\n\nLayout:\n\n- \\`apps/<name>/\\` — one folder per app; each deploys to this org automatically.\n- \\`agents/<name>/\\` — one folder per OpenClaw agent (AGENT.md, skills/, flows/).\n- \\`website/\\` — the org's single public website (Astro).\n\n## Add an app / an agent / the website\n\n\\`\\`\\`bash\nclawnify init # app → apps/<name>/ (inherits the org)\nclawnify init --type agent # agent → agents/<name>/\nclawnify init --type website # site → website/\n\\`\\`\\`\n\n## Deploy\n\n\\`\\`\\`bash\nclawnify deploy apps/<name> # one app (or: cd apps/<name> && clawnify deploy)\nclawnify deploy website # the website\n\\`\\`\\`\n\n## Install dependencies\n\n\\`\\`\\`bash\npnpm install # hoists deps for every app + the website\n\\`\\`\\`\n\n## GitHub sync (optional)\n\nPush this repo to a single GitHub monorepo, then in the dashboard link each app\nand the website to its own subdirectory (\\`apps/<name>\\`, \\`website\\`). Pushing the\nrepo auto-deploys only the targets whose folder changed; Clawnify mirrors edits\nback under the same subdirs. See \\`docs/internal/adr-company-monorepo.md\\` § \"GitHub sync\".\n`);\n\n // Keep apps/, agents/, and website/ in git even before anything is added.\n write(targetDir, \"apps/.gitkeep\", \"\");\n write(targetDir, \"agents/.gitkeep\", \"\");\n write(targetDir, \"website/.gitkeep\", \"\");\n\n const rel = path.relative(process.cwd(), targetDir) || \".\";\n console.log();\n console.log(` Created workspace for ${org.name} (${org.slug}) in ${rel}/`);\n console.log();\n console.log(\" Get started:\");\n if (rel !== \".\") console.log(` cd ${rel}`);\n console.log(` clawnify init # add an app under apps/`);\n console.log(` clawnify deploy apps/<name>`);\n console.log();\n}\n\n// ---------------------------------------------------------------------------\n// `clawnify workspace` (bare) — orientation for humans AND coding agents.\n// Prints who you are, which GitHub repo backs the org, the subdir↔target\n// map, and the operating contract for editing locally. This is the CLI's\n// front door: a one-line prompt (\"run `npx clawnify@latest workspace` and\n// follow it\") must be enough for an agent to bootstrap.\n// ---------------------------------------------------------------------------\n\ninterface WorkspaceStatusOptions {\n json?: boolean;\n}\n\ninterface RepoLink {\n repo: string;\n branch: string;\n subdir: string;\n auto_deploy: boolean;\n installation_id: number;\n target:\n | { type: \"app\"; slug: string; name: string }\n | { type: \"website\"; slug: string }\n | { type: \"agent\"; name: string };\n}\n\n/** The operating contract, phrased for a coding agent. Version-shipped with\n * the CLI, so `npx clawnify@latest` always prints the current rules. */\nconst WORKSPACE_GUIDE = `How editing works:\n - The org has ONE workspace repo on GitHub. The website lives under\n website/ (Astro), apps under apps/<slug>/, agent configs under\n agents/<name>/. Each folder two-way syncs with Clawnify.\n - Pushing to the synced branch auto-rebuilds ONLY the folders that\n changed. Clawnify also pushes its own edits back into the repo, so\n pull before you start.\n - Website: cd website && pnpm install && pnpm dev (Node 22+; preview on\n localhost:4321). Do NOT use \\`clawnify dev\\` for the website — it is\n for apps only. Reuse the existing components/blocks under src/.\n - Apps: cd apps/<slug> && clawnify dev.\n - Website deploys (via push or \\`clawnify deploy\\` from website/) land on\n the DRAFT site (<slug>.draft-site.clawnify.com), visible only to the\n org. Going live is a separate \"Publish\" step in the dashboard —\n remind the user.\n - NEVER commit .env files or .clawnify/ folders — they hold secrets.\n Never commit or echo tokens found in them.\n - Run \\`clawnify ai-files install\\` in the repo once: it installs\n Clawnify rules, skills, and MCP access for coding agents.\n - Per-app deep docs: \\`clawnify docs <app-slug>\\`.`;\n\nexport async function workspaceStatusCommand(\n opts?: WorkspaceStatusOptions,\n): Promise<void> {\n const token = await getValidToken();\n if (!token) {\n if (opts?.json) {\n console.log(JSON.stringify({ logged_in: false, next: \"clawnify login\" }));\n process.exit(1);\n }\n console.log(`Not logged in.\n\n \\`clawnify login\\` opens a browser for OAuth — a coding agent cannot\n complete it headlessly. Ask the user to run:\n\n npx clawnify@latest login\n\n then re-run \\`clawnify workspace\\`.\n\n${WORKSPACE_GUIDE}`);\n process.exit(1);\n }\n\n const auth = loadAuth();\n const orgId = auth?.org_id ?? process.env.CLAWNIFY_ORG_ID;\n const res = await api.get(\"/v1/github/links\", orgId ? { orgId } : undefined);\n if (!res.ok) {\n console.error(`Failed to load workspace state (${res.status}).`);\n process.exit(1);\n }\n const data = (await res.json()) as {\n org_id: string;\n installations: { installation_id: number; github_account: string }[];\n links: RepoLink[];\n };\n\n if (opts?.json) {\n console.log(JSON.stringify({ logged_in: true, ...data, guide: WORKSPACE_GUIDE }));\n return;\n }\n\n const orgLabel = auth?.org_slug ?? data.org_id;\n console.log(`Org: ${orgLabel}`);\n\n if (data.links.length === 0) {\n console.log(`\n No GitHub repo is linked yet. Local editing works through the org's\n synced workspace repo — connect it first (needs the dashboard):\n\n app.clawnify.com → Website (or an app) → GitHub icon → Connect\n\n That creates the workspace repo and pushes the current source. Then\n re-run \\`clawnify workspace\\` to get the clone URL.\n\n${WORKSPACE_GUIDE}`);\n return;\n }\n\n // Group links by repo (normally exactly one workspace repo per org/account).\n const byRepo = new Map<string, RepoLink[]>();\n for (const l of data.links) {\n const list = byRepo.get(`${l.repo}#${l.branch}`) ?? [];\n list.push(l);\n byRepo.set(`${l.repo}#${l.branch}`, list);\n }\n\n for (const [key, list] of byRepo) {\n const [repo, branch] = key.split(\"#\");\n console.log(`\\nRepo: ${repo} (branch ${branch})`);\n console.log(` Clone: git clone https://github.com/${repo}.git`);\n for (const l of list) {\n const label =\n l.target.type === \"app\"\n ? `app: ${l.target.name} (${l.target.slug})`\n : l.target.type === \"website\"\n ? `website: ${l.target.slug}`\n : `agent: ${l.target.name}`;\n console.log(` ${(l.subdir || \"(root)\").padEnd(28)} ${label}`);\n }\n }\n\n console.log(`\\n${WORKSPACE_GUIDE}`);\n}\n","import fs from \"node:fs\";\nimport { callTool, isError } from \"../lib/mcp-client.js\";\n\n/**\n * `clawnify execute [file]` / `clawnify execute -c \"code\"` — run\n * TypeScript on the active org's substrate via mcp.clawnify.com.\n *\n * Streams the result to stdout/stderr matching the substrate's exit\n * code. Useful for ad-hoc code-mode invocations from the terminal;\n * agent runtimes call the underlying MCP tool directly.\n */\nexport async function executeCommand(\n file: string | undefined,\n options: { code?: string; timeout?: string },\n) {\n let code: string;\n if (options.code) {\n code = options.code;\n } else if (file) {\n try {\n code = fs.readFileSync(file, \"utf-8\");\n } catch (err) {\n process.stderr.write(`Failed to read ${file}: ${String(err)}\\n`);\n process.exit(1);\n }\n } else {\n process.stderr.write(\n \"Provide a file path or --code 'inline code'.\\n\" +\n \"Usage: clawnify execute path/to/file.ts\\n\" +\n \" clawnify execute -c \\\"console.log(1 + 1)\\\"\\n\",\n );\n process.exit(1);\n }\n\n const timeout_ms = options.timeout ? Math.max(1000, parseInt(options.timeout, 10) * 1000) : 30000;\n\n const resp = await callTool(\"clawnify_execute\", { code, timeout_ms });\n if (isError(resp)) {\n process.stderr.write(`Error ${resp.error.code}: ${resp.error.message}\\n`);\n process.exit(1);\n }\n\n const sc = resp.result.structuredContent as\n | {\n stdout?: string;\n stderr?: string;\n exit_code?: number;\n duration_ms?: number;\n timed_out?: boolean;\n substrate_id?: string;\n runtime?: string;\n }\n | undefined;\n\n if (sc) {\n if (sc.stdout) process.stdout.write(sc.stdout);\n if (sc.stderr) process.stderr.write(sc.stderr);\n if (sc.timed_out) {\n process.stderr.write(`\\n[clawnify] timed out after ${timeout_ms}ms on ${sc.substrate_id}\\n`);\n }\n process.exit(sc.exit_code ?? 0);\n }\n\n // Fallback: surface the human-readable content[] entries\n for (const c of resp.result.content) {\n if (c.type === \"text\") process.stdout.write(c.text + \"\\n\");\n }\n process.exit(resp.result.isError ? 1 : 0);\n}\n","/**\n * Thin HTTP client for mcp.clawnify.com. Talks JSON-RPC 2.0 over POST\n * per the MCP Streamable HTTP transport. Reused by the `execute`,\n * `docs`, and `sdk inspect` subcommands; the stdio bridge uses raw\n * pass-through instead.\n */\n\nimport { getValidToken } from \"./auth.js\";\nimport { resolveOrgContext } from \"./api.js\";\n\nconst MCP_URL = \"https://mcp.clawnify.com/mcp\";\n\nexport interface McpToolResult {\n content: Array<\n | { type: \"text\"; text: string }\n | { type: \"image\"; data: string; mimeType: string }\n | { type: \"resource\"; resource: { uri: string; mimeType?: string; text?: string } }\n >;\n isError?: boolean;\n structuredContent?: unknown;\n}\n\nexport interface McpErrorResponse {\n error: { code: number; message: string };\n}\n\nexport type McpToolCallResponse = { result: McpToolResult } | McpErrorResponse;\n\nexport async function callTool(\n name: string,\n args: Record<string, unknown>,\n): Promise<McpToolCallResponse> {\n const token = await getValidToken();\n if (!token) {\n process.stderr.write(\"Not logged in. Run `clawnify login` first.\\n\");\n process.exit(1);\n }\n\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n authorization: \"Bearer \" + token,\n };\n const orgId = await resolveOrgContext();\n if (orgId) {\n headers[\"X-Clawnify-Org-Id\"] = orgId;\n }\n\n const res = await fetch(MCP_URL, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: Date.now(),\n method: \"tools/call\",\n params: { name, arguments: args },\n }),\n });\n\n if (res.status === 401) {\n process.stderr.write(\"Authentication failed. Run `clawnify login` again.\\n\");\n process.exit(1);\n }\n\n const body = (await res.json()) as { result?: McpToolResult; error?: { code: number; message: string } };\n if (body.error) return { error: body.error };\n if (!body.result) {\n return { error: { code: -32603, message: \"Empty response from MCP gateway\" } };\n }\n return { result: body.result };\n}\n\nexport function isError(resp: McpToolCallResponse): resp is McpErrorResponse {\n return \"error\" in resp;\n}\n","import { getValidToken, loadAuth } from \"../lib/auth.js\";\n\n/**\n * `clawnify docs [<app-slug>]` — fetch the skill-convention README\n * for an app (or the org-level index) from the docs runtime worker.\n *\n * Hits clawnify-mcp-docs directly via its public workers.dev URL\n * with the caller's Supabase access_token. Today the docs worker\n * trusts that anyone reaching it has been authenticated upstream;\n * the CLI is the upstream for human invocation.\n *\n * For agent use, `clawnify_docs_search` (via mcp.clawnify.com) is\n * the equivalent — that path also goes through the docs worker via\n * Service Binding.\n */\n\nconst DOCS_URL = \"https://clawnify-mcp-docs.workers.dev\";\n\nexport async function docsCommand(\n slug: string | undefined,\n options: { caller?: string },\n) {\n const token = await getValidToken();\n if (!token) {\n process.stderr.write(\"Not logged in. Run `clawnify login` first.\\n\");\n process.exit(1);\n }\n\n const auth = loadAuth();\n if (!auth?.org_id) {\n process.stderr.write(\n \"No active org. Pick one with `clawnify org use <slug-or-id>` first.\\n\",\n );\n process.exit(1);\n }\n\n const caller = options.caller ?? \"external\";\n const path = slug ? `/docs/${auth.org_id}/${slug}.md?caller=${caller}` : `/docs/${auth.org_id}/index.md`;\n\n const res = await fetch(DOCS_URL + path, {\n headers: {\n authorization: \"Bearer \" + token,\n },\n });\n\n if (!res.ok) {\n process.stderr.write(`Failed to fetch docs: ${res.status} ${res.statusText}\\n`);\n process.exit(1);\n }\n\n const md = await res.text();\n process.stdout.write(md);\n if (!md.endsWith(\"\\n\")) process.stdout.write(\"\\n\");\n}\n","import readline from \"node:readline\";\nimport { getValidToken, loadAuth } from \"../lib/auth.js\";\n\n/**\n * `clawnify mcp` — stdio bridge to mcp.clawnify.com.\n *\n * Reads newline-delimited JSON-RPC messages from stdin (the MCP\n * stdio transport convention), forwards each as an HTTP POST to\n * mcp.clawnify.com/mcp with the stored Bearer token, and writes\n * the JSON-RPC response back to stdout.\n *\n * Used by bash-less MCP clients (Claude Desktop, ChatGPT custom\n * apps) per docs/internal/agent-tiering.md § \"Surface 3 — MCP\". Bash-capable\n * agents should use the CLI directly (clawnify execute / docs /\n * sdk inspect) — same auth, fewer hops.\n *\n * Notifications (no `id`) yield 202 with no body; we emit nothing.\n * Errors during forwarding emit a JSON-RPC error response with the\n * original request id so the client surfaces them cleanly.\n */\n\nconst MCP_URL = \"https://mcp.clawnify.com/mcp\";\n\nexport async function mcpBridgeCommand() {\n const token = await getValidToken();\n if (!token) {\n process.stderr.write(\"Not logged in. Run `clawnify login` first.\\n\");\n process.exit(1);\n }\n\n const auth = loadAuth();\n const baseHeaders: Record<string, string> = {\n \"content-type\": \"application/json\",\n authorization: \"Bearer \" + token,\n };\n if (auth?.org_id) {\n baseHeaders[\"X-Clawnify-Org-Id\"] = auth.org_id;\n }\n\n const rl = readline.createInterface({ input: process.stdin, terminal: false });\n\n rl.on(\"line\", async (line) => {\n const trimmed = line.trim();\n if (!trimmed) return;\n\n let parsedId: string | number | null = null;\n try {\n parsedId = (JSON.parse(trimmed) as { id?: string | number | null }).id ?? null;\n } catch {\n // Malformed JSON — let the gateway surface the parse error;\n // it'll respond with a JSON-RPC parse error of its own.\n }\n\n try {\n const res = await fetch(MCP_URL, {\n method: \"POST\",\n headers: baseHeaders,\n body: trimmed,\n });\n const text = await res.text();\n // 202 (notification ack) returns empty body — emit nothing.\n if (text.length > 0) {\n process.stdout.write(text);\n if (!text.endsWith(\"\\n\")) process.stdout.write(\"\\n\");\n }\n } catch (err) {\n const errResp = {\n jsonrpc: \"2.0\",\n id: parsedId,\n error: { code: -32603, message: \"bridge transport error: \" + String(err) },\n };\n process.stdout.write(JSON.stringify(errResp) + \"\\n\");\n }\n });\n\n rl.on(\"close\", () => {\n process.exit(0);\n });\n}\n","import { loginCommand } from \"./login.js\";\nimport { docsCommand } from \"./docs.js\";\n\n/**\n * `clawnify sdk inspect <slug>` — show the typed-procedure README\n * for an app. Same data as `clawnify docs <slug>` but with a\n * developer-shaped command name per docs/internal/agent-tiering.md §\n * \"Three surfaces, three jobs\".\n *\n * `clawnify sdk login` — alias for `clawnify login`, kept so the\n * full surface advertised in agent-tiering.md (`sdk install`,\n * `sdk inspect`, `sdk login`) is reachable today.\n *\n * `clawnify sdk install` — deferred to a follow-up PR. Depends on\n * publishing the `@clawnify/sdk` npm package, which depends on the\n * template-strategy / build-pipeline manifest writer landing first.\n */\n\nexport async function sdkInspectCommand(slug: string, options: { caller?: string }) {\n // External density gives the richest cut — examples + anti-patterns.\n // Best for developers inspecting an app from the terminal.\n await docsCommand(slug, { caller: options.caller ?? \"external\" });\n}\n\nexport async function sdkLoginCommand() {\n await loginCommand();\n}\n\nexport async function sdkInstallCommand() {\n process.stderr.write(\n \"`clawnify sdk install` is not yet implemented.\\n\" +\n \"It depends on the `@clawnify/sdk` npm package being published, \" +\n \"which depends on the build-pipeline manifest writer (template-strategy.md).\\n\" +\n \"Track in the Phase 5 follow-up.\\n\",\n );\n process.exit(1);\n}\n","/**\n * `clawnify skills` — install / list / remove Clawnify-curated skills\n * into whichever coding agents you have in the current directory.\n *\n * Behavior:\n * - `list` shows every skill the CLI bundles + its version.\n * - `add <name|--all>` writes the skill into EVERY detected agent\n * simultaneously (.claude, .cursor, .openclaw, .codex, aider).\n * - `remove <name|--all>` cleans them back out of every agent.\n *\n * Version semantics: each installed file carries a\n * `<!-- clawnify-skill: <name> v<X.Y.Z> -->` header. Re-running `add`\n * on the same CLI version is a no-op; upgrading the CLI (`npm install\n * -g clawnify@latest`) then re-running `add` overwrites with the new\n * content. This is the only way skills update — there is no runtime\n * network fetch.\n */\n\nimport { SKILLS, CLI_VERSION, type BundledSkill } from \"../lib/skills/registry.js\";\nimport {\n agentByName,\n detectAgents,\n ALL_AGENTS,\n type Agent,\n type DetectedAgent,\n} from \"../lib/skills/detect.js\";\nimport { installSkill, removeSkill } from \"../lib/skills/install.js\";\n\ninterface AddOptions {\n all?: boolean;\n agent?: string;\n}\n\ninterface RemoveOptions {\n all?: boolean;\n agent?: string;\n}\n\nexport function skillsListCommand(): void {\n console.log(`Clawnify skills (v${CLI_VERSION}):\\n`);\n for (const s of SKILLS) {\n console.log(` ${s.name}`);\n console.log(` ${s.description}\\n`);\n }\n console.log(`Add one: clawnify skills add <name>`);\n console.log(`Add all: clawnify skills add --all`);\n console.log(`Remove: clawnify skills remove <name>`);\n}\n\nexport async function skillsAddCommand(name: string | undefined, opts: AddOptions): Promise<void> {\n const skills = resolveSkills(name, opts.all);\n if (skills.length === 0) {\n console.error(\"No skill specified. Pass a name or --all. See `clawnify skills list`.\");\n process.exit(1);\n }\n\n const agents = resolveAgents(opts.agent);\n if (agents.length === 0) {\n console.error(\n \"No coding agent detected in this directory. Looked for:\\n\" +\n \" .claude/ (Claude Code)\\n\" +\n \" .cursor/ (Cursor)\\n\" +\n \" .openclaw/ (OpenClaw)\\n\" +\n \" .codex/ or AGENTS.md (Codex)\\n\" +\n \" CONVENTIONS.md or .aider.conf.yml (Aider)\\n\\n\" +\n \"Force a target with --agent <claude|cursor|openclaw|codex|aider>.\",\n );\n process.exit(1);\n }\n\n const cwd = process.cwd();\n console.log(\n `Installing ${skills.length} skill${skills.length === 1 ? \"\" : \"s\"} into ${agents.length} agent${agents.length === 1 ? \"\" : \"s\"}:`,\n );\n console.log(` CLI version: v${CLI_VERSION}`);\n console.log(\n ` Agents: ${agents.map((a) => `${a.agent} (${a.marker})`).join(\", \")}\\n`,\n );\n\n let installed = 0;\n let updated = 0;\n let skipped = 0;\n for (const skill of skills) {\n for (const agent of agents) {\n const result = installSkill(skill, agent, cwd);\n if (result.status === \"installed\") {\n installed++;\n console.log(` ✓ ${skill.name} → ${result.path}`);\n } else if (result.status === \"updated\") {\n updated++;\n console.log(\n ` ↑ ${skill.name} → ${result.path} (v${result.previousVersion} → v${CLI_VERSION})`,\n );\n } else {\n skipped++;\n console.log(` · ${skill.name} → ${result.path} (${result.reason})`);\n }\n }\n }\n console.log(\n `\\nDone — ${installed} installed, ${updated} updated, ${skipped} unchanged.`,\n );\n}\n\nexport async function skillsRemoveCommand(name: string | undefined, opts: RemoveOptions): Promise<void> {\n const skills = resolveSkills(name, opts.all);\n if (skills.length === 0) {\n console.error(\"No skill specified. Pass a name or --all.\");\n process.exit(1);\n }\n\n const agents = resolveAgents(opts.agent);\n if (agents.length === 0) {\n console.error(\"No coding agent detected. Nothing to remove.\");\n return;\n }\n\n const cwd = process.cwd();\n let removed = 0;\n for (const skill of skills) {\n for (const agent of agents) {\n if (removeSkill(skill.name, agent, cwd)) {\n removed++;\n console.log(` ✗ ${skill.name} removed from ${agent.agent}`);\n }\n }\n }\n console.log(`\\nDone — removed ${removed} file${removed === 1 ? \"\" : \"s\"}.`);\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────\n\nfunction resolveSkills(name: string | undefined, all: boolean | undefined): BundledSkill[] {\n if (all) return [...SKILLS];\n if (!name) return [];\n const match = SKILLS.find((s) => s.name === name);\n if (!match) {\n console.error(\n `Unknown skill: ${name}\\nAvailable: ${SKILLS.map((s) => s.name).join(\", \")}`,\n );\n process.exit(1);\n }\n return [match];\n}\n\nfunction resolveAgents(forced: string | undefined): DetectedAgent[] {\n if (forced) {\n if (!ALL_AGENTS.includes(forced as Agent)) {\n console.error(\n `Unknown agent: ${forced}\\nValid: ${ALL_AGENTS.join(\", \")}`,\n );\n process.exit(1);\n }\n return [agentByName(forced as Agent)];\n }\n return detectAgents(process.cwd());\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,eAAe;;;ACAxB,OAAO,YAAY;AACnB,OAAO,UAAU;AACjB,OAAO,cAAc;AACrB,OAAO,UAAU;AASjB,IAAM,gBAAgB;AACtB,IAAM,qBAAqB,oBAAoB,aAAa;AAC5D,IAAM,sBAAsB;AAC5B,IAAM,aAAa;AAkBnB,SAAS,YAAY,YAAoB,aAAwC;AAC/E,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,QAAI,OAAO;AACX,QAAI,KAAgC;AAEpC,UAAM,SAAS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,UACG,QAAQ,SAAS,EACjB,YAAY,mGAAmG,EAC/G,OAAO,mBAAmB,sEAAsE,EAChG,OAAO,YAAY,wBAAwB,EAC3C,OAAO,CAAC,SAAS,sBAAsB,IAAI,CAAC;AAC/C,UACG,QAAQ,WAAW,EACnB,YAAY,+DAA+D,EAC3E,OAAO,mBAAmB,8BAA8B,EACxD,OAAO,CAAC,SAAS,wBAAwB,IAAI,CAAC;AAEjD,QAAM,MAAM,QAAQ,QAAQ,KAAK,EAAE,YAAY,4CAA4C;AAC3F,MACG,QAAQ,gBAAgB,EACxB,YAAY,+DAA+D,EAC3E,OAAO,mBAAmB,wDAAwD,UAAU,EAC5F,OAAO,iBAAiB;AAC3B,MACG,QAAQ,OAAO,EACf,YAAY,mEAAmE,EAC/E,OAAO,eAAe;AACzB,MACG,QAAQ,SAAS,EACjB,YAAY,kEAA6D,EACzE,OAAO,iBAAiB;AAE3B,MAAI;AACF,UAAM,QAAQ,WAAW;AAAA,EAC3B,SAAS,KAAK;AACZ,YAAQ,MAAO,KAAe,WAAW,GAAG;AAC5C,YAAQ,WAAW;AAAA,EACrB;AAUA,QAAM,IAAI,QAAc,CAAC,YAAY,QAAQ,OAAO,MAAM,IAAI,MAAM,QAAQ,CAAC,CAAC;AAC9E,UAAQ,KAAK,QAAQ,YAAY,CAAC;AACpC;","names":["redirectUri","fs","path","readline","readline","path","fs","result","fs","path","path","fs","path","readline","readline","open","open","fs","path","readline","path","existsSync","statSync","join","path","existsSync","join","statSync","existsSync","mkdirSync","readFileSync","unlinkSync","writeFileSync","dirname","join","join","escapeRe","existsSync","readFileSync","writeFileSync","mkdirSync","dirname","unlinkSync","existsSync","readFileSync","unlinkSync","writeFileSync","join","ask","readline","ask","path","fs","fs","path","spawn","slugify","assertNodeVersion","path","fs","spawn","code","path","UUID_RE","path","path","path","fs","path","slugify","write","path","fs","fs","fs","path","readline","MCP_URL","readline","resolveAgents"]}
|