clawnify 0.19.1 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/{chunk-JL5GFCTH.js → chunk-JBI5FFND.js} +4 -3
- package/dist/{chunk-JL5GFCTH.js.map → chunk-JBI5FFND.js.map} +1 -1
- package/dist/{cli-PXZFDCTL.js → cli-7WSI6PRM.js} +50 -13
- package/dist/cli-7WSI6PRM.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/{mcp-B4SXQWYQ.js → mcp-L2JJTE2Y.js} +2 -2
- package/package.json +1 -1
- package/dist/cli-PXZFDCTL.js.map +0 -1
- /package/dist/{mcp-B4SXQWYQ.js.map → mcp-L2JJTE2Y.js.map} +0 -0
package/README.md
CHANGED
|
@@ -70,6 +70,8 @@ If an app with the same slug already exists in your org, the CLI prompts you to
|
|
|
70
70
|
|
|
71
71
|
For CI or agent-driven deploys, pass `--yes` (default to updating on conflict), `--update-existing`, `--create-new`, or `--org <slug-or-id>` to skip the prompt. In a non-TTY environment, an unresolved slug conflict exits with code 75 instead of hanging on input. Use `--dry-run` to print the file list and gzipped size without uploading.
|
|
72
72
|
|
|
73
|
+
If the app has unpublished changes from the Clawnify chat, a deploy never publishes them on the way out: from a GitHub-synced folder it lands as a draft on top of them (publish both in the dashboard), and one that would overwrite them is refused. Pass `--discard-draft` to replace them with your deploy.
|
|
74
|
+
|
|
73
75
|
## Install
|
|
74
76
|
|
|
75
77
|
```bash
|
|
@@ -569,6 +569,7 @@ var SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834"
|
|
|
569
569
|
var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["live", "ready", "error", "failed"]);
|
|
570
570
|
var FAILURE_STATUSES = /* @__PURE__ */ new Set(["error", "failed"]);
|
|
571
571
|
var WEBSITE_TERMINAL_SUCCESS = /* @__PURE__ */ new Set(["preview"]);
|
|
572
|
+
var APP_TERMINAL_SUCCESS = /* @__PURE__ */ new Set(["draft"]);
|
|
572
573
|
async function pollUntilReady(resourceId, options = {}) {
|
|
573
574
|
const interval = options.interval ?? 3e3;
|
|
574
575
|
const timeout = options.timeout ?? 3e5;
|
|
@@ -604,7 +605,7 @@ async function pollUntilReady(resourceId, options = {}) {
|
|
|
604
605
|
lastMessage = message;
|
|
605
606
|
}
|
|
606
607
|
frame++;
|
|
607
|
-
const terminal = TERMINAL_STATUSES.has(data.status) || kind === "website" && WEBSITE_TERMINAL_SUCCESS.has(data.status);
|
|
608
|
+
const terminal = TERMINAL_STATUSES.has(data.status) || kind === "website" && WEBSITE_TERMINAL_SUCCESS.has(data.status) || kind === "app" && APP_TERMINAL_SUCCESS.has(data.status);
|
|
608
609
|
if (terminal) {
|
|
609
610
|
if (isTTY) process.stdout.write("\r\x1B[K");
|
|
610
611
|
if (FAILURE_STATUSES.has(data.status)) {
|
|
@@ -619,7 +620,7 @@ async function pollUntilReady(resourceId, options = {}) {
|
|
|
619
620
|
}
|
|
620
621
|
|
|
621
622
|
// src/version.ts
|
|
622
|
-
var VERSION = "0.
|
|
623
|
+
var VERSION = "0.20.1";
|
|
623
624
|
|
|
624
625
|
export {
|
|
625
626
|
OAUTH_CLIENT_ID,
|
|
@@ -643,4 +644,4 @@ export {
|
|
|
643
644
|
pollUntilReady,
|
|
644
645
|
VERSION
|
|
645
646
|
};
|
|
646
|
-
//# sourceMappingURL=chunk-
|
|
647
|
+
//# sourceMappingURL=chunk-JBI5FFND.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/auth.ts","../src/lib/config.ts","../src/lib/api.ts","../src/lib/archive.ts","../src/lib/poll.ts","../src/version.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\n\nconst SUPABASE_URL = \"https://auth.clawnify.com\";\nconst SUPABASE_ANON_KEY =\n \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imh0a3l4Zm1pbXlkeG5iemd4aGZ6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzgzNDk5MjEsImV4cCI6MjA1MzkyNTkyMX0.wopxB_gQSbNMPuxLUNK0BrGXE_0JxJqzMYFPeXFV1GE\";\nexport const OAUTH_CLIENT_ID = \"3defc0e6-80de-4e7a-aa36-0b501c06b697\";\nexport const OAUTH_AUTHORIZE_URL = `${SUPABASE_URL}/auth/v1/oauth/authorize`;\nexport const OAUTH_TOKEN_URL = `${SUPABASE_URL}/auth/v1/oauth/token`;\n\nconst AUTH_DIR = path.join(homedir(), \".clawnify\");\nconst AUTH_FILE = path.join(AUTH_DIR, \"auth.json\");\nconst LOCK_FILE = path.join(AUTH_DIR, \"auth.lock\");\n\n// A refresh POST is a single network round-trip; anything holding the lock\n// longer than this has crashed, so the lock is stolen. The wait timeout is a\n// bit longer so a legitimately in-flight refresh is never pre-empted.\nconst LOCK_STALE_MS = 15_000;\nconst LOCK_WAIT_MS = 20_000;\n\n/**\n * Session credentials only. No org: a machine-global active org made one\n * mutable pointer shared by every shell, worktree and agent on the box, so one\n * session could silently redirect another's commands at a different tenant.\n * The org binding belongs to the folder — see resolveOrgContext.\n */\nexport interface AuthData {\n access_token: string;\n refresh_token: string;\n expires_at: number;\n}\n\nexport function loadAuth(): AuthData | null {\n try {\n const data = fs.readFileSync(AUTH_FILE, \"utf-8\");\n return JSON.parse(data) as AuthData;\n } catch {\n return null;\n }\n}\n\nexport function saveAuth(data: AuthData): void {\n fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });\n // Whitelist the fields rather than writing `data` wholesale: a legacy\n // org_id/org_slug parsed out of an existing file would otherwise ride along\n // on every token refresh and never drain. This migrates the file silently.\n const { access_token, refresh_token, expires_at } = data;\n fs.writeFileSync(\n AUTH_FILE,\n JSON.stringify({ access_token, refresh_token, expires_at }, null, 2),\n { mode: 0o600 },\n );\n}\n\nexport function clearAuth(): void {\n try {\n fs.unlinkSync(AUTH_FILE);\n } catch {\n // ignore if not exists\n }\n}\n\nexport async function getValidToken(): Promise<string | null> {\n // An env-provided token wins entirely — a headless agent / CI can't do the\n // browser OAuth. CLAWNIFY_TOKEN must be a Supabase access token (JWT), minted\n // by whatever runs the CLI; it is used as-is and never refreshed.\n if (process.env.CLAWNIFY_TOKEN) return process.env.CLAWNIFY_TOKEN;\n\n const auth = loadAuth();\n if (!auth) return null;\n\n const now = Math.floor(Date.now() / 1000);\n if (auth.expires_at - 60 > now) {\n return auth.access_token;\n }\n\n // Locally expired — refresh under a cross-process lock so parallel `clawnify`\n // invocations don't each present the same refresh token (Supabase rotates it\n // on every use and revokes the whole family on reuse).\n return refreshUnderLock(auth.access_token);\n}\n\n/**\n * Force a refresh after the server rejected a token that looked locally valid\n * (family revocation, clock skew, rotation race). Returns a usable access token\n * or null if the session is genuinely dead. Env-token callers can't refresh, so\n * they get null and the caller surfaces the real error.\n */\nexport async function refreshOnUnauthorized(\n rejectedToken: string,\n): Promise<string | null> {\n if (process.env.CLAWNIFY_TOKEN) return null;\n if (!loadAuth()) return null;\n return refreshUnderLock(rejectedToken);\n}\n\n/**\n * Serialize the refresh across processes with an exclusive lock file, then\n * double-check: another invocation may have already rotated the token while we\n * waited. Only the process that still sees the stale token performs the network\n * refresh; everyone else re-reads the freshly rotated token from disk. This is\n * what keeps concurrent invocations from triggering Supabase reuse detection.\n */\nasync function refreshUnderLock(staleToken: string): Promise<string | null> {\n const release = await acquireRefreshLock();\n try {\n const auth = loadAuth();\n if (!auth) return null;\n\n // Someone else refreshed while we waited for the lock — use their token.\n const now = Math.floor(Date.now() / 1000);\n if (auth.access_token !== staleToken && auth.expires_at - 60 > now) {\n return auth.access_token;\n }\n\n const res = await fetch(OAUTH_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: auth.refresh_token,\n client_id: OAUTH_CLIENT_ID,\n }),\n });\n\n if (!res.ok) {\n clearAuth();\n return null;\n }\n\n const tokens = (await res.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n const newAuth: AuthData = {\n ...auth,\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n expires_at: Math.floor(Date.now() / 1000) + tokens.expires_in,\n };\n\n saveAuth(newAuth);\n return tokens.access_token;\n } finally {\n release();\n }\n}\n\n/**\n * Acquire an exclusive lock via atomic `O_EXCL` file creation. Waits for a\n * concurrent holder, steals a stale lock (holder crashed), and gives up after\n * LOCK_WAIT_MS to proceed best-effort rather than hang a command forever.\n */\nasync function acquireRefreshLock(): Promise<() => void> {\n fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });\n const start = Date.now();\n\n for (;;) {\n try {\n const fd = fs.openSync(LOCK_FILE, \"wx\", 0o600);\n fs.closeSync(fd);\n return () => {\n try {\n fs.unlinkSync(LOCK_FILE);\n } catch {\n // already released / stolen — nothing to do\n }\n };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n\n // Held by another process — steal it if it's stale.\n try {\n const age = Date.now() - fs.statSync(LOCK_FILE).mtimeMs;\n if (age > LOCK_STALE_MS) {\n fs.unlinkSync(LOCK_FILE);\n continue;\n }\n } catch {\n // lock vanished between openSync and statSync — retry immediately\n continue;\n }\n\n if (Date.now() - start > LOCK_WAIT_MS) {\n // Couldn't get the lock in time; proceed unlocked rather than hang.\n return () => {};\n }\n await sleep(50 + Math.floor(Math.random() * 50));\n }\n }\n}\n\nexport async function requireAuth(): Promise<AuthData> {\n // Env override (headless / CI): synthesize AuthData from CLAWNIFY_TOKEN so\n // nothing is read from or written to disk. The org is not carried here —\n // CLAWNIFY_ORG_ID is read by resolveOrgContext like every other source.\n if (process.env.CLAWNIFY_TOKEN) {\n return {\n access_token: process.env.CLAWNIFY_TOKEN,\n refresh_token: \"\",\n expires_at: Number.MAX_SAFE_INTEGER,\n };\n }\n\n const token = await getValidToken();\n if (!token) {\n console.error(\n \"Not logged in. Run `clawnify login`, or set CLAWNIFY_TOKEN (a Supabase access token) for headless / CI use.\",\n );\n process.exit(1);\n }\n return loadAuth()!;\n}\n\n/** Parse email from Supabase JWT claims (base64url-decoded payload) */\nexport function getEmailFromToken(token: string): string | null {\n try {\n const payload = token.split(\".\")[1]!;\n const decoded = JSON.parse(\n Buffer.from(payload, \"base64url\").toString(\"utf-8\")\n );\n return decoded.email ?? null;\n } catch {\n return null;\n }\n}\n\n/** Generate PKCE code_verifier and code_challenge */\nexport function generatePkce(): {\n codeVerifier: string;\n codeChallenge: string;\n} {\n const codeVerifier = crypto.randomBytes(32).toString(\"base64url\");\n const codeChallenge = crypto\n .createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n return { codeVerifier, codeChallenge };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface ClawnifyAppConfig {\n framework: string;\n database?: boolean;\n storage?: boolean;\n}\n\nexport interface ClawnifyWebsiteConfig {\n framework: string;\n}\n\n/**\n * An agent member (see `docs/internal/adr-company-monorepo.md` § Layer 1).\n * `harness` selects the runtime adapter — today only `openclaw`, whose\n * payload is `AGENT.md` + `skills/` + `flows/` + `openclaw.json`.\n */\nexport interface ClawnifyAgentConfig {\n harness: string;\n}\n\n/**\n * A workspace root is a monorepo that hosts an org's apps. It carries no\n * `app`/`website` block of its own — its `clawnify.json` declares only the\n * org every child app deploys to. See `docs/internal/adr-company-monorepo.md`.\n */\nexport interface ClawnifyWorkspaceConfig {\n /** Org slug or id this workspace (and every app under it) is bound to. */\n org: string;\n}\n\nexport interface ClawnifyManifest {\n name: string;\n description?: string;\n app?: ClawnifyAppConfig;\n website?: ClawnifyWebsiteConfig;\n /**\n * Overloaded (kept for back-compat with the published schema):\n * - OBJECT `{ harness }` → this project IS an agent (workspace member, #814).\n * - STRING → path to an app's agent-instructions file (schema default\n * \"agent.md\"); an app declares it alongside `app`, and the build reads\n * the file (`app-deployer.ts`). It is NOT a project kind.\n */\n agent?: ClawnifyAgentConfig | string;\n workspace?: ClawnifyWorkspaceConfig;\n deploy?: {\n /**\n * Agents to declare on an anonymous deploy. The platform shows them on\n * the claim page (and in the dashboard after claim) as \"not hired yet\";\n * hiring one prefills the create form and applies `instructions` as its\n * AGENTS.md. Ignored on signed-in deploys.\n */\n agents?: PendingAgentSpec[];\n };\n}\n\nexport interface PendingAgentSpec {\n name: string;\n role?: string;\n description?: string;\n avatar_url?: string;\n instructions?: string;\n}\n\nexport type ManifestKind = \"app\" | \"website\" | \"agent\";\n\n/** Anonymous-deploy context: the unclaimed org this folder deploys into.\n * deploy_token authorizes /v1/anon/* only and dies at claim or expiry. */\nexport interface AnonContext {\n org_id: string;\n deploy_token: string;\n claim_url: string;\n claim_expires_at: string;\n}\n\nexport interface ProjectConfig {\n kind?: ManifestKind;\n org_id?: string;\n org_slug?: string;\n app_id?: string;\n app_token?: string;\n website_id?: string;\n slug?: string;\n /** Agent link: the server + named agent this member deploys to. */\n server_id?: string;\n agent_name?: string;\n /** Present while this folder deploys anonymously (no login). */\n anon?: AnonContext;\n}\n\nexport function readManifest(dir: string = process.cwd()): ClawnifyManifest | null {\n try {\n const data = fs.readFileSync(path.join(dir, \"clawnify.json\"), \"utf-8\");\n const manifest = JSON.parse(data) as ClawnifyManifest;\n if (!manifest.name) return null;\n if (!manifest.app && !manifest.website && !manifest.agent) return null;\n return manifest;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns the manifest kind, or throws with a clear message when neither or\n * both blocks are present. Callers should run this before dispatching deploy.\n */\nexport function manifestKind(manifest: ClawnifyManifest): ManifestKind {\n // `agent` is a project kind ONLY when it's an object ({ harness }). A string\n // value is an app's agent-instructions file path (schema default \"agent.md\"),\n // declared alongside `app` — it must not be counted as a second kind, or\n // every app that references its agent.md fails with a false \"more than one\n // kind\" error (open-crm, open-kitchen, …).\n const isAgentProject =\n typeof manifest.agent === \"object\" && manifest.agent !== null;\n const present: ManifestKind[] = [\n manifest.app ? \"app\" : null,\n manifest.website ? \"website\" : null,\n isAgentProject ? \"agent\" : null,\n ].filter((k): k is ManifestKind => k !== null);\n if (present.length > 1) {\n throw new Error(\n `clawnify.json declares more than one of \\`app\\`, \\`website\\`, \\`agent\\` (${present.join(\", \")}) — a project is exactly one kind.`,\n );\n }\n if (present.length === 0) {\n throw new Error(\n \"clawnify.json must declare an `app`, `website`, or `agent` block.\",\n );\n }\n return present[0]!;\n}\n\nexport function readProject(dir: string = process.cwd()): ProjectConfig | null {\n try {\n const data = fs.readFileSync(\n path.join(dir, \".clawnify\", \"project.json\"),\n \"utf-8\"\n );\n return JSON.parse(data) as ProjectConfig;\n } catch {\n return null;\n }\n}\n\n/**\n * The nearest `.clawnify/project.json` at or above `startDir`.\n *\n * Deliberately NOT folded into readProject(): that is used by paths which write\n * (`agents.ts` merges over it before saveProject) and by deploy, where \"which\n * folder am I in\" is the question being asked. Walking there would let a child\n * directory inherit — and then persist — a parent app's id and token.\n *\n * Org resolution is the opposite case: which org a command acts on shouldn't\n * change just because you cd'd into src/. Mirrors findWorkspaceRoot below, and\n * the way `supabase` resolves its project root from the nearest ancestor.\n */\nexport function findProjectRoot(\n startDir: string = process.cwd(),\n): ProjectConfig | null {\n let cur = path.resolve(startDir);\n for (;;) {\n const proj = readProject(cur);\n if (proj) return proj;\n const parent = path.dirname(cur);\n if (parent === cur) return null;\n cur = parent;\n }\n}\n\nexport function saveProject(dir: string, data: ProjectConfig): void {\n const projDir = path.join(dir, \".clawnify\");\n fs.mkdirSync(projDir, { recursive: true });\n fs.writeFileSync(\n path.join(projDir, \"project.json\"),\n JSON.stringify(data, null, 2)\n );\n}\n\nexport interface WorkspaceRoot {\n /** Absolute path to the workspace root directory. */\n dir: string;\n /** Org slug or id the workspace is bound to. */\n org: string;\n}\n\n/**\n * Read a workspace root's binding from `clawnify.json` at `dir`, or null if\n * that dir isn't a workspace root. A workspace is discriminated by the\n * presence of a `workspace.org` field (mirrors how app/website are detected).\n */\nexport function readWorkspaceConfig(dir: string): WorkspaceRoot | null {\n try {\n const data = fs.readFileSync(path.join(dir, \"clawnify.json\"), \"utf-8\");\n const manifest = JSON.parse(data) as ClawnifyManifest;\n if (manifest.workspace?.org) return { dir, org: manifest.workspace.org };\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Walk up from `startDir` to the filesystem root, returning the nearest\n * enclosing workspace root, or null if there is none. Used so `init` drops\n * new apps under `apps/` and `deploy` inherits the org for a fresh app.\n */\nexport function findWorkspaceRoot(\n startDir: string = process.cwd(),\n): WorkspaceRoot | null {\n let cur = path.resolve(startDir);\n for (;;) {\n const ws = readWorkspaceConfig(cur);\n if (ws) return ws;\n const parent = path.dirname(cur);\n if (parent === cur) return null;\n cur = parent;\n }\n}\n","import {\n requireAuth,\n loadAuth,\n saveAuth,\n refreshOnUnauthorized,\n type AuthData,\n} from \"./auth.js\";\nimport { findProjectRoot, findWorkspaceRoot } from \"./config.js\";\nimport readline from \"node:readline\";\n\n// Overridable for CLI development against a local `wrangler dev` API.\nconst API_BASE = process.env.CLAWNIFY_API_BASE ?? \"https://provision.clawnify.com\";\n\nconst UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nasync function apiRequest(\n method: string,\n path: string,\n options?: {\n body?: unknown;\n formData?: FormData;\n token?: string;\n orgId?: string;\n }\n): Promise<Response> {\n const headers: Record<string, string> = {};\n\n if (options?.token) {\n headers[\"Authorization\"] = `Bearer ${options.token}`;\n }\n if (options?.orgId) {\n // The header carries a UUID and nothing else. A slug here does not fail\n // loudly — it fails as \"some other org\" — so an unresolved value must be\n // caught at the boundary that builds the request, not discovered later in\n // whichever org the server settled on. Callers pass ids from matchOrg() /\n // resolveOrgContext(); raw user input belongs in `orgFlag`, not here.\n if (!UUID_RE.test(options.orgId)) {\n throw new Error(\n `Internal: x-org-id must be an org UUID, got \"${options.orgId}\". ` +\n `Resolve it with resolveOrgContext({ orgFlag }) first.`,\n );\n }\n headers[\"x-org-id\"] = options.orgId;\n }\n\n let body: BodyInit | undefined;\n if (options?.formData) {\n body = options.formData;\n } else if (options?.body) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(options.body);\n }\n\n return fetch(`${API_BASE}${path}`, { method, headers, body });\n}\n\nasync function ensureOrg(auth: AuthData): Promise<string | undefined> {\n // Any `org_id` still sitting in auth.json is a legacy artifact from when\n // `org use` wrote machine-global state. Honouring it here would keep that\n // behaviour alive for everyone who already has the file, so it is ignored\n // and left to be dropped on the next login.\n\n // Fetch orgs and prompt\n const orgsRes = await apiRequest(\"GET\", \"/v1/orgs\", { token: auth.access_token });\n if (!orgsRes.ok) return undefined;\n\n const { orgs } = (await orgsRes.json()) as {\n orgs: Array<{ id: string; name: string; slug: string; role: string }>;\n };\n\n if (orgs.length === 0) return undefined;\n\n let orgId: string;\n if (orgs.length === 1) {\n orgId = orgs[0].id;\n } else if (!process.stdin.isTTY || process.env.CLAWNIFY_TOKEN) {\n // Non-interactive (headless agent / CI / env auth): can't prompt — default\n // to the first org and tell the caller how to pin one.\n console.error(\n `Multiple orgs — defaulting to \"${orgs[0].name}\". Pin with CLAWNIFY_ORG_ID or --org.`,\n );\n orgId = orgs[0].id;\n } else {\n console.log(\"\\nSelect an organization:\\n\");\n orgs.forEach((org, i) => {\n console.log(` ${i + 1}) ${org.name} (${org.role})`);\n });\n console.log();\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const choice = await new Promise<string>((resolve) => {\n rl.question(\"Enter number: \", (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n\n const index = parseInt(choice, 10) - 1;\n orgId = (index >= 0 && index < orgs.length) ? orgs[index].id : orgs[0].id;\n console.log(`Selected: ${orgs[index >= 0 && index < orgs.length ? index : 0].name}\\n`);\n }\n\n // Deliberately NOT persisted. Writing the choice back to auth.json is what\n // created the machine-global active org in the first place. The durable\n // binding belongs to the folder (clawnify.json `workspace.org`, or\n // `.clawnify/project.json` via `clawnify link`), not to the machine.\n if (orgs.length > 1) {\n const chosen = orgs.find((o) => o.id === orgId);\n console.error(\n ` Using ${chosen?.name ?? orgId} for this command only.\\n` +\n ` Pin it so every command in this folder agrees: clawnify link <app> --org ${chosen?.slug ?? orgId}\\n` +\n ` (or set workspace.org in clawnify.json, or pass --org).`,\n );\n }\n return orgId;\n}\n\ntype OrgSource = \"flag\" | \"env\" | \"link\" | \"workspace\";\nlet orgCtxCache: string | undefined | null = null;\nlet orgEchoed = false;\n\n/** Print the org a command is acting on, once, to stderr (keeps stdout clean). */\nfunction echoOrg(label: string, source: OrgSource): void {\n if (orgEchoed) return;\n orgEchoed = true;\n process.stderr.write(`→ org: ${label} (${source})\\n`);\n}\n\nasync function matchOrg(ref: string): Promise<{ id: string; slug: string }> {\n const orgs = await listMyOrgs();\n const m = orgs.find((o) => o.id === ref || o.slug === ref);\n if (!m) {\n console.error(`No org matched \"${ref}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`);\n process.exit(1);\n }\n return { id: m.id, slug: m.slug };\n}\n\n/**\n * Resolve which org the current command targets, folder-first:\n * --org → CLAWNIFY_ORG_ID → .clawnify/project.json org_id → workspace.org\n *\n * There is deliberately no machine-global fallback. Org is a property of the\n * directory you are standing in, never of the machine, so a second shell,\n * worktree or agent cannot repoint what this command targets. Memoized and\n * echoed once; returns undefined when nothing resolves, leaving the decision to\n * ensureOrg (single org → use it, otherwise prompt).\n */\nexport async function resolveOrgContext(\n opts?: { orgFlag?: string; dir?: string },\n): Promise<string | undefined> {\n if (orgCtxCache !== null) return orgCtxCache;\n const dir = opts?.dir ?? process.cwd();\n\n if (opts?.orgFlag) {\n const m = await matchOrg(opts.orgFlag);\n const proj = findProjectRoot(dir);\n if (proj?.org_id && proj.org_id !== m.id) {\n console.error(\n `This folder is linked to a different org (${proj.org_slug ?? proj.org_id}).\\n` +\n ` --org ${opts.orgFlag} resolves to ${m.slug}. Re-link, or run from another directory.`,\n );\n process.exit(1);\n }\n orgCtxCache = m.id;\n echoOrg(m.slug, \"flag\");\n return m.id;\n }\n\n const env = process.env.CLAWNIFY_ORG_ID;\n if (env) {\n // Accepts a slug as well as a UUID, like --org. A slug used to be passed\n // through untouched and land as \"some other org\" server-side; resolving it\n // here keeps CI configs honest. UUIDs skip the lookup — the common case\n // shouldn't pay for a network round-trip.\n const id = UUID_RE.test(env) ? env : (await matchOrg(env)).id;\n orgCtxCache = id;\n echoOrg(env, \"env\");\n return id;\n }\n\n const proj = findProjectRoot(dir);\n if (proj?.org_id) {\n orgCtxCache = proj.org_id;\n echoOrg(proj.org_slug ?? proj.org_id, \"link\");\n return proj.org_id;\n }\n\n const ws = findWorkspaceRoot(dir);\n if (ws?.org) {\n const m = await matchOrg(ws.org);\n orgCtxCache = m.id;\n echoOrg(m.slug, \"workspace\");\n return m.id;\n }\n\n // NO machine-global fallback. `~/.clawnify/auth.json` is an auth artifact and\n // must not carry a project binding: it is one mutable pointer shared by every\n // shell, worktree and agent on the box, so one session repointing it silently\n // redirected another session's commands at a different tenant. Falling through\n // to undefined hands the decision to ensureOrg, which resolves an unambiguous\n // single org and otherwise prompts — a better answer than a stale global.\n orgCtxCache = undefined;\n return undefined;\n}\n\nasync function authedRequest(\n method: string,\n path: string,\n options?: { body?: unknown; formData?: FormData; orgId?: string }\n): Promise<Response> {\n let auth = await requireAuth();\n let orgId = options?.orgId;\n if (!orgId) {\n orgId = await resolveOrgContext();\n if (!orgId) {\n orgId = await ensureOrg(auth);\n }\n }\n\n const res = await apiRequest(method, path, {\n ...options,\n token: auth.access_token,\n orgId,\n });\n\n if (res.status !== 401) return res;\n\n // A 401 is not necessarily an expired session: the token may have been\n // rotated by a concurrent invocation, revoked, or the route itself may be\n // rejecting an otherwise-valid token. Attempt exactly one silent refresh and\n // retry before deciding it's a login problem.\n const fresh = await refreshOnUnauthorized(auth.access_token);\n if (!fresh) {\n if (process.env.CLAWNIFY_TOKEN) {\n console.error(\"CLAWNIFY_TOKEN was rejected (401). Provide a valid Supabase access token.\");\n } else {\n console.error(\"Session expired. Run `clawnify login` again.\");\n }\n process.exit(1);\n }\n\n // Retry once with the refreshed token. If it still 401s, this isn't a session\n // problem — return the response so the caller surfaces the real error instead\n // of masquerading it as a login failure.\n return apiRequest(method, path, {\n ...options,\n token: fresh,\n orgId,\n });\n}\n\nexport interface Org {\n id: string;\n name: string;\n slug: string;\n role: string;\n}\n\n/** List every org the authenticated user belongs to, bypassing org selection. */\nexport async function listMyOrgs(): Promise<Org[]> {\n const auth = await requireAuth();\n const res = await apiRequest(\"GET\", \"/v1/orgs\", { token: auth.access_token });\n if (!res.ok) return [];\n const { orgs } = (await res.json()) as { orgs: Org[] };\n return orgs ?? [];\n}\n\nexport const api = {\n get: (path: string, opts?: { orgId?: string }) =>\n authedRequest(\"GET\", path, opts),\n post: (path: string, body?: unknown, opts?: { orgId?: string }) =>\n authedRequest(\"POST\", path, { body, ...opts }),\n postForm: (path: string, formData: FormData, opts?: { orgId?: string }) =>\n authedRequest(\"POST\", path, { formData, ...opts }),\n del: (path: string, opts?: { orgId?: string }) =>\n authedRequest(\"DELETE\", path, opts),\n // Generic authed request for the `clawnify api` escape hatch (any method).\n call: (method: string, path: string, opts?: { body?: unknown; orgId?: string }) =>\n authedRequest(method, path, opts),\n request: apiRequest,\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { gzipSync } from \"node:zlib\";\n\nconst EXCLUDE_DIRS = new Set([\n \"node_modules\",\n \".git\",\n \"dist\",\n \".next\",\n \".clawnify\",\n \"build\",\n]);\n\nconst MAX_SIZE = 20 * 1024 * 1024; // 20MB\n\nfunction runGit(args: string[], dir: string): string | null {\n try {\n return execSync(`git ${args.join(\" \")}`, {\n cwd: dir,\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // execSync's default maxBuffer is 1MB. `ls-files --others` enumerates\n // every file under an unignored node_modules, which easily exceeds that —\n // the throw was caught below and untracked files silently vanished from\n // the archive (new assets never deployed).\n maxBuffer: 64 * 1024 * 1024,\n });\n } catch {\n return null;\n }\n}\n\n/**\n * Collect every file `git add .` would stage: tracked files plus untracked\n * files that aren't ignored. Returns null if the directory isn't a git repo,\n * so the caller falls back to walkDir.\n *\n * The previous implementation used only `git ls-files`, which silently\n * excluded brand-new untracked files — a common foot-gun when an agent\n * (or human) creates a file but forgets to `git add` it.\n */\nfunction getGitFiles(dir: string): string[] | null {\n const tracked = runGit([\"ls-files\", \"-z\"], dir);\n if (tracked === null) return null;\n const untrackedResult = runGit([\"ls-files\", \"-z\", \"--others\", \"--exclude-standard\"], dir);\n if (untrackedResult === null) {\n // Never fail silently here: proceeding without untracked files means a\n // brand-new asset quietly missing from the deployed site.\n console.warn(\n \" warning: could not list untracked files (git ls-files --others failed); \" +\n \"newly created files that aren't committed may be missing from this deploy.\",\n );\n }\n const untracked = untrackedResult ?? \"\";\n const merged = new Set<string>();\n for (const f of tracked.split(\"\\0\")) if (f) merged.add(f);\n for (const f of untracked.split(\"\\0\")) if (f) merged.add(f);\n return [...merged];\n}\n\nfunction walkDir(dir: string, base: string = \"\"): string[] {\n const files: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (EXCLUDE_DIRS.has(entry.name)) continue;\n const rel = base ? `${base}/${entry.name}` : entry.name;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...walkDir(full, rel));\n } else if (entry.isFile()) {\n files.push(rel);\n }\n }\n return files;\n}\n\n/**\n * A repo-root `manifest.json` is not part of the clawnify contract\n * (clawnify.json is). Some templates leave a Preact-style manifest behind;\n * users see \"manifest\" and assume it controls something. Warn so they know\n * it's being uploaded as a dumb file.\n */\nfunction warnOnStaleManifest(dir: string, files: string[]) {\n if (!files.includes(\"manifest.json\")) return;\n try {\n const raw = fs.readFileSync(path.join(dir, \"manifest.json\"), \"utf-8\");\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n if (parsed && typeof parsed === \"object\" && \"framework\" in parsed && \"files\" in parsed) {\n console.warn(\n ` warning: manifest.json looks like a stale auto-generated file. ` +\n `Clawnify uses clawnify.json — manifest.json is ignored.`,\n );\n }\n } catch {\n // not JSON, not our concern\n }\n}\n\n/**\n * EXCLUDE_DIRS must hold on BOTH listing paths. The git path lists whatever\n * git would stage — which includes `.clawnify/` (app_token!) or `.env` when\n * the surrounding repo's .gitignore doesn't cover them (e.g. a cloned\n * template). Those must never be uploaded regardless of git status.\n */\nfunction isExcludedPath(rel: string): boolean {\n const parts = rel.split(\"/\");\n return parts.some((p) => EXCLUDE_DIRS.has(p)) || parts[parts.length - 1] === \".env\";\n}\n\nfunction listFiles(dir: string): string[] {\n const fromGit = getGitFiles(dir);\n const files = (fromGit ?? walkDir(dir)).filter((f) => !isExcludedPath(f));\n warnOnStaleManifest(dir, files);\n return files;\n}\n\n/** Public helper for `clawnify deploy --dry-run`. */\nexport function listArchiveFiles(dir: string): string[] {\n return listFiles(dir);\n}\n\nfunction createTarHeader(filename: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(filename, 0, Math.min(filename.length, 100), \"utf-8\");\n header.write(\"0000644\\0\", 100, 8, \"utf-8\");\n header.write(\"0000000\\0\", 108, 8, \"utf-8\");\n header.write(\"0000000\\0\", 116, 8, \"utf-8\");\n header.write(size.toString(8).padStart(11, \"0\") + \"\\0\", 124, 12, \"utf-8\");\n const mtime = Math.floor(Date.now() / 1000);\n header.write(mtime.toString(8).padStart(11, \"0\") + \"\\0\", 136, 12, \"utf-8\");\n header.write(\"0\", 156, 1, \"utf-8\");\n header.write(\"ustar\\0\", 257, 6, \"utf-8\");\n header.write(\"00\", 263, 2, \"utf-8\");\n header.write(\" \", 148, 8, \"utf-8\");\n let checksum = 0;\n for (let i = 0; i < 512; i++) {\n checksum += header[i]!;\n }\n header.write(checksum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, 8, \"utf-8\");\n return header;\n}\n\n/**\n * Drizzle migrations live under `.clawnify/drizzle/<NNNN>_<name>.sql`\n * locally (gitignored, regenerated by the CLI on dev/deploy). The\n * deploy pipeline (PR #444) scans R2's `drizzle/` prefix on each\n * deploy. We remap on upload — the user's repo stays clean, the\n * pipeline contract is unchanged.\n *\n * Only top-level `*.sql` files come along; drizzle's `meta/` snapshot\n * dir is local-only state.\n */\nfunction collectDrizzleMigrations(\n dir: string,\n): { src: string; tarName: string }[] {\n const drizzleDir = path.join(dir, \".clawnify\", \"drizzle\");\n if (!fs.existsSync(drizzleDir)) return [];\n try {\n return fs\n .readdirSync(drizzleDir)\n .filter((name) => name.endsWith(\".sql\"))\n .sort()\n .map((name) => ({\n src: path.join(drizzleDir, name),\n tarName: `drizzle/${name}`,\n }));\n } catch {\n return [];\n }\n}\n\nexport function createArchive(dir: string): { archive: Buffer; files: string[] } {\n const files = listFiles(dir);\n const parts: Buffer[] = [];\n const includedFiles: string[] = [];\n\n function addEntry(absPath: string, tarName: string): void {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(absPath);\n } catch {\n return;\n }\n if (!stat.isFile()) return;\n\n const content = fs.readFileSync(absPath);\n const header = createTarHeader(tarName, content.length);\n parts.push(header);\n parts.push(content);\n includedFiles.push(tarName);\n\n const remainder = content.length % 512;\n if (remainder > 0) {\n parts.push(Buffer.alloc(512 - remainder));\n }\n }\n\n for (const file of files) {\n addEntry(path.join(dir, file), file);\n }\n\n for (const m of collectDrizzleMigrations(dir)) {\n addEntry(m.src, m.tarName);\n }\n\n parts.push(Buffer.alloc(1024));\n\n const tar = Buffer.concat(parts);\n const gzipped = gzipSync(tar);\n\n if (gzipped.length > MAX_SIZE) {\n throw new Error(\n `Archive too large (${(gzipped.length / 1024 / 1024).toFixed(1)}MB). Maximum is 20MB.`,\n );\n }\n\n return { archive: gzipped, files: includedFiles };\n}\n","import { api } from \"./api.js\";\n\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n\nexport interface AppStatus {\n status: string;\n status_message?: string;\n url?: string;\n error?: string;\n}\n\n// Status values that mean we're done — apps use \"live\"/\"error\", websites\n// use \"live\"/\"failed\". Pollers stop on any of these.\nconst TERMINAL_STATUSES = new Set([\"live\", \"ready\", \"error\", \"failed\"]);\nconst FAILURE_STATUSES = new Set([\"error\", \"failed\"]);\n// Draft-first: a CLI website deploy builds to the draft tier and parks at\n// \"preview\" (publishing to live is an explicit, separate action from the\n// dashboard). So \"preview\" is a terminal SUCCESS for websites — without this\n// the poller would spin until it times out on a perfectly good deploy.\nconst WEBSITE_TERMINAL_SUCCESS = new Set([\"preview\"]);\n\nexport async function pollUntilReady(\n resourceId: string,\n options: {\n interval?: number;\n timeout?: number;\n kind?: \"app\" | \"website\";\n orgId?: string;\n /** Anonymous deploy token — polls /v1/anon/* instead of the authed surface. */\n anonToken?: string;\n } = {},\n): Promise<AppStatus> {\n const interval = options.interval ?? 3000;\n const timeout = options.timeout ?? 300000;\n const kind = options.kind ?? \"app\";\n const authedBase = kind === \"website\" ? \"/v1/websites\" : \"/v1/apps\";\n const basePath = options.anonToken\n ? (kind === \"website\" ? \"/v1/anon/websites\" : \"/v1/anon/apps\")\n : authedBase;\n const start = Date.now();\n let frame = 0;\n const isTTY = Boolean(process.stdout.isTTY);\n let lastMessage = \"\";\n // A reply with no status means the resource was not found for whoever we\n // asked as — nearly always the wrong org. Printing \"status: undefined\" for\n // five minutes and then claiming a timeout hides that, so say it. A couple\n // are tolerated first: a just-created app can lag its own row by a beat.\n let statusless = 0;\n const STATUSLESS_LIMIT = 3;\n\n while (Date.now() - start < timeout) {\n const res = options.anonToken\n ? await api.request(\"GET\", `${basePath}/${resourceId}`, { token: options.anonToken })\n : await api.get(`${basePath}/${resourceId}`, { orgId: options.orgId });\n const data = (await res.json()) as AppStatus;\n if (!data.status) {\n if (++statusless >= STATUSLESS_LIMIT) {\n if (isTTY) process.stdout.write(\"\\r\\x1b[K\");\n throw new Error(\n options.orgId\n ? `Deployed, but its status could not be read: ${kind === \"website\" ? \"website\" : \"app\"} ${resourceId} is not visible in org ${options.orgId}.`\n : `Deployed, but its status could not be read: ${kind === \"website\" ? \"website\" : \"app\"} ${resourceId} was not found. If it went to another organization, pass --org.`,\n );\n }\n await new Promise((r) => setTimeout(r, interval));\n continue;\n }\n statusless = 0;\n const message = data.status_message || data.status;\n\n if (isTTY) {\n const spinner = SPINNER_FRAMES[frame % SPINNER_FRAMES.length];\n process.stdout.write(`\\r${spinner} ${message}`);\n } else if (message !== lastMessage) {\n // Non-TTY (CI logs, background tasks): write whole lines so the\n // output survives in pipes and files instead of being mangled by\n // cursor escapes from the spinner.\n console.log(`status: ${message}`);\n lastMessage = message;\n }\n frame++;\n\n const terminal =\n TERMINAL_STATUSES.has(data.status) ||\n (kind === \"website\" && WEBSITE_TERMINAL_SUCCESS.has(data.status));\n if (terminal) {\n if (isTTY) process.stdout.write(\"\\r\\x1b[K\");\n // Normalize \"failed\" to \"error\" so downstream callers only branch\n // on one terminal-failure value.\n if (FAILURE_STATUSES.has(data.status)) {\n return { ...data, status: \"error\" };\n }\n return data;\n }\n\n await new Promise((r) => setTimeout(r, interval));\n }\n\n if (isTTY) process.stdout.write(\"\\r\\x1b[K\");\n throw new Error(\"Timed out waiting for deployment\");\n}\n","/**\n * The CLI's real version, injected at build time from package.json by\n * tsup.config.ts. package.json stays the single source of truth — bumping it\n * IS the release (see .github/workflows/publish-cli.yml), and this makes\n * `clawnify --version` say the same thing.\n *\n * It used to be a hardcoded \"0.1.0\" in cli.ts and mcp.ts, which meant every\n * build ever published reported the same string. That made \"are you on the\n * fixed CLI?\" unanswerable — a stale global install (npm installs into the\n * ACTIVE nvm node version, so one per node version is easy to end up with)\n * was indistinguishable from a current one.\n */\ndeclare const __CLI_VERSION__: string;\n\nexport const VERSION = __CLI_VERSION__;\n"],"mappings":";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lib/auth.ts","../src/lib/config.ts","../src/lib/api.ts","../src/lib/archive.ts","../src/lib/poll.ts","../src/version.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { setTimeout as sleep } from \"node:timers/promises\";\n\nconst SUPABASE_URL = \"https://auth.clawnify.com\";\nconst SUPABASE_ANON_KEY =\n \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imh0a3l4Zm1pbXlkeG5iemd4aGZ6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzgzNDk5MjEsImV4cCI6MjA1MzkyNTkyMX0.wopxB_gQSbNMPuxLUNK0BrGXE_0JxJqzMYFPeXFV1GE\";\nexport const OAUTH_CLIENT_ID = \"3defc0e6-80de-4e7a-aa36-0b501c06b697\";\nexport const OAUTH_AUTHORIZE_URL = `${SUPABASE_URL}/auth/v1/oauth/authorize`;\nexport const OAUTH_TOKEN_URL = `${SUPABASE_URL}/auth/v1/oauth/token`;\n\nconst AUTH_DIR = path.join(homedir(), \".clawnify\");\nconst AUTH_FILE = path.join(AUTH_DIR, \"auth.json\");\nconst LOCK_FILE = path.join(AUTH_DIR, \"auth.lock\");\n\n// A refresh POST is a single network round-trip; anything holding the lock\n// longer than this has crashed, so the lock is stolen. The wait timeout is a\n// bit longer so a legitimately in-flight refresh is never pre-empted.\nconst LOCK_STALE_MS = 15_000;\nconst LOCK_WAIT_MS = 20_000;\n\n/**\n * Session credentials only. No org: a machine-global active org made one\n * mutable pointer shared by every shell, worktree and agent on the box, so one\n * session could silently redirect another's commands at a different tenant.\n * The org binding belongs to the folder — see resolveOrgContext.\n */\nexport interface AuthData {\n access_token: string;\n refresh_token: string;\n expires_at: number;\n}\n\nexport function loadAuth(): AuthData | null {\n try {\n const data = fs.readFileSync(AUTH_FILE, \"utf-8\");\n return JSON.parse(data) as AuthData;\n } catch {\n return null;\n }\n}\n\nexport function saveAuth(data: AuthData): void {\n fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });\n // Whitelist the fields rather than writing `data` wholesale: a legacy\n // org_id/org_slug parsed out of an existing file would otherwise ride along\n // on every token refresh and never drain. This migrates the file silently.\n const { access_token, refresh_token, expires_at } = data;\n fs.writeFileSync(\n AUTH_FILE,\n JSON.stringify({ access_token, refresh_token, expires_at }, null, 2),\n { mode: 0o600 },\n );\n}\n\nexport function clearAuth(): void {\n try {\n fs.unlinkSync(AUTH_FILE);\n } catch {\n // ignore if not exists\n }\n}\n\nexport async function getValidToken(): Promise<string | null> {\n // An env-provided token wins entirely — a headless agent / CI can't do the\n // browser OAuth. CLAWNIFY_TOKEN must be a Supabase access token (JWT), minted\n // by whatever runs the CLI; it is used as-is and never refreshed.\n if (process.env.CLAWNIFY_TOKEN) return process.env.CLAWNIFY_TOKEN;\n\n const auth = loadAuth();\n if (!auth) return null;\n\n const now = Math.floor(Date.now() / 1000);\n if (auth.expires_at - 60 > now) {\n return auth.access_token;\n }\n\n // Locally expired — refresh under a cross-process lock so parallel `clawnify`\n // invocations don't each present the same refresh token (Supabase rotates it\n // on every use and revokes the whole family on reuse).\n return refreshUnderLock(auth.access_token);\n}\n\n/**\n * Force a refresh after the server rejected a token that looked locally valid\n * (family revocation, clock skew, rotation race). Returns a usable access token\n * or null if the session is genuinely dead. Env-token callers can't refresh, so\n * they get null and the caller surfaces the real error.\n */\nexport async function refreshOnUnauthorized(\n rejectedToken: string,\n): Promise<string | null> {\n if (process.env.CLAWNIFY_TOKEN) return null;\n if (!loadAuth()) return null;\n return refreshUnderLock(rejectedToken);\n}\n\n/**\n * Serialize the refresh across processes with an exclusive lock file, then\n * double-check: another invocation may have already rotated the token while we\n * waited. Only the process that still sees the stale token performs the network\n * refresh; everyone else re-reads the freshly rotated token from disk. This is\n * what keeps concurrent invocations from triggering Supabase reuse detection.\n */\nasync function refreshUnderLock(staleToken: string): Promise<string | null> {\n const release = await acquireRefreshLock();\n try {\n const auth = loadAuth();\n if (!auth) return null;\n\n // Someone else refreshed while we waited for the lock — use their token.\n const now = Math.floor(Date.now() / 1000);\n if (auth.access_token !== staleToken && auth.expires_at - 60 > now) {\n return auth.access_token;\n }\n\n const res = await fetch(OAUTH_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: auth.refresh_token,\n client_id: OAUTH_CLIENT_ID,\n }),\n });\n\n if (!res.ok) {\n clearAuth();\n return null;\n }\n\n const tokens = (await res.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n const newAuth: AuthData = {\n ...auth,\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token,\n expires_at: Math.floor(Date.now() / 1000) + tokens.expires_in,\n };\n\n saveAuth(newAuth);\n return tokens.access_token;\n } finally {\n release();\n }\n}\n\n/**\n * Acquire an exclusive lock via atomic `O_EXCL` file creation. Waits for a\n * concurrent holder, steals a stale lock (holder crashed), and gives up after\n * LOCK_WAIT_MS to proceed best-effort rather than hang a command forever.\n */\nasync function acquireRefreshLock(): Promise<() => void> {\n fs.mkdirSync(AUTH_DIR, { recursive: true, mode: 0o700 });\n const start = Date.now();\n\n for (;;) {\n try {\n const fd = fs.openSync(LOCK_FILE, \"wx\", 0o600);\n fs.closeSync(fd);\n return () => {\n try {\n fs.unlinkSync(LOCK_FILE);\n } catch {\n // already released / stolen — nothing to do\n }\n };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n\n // Held by another process — steal it if it's stale.\n try {\n const age = Date.now() - fs.statSync(LOCK_FILE).mtimeMs;\n if (age > LOCK_STALE_MS) {\n fs.unlinkSync(LOCK_FILE);\n continue;\n }\n } catch {\n // lock vanished between openSync and statSync — retry immediately\n continue;\n }\n\n if (Date.now() - start > LOCK_WAIT_MS) {\n // Couldn't get the lock in time; proceed unlocked rather than hang.\n return () => {};\n }\n await sleep(50 + Math.floor(Math.random() * 50));\n }\n }\n}\n\nexport async function requireAuth(): Promise<AuthData> {\n // Env override (headless / CI): synthesize AuthData from CLAWNIFY_TOKEN so\n // nothing is read from or written to disk. The org is not carried here —\n // CLAWNIFY_ORG_ID is read by resolveOrgContext like every other source.\n if (process.env.CLAWNIFY_TOKEN) {\n return {\n access_token: process.env.CLAWNIFY_TOKEN,\n refresh_token: \"\",\n expires_at: Number.MAX_SAFE_INTEGER,\n };\n }\n\n const token = await getValidToken();\n if (!token) {\n console.error(\n \"Not logged in. Run `clawnify login`, or set CLAWNIFY_TOKEN (a Supabase access token) for headless / CI use.\",\n );\n process.exit(1);\n }\n return loadAuth()!;\n}\n\n/** Parse email from Supabase JWT claims (base64url-decoded payload) */\nexport function getEmailFromToken(token: string): string | null {\n try {\n const payload = token.split(\".\")[1]!;\n const decoded = JSON.parse(\n Buffer.from(payload, \"base64url\").toString(\"utf-8\")\n );\n return decoded.email ?? null;\n } catch {\n return null;\n }\n}\n\n/** Generate PKCE code_verifier and code_challenge */\nexport function generatePkce(): {\n codeVerifier: string;\n codeChallenge: string;\n} {\n const codeVerifier = crypto.randomBytes(32).toString(\"base64url\");\n const codeChallenge = crypto\n .createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n return { codeVerifier, codeChallenge };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface ClawnifyAppConfig {\n framework: string;\n database?: boolean;\n storage?: boolean;\n}\n\nexport interface ClawnifyWebsiteConfig {\n framework: string;\n}\n\n/**\n * An agent member (see `docs/internal/adr-company-monorepo.md` § Layer 1).\n * `harness` selects the runtime adapter — today only `openclaw`, whose\n * payload is `AGENT.md` + `skills/` + `flows/` + `openclaw.json`.\n */\nexport interface ClawnifyAgentConfig {\n harness: string;\n}\n\n/**\n * A workspace root is a monorepo that hosts an org's apps. It carries no\n * `app`/`website` block of its own — its `clawnify.json` declares only the\n * org every child app deploys to. See `docs/internal/adr-company-monorepo.md`.\n */\nexport interface ClawnifyWorkspaceConfig {\n /** Org slug or id this workspace (and every app under it) is bound to. */\n org: string;\n}\n\nexport interface ClawnifyManifest {\n name: string;\n description?: string;\n app?: ClawnifyAppConfig;\n website?: ClawnifyWebsiteConfig;\n /**\n * Overloaded (kept for back-compat with the published schema):\n * - OBJECT `{ harness }` → this project IS an agent (workspace member, #814).\n * - STRING → path to an app's agent-instructions file (schema default\n * \"agent.md\"); an app declares it alongside `app`, and the build reads\n * the file (`app-deployer.ts`). It is NOT a project kind.\n */\n agent?: ClawnifyAgentConfig | string;\n workspace?: ClawnifyWorkspaceConfig;\n deploy?: {\n /**\n * Agents to declare on an anonymous deploy. The platform shows them on\n * the claim page (and in the dashboard after claim) as \"not hired yet\";\n * hiring one prefills the create form and applies `instructions` as its\n * AGENTS.md. Ignored on signed-in deploys.\n */\n agents?: PendingAgentSpec[];\n };\n}\n\nexport interface PendingAgentSpec {\n name: string;\n role?: string;\n description?: string;\n avatar_url?: string;\n instructions?: string;\n}\n\nexport type ManifestKind = \"app\" | \"website\" | \"agent\";\n\n/** Anonymous-deploy context: the unclaimed org this folder deploys into.\n * deploy_token authorizes /v1/anon/* only and dies at claim or expiry. */\nexport interface AnonContext {\n org_id: string;\n deploy_token: string;\n claim_url: string;\n claim_expires_at: string;\n}\n\nexport interface ProjectConfig {\n kind?: ManifestKind;\n org_id?: string;\n org_slug?: string;\n app_id?: string;\n app_token?: string;\n website_id?: string;\n slug?: string;\n /** Agent link: the server + named agent this member deploys to. */\n server_id?: string;\n agent_name?: string;\n /** Present while this folder deploys anonymously (no login). */\n anon?: AnonContext;\n}\n\nexport function readManifest(dir: string = process.cwd()): ClawnifyManifest | null {\n try {\n const data = fs.readFileSync(path.join(dir, \"clawnify.json\"), \"utf-8\");\n const manifest = JSON.parse(data) as ClawnifyManifest;\n if (!manifest.name) return null;\n if (!manifest.app && !manifest.website && !manifest.agent) return null;\n return manifest;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns the manifest kind, or throws with a clear message when neither or\n * both blocks are present. Callers should run this before dispatching deploy.\n */\nexport function manifestKind(manifest: ClawnifyManifest): ManifestKind {\n // `agent` is a project kind ONLY when it's an object ({ harness }). A string\n // value is an app's agent-instructions file path (schema default \"agent.md\"),\n // declared alongside `app` — it must not be counted as a second kind, or\n // every app that references its agent.md fails with a false \"more than one\n // kind\" error (open-crm, open-kitchen, …).\n const isAgentProject =\n typeof manifest.agent === \"object\" && manifest.agent !== null;\n const present: ManifestKind[] = [\n manifest.app ? \"app\" : null,\n manifest.website ? \"website\" : null,\n isAgentProject ? \"agent\" : null,\n ].filter((k): k is ManifestKind => k !== null);\n if (present.length > 1) {\n throw new Error(\n `clawnify.json declares more than one of \\`app\\`, \\`website\\`, \\`agent\\` (${present.join(\", \")}) — a project is exactly one kind.`,\n );\n }\n if (present.length === 0) {\n throw new Error(\n \"clawnify.json must declare an `app`, `website`, or `agent` block.\",\n );\n }\n return present[0]!;\n}\n\nexport function readProject(dir: string = process.cwd()): ProjectConfig | null {\n try {\n const data = fs.readFileSync(\n path.join(dir, \".clawnify\", \"project.json\"),\n \"utf-8\"\n );\n return JSON.parse(data) as ProjectConfig;\n } catch {\n return null;\n }\n}\n\n/**\n * The nearest `.clawnify/project.json` at or above `startDir`.\n *\n * Deliberately NOT folded into readProject(): that is used by paths which write\n * (`agents.ts` merges over it before saveProject) and by deploy, where \"which\n * folder am I in\" is the question being asked. Walking there would let a child\n * directory inherit — and then persist — a parent app's id and token.\n *\n * Org resolution is the opposite case: which org a command acts on shouldn't\n * change just because you cd'd into src/. Mirrors findWorkspaceRoot below, and\n * the way `supabase` resolves its project root from the nearest ancestor.\n */\nexport function findProjectRoot(\n startDir: string = process.cwd(),\n): ProjectConfig | null {\n let cur = path.resolve(startDir);\n for (;;) {\n const proj = readProject(cur);\n if (proj) return proj;\n const parent = path.dirname(cur);\n if (parent === cur) return null;\n cur = parent;\n }\n}\n\nexport function saveProject(dir: string, data: ProjectConfig): void {\n const projDir = path.join(dir, \".clawnify\");\n fs.mkdirSync(projDir, { recursive: true });\n fs.writeFileSync(\n path.join(projDir, \"project.json\"),\n JSON.stringify(data, null, 2)\n );\n}\n\nexport interface WorkspaceRoot {\n /** Absolute path to the workspace root directory. */\n dir: string;\n /** Org slug or id the workspace is bound to. */\n org: string;\n}\n\n/**\n * Read a workspace root's binding from `clawnify.json` at `dir`, or null if\n * that dir isn't a workspace root. A workspace is discriminated by the\n * presence of a `workspace.org` field (mirrors how app/website are detected).\n */\nexport function readWorkspaceConfig(dir: string): WorkspaceRoot | null {\n try {\n const data = fs.readFileSync(path.join(dir, \"clawnify.json\"), \"utf-8\");\n const manifest = JSON.parse(data) as ClawnifyManifest;\n if (manifest.workspace?.org) return { dir, org: manifest.workspace.org };\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Walk up from `startDir` to the filesystem root, returning the nearest\n * enclosing workspace root, or null if there is none. Used so `init` drops\n * new apps under `apps/` and `deploy` inherits the org for a fresh app.\n */\nexport function findWorkspaceRoot(\n startDir: string = process.cwd(),\n): WorkspaceRoot | null {\n let cur = path.resolve(startDir);\n for (;;) {\n const ws = readWorkspaceConfig(cur);\n if (ws) return ws;\n const parent = path.dirname(cur);\n if (parent === cur) return null;\n cur = parent;\n }\n}\n","import {\n requireAuth,\n loadAuth,\n saveAuth,\n refreshOnUnauthorized,\n type AuthData,\n} from \"./auth.js\";\nimport { findProjectRoot, findWorkspaceRoot } from \"./config.js\";\nimport readline from \"node:readline\";\n\n// Overridable for CLI development against a local `wrangler dev` API.\nconst API_BASE = process.env.CLAWNIFY_API_BASE ?? \"https://provision.clawnify.com\";\n\nconst UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nasync function apiRequest(\n method: string,\n path: string,\n options?: {\n body?: unknown;\n formData?: FormData;\n token?: string;\n orgId?: string;\n }\n): Promise<Response> {\n const headers: Record<string, string> = {};\n\n if (options?.token) {\n headers[\"Authorization\"] = `Bearer ${options.token}`;\n }\n if (options?.orgId) {\n // The header carries a UUID and nothing else. A slug here does not fail\n // loudly — it fails as \"some other org\" — so an unresolved value must be\n // caught at the boundary that builds the request, not discovered later in\n // whichever org the server settled on. Callers pass ids from matchOrg() /\n // resolveOrgContext(); raw user input belongs in `orgFlag`, not here.\n if (!UUID_RE.test(options.orgId)) {\n throw new Error(\n `Internal: x-org-id must be an org UUID, got \"${options.orgId}\". ` +\n `Resolve it with resolveOrgContext({ orgFlag }) first.`,\n );\n }\n headers[\"x-org-id\"] = options.orgId;\n }\n\n let body: BodyInit | undefined;\n if (options?.formData) {\n body = options.formData;\n } else if (options?.body) {\n headers[\"Content-Type\"] = \"application/json\";\n body = JSON.stringify(options.body);\n }\n\n return fetch(`${API_BASE}${path}`, { method, headers, body });\n}\n\nasync function ensureOrg(auth: AuthData): Promise<string | undefined> {\n // Any `org_id` still sitting in auth.json is a legacy artifact from when\n // `org use` wrote machine-global state. Honouring it here would keep that\n // behaviour alive for everyone who already has the file, so it is ignored\n // and left to be dropped on the next login.\n\n // Fetch orgs and prompt\n const orgsRes = await apiRequest(\"GET\", \"/v1/orgs\", { token: auth.access_token });\n if (!orgsRes.ok) return undefined;\n\n const { orgs } = (await orgsRes.json()) as {\n orgs: Array<{ id: string; name: string; slug: string; role: string }>;\n };\n\n if (orgs.length === 0) return undefined;\n\n let orgId: string;\n if (orgs.length === 1) {\n orgId = orgs[0].id;\n } else if (!process.stdin.isTTY || process.env.CLAWNIFY_TOKEN) {\n // Non-interactive (headless agent / CI / env auth): can't prompt — default\n // to the first org and tell the caller how to pin one.\n console.error(\n `Multiple orgs — defaulting to \"${orgs[0].name}\". Pin with CLAWNIFY_ORG_ID or --org.`,\n );\n orgId = orgs[0].id;\n } else {\n console.log(\"\\nSelect an organization:\\n\");\n orgs.forEach((org, i) => {\n console.log(` ${i + 1}) ${org.name} (${org.role})`);\n });\n console.log();\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const choice = await new Promise<string>((resolve) => {\n rl.question(\"Enter number: \", (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n\n const index = parseInt(choice, 10) - 1;\n orgId = (index >= 0 && index < orgs.length) ? orgs[index].id : orgs[0].id;\n console.log(`Selected: ${orgs[index >= 0 && index < orgs.length ? index : 0].name}\\n`);\n }\n\n // Deliberately NOT persisted. Writing the choice back to auth.json is what\n // created the machine-global active org in the first place. The durable\n // binding belongs to the folder (clawnify.json `workspace.org`, or\n // `.clawnify/project.json` via `clawnify link`), not to the machine.\n if (orgs.length > 1) {\n const chosen = orgs.find((o) => o.id === orgId);\n console.error(\n ` Using ${chosen?.name ?? orgId} for this command only.\\n` +\n ` Pin it so every command in this folder agrees: clawnify link <app> --org ${chosen?.slug ?? orgId}\\n` +\n ` (or set workspace.org in clawnify.json, or pass --org).`,\n );\n }\n return orgId;\n}\n\ntype OrgSource = \"flag\" | \"env\" | \"link\" | \"workspace\";\nlet orgCtxCache: string | undefined | null = null;\nlet orgEchoed = false;\n\n/** Print the org a command is acting on, once, to stderr (keeps stdout clean). */\nfunction echoOrg(label: string, source: OrgSource): void {\n if (orgEchoed) return;\n orgEchoed = true;\n process.stderr.write(`→ org: ${label} (${source})\\n`);\n}\n\nasync function matchOrg(ref: string): Promise<{ id: string; slug: string }> {\n const orgs = await listMyOrgs();\n const m = orgs.find((o) => o.id === ref || o.slug === ref);\n if (!m) {\n console.error(`No org matched \"${ref}\". Available: ${orgs.map((o) => o.slug).join(\", \")}`);\n process.exit(1);\n }\n return { id: m.id, slug: m.slug };\n}\n\n/**\n * Resolve which org the current command targets, folder-first:\n * --org → CLAWNIFY_ORG_ID → .clawnify/project.json org_id → workspace.org\n *\n * There is deliberately no machine-global fallback. Org is a property of the\n * directory you are standing in, never of the machine, so a second shell,\n * worktree or agent cannot repoint what this command targets. Memoized and\n * echoed once; returns undefined when nothing resolves, leaving the decision to\n * ensureOrg (single org → use it, otherwise prompt).\n */\nexport async function resolveOrgContext(\n opts?: { orgFlag?: string; dir?: string },\n): Promise<string | undefined> {\n if (orgCtxCache !== null) return orgCtxCache;\n const dir = opts?.dir ?? process.cwd();\n\n if (opts?.orgFlag) {\n const m = await matchOrg(opts.orgFlag);\n const proj = findProjectRoot(dir);\n if (proj?.org_id && proj.org_id !== m.id) {\n console.error(\n `This folder is linked to a different org (${proj.org_slug ?? proj.org_id}).\\n` +\n ` --org ${opts.orgFlag} resolves to ${m.slug}. Re-link, or run from another directory.`,\n );\n process.exit(1);\n }\n orgCtxCache = m.id;\n echoOrg(m.slug, \"flag\");\n return m.id;\n }\n\n const env = process.env.CLAWNIFY_ORG_ID;\n if (env) {\n // Accepts a slug as well as a UUID, like --org. A slug used to be passed\n // through untouched and land as \"some other org\" server-side; resolving it\n // here keeps CI configs honest. UUIDs skip the lookup — the common case\n // shouldn't pay for a network round-trip.\n const id = UUID_RE.test(env) ? env : (await matchOrg(env)).id;\n orgCtxCache = id;\n echoOrg(env, \"env\");\n return id;\n }\n\n const proj = findProjectRoot(dir);\n if (proj?.org_id) {\n orgCtxCache = proj.org_id;\n echoOrg(proj.org_slug ?? proj.org_id, \"link\");\n return proj.org_id;\n }\n\n const ws = findWorkspaceRoot(dir);\n if (ws?.org) {\n const m = await matchOrg(ws.org);\n orgCtxCache = m.id;\n echoOrg(m.slug, \"workspace\");\n return m.id;\n }\n\n // NO machine-global fallback. `~/.clawnify/auth.json` is an auth artifact and\n // must not carry a project binding: it is one mutable pointer shared by every\n // shell, worktree and agent on the box, so one session repointing it silently\n // redirected another session's commands at a different tenant. Falling through\n // to undefined hands the decision to ensureOrg, which resolves an unambiguous\n // single org and otherwise prompts — a better answer than a stale global.\n orgCtxCache = undefined;\n return undefined;\n}\n\nasync function authedRequest(\n method: string,\n path: string,\n options?: { body?: unknown; formData?: FormData; orgId?: string }\n): Promise<Response> {\n let auth = await requireAuth();\n let orgId = options?.orgId;\n if (!orgId) {\n orgId = await resolveOrgContext();\n if (!orgId) {\n orgId = await ensureOrg(auth);\n }\n }\n\n const res = await apiRequest(method, path, {\n ...options,\n token: auth.access_token,\n orgId,\n });\n\n if (res.status !== 401) return res;\n\n // A 401 is not necessarily an expired session: the token may have been\n // rotated by a concurrent invocation, revoked, or the route itself may be\n // rejecting an otherwise-valid token. Attempt exactly one silent refresh and\n // retry before deciding it's a login problem.\n const fresh = await refreshOnUnauthorized(auth.access_token);\n if (!fresh) {\n if (process.env.CLAWNIFY_TOKEN) {\n console.error(\"CLAWNIFY_TOKEN was rejected (401). Provide a valid Supabase access token.\");\n } else {\n console.error(\"Session expired. Run `clawnify login` again.\");\n }\n process.exit(1);\n }\n\n // Retry once with the refreshed token. If it still 401s, this isn't a session\n // problem — return the response so the caller surfaces the real error instead\n // of masquerading it as a login failure.\n return apiRequest(method, path, {\n ...options,\n token: fresh,\n orgId,\n });\n}\n\nexport interface Org {\n id: string;\n name: string;\n slug: string;\n role: string;\n}\n\n/** List every org the authenticated user belongs to, bypassing org selection. */\nexport async function listMyOrgs(): Promise<Org[]> {\n const auth = await requireAuth();\n const res = await apiRequest(\"GET\", \"/v1/orgs\", { token: auth.access_token });\n if (!res.ok) return [];\n const { orgs } = (await res.json()) as { orgs: Org[] };\n return orgs ?? [];\n}\n\nexport const api = {\n get: (path: string, opts?: { orgId?: string }) =>\n authedRequest(\"GET\", path, opts),\n post: (path: string, body?: unknown, opts?: { orgId?: string }) =>\n authedRequest(\"POST\", path, { body, ...opts }),\n postForm: (path: string, formData: FormData, opts?: { orgId?: string }) =>\n authedRequest(\"POST\", path, { formData, ...opts }),\n del: (path: string, opts?: { orgId?: string }) =>\n authedRequest(\"DELETE\", path, opts),\n // Generic authed request for the `clawnify api` escape hatch (any method).\n call: (method: string, path: string, opts?: { body?: unknown; orgId?: string }) =>\n authedRequest(method, path, opts),\n request: apiRequest,\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { execSync } from \"node:child_process\";\nimport { gzipSync } from \"node:zlib\";\n\nconst EXCLUDE_DIRS = new Set([\n \"node_modules\",\n \".git\",\n \"dist\",\n \".next\",\n \".clawnify\",\n \"build\",\n]);\n\nconst MAX_SIZE = 20 * 1024 * 1024; // 20MB\n\nfunction runGit(args: string[], dir: string): string | null {\n try {\n return execSync(`git ${args.join(\" \")}`, {\n cwd: dir,\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // execSync's default maxBuffer is 1MB. `ls-files --others` enumerates\n // every file under an unignored node_modules, which easily exceeds that —\n // the throw was caught below and untracked files silently vanished from\n // the archive (new assets never deployed).\n maxBuffer: 64 * 1024 * 1024,\n });\n } catch {\n return null;\n }\n}\n\n/**\n * Collect every file `git add .` would stage: tracked files plus untracked\n * files that aren't ignored. Returns null if the directory isn't a git repo,\n * so the caller falls back to walkDir.\n *\n * The previous implementation used only `git ls-files`, which silently\n * excluded brand-new untracked files — a common foot-gun when an agent\n * (or human) creates a file but forgets to `git add` it.\n */\nfunction getGitFiles(dir: string): string[] | null {\n const tracked = runGit([\"ls-files\", \"-z\"], dir);\n if (tracked === null) return null;\n const untrackedResult = runGit([\"ls-files\", \"-z\", \"--others\", \"--exclude-standard\"], dir);\n if (untrackedResult === null) {\n // Never fail silently here: proceeding without untracked files means a\n // brand-new asset quietly missing from the deployed site.\n console.warn(\n \" warning: could not list untracked files (git ls-files --others failed); \" +\n \"newly created files that aren't committed may be missing from this deploy.\",\n );\n }\n const untracked = untrackedResult ?? \"\";\n const merged = new Set<string>();\n for (const f of tracked.split(\"\\0\")) if (f) merged.add(f);\n for (const f of untracked.split(\"\\0\")) if (f) merged.add(f);\n return [...merged];\n}\n\nfunction walkDir(dir: string, base: string = \"\"): string[] {\n const files: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (EXCLUDE_DIRS.has(entry.name)) continue;\n const rel = base ? `${base}/${entry.name}` : entry.name;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...walkDir(full, rel));\n } else if (entry.isFile()) {\n files.push(rel);\n }\n }\n return files;\n}\n\n/**\n * A repo-root `manifest.json` is not part of the clawnify contract\n * (clawnify.json is). Some templates leave a Preact-style manifest behind;\n * users see \"manifest\" and assume it controls something. Warn so they know\n * it's being uploaded as a dumb file.\n */\nfunction warnOnStaleManifest(dir: string, files: string[]) {\n if (!files.includes(\"manifest.json\")) return;\n try {\n const raw = fs.readFileSync(path.join(dir, \"manifest.json\"), \"utf-8\");\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n if (parsed && typeof parsed === \"object\" && \"framework\" in parsed && \"files\" in parsed) {\n console.warn(\n ` warning: manifest.json looks like a stale auto-generated file. ` +\n `Clawnify uses clawnify.json — manifest.json is ignored.`,\n );\n }\n } catch {\n // not JSON, not our concern\n }\n}\n\n/**\n * EXCLUDE_DIRS must hold on BOTH listing paths. The git path lists whatever\n * git would stage — which includes `.clawnify/` (app_token!) or `.env` when\n * the surrounding repo's .gitignore doesn't cover them (e.g. a cloned\n * template). Those must never be uploaded regardless of git status.\n */\nfunction isExcludedPath(rel: string): boolean {\n const parts = rel.split(\"/\");\n return parts.some((p) => EXCLUDE_DIRS.has(p)) || parts[parts.length - 1] === \".env\";\n}\n\nfunction listFiles(dir: string): string[] {\n const fromGit = getGitFiles(dir);\n const files = (fromGit ?? walkDir(dir)).filter((f) => !isExcludedPath(f));\n warnOnStaleManifest(dir, files);\n return files;\n}\n\n/** Public helper for `clawnify deploy --dry-run`. */\nexport function listArchiveFiles(dir: string): string[] {\n return listFiles(dir);\n}\n\nfunction createTarHeader(filename: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(filename, 0, Math.min(filename.length, 100), \"utf-8\");\n header.write(\"0000644\\0\", 100, 8, \"utf-8\");\n header.write(\"0000000\\0\", 108, 8, \"utf-8\");\n header.write(\"0000000\\0\", 116, 8, \"utf-8\");\n header.write(size.toString(8).padStart(11, \"0\") + \"\\0\", 124, 12, \"utf-8\");\n const mtime = Math.floor(Date.now() / 1000);\n header.write(mtime.toString(8).padStart(11, \"0\") + \"\\0\", 136, 12, \"utf-8\");\n header.write(\"0\", 156, 1, \"utf-8\");\n header.write(\"ustar\\0\", 257, 6, \"utf-8\");\n header.write(\"00\", 263, 2, \"utf-8\");\n header.write(\" \", 148, 8, \"utf-8\");\n let checksum = 0;\n for (let i = 0; i < 512; i++) {\n checksum += header[i]!;\n }\n header.write(checksum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, 8, \"utf-8\");\n return header;\n}\n\n/**\n * Drizzle migrations live under `.clawnify/drizzle/<NNNN>_<name>.sql`\n * locally (gitignored, regenerated by the CLI on dev/deploy). The\n * deploy pipeline (PR #444) scans R2's `drizzle/` prefix on each\n * deploy. We remap on upload — the user's repo stays clean, the\n * pipeline contract is unchanged.\n *\n * Only top-level `*.sql` files come along; drizzle's `meta/` snapshot\n * dir is local-only state.\n */\nfunction collectDrizzleMigrations(\n dir: string,\n): { src: string; tarName: string }[] {\n const drizzleDir = path.join(dir, \".clawnify\", \"drizzle\");\n if (!fs.existsSync(drizzleDir)) return [];\n try {\n return fs\n .readdirSync(drizzleDir)\n .filter((name) => name.endsWith(\".sql\"))\n .sort()\n .map((name) => ({\n src: path.join(drizzleDir, name),\n tarName: `drizzle/${name}`,\n }));\n } catch {\n return [];\n }\n}\n\nexport function createArchive(dir: string): { archive: Buffer; files: string[] } {\n const files = listFiles(dir);\n const parts: Buffer[] = [];\n const includedFiles: string[] = [];\n\n function addEntry(absPath: string, tarName: string): void {\n let stat: fs.Stats;\n try {\n stat = fs.statSync(absPath);\n } catch {\n return;\n }\n if (!stat.isFile()) return;\n\n const content = fs.readFileSync(absPath);\n const header = createTarHeader(tarName, content.length);\n parts.push(header);\n parts.push(content);\n includedFiles.push(tarName);\n\n const remainder = content.length % 512;\n if (remainder > 0) {\n parts.push(Buffer.alloc(512 - remainder));\n }\n }\n\n for (const file of files) {\n addEntry(path.join(dir, file), file);\n }\n\n for (const m of collectDrizzleMigrations(dir)) {\n addEntry(m.src, m.tarName);\n }\n\n parts.push(Buffer.alloc(1024));\n\n const tar = Buffer.concat(parts);\n const gzipped = gzipSync(tar);\n\n if (gzipped.length > MAX_SIZE) {\n throw new Error(\n `Archive too large (${(gzipped.length / 1024 / 1024).toFixed(1)}MB). Maximum is 20MB.`,\n );\n }\n\n return { archive: gzipped, files: includedFiles };\n}\n","import { api } from \"./api.js\";\n\nconst SPINNER_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n\nexport interface AppStatus {\n status: string;\n status_message?: string;\n url?: string;\n error?: string;\n}\n\n// Status values that mean we're done — apps use \"live\"/\"error\", websites\n// use \"live\"/\"failed\". Pollers stop on any of these.\nconst TERMINAL_STATUSES = new Set([\"live\", \"ready\", \"error\", \"failed\"]);\nconst FAILURE_STATUSES = new Set([\"error\", \"failed\"]);\n// Draft-first: a CLI website deploy builds to the draft tier and parks at\n// \"preview\" (publishing to live is an explicit, separate action from the\n// dashboard). So \"preview\" is a terminal SUCCESS for websites — without this\n// the poller would spin until it times out on a perfectly good deploy.\nconst WEBSITE_TERMINAL_SUCCESS = new Set([\"preview\"]);\n// An app deploy made while the app has unpublished chat changes joins them as\n// a draft instead of going live (the server only does this for a client that\n// sends `accepts_draft`), so \"draft\" is a terminal success for apps.\nconst APP_TERMINAL_SUCCESS = new Set([\"draft\"]);\n\nexport async function pollUntilReady(\n resourceId: string,\n options: {\n interval?: number;\n timeout?: number;\n kind?: \"app\" | \"website\";\n orgId?: string;\n /** Anonymous deploy token — polls /v1/anon/* instead of the authed surface. */\n anonToken?: string;\n } = {},\n): Promise<AppStatus> {\n const interval = options.interval ?? 3000;\n const timeout = options.timeout ?? 300000;\n const kind = options.kind ?? \"app\";\n const authedBase = kind === \"website\" ? \"/v1/websites\" : \"/v1/apps\";\n const basePath = options.anonToken\n ? (kind === \"website\" ? \"/v1/anon/websites\" : \"/v1/anon/apps\")\n : authedBase;\n const start = Date.now();\n let frame = 0;\n const isTTY = Boolean(process.stdout.isTTY);\n let lastMessage = \"\";\n // A reply with no status means the resource was not found for whoever we\n // asked as — nearly always the wrong org. Printing \"status: undefined\" for\n // five minutes and then claiming a timeout hides that, so say it. A couple\n // are tolerated first: a just-created app can lag its own row by a beat.\n let statusless = 0;\n const STATUSLESS_LIMIT = 3;\n\n while (Date.now() - start < timeout) {\n const res = options.anonToken\n ? await api.request(\"GET\", `${basePath}/${resourceId}`, { token: options.anonToken })\n : await api.get(`${basePath}/${resourceId}`, { orgId: options.orgId });\n const data = (await res.json()) as AppStatus;\n if (!data.status) {\n if (++statusless >= STATUSLESS_LIMIT) {\n if (isTTY) process.stdout.write(\"\\r\\x1b[K\");\n throw new Error(\n options.orgId\n ? `Deployed, but its status could not be read: ${kind === \"website\" ? \"website\" : \"app\"} ${resourceId} is not visible in org ${options.orgId}.`\n : `Deployed, but its status could not be read: ${kind === \"website\" ? \"website\" : \"app\"} ${resourceId} was not found. If it went to another organization, pass --org.`,\n );\n }\n await new Promise((r) => setTimeout(r, interval));\n continue;\n }\n statusless = 0;\n const message = data.status_message || data.status;\n\n if (isTTY) {\n const spinner = SPINNER_FRAMES[frame % SPINNER_FRAMES.length];\n process.stdout.write(`\\r${spinner} ${message}`);\n } else if (message !== lastMessage) {\n // Non-TTY (CI logs, background tasks): write whole lines so the\n // output survives in pipes and files instead of being mangled by\n // cursor escapes from the spinner.\n console.log(`status: ${message}`);\n lastMessage = message;\n }\n frame++;\n\n const terminal =\n TERMINAL_STATUSES.has(data.status) ||\n (kind === \"website\" && WEBSITE_TERMINAL_SUCCESS.has(data.status)) ||\n (kind === \"app\" && APP_TERMINAL_SUCCESS.has(data.status));\n if (terminal) {\n if (isTTY) process.stdout.write(\"\\r\\x1b[K\");\n // Normalize \"failed\" to \"error\" so downstream callers only branch\n // on one terminal-failure value.\n if (FAILURE_STATUSES.has(data.status)) {\n return { ...data, status: \"error\" };\n }\n return data;\n }\n\n await new Promise((r) => setTimeout(r, interval));\n }\n\n if (isTTY) process.stdout.write(\"\\r\\x1b[K\");\n throw new Error(\"Timed out waiting for deployment\");\n}\n","/**\n * The CLI's real version, injected at build time from package.json by\n * tsup.config.ts. package.json stays the single source of truth — bumping it\n * IS the release (see .github/workflows/publish-cli.yml), and this makes\n * `clawnify --version` say the same thing.\n *\n * It used to be a hardcoded \"0.1.0\" in cli.ts and mcp.ts, which meant every\n * build ever published reported the same string. That made \"are you on the\n * fixed CLI?\" unanswerable — a stale global install (npm installs into the\n * ACTIVE nvm node version, so one per node version is easy to end up with)\n * was indistinguishable from a current one.\n */\ndeclare const __CLI_VERSION__: string;\n\nexport const VERSION = __CLI_VERSION__;\n"],"mappings":";;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,YAAY;AACnB,SAAS,eAAe;AACxB,SAAS,cAAc,aAAa;AAEpC,IAAM,eAAe;AAGd,IAAM,kBAAkB;AACxB,IAAM,sBAAsB,GAAG,YAAY;AAC3C,IAAM,kBAAkB,GAAG,YAAY;AAE9C,IAAM,WAAW,KAAK,KAAK,QAAQ,GAAG,WAAW;AACjD,IAAM,YAAY,KAAK,KAAK,UAAU,WAAW;AACjD,IAAM,YAAY,KAAK,KAAK,UAAU,WAAW;AAKjD,IAAM,gBAAgB;AACtB,IAAM,eAAe;AAcd,SAAS,WAA4B;AAC1C,MAAI;AACF,UAAM,OAAO,GAAG,aAAa,WAAW,OAAO;AAC/C,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,SAAS,MAAsB;AAC7C,KAAG,UAAU,UAAU,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAIvD,QAAM,EAAE,cAAc,eAAe,WAAW,IAAI;AACpD,KAAG;AAAA,IACD;AAAA,IACA,KAAK,UAAU,EAAE,cAAc,eAAe,WAAW,GAAG,MAAM,CAAC;AAAA,IACnE,EAAE,MAAM,IAAM;AAAA,EAChB;AACF;AAEO,SAAS,YAAkB;A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KAChC,SAAS,aAAa,yBAAyB,IAAI,KAAK,MAAM,KAC9D,SAAS,SAAS,qBAAqB,IAAI,KAAK,MAAM;AACzD,QAAI,UAAU;AACZ,UAAI,MAAO,SAAQ,OAAO,MAAM,UAAU;AAG1C,UAAI,iBAAiB,IAAI,KAAK,MAAM,GAAG;AACrC,eAAO,EAAE,GAAG,MAAM,QAAQ,QAAQ;AAAA,MACpC;AACA,aAAO;AAAA,IACT;AAEA,UAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,QAAQ,CAAC;AAAA,EAClD;AAEA,MAAI,MAAO,SAAQ,OAAO,MAAM,UAAU;AAC1C,QAAM,IAAI,MAAM,kCAAkC;AACpD;;;AC3FO,IAAM,UAAU;","names":["fs","path","path","proj","fs","path","path","fs"]}
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
resolveOrgContext,
|
|
21
21
|
saveAuth,
|
|
22
22
|
saveProject
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-JBI5FFND.js";
|
|
24
24
|
|
|
25
25
|
// src/cli.ts
|
|
26
26
|
import { Command, Option } from "commander";
|
|
@@ -487,13 +487,24 @@ async function uploadRedeploy(appId, archive, orgId, sync) {
|
|
|
487
487
|
const formData = new FormData();
|
|
488
488
|
formData.append("source", new Blob([archive]), "source.tar.gz");
|
|
489
489
|
appendSyncFields(formData, sync.dir, sync.force);
|
|
490
|
+
appendDraftFields(formData, sync.discardDraft);
|
|
490
491
|
const res = await postFormWithRetry(`/v1/apps/${appId}/redeploy`, formData, orgId);
|
|
491
492
|
if (res.ok) {
|
|
492
493
|
const data = await res.json();
|
|
493
494
|
return { ok: true, data };
|
|
494
495
|
}
|
|
495
496
|
const err = await res.json().catch(() => ({}));
|
|
496
|
-
return { ok: false, error: err
|
|
497
|
+
return { ok: false, error: redeployError(err, res.statusText) };
|
|
498
|
+
}
|
|
499
|
+
function appendDraftFields(formData, discardDraft) {
|
|
500
|
+
formData.append("accepts_draft", "true");
|
|
501
|
+
if (discardDraft) formData.append("discard_draft", "true");
|
|
502
|
+
}
|
|
503
|
+
function redeployError(err, fallback) {
|
|
504
|
+
if (err.code === "draft_pending") {
|
|
505
|
+
return "This app has unpublished changes from the chat, and this deploy would overwrite them. Review and publish them in the dashboard first, or deploy again with --discard-draft to replace them.";
|
|
506
|
+
}
|
|
507
|
+
return err.error || fallback;
|
|
497
508
|
}
|
|
498
509
|
async function repoDeploy(opts) {
|
|
499
510
|
const res = await api.post(
|
|
@@ -521,7 +532,13 @@ async function repoDeploy(opts) {
|
|
|
521
532
|
async function repoRedeploy(appId, opts, orgId) {
|
|
522
533
|
const res = await api.post(
|
|
523
534
|
`/v1/apps/${appId}/redeploy`,
|
|
524
|
-
{
|
|
535
|
+
{
|
|
536
|
+
repo: opts.repo,
|
|
537
|
+
branch: "main",
|
|
538
|
+
subdir: opts.subdir,
|
|
539
|
+
accepts_draft: true,
|
|
540
|
+
...opts.discardDraft ? { discard_draft: true } : {}
|
|
541
|
+
},
|
|
525
542
|
{ orgId }
|
|
526
543
|
);
|
|
527
544
|
if (res.ok) {
|
|
@@ -529,7 +546,7 @@ async function repoRedeploy(appId, opts, orgId) {
|
|
|
529
546
|
return { ok: true, data };
|
|
530
547
|
}
|
|
531
548
|
const err = await res.json().catch(() => ({}));
|
|
532
|
-
return { ok: false, error: err
|
|
549
|
+
return { ok: false, error: redeployError(err, res.statusText) };
|
|
533
550
|
}
|
|
534
551
|
function assertNodeVersion() {
|
|
535
552
|
const [major] = process.versions.node.split(".").map(Number);
|
|
@@ -980,7 +997,11 @@ async function deployCommand(dir, options = {}) {
|
|
|
980
997
|
if (decision === "update") {
|
|
981
998
|
const existingSlug = result2.conflict.existing_app_slug ?? result2.conflict.slug;
|
|
982
999
|
console.log(`Updating ${result2.conflict.existing_app_name} (${existingSlug})...`);
|
|
983
|
-
const redeployed = await repoRedeploy(
|
|
1000
|
+
const redeployed = await repoRedeploy(
|
|
1001
|
+
result2.conflict.existing_app_id,
|
|
1002
|
+
{ repo, subdir, discardDraft: options.discardDraft },
|
|
1003
|
+
orgId
|
|
1004
|
+
);
|
|
984
1005
|
if (!redeployed.ok) {
|
|
985
1006
|
console.error(`Deploy failed: ${redeployed.error}`);
|
|
986
1007
|
process.exit(1);
|
|
@@ -1079,7 +1100,11 @@ async function deployCommand(dir, options = {}) {
|
|
|
1079
1100
|
let needsCreate = !linkedProject?.app_id;
|
|
1080
1101
|
if (linkedProject?.app_id) {
|
|
1081
1102
|
console.log(`Updating ${baseName} (${linkedProject.slug ?? linkedProject.app_id})...`);
|
|
1082
|
-
const result2 = await uploadRedeploy(linkedProject.app_id, archive, orgId, {
|
|
1103
|
+
const result2 = await uploadRedeploy(linkedProject.app_id, archive, orgId, {
|
|
1104
|
+
dir: resolvedDir,
|
|
1105
|
+
force: options.force,
|
|
1106
|
+
discardDraft: options.discardDraft
|
|
1107
|
+
});
|
|
1083
1108
|
if (result2.ok) {
|
|
1084
1109
|
appId = result2.data.app_id;
|
|
1085
1110
|
slug = result2.data.slug;
|
|
@@ -1105,7 +1130,8 @@ async function deployCommand(dir, options = {}) {
|
|
|
1105
1130
|
if (decision === "update") {
|
|
1106
1131
|
const redeployResult = await uploadRedeploy(result2.conflict.existing_app_id, archive, orgId, {
|
|
1107
1132
|
dir: resolvedDir,
|
|
1108
|
-
force: options.force
|
|
1133
|
+
force: options.force,
|
|
1134
|
+
discardDraft: options.discardDraft
|
|
1109
1135
|
});
|
|
1110
1136
|
if (!redeployResult.ok) {
|
|
1111
1137
|
console.error(`Deploy failed: ${redeployResult.error}`);
|
|
@@ -1147,11 +1173,22 @@ async function deployCommand(dir, options = {}) {
|
|
|
1147
1173
|
process.exit(1);
|
|
1148
1174
|
}
|
|
1149
1175
|
const url = `https://${slug}.apps.clawnify.com`;
|
|
1150
|
-
|
|
1176
|
+
if (result.status === "draft") {
|
|
1177
|
+
console.log(
|
|
1178
|
+
`
|
|
1179
|
+
\u2713 Deployed as a draft. ${slug} has unpublished changes from the chat, so this deploy joined them
|
|
1180
|
+
instead of going live. Review and publish both in the dashboard:
|
|
1181
|
+
https://app.clawnify.com/apps/${slug}
|
|
1182
|
+
To replace those changes instead, deploy again with --discard-draft.
|
|
1183
|
+
`
|
|
1184
|
+
);
|
|
1185
|
+
} else {
|
|
1186
|
+
console.log(`
|
|
1151
1187
|
\u2713 Deployed! ${url}
|
|
1152
1188
|
`);
|
|
1153
|
-
|
|
1189
|
+
console.log(` Open: clawnify open ${slug}
|
|
1154
1190
|
`);
|
|
1191
|
+
}
|
|
1155
1192
|
if (syncTargetDir && !options.noSync && resolvedOrgId) {
|
|
1156
1193
|
try {
|
|
1157
1194
|
const schema = await fetchSchema({ appId, orgId: resolvedOrgId });
|
|
@@ -1754,7 +1791,7 @@ function agentByName(name) {
|
|
|
1754
1791
|
var ALL_AGENTS = DETECTORS.map((d) => d.agent);
|
|
1755
1792
|
|
|
1756
1793
|
// src/lib/skills/content.gen.ts
|
|
1757
|
-
var CLI_VERSION = "0.
|
|
1794
|
+
var CLI_VERSION = "0.20.1";
|
|
1758
1795
|
var BUNDLED_SKILLS = [
|
|
1759
1796
|
{
|
|
1760
1797
|
name: "build-a-clawnify-app",
|
|
@@ -1769,7 +1806,7 @@ var BUNDLED_SKILLS = [
|
|
|
1769
1806
|
{
|
|
1770
1807
|
name: "use-the-clawnify-cli",
|
|
1771
1808
|
description: "Use the Clawnify CLI end-to-end \u2014 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.",
|
|
1772
|
-
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, route patterns), use the\n`build-a-clawnify-app` skill \u2014 this one covers the tooling around it.\n\n## TL;DR\n\n```bash\nnpx clawnify@latest login # browser sign-in, paste-code fallback\nnpx clawnify@latest init my-app # scaffold an app or website\ncd my-app && npx clawnify@latest dev\nnpx clawnify@latest deploy # \u2192 https://<slug>.apps.clawnify.com\n```\n\n- **Always invoke as `npx clawnify@latest <command>`.** Never install\n globally or pin a version \u2014 the CLI ships guards and self-heals\n continuously, and a stale copy misses them. Reference blocks below\n show bare `clawnify <cmd>` for brevity; run them with the full\n `npx clawnify@latest` form. (Scaffolded apps' package scripts \u2014\n `pnpm dev`, `pnpm deploy` \u2014 already delegate correctly.)\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** \u2014 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 \u2014 no port forwarding needed).\n\n**Headless / CI / agents \u2014 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 \u2014 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 \u2014 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 db generate # refresh .clawnify/drizzle/*.sql from schema.ts\nclawnify pull schema --from <app-id-or-slug> # snapshot the DEPLOYED schema to schema.sql (generated; read-only reference)\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 \u2014 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 live agent state, never a GitHub\nrepo).\n\n**The model \u2014 two levels, and only two.** An org has one or more **agents** (the\nAI employees, e.g. \"Ash\"). Each agent can have **sub-agents**: narrower helpers\nit delegates to. `clawnify agents list` prints both, sub-agents indented under\nthe agent that owns them:\n\n```\nAsh (ready, nbg1)\n id: 7c2f\u2026\n sub-agents:\n \u2514\u2500 research (Research) 4 sessions\n```\n\nAn org normally has exactly one agent, so nothing needs to be selected. When it\nhas several, pass `--agent-id <id>` (the `id:` line above).\n\n```bash\nclawnify agents list # the org's agents, each with its sub-agents\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 \u2014 where it veered\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/ to edit (flows/ come with main only \u2014 flows belong to the main agent)\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 SUB-AGENT (RESTARTS the gateway)\nclawnify env set <KEY> <VALUE> # org custom env \u2014 NON-SECRET only (restarts gateway)\nclawnify connections connect <id> # how to connect an integration (dashboard OAuth; you can't)\nclawnify flows list # the main agent's flows + latest published version\nclawnify flows read <name> # print a flow's draft\nclawnify flows create <name> --file f.json # new draft (validated on save)\nclawnify flows edit <name> # edit the draft ($EDITOR, or --file to replace)\nclawnify flows publish <name> # cut the next numbered live version\n```\n\n**Flows:** runs and triggers use the latest **published** version, so editing a\ndraft doesn't change what's live \u2014 until a flow's first publish, though, the\ndraft *is* what runs. `create`/`edit`/`publish` validate automatically and\nreport per-node errors; fix and re-save. Prefer these verbs over pushing raw\n`flows/*.json` edits (which skip validation and versioning).\n\n**Boundary:** everything above is autonomous *except* the human-auth actions \u2014\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 agent.\n\n**`agents create` makes a NEW sub-agent \u2014 it is never the way to \"find\" an\nexisting one.** If you were looking for an agent and `agents list` didn't show\nit, the answer is that the org doesn't have it, or you're in the wrong org\n(`clawnify org list`). Creating one restarts the gateway and leaves a duplicate\nbehind.\n\n## Connections & env names\n\n```bash\nclawnify connections list # the org's naming catalog (\u25CF connected / \u25CB not)\nclawnify connections connect <id> # how to connect one \u2014 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 \u2014 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 /agents # any GET\nclawnify api /apps -X POST -d '{\u2026}' # any method + JSON body\n```\n\n`clawnify api <path>` makes an authenticated request to any Clawnify API path \u2014\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` \u2014 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"
|
|
1809
|
+
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, route patterns), use the\n`build-a-clawnify-app` skill \u2014 this one covers the tooling around it.\n\n## TL;DR\n\n```bash\nnpx clawnify@latest login # browser sign-in, paste-code fallback\nnpx clawnify@latest init my-app # scaffold an app or website\ncd my-app && npx clawnify@latest dev\nnpx clawnify@latest deploy # \u2192 https://<slug>.apps.clawnify.com\n```\n\n- **Always invoke as `npx clawnify@latest <command>`.** Never install\n globally or pin a version \u2014 the CLI ships guards and self-heals\n continuously, and a stale copy misses them. Reference blocks below\n show bare `clawnify <cmd>` for brevity; run them with the full\n `npx clawnify@latest` form. (Scaffolded apps' package scripts \u2014\n `pnpm dev`, `pnpm deploy` \u2014 already delegate correctly.)\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** \u2014 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 \u2014 no port forwarding needed).\n\n**Headless / CI / agents \u2014 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 \u2014 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 \u2014 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\nIf the app has unpublished changes from the chat, the deploy won't publish\nthem: it lands as a draft on top of them (publish both in the dashboard), or\nit is refused if it would overwrite them. `--discard-draft` replaces them;\nonly use it when the user says those changes can go.\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 db generate # refresh .clawnify/drizzle/*.sql from schema.ts\nclawnify pull schema --from <app-id-or-slug> # snapshot the DEPLOYED schema to schema.sql (generated; read-only reference)\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 \u2014 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 live agent state, never a GitHub\nrepo).\n\n**The model \u2014 two levels, and only two.** An org has one or more **agents** (the\nAI employees, e.g. \"Ash\"). Each agent can have **sub-agents**: narrower helpers\nit delegates to. `clawnify agents list` prints both, sub-agents indented under\nthe agent that owns them:\n\n```\nAsh (ready, nbg1)\n id: 7c2f\u2026\n sub-agents:\n \u2514\u2500 research (Research) 4 sessions\n```\n\nAn org normally has exactly one agent, so nothing needs to be selected. When it\nhas several, pass `--agent-id <id>` (the `id:` line above).\n\n```bash\nclawnify agents list # the org's agents, each with its sub-agents\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 \u2014 where it veered\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/ to edit (flows/ come with main only \u2014 flows belong to the main agent)\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 SUB-AGENT (RESTARTS the gateway)\nclawnify env set <KEY> <VALUE> # org custom env \u2014 NON-SECRET only (restarts gateway)\nclawnify connections connect <id> # how to connect an integration (dashboard OAuth; you can't)\nclawnify flows list # the main agent's flows + latest published version\nclawnify flows read <name> # print a flow's draft\nclawnify flows create <name> --file f.json # new draft (validated on save)\nclawnify flows edit <name> # edit the draft ($EDITOR, or --file to replace)\nclawnify flows publish <name> # cut the next numbered live version\n```\n\n**Flows:** runs and triggers use the latest **published** version, so editing a\ndraft doesn't change what's live \u2014 until a flow's first publish, though, the\ndraft *is* what runs. `create`/`edit`/`publish` validate automatically and\nreport per-node errors; fix and re-save. Prefer these verbs over pushing raw\n`flows/*.json` edits (which skip validation and versioning).\n\n**Boundary:** everything above is autonomous *except* the human-auth actions \u2014\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 agent.\n\n**`agents create` makes a NEW sub-agent \u2014 it is never the way to \"find\" an\nexisting one.** If you were looking for an agent and `agents list` didn't show\nit, the answer is that the org doesn't have it, or you're in the wrong org\n(`clawnify org list`). Creating one restarts the gateway and leaves a duplicate\nbehind.\n\n## Connections & env names\n\n```bash\nclawnify connections list # the org's naming catalog (\u25CF connected / \u25CB not)\nclawnify connections connect <id> # how to connect one \u2014 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 \u2014 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 /agents # any GET\nclawnify api /apps -X POST -d '{\u2026}' # any method + JSON body\n```\n\n`clawnify api <path>` makes an authenticated request to any Clawnify API path \u2014\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` \u2014 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"
|
|
1773
1810
|
},
|
|
1774
1811
|
{
|
|
1775
1812
|
name: "fix-a-clawnify-agent",
|
|
@@ -4395,7 +4432,7 @@ async function runCli() {
|
|
|
4395
4432
|
"--agent-id <id>",
|
|
4396
4433
|
"Agent deploy: which agent to push to when the org has several (saved as a link)"
|
|
4397
4434
|
)
|
|
4398
|
-
).addOption(legacyServerOption()).option("--agent <name>", "Agent deploy: the named agent to push to (default: main)").option("--path <subdir>", "Subdirectory within the --from repo that holds the app (monorepo)").option("--name <name>", "Override app name").option("--org <slug-or-id>", "Deploy to a specific org (overrides active org)").option("-y, --yes", "Non-interactive: on conflict, update the existing app").option("--update-existing", "Non-interactive: on conflict, overwrite the existing app").option("--create-new", "Non-interactive: on conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").option("--no-sync", "Skip the post-deploy schema.sql sync into the local working directory").option("--force", "Deploy even if it would overwrite newer changes in the synced GitHub repo").option("--replace", "Website deploy: replace the organization's existing website with this folder, which isn't linked to it").action(deployCommand);
|
|
4435
|
+
).addOption(legacyServerOption()).option("--agent <name>", "Agent deploy: the named agent to push to (default: main)").option("--path <subdir>", "Subdirectory within the --from repo that holds the app (monorepo)").option("--name <name>", "Override app name").option("--org <slug-or-id>", "Deploy to a specific org (overrides active org)").option("-y, --yes", "Non-interactive: on conflict, update the existing app").option("--update-existing", "Non-interactive: on conflict, overwrite the existing app").option("--create-new", "Non-interactive: on conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").option("--no-sync", "Skip the post-deploy schema.sql sync into the local working directory").option("--force", "Deploy even if it would overwrite newer changes in the synced GitHub repo").option("--discard-draft", "Replace the app's unpublished chat changes with this deploy instead of keeping them for review").option("--replace", "Website deploy: replace the organization's existing website with this folder, which isn't linked to it").action(deployCommand);
|
|
4399
4436
|
program.command("link <app-id-or-slug>").description("Link the current directory to an existing Clawnify app (accepts id or slug)").option("--dir <dir>", "Directory to link (default: cwd)").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(linkCommand);
|
|
4400
4437
|
const pull = program.command("pull").description("Pull artifacts from a deployed app into the current directory");
|
|
4401
4438
|
pull.command("schema").description("Fetch the deployed app's current schema.sql snapshot into the local repo").option("--from <app-id-or-slug>", "App to fetch from (required)").option("--out <path>", "Where to write (default: ./schema.sql)").option("--force", "Overwrite a locally-modified or uncommitted schema.sql").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(pullSchemaCommand);
|
|
@@ -4461,4 +4498,4 @@ async function runCli() {
|
|
|
4461
4498
|
export {
|
|
4462
4499
|
runCli
|
|
4463
4500
|
};
|
|
4464
|
-
//# sourceMappingURL=cli-
|
|
4501
|
+
//# sourceMappingURL=cli-7WSI6PRM.js.map
|