clawnify 0.16.0 → 0.16.2
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-6NPBW4NU.js → chunk-EW7CPMFC.js} +2 -2
- package/dist/{cli-G6ZBPA6D.js → cli-YR6BKMOT.js} +250 -166
- package/dist/cli-YR6BKMOT.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/{mcp-IA7KEV4T.js → mcp-JCWN7ZYR.js} +2 -2
- package/package.json +1 -1
- package/dist/cli-G6ZBPA6D.js.map +0 -1
- /package/dist/{chunk-6NPBW4NU.js.map → chunk-EW7CPMFC.js.map} +0 -0
- /package/dist/{mcp-IA7KEV4T.js.map → mcp-JCWN7ZYR.js.map} +0 -0
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
resolveOrgContext,
|
|
21
21
|
saveAuth,
|
|
22
22
|
saveProject
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-EW7CPMFC.js";
|
|
24
24
|
|
|
25
25
|
// src/cli.ts
|
|
26
26
|
import { Command, Option } from "commander";
|
|
@@ -175,8 +175,8 @@ async function loginCommand() {
|
|
|
175
175
|
}
|
|
176
176
|
|
|
177
177
|
// src/commands/deploy.ts
|
|
178
|
-
import
|
|
179
|
-
import
|
|
178
|
+
import fs3 from "fs";
|
|
179
|
+
import path3 from "path";
|
|
180
180
|
import readline2 from "readline";
|
|
181
181
|
import { spawn } from "child_process";
|
|
182
182
|
|
|
@@ -194,7 +194,15 @@ function saveAnon(dir, ctx, extra = {}) {
|
|
|
194
194
|
function clearAnon(dir) {
|
|
195
195
|
const existing = readProject(dir);
|
|
196
196
|
if (!existing?.anon) return;
|
|
197
|
-
const {
|
|
197
|
+
const {
|
|
198
|
+
anon: _anon,
|
|
199
|
+
app_id: _a,
|
|
200
|
+
website_id: _w,
|
|
201
|
+
slug: _s,
|
|
202
|
+
org_id: _o,
|
|
203
|
+
app_token: _t,
|
|
204
|
+
...rest
|
|
205
|
+
} = existing;
|
|
198
206
|
saveProject(dir, rest);
|
|
199
207
|
}
|
|
200
208
|
async function getOrCreateAnonContext(dir, name) {
|
|
@@ -222,8 +230,8 @@ async function getOrCreateAnonContext(dir, name) {
|
|
|
222
230
|
saveAnon(dir, ctx);
|
|
223
231
|
return { ctx, created: true };
|
|
224
232
|
}
|
|
225
|
-
async function anonPostForm(
|
|
226
|
-
return api.request("POST",
|
|
233
|
+
async function anonPostForm(path12, formData, ctx) {
|
|
234
|
+
return api.request("POST", path12, { formData, token: ctx.deploy_token });
|
|
227
235
|
}
|
|
228
236
|
function explainAnonUnauthorized(dir) {
|
|
229
237
|
clearAnon(dir);
|
|
@@ -232,6 +240,17 @@ function explainAnonUnauthorized(dir) {
|
|
|
232
240
|
);
|
|
233
241
|
process.exit(1);
|
|
234
242
|
}
|
|
243
|
+
async function healStaleAnonLink(dir, ctx) {
|
|
244
|
+
console.log("\nThis folder was linked to a temporary workspace this account can't access.");
|
|
245
|
+
if (new Date(ctx.claim_expires_at).getTime() > Date.now()) {
|
|
246
|
+
console.log("If nobody claimed it yet, it is still claimable:");
|
|
247
|
+
printClaimBlock(ctx);
|
|
248
|
+
}
|
|
249
|
+
clearAnon(dir);
|
|
250
|
+
const orgId = await resolveOrgContext({ dir });
|
|
251
|
+
console.log("Deploying into your own workspace instead...\n");
|
|
252
|
+
return orgId;
|
|
253
|
+
}
|
|
235
254
|
function printClaimBlock(ctx) {
|
|
236
255
|
const hoursLeft = Math.max(
|
|
237
256
|
1,
|
|
@@ -339,6 +358,32 @@ function hasUncommittedChanges(dir, filePath) {
|
|
|
339
358
|
}
|
|
340
359
|
}
|
|
341
360
|
|
|
361
|
+
// src/lib/drizzle.ts
|
|
362
|
+
import fs2 from "fs";
|
|
363
|
+
import path2 from "path";
|
|
364
|
+
var MANAGED_CONFIG = `import { defineConfig } from "drizzle-kit";
|
|
365
|
+
|
|
366
|
+
// Generated by the Clawnify CLI \u2014 do not edit. Derived from clawnify.json
|
|
367
|
+
// ("database": true) and src/server/schema.ts; regenerated on every
|
|
368
|
+
// dev / deploy / db generate run.
|
|
369
|
+
export default defineConfig({
|
|
370
|
+
schema: "./src/server/schema.ts",
|
|
371
|
+
out: "./.clawnify/drizzle",
|
|
372
|
+
dialect: "sqlite",
|
|
373
|
+
});
|
|
374
|
+
`;
|
|
375
|
+
function ensureDrizzleConfig(resolvedDir) {
|
|
376
|
+
const schemaTs = path2.join(resolvedDir, "src/server/schema.ts");
|
|
377
|
+
if (!fs2.existsSync(schemaTs)) return null;
|
|
378
|
+
const rootConfig = path2.join(resolvedDir, "drizzle.config.ts");
|
|
379
|
+
if (fs2.existsSync(rootConfig)) return rootConfig;
|
|
380
|
+
const clawnifyDir = path2.join(resolvedDir, ".clawnify");
|
|
381
|
+
fs2.mkdirSync(clawnifyDir, { recursive: true });
|
|
382
|
+
const managed = path2.join(clawnifyDir, "drizzle.config.ts");
|
|
383
|
+
fs2.writeFileSync(managed, MANAGED_CONFIG);
|
|
384
|
+
return managed;
|
|
385
|
+
}
|
|
386
|
+
|
|
342
387
|
// src/lib/servers.ts
|
|
343
388
|
async function resolveServerId(explicit) {
|
|
344
389
|
if (explicit) return explicit;
|
|
@@ -381,11 +426,11 @@ function ask(question) {
|
|
|
381
426
|
});
|
|
382
427
|
});
|
|
383
428
|
}
|
|
384
|
-
async function postFormWithRetry(
|
|
429
|
+
async function postFormWithRetry(path12, formData, orgId, attempts = 3) {
|
|
385
430
|
let lastErr;
|
|
386
431
|
for (let i = 0; i < attempts; i++) {
|
|
387
432
|
try {
|
|
388
|
-
return await api.postForm(
|
|
433
|
+
return await api.postForm(path12, formData, { orgId });
|
|
389
434
|
} catch (err) {
|
|
390
435
|
lastErr = err;
|
|
391
436
|
if (i === attempts - 1) break;
|
|
@@ -587,9 +632,9 @@ async function deployWebsite(dir, options) {
|
|
|
587
632
|
console.error("--from is app-only for now. Run `clawnify deploy` inside the website project directory.");
|
|
588
633
|
process.exit(EXIT_USAGE);
|
|
589
634
|
}
|
|
590
|
-
const resolvedDir = dir ?
|
|
635
|
+
const resolvedDir = dir ? path3.resolve(dir) : process.cwd();
|
|
591
636
|
const manifest = readManifest(resolvedDir);
|
|
592
|
-
const baseName = options.name || manifest?.name ||
|
|
637
|
+
const baseName = options.name || manifest?.name || path3.basename(resolvedDir);
|
|
593
638
|
const linkedProject = readProject(resolvedDir);
|
|
594
639
|
const { archive, files } = createArchive(resolvedDir);
|
|
595
640
|
if (isLoggedOut() && !options.org) {
|
|
@@ -678,7 +723,11 @@ async function deployWebsite(dir, options) {
|
|
|
678
723
|
return;
|
|
679
724
|
}
|
|
680
725
|
console.log(linkedProject?.website_id ? `Updating ${baseName}...` : `Deploying ${baseName}...`);
|
|
681
|
-
|
|
726
|
+
let result = await uploadWebsiteDeploy(archive, baseName, orgId);
|
|
727
|
+
if (!result.ok && result.error === "org_not_accessible" && linkedProject?.anon) {
|
|
728
|
+
orgId = await healStaleAnonLink(resolvedDir, linkedProject.anon);
|
|
729
|
+
result = await uploadWebsiteDeploy(archive, baseName, orgId);
|
|
730
|
+
}
|
|
682
731
|
if (!result.ok) {
|
|
683
732
|
console.error(`Deploy failed: ${result.error}`);
|
|
684
733
|
process.exit(1);
|
|
@@ -713,12 +762,12 @@ async function deployWebsite(dir, options) {
|
|
|
713
762
|
}
|
|
714
763
|
}
|
|
715
764
|
function walkFiles(root, cb) {
|
|
716
|
-
if (!
|
|
765
|
+
if (!fs3.existsSync(root)) return;
|
|
717
766
|
const walk = (cur, prefix) => {
|
|
718
|
-
for (const name of
|
|
719
|
-
const abs =
|
|
767
|
+
for (const name of fs3.readdirSync(cur)) {
|
|
768
|
+
const abs = path3.join(cur, name);
|
|
720
769
|
const rel = prefix ? `${prefix}/${name}` : name;
|
|
721
|
-
if (
|
|
770
|
+
if (fs3.statSync(abs).isDirectory()) walk(abs, rel);
|
|
722
771
|
else cb(rel, abs);
|
|
723
772
|
}
|
|
724
773
|
};
|
|
@@ -726,25 +775,25 @@ function walkFiles(root, cb) {
|
|
|
726
775
|
}
|
|
727
776
|
function assembleAgentFiles(dir) {
|
|
728
777
|
const out = [];
|
|
729
|
-
const agentMd =
|
|
730
|
-
if (
|
|
731
|
-
out.push({ path: "AGENTS.md", content:
|
|
778
|
+
const agentMd = path3.join(dir, "AGENT.md");
|
|
779
|
+
if (fs3.existsSync(agentMd)) {
|
|
780
|
+
out.push({ path: "AGENTS.md", content: fs3.readFileSync(agentMd, "utf8") });
|
|
732
781
|
}
|
|
733
|
-
walkFiles(
|
|
734
|
-
if (
|
|
735
|
-
out.push({ path: `skills/${rel}`, content:
|
|
782
|
+
walkFiles(path3.join(dir, "skills"), (rel, abs) => {
|
|
783
|
+
if (path3.basename(abs) === ".gitkeep") return;
|
|
784
|
+
out.push({ path: `skills/${rel}`, content: fs3.readFileSync(abs, "utf8") });
|
|
736
785
|
});
|
|
737
|
-
const flowsDir =
|
|
738
|
-
if (
|
|
739
|
-
for (const name of
|
|
786
|
+
const flowsDir = path3.join(dir, "flows");
|
|
787
|
+
if (fs3.existsSync(flowsDir)) {
|
|
788
|
+
for (const name of fs3.readdirSync(flowsDir)) {
|
|
740
789
|
if (!name.endsWith(".json")) continue;
|
|
741
|
-
out.push({ path: `flows/${name}`, content:
|
|
790
|
+
out.push({ path: `flows/${name}`, content: fs3.readFileSync(path3.join(flowsDir, name), "utf8") });
|
|
742
791
|
}
|
|
743
792
|
}
|
|
744
793
|
return out;
|
|
745
794
|
}
|
|
746
795
|
async function deployAgent(dir, options) {
|
|
747
|
-
const resolvedDir = dir ?
|
|
796
|
+
const resolvedDir = dir ? path3.resolve(dir) : process.cwd();
|
|
748
797
|
const linked = readProject(resolvedDir);
|
|
749
798
|
const serverId = await resolveServerId(options.server || linked?.server_id);
|
|
750
799
|
const agentName = options.agent || linked?.agent_name || "main";
|
|
@@ -807,7 +856,7 @@ async function deployAgent(dir, options) {
|
|
|
807
856
|
async function deployCommand(dir, options = {}) {
|
|
808
857
|
assertNodeVersion();
|
|
809
858
|
if (!options.from) {
|
|
810
|
-
const resolvedDir = dir ?
|
|
859
|
+
const resolvedDir = dir ? path3.resolve(dir) : process.cwd();
|
|
811
860
|
const manifest = readManifest(resolvedDir);
|
|
812
861
|
if (!manifest && readWorkspaceConfig(resolvedDir)) {
|
|
813
862
|
console.error(
|
|
@@ -829,16 +878,16 @@ async function deployCommand(dir, options = {}) {
|
|
|
829
878
|
process.exit(EXIT_USAGE);
|
|
830
879
|
}
|
|
831
880
|
}
|
|
832
|
-
if (!manifest && (
|
|
881
|
+
if (!manifest && (fs3.existsSync(path3.join(resolvedDir, "astro.config.mjs")) || fs3.existsSync(path3.join(resolvedDir, "astro.config.ts"))) && fs3.existsSync(path3.join(resolvedDir, "src", "tree"))) {
|
|
833
882
|
console.error(
|
|
834
883
|
'This looks like a Clawnify website, but it has no clawnify.json so it\ncannot be told apart from an app \u2014 deploying it as one creates a broken app.\n\n Add a clawnify.json here:\n { "version": 1, "name": "website", "website": { "framework": "astro" } }\n\n Or push to the synced workspace repo, which rebuilds the site for you.'
|
|
835
884
|
);
|
|
836
885
|
process.exit(EXIT_USAGE);
|
|
837
886
|
}
|
|
838
887
|
}
|
|
839
|
-
let appId;
|
|
840
|
-
let slug;
|
|
841
|
-
let appToken;
|
|
888
|
+
let appId = "";
|
|
889
|
+
let slug = "";
|
|
890
|
+
let appToken = "";
|
|
842
891
|
let resolvedOrgId;
|
|
843
892
|
let syncTargetDir;
|
|
844
893
|
if (options.from) {
|
|
@@ -890,10 +939,10 @@ async function deployCommand(dir, options = {}) {
|
|
|
890
939
|
appToken = result2.data.app_token;
|
|
891
940
|
resolvedOrgId = orgId;
|
|
892
941
|
} else {
|
|
893
|
-
const resolvedDir = dir ?
|
|
942
|
+
const resolvedDir = dir ? path3.resolve(dir) : process.cwd();
|
|
894
943
|
syncTargetDir = resolvedDir;
|
|
895
944
|
const manifest = readManifest(resolvedDir);
|
|
896
|
-
const baseName = options.name || manifest?.name ||
|
|
945
|
+
const baseName = options.name || manifest?.name || path3.basename(resolvedDir);
|
|
897
946
|
const framework = manifest?.app?.framework || "vite-preact";
|
|
898
947
|
const linkedProject = readProject(resolvedDir);
|
|
899
948
|
await regenerateDrizzleMigrations(resolvedDir);
|
|
@@ -946,7 +995,7 @@ async function deployCommand(dir, options = {}) {
|
|
|
946
995
|
printClaimBlock(ctx);
|
|
947
996
|
return;
|
|
948
997
|
}
|
|
949
|
-
|
|
998
|
+
let orgId = await resolveOrgId(options, linkedProject, resolvedDir);
|
|
950
999
|
if (options.dryRun) {
|
|
951
1000
|
summarizeArchive(archive, files, framework, baseName);
|
|
952
1001
|
if (linkedProject?.app_id) {
|
|
@@ -958,20 +1007,30 @@ async function deployCommand(dir, options = {}) {
|
|
|
958
1007
|
}
|
|
959
1008
|
return;
|
|
960
1009
|
}
|
|
1010
|
+
let needsCreate = !linkedProject?.app_id;
|
|
961
1011
|
if (linkedProject?.app_id) {
|
|
962
1012
|
console.log(`Updating ${baseName} (${linkedProject.slug ?? linkedProject.app_id})...`);
|
|
963
1013
|
const result2 = await uploadRedeploy(linkedProject.app_id, archive, orgId);
|
|
964
|
-
if (
|
|
1014
|
+
if (result2.ok) {
|
|
1015
|
+
appId = result2.data.app_id;
|
|
1016
|
+
slug = result2.data.slug;
|
|
1017
|
+
appToken = result2.data.app_token;
|
|
1018
|
+
saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });
|
|
1019
|
+
} else if (result2.error === "org_not_accessible" && linkedProject.anon) {
|
|
1020
|
+
orgId = await healStaleAnonLink(resolvedDir, linkedProject.anon);
|
|
1021
|
+
needsCreate = true;
|
|
1022
|
+
} else {
|
|
965
1023
|
console.error(`Deploy failed: ${result2.error}`);
|
|
966
1024
|
process.exit(1);
|
|
967
1025
|
}
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
appToken = result2.data.app_token;
|
|
971
|
-
saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });
|
|
972
|
-
} else {
|
|
1026
|
+
}
|
|
1027
|
+
if (needsCreate) {
|
|
973
1028
|
console.log(`Deploying ${baseName}...`);
|
|
974
1029
|
let result2 = await uploadDeploy(archive, baseName, framework, orgId);
|
|
1030
|
+
if (!result2.ok && !("conflict" in result2) && result2.error === "org_not_accessible" && linkedProject?.anon) {
|
|
1031
|
+
orgId = await healStaleAnonLink(resolvedDir, linkedProject.anon);
|
|
1032
|
+
result2 = await uploadDeploy(archive, baseName, framework, orgId);
|
|
1033
|
+
}
|
|
975
1034
|
if (!result2.ok && "conflict" in result2) {
|
|
976
1035
|
const decision = await resolveConflictDecision(options, result2.conflict);
|
|
977
1036
|
if (decision === "update") {
|
|
@@ -1024,9 +1083,9 @@ async function deployCommand(dir, options = {}) {
|
|
|
1024
1083
|
if (syncTargetDir && !options.noSync && resolvedOrgId) {
|
|
1025
1084
|
try {
|
|
1026
1085
|
const schema = await fetchSchema({ appId, orgId: resolvedOrgId });
|
|
1027
|
-
const target =
|
|
1086
|
+
const target = path3.join(syncTargetDir, "schema.sql");
|
|
1028
1087
|
const writeResult = await writeSchema(target, schema);
|
|
1029
|
-
const rel =
|
|
1088
|
+
const rel = path3.relative(process.cwd(), writeResult.path) || writeResult.path;
|
|
1030
1089
|
switch (writeResult.status) {
|
|
1031
1090
|
case "written":
|
|
1032
1091
|
console.log(` Synced ${rel} (${writeResult.bytes} bytes)
|
|
@@ -1057,11 +1116,10 @@ async function deployCommand(dir, options = {}) {
|
|
|
1057
1116
|
}
|
|
1058
1117
|
}
|
|
1059
1118
|
async function regenerateDrizzleMigrations(resolvedDir) {
|
|
1060
|
-
const
|
|
1061
|
-
|
|
1062
|
-
if (!fs2.existsSync(schemaTs) || !fs2.existsSync(drizzleConfig)) return;
|
|
1119
|
+
const drizzleConfig = ensureDrizzleConfig(resolvedDir);
|
|
1120
|
+
if (!drizzleConfig) return;
|
|
1063
1121
|
await new Promise((resolve) => {
|
|
1064
|
-
const proc = spawn("npx", ["drizzle-kit", "generate"], {
|
|
1122
|
+
const proc = spawn("npx", ["drizzle-kit", "generate", `--config=${drizzleConfig}`], {
|
|
1065
1123
|
cwd: resolvedDir,
|
|
1066
1124
|
stdio: ["ignore", "pipe", "pipe"],
|
|
1067
1125
|
env: { ...process.env }
|
|
@@ -1086,20 +1144,20 @@ async function regenerateDrizzleMigrations(resolvedDir) {
|
|
|
1086
1144
|
}
|
|
1087
1145
|
function assertDatabaseDdlPresent(resolvedDir, manifest) {
|
|
1088
1146
|
if (!manifest?.app?.database) return;
|
|
1089
|
-
const hasSchemaSql =
|
|
1147
|
+
const hasSchemaSql = fs3.existsSync(path3.join(resolvedDir, "schema.sql")) || fs3.existsSync(path3.join(resolvedDir, "src/server/schema.sql"));
|
|
1090
1148
|
if (hasSchemaSql) return;
|
|
1091
|
-
const drizzleDir =
|
|
1092
|
-
const hasDrizzleSql =
|
|
1149
|
+
const drizzleDir = path3.join(resolvedDir, ".clawnify", "drizzle");
|
|
1150
|
+
const hasDrizzleSql = fs3.existsSync(drizzleDir) && fs3.readdirSync(drizzleDir).some((f) => f.endsWith(".sql"));
|
|
1093
1151
|
if (hasDrizzleSql) return;
|
|
1094
1152
|
console.error(
|
|
1095
1153
|
`Deploy aborted: this app sets "database": true in clawnify.json, but no schema
|
|
1096
1154
|
would be applied \u2014 so every query would fail at runtime with "no such table".
|
|
1097
1155
|
|
|
1098
1156
|
Fix:
|
|
1099
|
-
\u2022
|
|
1157
|
+
\u2022 npx clawnify db generate (emits .clawnify/drizzle/*.sql from src/server/schema.ts)
|
|
1100
1158
|
If that just failed, see the warning above \u2014 drizzle-kit ships as a
|
|
1101
1159
|
devDependency, so run your package manager's install first.
|
|
1102
|
-
\u2022 set "database": false
|
|
1160
|
+
\u2022 set "database": false (if this app genuinely has no database)
|
|
1103
1161
|
|
|
1104
1162
|
schema.ts is the source of truth; a hand-written schema.sql at the app root
|
|
1105
1163
|
is also accepted, but only for apps not using Drizzle.`
|
|
@@ -1241,8 +1299,8 @@ async function sessionsHistoryCommand(key, opts) {
|
|
|
1241
1299
|
}
|
|
1242
1300
|
|
|
1243
1301
|
// src/commands/agents.ts
|
|
1244
|
-
import
|
|
1245
|
-
import
|
|
1302
|
+
import fs4 from "fs";
|
|
1303
|
+
import path4 from "path";
|
|
1246
1304
|
async function agentsListCommand() {
|
|
1247
1305
|
const res = await api.get("/agents");
|
|
1248
1306
|
if (!res.ok) {
|
|
@@ -1289,15 +1347,15 @@ async function agentsPullCommand(dir, opts) {
|
|
|
1289
1347
|
process.exit(1);
|
|
1290
1348
|
}
|
|
1291
1349
|
const { files } = await res.json();
|
|
1292
|
-
const target = dir ?
|
|
1293
|
-
|
|
1350
|
+
const target = dir ? path4.resolve(dir) : process.cwd();
|
|
1351
|
+
fs4.mkdirSync(target, { recursive: true });
|
|
1294
1352
|
let written = 0;
|
|
1295
1353
|
for (const f of files ?? []) {
|
|
1296
|
-
const norm =
|
|
1354
|
+
const norm = path4.posix.normalize(f.path);
|
|
1297
1355
|
if (norm.startsWith("/") || norm.split("/").includes("..")) continue;
|
|
1298
|
-
const abs =
|
|
1299
|
-
|
|
1300
|
-
|
|
1356
|
+
const abs = path4.join(target, norm);
|
|
1357
|
+
fs4.mkdirSync(path4.dirname(abs), { recursive: true });
|
|
1358
|
+
fs4.writeFileSync(abs, f.content);
|
|
1301
1359
|
written++;
|
|
1302
1360
|
}
|
|
1303
1361
|
const existing = readProject(target) ?? {};
|
|
@@ -1306,14 +1364,14 @@ async function agentsPullCommand(dir, opts) {
|
|
|
1306
1364
|
console.log(`Edit AGENTS.md / skills / flows, then push: clawnify agents push${dir ? ` ${dir}` : ""}`);
|
|
1307
1365
|
}
|
|
1308
1366
|
async function agentsPushCommand(dir, opts) {
|
|
1309
|
-
const target = dir ?
|
|
1367
|
+
const target = dir ? path4.resolve(dir) : process.cwd();
|
|
1310
1368
|
const linked = readProject(target);
|
|
1311
1369
|
const serverId = await resolveServerId(opts.server || linked?.server_id);
|
|
1312
1370
|
const agent = opts.agent || linked?.agent_name || "main";
|
|
1313
1371
|
const files = [];
|
|
1314
1372
|
const add = (rel) => {
|
|
1315
1373
|
try {
|
|
1316
|
-
files.push({ path: rel, content:
|
|
1374
|
+
files.push({ path: rel, content: fs4.readFileSync(path4.join(target, rel), "utf8") });
|
|
1317
1375
|
} catch {
|
|
1318
1376
|
}
|
|
1319
1377
|
};
|
|
@@ -1321,7 +1379,7 @@ async function agentsPushCommand(dir, opts) {
|
|
|
1321
1379
|
const walk = (relDir) => {
|
|
1322
1380
|
let names;
|
|
1323
1381
|
try {
|
|
1324
|
-
names =
|
|
1382
|
+
names = fs4.readdirSync(path4.join(target, relDir));
|
|
1325
1383
|
} catch {
|
|
1326
1384
|
return;
|
|
1327
1385
|
}
|
|
@@ -1329,7 +1387,7 @@ async function agentsPushCommand(dir, opts) {
|
|
|
1329
1387
|
const rel = `${relDir}/${name}`;
|
|
1330
1388
|
let isDir = false;
|
|
1331
1389
|
try {
|
|
1332
|
-
isDir =
|
|
1390
|
+
isDir = fs4.statSync(path4.join(target, rel)).isDirectory();
|
|
1333
1391
|
} catch {
|
|
1334
1392
|
continue;
|
|
1335
1393
|
}
|
|
@@ -1340,7 +1398,7 @@ async function agentsPushCommand(dir, opts) {
|
|
|
1340
1398
|
walk("skills");
|
|
1341
1399
|
let flowNames = [];
|
|
1342
1400
|
try {
|
|
1343
|
-
flowNames =
|
|
1401
|
+
flowNames = fs4.readdirSync(path4.join(target, "flows"));
|
|
1344
1402
|
} catch {
|
|
1345
1403
|
}
|
|
1346
1404
|
for (const name of flowNames) if (name.endsWith(".json")) add(`flows/${name}`);
|
|
@@ -1463,7 +1521,7 @@ async function envUnsetCommand(key) {
|
|
|
1463
1521
|
}
|
|
1464
1522
|
|
|
1465
1523
|
// src/commands/api.ts
|
|
1466
|
-
async function apiCommand(
|
|
1524
|
+
async function apiCommand(path12, opts) {
|
|
1467
1525
|
const method = (opts.method || (opts.data !== void 0 ? "POST" : "GET")).toUpperCase();
|
|
1468
1526
|
let body;
|
|
1469
1527
|
if (opts.data !== void 0) {
|
|
@@ -1474,7 +1532,7 @@ async function apiCommand(path10, opts) {
|
|
|
1474
1532
|
process.exit(1);
|
|
1475
1533
|
}
|
|
1476
1534
|
}
|
|
1477
|
-
const p =
|
|
1535
|
+
const p = path12.startsWith("/") ? path12 : `/${path12}`;
|
|
1478
1536
|
const orgId = await resolveOrgContext({ orgFlag: opts.org });
|
|
1479
1537
|
const res = await api.call(method, p, { body, orgId });
|
|
1480
1538
|
const text = await res.text();
|
|
@@ -1583,8 +1641,8 @@ async function whoamiCommand() {
|
|
|
1583
1641
|
}
|
|
1584
1642
|
|
|
1585
1643
|
// src/commands/init.ts
|
|
1586
|
-
import
|
|
1587
|
-
import
|
|
1644
|
+
import fs5 from "fs";
|
|
1645
|
+
import path5 from "path";
|
|
1588
1646
|
import readline4 from "readline";
|
|
1589
1647
|
|
|
1590
1648
|
// src/lib/skills/detect.ts
|
|
@@ -1598,9 +1656,9 @@ var DETECTORS = [
|
|
|
1598
1656
|
{ agent: "aider", markers: ["CONVENTIONS.md", ".aider.conf.yml"], target: "CONVENTIONS.md" }
|
|
1599
1657
|
];
|
|
1600
1658
|
function exists(cwd, name) {
|
|
1601
|
-
const
|
|
1659
|
+
const path12 = join(cwd, name);
|
|
1602
1660
|
try {
|
|
1603
|
-
statSync(
|
|
1661
|
+
statSync(path12);
|
|
1604
1662
|
return true;
|
|
1605
1663
|
} catch {
|
|
1606
1664
|
return false;
|
|
@@ -1624,22 +1682,22 @@ function agentByName(name) {
|
|
|
1624
1682
|
var ALL_AGENTS = DETECTORS.map((d) => d.agent);
|
|
1625
1683
|
|
|
1626
1684
|
// src/lib/skills/content.gen.ts
|
|
1627
|
-
var CLI_VERSION = "0.16.
|
|
1685
|
+
var CLI_VERSION = "0.16.2";
|
|
1628
1686
|
var BUNDLED_SKILLS = [
|
|
1629
1687
|
{
|
|
1630
1688
|
name: "build-a-clawnify-app",
|
|
1631
|
-
description: "Author a Clawnify app end-to-end \u2014 the canonical Hono + React + Vite + @hono/zod-openapi + @clawnify/db (Drizzle) stack, schema.ts
|
|
1632
|
-
content: '# Build a Clawnify app\n\nCanonical skill: how to author a Clawnify app end-to-end. Same content\nfor humans reading the docs and for AI coding agents injecting this as\ninstructions during an app build.\n\nIf you\'re an agent: this document is enough context to produce a\nworking app from scratch. Follow it literally. The patterns here\nare exactly what `clawnify init` scaffolds and what the platform\nexpects.\n\n## TL;DR\n\n- **One stack.** Hono + React + Vite + `@hono/zod-openapi` +\n `@clawnify/db` (Drizzle) + `@clawnify/app` (entry, routing,\n identity) + Tailwind v4. Nothing else.\n- **Schema lives in two files kept in sync** \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- **`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 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 entry\n\n```ts\nimport { createApp } from "@clawnify/app";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database } };\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<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.route("/", api);\n\nexport default app;\n```\n\nThe entry is thin: `createApp()` then mount your routes. `createApp`\nreturns an `OpenAPIHono` with **API discovery already mounted** \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 } from "@clawnify/app";\nimport { initUploads } from "./uploads";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\n\nconst app = createApp<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.use("*", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route("/", api);\n\nexport default app;\n```\n\n## `src/server/routes.ts` \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 } from "@clawnify/app";\nimport { getDB, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\nexport default api;\n```\n\nCRUD template \u2014 the full list/create/update/delete surface:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@clawnify/app";\nimport { getDB, eq, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi("UpdateItem");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\napi.openapi(\n createRoute({\n method: "post",\n path: "/api/items",\n summary: "Create item",\n request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: "Created item",\n content: { "application/json": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid("json");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: "patch",\n path: "/api/items/:id",\n summary: "Update item",\n request: {\n params: IdParamSchema,\n body: { content: { "application/json": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const body = c.req.valid("json");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: "delete",\n path: "/api/items/:id",\n summary: "Delete item",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n```\n\nPatterns to follow:\n- **Give every route a clear `summary`/`description`.** The generated\n OpenAPI spec is what the agent reads to decide which endpoint to\n call \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\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.\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 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 calls `call_app_api` with `GET /llms.txt` (index of every\n endpoint) or `GET /api/openapi.json` (full request/response schemas).\n Because both are generated from the live route table, they cannot\n drift from the code.\n2. The agent then drives your endpoints with `call_app_api` (a `method`\n + `path` on the live app). No per-app MCP registration and no\n manifest tools array. Use source reading to *modify* code, not to\n 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\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, or\n hand-parse `X-Clawnify-*` headers. Use `user(c)` / `orgId(c)` /\n `caller(c)` from `@clawnify/app`.\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\n through `@clawnify/connections` (`connect` / `secret` / `run`).\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\n need to pin a specific version (rare).\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `desc`, `sql`, `sqliteTable`, `text`,\n `integer`, `index`, etc. are all re-exported there). Drop to\n `drizzle-orm` directly only for things not re-exported.\n- Give every route a clear `summary`/`description` and Zod-typed\n request/response so the agent can discover and call it via the\n OpenAPI spec.\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\n publishing \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'
|
|
1689
|
+
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.",
|
|
1690
|
+
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 `clawnify db generate` (the scaffold\'s `pnpm db:generate`\nis an alias for it). 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\ntype Env = { Bindings: { DB: D1Database } };\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<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.route("/", api);\n\nexport default app;\n```\n\nThe entry is thin: `createApp()` then mount your routes. `createApp`\nreturns an `OpenAPIHono` with **API discovery already mounted** \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 } from "@clawnify/app";\nimport { initUploads } from "./uploads";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\n\nconst app = createApp<Env>({ title: "My app", version: "1.0.0", db: false });\n\napp.use("*", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route("/", api);\n\nexport default app;\n```\n\n## `src/server/routes.ts` \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 } from "@clawnify/app";\nimport { getDB, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\nexport default api;\n```\n\nCRUD template \u2014 the full list/create/update/delete surface:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@clawnify/app";\nimport { getDB, eq, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi("UpdateItem");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\napi.openapi(\n createRoute({\n method: "post",\n path: "/api/items",\n summary: "Create item",\n request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: "Created item",\n content: { "application/json": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid("json");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: "patch",\n path: "/api/items/:id",\n summary: "Update item",\n request: {\n params: IdParamSchema,\n body: { content: { "application/json": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const body = c.req.valid("json");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: "delete",\n path: "/api/items/:id",\n summary: "Delete item",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n```\n\nPatterns to follow:\n- **Give every route a clear `summary`/`description`.** The generated\n OpenAPI spec is what the agent reads to decide which endpoint to\n call \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\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.\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. `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 calls `call_app_api` with `GET /llms.txt` (index of every\n endpoint) or `GET /api/openapi.json` (full request/response schemas).\n Because both are generated from the live route table, they cannot\n drift from the code.\n2. The agent then drives your endpoints with `call_app_api` (a `method`\n + `path` on the live app). No per-app MCP registration and no\n manifest tools array. Use source reading to *modify* code, not to\n 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-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\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 `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` 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- Read auth from `Authorization` / cookies / `Bearer` tokens, or\n hand-parse `X-Clawnify-*` headers. Use `user(c)` / `orgId(c)` /\n `caller(c)` from `@clawnify/app`.\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\n through `@clawnify/connections` (`connect` / `secret` / `run`).\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\n need to pin a specific version (rare).\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `desc`, `sql`, `sqliteTable`, `text`,\n `integer`, `index`, etc. are all re-exported there). Drop to\n `drizzle-orm` directly only for things not re-exported.\n- Give every route a clear `summary`/`description` and Zod-typed\n request/response so the agent can discover and call it via the\n OpenAPI spec.\n- Test locally with `clawnify 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'
|
|
1633
1691
|
},
|
|
1634
1692
|
{
|
|
1635
1693
|
name: "build-a-clawnify-website",
|
|
1636
1694
|
description: "Build and ship a Clawnify website \u2014 Astro on Cloudflare Workers, the built-in form system (never hand-roll a form), images and assets, and the draft-then-publish deploy flow. Use when creating or editing a Clawnify website, or when a site needs a contact/waitlist/signup form.",
|
|
1637
|
-
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\nclawnify init --type website --name \"My Site\" website\ncd website && pnpm install && pnpm dev # http://localhost:4321\n```\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-form` attribute and its submit script,\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\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### 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: draft first, then publish\n\n```bash\nclawnify deploy # \u2192 the DRAFT site, visible only to your org\n```\n\nDeploying **never** changes the live site. Going live is a separate, explicit\nstep: review the draft, then **Publish to live** in the dashboard. Tell the user\nthis \u2014 a deploy that \"worked\" but didn't appear on the live site is almost\nalways someone expecting deploy to publish.\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"
|
|
1695
|
+
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\nclawnify init --type website --name \"My Site\" website\ncd website && pnpm install && pnpm dev # http://localhost:4321\n```\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-form` attribute and its submit script,\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\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: draft first, then publish\n\n```bash\nclawnify deploy # \u2192 the DRAFT site, visible only to your org\n```\n\nDeploying **never** changes the live site. Going live is a separate, explicit\nstep: review the draft, then **Publish to live** in the dashboard. Tell the user\nthis \u2014 a deploy that \"worked\" but didn't appear on the live site is almost\nalways someone expecting deploy to publish.\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"
|
|
1638
1696
|
},
|
|
1639
1697
|
{
|
|
1640
1698
|
name: "use-the-clawnify-cli",
|
|
1641
1699
|
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.",
|
|
1642
|
-
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,
|
|
1700
|
+
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\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 db generate # refresh .clawnify/drizzle/*.sql from schema.ts\nclawnify pull schema --from <app-id-or-slug> # snapshot the DEPLOYED schema to schema.sql (generated; read-only reference)\nclawnify docs [slug] # usage README for an app (org index if omitted)\n```\n\n`pull schema` refuses to clobber local uncommitted changes unless you\npass `--force`.\n\n## Manage agents (the FDE surface)\n\nDrive an org's AI agents from the terminal \u2014 observe them and fix them. See the\n`fix-a-clawnify-agent` skill for the workflow; this is the command list. All\norg-scoped and **repo-independent** (reads live agent state, never a GitHub\nrepo).\n\n**The model \u2014 two levels, and only two.** An org has one or more **agents** (the\nAI employees, e.g. \"Ash\"). Each agent can have **sub-agents**: narrower helpers\nit delegates to. `clawnify agents list` prints both, sub-agents indented under\nthe agent that owns them:\n\n```\nAsh (ready, nbg1)\n id: 7c2f\u2026\n sub-agents:\n \u2514\u2500 research (Research) 4 sessions\n```\n\nAn org normally has exactly one agent, so nothing needs to be selected. When it\nhas several, pass `--agent-id <id>` (the `id:` line above).\n\n```bash\nclawnify agents list # the org's agents, each with its sub-agents\nclawnify agents skills [agent] # what an agent can ACTUALLY run (not just its workspace)\nclawnify sessions --agent <slug> --json # stored sessions + token counters (contextTokens = bloat)\nclawnify sessions history <key> --json # one session's transcript \u2014 where it veered\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/ to edit (flows/ come with main only \u2014 flows belong to the main agent)\nclawnify agents push [dir] # push edits back (additive; next session, no restart)\nclawnify agents grant-skill <s> --to <a> # share a main-authored skill (or --all for every agent)\nclawnify agents create <slug> --yes # new SUB-AGENT (RESTARTS the gateway)\nclawnify env set <KEY> <VALUE> # org custom env \u2014 NON-SECRET only (restarts gateway)\nclawnify connections connect <id> # how to connect an integration (dashboard OAuth; you can't)\nclawnify flows list # the main agent's flows + latest published version\nclawnify flows read <name> # print a flow's draft\nclawnify flows create <name> --file f.json # new draft (validated on save)\nclawnify flows edit <name> # edit the draft ($EDITOR, or --file to replace)\nclawnify flows publish <name> # cut the next numbered live version\n```\n\n**Flows:** runs and triggers use the latest **published** version, so editing a\ndraft doesn't change what's live \u2014 until a flow's first publish, though, the\ndraft *is* what runs. `create`/`edit`/`publish` validate automatically and\nreport per-node errors; fix and re-save. Prefer these verbs over pushing raw\n`flows/*.json` edits (which skip validation and versioning).\n\n**Boundary:** everything above is autonomous *except* the human-auth actions \u2014\nconnecting an integration (OAuth) and handing over a secret/API key. For those,\nexplain the dashboard steps; never fake them. `agents create` / `env set`\nrestart the gateway, so confirm before running them on a busy agent.\n\n**`agents create` makes a NEW sub-agent \u2014 it is never the way to \"find\" an\nexisting one.** If you were looking for an agent and `agents list` didn't show\nit, the answer is that the org doesn't have it, or you're in the wrong org\n(`clawnify org list`). Creating one restarts the gateway and leaves a duplicate\nbehind.\n\n## Connections & env names\n\n```bash\nclawnify connections list # the org's naming catalog (\u25CF connected / \u25CB not)\nclawnify connections connect <id> # how to connect one \u2014 dashboard OAuth; the CLI/agent can't do it for you\n```\n\nLists the active org's integrations (canonical ids + connected state),\nprovider API keys (fixed names + set state), and custom env vars. Read\nit before declaring `credentials` or env names in `clawnify.json` and\nreuse the exact identifiers it shows \u2014 a misspelled id or key name\ndoesn't fail the build, it silently resolves to nothing at runtime.\n\n## Workspaces (one repo, one org's apps)\n\n```bash\nclawnify workspace init [dir] [--org <slug-or-id>]\n```\n\nScaffolds a monorepo bound to an org; apps scaffolded inside land\nunder `apps/` and inherit the org on deploy.\n\n## Wire up coding agents\n\n```bash\nclawnify ai-files install # rules + skills + MCP server in one step\nclawnify skills list # bundled skills\nclawnify skills add <name> # install one into detected agents\nclawnify mcp # stdio MCP bridge (Claude Desktop, etc.)\n```\n\n`ai-files install` detects agent config dirs in the project (Claude\nCode, Cursor, OpenClaw, Codex, Aider) and writes the always-on rules\nblock, installs bundled skills, and adds the Clawnify MCP server to\n`.mcp.json`. Target one agent with `--agent <name>`; undo with\n`clawnify ai-files uninstall`.\n\n## The raw escape hatch\n\n```bash\nclawnify api /agents # any GET\nclawnify api /apps -X POST -d '{\u2026}' # any method + JSON body\n```\n\n`clawnify api <path>` makes an authenticated request to any Clawnify API path \u2014\nsame auth and org scoping as every other command (it can only do what you can).\nUse it for anything the porcelain doesn't wrap; the curated commands stay small\nbecause this is always there.\n\n## Tips\n\n- `npx clawnify@latest <command>` always runs the newest release.\n- Every org-scoped command accepts `--org` \u2014 prefer it in scripts over\n relying on the saved active org.\n- If sign-in ever fails mid-flow, just run `clawnify login` again; it\n is safe to repeat.\n"
|
|
1643
1701
|
},
|
|
1644
1702
|
{
|
|
1645
1703
|
name: "fix-a-clawnify-agent",
|
|
@@ -1648,7 +1706,7 @@ var BUNDLED_SKILLS = [
|
|
|
1648
1706
|
}
|
|
1649
1707
|
];
|
|
1650
1708
|
var RULES_BY_KIND = {
|
|
1651
|
-
"app": "You are working inside a **Clawnify app** \u2014 a full-stack project that deploys to\nCloudflare through the Clawnify platform. Follow these rules.\n\n## Stack (fixed \u2014 do not swap)\n\n- **Frontend:** React 19 + Tailwind v4, built with Vite.\n- **API:** Hono (`@hono/zod-openapi`) running on Cloudflare Workers.\n- **Database:** D1 (SQLite at the edge) via `@clawnify/db` (Drizzle).\n\nOne app = one `clawnify.json` manifest at the repo root. Don't introduce other\nframeworks, ORMs, or hosting targets.\n\n## The schema lives in `src/server/schema.ts`\n\n- Define tables with the Drizzle DSL there \u2014 it is the single source of truth.\n- **Never** hand-write SQL migrations or edit a `schema.sql` by hand. `clawnify\n dev` and `clawnify deploy` run `drizzle-kit generate` for you.\n- Every user-facing table needs an `org_id` column, and every query must filter\n by the `
|
|
1709
|
+
"app": "You are working inside a **Clawnify app** \u2014 a full-stack project that deploys to\nCloudflare through the Clawnify platform. Follow these rules.\n\n## Stack (fixed \u2014 do not swap)\n\n- **Frontend:** React 19 + Tailwind v4, built with Vite.\n- **API:** Hono (`@hono/zod-openapi`) running on Cloudflare Workers.\n- **Database:** D1 (SQLite at the edge) via `@clawnify/db` (Drizzle).\n\nOne app = one `clawnify.json` manifest at the repo root. Don't introduce other\nframeworks, ORMs, or hosting targets.\n\n## The schema lives in `src/server/schema.ts`\n\n- Define tables with the Drizzle DSL there \u2014 it is the single source of truth.\n- **Never** hand-write SQL migrations or edit a `schema.sql` by hand. `clawnify\n dev` and `clawnify deploy` run `drizzle-kit generate` for you.\n- Every user-facing table needs an `org_id` column, and every query must filter\n by the org \u2014 read it with `orgId(c)` from `@clawnify/app`. This is how\n multi-tenancy works \u2014 there are no exceptions.\n\n## Identity comes from request headers, never the client\n\nThe platform injects identity the client cannot forge. Read it with\n`user(c)` / `orgId(c)` / `caller(c)` from `@clawnify/app` \u2014 never parse\n`X-Clawnify-*` headers by hand, and never trust a client-supplied user or\norg id.\n\n## Integrations: use `@clawnify/connections`\n\nDon't store per-service API keys or OAuth secrets in the app. Declare what the\napp needs under `app.credentials` in `clawnify.json`, then call\n`connect(service, env)` and `secret(name, env)` from the SDK. Off-platform\n(local dev, scripts), put a `clw_` org service token in `.dev.vars` as\n`CLAWNIFY_TOKEN` \u2014 the SDK then resolves your **real** org connections over HTTP\nwith no per-service secrets.\n\n## Commands\n\n- `clawnify dev` \u2014 local dev server. D1 runs as local SQLite, identical to\n production. Leave it running in a separate terminal so generated types stay\n fresh.\n- `clawnify deploy` \u2014 ships the app live at `https://<slug>.apps.clawnify.com`.\n- Don't invoke raw `wrangler` or `drizzle-kit` \u2014 the CLI wraps them. Editing\n `schema.ts` and running `clawnify dev`/`deploy` is the whole workflow.\n\n## Going deeper\n\nFor the full gold-standard structure \u2014 routing, OpenAPI route definitions,\nclient data-fetching patterns, file uploads \u2014 read the **build-a-clawnify-app**\nskill installed alongside these rules.\n",
|
|
1652
1710
|
"website": "You are working inside a **Clawnify website** \u2014 an Astro site that deploys to\nCloudflare through the Clawnify platform. Follow these rules.\n\n## Stack (fixed \u2014 do not swap)\n\n- **Framework:** Astro 5, `output: \"server\"` with the `@astrojs/cloudflare`\n adapter. Pages render on a Worker, so `Astro.request` and runtime env are\n available; there is no static export step to fight.\n- **Styling:** Tailwind v4 via `@tailwindcss/vite`, entry `src/styles/global.css`.\n\nOne website = one `clawnify.json` manifest at the repo root, with\n`website: { framework: \"astro\" }`. Don't introduce another framework, another\nCSS system, or another hosting target.\n\n## This is a normal Astro project \u2014 author it as one\n\n- Pages are files: `src/pages/index.astro` is `/`, `src/pages/about.astro` is\n `/about`. Dynamic routes use `[slug].astro` the usual way.\n- Shared chrome belongs in `src/layouts/`; reusable markup in\n `src/components/`.\n- A route that fetches per request needs `export const prerender = false`.\n Without it Astro prerenders at build time and your data is frozen at deploy.\n\nThere is no page-tree JSON, no block registry, and no theme token file in this\nproject. Those belong to Clawnify's dashboard-managed website product, which is\na different thing with a different authoring model \u2014 don't go looking for them\nhere, and don't invent them.\n\n## Fetching data on the server\n\nFetch in the frontmatter (it runs on the Worker), not in a client script, unless\nthe data is genuinely user-interactive. Anything you can resolve server-side\nrenders in the first byte and costs the visitor nothing.\n\nGive any response you cache-control a real TTL: `public, max-age=<n>`. Clawnify\nedge-caches declared-public GETs, but only when the response says how long it is\ngood for.\n\n## Commands\n\n- `clawnify dev` \u2014 local dev server, same adapter as production.\n- `clawnify deploy` \u2014 publishes the site and prints its live URL.\n- Don't invoke raw `astro` or `wrangler` \u2014 the CLI wraps them, and it is what\n binds the deploy to your org and site.\n\n## Going deeper\n\nAstro's own docs are the reference for routing, layouts, and content\ncollections \u2014 this is a standard Astro project and nothing about it is\nClawnify-specific except the manifest and the deploy step. For CLI mechanics\n(workspaces, orgs, linking, custom domains) read the **use-the-clawnify-cli**\nskill installed alongside these rules.\n",
|
|
1653
1711
|
"agent": 'You are working inside a **Clawnify agent** project \u2014 the configuration for an\nAI employee that runs on the Clawnify platform. Follow these rules.\n\n## What this project is\n\nOne agent = one `clawnify.json` manifest at the repo root, with\n`agent: { harness: "openclaw" }`. The manifest picks the runtime; everything\nelse here is prose and JSON that shapes behaviour. There is no application\nstack to choose \u2014 no framework, no database, no build.\n\n## The pieces\n\n- **`AGENT.md`** \u2014 the agent\'s primary instructions, its role, tone and\n boundaries, written as prose. This is the file that actually changes how the\n agent behaves; most requests to "change what the agent does" are edits here.\n- **`skills/<name>/`** \u2014 reusable procedures. A `SKILL.md` the agent reads when\n triggered, plus a `skill.json` describing when it runs. Reach for a skill when\n a task recurs with the same shape; don\'t encode one-offs.\n- **`flows/<name>.json`** \u2014 ClawFlow definitions for automations that run on a\n schedule or a trigger rather than in conversation.\n\n## Write instructions, not code\n\nThe most common mistake here is reaching for a script when the answer is a\nclearer sentence in `AGENT.md` or a skill. Prefer changing the instructions.\nAdd a flow only when something must run without a human in the loop.\n\n## Commands\n\n- `clawnify deploy` \u2014 pushes this configuration to the agent.\n- The push is additive on the agent\'s machine: it never deletes files the agent\n authored for itself.\n\n## Going deeper\n\nFor diagnosing an agent that is misbehaving \u2014 instructions not taking effect,\na channel not responding, a skill not firing \u2014 read the **fix-a-clawnify-agent**\nskill installed alongside these rules.\n'
|
|
1654
1712
|
};
|
|
@@ -1669,10 +1727,10 @@ var VERSION_HEADER_RE = /<!--\s*clawnify-skill:\s*([\w-]+)\s+v([\d.]+)\s*-->/;
|
|
|
1669
1727
|
function versionHeader(name) {
|
|
1670
1728
|
return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;
|
|
1671
1729
|
}
|
|
1672
|
-
function readExistingVersion(
|
|
1673
|
-
if (!existsSync2(
|
|
1730
|
+
function readExistingVersion(path12) {
|
|
1731
|
+
if (!existsSync2(path12)) return null;
|
|
1674
1732
|
try {
|
|
1675
|
-
const head = readFileSync(
|
|
1733
|
+
const head = readFileSync(path12, "utf8").slice(0, 500);
|
|
1676
1734
|
const match = head.match(VERSION_HEADER_RE);
|
|
1677
1735
|
return match ? match[2] : null;
|
|
1678
1736
|
} catch {
|
|
@@ -2106,15 +2164,15 @@ async function initCommand(dir, opts) {
|
|
|
2106
2164
|
}
|
|
2107
2165
|
async function initApp(dir, opts) {
|
|
2108
2166
|
const yes = !!opts?.yes;
|
|
2109
|
-
const dirArgName = dir ?
|
|
2167
|
+
const dirArgName = dir ? path5.basename(path5.resolve(dir)) : void 0;
|
|
2110
2168
|
const name = opts?.name || (yes ? dirArgName ?? "my-app" : await ask2("App name: ") || "my-app");
|
|
2111
2169
|
const slug = slugify(name);
|
|
2112
2170
|
let targetDir;
|
|
2113
2171
|
if (dir) {
|
|
2114
|
-
targetDir =
|
|
2172
|
+
targetDir = path5.resolve(dir);
|
|
2115
2173
|
} else {
|
|
2116
2174
|
const ws = findWorkspaceRoot(process.cwd());
|
|
2117
|
-
targetDir = ws ?
|
|
2175
|
+
targetDir = ws ? path5.join(ws.dir, "apps", slug) : path5.resolve(slug);
|
|
2118
2176
|
}
|
|
2119
2177
|
let template;
|
|
2120
2178
|
if (opts?.template) {
|
|
@@ -2130,12 +2188,12 @@ async function initApp(dir, opts) {
|
|
|
2130
2188
|
const templateChoice = await ask2("Template [1]: ") || "1";
|
|
2131
2189
|
template = templateChoice === "2" ? "crud" : "blank";
|
|
2132
2190
|
}
|
|
2133
|
-
if (
|
|
2191
|
+
if (fs5.existsSync(targetDir) && fs5.readdirSync(targetDir).length > 0) {
|
|
2134
2192
|
console.error(`Directory ${targetDir} is not empty.`);
|
|
2135
2193
|
process.exit(1);
|
|
2136
2194
|
}
|
|
2137
|
-
|
|
2138
|
-
|
|
2195
|
+
fs5.mkdirSync(path5.join(targetDir, "src/server"), { recursive: true });
|
|
2196
|
+
fs5.mkdirSync(path5.join(targetDir, "src/client"), { recursive: true });
|
|
2139
2197
|
let storage;
|
|
2140
2198
|
if (opts?.storage !== void 0) {
|
|
2141
2199
|
storage = opts.storage;
|
|
@@ -2160,7 +2218,10 @@ async function initApp(dir, opts) {
|
|
|
2160
2218
|
"@types/react": "^19.0.0",
|
|
2161
2219
|
"@types/react-dom": "^19.0.0",
|
|
2162
2220
|
"@vitejs/plugin-react": "^4.0.0",
|
|
2163
|
-
|
|
2221
|
+
// Floor must be a PUBLISHED version at scaffold time — an unpublished
|
|
2222
|
+
// pin fails the whole install (and with it drizzle-kit, vite, …).
|
|
2223
|
+
// Caret picks up newer releases automatically.
|
|
2224
|
+
clawnify: "^0.16.1",
|
|
2164
2225
|
"drizzle-kit": "^0.31.0",
|
|
2165
2226
|
tailwindcss: "^4.0.0",
|
|
2166
2227
|
// `vite build` only transpiles — it never typechecks — so without this the
|
|
@@ -2179,7 +2240,9 @@ async function initApp(dir, opts) {
|
|
|
2179
2240
|
// Referenced by the generated schema.ts comment and the starter UI, and
|
|
2180
2241
|
// run implicitly by `clawnify deploy`. It must exist as a script or
|
|
2181
2242
|
// following the app's own instructions fails with "Missing script".
|
|
2182
|
-
|
|
2243
|
+
// Delegates to the CLI, which materializes the managed drizzle config
|
|
2244
|
+
// in .clawnify/ before invoking drizzle-kit (lib/drizzle.ts).
|
|
2245
|
+
"db:generate": "clawnify db generate",
|
|
2183
2246
|
typecheck: "tsc --noEmit",
|
|
2184
2247
|
deploy: "clawnify deploy"
|
|
2185
2248
|
},
|
|
@@ -2273,14 +2336,6 @@ export const items = sqliteTable("items", {
|
|
|
2273
2336
|
name: text("name").notNull(),
|
|
2274
2337
|
createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),
|
|
2275
2338
|
});
|
|
2276
|
-
`);
|
|
2277
|
-
write(targetDir, "drizzle.config.ts", `import { defineConfig } from "drizzle-kit";
|
|
2278
|
-
|
|
2279
|
-
export default defineConfig({
|
|
2280
|
-
schema: "./src/server/schema.ts",
|
|
2281
|
-
out: "./.clawnify/drizzle",
|
|
2282
|
-
dialect: "sqlite",
|
|
2283
|
-
});
|
|
2284
2339
|
`);
|
|
2285
2340
|
if (storage) {
|
|
2286
2341
|
write(targetDir, "src/server/index.ts", `import { createApp } from "@clawnify/app";
|
|
@@ -2436,10 +2491,10 @@ createRoot(document.getElementById("app")!).render(
|
|
|
2436
2491
|
}
|
|
2437
2492
|
const pm = detectPackageManager();
|
|
2438
2493
|
console.log();
|
|
2439
|
-
console.log(` Created ${name} in ${
|
|
2494
|
+
console.log(` Created ${name} in ${path5.relative(process.cwd(), targetDir)}/`);
|
|
2440
2495
|
console.log();
|
|
2441
2496
|
console.log(" Get started:");
|
|
2442
|
-
console.log(` cd ${
|
|
2497
|
+
console.log(` cd ${path5.relative(process.cwd(), targetDir)}`);
|
|
2443
2498
|
console.log(` ${pm} install`);
|
|
2444
2499
|
console.log(` ${pm} ${pm === "npm" ? "run " : ""}dev # local dev at http://localhost:5173`);
|
|
2445
2500
|
console.log(` ${pm} ${pm === "npm" ? "run " : ""}deploy # deploy to production`);
|
|
@@ -2450,21 +2505,21 @@ async function initWebsite(dir, opts) {
|
|
|
2450
2505
|
const slug = slugify(name);
|
|
2451
2506
|
let targetDir;
|
|
2452
2507
|
if (dir) {
|
|
2453
|
-
targetDir =
|
|
2508
|
+
targetDir = path5.resolve(dir);
|
|
2454
2509
|
} else {
|
|
2455
2510
|
const ws = findWorkspaceRoot(process.cwd());
|
|
2456
|
-
targetDir = ws ?
|
|
2511
|
+
targetDir = ws ? path5.join(ws.dir, "website") : path5.resolve(slug);
|
|
2457
2512
|
}
|
|
2458
|
-
if (
|
|
2459
|
-
const entries =
|
|
2513
|
+
if (fs5.existsSync(targetDir)) {
|
|
2514
|
+
const entries = fs5.readdirSync(targetDir);
|
|
2460
2515
|
const onlyGitkeep = entries.length === 1 && entries[0] === ".gitkeep";
|
|
2461
2516
|
if (entries.length > 0 && !onlyGitkeep) {
|
|
2462
2517
|
console.error(`Directory ${targetDir} is not empty.`);
|
|
2463
2518
|
process.exit(1);
|
|
2464
2519
|
}
|
|
2465
|
-
if (onlyGitkeep)
|
|
2520
|
+
if (onlyGitkeep) fs5.rmSync(path5.join(targetDir, ".gitkeep"));
|
|
2466
2521
|
}
|
|
2467
|
-
|
|
2522
|
+
fs5.mkdirSync(targetDir, { recursive: true });
|
|
2468
2523
|
write(targetDir, "clawnify.json", JSON.stringify({
|
|
2469
2524
|
$schema: "https://app.clawnify.com/schema/v1/clawnify.json",
|
|
2470
2525
|
version: 1,
|
|
@@ -2574,10 +2629,10 @@ import BaseLayout from "../layouts/BaseLayout.astro";
|
|
|
2574
2629
|
</BaseLayout>
|
|
2575
2630
|
`);
|
|
2576
2631
|
console.log();
|
|
2577
|
-
console.log(` Created ${name} in ${
|
|
2632
|
+
console.log(` Created ${name} in ${path5.relative(process.cwd(), targetDir)}/`);
|
|
2578
2633
|
console.log();
|
|
2579
2634
|
console.log(" Get started:");
|
|
2580
|
-
console.log(` cd ${
|
|
2635
|
+
console.log(` cd ${path5.relative(process.cwd(), targetDir)}`);
|
|
2581
2636
|
console.log(" pnpm install");
|
|
2582
2637
|
console.log(" pnpm dev # local dev at http://localhost:4321");
|
|
2583
2638
|
console.log(" pnpm deploy # deploy as your org's website");
|
|
@@ -2585,17 +2640,17 @@ import BaseLayout from "../layouts/BaseLayout.astro";
|
|
|
2585
2640
|
}
|
|
2586
2641
|
async function initAgent(dir, opts) {
|
|
2587
2642
|
const yes = !!opts?.yes;
|
|
2588
|
-
const dirArgName = dir ?
|
|
2643
|
+
const dirArgName = dir ? path5.basename(path5.resolve(dir)) : void 0;
|
|
2589
2644
|
const name = opts?.name || (yes ? dirArgName ?? "my-agent" : await ask2("Agent name: ") || "my-agent");
|
|
2590
2645
|
const slug = slugify(name);
|
|
2591
2646
|
let targetDir;
|
|
2592
2647
|
if (dir) {
|
|
2593
|
-
targetDir =
|
|
2648
|
+
targetDir = path5.resolve(dir);
|
|
2594
2649
|
} else {
|
|
2595
2650
|
const ws = findWorkspaceRoot(process.cwd());
|
|
2596
|
-
targetDir = ws ?
|
|
2651
|
+
targetDir = ws ? path5.join(ws.dir, "agents", slug) : path5.resolve(slug);
|
|
2597
2652
|
}
|
|
2598
|
-
if (
|
|
2653
|
+
if (fs5.existsSync(targetDir) && fs5.readdirSync(targetDir).length > 0) {
|
|
2599
2654
|
console.error(`Directory ${targetDir} is not empty.`);
|
|
2600
2655
|
process.exit(1);
|
|
2601
2656
|
}
|
|
@@ -2635,7 +2690,7 @@ memories/
|
|
|
2635
2690
|
sessions/
|
|
2636
2691
|
logs/
|
|
2637
2692
|
`);
|
|
2638
|
-
const rel =
|
|
2693
|
+
const rel = path5.relative(process.cwd(), targetDir) || ".";
|
|
2639
2694
|
console.log();
|
|
2640
2695
|
console.log(` Created agent ${name} in ${rel}/`);
|
|
2641
2696
|
console.log();
|
|
@@ -2947,14 +3002,14 @@ export function App() {
|
|
|
2947
3002
|
`);
|
|
2948
3003
|
}
|
|
2949
3004
|
function write(dir, file, content) {
|
|
2950
|
-
const fullPath =
|
|
2951
|
-
|
|
2952
|
-
|
|
3005
|
+
const fullPath = path5.join(dir, file);
|
|
3006
|
+
fs5.mkdirSync(path5.dirname(fullPath), { recursive: true });
|
|
3007
|
+
fs5.writeFileSync(fullPath, content);
|
|
2953
3008
|
}
|
|
2954
3009
|
|
|
2955
3010
|
// src/commands/dev.ts
|
|
2956
|
-
import
|
|
2957
|
-
import
|
|
3011
|
+
import fs6 from "fs";
|
|
3012
|
+
import path6 from "path";
|
|
2958
3013
|
import { spawn as spawn2 } from "child_process";
|
|
2959
3014
|
function slugify2(name) {
|
|
2960
3015
|
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
|
|
@@ -2999,7 +3054,7 @@ function assertNodeVersion2() {
|
|
|
2999
3054
|
}
|
|
3000
3055
|
async function devCommand(dir, options) {
|
|
3001
3056
|
assertNodeVersion2();
|
|
3002
|
-
const resolvedDir = dir ?
|
|
3057
|
+
const resolvedDir = dir ? path6.resolve(dir) : process.cwd();
|
|
3003
3058
|
const manifest = readManifest(resolvedDir);
|
|
3004
3059
|
if (!manifest) {
|
|
3005
3060
|
console.error("No clawnify.json found. Run `clawnify init` first.");
|
|
@@ -3015,21 +3070,20 @@ async function devCommand(dir, options) {
|
|
|
3015
3070
|
const database = manifest.app.database !== false;
|
|
3016
3071
|
const storage = manifest.app.storage === true;
|
|
3017
3072
|
const apiPort = options?.port || "8787";
|
|
3018
|
-
const clawnifyDir =
|
|
3019
|
-
|
|
3020
|
-
const wranglerPath =
|
|
3021
|
-
|
|
3073
|
+
const clawnifyDir = path6.join(resolvedDir, ".clawnify");
|
|
3074
|
+
fs6.mkdirSync(clawnifyDir, { recursive: true });
|
|
3075
|
+
const wranglerPath = path6.join(clawnifyDir, "wrangler.toml");
|
|
3076
|
+
fs6.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
|
|
3022
3077
|
if (database) {
|
|
3023
|
-
const
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
await syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath);
|
|
3078
|
+
const drizzleConfigPath = ensureDrizzleConfig(resolvedDir);
|
|
3079
|
+
if (drizzleConfigPath) {
|
|
3080
|
+
await syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath, drizzleConfigPath);
|
|
3027
3081
|
} else {
|
|
3028
3082
|
const schemaCandidates = [
|
|
3029
|
-
|
|
3030
|
-
|
|
3083
|
+
path6.join(resolvedDir, "schema.sql"),
|
|
3084
|
+
path6.join(resolvedDir, "src/server/schema.sql")
|
|
3031
3085
|
];
|
|
3032
|
-
const schemaPath = schemaCandidates.find((p) =>
|
|
3086
|
+
const schemaPath = schemaCandidates.find((p) => fs6.existsSync(p));
|
|
3033
3087
|
if (schemaPath) {
|
|
3034
3088
|
await runQuiet(resolvedDir, "npx", [
|
|
3035
3089
|
"wrangler",
|
|
@@ -3131,9 +3185,9 @@ function runQuiet(cwd, cmd, args) {
|
|
|
3131
3185
|
});
|
|
3132
3186
|
});
|
|
3133
3187
|
}
|
|
3134
|
-
async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath) {
|
|
3188
|
+
async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath, drizzleConfigPath) {
|
|
3135
3189
|
try {
|
|
3136
|
-
await runQuiet(resolvedDir, "npx", ["drizzle-kit", "generate"]);
|
|
3190
|
+
await runQuiet(resolvedDir, "npx", ["drizzle-kit", "generate", `--config=${drizzleConfigPath}`]);
|
|
3137
3191
|
} catch (err) {
|
|
3138
3192
|
console.error(
|
|
3139
3193
|
` drizzle-kit generate failed. Is \`drizzle-kit\` in devDependencies?
|
|
@@ -3141,15 +3195,15 @@ async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath
|
|
|
3141
3195
|
);
|
|
3142
3196
|
throw err;
|
|
3143
3197
|
}
|
|
3144
|
-
const drizzleDir =
|
|
3145
|
-
if (!
|
|
3146
|
-
const sqlFiles =
|
|
3198
|
+
const drizzleDir = path6.join(clawnifyDir, "drizzle");
|
|
3199
|
+
if (!fs6.existsSync(drizzleDir)) return;
|
|
3200
|
+
const sqlFiles = fs6.readdirSync(drizzleDir).filter((name) => name.endsWith(".sql")).sort();
|
|
3147
3201
|
if (sqlFiles.length === 0) return;
|
|
3148
|
-
const appliedPath =
|
|
3202
|
+
const appliedPath = path6.join(clawnifyDir, "applied-migrations.json");
|
|
3149
3203
|
let applied = [];
|
|
3150
|
-
if (
|
|
3204
|
+
if (fs6.existsSync(appliedPath)) {
|
|
3151
3205
|
try {
|
|
3152
|
-
applied = JSON.parse(
|
|
3206
|
+
applied = JSON.parse(fs6.readFileSync(appliedPath, "utf8"));
|
|
3153
3207
|
if (!Array.isArray(applied)) applied = [];
|
|
3154
3208
|
} catch {
|
|
3155
3209
|
applied = [];
|
|
@@ -3158,7 +3212,7 @@ async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath
|
|
|
3158
3212
|
const appliedSet = new Set(applied);
|
|
3159
3213
|
for (const file of sqlFiles) {
|
|
3160
3214
|
if (appliedSet.has(file)) continue;
|
|
3161
|
-
const filePath =
|
|
3215
|
+
const filePath = path6.join(drizzleDir, file);
|
|
3162
3216
|
await runQuiet(resolvedDir, "npx", [
|
|
3163
3217
|
"wrangler",
|
|
3164
3218
|
"d1",
|
|
@@ -3170,11 +3224,39 @@ async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath
|
|
|
3170
3224
|
]);
|
|
3171
3225
|
applied.push(file);
|
|
3172
3226
|
}
|
|
3173
|
-
|
|
3227
|
+
fs6.writeFileSync(appliedPath, JSON.stringify(applied, null, 2) + "\n");
|
|
3228
|
+
}
|
|
3229
|
+
|
|
3230
|
+
// src/commands/db.ts
|
|
3231
|
+
import path7 from "path";
|
|
3232
|
+
import { spawn as spawn3 } from "child_process";
|
|
3233
|
+
async function dbGenerateCommand(dir) {
|
|
3234
|
+
const resolvedDir = dir ? path7.resolve(dir) : process.cwd();
|
|
3235
|
+
const configPath = ensureDrizzleConfig(resolvedDir);
|
|
3236
|
+
if (!configPath) {
|
|
3237
|
+
console.error(
|
|
3238
|
+
"No src/server/schema.ts here \u2014 nothing to generate.\n Drizzle apps define tables in src/server/schema.ts; apps without a\n database don't need this command."
|
|
3239
|
+
);
|
|
3240
|
+
process.exit(1);
|
|
3241
|
+
}
|
|
3242
|
+
const code = await new Promise((resolve) => {
|
|
3243
|
+
const proc = spawn3("npx", ["drizzle-kit", "generate", `--config=${configPath}`], {
|
|
3244
|
+
cwd: resolvedDir,
|
|
3245
|
+
stdio: "inherit",
|
|
3246
|
+
env: { ...process.env }
|
|
3247
|
+
});
|
|
3248
|
+
proc.on("exit", (c) => resolve(c ?? 1));
|
|
3249
|
+
proc.on("error", (err) => {
|
|
3250
|
+
console.error(`Could not run drizzle-kit: ${String(err).slice(0, 160)}`);
|
|
3251
|
+
resolve(1);
|
|
3252
|
+
});
|
|
3253
|
+
});
|
|
3254
|
+
if (code !== 0) process.exit(code);
|
|
3255
|
+
console.log(" \u2713 Migrations in .clawnify/drizzle/ (applied on the next dev/deploy)");
|
|
3174
3256
|
}
|
|
3175
3257
|
|
|
3176
3258
|
// src/commands/link.ts
|
|
3177
|
-
import
|
|
3259
|
+
import path8 from "path";
|
|
3178
3260
|
var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
3179
3261
|
async function findByAppId(orgs, appId) {
|
|
3180
3262
|
for (const org of orgs) {
|
|
@@ -3213,7 +3295,7 @@ async function findBySlug(orgs, slug) {
|
|
|
3213
3295
|
return null;
|
|
3214
3296
|
}
|
|
3215
3297
|
async function linkCommand(appIdOrSlug, options) {
|
|
3216
|
-
const dir = options?.dir ?
|
|
3298
|
+
const dir = options?.dir ? path8.resolve(options.dir) : process.cwd();
|
|
3217
3299
|
const orgs = await listMyOrgs();
|
|
3218
3300
|
if (orgs.length === 0) {
|
|
3219
3301
|
console.error("No organizations found. Run `clawnify login` first.");
|
|
@@ -3242,14 +3324,14 @@ async function linkCommand(appIdOrSlug, options) {
|
|
|
3242
3324
|
slug: matched.app.slug,
|
|
3243
3325
|
app_token: matched.app.app_token
|
|
3244
3326
|
});
|
|
3245
|
-
const rel =
|
|
3327
|
+
const rel = path8.relative(process.cwd(), dir) || ".";
|
|
3246
3328
|
console.log(` Linked ${matched.app.name} (${matched.app.slug}) in ${matched.org.name}`);
|
|
3247
3329
|
console.log(` Wrote ${rel}/.clawnify/project.json`);
|
|
3248
3330
|
console.log(` Run \`clawnify deploy\` to push the current source to this app.`);
|
|
3249
3331
|
}
|
|
3250
3332
|
|
|
3251
3333
|
// src/commands/pull.ts
|
|
3252
|
-
import
|
|
3334
|
+
import path9 from "path";
|
|
3253
3335
|
async function pullSchemaCommand(options) {
|
|
3254
3336
|
if (!options.from) {
|
|
3255
3337
|
console.error("Usage: clawnify pull schema --from <app-id-or-slug>");
|
|
@@ -3267,9 +3349,9 @@ async function pullSchemaCommand(options) {
|
|
|
3267
3349
|
console.error(`Failed to fetch schema: ${err.message}`);
|
|
3268
3350
|
process.exit(1);
|
|
3269
3351
|
}
|
|
3270
|
-
const targetPath =
|
|
3352
|
+
const targetPath = path9.resolve(options.out ?? "schema.sql");
|
|
3271
3353
|
const result = await writeSchema(targetPath, schema, { force: options.force });
|
|
3272
|
-
const rel =
|
|
3354
|
+
const rel = path9.relative(process.cwd(), result.path) || result.path;
|
|
3273
3355
|
switch (result.status) {
|
|
3274
3356
|
case "no-schema":
|
|
3275
3357
|
console.log(` ${ref.slug}: no schema.sql in R2 (pre-backfill app, or no database)`);
|
|
@@ -3431,8 +3513,8 @@ async function connectionsConnectCommand(id, opts) {
|
|
|
3431
3513
|
}
|
|
3432
3514
|
|
|
3433
3515
|
// src/commands/workspace.ts
|
|
3434
|
-
import
|
|
3435
|
-
import
|
|
3516
|
+
import fs7 from "fs";
|
|
3517
|
+
import path10 from "path";
|
|
3436
3518
|
function slugify3(name) {
|
|
3437
3519
|
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
|
|
3438
3520
|
}
|
|
@@ -3463,15 +3545,15 @@ async function resolveOrg(opts) {
|
|
|
3463
3545
|
process.exit(1);
|
|
3464
3546
|
}
|
|
3465
3547
|
function write2(dir, file, content) {
|
|
3466
|
-
const fullPath =
|
|
3467
|
-
|
|
3468
|
-
|
|
3548
|
+
const fullPath = path10.join(dir, file);
|
|
3549
|
+
fs7.mkdirSync(path10.dirname(fullPath), { recursive: true });
|
|
3550
|
+
fs7.writeFileSync(fullPath, content);
|
|
3469
3551
|
}
|
|
3470
3552
|
async function workspaceInitCommand(dir, opts) {
|
|
3471
3553
|
const org = await resolveOrg(opts);
|
|
3472
3554
|
const name = opts?.name || org.name;
|
|
3473
|
-
const targetDir = dir ?
|
|
3474
|
-
if (
|
|
3555
|
+
const targetDir = dir ? path10.resolve(dir) : path10.resolve(slugify3(org.slug));
|
|
3556
|
+
if (fs7.existsSync(targetDir) && fs7.readdirSync(targetDir).length > 0) {
|
|
3475
3557
|
console.error(`Directory ${targetDir} is not empty.`);
|
|
3476
3558
|
process.exit(1);
|
|
3477
3559
|
}
|
|
@@ -3542,7 +3624,7 @@ back under the same subdirs. See \`docs/internal/adr-company-monorepo.md\` \xA7
|
|
|
3542
3624
|
write2(targetDir, "apps/.gitkeep", "");
|
|
3543
3625
|
write2(targetDir, "agents/.gitkeep", "");
|
|
3544
3626
|
write2(targetDir, "website/.gitkeep", "");
|
|
3545
|
-
const rel =
|
|
3627
|
+
const rel = path10.relative(process.cwd(), targetDir) || ".";
|
|
3546
3628
|
console.log();
|
|
3547
3629
|
console.log(` Created workspace for ${org.name} (${org.slug}) in ${rel}/`);
|
|
3548
3630
|
console.log();
|
|
@@ -3737,7 +3819,7 @@ async function workspaceConnectCommand(opts) {
|
|
|
3737
3819
|
}
|
|
3738
3820
|
|
|
3739
3821
|
// src/commands/execute.ts
|
|
3740
|
-
import
|
|
3822
|
+
import fs8 from "fs";
|
|
3741
3823
|
|
|
3742
3824
|
// src/lib/mcp-client.ts
|
|
3743
3825
|
var MCP_URL = "https://mcp.clawnify.com/mcp";
|
|
@@ -3787,7 +3869,7 @@ async function executeCommand(file, options) {
|
|
|
3787
3869
|
code = options.code;
|
|
3788
3870
|
} else if (file) {
|
|
3789
3871
|
try {
|
|
3790
|
-
code =
|
|
3872
|
+
code = fs8.readFileSync(file, "utf-8");
|
|
3791
3873
|
} catch (err) {
|
|
3792
3874
|
process.stderr.write(`Failed to read ${file}: ${String(err)}
|
|
3793
3875
|
`);
|
|
@@ -3842,8 +3924,8 @@ async function docsCommand(slug, options) {
|
|
|
3842
3924
|
process.exit(1);
|
|
3843
3925
|
}
|
|
3844
3926
|
const caller = options.caller ?? "external";
|
|
3845
|
-
const
|
|
3846
|
-
const res = await fetch(DOCS_URL +
|
|
3927
|
+
const path12 = slug ? `/docs/${orgId}/${slug}.md?caller=${caller}` : `/docs/${orgId}/index.md`;
|
|
3928
|
+
const res = await fetch(DOCS_URL + path12, {
|
|
3847
3929
|
headers: {
|
|
3848
3930
|
authorization: "Bearer " + token
|
|
3849
3931
|
}
|
|
@@ -4037,17 +4119,17 @@ Valid: ${ALL_AGENTS.join(", ")}`
|
|
|
4037
4119
|
|
|
4038
4120
|
// src/commands/flows.ts
|
|
4039
4121
|
import { spawnSync } from "child_process";
|
|
4040
|
-
import
|
|
4122
|
+
import fs9 from "fs";
|
|
4041
4123
|
import os from "os";
|
|
4042
|
-
import
|
|
4124
|
+
import path11 from "path";
|
|
4043
4125
|
function flowFileName(name) {
|
|
4044
4126
|
return name.endsWith(".json") ? name : `${name}.json`;
|
|
4045
4127
|
}
|
|
4046
4128
|
function parseFlowFile(file) {
|
|
4047
|
-
const abs =
|
|
4129
|
+
const abs = path11.resolve(file);
|
|
4048
4130
|
let raw;
|
|
4049
4131
|
try {
|
|
4050
|
-
raw =
|
|
4132
|
+
raw = fs9.readFileSync(abs, "utf8");
|
|
4051
4133
|
} catch {
|
|
4052
4134
|
console.error(`Cannot read ${abs}.`);
|
|
4053
4135
|
process.exit(1);
|
|
@@ -4154,18 +4236,18 @@ async function flowsEditCommand(name, opts) {
|
|
|
4154
4236
|
} else {
|
|
4155
4237
|
const res = await api.get(`/servers/${serverId}/flows?name=${encodeURIComponent(flowFileName(name))}`);
|
|
4156
4238
|
const { flow: current } = await res.json();
|
|
4157
|
-
tmpDir =
|
|
4158
|
-
tmpFile =
|
|
4159
|
-
|
|
4239
|
+
tmpDir = fs9.mkdtempSync(path11.join(os.tmpdir(), "clawnify-flow-"));
|
|
4240
|
+
tmpFile = path11.join(tmpDir, flowFileName(name));
|
|
4241
|
+
fs9.writeFileSync(tmpFile, JSON.stringify(current, null, 2) + "\n");
|
|
4160
4242
|
const editor = process.env.VISUAL || process.env.EDITOR || "vi";
|
|
4161
4243
|
const result = spawnSync(`${editor} "${tmpFile}"`, { shell: true, stdio: "inherit" });
|
|
4162
4244
|
if (result.status !== 0) {
|
|
4163
4245
|
console.error(`Editor exited without saving \u2014 draft unchanged (kept at ${tmpFile}).`);
|
|
4164
4246
|
process.exit(1);
|
|
4165
4247
|
}
|
|
4166
|
-
const edited =
|
|
4248
|
+
const edited = fs9.readFileSync(tmpFile, "utf8");
|
|
4167
4249
|
if (edited === JSON.stringify(current, null, 2) + "\n") {
|
|
4168
|
-
|
|
4250
|
+
fs9.rmSync(tmpDir, { recursive: true, force: true });
|
|
4169
4251
|
console.log("No changes.");
|
|
4170
4252
|
return;
|
|
4171
4253
|
}
|
|
@@ -4182,7 +4264,7 @@ async function flowsEditCommand(name, opts) {
|
|
|
4182
4264
|
flow,
|
|
4183
4265
|
tmpFile ? `Draft unchanged \u2014 your edits are kept at ${tmpFile}; fix and re-save with: clawnify flows edit ${name} --file "${tmpFile}"` : void 0
|
|
4184
4266
|
);
|
|
4185
|
-
if (tmpDir)
|
|
4267
|
+
if (tmpDir) fs9.rmSync(tmpDir, { recursive: true, force: true });
|
|
4186
4268
|
console.log(
|
|
4187
4269
|
existing.published != null ? `Saved draft "${name}". Runs and triggers keep using v${existing.published} \u2014 publish to make this live: clawnify flows publish ${name}` : `Saved draft "${name}". This flow has no published version, so runs and triggers execute the draft as-is \u2014 cut v1 with: clawnify flows publish ${name}`
|
|
4188
4270
|
);
|
|
@@ -4225,6 +4307,8 @@ async function runCli() {
|
|
|
4225
4307
|
});
|
|
4226
4308
|
program.command("init [dir]").description("Scaffold a new Clawnify project (app, website, or agent)").option("--type <type>", "Project type: app, website, or agent (skips prompt)").option("--name <name>", "Project name (skips prompt)").option("--template <template>", "App template: blank or crud (apps only)").option("--storage", "Enable file uploads (R2) \u2014 apps only").option("-y, --yes", "Non-interactive: use all defaults (app, blank, no storage)").option("--no-ai-files", "Skip installing AI files (rules + skills + MCP) after scaffolding").action(initCommand);
|
|
4227
4309
|
program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
|
|
4310
|
+
const db = program.command("db").description("Database schema tooling");
|
|
4311
|
+
db.command("generate [dir]").description("Generate migration SQL from src/server/schema.ts (dev/deploy run this automatically)").action(dbGenerateCommand);
|
|
4228
4312
|
program.command("login").description("Authenticate with Clawnify").action(loginCommand);
|
|
4229
4313
|
program.command("deploy [dir]").description("Deploy an app, website, or agent to Clawnify").option("--from <repo>", "Deploy from a GitHub repo (owner/repo)").addOption(
|
|
4230
4314
|
new Option(
|
|
@@ -4297,4 +4381,4 @@ async function runCli() {
|
|
|
4297
4381
|
export {
|
|
4298
4382
|
runCli
|
|
4299
4383
|
};
|
|
4300
|
-
//# sourceMappingURL=cli-
|
|
4384
|
+
//# sourceMappingURL=cli-YR6BKMOT.js.map
|