clawnify 0.10.0 → 0.11.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.
- package/dist/{chunk-S2EOEZO7.js → chunk-ORXUA446.js} +254 -116
- package/dist/chunk-ORXUA446.js.map +1 -0
- package/dist/{cli-BBJGGLQP.js → cli-EZU6EZCU.js} +41 -17
- package/dist/cli-EZU6EZCU.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/{mcp-OSFATJGC.js → mcp-UYOTTL53.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-S2EOEZO7.js.map +0 -1
- package/dist/cli-BBJGGLQP.js.map +0 -1
- /package/dist/{mcp-OSFATJGC.js.map → mcp-UYOTTL53.js.map} +0 -0
|
@@ -16,9 +16,10 @@ import {
|
|
|
16
16
|
readManifest,
|
|
17
17
|
readProject,
|
|
18
18
|
readWorkspaceConfig,
|
|
19
|
+
resolveOrgContext,
|
|
19
20
|
saveAuth,
|
|
20
21
|
saveProject
|
|
21
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-ORXUA446.js";
|
|
22
23
|
|
|
23
24
|
// src/cli.ts
|
|
24
25
|
import { Command } from "commander";
|
|
@@ -340,17 +341,17 @@ async function resolveOrgId(options, linkedProject, resolvedDir) {
|
|
|
340
341
|
);
|
|
341
342
|
process.exit(EXIT_USAGE);
|
|
342
343
|
}
|
|
343
|
-
if (linkedProject?.
|
|
344
|
+
if (linkedProject?.org_id && linkedProject.org_id !== match.id) {
|
|
344
345
|
console.error(
|
|
345
|
-
`This
|
|
346
|
+
`This folder is linked to a different org (${linkedProject.org_slug ?? linkedProject.org_id}).
|
|
346
347
|
--org ${options.org} resolves to ${match.id}.
|
|
347
|
-
Re-link
|
|
348
|
+
Re-link with \`clawnify link\`, or deploy from another directory.`
|
|
348
349
|
);
|
|
349
350
|
process.exit(1);
|
|
350
351
|
}
|
|
351
352
|
return match.id;
|
|
352
353
|
}
|
|
353
|
-
if (linkedProject?.
|
|
354
|
+
if (linkedProject?.org_id) {
|
|
354
355
|
return linkedProject.org_id;
|
|
355
356
|
}
|
|
356
357
|
if (resolvedDir) {
|
|
@@ -1264,15 +1265,37 @@ async function openCommand(slug) {
|
|
|
1264
1265
|
|
|
1265
1266
|
// src/commands/whoami.ts
|
|
1266
1267
|
async function whoamiCommand() {
|
|
1268
|
+
const envToken = process.env.CLAWNIFY_TOKEN;
|
|
1267
1269
|
const auth = loadAuth();
|
|
1268
|
-
if (!auth) {
|
|
1270
|
+
if (!auth && !envToken) {
|
|
1269
1271
|
console.log("Not logged in");
|
|
1270
1272
|
return;
|
|
1271
1273
|
}
|
|
1272
|
-
const email = getEmailFromToken(auth.access_token) ?? "unknown";
|
|
1274
|
+
const email = getEmailFromToken(envToken ?? auth.access_token) ?? "unknown";
|
|
1273
1275
|
console.log(`Email: ${email}`);
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
+
const orgId = auth?.org_id ?? process.env.CLAWNIFY_ORG_ID;
|
|
1277
|
+
if (orgId) {
|
|
1278
|
+
console.log(`Org: ${orgId}`);
|
|
1279
|
+
}
|
|
1280
|
+
const token = await getValidToken();
|
|
1281
|
+
if (!token) {
|
|
1282
|
+
console.log("Status: session expired \u2014 run `clawnify login`");
|
|
1283
|
+
process.exitCode = 1;
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
try {
|
|
1287
|
+
const res = await api.request("GET", "/v1/orgs", { token });
|
|
1288
|
+
if (res.ok) {
|
|
1289
|
+
console.log("Status: active");
|
|
1290
|
+
} else if (res.status === 401) {
|
|
1291
|
+
console.log("Status: session expired \u2014 run `clawnify login`");
|
|
1292
|
+
process.exitCode = 1;
|
|
1293
|
+
} else {
|
|
1294
|
+
console.log(`Status: could not verify (HTTP ${res.status})`);
|
|
1295
|
+
process.exitCode = 1;
|
|
1296
|
+
}
|
|
1297
|
+
} catch {
|
|
1298
|
+
console.log("Status: could not reach the server (offline?)");
|
|
1276
1299
|
}
|
|
1277
1300
|
}
|
|
1278
1301
|
|
|
@@ -1318,17 +1341,17 @@ function agentByName(name) {
|
|
|
1318
1341
|
var ALL_AGENTS = DETECTORS.map((d) => d.agent);
|
|
1319
1342
|
|
|
1320
1343
|
// src/lib/skills/content.gen.ts
|
|
1321
|
-
var CLI_VERSION = "0.
|
|
1344
|
+
var CLI_VERSION = "0.11.0";
|
|
1322
1345
|
var BUNDLED_SKILLS = [
|
|
1323
1346
|
{
|
|
1324
1347
|
name: "build-a-clawnify-app",
|
|
1325
1348
|
description: "Author a Clawnify app end-to-end \u2014 the canonical Hono + React + Vite + @hono/zod-openapi + @clawnify/db (Drizzle) stack, schema.ts (typed queries) kept in sync with schema.sql (the DDL the deploy applies), OpenAPIHono routes (createRoute) that auto-generate an OpenAPI spec, and X-Clawnify-* identity headers. Use when building or modifying an app that deploys to the Clawnify platform.",
|
|
1326
|
-
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) + Tailwind v4. Nothing else.\n- **Schema lives in two files kept in sync** \u2014 `schema.ts` (Drizzle\n DSL, the typed view your queries use) and `schema.sql` (the DDL the\n deploy applies to your app\'s D1). Change one, change the other.\n- **Queries through `getDB`** \u2014 `import { getDB, eq } from\n "@clawnify/db"`. JSON columns auto-serialize.\n- **API routes are `OpenAPIHono` + `createRoute`** \u2014 Zod-validated\n request/response. `app.doc()` auto-generates the OpenAPI spec at\n `/api/openapi.json`. That spec *is* the tool surface.\n- **`clawnify.json`** declares framework, env, and public routes.\n There is no `api.tools[]` \u2014 the agent discovers and calls your\n endpoints by reading the live OpenAPI spec.\n- **Identity flows via `X-Clawnify-*` headers** injected by the\n platform. Read them, don\'t fake them.\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 CLI cache (gitignored)\n wrangler.toml \u2190 Generated per-dev wrangler config\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 (typed view for queries)\n schema.sql \u2190 canonical DDL the deploy applies \u2014 keep in sync with schema.ts\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` + `schema.sql`, kept in sync\n\nTwo files describe the same tables. `schema.ts` (Drizzle DSL) is the\ntyped view your queries compile against; `schema.sql` is the DDL the\ndeploy applies to your app\'s D1. **When you change one, update the\nother** \u2014 they must describe the same tables.\n\nThe scaffold\'s starter table (blank template):\n\n```ts\n// src/server/schema.ts\nimport { sqliteTable, text, integer } from "@clawnify/db";\n\nexport const items = sqliteTable("items", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n name: text("name").notNull(),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n});\n```\n\nReal apps are multi-tenant. Every user-facing table carries an\n`org_id`, every query filters by it. JSON columns and indexes use the\nDrizzle DSL re-exported from `@clawnify/db`:\n\n```ts\nimport { sqliteTable, text, integer, index } from "@clawnify/db";\n\nexport const notes = sqliteTable(\n "notes",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n orgId: text("org_id").notNull(), // ALWAYS filter by this in queries\n title: text("title").notNull(),\n body: text("body").notNull().default(""),\n tags: text("tags", { mode: "json" }).$type<string[]>().notNull().default([]),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n },\n (t) => ({\n byOrg: index("notes_by_org").on(t.orgId, t.createdAt),\n }),\n);\n```\n\nRules:\n- JSON columns: `text(col, { mode: "json" }).$type<T>()` \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## `schema.sql` \u2014 the DDL the deploy applies\n\nAlongside `schema.ts`, keep a `schema.sql` describing the same tables.\nThis is the DDL applied to your app\'s database on deploy.\n\n```sql\n-- src/server/schema.sql (mirror of the schema.ts tables)\nCREATE TABLE IF NOT EXISTS notes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n org_id TEXT NOT NULL,\n title TEXT NOT NULL,\n body TEXT NOT NULL DEFAULT \'\',\n tags TEXT NOT NULL DEFAULT \'[]\', -- JSON column\n created_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS notes_by_org ON notes(org_id, created_at);\n```\n\nRules:\n- Always `CREATE TABLE IF NOT EXISTS` \u2014 the apply is additive and\n re-run-safe.\n- Add a new column with `ALTER TABLE <t> ADD COLUMN \u2026` at the **end** of\n `schema.sql`, and reflect it in `schema.ts`. The deploy adds it.\n- Deploys are **additive**: new tables and columns are added\n automatically. Destructive changes (dropping or retyping a column) are\n not applied automatically \u2014 do those deliberately, and never drop a\n table with user data unless explicitly asked.\n- **Never let `schema.ts` and `schema.sql` drift.** Change one, change\n the other \u2014 they must describe the same tables.\n\n## `src/server/index.ts` \u2014 the OpenAPIHono entry\n\n```ts\nimport { OpenAPIHono } from "@hono/zod-openapi";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.route("/", api);\n\napp.doc("/api/openapi.json", {\n openapi: "3.0.0",\n info: { title: "My app", version: "1.0.0" },\n});\n\nexport default app;\n```\n\nThe entry is thin: mount the routes, then `app.doc()` \u2014 that single\ncall generates a live OpenAPI 3.0 spec from your `createRoute`\ndefinitions and serves it at `/api/openapi.json`. You never write a\n`/openapi.json` handler by hand; the framework derives 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 { OpenAPIHono } from "@hono/zod-openapi";\nimport { initUploads } from "./uploads";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.use("*", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route("/", api);\n\napp.doc("/api/openapi.json", {\n openapi: "3.0.0",\n info: { title: "My app", version: "1.0.0" },\n});\n\nexport default app;\n```\n\n## `src/server/routes.ts` \u2014 OpenAPIHono 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 } from "@hono/zod-openapi";\nimport { getDB, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\nexport default api;\n```\n\nCRUD template \u2014 the full list/create/update/delete surface:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";\nimport { getDB, eq, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi("UpdateItem");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\napi.openapi(\n createRoute({\n method: "post",\n path: "/api/items",\n summary: "Create item",\n request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: "Created item",\n content: { "application/json": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid("json");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: "patch",\n path: "/api/items/:id",\n summary: "Update item",\n request: {\n params: IdParamSchema,\n body: { content: { "application/json": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const body = c.req.valid("json");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: "delete",\n path: "/api/items/:id",\n summary: "Delete item",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n```\n\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 identity\n headers below). No exceptions.\n\n## `src/server` \u2014 reading identity headers\n\nThe scaffold\'s starter routes are single-tenant for brevity. Real\napps read the caller\'s identity from the `X-Clawnify-*` headers the\nplatform injects, using Hono\'s `c.req.header(...)` inside the handler:\n\n```ts\nconst orgId = c.req.header("X-Clawnify-Org-Id");\nif (!orgId) return c.json({ error: "unauthorized" }, 401);\nconst db = getDB(c.env, { schema });\nconst rows = await db\n .select()\n .from(schema.notes)\n .where(eq(schema.notes.orgId, orgId));\n```\n\nThe headers the platform injects (never set by the client \u2014 it strips\nclient-supplied versions and reinjects authenticated ones at the\nperimeter):\n\n| Header | Value |\n|--------|-------|\n| `X-Clawnify-User-Id` | Supabase user UUID |\n| `X-Clawnify-Org-Id` | Organization UUID |\n| `X-Clawnify-User-Email` | User email |\n| `X-Clawnify-Caller` | `user`, `agent`, `agent-browser`, or `system` |\n\nTrust these headers. Never read `Authorization`, `Bearer` tokens, or\nsession cookies directly.\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());\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. Ship both `schema.ts`\n (typed) and `schema.sql` (the applied DDL), kept in sync.\n\n## How the agent reaches your API (no `api.tools[]`)\n\nThe old tRPC stack emitted an `api.tools[]` array from procedure meta.\nThat mechanism is gone. Today the flow is:\n\n1. Your `createRoute` definitions + `app.doc("/api/openapi.json", \u2026)`\n auto-generate a live OpenAPI 3.0 spec.\n2. The user\'s agent calls the platform\'s built-in tools \u2014\n `get_app_openapi` (fetch the app\'s OpenAPI JSON) and `call_app_api`\n (invoke a `method` + `path` on the live app) \u2014 to discover and\n drive your endpoints. No per-app MCP registration, no manifest\n tools array.\n\nSo you make an endpoint "agent-callable" simply by shipping it with a\nclear `summary`/`description` and Zod-typed request/response. The\nricher and clearer the spec, the more reliably the agent uses it.\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\nIt\'s a thin seam over a platform primitive, same shape as `@clawnify/db` /\n`@clawnify/connections` (a `@clawnify/queue` package is coming; inline the seam\nuntil then). Auth is the build-injected `env.CLAWNIFY_TOKEN`; with no token\n(local dev) the seam degrades to a no-op.\n\n**Enqueue** a deferred call to your own endpoint:\n\n```ts\n// POST https://services.clawnify.com/queue/enqueue (Bearer CLAWNIFY_TOKEN)\nconst res = await fetch("https://services.clawnify.com/queue/enqueue", {\n method: "POST",\n headers: { Authorization: `Bearer ${env.CLAWNIFY_TOKEN}`, "Content-Type": "application/json" },\n body: JSON.stringify({\n target_url: `${origin}/api/internal/publish`, // an endpoint on THIS app\n payload: { post_id: id }, // echoed back to you on fire\n run_at: new Date(whenMs).toISOString(),\n idempotency_key: `post:${id}:${whenMs}`, // same key dedupes; new time = new job\n }),\n});\nconst { job_id } = await res.json(); // store it to cancel/reschedule\n```\n\nPersist `job_id` on the row (e.g. `posts.queue_job_id`). **Cancel / reschedule**:\n`DELETE https://services.clawnify.com/queue/jobs/{job_id}` (Bearer token);\nreschedule = cancel + a fresh enqueue.\n\n**The callback endpoint is a public, signature-verified route.** The queue calls\n`target_url` from outside the perimeter, so the endpoint must be declared in\n`clawnify.json` `public_routes` **and** verify the delivery signature itself \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-clawnify-signature"),\n timestamp: c.req.header("x-clawnify-timestamp"),\n keyId: c.req.header("x-clawnify-key-id"),\n });\n if (!ok) return c.json({ error: "bad signature" }, 401);\n const { post_id } = JSON.parse(raw);\n // \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## Migrations\n\nKeep `schema.ts` and `schema.sql` in sync by hand. The workflow is:\n\n1. Edit `src/server/schema.ts` for the new shape (types + queries).\n2. Make the matching edit in `src/server/schema.sql` \u2014 a new\n `CREATE TABLE IF NOT EXISTS`, or `ALTER TABLE \u2026 ADD COLUMN \u2026` at the\n **end** of the file for a new column.\n3. Run `clawnify dev` locally, then `clawnify deploy`.\n\nOn deploy your schema changes are applied to the app\'s database \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` handler by hand. `app.doc("/api/openapi.json", \u2026)`\n generates it from your `createRoute` definitions.\n- Let `schema.ts` and `schema.sql` drift. They describe the same\n tables \u2014 change both, every time.\n- Hand-author migration SQL files. Make schema changes in `schema.sql`\n (and mirror them in `schema.ts`); the deploy applies them.\n- Invent an `api.tools[]` array in the manifest. It isn\'t a valid\n field \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- Read auth from `Authorization` / cookies / `Bearer` tokens. Use\n the `X-Clawnify-*` headers via `c.req.header(...)`.\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\n through `@clawnify/connections` (`connect` / `secret` / `run`).\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\n need to pin a specific version (rare).\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `desc`, `sql`, `sqliteTable`, `text`,\n `integer`, `index`, etc. are all re-exported there). Drop to\n `drizzle-orm` directly only for things not re-exported.\n- Give every route a clear `summary`/`description` and Zod-typed\n request/response so the agent can discover and call it via the\n OpenAPI spec.\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\n publishing \u2014 the preview tier catches schema drift and type errors\n at build time.\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\n README for the current API + version notes.\n\n## Schema-as-data exception\n\nApps that let END users define data shapes at runtime (CMS, no-code\ntable editor) can\'t model their schema in `schema.ts` \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'
|
|
1349
|
+
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/routes` + Tailwind v4. Nothing else.\n- **Schema lives in two files kept in sync** \u2014 `schema.ts` (Drizzle\n DSL, the typed view your queries use) and `schema.sql` (the DDL the\n deploy applies to your app\'s D1). Change one, change the other.\n- **Queries through `getDB`** \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- **`mountDiscovery(app)`** (from `@clawnify/routes`) is **required** in\n the entry \u2014 it serves `/api/openapi.json` + `/llms.txt` from your live\n routes. That descriptor *is* the tool surface agents discover.\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 flows via `X-Clawnify-*` headers** injected by the\n platform. Read them, don\'t fake them.\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 CLI cache (gitignored)\n wrangler.toml \u2190 Generated per-dev wrangler config\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 (typed view for queries)\n schema.sql \u2190 canonical DDL the deploy applies \u2014 keep in sync with schema.ts\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` + `schema.sql`, kept in sync\n\nTwo files describe the same tables. `schema.ts` (Drizzle DSL) is the\ntyped view your queries compile against; `schema.sql` is the DDL the\ndeploy applies to your app\'s D1. **When you change one, update the\nother** \u2014 they must describe the same tables.\n\nThe scaffold\'s starter table (blank template):\n\n```ts\n// src/server/schema.ts\nimport { sqliteTable, text, integer } from "@clawnify/db";\n\nexport const items = sqliteTable("items", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n name: text("name").notNull(),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n});\n```\n\nReal apps are multi-tenant. Every user-facing table carries an\n`org_id`, every query filters by it. JSON columns and indexes use the\nDrizzle DSL re-exported from `@clawnify/db`:\n\n```ts\nimport { sqliteTable, text, integer, index } from "@clawnify/db";\n\nexport const notes = sqliteTable(\n "notes",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n orgId: text("org_id").notNull(), // ALWAYS filter by this in queries\n title: text("title").notNull(),\n body: text("body").notNull().default(""),\n tags: text("tags", { mode: "json" }).$type<string[]>().notNull().default([]),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n },\n (t) => ({\n byOrg: index("notes_by_org").on(t.orgId, t.createdAt),\n }),\n);\n```\n\nRules:\n- JSON columns: `text(col, { mode: "json" }).$type<T>()` \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## `schema.sql` \u2014 the DDL the deploy applies\n\nAlongside `schema.ts`, keep a `schema.sql` describing the same tables.\nThis is the DDL applied to your app\'s database on deploy.\n\n```sql\n-- src/server/schema.sql (mirror of the schema.ts tables)\nCREATE TABLE IF NOT EXISTS notes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n org_id TEXT NOT NULL,\n title TEXT NOT NULL,\n body TEXT NOT NULL DEFAULT \'\',\n tags TEXT NOT NULL DEFAULT \'[]\', -- JSON column\n created_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS notes_by_org ON notes(org_id, created_at);\n```\n\nRules:\n- Always `CREATE TABLE IF NOT EXISTS` \u2014 the apply is additive and\n re-run-safe.\n- Add a new column with `ALTER TABLE <t> ADD COLUMN \u2026` at the **end** of\n `schema.sql`, and reflect it in `schema.ts`. The deploy adds it.\n- Deploys are **additive**: new tables and columns are added\n automatically. Destructive changes (dropping or retyping a column) are\n not applied automatically \u2014 do those deliberately, and never drop a\n table with user data unless explicitly asked.\n- **Never let `schema.ts` and `schema.sql` drift.** Change one, change\n the other \u2014 they must describe the same tables.\n\n## `src/server/index.ts` \u2014 the OpenAPIHono entry\n\n```ts\nimport { OpenAPIHono } from "@hono/zod-openapi";\nimport { mountDiscovery } from "@clawnify/routes";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.route("/", api);\n\n// REQUIRED: serves /api/openapi.json + /llms.txt so agents can discover\n// this app\'s API. One call \u2014 never hand-write these routes.\nmountDiscovery(app, { title: "My app", version: "1.0.0" });\n\nexport default app;\n```\n\nThe entry is thin: mount the routes, then `mountDiscovery(app)` \u2014 that\nsingle call (from `@clawnify/routes`) serves both `/api/openapi.json`\n(generated from your `createRoute` definitions, with schemas) **and**\n`/llms.txt` (the same, agent-readable). Any `/api/*` route written as a\nplain `app.get` with no `createRoute` is still listed from the live\nroute table, so the endpoint inventory is always complete.\n**`mountDiscovery(app)` is required in every app** \u2014 never hand-write a\n`/openapi.json` handler.\n\nWhen storage (file uploads) is enabled, the entry also wires the R2\nbucket in a middleware before mounting routes:\n\n```ts\nimport { OpenAPIHono } from "@hono/zod-openapi";\nimport { mountDiscovery } from "@clawnify/routes";\nimport { initUploads } from "./uploads";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.use("*", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route("/", api);\n\nmountDiscovery(app, { title: "My app", version: "1.0.0" });\n\nexport default app;\n```\n\n## `src/server/routes.ts` \u2014 OpenAPIHono 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 } from "@hono/zod-openapi";\nimport { getDB, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\nexport default api;\n```\n\nCRUD template \u2014 the full list/create/update/delete surface:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";\nimport { getDB, eq, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi("UpdateItem");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\napi.openapi(\n createRoute({\n method: "post",\n path: "/api/items",\n summary: "Create item",\n request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: "Created item",\n content: { "application/json": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid("json");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: "patch",\n path: "/api/items/:id",\n summary: "Update item",\n request: {\n params: IdParamSchema,\n body: { content: { "application/json": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const body = c.req.valid("json");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: "delete",\n path: "/api/items/:id",\n summary: "Delete item",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n```\n\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 identity\n headers below). No exceptions.\n\n## `src/server` \u2014 reading identity headers\n\nThe scaffold\'s starter routes are single-tenant for brevity. Real\napps read the caller\'s identity from the `X-Clawnify-*` headers the\nplatform injects, using Hono\'s `c.req.header(...)` inside the handler:\n\n```ts\nconst orgId = c.req.header("X-Clawnify-Org-Id");\nif (!orgId) return c.json({ error: "unauthorized" }, 401);\nconst db = getDB(c.env, { schema });\nconst rows = await db\n .select()\n .from(schema.notes)\n .where(eq(schema.notes.orgId, orgId));\n```\n\nThe headers the platform injects (never set by the client \u2014 it strips\nclient-supplied versions and reinjects authenticated ones at the\nperimeter):\n\n| Header | Value |\n|--------|-------|\n| `X-Clawnify-User-Id` | Supabase user UUID |\n| `X-Clawnify-Org-Id` | Organization UUID |\n| `X-Clawnify-User-Email` | User email |\n| `X-Clawnify-Caller` | `user`, `agent`, `agent-browser`, or `system` |\n\nTrust these headers. Never read `Authorization`, `Bearer` tokens, or\nsession cookies directly.\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());\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. Ship both `schema.ts`\n (typed) and `schema.sql` (the applied DDL), kept in sync.\n\n## How the agent reaches your API (no `api.tools[]`)\n\nThe old tRPC stack emitted an `api.tools[]` array from procedure meta.\nThat mechanism is gone. Today the flow is:\n\n1. Your `createRoute` definitions + `app.doc("/api/openapi.json", \u2026)`\n auto-generate a live OpenAPI 3.0 spec. The platform still reads this\n internally (e.g. `update_app` triage decides whether an existing\n endpoint can serve a request instead of a rebuild), so keep it\n accurate \u2014 but it is **not** the agent\'s discovery channel.\n2. The agent discovers your endpoints from the app\'s **`agent.md`**\n (extracted into `agent_instructions`, returned by `get_app`) and, for\n the exact routes, `get_app_source`. It then drives them with the\n built-in `call_app_api` tool (invoke a `method` + `path` on the live\n app). No per-app MCP registration, no manifest tools array, and no\n raw-OpenAPI tool \u2014 a generated spec is only as complete as its\n annotations, so `agent.md` is the authored contract of record.\n\nSo you make an endpoint "agent-callable" by describing it in `agent.md`\n(what it does, method + path, when to use it) and shipping it with a\nclear `summary`/`description` and Zod-typed request/response. The\nclearer both are, the more reliably the agent uses it.\n\n## Connections & secrets \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\nIt\'s a thin seam over a platform primitive, same shape as `@clawnify/db` /\n`@clawnify/connections` (a `@clawnify/queue` package is coming; inline the seam\nuntil then). Auth is the build-injected `env.CLAWNIFY_TOKEN`; with no token\n(local dev) the seam degrades to a no-op.\n\n**Enqueue** a deferred call to your own endpoint:\n\n```ts\n// POST https://services.clawnify.com/queue/enqueue (Bearer CLAWNIFY_TOKEN)\nconst res = await fetch("https://services.clawnify.com/queue/enqueue", {\n method: "POST",\n headers: { Authorization: `Bearer ${env.CLAWNIFY_TOKEN}`, "Content-Type": "application/json" },\n body: JSON.stringify({\n target_url: `${origin}/api/internal/publish`, // an endpoint on THIS app\n payload: { post_id: id }, // echoed back to you on fire\n run_at: new Date(whenMs).toISOString(),\n idempotency_key: `post:${id}:${whenMs}`, // same key dedupes; new time = new job\n }),\n});\nconst { job_id } = await res.json(); // store it to cancel/reschedule\n```\n\nPersist `job_id` on the row (e.g. `posts.queue_job_id`). **Cancel / reschedule**:\n`DELETE https://services.clawnify.com/queue/jobs/{job_id}` (Bearer token);\nreschedule = cancel + a fresh enqueue.\n\n**The callback endpoint is a public, signature-verified route.** The queue calls\n`target_url` from outside the perimeter, so the endpoint must be declared in\n`clawnify.json` `public_routes` **and** verify the delivery signature itself \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-clawnify-signature"),\n timestamp: c.req.header("x-clawnify-timestamp"),\n keyId: c.req.header("x-clawnify-key-id"),\n });\n if (!ok) return c.json({ error: "bad signature" }, 401);\n const { post_id } = JSON.parse(raw);\n // \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## Migrations\n\nKeep `schema.ts` and `schema.sql` in sync by hand. The workflow is:\n\n1. Edit `src/server/schema.ts` for the new shape (types + queries).\n2. Make the matching edit in `src/server/schema.sql` \u2014 a new\n `CREATE TABLE IF NOT EXISTS`, or `ALTER TABLE \u2026 ADD COLUMN \u2026` at the\n **end** of the file for a new column.\n3. Run `clawnify dev` locally, then `clawnify deploy`.\n\nOn deploy your schema changes are applied to the app\'s database \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` handler by hand. `app.doc("/api/openapi.json", \u2026)`\n generates it from your `createRoute` definitions.\n- Let `schema.ts` and `schema.sql` drift. They describe the same\n tables \u2014 change both, every time.\n- Hand-author migration SQL files. Make schema changes in `schema.sql`\n (and mirror them in `schema.ts`); the deploy applies them.\n- Invent an `api.tools[]` array in the manifest. It isn\'t a valid\n field \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- Read auth from `Authorization` / cookies / `Bearer` tokens. Use\n the `X-Clawnify-*` headers via `c.req.header(...)`.\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\n through `@clawnify/connections` (`connect` / `secret` / `run`).\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\n need to pin a specific version (rare).\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `desc`, `sql`, `sqliteTable`, `text`,\n `integer`, `index`, etc. are all re-exported there). Drop to\n `drizzle-orm` directly only for things not re-exported.\n- Give every route a clear `summary`/`description` and Zod-typed\n request/response so the agent can discover and call it via the\n OpenAPI spec.\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\n publishing \u2014 the preview tier catches schema drift and type errors\n at build time.\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\n README for the current API + version notes.\n\n## Schema-as-data exception\n\nApps that let END users define data shapes at runtime (CMS, no-code\ntable editor) can\'t model their schema in `schema.ts` \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'
|
|
1327
1350
|
},
|
|
1328
1351
|
{
|
|
1329
1352
|
name: "use-the-clawnify-cli",
|
|
1330
1353
|
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.",
|
|
1331
|
-
content: "# Use the Clawnify CLI\n\nCanonical skill: how to drive the `clawnify` CLI. Same content for\nhumans and for AI coding agents operating a terminal.\n\nFor **authoring app code** (stack, schema, tRPC patterns), use the\n`build-a-clawnify-app` skill \u2014 this one covers the tooling around it.\n\n## TL;DR\n\n```bash\nnpm i -g clawnify # or: npx clawnify@latest <command>\nclawnify login # browser sign-in, paste-code fallback\nclawnify init my-app # scaffold an app or website\ncd my-app && clawnify dev\nclawnify deploy # \u2192 https://<slug>.apps.clawnify.com\n```\n\n- **Auth once, org lazily.** `login` only signs you in; the first\n command that needs an organization asks once and remembers it.\n- **A directory links to one app.** `deploy` from a linked directory\n updates that app; `clawnify link <id-or-slug>` adopts an existing one.\n- **Non-interactive flags exist for every prompt** \u2014 use them in\n scripts and CI (`-y`, `--update-existing`, `--create-new`, `--org`).\n\n## Authenticate\n\n```bash\nclawnify login # opens the browser; also prints the sign-in URL\nclawnify whoami # current user, active org (if linked)\n```\n\n`login` works from any browser: if the browser runs on the same\nmachine, sign-in completes automatically; otherwise the page shows a\ncode to paste back at the `Paste code here if prompted >` prompt\n(useful over SSH \u2014 no port forwarding needed).\n\n**Headless / CI / agents \u2014 skip `login` entirely.** Set `CLAWNIFY_TOKEN` (a\nSupabase access token) and it wins over any stored session, reading/writing no\nfiles; `CLAWNIFY_ORG_ID` (or a per-command `--org`) pins the org. This is how a\ncoding agent runs the CLI without a browser.\n\n### Organizations\n\nYou belong to one or more orgs; apps live inside an org.\n\n```bash\nclawnify org list # orgs you belong to (* marks active)\nclawnify org use <slug-or-id> # switch the active org\n```\n\nNo need to pick one up front \u2014 the first org-scoped command prompts\nonce and persists the choice. Any single command can override with\n`--org <slug-or-id>`.\n\n## Create and run locally\n\n```bash\nclawnify init [dir] # interactive: app or website\nclawnify init my-app -y # non-interactive defaults (blank app)\nclawnify init --type app --template crud --name my-app\nclawnify init --type website --name my-site\nclawnify dev [dir] [--port 8787] # local dev server\n```\n\n`init` also installs AI files (rules + skills + MCP config) for any\ncoding agents detected in the project; skip with `--no-ai-files`.\n\n## Deploy\n\n```bash\nclawnify deploy # deploy the current directory\nclawnify deploy path/to/app\nclawnify deploy --from owner/repo # deploy straight from GitHub\nclawnify deploy --from owner/repo --path apps/web # monorepo subdir\nclawnify deploy --dry-run # list files that would upload\n```\n\nFirst deploy creates the app and links the directory (writes a local\nproject file); later deploys update the same app. On a slug conflict\nyou'll be asked \u2014 or decide up front:\n\n```bash\nclawnify deploy -y # reuse/update the existing app\nclawnify deploy --update-existing # same, explicit\nclawnify deploy --create-new # take the suggested new slug\n```\n\nLink an existing deployed app to the current directory instead of\ncreating a new one:\n\n```bash\nclawnify link <app-id-or-slug>\n```\n\n## Inspect and manage deployed apps\n\n```bash\nclawnify ls # list deployed apps in the active org\nclawnify logs <app-id> # build logs\nclawnify open <slug> # open the live app in the browser\nclawnify rm <app-id> # delete an app\nclawnify pull schema --from <app-id-or-slug> # fetch live schema.sql\nclawnify docs [slug] # usage README for an app (org index if omitted)\n```\n\n`pull schema` refuses to clobber local uncommitted changes unless you\npass `--force`.\n\n## Manage agents (the FDE surface)\n\nDrive an org's AI agents from the terminal \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 session data + the box, never a\nGitHub repo). Add `--server <id>` when the org has more than one server.\n\n```bash\nclawnify servers list # the org's servers (an org can have several)\nclawnify agents list # agents on a server (main + specialists)\nclawnify agents skills [agent] # what an agent can ACTUALLY run (not just its workspace)\nclawnify sessions --agent <slug> --json # stored sessions + token counters (contextTokens = bloat)\nclawnify sessions history <key> --json # one session's transcript \u2014 where it veered\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/
|
|
1354
|
+
content: "# Use the Clawnify CLI\n\nCanonical skill: how to drive the `clawnify` CLI. Same content for\nhumans and for AI coding agents operating a terminal.\n\nFor **authoring app code** (stack, schema, tRPC patterns), use the\n`build-a-clawnify-app` skill \u2014 this one covers the tooling around it.\n\n## TL;DR\n\n```bash\nnpm i -g clawnify # or: npx clawnify@latest <command>\nclawnify login # browser sign-in, paste-code fallback\nclawnify init my-app # scaffold an app or website\ncd my-app && clawnify dev\nclawnify deploy # \u2192 https://<slug>.apps.clawnify.com\n```\n\n- **Auth once, org lazily.** `login` only signs you in; the first\n command that needs an organization asks once and remembers it.\n- **A directory links to one app.** `deploy` from a linked directory\n updates that app; `clawnify link <id-or-slug>` adopts an existing one.\n- **Non-interactive flags exist for every prompt** \u2014 use them in\n scripts and CI (`-y`, `--update-existing`, `--create-new`, `--org`).\n\n## Authenticate\n\n```bash\nclawnify login # opens the browser; also prints the sign-in URL\nclawnify whoami # current user, active org (if linked)\n```\n\n`login` works from any browser: if the browser runs on the same\nmachine, sign-in completes automatically; otherwise the page shows a\ncode to paste back at the `Paste code here if prompted >` prompt\n(useful over SSH \u2014 no port forwarding needed).\n\n**Headless / CI / agents \u2014 skip `login` entirely.** Set `CLAWNIFY_TOKEN` (a\nSupabase access token) and it wins over any stored session, reading/writing no\nfiles; `CLAWNIFY_ORG_ID` (or a per-command `--org`) pins the org. This is how a\ncoding agent runs the CLI without a browser.\n\n### Organizations\n\nYou belong to one or more orgs; apps live inside an org.\n\n```bash\nclawnify org list # orgs you belong to (* marks active)\nclawnify org use <slug-or-id> # switch the active org\n```\n\nNo need to pick one up front \u2014 the first org-scoped command prompts\nonce and persists the choice. Any single command can override with\n`--org <slug-or-id>`.\n\n## Create and run locally\n\n```bash\nclawnify init [dir] # interactive: app or website\nclawnify init my-app -y # non-interactive defaults (blank app)\nclawnify init --type app --template crud --name my-app\nclawnify init --type website --name my-site\nclawnify dev [dir] [--port 8787] # local dev server\n```\n\n`init` also installs AI files (rules + skills + MCP config) for any\ncoding agents detected in the project; skip with `--no-ai-files`.\n\n## Deploy\n\n```bash\nclawnify deploy # deploy the current directory\nclawnify deploy path/to/app\nclawnify deploy --from owner/repo # deploy straight from GitHub\nclawnify deploy --from owner/repo --path apps/web # monorepo subdir\nclawnify deploy --dry-run # list files that would upload\n```\n\nFirst deploy creates the app and links the directory (writes a local\nproject file); later deploys update the same app. On a slug conflict\nyou'll be asked \u2014 or decide up front:\n\n```bash\nclawnify deploy -y # reuse/update the existing app\nclawnify deploy --update-existing # same, explicit\nclawnify deploy --create-new # take the suggested new slug\n```\n\nLink an existing deployed app to the current directory instead of\ncreating a new one:\n\n```bash\nclawnify link <app-id-or-slug>\n```\n\n## Inspect and manage deployed apps\n\n```bash\nclawnify ls # list deployed apps in the active org\nclawnify logs <app-id> # build logs\nclawnify open <slug> # open the live app in the browser\nclawnify rm <app-id> # delete an app\nclawnify pull schema --from <app-id-or-slug> # fetch live schema.sql\nclawnify docs [slug] # usage README for an app (org index if omitted)\n```\n\n`pull schema` refuses to clobber local uncommitted changes unless you\npass `--force`.\n\n## Manage agents (the FDE surface)\n\nDrive an org's AI agents from the terminal \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 session data + the box, never a\nGitHub repo). Add `--server <id>` when the org has more than one server.\n\n```bash\nclawnify servers list # the org's servers (an org can have several)\nclawnify agents list # agents on a server (main + specialists)\nclawnify agents skills [agent] # what an agent can ACTUALLY run (not just its workspace)\nclawnify sessions --agent <slug> --json # stored sessions + token counters (contextTokens = bloat)\nclawnify sessions history <key> --json # one session's transcript \u2014 where it veered\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/ to edit (flows/ come with main only \u2014 flows are box-level)\nclawnify agents push [dir] # push edits back (additive; next session, no restart)\nclawnify agents grant-skill <s> --to <a> # share a main-authored skill (or --all for every agent)\nclawnify agents create <slug> --yes # new specialist (RESTARTS the gateway)\nclawnify env set <KEY> <VALUE> # org custom env \u2014 NON-SECRET only (restarts gateway)\nclawnify connections connect <id> # how to connect an integration (dashboard OAuth; you can't)\n```\n\n**Boundary:** everything above is autonomous *except* the human-auth actions \u2014\nconnecting an integration (OAuth) and handing over a secret/API key. For those,\nexplain the dashboard steps; never fake them. `agents create` / `env set`\nrestart the gateway, so confirm before running them on a busy box.\n\n## Connections & env names\n\n```bash\nclawnify connections list # the org's naming catalog (\u25CF connected / \u25CB not)\nclawnify connections connect <id> # how to connect one \u2014 dashboard OAuth; the CLI/agent can't do it for you\n```\n\nLists the active org's integrations (canonical ids + connected state),\nprovider API keys (fixed names + set state), and custom env vars. Read\nit before declaring `credentials` or env names in `clawnify.json` and\nreuse the exact identifiers it shows \u2014 a misspelled id or key name\ndoesn't fail the build, it silently resolves to nothing at runtime.\n\n## Workspaces (one repo, one org's apps)\n\n```bash\nclawnify workspace init [dir] [--org <slug-or-id>]\n```\n\nScaffolds a monorepo bound to an org; apps scaffolded inside land\nunder `apps/` and inherit the org on deploy.\n\n## Wire up coding agents\n\n```bash\nclawnify ai-files install # rules + skills + MCP server in one step\nclawnify skills list # bundled skills\nclawnify skills add <name> # install one into detected agents\nclawnify mcp # stdio MCP bridge (Claude Desktop, etc.)\n```\n\n`ai-files install` detects agent config dirs in the project (Claude\nCode, Cursor, OpenClaw, Codex, Aider) and writes the always-on rules\nblock, installs bundled skills, and adds the Clawnify MCP server to\n`.mcp.json`. Target one agent with `--agent <name>`; undo with\n`clawnify ai-files uninstall`.\n\n## The raw escape hatch\n\n```bash\nclawnify api /servers # any GET\nclawnify api /servers/<id>/agents -X POST -d '{\u2026}' # any method + JSON body\n```\n\n`clawnify api <path>` makes an authenticated request to any Clawnify API path \u2014\nsame auth and org scoping as every other command (it can only do what you can).\nUse it for anything the porcelain doesn't wrap; the curated commands stay small\nbecause this is always there.\n\n## Tips\n\n- `npx clawnify@latest <command>` always runs the newest release.\n- Every org-scoped command accepts `--org` \u2014 prefer it in scripts over\n relying on the saved active org.\n- If sign-in ever fails mid-flow, just run `clawnify login` again; it\n is safe to repeat.\n"
|
|
1332
1355
|
},
|
|
1333
1356
|
{
|
|
1334
1357
|
name: "fix-a-clawnify-agent",
|
|
@@ -2851,6 +2874,7 @@ async function linkCommand(appIdOrSlug, options) {
|
|
|
2851
2874
|
}
|
|
2852
2875
|
saveProject(dir, {
|
|
2853
2876
|
org_id: matched.org.id,
|
|
2877
|
+
org_slug: matched.org.slug,
|
|
2854
2878
|
app_id: matched.app.id,
|
|
2855
2879
|
slug: matched.app.slug,
|
|
2856
2880
|
app_token: matched.app.app_token
|
|
@@ -2941,7 +2965,7 @@ async function orgUseCommand(slugOrId) {
|
|
|
2941
2965
|
console.error("Not logged in. Run `clawnify login` first.");
|
|
2942
2966
|
process.exit(1);
|
|
2943
2967
|
}
|
|
2944
|
-
saveAuth({ ...auth, org_id: match.id });
|
|
2968
|
+
saveAuth({ ...auth, org_id: match.id, org_slug: match.slug });
|
|
2945
2969
|
console.log(` Active org set to ${match.name} (${match.slug})`);
|
|
2946
2970
|
}
|
|
2947
2971
|
|
|
@@ -3167,13 +3191,13 @@ async function callTool(name, args) {
|
|
|
3167
3191
|
process.stderr.write("Not logged in. Run `clawnify login` first.\n");
|
|
3168
3192
|
process.exit(1);
|
|
3169
3193
|
}
|
|
3170
|
-
const auth = loadAuth();
|
|
3171
3194
|
const headers = {
|
|
3172
3195
|
"content-type": "application/json",
|
|
3173
3196
|
authorization: "Bearer " + token
|
|
3174
3197
|
};
|
|
3175
|
-
|
|
3176
|
-
|
|
3198
|
+
const orgId = await resolveOrgContext();
|
|
3199
|
+
if (orgId) {
|
|
3200
|
+
headers["X-Clawnify-Org-Id"] = orgId;
|
|
3177
3201
|
}
|
|
3178
3202
|
const res = await fetch(MCP_URL, {
|
|
3179
3203
|
method: "POST",
|
|
@@ -3520,4 +3544,4 @@ async function runCli() {
|
|
|
3520
3544
|
export {
|
|
3521
3545
|
runCli
|
|
3522
3546
|
};
|
|
3523
|
-
//# sourceMappingURL=cli-
|
|
3547
|
+
//# sourceMappingURL=cli-EZU6EZCU.js.map
|