clawnify 0.22.3 → 0.23.0
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.
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
resolveOrgContext,
|
|
23
23
|
saveAuth,
|
|
24
24
|
saveProject
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-AWYLQGFE.js";
|
|
26
26
|
|
|
27
27
|
// src/cli.ts
|
|
28
28
|
import { Command, Option } from "commander";
|
|
@@ -415,6 +415,23 @@ async function resolveServerId(explicit) {
|
|
|
415
415
|
process.exit(1);
|
|
416
416
|
}
|
|
417
417
|
|
|
418
|
+
// src/lib/node-version.ts
|
|
419
|
+
function assertNodeVersion() {
|
|
420
|
+
const [major] = process.versions.node.split(".").map(Number);
|
|
421
|
+
if (major < 22) {
|
|
422
|
+
console.error(
|
|
423
|
+
`
|
|
424
|
+
Clawnify requires Node.js v22 or later.
|
|
425
|
+
You are using v${process.versions.node}.
|
|
426
|
+
|
|
427
|
+
Install a newer version: https://nodejs.org
|
|
428
|
+
Or use a version manager: nvm use 22
|
|
429
|
+
`
|
|
430
|
+
);
|
|
431
|
+
process.exit(1);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
418
435
|
// src/commands/deploy.ts
|
|
419
436
|
var EXIT_USAGE = 64;
|
|
420
437
|
var EXIT_CONFLICT_NEEDS_DECISION = 75;
|
|
@@ -550,21 +567,6 @@ async function repoRedeploy(appId, opts, orgId) {
|
|
|
550
567
|
const err = await res.json().catch(() => ({}));
|
|
551
568
|
return { ok: false, error: redeployError(err, res.statusText) };
|
|
552
569
|
}
|
|
553
|
-
function assertNodeVersion() {
|
|
554
|
-
const [major] = process.versions.node.split(".").map(Number);
|
|
555
|
-
if (major < 22) {
|
|
556
|
-
console.error(
|
|
557
|
-
`
|
|
558
|
-
Clawnify requires Node.js v22 or later.
|
|
559
|
-
You are using v${process.versions.node}.
|
|
560
|
-
|
|
561
|
-
Install a newer version: https://nodejs.org
|
|
562
|
-
Or use a version manager: nvm use 22
|
|
563
|
-
`
|
|
564
|
-
);
|
|
565
|
-
process.exit(1);
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
570
|
async function resolveOrgId(options, linkedProject, resolvedDir) {
|
|
569
571
|
if (options.org) {
|
|
570
572
|
const orgs = await listMyOrgs();
|
|
@@ -1777,22 +1779,22 @@ function agentByName(name) {
|
|
|
1777
1779
|
var ALL_AGENTS = DETECTORS.map((d) => d.agent);
|
|
1778
1780
|
|
|
1779
1781
|
// src/lib/skills/content.gen.ts
|
|
1780
|
-
var CLI_VERSION = "0.
|
|
1782
|
+
var CLI_VERSION = "0.23.0";
|
|
1781
1783
|
var BUNDLED_SKILLS = [
|
|
1782
1784
|
{
|
|
1783
1785
|
name: "build-a-clawnify-app",
|
|
1784
1786
|
description: "Author a Clawnify app end-to-end \u2014 the canonical Hono + React + Vite + @hono/zod-openapi + @clawnify/db (Drizzle) stack, schema.ts as the single schema source of truth (DDL generated via pnpm db:generate), OpenAPIHono routes (createRoute) that auto-generate an OpenAPI spec, and platform-injected identity via user()/orgId()/caller(). Use when building or modifying an app that deploys to the Clawnify platform.",
|
|
1785
|
-
content: '# Build a Clawnify app\n\nCanonical skill: how to author a Clawnify app end-to-end. Same content\nfor humans reading the docs and for AI coding agents injecting this as\ninstructions during an app build.\n\nIf you\'re an agent: this document is enough context to produce a\nworking app from scratch. Follow it literally. The patterns here\nare exactly what `clawnify init` scaffolds and what the platform\nexpects.\n\n## TL;DR\n\n- **One stack.** Hono + React + Vite + `@hono/zod-openapi` +\n `@clawnify/db` (Drizzle) + `@clawnify/app` (entry, routing,\n identity) + Tailwind v4. Nothing else.\n- **Schema lives in `schema.ts` alone** \u2014 the Drizzle DSL your queries\n compile against. The DDL is generated from it (`pnpm db:generate` \u2192\n `.clawnify/drizzle/*.sql`); never hand-write a `schema.sql` in a\n scaffolded app.\n- **Queries through `getDB`** \u2014 `import { getDB, eq } from\n "@clawnify/db"`. JSON columns auto-serialize.\n- **API routes are `OpenAPIHono` + `createRoute`** \u2014 Zod-validated\n request/response.\n- **`createApp()`** (from `@clawnify/app`) builds the entry \u2014 it returns an\n `OpenAPIHono` with API discovery already mounted (`/api/openapi.json` +\n `/llms.txt`, generated from your live routes). That descriptor *is* the\n tool surface agents discover. Never hand-write those routes.\n- **One import.** `@clawnify/app` re-exports `createRoute`, `z` and\n `OpenAPIHono`, and adds `user` / `orgId` / `caller`. Import from it, not\n from `@clawnify/routes` directly.\n- **`clawnify.json`** declares framework, env, and public routes.\n There is no `api.tools[]` \u2014 the agent discovers and calls your\n endpoints via `/llms.txt` (and the OpenAPI spec).\n- **Identity is injected by the platform** \u2014 read it with `user(c)` /\n `orgId(c)` / `caller(c)` from `@clawnify/app`. Your app never\n authenticates anyone.\n\n## Stack rationale\n\nOne template, one set of decisions. Don\'t deviate unless the user has\nexplicitly asked. `clawnify init` (type `app`) scaffolds either a\n`blank` template (one GET route + a page) or a `crud` template (a\ntable with list/create/update/delete + a form). Both share the exact\nsame stack below.\n\n## File layout\n\n```\nmy-app/\n clawnify.json \u2190 Manifest (validated against /schema/v1/clawnify.json)\n package.json\n tsconfig.json\n vite.config.ts \u2190 @vitejs/plugin-react + @tailwindcss/vite; proxies /api \u2192 :8787\n index.html\n .gitignore\n .clawnify/ \u2190 Managed by the CLI (gitignored) \u2014 never edit\n wrangler.toml \u2190 Generated wrangler config\n drizzle.config.ts \u2190 Generated drizzle config (from clawnify.json + schema.ts)\n drizzle/ \u2190 Generated migration SQL (applied by dev + deploy)\n applied-migrations.json \u2190 Local-apply tracker\n src/\n server/\n index.ts \u2190 OpenAPIHono entry \u2014 mounts routes, serves /api/openapi.json\n routes.ts \u2190 OpenAPIHono + createRoute definitions \u2014 the API surface\n schema.ts \u2190 Drizzle table definitions \u2014 the single source of truth\n worker-env.d.ts \u2190 Cloudflare Workers types reference\n uploads.ts \u2190 R2 helpers (only when storage is enabled)\n client/\n main.tsx \u2190 React mount point\n app.tsx \u2190 Root component (plain fetch against /api/*)\n index.css \u2190 @import "tailwindcss"\n```\n\n## Schema \u2014 `schema.ts` is the single source of truth\n\n`schema.ts` (Drizzle DSL) defines the tables. Do **not** hand-write a\n`schema.sql` in a scaffolded app, and there is no toolchain config to\nmaintain: the drizzle config is a managed artifact the CLI materializes\ninto `.clawnify/` (from `clawnify.json` + the schema path), and the DDL\nis generated from `schema.ts` into `.clawnify/drizzle/*.sql` \u2014 which is\nwhat `clawnify dev` applies locally and the deploy applies to your D1.\n\nThe scaffold\'s starter table (blank template):\n\n```ts\n// src/server/schema.ts\nimport { sqliteTable, text, integer } from "@clawnify/db";\n\nexport const items = sqliteTable("items", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n name: text("name").notNull(),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n});\n```\n\nReal apps are multi-tenant. Every user-facing table carries an\n`org_id`, every query filters by it. JSON columns and indexes use the\nDrizzle DSL re-exported from `@clawnify/db`:\n\n```ts\nimport { sqliteTable, text, integer, index } from "@clawnify/db";\n\nexport const notes = sqliteTable(\n "notes",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n orgId: text("org_id").notNull(), // ALWAYS filter by this in queries\n title: text("title").notNull(),\n body: text("body").notNull().default(""),\n tags: text("tags", { mode: "json" }).$type<string[]>().notNull().default([]),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n },\n (t) => ({\n byOrg: index("notes_by_org").on(t.orgId, t.createdAt),\n }),\n);\n```\n\nRules:\n- JSON columns: `text(col, { mode: "json" }).$type<T>()` \u2014 Drizzle\n serializes on write and parses on read.\n- Multi-tenancy: every user-facing table has `org_id`. Every query\n filters by it. No exceptions.\n- Identifiers: snake_case in SQL, camelCase in TS (Drizzle bridges).\n\n## Generating the DDL \u2014 automatic, or `clawnify db generate`\n\n`clawnify dev` and `clawnify deploy` (local-directory deploys) generate\nthe migration SQL themselves \u2014 editing `schema.ts` and running dev or\ndeploy is the whole workflow. To refresh the SQL explicitly without\neither, run `npx clawnify@latest db generate` (the scaffold\'s\n`pnpm db:generate` is an alias for it). Always invoke the CLI as\n`npx clawnify@latest` \u2014 never a global or pinned install. Deploy refuses a database-enabled app with no DDL,\nso a broken generate fails loudly, not silently.\n\nOne artifact to leave alone: after a successful signed-in deploy the CLI\nsyncs a read-only `schema.sql` snapshot of the DEPLOYED schema into the\napp root. It is generated output for reference/diffing \u2014 never edit it,\nand never treat it as the source of truth (`schema.ts` is).\n\nRules:\n- Deploys are **additive**: new tables and columns are added\n automatically. Destructive changes (dropping or retyping a column) are\n not applied automatically \u2014 do those deliberately, and never drop a\n table with user data unless explicitly asked.\n- Never edit the generated `.clawnify/drizzle/*.sql` by hand \u2014 change\n `schema.ts` and regenerate.\n- A hand-written `schema.sql` at the app root is accepted **only** for\n apps that don\'t use Drizzle at all (e.g. some template repos). A\n scaffolded app never needs one.\n\n## `src/server/index.ts` \u2014 the entry\n\n```ts\nimport { createApp } from "@clawnify/app";\nimport api from "./routes";\n\n// db:false \u2014 this app reads the database per request via getDB(c.env),\n// which needs no init middleware.\nconst app = createApp({ title: "My app", version: "1.0.0", db: false });\n\napp.route("/", api);\n\nexport default app;\n```\n\nThe entry is thin: `createApp()` then mount your routes. `createApp`\nreturns an `OpenAPIHono` with **API discovery already mounted** \u2014 it\nserves both `/api/openapi.json` (generated from your `createRoute`\ndefinitions, with schemas) **and** `/llms.txt` (the same, agent-readable).\nAny `/api/*` route written as a plain `app.get` with no `createRoute` is\nstill listed from the live route table, so the endpoint inventory is\nalways complete. **Never hand-write a `/openapi.json` or `/llms.txt`\nhandler** \u2014 and don\'t call `mountDiscovery` yourself; `createApp` did it.\n\nWhen storage (file uploads) is enabled, the entry also wires the R2\nbucket in a middleware before mounting routes:\n\n```ts\nimport { createApp, type AppEnv } from "@clawnify/app";\nimport { initUploads } from "./uploads";\nimport api from "./routes";\n\ntype Env = AppEnv & { Bindings: { UPLOADS: R2Bucket } };\n\nconst app = createApp<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.use("*", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route("/", api);\n\nexport default app;\n```\n\n## `src/server/routes.ts` \u2014 routes with `createRoute`\n\nEach endpoint is a `createRoute({ method, path, summary, request, responses })`\ndefinition paired with a handler via `api.openapi(route, handler)`.\nRequest bodies and params are Zod-validated (`c.req.valid("json")`,\n`c.req.valid("param")`); response shapes are declared with\n`.openapi("Name")` Zod schemas so they land in the generated spec.\n\nBlank template \u2014 one read route:\n\n```ts\nimport { OpenAPIHono, createRoute, z, PageQuery, pageParams, pagedResponse, type AppEnv } from "@clawnify/app";\nimport { getDB, desc, like } from "@clawnify/db";\nimport * as schema from "./schema";\n\nconst api = new OpenAPIHono<AppEnv>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n // Every list endpoint pages: an agent reads this API through one tool,\n // and an unbounded list would land in its context whole.\n request: { query: PageQuery },\n responses: { 200: pagedResponse("items", ItemSchema) },\n }),\n async (c) => {\n const { page, limit, offset, search } = pageParams(c.req.valid("query"));\n const db = getDB(c.env, { schema });\n const where = search ? like(schema.items.name, "%" + search + "%") : undefined;\n const total = await db.$count(schema.items, where);\n const items = await db\n .select()\n .from(schema.items)\n .where(where)\n .orderBy(desc(schema.items.createdAt))\n .limit(limit)\n .offset(offset);\n return c.json({ items, total, page, limit }, 200);\n },\n);\n\nexport default api;\n```\n\nCRUD template \u2014 the full list/create/update/delete surface:\n\n```ts\nimport { OpenAPIHono, createRoute, z, PageQuery, pageParams, pagedResponse, type AppEnv } from "@clawnify/app";\nimport { getDB, eq, desc, like } from "@clawnify/db";\nimport * as schema from "./schema";\n\nconst api = new OpenAPIHono<AppEnv>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi("UpdateItem");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n // Every list endpoint pages: an agent reads this API through one tool,\n // and an unbounded list would land in its context whole.\n request: { query: PageQuery },\n responses: { 200: pagedResponse("items", ItemSchema) },\n }),\n async (c) => {\n const { page, limit, offset, search } = pageParams(c.req.valid("query"));\n const db = getDB(c.env, { schema });\n const where = search ? like(schema.items.title, "%" + search + "%") : undefined;\n const total = await db.$count(schema.items, where);\n const items = await db\n .select()\n .from(schema.items)\n .where(where)\n .orderBy(desc(schema.items.createdAt))\n .limit(limit)\n .offset(offset);\n return c.json({ items, total, page, limit }, 200);\n },\n);\n\napi.openapi(\n createRoute({\n method: "post",\n path: "/api/items",\n summary: "Create item",\n request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: "Created item",\n content: { "application/json": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid("json");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: "patch",\n path: "/api/items/:id",\n summary: "Update item",\n request: {\n params: IdParamSchema,\n body: { content: { "application/json": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },\n 400: { description: "Nothing to update", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const body = c.req.valid("json");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: "delete",\n path: "/api/items/:id",\n summary: "Delete item",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n```\n\nPatterns to follow:\n- **Give every route a clear `summary`/`description`.** The generated\n OpenAPI spec is what the agent reads to decide which endpoint to\n call \u2014 a vague summary makes your endpoint invisible in practice.\n- **Validate input with Zod** via `request.body` / `request.params`\n and read it with `c.req.valid("json")` / `c.req.valid("param")`.\n Never parse `c.req.raw` by hand.\n- **Declare response shapes** with `.openapi("Name")` schemas \u2014 they\n become the documented return type in the spec.\n- **Filter by the org** on every user-facing query (see "who is\n calling" below). No exceptions.\n\n## `src/server` \u2014 who is calling\n\nThe platform authenticates every caller at its perimeter and injects a\nverified identity onto the request (it strips any client-supplied\nversion first, so it can\'t be spoofed). Your app never authenticates\nanyone: no `Authorization`, no cookies, no JWT, no login screen.\n\nRead it with the helpers from `@clawnify/app` \u2014 don\'t parse headers\nyourself:\n\n```ts\nimport { user, orgId, caller } from "@clawnify/app";\n\napp.get("/api/notes", async (c) => {\n const org = orgId(c);\n if (!org) return c.json({ error: "unauthorized" }, 401);\n\n const db = getDB(c.env, { schema });\n return c.json(\n await db.select().from(schema.notes).where(eq(schema.notes.orgId, org)),\n );\n});\n```\n\n| Helper | Returns |\n|--------|---------|\n| `orgId(c)` | Organization UUID \u2014 the tenant key. Filter every user-facing query by it. |\n| `user(c)` | `{ id, email, name, avatarUrl, firstName, lastName }` \u2014 or **`null`** when the caller isn\'t a person. |\n| `caller(c)` | `user`, `api`, `agent`, `agent-browser`, `public`, `bypass`, `system`, or `app`. |\n| `hasRole(c, min)` | Whether the caller may do a task meant for `min` (`member` < `admin` < `owner`). Use it to gate admin-only tasks. Needs `@clawnify/app` 0.4.5 or later. |\n| `role(c)` | `owner`, `admin` or `member` on Team plans and up; **`null`** below that, where every member is treated the same. For display, not for gating. |\n\nTwo rules that catch people out:\n\n- **`user(c)` is null for five of the eight caller kinds**\n (`agent-browser`, `public`, `bypass`, `system`, `app`). Always handle\n the null case \u2014 don\'t assume a person is present just because a\n request arrived. For per-user rows, store `user(c).id` in a `user_id`\n column and filter on it, exactly as you filter on `org_id`.\n- **`firstName` / `lastName` are a heuristic** split of a single stored\n full name (first word / the rest). Fine for a greeting; never persist\n them or treat them as someone\'s legal name \u2014 store `name`.\n\nDon\'t build app-level users, roles, or permissions. Authorization\nalready happened at the perimeter. For a task meant for admins, use\n`hasRole(c, "admin")`: it checks the role where the plan has role tiers\nand lets every person through where it does not, so one check works on\nevery plan. It fails closed: a caller with no person behind it, or a\nrequest with no identity at all (local `pnpm dev`), passes no check, so a\ngated endpoint answering 403 there is the gate working. Don\'t loosen a\ngate to make a test pass. Never gate on `role(c)` by hand.\n\n## `src/client` \u2014 React + plain fetch\n\nThe client mounts React and talks to the API with plain `fetch`\nagainst the `/api/*` routes. No data-layer library is scaffolded.\n\n```tsx\n// src/client/main.tsx\nimport { StrictMode } from "react";\nimport { createRoot } from "react-dom/client";\nimport { App } from "./app";\nimport "./index.css";\n\ncreateRoot(document.getElementById("app")!).render(\n <StrictMode>\n <App />\n </StrictMode>\n);\n```\n\n```tsx\n// src/client/app.tsx (CRUD template shape)\nimport { useState, useEffect } from "react";\n\ninterface Item {\n id: number;\n title: string;\n status: string;\n createdAt: string;\n}\n\nexport function App() {\n const [items, setItems] = useState<Item[]>([]);\n const [title, setTitle] = useState("");\n\n async function load() {\n const res = await fetch("/api/items");\n setItems(((await res.json()) as { items: Item[] }).items);\n }\n\n useEffect(() => { load(); }, []);\n\n async function addItem(e: React.FormEvent) {\n e.preventDefault();\n if (!title.trim()) return;\n await fetch("/api/items", {\n method: "POST",\n headers: { "Content-Type": "application/json" },\n body: JSON.stringify({ title }),\n });\n setTitle("");\n load();\n }\n\n // ...toggleStatus / deleteItem call PATCH/DELETE the same way.\n\n return (\n <div className="max-w-xl mx-auto mt-10 px-4">\n {/* form + list */}\n </div>\n );\n}\n```\n\nIn local dev, Vite proxies `/api` to the Worker on `:8787` (see\n`vite.config.ts`), so the same relative fetch paths work in dev and\nin production. The API is the one contract: the UI calls it over\n`fetch`, and the agent calls it over the OpenAPI spec.\n\n## Design\n\nIf the project contains a `DESIGN.md`, it is the single source of\ntruth for visuals \u2014 follow its tokens, don\'t restyle around it. The\nscaffold ships Tailwind v4 (via `@tailwindcss/vite`, imported with\n`@import "tailwindcss";` in `index.css`) and nothing else \u2014 no\ncomponent library. The rules every Clawnify app follows:\n\n- **Neutral chrome.** White canvas and surfaces, one text ramp\n (foreground \u2192 muted \u2192 faint), hairline borders. Color is for\n meaning, not decoration.\n- **One primary CTA per screen.** Blue is reserved for links and\n focus rings; never a second accent.\n- **Status colors are muted pairs** \u2014 never pure-saturated fills.\n- **Style with Tailwind utilities.** Don\'t install another component\n library or write a bespoke CSS system unless the user asks.\n- **Sizes in rem**, so browser zoom and font settings are respected.\n\n## `clawnify.json` \u2014 the manifest\n\n```json\n{\n "$schema": "https://app.clawnify.com/schema/v1/clawnify.json",\n "version": 1,\n "name": "Notes",\n "description": "Take and organize notes. Searchable by tag.",\n "app": {\n "framework": "react+hono",\n "database": true,\n "storage": false\n },\n "env": {\n "optional": ["OPENROUTER_API_KEY"]\n },\n "api": {\n "public_routes": [\n { "path": "/api/feed", "methods": ["GET"] }\n ]\n }\n}\n```\n\n`clawnify init` writes the minimal form:\n`{ app: { framework: "react+hono", database: true, storage } }`. Add\nthe rest as needed.\n\nIf the app talks to third-party services the user has connected\n(ads platforms, CRMs, messaging), declare them:\n\n```json\n{ "app": { "credentials": ["metaads", "googleads"] } }\n```\n\nGet the ids and names from `clawnify connections list` \u2014 see the\nnaming rule below.\n\n`env` supports `required` (deploy warns if missing), `optional`\n(injected when available), and `oneOf` (at least one per group).\n\nRules:\n- **There is no `api.tools[]`.** The manifest\'s `api` object only\n accepts `public_routes` and `automation_bypass`. Your API surface\n is discovered from the generated OpenAPI spec, not a hand-authored\n tools list (see the next section).\n- **Public routes are the exception**, not the default. Every route\n is behind the Clawnify perimeter (auth-required) unless you\n explicitly add a matching path to `api.public_routes`. Use only for\n webhooks, RSS, embedded feeds.\n- **`framework: "react+hono"`** for new apps. Never `preact+hono` or\n `vite-preact` \u2014 those are legacy.\n- **`database: true`** if the app uses a DB. `schema.ts` defines the\n tables; run `pnpm db:generate` after changing it.\n\n## How the agent reaches your API (no `api.tools[]`)\n\nThe old tRPC stack emitted an `api.tools[]` array from procedure meta.\nThat mechanism is gone. Today the flow is:\n\n1. Your `createRoute` definitions auto-generate a live OpenAPI 3.0 spec\n plus a lean `/llms.txt` index, both served for you \u2014 never hand-write\n or route them yourself. **These are the agent\'s discovery channel:**\n it reads `GET /llms.txt` (index of every endpoint) or\n `GET /api/openapi.json` (full request/response schemas) on the live\n app. Because both are generated from the live route table, they\n cannot drift from the code.\n2. The agent then drives your endpoints on the live app. A Clawnify\n agent uses `clawnify_call_app_api`; Claude, ChatGPT and other MCP\n clients use `clawnify_app_api_read` (GET), `clawnify_app_api_write`\n (POST, PUT, PATCH) and `clawnify_app_api_delete`. No per-app MCP\n registration and no manifest tools array. Use source reading to\n *modify* code, not to discover endpoints.\n\nSo you make an endpoint "agent-callable" by defining it with\n`createRoute()` + `app.openapi()` and giving it a clear\n`summary`/`description` with Zod-typed request/response. The clearer\nthose are, the more reliably the agent uses it.\n\n### `agent.md` \u2014 lead with the procedure, not the endpoint list\n\n`agent.md` is extracted into `agent_instructions` on every build. Since\ndiscovery is already covered by the generated surfaces above, **`agent.md`\nis not an API reference** \u2014 re-listing every payload there just creates a\nsecond source of truth that goes stale the first time a route changes.\nIt is the one place for what generation can\'t produce: **judgment**.\n\nWrite it in this order:\n\n1. **Division of labour, first and short.** What the agent should do\n itself vs. what it must delegate to the app \u2014 and say the wrong move\n out loud (*"never look up contact details yourself; post the records\n and let the app resolve them"*). This one block prevents more misuse\n than the rest of the file combined.\n2. **The procedure** \u2014 numbered steps for the app\'s main job, written so\n the agent can follow them on a request it has never seen.\n3. **Pages**, flagging the screenshot-friendly ones.\n4. **API anchors, not API docs** \u2014 method, path, and *when to reach for\n it*, plus the one or two request shapes the agent writes most often.\n For anything else, let it read `/llms.txt`.\n5. **How to read failures**, and any **cost discipline** \u2014 which calls\n spend the user\'s money and which are free.\n\n**Don\'t ship a per-app skill.** A skill\'s frontmatter stays resident in\nagent context, so one skill per app grows the agent\'s context floor as\nthe app count grows; `agent_instructions` and `/llms.txt` are pulled on\ndemand instead. Skills are for **cross-app** procedures \u2014 if one earns\nreuse across more than one app, promote that single procedure\n(parameterized) to the shared skills library rather than copying it into\nevery app.\n\n## Connections & secrets \u2014 `@clawnify/connections`\n\n**The naming rule \u2014 never invent an identifier.** Before declaring\n`credentials` or env names, run `clawnify connections list`: it shows\nthe org\'s canonical integration ids (`googleads`, never `google_ads`),\nthe fixed provider-key names (`OPENROUTER_API_KEY`, never\n`OPENROUTER_KEY`), and custom env vars already defined \u2014 each with\nconnected/set state. Reuse those exact identifiers; a misspelled one\ndoesn\'t fail the build, it silently resolves to nothing at runtime. If\nyou need a custom secret that isn\'t listed, pick a clear name and tell\nthe user to set it in the dashboard.\n\nIf the app needs a third-party service or a provider API key, use\nthe `@clawnify/connections` SDK. Never read credential bindings\ndirectly, never paste API keys, never hardcode a token or endpoint.\n\n```ts\nimport { connect, secret, describe, searchActions } from "@clawnify/connections";\n\n// A connected integration:\nconst meta = connect("metaads", env);\nconst accounts = await meta.adAccounts("name,currency");\n\n// A provider key the user supplied (null if absent):\nconst key = secret("OPENROUTER_API_KEY", env);\n\n// What\'s wired vs missing \u2014 drive your setup/empty state from this:\nconst status = await describe(env, undefined, REQUIRES);\n```\n\nHow to call a connected service \u2014 the mistake that silently breaks\nintegration apps, so get it right:\n\n- **Prefer the typed client\'s semantic methods** where they exist\n (`meta.adAccounts(...)`, `googleads.query(gaql)`).\n- **For anything else, discover and run an action:**\n ```ts\n const [best] = await searchActions("list google ads campaigns", env);\n const data = await connect(best.service, env).run(best.slug, body);\n ```\n- Some integrations also expose a raw REST client\n (`connect("bird", env).get("/path")`) \u2014 but if `.get()`/`.post()`\n throws for a service, that service only supports semantic methods\n and `run()`. When unsure, use `run()`.\n- **Need exact paths/arguments for a raw-REST provider?** Some carry\n a `spec_url` (the provider\'s published OpenAPI spec) \u2014\n `clawnify connections list --json` shows it. Download and query it \u2014\n `curl -s <spec_url> -o spec.json && jq \'.paths | keys\' spec.json` \u2014\n never read a whole spec into context (they run to 10+ MB).\n- **Never fall back to raw `fetch`** against a provider API, and\n never invent endpoints or guess tokens.\n\n**The one exception \u2014 a service we don\'t support at all.** If a\nprovider isn\'t in the connections registry (nothing to `connect()`\nto, and `clawnify connections list` doesn\'t show it), the sanctioned\npath *is* a raw call with a user-supplied key: declare the key(s) it\nneeds in `clawnify.json` `env` (`required`/`optional`/`oneOf`), tell\nthe user to set them in the dashboard, read them with\n`secret("THAT_KEY", env)`, and `fetch` the provider\'s documented\nendpoints directly. This is the escape hatch for the long tail of\nintegrations we don\'t model yet \u2014 it does **not** apply to a service\nwe *do* support (use `connect()` / `run()` for those, always). Keep\nthe endpoint and token server-side, never in the client bundle.\n\nBuild a `describe()`-driven setup state instead of assuming\nconnections exist \u2014 show the user what\'s missing and where to\nconnect it.\n\n## Scheduling & deferred work \u2014 the managed queue\n\nA deployed app **cannot bind Cloudflare Queues, Durable Objects, or cron\ntriggers** (the platform builds every app with a fixed binding set: `DB` +\n`ASSETS` + `UPLOADS`). To run work later \u2014 a scheduled publish, a reminder, a\nretry, a "do this in 10 minutes" \u2014 use the **Clawnify managed queue service**\nover HTTP. It owns the clock, retries, and at-least-once delivery, then calls an\nendpoint on *your own app* back at the scheduled time.\n\nUse the published `@clawnify/queue` package \u2014 `enqueueJob`, `cancelJob`,\n`verifyDelivery` \u2014 same shape as `@clawnify/db` / `@clawnify/connections`.\nAuth is the build-injected `env.CLAWNIFY_TOKEN`; with no token (local dev)\nit degrades to a no-op.\n\n**Enqueue** a deferred call to your own endpoint:\n\n```ts\n// POST https://services.clawnify.com/queue/enqueue (Bearer CLAWNIFY_TOKEN)\nconst res = await fetch("https://services.clawnify.com/queue/enqueue", {\n method: "POST",\n headers: { Authorization: `Bearer ${env.CLAWNIFY_TOKEN}`, "Content-Type": "application/json" },\n body: JSON.stringify({\n target_url: `${origin}/api/internal/publish`, // an endpoint on THIS app\n payload: { post_id: id }, // echoed back to you on fire\n run_at: new Date(whenMs).toISOString(),\n idempotency_key: `post:${id}:${whenMs}`, // same key dedupes; new time = new job\n }),\n});\nconst { job_id } = await res.json(); // store it to cancel/reschedule\n```\n\nPersist `job_id` on the row (e.g. `posts.queue_job_id`). **Cancel / reschedule**:\n`DELETE https://services.clawnify.com/queue/jobs/{job_id}` (Bearer token);\nreschedule = cancel + a fresh enqueue.\n\n**The callback endpoint is a public, signature-verified route.** The queue calls\n`target_url` from outside the perimeter, so the endpoint must be declared in\n`clawnify.json` `public_routes` **and** verify the delivery signature itself \u2014\nthe signature *is* its auth (never trust an unsigned call):\n\n```jsonc\n// clawnify.json\n"api": { "public_routes": [ { "path": "/api/internal/publish", "methods": ["POST"] } ] }\n```\n\nDeliveries are signed with the platform\'s **ECDSA P-256 (ES256)** key,\nStripe-style over `${timestamp}.${rawBody}`, verified against\n`https://services.clawnify.com/.well-known/jwks.json` (public key \u2014 nothing\nbreaks on token rotation). Read the raw body, check the signature + a timestamp\ntolerance (~5 min) before doing anything:\n\n```ts\napp.post("/api/internal/publish", async (c) => {\n const raw = await c.req.text();\n const ok = await verifyDelivery(raw, {\n signature: c.req.header("x-queue-signature"),\n timestamp: c.req.header("x-queue-timestamp"),\n keyId: c.req.header("x-queue-key-id"),\n });\n if (!ok) return c.json({ error: "bad signature" }, 401);\n const { post_id } = JSON.parse(raw);\n // \u2026do the deferred work (short: it\'s one normal Worker invocation)\u2026\n return c.json({ ok: true });\n});\n```\n\nEach fire is a normal Worker request \u2014 size the work to one invocation (publish a\npost, send a digest). For long compute *now* (not deferred), hold the request\nopen and return when done; don\'t fire-and-forget past the response.\n\n**When the queue says no.** A refused enqueue answers `{ "error", "detail" }`\n(`enqueueJob` throws `ClawnifyQueueError` with `code`, `status` and `message`).\nPast the plan\'s monthly included jobs each job costs credits, so only an empty\nbalance (`402 insufficient_credits`) or no active plan (`403 quota_exceeded`)\nrefuses one; show its `detail` to the owner as it is, since it says where to fix\nit. A job that books the next one (a daily sync) must never swallow that\nrefusal: keep it, show it as a banner on the app\'s main page, and return it from\nthe app\'s status endpoint. Every service error code:\nhttps://docs.clawnify.com/concepts/service-errors\n\n## Migrations\n\nThe workflow is:\n\n1. Edit `src/server/schema.ts` for the new shape (types + queries).\n2. Run `pnpm db:generate` \u2014 emits the migration SQL under\n `.clawnify/drizzle/`.\n3. Run `npx clawnify@latest dev` locally, then `npx clawnify@latest deploy`.\n\nOn deploy your schema changes are applied to the app\'s database \u2014 new\ntables and columns are added automatically.\n\nDestructive changes (drop column, rename) are not applied automatically;\ndo them deliberately, and only when the user explicitly asks. Renames\nare risky on production data \u2014 prefer "add new column, backfill, switch\nqueries, drop old column" over a single-step rename.\n\n## What the agent must NOT do\n\n- Author a `/openapi.json` or `/llms.txt` handler by hand. `createApp()`\n mounts both, generated from your `createRoute` definitions.\n- Hand-write a `schema.sql`, edit anything under `.clawnify/`, or add a\n root `drizzle.config.ts`. Schema changes happen in `schema.ts`; the\n CLI generates and applies the SQL.\n- Invent an `api.tools[]` array in the manifest. It isn\'t a valid\n field \u2014 the OpenAPI spec is the tool surface.\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\n via Drizzle. The raw SQL API has `json()` as a helper.\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\n leak is the worst-class bug we can ship.\n- Return a whole table from a list endpoint, or a bare array. Every list\n pages: `PageQuery`, `pageParams` and `pagedResponse` from `@clawnify/app`.\n- Read auth from `Authorization` / cookies / `Bearer` tokens, or\n hand-parse `X-Clawnify-*` headers. Use `user(c)` / `orgId(c)` /\n `caller(c)` from `@clawnify/app`.\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\n through `@clawnify/connections` (`connect` / `secret` / `run`).\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\n need to pin a specific version (rare).\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `desc`, `sql`, `sqliteTable`, `text`,\n `integer`, `index`, etc. are all re-exported there). Drop to\n `drizzle-orm` directly only for things not re-exported.\n- Give every route a clear `summary`/`description` and Zod-typed\n request/response so the agent can discover and call it via the\n OpenAPI spec.\n- Page every list endpoint with the helpers `@clawnify/app` exports:\n `request: { query: PageQuery.extend({ /* filters */ }) }`,\n `const { page, limit, offset, search } = pageParams(c.req.valid("query"))`\n (25 per page by default, capped at 100, bad input falls back), and\n `responses: { 200: pagedResponse("items", ItemSchema) }` for\n `{ items, total, page, limit }`. Count with `db.$count(table, where)`.\n- Keep a long text field an agent edits again and again (HTML, a\n document body, a template) as one top-level string of the record,\n with GET and a *partial* update (`PATCH`, or a PUT that keeps the\n fields it is not sent) on the same path, returning the updated\n record. Agents then read it in parts and change it with literal\n `old_text` \u2192 `new_text` edits instead of sending all of it back; the\n platform provides that, so don\'t build a find/replace endpoint.\n- Type a helper that takes the database client as `DB<typeof schema>`\n (from `@clawnify/db`), and a separate routes file\'s env as `AppEnv`\n (from `@clawnify/app`). Never name the backend (`D1Database`,\n `DrizzleD1Database`) or cast `getDB`\'s result: the same app code is\n served by more than one database backend.\n- Test locally with `npx clawnify@latest dev` before deploying; deploys go live at\n `https://<slug>.apps.clawnify.com` (the dashboard\'s preview pane shows\n the draft tier).\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\n README for the current API + version notes.\n\n## Schema-as-data exception\n\nApps that let END users define data shapes at runtime (CMS, no-code\ntable editor) can\'t model their schema in `schema.ts` \u2014 the table\ndefinitions live in rows. Those apps fall back to the raw SQL API\nfrom `@clawnify/db` (`query`, `get`, `run`, `json`). Open-cms is\nthe canonical example.\n\nIf you\'re building this kind of app, you still use Drizzle\'s\n`schema.ts` for the **registry** tables (content types, field\ndefinitions). Only the dynamically-spawned per-collection tables\nneed raw SQL. See open-cms\'s `src/server/schema-sync.ts` for the\nruntime DDL pattern.\n\n## When you\'re stuck: compare with a working app\n\nEvery `Open*` repo under [github.com/clawnify](https://github.com/clawnify)\nis a complete, open-source app running on this platform. When your\napp hits an error you can\'t resolve from this document, find one that\ndoes the same thing and compare how it does it.\n\n- **Pick the repo by what it uses.** Each repo\'s `clawnify.json`\n declares it: `app.credentials` lists its integrations (`metaads`,\n `googleads`, ...), `app.database` and `app.storage` say whether it\n uses D1 and R2. The README says what the app does.\n- **Read it without signing in.** List the repos at\n `https://api.github.com/orgs/clawnify/repos?per_page=100`, and fetch\n any file at `https://raw.githubusercontent.com/clawnify/<repo>/HEAD/<path>`\n (`HEAD` resolves the default branch, which is not always `main`).\n- **Copy the solution, not the layout.** This document wins on\n conventions. Many templates predate parts of it: most hand-write\n `src/server/schema.sql` instead of `schema.ts`, some use Preact, and\n older ones don\'t page their lists with the `@clawnify/app` helpers.\n- **If the error comes from a `@clawnify/*` package**, read what you\n installed: `node_modules/@clawnify/<pkg>/README.md` and\n `dist/index.d.ts`, which match your version exactly.\n'
|
|
1787
|
+
content: '# Build a Clawnify app\n\nCanonical skill: how to author a Clawnify app end-to-end. Same content\nfor humans reading the docs and for AI coding agents injecting this as\ninstructions during an app build.\n\nIf you\'re an agent: this document is enough context to produce a\nworking app from scratch. Follow it literally. The patterns here\nare exactly what `clawnify init` scaffolds and what the platform\nexpects.\n\n## TL;DR\n\n- **One stack.** Hono + React + Vite + `@hono/zod-openapi` +\n `@clawnify/db` (Drizzle) + `@clawnify/app` (entry, routing,\n identity) + Tailwind v4. Nothing else.\n- **Schema lives in `schema.ts` alone** \u2014 the Drizzle DSL your queries\n compile against. The DDL is generated from it (`pnpm db:generate` \u2192\n `.clawnify/drizzle/*.sql`); never hand-write a `schema.sql` in a\n scaffolded app.\n- **Queries through `getDB`** \u2014 `import { getDB, eq } from\n "@clawnify/db"`. JSON columns auto-serialize.\n- **API routes are `OpenAPIHono` + `createRoute`** \u2014 Zod-validated\n request/response.\n- **`createApp()`** (from `@clawnify/app`) builds the entry \u2014 it returns an\n `OpenAPIHono` with API discovery already mounted (`/api/openapi.json` +\n `/llms.txt`, generated from your live routes). That descriptor *is* the\n tool surface agents discover. Never hand-write those routes.\n- **One import.** `@clawnify/app` re-exports `createRoute`, `z` and\n `OpenAPIHono`, and adds `user` / `orgId` / `caller`. Import from it, not\n from `@clawnify/routes` directly.\n- **`clawnify.json`** declares framework, env, and public routes.\n There is no `api.tools[]` \u2014 the agent discovers and calls your\n endpoints via `/llms.txt` (and the OpenAPI spec).\n- **Identity is injected by the platform** \u2014 read it with `user(c)` /\n `orgId(c)` / `caller(c)` from `@clawnify/app`. Your app never\n authenticates anyone.\n\n## Stack rationale\n\nOne template, one set of decisions. Don\'t deviate unless the user has\nexplicitly asked. `clawnify init` (type `app`) scaffolds either a\n`blank` template (one GET route + a page) or a `crud` template (a\ntable with list/create/update/delete + a form). Both share the exact\nsame stack below.\n\n## File layout\n\n```\nmy-app/\n clawnify.json \u2190 Manifest (validated against /schema/v1/clawnify.json)\n package.json\n tsconfig.json\n vite.config.ts \u2190 @vitejs/plugin-react + @tailwindcss/vite; proxies /api \u2192 :8787\n index.html\n .gitignore\n .clawnify/ \u2190 Managed by the CLI (gitignored) \u2014 never edit\n wrangler.toml \u2190 Generated wrangler config\n drizzle.config.ts \u2190 Generated drizzle config (from clawnify.json + schema.ts)\n drizzle/ \u2190 Generated migration SQL (applied by dev + deploy)\n applied-migrations.json \u2190 Local-apply tracker\n src/\n server/\n index.ts \u2190 OpenAPIHono entry \u2014 mounts routes, serves /api/openapi.json\n routes.ts \u2190 OpenAPIHono + createRoute definitions \u2014 the API surface\n schema.ts \u2190 Drizzle table definitions \u2014 the single source of truth\n worker-env.d.ts \u2190 Cloudflare Workers types reference\n uploads.ts \u2190 R2 helpers (only when storage is enabled)\n client/\n main.tsx \u2190 React mount point\n app.tsx \u2190 Root component (plain fetch against /api/*)\n index.css \u2190 @import "tailwindcss"\n```\n\n## Schema \u2014 `schema.ts` is the single source of truth\n\n`schema.ts` (Drizzle DSL) defines the tables. Do **not** hand-write a\n`schema.sql` in a scaffolded app, and there is no toolchain config to\nmaintain: the drizzle config is a managed artifact the CLI materializes\ninto `.clawnify/` (from `clawnify.json` + the schema path), and the DDL\nis generated from `schema.ts` into `.clawnify/drizzle/*.sql` \u2014 which is\nwhat `clawnify dev` applies locally and the deploy applies to your D1.\n\nThe scaffold\'s starter table (blank template):\n\n```ts\n// src/server/schema.ts\nimport { sqliteTable, text, integer } from "@clawnify/db";\n\nexport const items = sqliteTable("items", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n name: text("name").notNull(),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n});\n```\n\nReal apps are multi-tenant. Every user-facing table carries an\n`org_id`, every query filters by it. JSON columns and indexes use the\nDrizzle DSL re-exported from `@clawnify/db`:\n\n```ts\nimport { sqliteTable, text, integer, index } from "@clawnify/db";\n\nexport const notes = sqliteTable(\n "notes",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n orgId: text("org_id").notNull(), // ALWAYS filter by this in queries\n title: text("title").notNull(),\n body: text("body").notNull().default(""),\n tags: text("tags", { mode: "json" }).$type<string[]>().notNull().default([]),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n },\n (t) => ({\n byOrg: index("notes_by_org").on(t.orgId, t.createdAt),\n }),\n);\n```\n\nRules:\n- JSON columns: `text(col, { mode: "json" }).$type<T>()` \u2014 Drizzle\n serializes on write and parses on read.\n- Multi-tenancy: every user-facing table has `org_id`. Every query\n filters by it. No exceptions.\n- Identifiers: snake_case in SQL, camelCase in TS (Drizzle bridges).\n\n## Generating the DDL \u2014 automatic, or `clawnify db generate`\n\n`clawnify dev` and `clawnify deploy` (local-directory deploys) generate\nthe migration SQL themselves \u2014 editing `schema.ts` and running dev or\ndeploy is the whole workflow. To refresh the SQL explicitly without\neither, run `npx clawnify@latest db generate` (the scaffold\'s\n`pnpm db:generate` is an alias for it). Always invoke the CLI as\n`npx clawnify@latest` \u2014 never a global or pinned install. Deploy refuses a database-enabled app with no DDL,\nso a broken generate fails loudly, not silently.\n\nOne artifact to leave alone: after a successful signed-in deploy the CLI\nsyncs a read-only `schema.sql` snapshot of the DEPLOYED schema into the\napp root. It is generated output for reference/diffing \u2014 never edit it,\nand never treat it as the source of truth (`schema.ts` is).\n\nRules:\n- Deploys are **additive**: new tables and columns are added\n automatically. Destructive changes (dropping or retyping a column) are\n not applied automatically \u2014 do those deliberately, and never drop a\n table with user data unless explicitly asked.\n- Never edit the generated `.clawnify/drizzle/*.sql` by hand \u2014 change\n `schema.ts` and regenerate.\n- A hand-written `schema.sql` at the app root is accepted **only** for\n apps that don\'t use Drizzle at all (e.g. some template repos). A\n scaffolded app never needs one.\n\n## `src/server/index.ts` \u2014 the entry\n\n```ts\nimport { createApp } from "@clawnify/app";\nimport api from "./routes";\n\n// db:false \u2014 this app reads the database per request via getDB(c.env),\n// which needs no init middleware.\nconst app = createApp({ title: "My app", version: "1.0.0", db: false });\n\napp.route("/", api);\n\nexport default app;\n```\n\nThe entry is thin: `createApp()` then mount your routes. `createApp`\nreturns an `OpenAPIHono` with **API discovery already mounted** \u2014 it\nserves both `/api/openapi.json` (generated from your `createRoute`\ndefinitions, with schemas) **and** `/llms.txt` (the same, agent-readable).\nAny `/api/*` route written as a plain `app.get` with no `createRoute` is\nstill listed from the live route table, so the endpoint inventory is\nalways complete. **Never hand-write a `/openapi.json` or `/llms.txt`\nhandler** \u2014 and don\'t call `mountDiscovery` yourself; `createApp` did it.\n\nWhen storage (file uploads) is enabled, the entry also wires the R2\nbucket in a middleware before mounting routes:\n\n```ts\nimport { createApp, type AppEnv } from "@clawnify/app";\nimport { initUploads } from "./uploads";\nimport api from "./routes";\n\ntype Env = AppEnv & { Bindings: { UPLOADS: R2Bucket } };\n\nconst app = createApp<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.use("*", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route("/", api);\n\nexport default app;\n```\n\n## `src/server/routes.ts` \u2014 routes with `createRoute`\n\nEach endpoint is a `createRoute({ method, path, summary, request, responses })`\ndefinition paired with a handler via `api.openapi(route, handler)`.\nRequest bodies and params are Zod-validated (`c.req.valid("json")`,\n`c.req.valid("param")`); response shapes are declared with\n`.openapi("Name")` Zod schemas so they land in the generated spec.\n\nBlank template \u2014 one read route:\n\n```ts\nimport { OpenAPIHono, createRoute, z, PageQuery, pageParams, pagedResponse, type AppEnv } from "@clawnify/app";\nimport { getDB, desc, like } from "@clawnify/db";\nimport * as schema from "./schema";\n\nconst api = new OpenAPIHono<AppEnv>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n // Every list endpoint pages: an agent reads this API through one tool,\n // and an unbounded list would land in its context whole.\n request: { query: PageQuery },\n responses: { 200: pagedResponse("items", ItemSchema) },\n }),\n async (c) => {\n const { page, limit, offset, search } = pageParams(c.req.valid("query"));\n const db = getDB(c.env, { schema });\n const where = search ? like(schema.items.name, "%" + search + "%") : undefined;\n const total = await db.$count(schema.items, where);\n const items = await db\n .select()\n .from(schema.items)\n .where(where)\n .orderBy(desc(schema.items.createdAt))\n .limit(limit)\n .offset(offset);\n return c.json({ items, total, page, limit }, 200);\n },\n);\n\nexport default api;\n```\n\nCRUD template \u2014 the full list/create/update/delete surface:\n\n```ts\nimport { OpenAPIHono, createRoute, z, PageQuery, pageParams, pagedResponse, type AppEnv } from "@clawnify/app";\nimport { getDB, eq, desc, like } from "@clawnify/db";\nimport * as schema from "./schema";\n\nconst api = new OpenAPIHono<AppEnv>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi("UpdateItem");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n // Every list endpoint pages: an agent reads this API through one tool,\n // and an unbounded list would land in its context whole.\n request: { query: PageQuery },\n responses: { 200: pagedResponse("items", ItemSchema) },\n }),\n async (c) => {\n const { page, limit, offset, search } = pageParams(c.req.valid("query"));\n const db = getDB(c.env, { schema });\n const where = search ? like(schema.items.title, "%" + search + "%") : undefined;\n const total = await db.$count(schema.items, where);\n const items = await db\n .select()\n .from(schema.items)\n .where(where)\n .orderBy(desc(schema.items.createdAt))\n .limit(limit)\n .offset(offset);\n return c.json({ items, total, page, limit }, 200);\n },\n);\n\napi.openapi(\n createRoute({\n method: "post",\n path: "/api/items",\n summary: "Create item",\n request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: "Created item",\n content: { "application/json": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid("json");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: "patch",\n path: "/api/items/:id",\n summary: "Update item",\n request: {\n params: IdParamSchema,\n body: { content: { "application/json": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },\n 400: { description: "Nothing to update", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const body = c.req.valid("json");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: "delete",\n path: "/api/items/:id",\n summary: "Delete item",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n```\n\nPatterns to follow:\n- **Give every route a clear `summary`/`description`.** The generated\n OpenAPI spec is what the agent reads to decide which endpoint to\n call \u2014 a vague summary makes your endpoint invisible in practice.\n- **Validate input with Zod** via `request.body` / `request.params`\n and read it with `c.req.valid("json")` / `c.req.valid("param")`.\n Never parse `c.req.raw` by hand.\n- **Declare response shapes** with `.openapi("Name")` schemas \u2014 they\n become the documented return type in the spec.\n- **Filter by the org** on every user-facing query (see "who is\n calling" below). No exceptions.\n\n## `src/server` \u2014 who is calling\n\nThe platform authenticates every caller at its perimeter and injects a\nverified identity onto the request (it strips any client-supplied\nversion first, so it can\'t be spoofed). Your app never authenticates\nanyone: no `Authorization`, no cookies, no JWT, no login screen.\n\nRead it with the helpers from `@clawnify/app` \u2014 don\'t parse headers\nyourself:\n\n```ts\nimport { user, orgId, caller } from "@clawnify/app";\n\napp.get("/api/notes", async (c) => {\n const org = orgId(c);\n if (!org) return c.json({ error: "unauthorized" }, 401);\n\n const db = getDB(c.env, { schema });\n return c.json(\n await db.select().from(schema.notes).where(eq(schema.notes.orgId, org)),\n );\n});\n```\n\n| Helper | Returns |\n|--------|---------|\n| `orgId(c)` | Organization UUID \u2014 the tenant key. Filter every user-facing query by it. |\n| `user(c)` | `{ id, email, name, avatarUrl, firstName, lastName }` \u2014 or **`null`** when the caller isn\'t a person. |\n| `caller(c)` | `user`, `api`, `agent`, `agent-browser`, `public`, `bypass`, `system`, or `app`. |\n| `hasRole(c, min)` | Whether the caller may do a task meant for `min` (`member` < `admin` < `owner`). Use it to gate admin-only tasks. Needs `@clawnify/app` 0.4.5 or later. |\n| `role(c)` | `owner`, `admin` or `member` on Team plans and up; **`null`** below that, where every member is treated the same. For display, not for gating. |\n\nTwo rules that catch people out:\n\n- **`user(c)` is null for five of the eight caller kinds**\n (`agent-browser`, `public`, `bypass`, `system`, `app`). Always handle\n the null case \u2014 don\'t assume a person is present just because a\n request arrived. For per-user rows, store `user(c).id` in a `user_id`\n column and filter on it, exactly as you filter on `org_id`.\n- **`firstName` / `lastName` are a heuristic** split of a single stored\n full name (first word / the rest). Fine for a greeting; never persist\n them or treat them as someone\'s legal name \u2014 store `name`.\n\nDon\'t build app-level users, roles, or permissions. Authorization\nalready happened at the perimeter. For a task meant for admins, use\n`hasRole(c, "admin")`: it checks the role where the plan has role tiers\nand lets every person through where it does not, so one check works on\nevery plan. It fails closed: a caller with no person behind it, or a\nrequest with no identity at all (local `pnpm dev`), passes no check, so a\ngated endpoint answering 403 there is the gate working. Don\'t loosen a\ngate to make a test pass. Never gate on `role(c)` by hand.\n\n## `src/client` \u2014 React + plain fetch\n\nThe client mounts React and talks to the API with plain `fetch`\nagainst the `/api/*` routes. No data-layer library is scaffolded.\n\n```tsx\n// src/client/main.tsx\nimport { StrictMode } from "react";\nimport { createRoot } from "react-dom/client";\nimport { App } from "./app";\nimport "./index.css";\n\ncreateRoot(document.getElementById("app")!).render(\n <StrictMode>\n <App />\n </StrictMode>\n);\n```\n\n```tsx\n// src/client/app.tsx (CRUD template shape)\nimport { useState, useEffect } from "react";\n\ninterface Item {\n id: number;\n title: string;\n status: string;\n createdAt: string;\n}\n\nexport function App() {\n const [items, setItems] = useState<Item[]>([]);\n const [title, setTitle] = useState("");\n\n async function load() {\n const res = await fetch("/api/items");\n setItems(((await res.json()) as { items: Item[] }).items);\n }\n\n useEffect(() => { load(); }, []);\n\n async function addItem(e: React.FormEvent) {\n e.preventDefault();\n if (!title.trim()) return;\n await fetch("/api/items", {\n method: "POST",\n headers: { "Content-Type": "application/json" },\n body: JSON.stringify({ title }),\n });\n setTitle("");\n load();\n }\n\n // ...toggleStatus / deleteItem call PATCH/DELETE the same way.\n\n return (\n <div className="max-w-xl mx-auto mt-10 px-4">\n {/* form + list */}\n </div>\n );\n}\n```\n\nIn local dev, Vite proxies `/api` to the Worker on `:8787` (see\n`vite.config.ts`), so the same relative fetch paths work in dev and\nin production. The API is the one contract: the UI calls it over\n`fetch`, and the agent calls it over the OpenAPI spec.\n\n## Design\n\nIf the project contains a `DESIGN.md`, it is the single source of\ntruth for visuals \u2014 follow its tokens, don\'t restyle around it. The\nscaffold ships Tailwind v4 (via `@tailwindcss/vite`, imported with\n`@import "tailwindcss";` in `index.css`) and nothing else \u2014 no\ncomponent library. The rules every Clawnify app follows:\n\n- **Neutral chrome.** White canvas and surfaces, one text ramp\n (foreground \u2192 muted \u2192 faint), hairline borders. Color is for\n meaning, not decoration.\n- **One primary CTA per screen.** Blue is reserved for links and\n focus rings; never a second accent.\n- **Status colors are muted pairs** \u2014 never pure-saturated fills.\n- **Style with Tailwind utilities.** Don\'t install another component\n library or write a bespoke CSS system unless the user asks.\n- **Sizes in rem**, so browser zoom and font settings are respected.\n\n## `clawnify.json` \u2014 the manifest\n\n```json\n{\n "$schema": "https://app.clawnify.com/schema/v1/clawnify.json",\n "version": 1,\n "name": "Notes",\n "description": "Take and organize notes. Searchable by tag.",\n "app": {\n "framework": "react+hono",\n "database": true,\n "storage": false\n },\n "env": {\n "optional": ["OPENROUTER_API_KEY"]\n },\n "api": {\n "public_routes": [\n { "path": "/api/feed", "methods": ["GET"] }\n ]\n }\n}\n```\n\n`clawnify init` writes the minimal form:\n`{ app: { framework: "react+hono", database: true, storage } }`. Add\nthe rest as needed.\n\nIf the app talks to third-party services the user has connected\n(ads platforms, CRMs, messaging), declare them:\n\n```json\n{ "app": { "credentials": ["metaads", "googleads"] } }\n```\n\nGet the ids and names from `clawnify connections list` \u2014 see the\nnaming rule below.\n\n`env` supports `required` (deploy warns if missing), `optional`\n(injected when available), and `oneOf` (at least one per group).\n\nRules:\n- **There is no `api.tools[]`.** The manifest\'s `api` object only\n accepts `public_routes` and `automation_bypass`. Your API surface\n is discovered from the generated OpenAPI spec, not a hand-authored\n tools list (see the next section).\n- **Public routes are the exception**, not the default. Every route\n is behind the Clawnify perimeter (auth-required) unless you\n explicitly add a matching path to `api.public_routes`. Use only for\n webhooks, RSS, embedded feeds.\n- **`framework: "react+hono"`** for new apps. Never `preact+hono` or\n `vite-preact` \u2014 those are legacy.\n- **`database: true`** if the app uses a DB. `schema.ts` defines the\n tables; run `pnpm db:generate` after changing it.\n\n## How the agent reaches your API (no `api.tools[]`)\n\nThe old tRPC stack emitted an `api.tools[]` array from procedure meta.\nThat mechanism is gone. Today the flow is:\n\n1. Your `createRoute` definitions auto-generate a live OpenAPI 3.0 spec\n plus a lean `/llms.txt` index, both served for you \u2014 never hand-write\n or route them yourself. **These are the agent\'s discovery channel:**\n it reads `GET /llms.txt` (index of every endpoint) or\n `GET /api/openapi.json` (full request/response schemas) on the live\n app. Because both are generated from the live route table, they\n cannot drift from the code.\n2. The agent then drives your endpoints on the live app. A Clawnify\n agent uses `clawnify_call_app_api`; Claude, ChatGPT and other MCP\n clients use `clawnify_app_api_read` (GET), `clawnify_app_api_write`\n (POST, PUT, PATCH) and `clawnify_app_api_delete`. No per-app MCP\n registration and no manifest tools array. Use source reading to\n *modify* code, not to discover endpoints.\n\nSo you make an endpoint "agent-callable" by defining it with\n`createRoute()` + `app.openapi()` and giving it a clear\n`summary`/`description` with Zod-typed request/response. The clearer\nthose are, the more reliably the agent uses it.\n\n### `agent.md` \u2014 lead with the procedure, not the endpoint list\n\n`agent.md` is extracted into `agent_instructions` on every build. Since\ndiscovery is already covered by the generated surfaces above, **`agent.md`\nis not an API reference** \u2014 re-listing every payload there just creates a\nsecond source of truth that goes stale the first time a route changes.\nIt is the one place for what generation can\'t produce: **judgment**.\n\nWrite it in this order:\n\n1. **Division of labour, first and short.** What the agent should do\n itself vs. what it must delegate to the app \u2014 and say the wrong move\n out loud (*"never look up contact details yourself; post the records\n and let the app resolve them"*). This one block prevents more misuse\n than the rest of the file combined.\n2. **The procedure** \u2014 numbered steps for the app\'s main job, written so\n the agent can follow them on a request it has never seen.\n3. **Pages**, flagging the screenshot-friendly ones.\n4. **API anchors, not API docs** \u2014 method, path, and *when to reach for\n it*, plus the one or two request shapes the agent writes most often.\n For anything else, let it read `/llms.txt`.\n5. **How to read failures**, and any **cost discipline** \u2014 which calls\n spend the user\'s money and which are free.\n\n**Don\'t ship a per-app skill.** A skill\'s frontmatter stays resident in\nagent context, so one skill per app grows the agent\'s context floor as\nthe app count grows; `agent_instructions` and `/llms.txt` are pulled on\ndemand instead. Skills are for **cross-app** procedures \u2014 if one earns\nreuse across more than one app, promote that single procedure\n(parameterized) to the shared skills library rather than copying it into\nevery app.\n\n## Connections & secrets \u2014 `@clawnify/connections`\n\n**The naming rule \u2014 never invent an identifier.** Before declaring\n`credentials` or env names, run `clawnify connections list`: it shows\nthe org\'s canonical integration ids (`googleads`, never `google_ads`),\nthe fixed provider-key names (`OPENROUTER_API_KEY`, never\n`OPENROUTER_KEY`), and custom env vars already defined \u2014 each with\nconnected/set state. Reuse those exact identifiers; a misspelled one\ndoesn\'t fail the build, it silently resolves to nothing at runtime. If\nyou need a custom secret that isn\'t listed, pick a clear name and tell\nthe user to set it in the dashboard.\n\nIf the app needs a third-party service or a provider API key, use\nthe `@clawnify/connections` SDK. Never read credential bindings\ndirectly, never paste API keys, never hardcode a token or endpoint.\n\n```ts\nimport { connect, secret, describe, searchActions } from "@clawnify/connections";\n\n// A connected integration:\nconst meta = connect("metaads", env);\nconst accounts = await meta.adAccounts("name,currency");\n\n// A provider key the user supplied (null if absent):\nconst key = secret("OPENROUTER_API_KEY", env);\n\n// What\'s wired vs missing \u2014 drive your setup/empty state from this:\nconst status = await describe(env, undefined, REQUIRES);\n```\n\nHow to call a connected service \u2014 the mistake that silently breaks\nintegration apps, so get it right:\n\n- **Prefer the typed client\'s semantic methods** where they exist\n (`meta.adAccounts(...)`, `googleads.query(gaql)`).\n- **For anything else, discover and run an action:**\n ```ts\n const [best] = await searchActions("list google ads campaigns", env);\n const data = await connect(best.service, env).run(best.slug, body);\n ```\n- Some integrations also expose a raw REST client\n (`connect("bird", env).get("/path")`) \u2014 but if `.get()`/`.post()`\n throws for a service, that service only supports semantic methods\n and `run()`. When unsure, use `run()`.\n- **Need exact paths/arguments for a raw-REST provider?** Some carry\n a `spec_url` (the provider\'s published OpenAPI spec) \u2014\n `clawnify connections list --json` shows it. Save the spec to a file\n and query the file, for example `jq \'.paths | keys\' spec.json`; never\n read a whole spec into context (they run to 10+ MB).\n- **Never fall back to raw `fetch`** against a provider API, and\n never invent endpoints or guess tokens.\n\n**The one exception \u2014 a service we don\'t support at all.** If a\nprovider isn\'t in the connections registry (nothing to `connect()`\nto, and `clawnify connections list` doesn\'t show it), the sanctioned\npath *is* a raw call with a user-supplied key: declare the key(s) it\nneeds in `clawnify.json` `env` (`required`/`optional`/`oneOf`), tell\nthe user to set them in the dashboard, read them with\n`secret("THAT_KEY", env)`, and `fetch` the provider\'s documented\nendpoints directly. This is the escape hatch for the long tail of\nintegrations we don\'t model yet \u2014 it does **not** apply to a service\nwe *do* support (use `connect()` / `run()` for those, always). Keep\nthe endpoint and token server-side, never in the client bundle.\n\nBuild a `describe()`-driven setup state instead of assuming\nconnections exist \u2014 show the user what\'s missing and where to\nconnect it.\n\n## Scheduling & deferred work \u2014 the managed queue\n\nA deployed app **cannot bind Cloudflare Queues, Durable Objects, or cron\ntriggers** (the platform builds every app with a fixed binding set: `DB` +\n`ASSETS` + `UPLOADS`). To run work later \u2014 a scheduled publish, a reminder, a\nretry, a "do this in 10 minutes" \u2014 use the **Clawnify managed queue service**\nover HTTP. It owns the clock, retries, and at-least-once delivery, then calls an\nendpoint on *your own app* back at the scheduled time.\n\nUse the published `@clawnify/queue` package \u2014 `enqueueJob`, `cancelJob`,\n`verifyDelivery` \u2014 same shape as `@clawnify/db` / `@clawnify/connections`.\nAuth is the build-injected `env.CLAWNIFY_TOKEN`; with no token (local dev)\nit degrades to a no-op.\n\n**Enqueue** a deferred call to your own endpoint:\n\n```ts\nimport { enqueueJob, cancelJob, verifyDelivery } from "@clawnify/queue";\n\nconst job = await enqueueJob(env, {\n targetUrl: `${origin}/api/internal/publish`, // an endpoint on THIS app\n payload: { post_id: id }, // echoed back to you on fire\n runAt: new Date(whenMs),\n idempotencyKey: `post:${id}:${whenMs}`, // same key dedupes; new time = new job\n});\n// job.id: store it to cancel or reschedule\n```\n\nPersist `job.id` on the row (e.g. `posts.queue_job_id`). **Cancel / reschedule**:\n`await cancelJob(env, jobId)`; reschedule = cancel + a fresh enqueue.\n\n**The callback endpoint is a public, signature-verified route.** The queue calls\n`target_url` from outside the perimeter, so the endpoint must be declared in\n`clawnify.json` `public_routes` **and** verify the delivery signature itself \u2014\nthe signature *is* its auth (never trust an unsigned call):\n\n```jsonc\n// clawnify.json\n"api": { "public_routes": [ { "path": "/api/internal/publish", "methods": ["POST"] } ] }\n```\n\nDeliveries are signed with the platform\'s **ECDSA P-256 (ES256)** key,\nStripe-style over `${timestamp}.${rawBody}`, verified against\n`https://services.clawnify.com/.well-known/jwks.json` (public key \u2014 nothing\nbreaks on token rotation). Read the raw body, check the signature + a timestamp\ntolerance (~5 min) before doing anything:\n\n```ts\napp.post("/api/internal/publish", async (c) => {\n const raw = await c.req.text();\n const ok = await verifyDelivery(raw, {\n signature: c.req.header("x-queue-signature"),\n timestamp: c.req.header("x-queue-timestamp"),\n keyId: c.req.header("x-queue-key-id"),\n });\n if (!ok) return c.json({ error: "bad signature" }, 401);\n const { post_id } = JSON.parse(raw);\n // \u2026do the deferred work (short: it\'s one normal Worker invocation)\u2026\n return c.json({ ok: true });\n});\n```\n\nEach fire is a normal Worker request \u2014 size the work to one invocation (publish a\npost, send a digest). For long compute *now* (not deferred), hold the request\nopen and return when done; don\'t fire-and-forget past the response.\n\n**When the queue says no.** A refused enqueue answers `{ "error", "detail" }`\n(`enqueueJob` throws `ClawnifyQueueError` with `code`, `status` and `message`).\nPast the plan\'s monthly included jobs each job costs credits, so only an empty\nbalance (`402 insufficient_credits`) or no active plan (`403 quota_exceeded`)\nrefuses one; show its `detail` to the owner as it is, since it says where to fix\nit. A job that books the next one (a daily sync) must never swallow that\nrefusal: keep it, show it as a banner on the app\'s main page, and return it from\nthe app\'s status endpoint. Every service error code:\nhttps://docs.clawnify.com/concepts/service-errors\n\n## Migrations\n\nThe workflow is:\n\n1. Edit `src/server/schema.ts` for the new shape (types + queries).\n2. Run `pnpm db:generate` \u2014 emits the migration SQL under\n `.clawnify/drizzle/`.\n3. Run `npx clawnify@latest dev` locally, then `npx clawnify@latest deploy`.\n\nOn deploy your schema changes are applied to the app\'s database \u2014 new\ntables and columns are added automatically.\n\nDestructive changes (drop column, rename) are not applied automatically;\ndo them deliberately, and only when the user explicitly asks. Renames\nare risky on production data \u2014 prefer "add new column, backfill, switch\nqueries, drop old column" over a single-step rename.\n\n## What the agent must NOT do\n\n- Author a `/openapi.json` or `/llms.txt` handler by hand. `createApp()`\n mounts both, generated from your `createRoute` definitions.\n- Hand-write a `schema.sql`, edit anything under `.clawnify/`, or add a\n root `drizzle.config.ts`. Schema changes happen in `schema.ts`; the\n CLI generates and applies the SQL.\n- Invent an `api.tools[]` array in the manifest. It isn\'t a valid\n field \u2014 the OpenAPI spec is the tool surface.\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\n via Drizzle. The raw SQL API has `json()` as a helper.\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\n leak is the worst-class bug we can ship.\n- Return a whole table from a list endpoint, or a bare array. Every list\n pages: `PageQuery`, `pageParams` and `pagedResponse` from `@clawnify/app`.\n- Read auth from `Authorization` / cookies / `Bearer` tokens, or\n hand-parse `X-Clawnify-*` headers. Use `user(c)` / `orgId(c)` /\n `caller(c)` from `@clawnify/app`.\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\n through `@clawnify/connections` (`connect` / `secret` / `run`).\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\n need to pin a specific version (rare).\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `desc`, `sql`, `sqliteTable`, `text`,\n `integer`, `index`, etc. are all re-exported there). Drop to\n `drizzle-orm` directly only for things not re-exported.\n- Give every route a clear `summary`/`description` and Zod-typed\n request/response so the agent can discover and call it via the\n OpenAPI spec.\n- Page every list endpoint with the helpers `@clawnify/app` exports:\n `request: { query: PageQuery.extend({ /* filters */ }) }`,\n `const { page, limit, offset, search } = pageParams(c.req.valid("query"))`\n (25 per page by default, capped at 100, bad input falls back), and\n `responses: { 200: pagedResponse("items", ItemSchema) }` for\n `{ items, total, page, limit }`. Count with `db.$count(table, where)`.\n- Keep a long text field an agent edits again and again (HTML, a\n document body, a template) as one top-level string of the record,\n with GET and a *partial* update (`PATCH`, or a PUT that keeps the\n fields it is not sent) on the same path, returning the updated\n record. Agents then read it in parts and change it with literal\n `old_text` \u2192 `new_text` edits instead of sending all of it back; the\n platform provides that, so don\'t build a find/replace endpoint.\n- Type a helper that takes the database client as `DB<typeof schema>`\n (from `@clawnify/db`), and a separate routes file\'s env as `AppEnv`\n (from `@clawnify/app`). Never name the backend (`D1Database`,\n `DrizzleD1Database`) or cast `getDB`\'s result: the same app code is\n served by more than one database backend.\n- Test locally with `npx clawnify@latest dev` before deploying; deploys go live at\n `https://<slug>.apps.clawnify.com` (the dashboard\'s preview pane shows\n the draft tier).\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\n README for the current API + version notes.\n\n## Schema-as-data exception\n\nApps that let END users define data shapes at runtime (CMS, no-code\ntable editor) can\'t model their schema in `schema.ts` \u2014 the table\ndefinitions live in rows. Those apps fall back to the raw SQL API\nfrom `@clawnify/db` (`query`, `get`, `run`, `json`). Open-cms is\nthe canonical example.\n\nIf you\'re building this kind of app, you still use Drizzle\'s\n`schema.ts` for the **registry** tables (content types, field\ndefinitions). Only the dynamically-spawned per-collection tables\nneed raw SQL. See open-cms\'s `src/server/schema-sync.ts` for the\nruntime DDL pattern.\n\n## When you\'re stuck: compare with a working app\n\nEvery `Open*` repo under [github.com/clawnify](https://github.com/clawnify)\nis a complete, open-source app running on this platform. When your\napp hits an error you can\'t resolve from this document, find one that\ndoes the same thing and compare how it does it.\n\n- **Pick the repo by what it uses.** Each repo\'s `clawnify.json`\n declares it: `app.credentials` lists its integrations (`metaads`,\n `googleads`, ...), `app.database` and `app.storage` say whether it\n uses D1 and R2. The README says what the app does.\n- **Read it without signing in.** List the repos at\n `https://api.github.com/orgs/clawnify/repos?per_page=100`, and fetch\n any file at `https://raw.githubusercontent.com/clawnify/<repo>/HEAD/<path>`\n (`HEAD` resolves the default branch, which is not always `main`).\n- **Copy the solution, not the layout.** This document wins on\n conventions. Many templates predate parts of it: most hand-write\n `src/server/schema.sql` instead of `schema.ts`, some use Preact, and\n older ones don\'t page their lists with the `@clawnify/app` helpers.\n- **If the error comes from a `@clawnify/*` package**, read what you\n installed: `node_modules/@clawnify/<pkg>/README.md` and\n `dist/index.d.ts`, which match your version exactly.\n'
|
|
1786
1788
|
},
|
|
1787
1789
|
{
|
|
1788
1790
|
name: "build-a-clawnify-website",
|
|
1789
|
-
description: "Build and ship a Clawnify website (Astro on Cloudflare Workers): the built-in form system (never hand-roll a form), images and assets, and the deploy flow (live, or a draft when the chat has one open). Use when creating or editing a Clawnify website, or when a site needs a contact/waitlist/signup form.",
|
|
1791
|
+
description: '"Build and ship a Clawnify website (Astro on Cloudflare Workers): the built-in form system (never hand-roll a form), images and assets, and the deploy flow (live, or a draft when the chat has one open). Use when creating or editing a Clawnify website, or when a site needs a contact/waitlist/signup form."',
|
|
1790
1792
|
content: "# Build a Clawnify website\n\nA Clawnify website is an **Astro** project deployed to Cloudflare Workers. One\nsite per organization. You write pages; the platform owns hosting, forms and\nthe publish flow.\n\n```bash\nnpx clawnify@latest init --type website --name \"My Site\" website\ncd website && pnpm install && pnpm dev # http://localhost:4321\n```\n\nAlways invoke the CLI as `npx clawnify@latest <command>` \u2014 never a\nglobal or pinned install; stale CLIs miss deploy guards and fixes.\n\n```\nwebsite/\n src/pages/ # one .astro file per route (index.astro \u2192 /)\n src/layouts/ # shared shell: nav, footer, <head>\n src/blocks/ # platform blocks you've adopted (see Forms below)\n public/ # images, favicons \u2014 served as-is from /\n```\n\n## Forms: use the built-in system. Do not build your own.\n\n**This is the single most common mistake.** A site needs a contact or waitlist\nform, and the obvious move is to write a `<form>` and POST it somewhere \u2014 your\nown endpoint, a third-party form service, or the platform's submit URL with the\nwebsite id pasted in. All three are wrong, and the last one looks right enough\nto survive review.\n\nClawnify has a form system. It captures submissions, stores them, can email you,\nand can hand each one to an agent or a flow. You get all of it by using the\n**Forms block** rather than writing a form yourself.\n\n### How it works\n\n- The submit target is **computed at render time** from `WEBSITE_ID` \u2014 a\n variable the platform bakes into your site's Worker \u2014 plus the form's id:\n\n ```astro\n const env = (Astro.locals as { runtime?: { env?: Record<string, string> } })?.runtime?.env;\n const websiteId = env?.WEBSITE_ID ?? \"\";\n const action = websiteId ? `https://provision.clawnify.com/forms/submit/${websiteId}/${formId}` : \"\";\n ```\n\n **Never hardcode the website id.** It is baked per Worker so a site can only\n ever submit to itself \u2014 hardcoding throws that away, and the literal goes\n stale the moment the site is recreated. An empty `action` in local `astro dev`\n is expected: there are no Worker vars locally, so the form simply no-ops.\n\n- The submit script POSTs JSON with `Content-Type: text/plain;charset=UTF-8`.\n That is not a typo \u2014 `text/plain` is CORS-safelisted, so the request needs no\n preflight, which matters because the platform can't know your site's origin in\n advance. The route parses the text body as JSON.\n\n- **Keep the Turnstile widget.** The ingest rejects a submission with no token,\n so a form without the widget fails every time with \"Verification required\".\n The sitekey shipped in the block is public and pairs with the platform's\n secret; the widget will not validate on `localhost`, only on a real hostname.\n\n### Getting the block\n\nSites are seeded with the platform's block library at creation. If yours has\n`src/blocks/Forms/Contact.astro`, import it and go. If it doesn't \u2014 an older\nsite, or one scaffolded bare by the CLI \u2014 copy it in from the website template\nand adapt it.\n\n**The design is yours; the plumbing is not.** Restyle the markup, labels and\nclasses freely. Preserve, exactly:\n\n- the computed `action` (never a prop, never a literal),\n- the Turnstile widget,\n- the `data-clawnify-managed-form` attribute,\n- `export const schema`,\n- destructuring only known props \u2014 never splat leftover props onto `<form>`,\n or an injected `action` becomes a way to point your form at someone else.\n\nThere is no submit script to copy. The runtime lives in the framework catch-all\n(`src/pages/[...path].astro`) and binds every `data-clawnify-managed-form` on\nthe page. If the block you inherited still has its own inline `<script>` and a\n`data-clawnify-form` attribute, it is the older shape: it still works, and you\ncan migrate it by deleting the script and renaming the attribute. Do not carry\nboth attributes on one form, and do not add `data-clawnify-form` to a managed\nform: older blocks bind that selector unconditionally, so the form would submit\ntwice.\n\n### After a successful submit\n\nTwo options, and the default is unchanged.\n\n- **Inline message** (default). The `successText` prop, rendered into the\n status line.\n- **Redirect.** Set the `successUrl` prop, or `data-success-url` on any form\n you hand-built. A site-relative path (`/thanks`) or an absolute `https://`\n URL (a booking page is fine). Anything else is ignored and the message is\n shown instead, which is what keeps `javascript:` out of the navigation.\n\nA redirect to a thank-you page is also the only way to count a form conversion\nin the analytics tool, which has no custom events: the dashboard Submissions\npanel counts submissions, but a pageview is what gives you a rate.\n\nNeed a side effect on success, like setting a cookie? Listen for the\n`clawnify:form-success` event on the form. It is cancelable, so\n`preventDefault()` suppresses the redirect if you would rather navigate\nyourself.\n\n### Fields\n\nThe stock block collects **name, email and message**. Two ways to go beyond\nthat, and the right one depends on whether your form is registered:\n\n- **Registered forms** (a tree node named `Forms/Contact`) are schema-locked:\n the ingest 422s any field it doesn't expect. Give extra inputs **no `name`\n attribute** and have the submit script fold them into `message`.\n- **Unregistered forms** \u2014 hand-built pages like this one \u2014 are not locked, so\n extra fields post as themselves and are stored verbatim in the payload. Better\n data, but if the site later moves onto the tree renderer, registration will\n start rejecting them. Leave a comment saying so.\n\n### PDF attachments\n\nThe Contact block can collect one PDF per submission (job applications, RFQs).\nOff by default \u2014 enable it with the block's `attachment` prop (and optionally\n`attachmentLabel`), then **publish**: the file field is registered at publish\ntime, and the ingest rejects files on forms that haven't registered one. Rules\nthe platform enforces server-side (don't fight them client-side): PDF only,\nverified by content not by extension, max 10 MB. The submission's payload\ncarries the filename and a download link that only the site's own organization\ncan open \u2014 the file is never on a public URL. When a file is attached the\nsubmit script posts `multipart/form-data` instead of JSON; both are\npreflight-free, and the block already handles the switch.\n\n### Where submissions go\n\nEvery submission is stored and visible in the dashboard. From there it can\nnotify an email address, or fan out to an agent or a flow \u2014 which is how a\nsignup becomes a CRM record or a WhatsApp message without you writing a backend.\nSet the notification address in the dashboard, not in the site.\n\n## Images and assets\n\nPut them in `public/` and reference them with an absolute path (`/img/hero.jpg`).\nThey're served as static files. Pull in real assets at real resolution rather\nthan linking someone else's CDN from your markup.\n\n## Deploying: live, unless the chat has a draft open\n\n```bash\nnpx clawnify@latest deploy # \u2192 the LIVE site\n```\n\nA deploy (or a push to the workspace repo) goes live. The exception: when the\nsite has unpublished changes made from the dashboard chat, the deploy joins\nthem on the DRAFT site, visible only to your org, and **Publish to live** in the\ndashboard ships both. The CLI says which happened; pass it on to the user.\n\n## Pinning the org\n\nEvery command resolves which organization it targets, folder-first. In a linked\nfolder you get it for free; otherwise pass `--org`. If you work across several\norganizations, pass `--org` explicitly on anything that writes \u2014 the global\nactive org is shared machine-wide and another session can change it under you.\n"
|
|
1791
1793
|
},
|
|
1792
1794
|
{
|
|
1793
1795
|
name: "use-the-clawnify-cli",
|
|
1794
1796
|
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.",
|
|
1795
|
-
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 \u2014 skip `login`.** The person running the pipeline sets\n`CLAWNIFY_TOKEN` to a Clawnify sign-in token in that environment's secret\nstore; it wins over any stored session and reads/writes no files.\n`CLAWNIFY_ORG_ID` (or a per-command `--org`) pins the org. Never read, copy or\nprint credential files such as `~/.clawnify/auth.json` yourself: if there is no\nsession and no `CLAWNIFY_TOKEN`, ask the person to run `clawnify login`.\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 (permanent: ask the person first)\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\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, eu)\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:** reading (`list`, `skills`, `sessions`, `pull`, `read`) is fine on\nyour own. Anything that changes a live agent or app (`agents push`,\n`agents create`, `grant-skill`, `env set`, `flows create|edit|publish`,\n`rm`) needs the person's OK first: show them what will change. `agents create`\nand `env set` also restart the gateway. Connecting an integration (OAuth) and\nhanding over a secret or API key are the person's alone: explain the dashboard\nsteps; never fake them.\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`. It changes how those coding agents behave in this project, so\nrun it only when the person asks, in their own project, after telling them\nwhat it will add. 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 # read anything the commands don't show\n```\n\n`clawnify api <path>` makes an authenticated request to a Clawnify API path,\nwith the same auth and org scoping as every other command (it can only do what\nthe signed-in person can). Use it to read what the commands don't show. For a\nchange, use the dedicated command; if none exists, show the person the exact\nrequest (`-X POST|PUT|DELETE -d '{\u2026}'`) and get their OK before sending it.\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"
|
|
1797
|
+
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,\n `npm run dev` and `npm run deploy`, delegate to the CLI too. With pnpm\n write `pnpm run deploy`: bare `pnpm deploy` is pnpm's own command and\n never reaches the script.)\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 \u2014 skip `login`.** The person running the pipeline sets\n`CLAWNIFY_TOKEN` to a Clawnify sign-in token in that environment's secret\nstore; it wins over any stored session and reads/writes no files.\n`CLAWNIFY_ORG_ID` (or a per-command `--org`) pins the org. Never read, copy or\nprint credential files such as `~/.clawnify/auth.json` yourself: if there is no\nsession and no `CLAWNIFY_TOKEN`, ask the person to run `clawnify login`.\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 (permanent: ask the person first)\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\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, eu)\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:** reading (`list`, `skills`, `sessions`, `pull`, `read`) is fine on\nyour own. Anything that changes a live agent or app (`agents push`,\n`agents create`, `grant-skill`, `env set`, `flows create|edit|publish`,\n`rm`) needs the person's OK first: show them what will change. `agents create`\nand `env set` also restart the gateway. Connecting an integration (OAuth) and\nhanding over a secret or API key are the person's alone: explain the dashboard\nsteps; never fake them.\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`. It changes how those coding agents behave in this project, so\nrun it only when the person asks, in their own project, after telling them\nwhat it will add. 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 # read anything the commands don't show\n```\n\n`clawnify api <path>` makes an authenticated request to a Clawnify API path,\nwith the same auth and org scoping as every other command (it can only do what\nthe signed-in person can). Use it to read what the commands don't show. For a\nchange, use the dedicated command; if none exists, show the person the exact\nrequest (`-X POST|PUT|DELETE -d '{\u2026}'`) and get their OK before sending it.\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"
|
|
1796
1798
|
},
|
|
1797
1799
|
{
|
|
1798
1800
|
name: "fix-a-clawnify-agent",
|
|
@@ -2205,13 +2207,26 @@ Done \u2014 removed ${removed} item${removed === 1 ? "" : "s"}.`);
|
|
|
2205
2207
|
}
|
|
2206
2208
|
|
|
2207
2209
|
// src/commands/init.ts
|
|
2210
|
+
var EXIT_USAGE2 = 64;
|
|
2208
2211
|
function ask2(question) {
|
|
2209
2212
|
const rl = readline4.createInterface({
|
|
2210
2213
|
input: process.stdin,
|
|
2211
2214
|
output: process.stdout
|
|
2212
2215
|
});
|
|
2213
2216
|
return new Promise((resolve) => {
|
|
2217
|
+
let answered = false;
|
|
2218
|
+
rl.on("close", () => {
|
|
2219
|
+
if (answered) return;
|
|
2220
|
+
console.error(
|
|
2221
|
+
`
|
|
2222
|
+
No answer to "${question.trim()}": there is no terminal to ask in.
|
|
2223
|
+
Pass --yes for the defaults, or the answers as flags (clawnify init --help).
|
|
2224
|
+
`
|
|
2225
|
+
);
|
|
2226
|
+
process.exit(EXIT_USAGE2);
|
|
2227
|
+
});
|
|
2214
2228
|
rl.question(question, (answer) => {
|
|
2229
|
+
answered = true;
|
|
2215
2230
|
rl.close();
|
|
2216
2231
|
resolve(answer.trim());
|
|
2217
2232
|
});
|
|
@@ -2220,6 +2235,59 @@ function ask2(question) {
|
|
|
2220
2235
|
function slugify(name) {
|
|
2221
2236
|
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
|
|
2222
2237
|
}
|
|
2238
|
+
var STARTER_ENTRIES = /* @__PURE__ */ new Set([
|
|
2239
|
+
".git",
|
|
2240
|
+
".gitkeep",
|
|
2241
|
+
".gitignore",
|
|
2242
|
+
".gitattributes",
|
|
2243
|
+
".DS_Store",
|
|
2244
|
+
"README.md",
|
|
2245
|
+
"LICENSE",
|
|
2246
|
+
".claude",
|
|
2247
|
+
".claude.json",
|
|
2248
|
+
"CLAUDE.md",
|
|
2249
|
+
".cursor",
|
|
2250
|
+
".cursorrules",
|
|
2251
|
+
".codex",
|
|
2252
|
+
"AGENTS.md",
|
|
2253
|
+
"CONVENTIONS.md",
|
|
2254
|
+
".aider.conf.yml",
|
|
2255
|
+
".mcp.json",
|
|
2256
|
+
".vscode",
|
|
2257
|
+
".idea"
|
|
2258
|
+
]);
|
|
2259
|
+
function isStarterFolder(dir) {
|
|
2260
|
+
return !fs5.existsSync(dir) || fs5.readdirSync(dir).every((entry) => STARTER_ENTRIES.has(entry));
|
|
2261
|
+
}
|
|
2262
|
+
function defaultTargetDir(wsSubdir, slug) {
|
|
2263
|
+
const ws = findWorkspaceRoot(process.cwd());
|
|
2264
|
+
if (ws) return wsSubdir(ws.dir);
|
|
2265
|
+
return isStarterFolder(process.cwd()) ? process.cwd() : path5.resolve(slug);
|
|
2266
|
+
}
|
|
2267
|
+
function refuseUnlessStarterFolder(dir) {
|
|
2268
|
+
if (!isStarterFolder(dir)) {
|
|
2269
|
+
console.error(`Directory ${dir} is not empty.`);
|
|
2270
|
+
process.exit(1);
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
function writeGitignore(dir, content) {
|
|
2274
|
+
const file = path5.join(dir, ".gitignore");
|
|
2275
|
+
if (!fs5.existsSync(file)) return write(dir, ".gitignore", content);
|
|
2276
|
+
const existing = fs5.readFileSync(file, "utf8");
|
|
2277
|
+
const have = new Set(existing.split("\n").map((line) => line.trim()));
|
|
2278
|
+
const missing = content.split("\n").filter((line) => line.trim() && !have.has(line.trim()));
|
|
2279
|
+
if (missing.length === 0) return;
|
|
2280
|
+
fs5.writeFileSync(file, `${existing.replace(/\n?$/, "\n")}${missing.join("\n")}
|
|
2281
|
+
`);
|
|
2282
|
+
}
|
|
2283
|
+
var CLI = (command) => `npx --yes clawnify@latest ${command}`;
|
|
2284
|
+
function printGetStarted(targetDir, lines) {
|
|
2285
|
+
const rel = path5.relative(process.cwd(), targetDir);
|
|
2286
|
+
console.log(" Get started:");
|
|
2287
|
+
if (rel) console.log(` cd ${/\s/.test(rel) ? JSON.stringify(rel) : rel}`);
|
|
2288
|
+
for (const line of lines) console.log(` ${line}`);
|
|
2289
|
+
console.log();
|
|
2290
|
+
}
|
|
2223
2291
|
async function askProjectType(opts) {
|
|
2224
2292
|
if (opts?.type === "app" || opts?.type === "website" || opts?.type === "agent") {
|
|
2225
2293
|
return opts.type;
|
|
@@ -2248,6 +2316,7 @@ function detectPackageManager() {
|
|
|
2248
2316
|
return "npm";
|
|
2249
2317
|
}
|
|
2250
2318
|
async function initCommand(dir, opts) {
|
|
2319
|
+
assertNodeVersion();
|
|
2251
2320
|
const type = await askProjectType(opts);
|
|
2252
2321
|
if (type === "website") {
|
|
2253
2322
|
return initWebsite(dir, opts);
|
|
@@ -2259,16 +2328,11 @@ async function initCommand(dir, opts) {
|
|
|
2259
2328
|
}
|
|
2260
2329
|
async function initApp(dir, opts) {
|
|
2261
2330
|
const yes = !!opts?.yes;
|
|
2262
|
-
const
|
|
2331
|
+
const inPlace = !dir && !findWorkspaceRoot(process.cwd()) && isStarterFolder(process.cwd());
|
|
2332
|
+
const dirArgName = dir ? path5.basename(path5.resolve(dir)) : inPlace ? path5.basename(process.cwd()) : void 0;
|
|
2263
2333
|
const name = opts?.name || (yes ? dirArgName ?? "my-app" : await ask2("App name: ") || "my-app");
|
|
2264
2334
|
const slug = slugify(name);
|
|
2265
|
-
|
|
2266
|
-
if (dir) {
|
|
2267
|
-
targetDir = path5.resolve(dir);
|
|
2268
|
-
} else {
|
|
2269
|
-
const ws = findWorkspaceRoot(process.cwd());
|
|
2270
|
-
targetDir = ws ? path5.join(ws.dir, "apps", slug) : path5.resolve(slug);
|
|
2271
|
-
}
|
|
2335
|
+
const targetDir = dir ? path5.resolve(dir) : defaultTargetDir((ws) => path5.join(ws, "apps", slug), slug);
|
|
2272
2336
|
let template;
|
|
2273
2337
|
if (opts?.template) {
|
|
2274
2338
|
template = opts.template === "crud" ? "crud" : "blank";
|
|
@@ -2283,10 +2347,7 @@ async function initApp(dir, opts) {
|
|
|
2283
2347
|
const templateChoice = await ask2("Template [1]: ") || "1";
|
|
2284
2348
|
template = templateChoice === "2" ? "crud" : "blank";
|
|
2285
2349
|
}
|
|
2286
|
-
|
|
2287
|
-
console.error(`Directory ${targetDir} is not empty.`);
|
|
2288
|
-
process.exit(1);
|
|
2289
|
-
}
|
|
2350
|
+
refuseUnlessStarterFolder(targetDir);
|
|
2290
2351
|
fs5.mkdirSync(path5.join(targetDir, "src/server"), { recursive: true });
|
|
2291
2352
|
fs5.mkdirSync(path5.join(targetDir, "src/client"), { recursive: true });
|
|
2292
2353
|
let storage;
|
|
@@ -2313,10 +2374,6 @@ async function initApp(dir, opts) {
|
|
|
2313
2374
|
"@types/react": "^19.0.0",
|
|
2314
2375
|
"@types/react-dom": "^19.0.0",
|
|
2315
2376
|
"@vitejs/plugin-react": "^4.0.0",
|
|
2316
|
-
// Floor must be a PUBLISHED version at scaffold time — an unpublished
|
|
2317
|
-
// pin fails the whole install (and with it drizzle-kit, vite, …).
|
|
2318
|
-
// Caret picks up newer releases automatically.
|
|
2319
|
-
clawnify: "^0.16.1",
|
|
2320
2377
|
"drizzle-kit": "^0.31.0",
|
|
2321
2378
|
tailwindcss: "^4.0.0",
|
|
2322
2379
|
// `vite build` only transpiles — it never typechecks — so without this the
|
|
@@ -2330,16 +2387,21 @@ async function initApp(dir, opts) {
|
|
|
2330
2387
|
private: true,
|
|
2331
2388
|
type: "module",
|
|
2332
2389
|
scripts: {
|
|
2333
|
-
|
|
2390
|
+
// The CLI is not a dependency: scripts run the newest release, the same
|
|
2391
|
+
// `npx clawnify@latest` the agent docs use. A devDependency froze it:
|
|
2392
|
+
// a caret on 0.x never crosses a minor, so `^0.16.1` kept
|
|
2393
|
+
// `npm run deploy` on 0.16.3 while npm had 0.22, and the website
|
|
2394
|
+
// scaffold's `^0.1.15` on 0.1.17.
|
|
2395
|
+
dev: CLI("dev"),
|
|
2334
2396
|
build: "vite build",
|
|
2335
2397
|
// Referenced by the generated schema.ts comment and the starter UI, and
|
|
2336
2398
|
// run implicitly by `clawnify deploy`. It must exist as a script or
|
|
2337
2399
|
// following the app's own instructions fails with "Missing script".
|
|
2338
2400
|
// Delegates to the CLI, which materializes the managed drizzle config
|
|
2339
2401
|
// in .clawnify/ before invoking drizzle-kit (lib/drizzle.ts).
|
|
2340
|
-
"db:generate": "
|
|
2402
|
+
"db:generate": CLI("db generate"),
|
|
2341
2403
|
typecheck: "tsc --noEmit",
|
|
2342
|
-
deploy: "
|
|
2404
|
+
deploy: CLI("deploy")
|
|
2343
2405
|
},
|
|
2344
2406
|
dependencies: {
|
|
2345
2407
|
"@clawnify/app": "^0.4.3",
|
|
@@ -2403,7 +2465,7 @@ export default defineConfig({
|
|
|
2403
2465
|
</body>
|
|
2404
2466
|
</html>
|
|
2405
2467
|
`);
|
|
2406
|
-
|
|
2468
|
+
writeGitignore(targetDir, `node_modules
|
|
2407
2469
|
dist
|
|
2408
2470
|
.wrangler
|
|
2409
2471
|
.clawnify
|
|
@@ -2584,34 +2646,20 @@ createRoot(document.getElementById("app")!).render(
|
|
|
2584
2646
|
}
|
|
2585
2647
|
const pm = detectPackageManager();
|
|
2586
2648
|
console.log();
|
|
2587
|
-
console.log(` Created ${name} in ${path5.relative(process.cwd(), targetDir)}/`);
|
|
2588
|
-
console.log();
|
|
2589
|
-
console.log(" Get started:");
|
|
2590
|
-
console.log(` cd ${path5.relative(process.cwd(), targetDir)}`);
|
|
2591
|
-
console.log(` ${pm} install`);
|
|
2592
|
-
console.log(` ${pm} ${pm === "npm" ? "run " : ""}dev # local dev at http://localhost:5173`);
|
|
2593
|
-
console.log(` ${pm} ${pm === "npm" ? "run " : ""}deploy # deploy to production`);
|
|
2649
|
+
console.log(` Created ${name} in ${path5.relative(process.cwd(), targetDir) || "."}/`);
|
|
2594
2650
|
console.log();
|
|
2651
|
+
printGetStarted(targetDir, [
|
|
2652
|
+
`${pm} install`,
|
|
2653
|
+
`${pm} run dev # local dev at http://localhost:5173`,
|
|
2654
|
+
`${pm} run deploy # deploy to production`
|
|
2655
|
+
]);
|
|
2595
2656
|
}
|
|
2596
2657
|
async function initWebsite(dir, opts) {
|
|
2597
2658
|
const name = opts?.name || await ask2("Site name: ") || "my-site";
|
|
2598
2659
|
const slug = slugify(name);
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
} else {
|
|
2603
|
-
const ws = findWorkspaceRoot(process.cwd());
|
|
2604
|
-
targetDir = ws ? path5.join(ws.dir, "website") : path5.resolve(slug);
|
|
2605
|
-
}
|
|
2606
|
-
if (fs5.existsSync(targetDir)) {
|
|
2607
|
-
const entries = fs5.readdirSync(targetDir);
|
|
2608
|
-
const onlyGitkeep = entries.length === 1 && entries[0] === ".gitkeep";
|
|
2609
|
-
if (entries.length > 0 && !onlyGitkeep) {
|
|
2610
|
-
console.error(`Directory ${targetDir} is not empty.`);
|
|
2611
|
-
process.exit(1);
|
|
2612
|
-
}
|
|
2613
|
-
if (onlyGitkeep) fs5.rmSync(path5.join(targetDir, ".gitkeep"));
|
|
2614
|
-
}
|
|
2660
|
+
const targetDir = dir ? path5.resolve(dir) : defaultTargetDir((ws) => path5.join(ws, "website"), slug);
|
|
2661
|
+
refuseUnlessStarterFolder(targetDir);
|
|
2662
|
+
fs5.rmSync(path5.join(targetDir, ".gitkeep"), { force: true });
|
|
2615
2663
|
fs5.mkdirSync(targetDir, { recursive: true });
|
|
2616
2664
|
write(targetDir, "clawnify.json", JSON.stringify({
|
|
2617
2665
|
$schema: "https://app.clawnify.com/schema/v1/clawnify.json",
|
|
@@ -2628,7 +2676,7 @@ async function initWebsite(dir, opts) {
|
|
|
2628
2676
|
dev: "astro dev",
|
|
2629
2677
|
build: "astro build",
|
|
2630
2678
|
preview: "astro preview",
|
|
2631
|
-
deploy: "
|
|
2679
|
+
deploy: CLI("deploy")
|
|
2632
2680
|
},
|
|
2633
2681
|
dependencies: {
|
|
2634
2682
|
"@astrojs/cloudflare": "^12.0.0",
|
|
@@ -2637,7 +2685,6 @@ async function initWebsite(dir, opts) {
|
|
|
2637
2685
|
tailwindcss: "^4.0.0"
|
|
2638
2686
|
},
|
|
2639
2687
|
devDependencies: {
|
|
2640
|
-
clawnify: "^0.1.15",
|
|
2641
2688
|
"wrangler": "^4.0.0"
|
|
2642
2689
|
},
|
|
2643
2690
|
engines: { node: ">=22" }
|
|
@@ -2659,7 +2706,7 @@ export default defineConfig({
|
|
|
2659
2706
|
},
|
|
2660
2707
|
});
|
|
2661
2708
|
`);
|
|
2662
|
-
|
|
2709
|
+
writeGitignore(targetDir, `node_modules
|
|
2663
2710
|
dist
|
|
2664
2711
|
.astro
|
|
2665
2712
|
.wrangler
|
|
@@ -2721,15 +2768,15 @@ import BaseLayout from "../layouts/BaseLayout.astro";
|
|
|
2721
2768
|
</main>
|
|
2722
2769
|
</BaseLayout>
|
|
2723
2770
|
`);
|
|
2771
|
+
const pm = detectPackageManager();
|
|
2724
2772
|
console.log();
|
|
2725
|
-
console.log(` Created ${name} in ${path5.relative(process.cwd(), targetDir)}/`);
|
|
2726
|
-
console.log();
|
|
2727
|
-
console.log(" Get started:");
|
|
2728
|
-
console.log(` cd ${path5.relative(process.cwd(), targetDir)}`);
|
|
2729
|
-
console.log(" pnpm install");
|
|
2730
|
-
console.log(" pnpm dev # local dev at http://localhost:4321");
|
|
2731
|
-
console.log(" pnpm deploy # deploy as your org's website");
|
|
2773
|
+
console.log(` Created ${name} in ${path5.relative(process.cwd(), targetDir) || "."}/`);
|
|
2732
2774
|
console.log();
|
|
2775
|
+
printGetStarted(targetDir, [
|
|
2776
|
+
`${pm} install`,
|
|
2777
|
+
`${pm} run dev # local dev at http://localhost:4321`,
|
|
2778
|
+
`${pm} run deploy # deploy as your org's website`
|
|
2779
|
+
]);
|
|
2733
2780
|
}
|
|
2734
2781
|
async function initAgent(dir, opts) {
|
|
2735
2782
|
const yes = !!opts?.yes;
|
|
@@ -2861,7 +2908,7 @@ export default api;
|
|
|
2861
2908
|
<span className="font-medium text-slate-900">Evolve the schema.</span> Edit <code>src/server/schema.ts</code>, then run <code>pnpm db:generate</code>.
|
|
2862
2909
|
</li>
|
|
2863
2910
|
<li className="rounded-lg border border-slate-200 bg-white px-4 py-3">
|
|
2864
|
-
<span className="font-medium text-slate-900">Deploy.</span> Run <code>
|
|
2911
|
+
<span className="font-medium text-slate-900">Deploy.</span> Run <code>npm run deploy</code> to push live.
|
|
2865
2912
|
</li>
|
|
2866
2913
|
</ul>
|
|
2867
2914
|
|
|
@@ -3137,23 +3184,8 @@ bucket_name = "${slug}-uploads"
|
|
|
3137
3184
|
}
|
|
3138
3185
|
return toml;
|
|
3139
3186
|
}
|
|
3140
|
-
function assertNodeVersion2() {
|
|
3141
|
-
const [major] = process.versions.node.split(".").map(Number);
|
|
3142
|
-
if (major < 22) {
|
|
3143
|
-
console.error(
|
|
3144
|
-
`
|
|
3145
|
-
Clawnify requires Node.js v22 or later.
|
|
3146
|
-
You are using v${process.versions.node}.
|
|
3147
|
-
|
|
3148
|
-
Install a newer version: https://nodejs.org
|
|
3149
|
-
Or use a version manager: nvm use 22
|
|
3150
|
-
`
|
|
3151
|
-
);
|
|
3152
|
-
process.exit(1);
|
|
3153
|
-
}
|
|
3154
|
-
}
|
|
3155
3187
|
async function devCommand(dir, options) {
|
|
3156
|
-
|
|
3188
|
+
assertNodeVersion();
|
|
3157
3189
|
const resolvedDir = dir ? path6.resolve(dir) : process.cwd();
|
|
3158
3190
|
const manifest = readManifest(resolvedDir);
|
|
3159
3191
|
if (!manifest) {
|
|
@@ -4400,20 +4432,30 @@ async function workspaceStatusCommand(opts) {
|
|
|
4400
4432
|
const token = await getValidToken();
|
|
4401
4433
|
if (!token) {
|
|
4402
4434
|
if (opts?.json) {
|
|
4403
|
-
console.log(JSON.stringify({
|
|
4404
|
-
|
|
4435
|
+
console.log(JSON.stringify({
|
|
4436
|
+
logged_in: false,
|
|
4437
|
+
next: "clawnify init --type app --yes && npm install && clawnify deploy",
|
|
4438
|
+
existing_org: "clawnify login"
|
|
4439
|
+
}));
|
|
4440
|
+
return;
|
|
4405
4441
|
}
|
|
4406
|
-
console.log(`Not
|
|
4442
|
+
console.log(`Not signed in. You can still build and deploy now.
|
|
4407
4443
|
|
|
4408
|
-
|
|
4409
|
-
complete it headlessly. Ask the user to run:
|
|
4444
|
+
New project, in an empty folder:
|
|
4410
4445
|
|
|
4411
|
-
npx clawnify@latest
|
|
4446
|
+
npx clawnify@latest init --type app --name "<app name>" --yes
|
|
4447
|
+
npm install
|
|
4448
|
+
npx clawnify@latest deploy
|
|
4412
4449
|
|
|
4413
|
-
|
|
4450
|
+
(A website: \`init --type website\` instead.) Signed out, \`deploy\` puts it
|
|
4451
|
+
in a temporary private workspace and prints a private preview link and a
|
|
4452
|
+
claim link to give your user.
|
|
4414
4453
|
|
|
4415
|
-
|
|
4416
|
-
|
|
4454
|
+
Working in an organization the user already belongs to? \`clawnify login\`
|
|
4455
|
+
opens a browser for Google sign-in, which a coding agent cannot complete.
|
|
4456
|
+
Ask the user to run \`npx clawnify@latest login\`, then re-run
|
|
4457
|
+
\`clawnify workspace\`.`);
|
|
4458
|
+
return;
|
|
4417
4459
|
}
|
|
4418
4460
|
const orgId = await resolveOrgContext();
|
|
4419
4461
|
const res = await api.get("/v1/workspace", orgId ? { orgId } : void 0);
|
package/dist/index.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
4
|
if (process.argv.includes("--mcp")) {
|
|
5
|
-
const { startMcpServer } = await import("./mcp-
|
|
5
|
+
const { startMcpServer } = await import("./mcp-CDTYBBFD.js");
|
|
6
6
|
await startMcpServer();
|
|
7
7
|
} else {
|
|
8
|
-
const { runCli } = await import("./cli-
|
|
8
|
+
const { runCli } = await import("./cli-SZGZGXY7.js");
|
|
9
9
|
await runCli();
|
|
10
10
|
}
|