clawnify 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-HOCFYU72.js → chunk-S2EOEZO7.js} +30 -11
- package/dist/chunk-S2EOEZO7.js.map +1 -0
- package/dist/{cli-K7BINKS7.js → cli-BBJGGLQP.js} +670 -79
- package/dist/cli-BBJGGLQP.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/{mcp-3JPAW35L.js → mcp-OSFATJGC.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-HOCFYU72.js.map +0 -1
- package/dist/cli-K7BINKS7.js.map +0 -1
- /package/dist/{mcp-3JPAW35L.js.map → mcp-OSFATJGC.js.map} +0 -0
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
readWorkspaceConfig,
|
|
19
19
|
saveAuth,
|
|
20
20
|
saveProject
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-S2EOEZO7.js";
|
|
22
22
|
|
|
23
23
|
// src/cli.ts
|
|
24
24
|
import { Command } from "commander";
|
|
@@ -515,6 +515,107 @@ async function deployWebsite(dir, options) {
|
|
|
515
515
|
);
|
|
516
516
|
}
|
|
517
517
|
}
|
|
518
|
+
function walkFiles(root, cb) {
|
|
519
|
+
if (!fs2.existsSync(root)) return;
|
|
520
|
+
const walk = (cur, prefix) => {
|
|
521
|
+
for (const name of fs2.readdirSync(cur)) {
|
|
522
|
+
const abs = path2.join(cur, name);
|
|
523
|
+
const rel = prefix ? `${prefix}/${name}` : name;
|
|
524
|
+
if (fs2.statSync(abs).isDirectory()) walk(abs, rel);
|
|
525
|
+
else cb(rel, abs);
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
walk(root, "");
|
|
529
|
+
}
|
|
530
|
+
function assembleAgentFiles(dir) {
|
|
531
|
+
const out = [];
|
|
532
|
+
const agentMd = path2.join(dir, "AGENT.md");
|
|
533
|
+
if (fs2.existsSync(agentMd)) {
|
|
534
|
+
out.push({ path: "AGENTS.md", content: fs2.readFileSync(agentMd, "utf8") });
|
|
535
|
+
}
|
|
536
|
+
walkFiles(path2.join(dir, "skills"), (rel, abs) => {
|
|
537
|
+
if (path2.basename(abs) === ".gitkeep") return;
|
|
538
|
+
out.push({ path: `skills/${rel}`, content: fs2.readFileSync(abs, "utf8") });
|
|
539
|
+
});
|
|
540
|
+
const flowsDir = path2.join(dir, "flows");
|
|
541
|
+
if (fs2.existsSync(flowsDir)) {
|
|
542
|
+
for (const name of fs2.readdirSync(flowsDir)) {
|
|
543
|
+
if (!name.endsWith(".json")) continue;
|
|
544
|
+
out.push({ path: `flows/${name}`, content: fs2.readFileSync(path2.join(flowsDir, name), "utf8") });
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
return out;
|
|
548
|
+
}
|
|
549
|
+
async function deployAgent(dir, options) {
|
|
550
|
+
const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
|
|
551
|
+
const linked = readProject(resolvedDir);
|
|
552
|
+
const serverId = options.server || linked?.server_id;
|
|
553
|
+
const agentName = options.agent || linked?.agent_name || "main";
|
|
554
|
+
if (!serverId) {
|
|
555
|
+
console.error(
|
|
556
|
+
`This agent isn't linked to a server yet.
|
|
557
|
+
Link it on first deploy:
|
|
558
|
+
clawnify deploy --server <server-id> --agent <name>
|
|
559
|
+
(agent defaults to "main" if omitted).`
|
|
560
|
+
);
|
|
561
|
+
process.exit(EXIT_USAGE);
|
|
562
|
+
}
|
|
563
|
+
const files = assembleAgentFiles(resolvedDir);
|
|
564
|
+
if (files.length === 0) {
|
|
565
|
+
console.error(
|
|
566
|
+
`Nothing to deploy \u2014 no AGENT.md, skills/, or flows/ found in ${resolvedDir}.`
|
|
567
|
+
);
|
|
568
|
+
process.exit(EXIT_USAGE);
|
|
569
|
+
}
|
|
570
|
+
let orgId;
|
|
571
|
+
if (options.org) {
|
|
572
|
+
const orgs = await listMyOrgs();
|
|
573
|
+
const match = orgs.find((o) => o.id === options.org || o.slug === options.org);
|
|
574
|
+
if (!match) {
|
|
575
|
+
console.error(
|
|
576
|
+
`No org matched "${options.org}". Available: ${orgs.map((o) => o.slug).join(", ")}`
|
|
577
|
+
);
|
|
578
|
+
process.exit(EXIT_USAGE);
|
|
579
|
+
}
|
|
580
|
+
orgId = match.id;
|
|
581
|
+
} else {
|
|
582
|
+
orgId = linked?.org_id || await workspaceOrgId(resolvedDir);
|
|
583
|
+
}
|
|
584
|
+
if (options.dryRun) {
|
|
585
|
+
console.log(`
|
|
586
|
+
Dry run \u2014 would deploy to server ${serverId}, agent "${agentName}"`);
|
|
587
|
+
for (const f of files) {
|
|
588
|
+
console.log(` ${f.path} (${Buffer.byteLength(f.content, "utf8")} bytes)`);
|
|
589
|
+
}
|
|
590
|
+
console.log();
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
console.log(`Deploying agent \u2192 server ${serverId}, agent "${agentName}"...`);
|
|
594
|
+
const res = await api.post(
|
|
595
|
+
`/servers/${serverId}/deploy-agent`,
|
|
596
|
+
{ agent: agentName, files },
|
|
597
|
+
{ orgId }
|
|
598
|
+
);
|
|
599
|
+
const data = await res.json().catch(() => ({}));
|
|
600
|
+
if (!res.ok) {
|
|
601
|
+
console.error(`Deploy failed: ${data.error || res.statusText}`);
|
|
602
|
+
process.exit(1);
|
|
603
|
+
}
|
|
604
|
+
saveProject(resolvedDir, {
|
|
605
|
+
kind: "agent",
|
|
606
|
+
org_id: orgId,
|
|
607
|
+
server_id: serverId,
|
|
608
|
+
agent_name: agentName
|
|
609
|
+
});
|
|
610
|
+
const written = data.written ?? [];
|
|
611
|
+
const rejected = (data.rejected ?? []).filter(Boolean);
|
|
612
|
+
console.log(`
|
|
613
|
+
\u2713 Deployed ${written.length} file(s) to agent "${agentName}".`);
|
|
614
|
+
if (rejected.length) {
|
|
615
|
+
console.log(` Skipped (outside the agent payload allowlist): ${rejected.join(", ")}`);
|
|
616
|
+
}
|
|
617
|
+
console.log();
|
|
618
|
+
}
|
|
518
619
|
async function deployCommand(dir, options = {}) {
|
|
519
620
|
assertNodeVersion();
|
|
520
621
|
if (!options.from) {
|
|
@@ -532,6 +633,9 @@ async function deployCommand(dir, options = {}) {
|
|
|
532
633
|
if (kind === "website") {
|
|
533
634
|
return deployWebsite(dir, options);
|
|
534
635
|
}
|
|
636
|
+
if (kind === "agent") {
|
|
637
|
+
return deployAgent(dir, options);
|
|
638
|
+
}
|
|
535
639
|
} catch (err) {
|
|
536
640
|
console.error(`${err.message}`);
|
|
537
641
|
process.exit(EXIT_USAGE);
|
|
@@ -759,6 +863,350 @@ async function logsCommand(appId) {
|
|
|
759
863
|
}
|
|
760
864
|
}
|
|
761
865
|
|
|
866
|
+
// src/lib/servers.ts
|
|
867
|
+
async function resolveServerId(explicit) {
|
|
868
|
+
if (explicit) return explicit;
|
|
869
|
+
const linked = readProject()?.server_id;
|
|
870
|
+
if (linked) return linked;
|
|
871
|
+
const res = await api.get("/servers");
|
|
872
|
+
if (!res.ok) {
|
|
873
|
+
console.error("Failed to list servers. Run `clawnify login` and try again.");
|
|
874
|
+
process.exit(1);
|
|
875
|
+
}
|
|
876
|
+
const { servers } = await res.json();
|
|
877
|
+
if (!servers || servers.length === 0) {
|
|
878
|
+
console.error(
|
|
879
|
+
"No agent server in this org yet. Provision one at https://app.clawnify.com."
|
|
880
|
+
);
|
|
881
|
+
process.exit(1);
|
|
882
|
+
}
|
|
883
|
+
if (servers.length === 1) return servers[0].id;
|
|
884
|
+
console.error(
|
|
885
|
+
"This org has multiple servers \u2014 pick one with --server <id> (or run `clawnify servers`):\n"
|
|
886
|
+
);
|
|
887
|
+
for (const s of servers) {
|
|
888
|
+
console.error(` ${s.id} ${s.name ?? "(unnamed)"} [${s.status}]`);
|
|
889
|
+
}
|
|
890
|
+
process.exit(1);
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// src/commands/sessions.ts
|
|
894
|
+
async function sessionsListCommand(opts) {
|
|
895
|
+
const serverId = await resolveServerId(opts.server);
|
|
896
|
+
const params = new URLSearchParams();
|
|
897
|
+
if (opts.agent) params.set("agentId", opts.agent);
|
|
898
|
+
if (opts.active) params.set("activeMinutes", opts.active);
|
|
899
|
+
if (opts.limit) params.set("limit", opts.limit);
|
|
900
|
+
const qs = params.toString();
|
|
901
|
+
const res = await api.get(`/servers/${serverId}/sessions${qs ? `?${qs}` : ""}`);
|
|
902
|
+
if (!res.ok) {
|
|
903
|
+
console.error(`Failed to list sessions (${res.status}).`);
|
|
904
|
+
process.exit(1);
|
|
905
|
+
}
|
|
906
|
+
const data = await res.json();
|
|
907
|
+
const sessions = data.sessions ?? [];
|
|
908
|
+
if (opts.json) {
|
|
909
|
+
console.log(JSON.stringify(data, null, 2));
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
if (sessions.length === 0) {
|
|
913
|
+
console.log("No sessions found.");
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
const agentW = Math.max(5, ...sessions.map((s) => (s.agentId ?? "").length));
|
|
917
|
+
const keyW = Math.max(3, ...sessions.map((s) => (s.key ?? "").length));
|
|
918
|
+
console.log(
|
|
919
|
+
`${"Agent".padEnd(agentW)} ${"Key".padEnd(keyW)} ${"Updated".padEnd(19)} Model`
|
|
920
|
+
);
|
|
921
|
+
console.log(
|
|
922
|
+
`${"\u2500".repeat(agentW)} ${"\u2500".repeat(keyW)} ${"\u2500".repeat(19)} ${"\u2500".repeat(20)}`
|
|
923
|
+
);
|
|
924
|
+
for (const s of sessions) {
|
|
925
|
+
const updated = (s.updatedAt ?? "").replace("T", " ").slice(0, 19);
|
|
926
|
+
console.log(
|
|
927
|
+
`${(s.agentId ?? "").padEnd(agentW)} ${(s.key ?? "").padEnd(keyW)} ${updated.padEnd(19)} ${s.model ?? ""}`
|
|
928
|
+
);
|
|
929
|
+
}
|
|
930
|
+
if (data.hasMore) {
|
|
931
|
+
console.log(
|
|
932
|
+
`
|
|
933
|
+
\u2026 more available \u2014 raise --limit (showing ${sessions.length}${data.totalCount ? ` of ${data.totalCount}` : ""}).`
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
async function sessionsHistoryCommand(key, opts) {
|
|
938
|
+
const serverId = await resolveServerId(opts.server);
|
|
939
|
+
const params = new URLSearchParams();
|
|
940
|
+
params.set("key", key);
|
|
941
|
+
if (opts.agent) params.set("agentId", opts.agent);
|
|
942
|
+
if (opts.limit) params.set("limit", opts.limit);
|
|
943
|
+
const res = await api.get(
|
|
944
|
+
`/servers/${serverId}/sessions/history?${params.toString()}`
|
|
945
|
+
);
|
|
946
|
+
if (!res.ok) {
|
|
947
|
+
if (res.status === 404) {
|
|
948
|
+
console.error(
|
|
949
|
+
`No session found for key "${key}". List sessions with \`clawnify sessions\`.`
|
|
950
|
+
);
|
|
951
|
+
} else {
|
|
952
|
+
console.error(`Failed to read session (${res.status}).`);
|
|
953
|
+
}
|
|
954
|
+
process.exit(1);
|
|
955
|
+
}
|
|
956
|
+
const data = await res.json();
|
|
957
|
+
if (opts.json) {
|
|
958
|
+
console.log(JSON.stringify(data, null, 2));
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
console.log(
|
|
962
|
+
`agent: ${data.agentId} key: ${data.key} session: ${data.sessionId ?? "?"}`
|
|
963
|
+
);
|
|
964
|
+
console.log(
|
|
965
|
+
`${data.entryCount} entr${data.entryCount === 1 ? "y" : "ies"}${data.hasMore ? ` (of ${data.totalLines}; raise --limit for more)` : ""}
|
|
966
|
+
`
|
|
967
|
+
);
|
|
968
|
+
for (const entry of data.entries) {
|
|
969
|
+
console.log(JSON.stringify(entry));
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// src/commands/agents.ts
|
|
974
|
+
import fs3 from "fs";
|
|
975
|
+
import path3 from "path";
|
|
976
|
+
async function agentsListCommand(opts) {
|
|
977
|
+
const serverId = await resolveServerId(opts.server);
|
|
978
|
+
const res = await api.get(`/servers/${serverId}/agents`);
|
|
979
|
+
if (!res.ok) {
|
|
980
|
+
console.error(`Failed to list agents (${res.status}).`);
|
|
981
|
+
process.exit(1);
|
|
982
|
+
}
|
|
983
|
+
const payload = await res.json();
|
|
984
|
+
const agents = Array.isArray(payload) ? payload : payload.agents;
|
|
985
|
+
if (!agents || agents.length === 0) {
|
|
986
|
+
console.log("No agents on this server.");
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
const idW = Math.max(2, ...agents.map((a) => (a.id ?? "").length));
|
|
990
|
+
const nameW = Math.max(4, ...agents.map((a) => (a.name ?? "").length));
|
|
991
|
+
console.log(`${"ID".padEnd(idW)} ${"Name".padEnd(nameW)} ${"Status".padEnd(8)} Sessions`);
|
|
992
|
+
console.log(`${"\u2500".repeat(idW)} ${"\u2500".repeat(nameW)} ${"\u2500".repeat(8)} ${"\u2500".repeat(8)}`);
|
|
993
|
+
for (const a of agents) {
|
|
994
|
+
console.log(
|
|
995
|
+
`${(a.id ?? "").padEnd(idW)} ${(a.name ?? "").padEnd(nameW)} ${(a.status ?? "").padEnd(8)} ${a.sessionCount ?? 0}`
|
|
996
|
+
);
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
async function agentsPullCommand(dir, opts) {
|
|
1000
|
+
const serverId = await resolveServerId(opts.server);
|
|
1001
|
+
const agent = opts.agent || "main";
|
|
1002
|
+
const res = await api.get(`/servers/${serverId}/agent-config?agent=${encodeURIComponent(agent)}`);
|
|
1003
|
+
if (!res.ok) {
|
|
1004
|
+
if (res.status === 404) console.error(`Agent "${agent}" not found on this server.`);
|
|
1005
|
+
else console.error(`Failed to read agent config (${res.status}).`);
|
|
1006
|
+
process.exit(1);
|
|
1007
|
+
}
|
|
1008
|
+
const { files } = await res.json();
|
|
1009
|
+
const target = dir ? path3.resolve(dir) : process.cwd();
|
|
1010
|
+
fs3.mkdirSync(target, { recursive: true });
|
|
1011
|
+
let written = 0;
|
|
1012
|
+
for (const f of files ?? []) {
|
|
1013
|
+
const norm = path3.posix.normalize(f.path);
|
|
1014
|
+
if (norm.startsWith("/") || norm.split("/").includes("..")) continue;
|
|
1015
|
+
const abs = path3.join(target, norm);
|
|
1016
|
+
fs3.mkdirSync(path3.dirname(abs), { recursive: true });
|
|
1017
|
+
fs3.writeFileSync(abs, f.content);
|
|
1018
|
+
written++;
|
|
1019
|
+
}
|
|
1020
|
+
const existing = readProject(target) ?? {};
|
|
1021
|
+
saveProject(target, { ...existing, kind: "agent", server_id: serverId, agent_name: agent });
|
|
1022
|
+
console.log(`Pulled ${written} file(s) for agent "${agent}" \u2192 ${target}`);
|
|
1023
|
+
console.log(`Edit AGENTS.md / skills / flows, then push: clawnify agents push${dir ? ` ${dir}` : ""}`);
|
|
1024
|
+
}
|
|
1025
|
+
async function agentsPushCommand(dir, opts) {
|
|
1026
|
+
const target = dir ? path3.resolve(dir) : process.cwd();
|
|
1027
|
+
const linked = readProject(target);
|
|
1028
|
+
const serverId = await resolveServerId(opts.server || linked?.server_id);
|
|
1029
|
+
const agent = opts.agent || linked?.agent_name || "main";
|
|
1030
|
+
const files = [];
|
|
1031
|
+
const add = (rel) => {
|
|
1032
|
+
try {
|
|
1033
|
+
files.push({ path: rel, content: fs3.readFileSync(path3.join(target, rel), "utf8") });
|
|
1034
|
+
} catch {
|
|
1035
|
+
}
|
|
1036
|
+
};
|
|
1037
|
+
add("AGENTS.md");
|
|
1038
|
+
const walk = (relDir) => {
|
|
1039
|
+
let names;
|
|
1040
|
+
try {
|
|
1041
|
+
names = fs3.readdirSync(path3.join(target, relDir));
|
|
1042
|
+
} catch {
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
for (const name of names) {
|
|
1046
|
+
const rel = `${relDir}/${name}`;
|
|
1047
|
+
let isDir = false;
|
|
1048
|
+
try {
|
|
1049
|
+
isDir = fs3.statSync(path3.join(target, rel)).isDirectory();
|
|
1050
|
+
} catch {
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1053
|
+
if (isDir) walk(rel);
|
|
1054
|
+
else add(rel);
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
walk("skills");
|
|
1058
|
+
let flowNames = [];
|
|
1059
|
+
try {
|
|
1060
|
+
flowNames = fs3.readdirSync(path3.join(target, "flows"));
|
|
1061
|
+
} catch {
|
|
1062
|
+
}
|
|
1063
|
+
for (const name of flowNames) if (name.endsWith(".json")) add(`flows/${name}`);
|
|
1064
|
+
if (files.length === 0) {
|
|
1065
|
+
console.error(`No agent files (AGENTS.md / skills / flows) found in ${target}. Run \`clawnify agents pull\` first.`);
|
|
1066
|
+
process.exit(1);
|
|
1067
|
+
}
|
|
1068
|
+
const res = await api.post(`/servers/${serverId}/deploy-agent`, { agent, files });
|
|
1069
|
+
if (!res.ok) {
|
|
1070
|
+
console.error(`Failed to push (${res.status}).`);
|
|
1071
|
+
process.exit(1);
|
|
1072
|
+
}
|
|
1073
|
+
console.log(
|
|
1074
|
+
`Pushed ${files.length} file(s) to agent "${agent}". Additive \u2014 the agent picks them up on its next session (no restart).`
|
|
1075
|
+
);
|
|
1076
|
+
}
|
|
1077
|
+
async function agentsSkillsCommand(agent, opts) {
|
|
1078
|
+
const serverId = await resolveServerId(opts.server);
|
|
1079
|
+
const who = agent || "main";
|
|
1080
|
+
const res = await api.get(`/servers/${serverId}/agent-skills?agent=${encodeURIComponent(who)}`);
|
|
1081
|
+
if (!res.ok) {
|
|
1082
|
+
if (res.status === 404) console.error(`Agent "${who}" not found on this server.`);
|
|
1083
|
+
else console.error(`Failed to read skills (${res.status}).`);
|
|
1084
|
+
process.exit(1);
|
|
1085
|
+
}
|
|
1086
|
+
const data = await res.json();
|
|
1087
|
+
console.log(JSON.stringify(data.skills, null, 2));
|
|
1088
|
+
}
|
|
1089
|
+
async function agentsGrantSkillCommand(skill, opts) {
|
|
1090
|
+
const serverId = await resolveServerId(opts.server);
|
|
1091
|
+
if (!opts.all && !opts.to) {
|
|
1092
|
+
console.error(
|
|
1093
|
+
"Specify who gets the skill: --to <agent> (one specialist) or --all (every agent on the box)."
|
|
1094
|
+
);
|
|
1095
|
+
process.exit(1);
|
|
1096
|
+
}
|
|
1097
|
+
const scope = opts.all ? "tree" : "agent";
|
|
1098
|
+
const payload = { skill, action: "grant", scope };
|
|
1099
|
+
if (scope === "agent") payload.slug = opts.to;
|
|
1100
|
+
const res = await api.post(`/servers/${serverId}/agent-skills`, payload);
|
|
1101
|
+
const data = await res.json().catch(() => ({}));
|
|
1102
|
+
if (!res.ok) {
|
|
1103
|
+
if (res.status === 404 && /source skill not found/i.test(data.error ?? "")) {
|
|
1104
|
+
console.error(
|
|
1105
|
+
`Skill "${skill}" isn't in the main agent's workspace, so there's nothing to grant yet.
|
|
1106
|
+
Author it first: clawnify agents pull ./main --agent main \u2192 add skills/${skill}/SKILL.md \u2192 clawnify agents push ./main`
|
|
1107
|
+
);
|
|
1108
|
+
} else {
|
|
1109
|
+
console.error(`Failed to grant skill (${res.status})${data.error ? `: ${data.error}` : ""}.`);
|
|
1110
|
+
}
|
|
1111
|
+
process.exit(1);
|
|
1112
|
+
}
|
|
1113
|
+
const who = opts.all ? "every agent (shared managed root; includes future agents)" : `agent "${opts.to}"`;
|
|
1114
|
+
console.log(`Granted skill "${skill}" to ${who}. Picked up on the agent's next session (no restart). Reversible.`);
|
|
1115
|
+
}
|
|
1116
|
+
async function agentsCreateCommand(slug, opts) {
|
|
1117
|
+
const serverId = await resolveServerId(opts.server);
|
|
1118
|
+
if (!opts.yes) {
|
|
1119
|
+
console.error(
|
|
1120
|
+
`This creates agent "${slug}" and RESTARTS the gateway (~20-40s), briefly interrupting every agent on the server.
|
|
1121
|
+
Re-run with --yes once the user has confirmed: clawnify agents create ${slug} --yes`
|
|
1122
|
+
);
|
|
1123
|
+
process.exit(1);
|
|
1124
|
+
}
|
|
1125
|
+
const payload = { slug };
|
|
1126
|
+
if (opts.name) payload.name = opts.name;
|
|
1127
|
+
if (opts.description) payload.description = opts.description;
|
|
1128
|
+
const res = await api.post(`/servers/${serverId}/agents`, payload);
|
|
1129
|
+
const data = await res.json().catch(() => ({}));
|
|
1130
|
+
if (!res.ok) {
|
|
1131
|
+
console.error(`Failed to create agent (${res.status})${data.error ? `: ${data.error}` : ""}.`);
|
|
1132
|
+
process.exit(1);
|
|
1133
|
+
}
|
|
1134
|
+
console.log(
|
|
1135
|
+
`Created agent "${slug}". The gateway was restarted and it onboards shortly. Author it with: clawnify agents pull ./${slug} --agent ${slug}`
|
|
1136
|
+
);
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
// src/commands/servers.ts
|
|
1140
|
+
async function serversListCommand() {
|
|
1141
|
+
const res = await api.get("/servers");
|
|
1142
|
+
if (!res.ok) {
|
|
1143
|
+
console.error(`Failed to list servers (${res.status}).`);
|
|
1144
|
+
process.exit(1);
|
|
1145
|
+
}
|
|
1146
|
+
const { servers } = await res.json();
|
|
1147
|
+
if (!servers || servers.length === 0) {
|
|
1148
|
+
console.log("No servers in this org yet. Provision one at https://app.clawnify.com.");
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
const idW = Math.max(2, ...servers.map((s) => s.id.length));
|
|
1152
|
+
const nameW = Math.max(4, ...servers.map((s) => (s.name ?? "").length));
|
|
1153
|
+
console.log(`${"ID".padEnd(idW)} ${"Name".padEnd(nameW)} ${"Status".padEnd(10)} Region`);
|
|
1154
|
+
console.log(`${"\u2500".repeat(idW)} ${"\u2500".repeat(nameW)} ${"\u2500".repeat(10)} ${"\u2500".repeat(10)}`);
|
|
1155
|
+
for (const s of servers) {
|
|
1156
|
+
console.log(
|
|
1157
|
+
`${s.id.padEnd(idW)} ${(s.name ?? "").padEnd(nameW)} ${s.status.padEnd(10)} ${s.region ?? ""}`
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
// src/commands/env.ts
|
|
1163
|
+
async function envSetCommand(key, value) {
|
|
1164
|
+
const res = await api.post("/settings/custom-keys", { key_name: key, key_value: value });
|
|
1165
|
+
const data = await res.json().catch(() => ({}));
|
|
1166
|
+
if (!res.ok) {
|
|
1167
|
+
console.error(`Failed to set ${key} (${res.status})${data.error ? `: ${data.error}` : ""}.`);
|
|
1168
|
+
process.exit(1);
|
|
1169
|
+
}
|
|
1170
|
+
console.log(`Set ${key} org-wide. The gateway restarts to apply \u2014 agents briefly reconnect.`);
|
|
1171
|
+
}
|
|
1172
|
+
async function envUnsetCommand(key) {
|
|
1173
|
+
const res = await api.del(`/settings/custom-keys/${encodeURIComponent(key)}`);
|
|
1174
|
+
if (!res.ok) {
|
|
1175
|
+
const data = await res.json().catch(() => ({}));
|
|
1176
|
+
console.error(`Failed to unset ${key} (${res.status})${data.error ? `: ${data.error}` : ""}.`);
|
|
1177
|
+
process.exit(1);
|
|
1178
|
+
}
|
|
1179
|
+
console.log(`Removed ${key} org-wide. The gateway restarts to apply.`);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// src/commands/api.ts
|
|
1183
|
+
async function apiCommand(path9, opts) {
|
|
1184
|
+
const method = (opts.method || (opts.data !== void 0 ? "POST" : "GET")).toUpperCase();
|
|
1185
|
+
let body;
|
|
1186
|
+
if (opts.data !== void 0) {
|
|
1187
|
+
try {
|
|
1188
|
+
body = JSON.parse(opts.data);
|
|
1189
|
+
} catch {
|
|
1190
|
+
console.error("-d/--data must be valid JSON.");
|
|
1191
|
+
process.exit(1);
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
const p = path9.startsWith("/") ? path9 : `/${path9}`;
|
|
1195
|
+
const res = await api.call(method, p, { body, orgId: opts.org });
|
|
1196
|
+
const text = await res.text();
|
|
1197
|
+
let out = text;
|
|
1198
|
+
try {
|
|
1199
|
+
out = JSON.stringify(JSON.parse(text), null, 2);
|
|
1200
|
+
} catch {
|
|
1201
|
+
}
|
|
1202
|
+
if (!res.ok) {
|
|
1203
|
+
console.error(`HTTP ${res.status}`);
|
|
1204
|
+
if (out) console.error(out);
|
|
1205
|
+
process.exit(1);
|
|
1206
|
+
}
|
|
1207
|
+
if (out) console.log(out);
|
|
1208
|
+
}
|
|
1209
|
+
|
|
762
1210
|
// src/commands/rm.ts
|
|
763
1211
|
import readline3 from "readline";
|
|
764
1212
|
async function rmCommand(appId) {
|
|
@@ -829,8 +1277,8 @@ async function whoamiCommand() {
|
|
|
829
1277
|
}
|
|
830
1278
|
|
|
831
1279
|
// src/commands/init.ts
|
|
832
|
-
import
|
|
833
|
-
import
|
|
1280
|
+
import fs4 from "fs";
|
|
1281
|
+
import path4 from "path";
|
|
834
1282
|
import readline4 from "readline";
|
|
835
1283
|
|
|
836
1284
|
// src/lib/skills/detect.ts
|
|
@@ -844,9 +1292,9 @@ var DETECTORS = [
|
|
|
844
1292
|
{ agent: "aider", markers: ["CONVENTIONS.md", ".aider.conf.yml"], target: "CONVENTIONS.md" }
|
|
845
1293
|
];
|
|
846
1294
|
function exists(cwd, name) {
|
|
847
|
-
const
|
|
1295
|
+
const path9 = join(cwd, name);
|
|
848
1296
|
try {
|
|
849
|
-
statSync(
|
|
1297
|
+
statSync(path9);
|
|
850
1298
|
return true;
|
|
851
1299
|
} catch {
|
|
852
1300
|
return false;
|
|
@@ -870,17 +1318,22 @@ function agentByName(name) {
|
|
|
870
1318
|
var ALL_AGENTS = DETECTORS.map((d) => d.agent);
|
|
871
1319
|
|
|
872
1320
|
// src/lib/skills/content.gen.ts
|
|
873
|
-
var CLI_VERSION = "0.
|
|
1321
|
+
var CLI_VERSION = "0.10.0";
|
|
874
1322
|
var BUNDLED_SKILLS = [
|
|
875
1323
|
{
|
|
876
1324
|
name: "build-a-clawnify-app",
|
|
877
|
-
description: "Author a Clawnify app end-to-end \u2014 the canonical Hono + React + Vite +
|
|
878
|
-
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 the patterns the platform expects.\n\n## TL;DR\n\n- **One stack.** Hono + React + Vite + tRPC + `@clawnify/db` (Drizzle)\n + Tailwind + shadcn/ui. Nothing else.\n- **Schema lives in `schema.ts`** (Drizzle DSL) \u2014 single source of\n truth. Never write SQL DDL by hand.\n- **Queries through `getDB`** \u2014 `import { getDB, eq } from\n "@clawnify/db"`. JSON columns auto-serialize.\n- **`clawnify.json`** declares framework, env, and public routes.\n Build emits `api.tools[]` from tRPC procedure meta.\n- **No `/mcp` endpoint.** The org\'s MCP gateway projects tools\n from the manifest.\n- **Identity flows via `X-Clawnify-*` headers** injected by the\n platform. Read them, don\'t fake them.\n\n## Stack rationale\n\nOne template, one set of decisions. Don\'t deviate unless the user has\nexplicitly asked.\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\n tailwind.config.ts\n components.json \u2190 shadcn/ui config\n index.html\n drizzle.config.ts \u2190 Points at src/server/schema.ts \u2192 outputs to .clawnify/drizzle\n .clawnify/ \u2190 CLI cache (gitignored)\n drizzle/ \u2190 drizzle-kit generate output \u2014 never hand-edit\n 0000_<name>.sql\n meta/\n applied-migrations.json \u2190 Local-D1 applied tracker\n wrangler.toml \u2190 Generated per-dev wrangler config\n src/\n server/\n index.ts \u2190 Hono entry \u2014 mounts the tRPC router\n schema.ts \u2190 Drizzle table definitions \u2014 THE schema\n router.ts \u2190 tRPC router with MCP-tagged procedures\n auth.ts \u2190 Read X-Clawnify-* identity headers\n env.d.ts \u2190 Worker bindings types\n client/\n main.tsx \u2190 React mount point\n app.tsx \u2190 Root component\n lib/\n trpc.ts \u2190 Typed tRPC client\n components/ \u2190 shadcn/ui + your components\n styles.css\n```\n\n## `schema.ts` \u2014 the only place tables exist\n\n```ts\n// src/server/schema.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## `drizzle.config.ts`\n\n```ts\nimport { defineConfig } from "drizzle-kit";\n\nexport default defineConfig({\n schema: "./src/server/schema.ts",\n out: "./.clawnify/drizzle",\n dialect: "sqlite",\n});\n```\n\nYou never run `drizzle-kit` manually. The CLI runs it for you:\n\n- **`clawnify dev`** \u2014 runs `drizzle-kit generate`, applies any new\n migrations to local D1 via `wrangler d1 execute --local`, tracks\n applied state in `.clawnify/applied-migrations.json` (idempotent\n on rerun).\n- **`clawnify deploy`** \u2014 same generate step, then auto-includes\n `.clawnify/drizzle/*.sql` in the upload tar (remapped to\n `drizzle/<name>` for the deploy pipeline, which applies them\n transactionally to the live and preview databases and records them\n in `__clawnify_migrations`).\n\nThe output dir (`.clawnify/drizzle/`) is gitignored. Migrations\nare derived artifacts, not source \u2014 never commit them, never edit\nthem. The single source of truth is `schema.ts`.\n\n## `src/server/index.ts` \u2014 Hono entry\n\n```ts\nimport { Hono } from "hono";\nimport { trpcServer } from "@hono/trpc-server";\nimport { appRouter } from "./router";\nimport { createContext } from "./auth";\n\nconst app = new Hono<{ Bindings: Env }>();\n\napp.use("/trpc/*", trpcServer({\n router: appRouter,\n createContext: (opts, c) => createContext(opts, c.env, c.req.raw),\n}));\n\n// SPA fallback \u2014 Vite-built static assets served by the platform\napp.notFound((c) => c.env.ASSETS.fetch(c.req.raw));\n\nexport default app;\n```\n\nThat\'s it. The Worker entry is thin. No MCP mounting, no inline\nroute handlers \u2014 tRPC owns the API surface.\n\n## `src/server/auth.ts` \u2014 identity from headers\n\n```ts\nimport type { Context } from "hono";\n\nexport interface User {\n id: string;\n orgId: string;\n email: string;\n caller: "user" | "agent" | "agent-browser" | "system";\n}\n\nexport function readUser(req: Request): User | null {\n const id = req.headers.get("X-Clawnify-User-Id");\n const orgId = req.headers.get("X-Clawnify-Org-Id");\n const email = req.headers.get("X-Clawnify-User-Email") ?? "";\n const caller = (req.headers.get("X-Clawnify-Caller") ?? "user") as User["caller"];\n if (!id || !orgId) return null;\n return { id, orgId, email, caller };\n}\n\nexport function createContext(_opts: unknown, env: Env, req: Request) {\n const user = readUser(req);\n return { env, user };\n}\n```\n\nTrust these headers \u2014 the platform strips client-supplied versions\nand reinjects authenticated ones at the perimeter. Never read\n`Authorization` or session cookies directly.\n\n## `src/server/router.ts` \u2014 tRPC procedures with MCP meta\n\n```ts\nimport { initTRPC } from "@trpc/server";\nimport { z } from "zod";\nimport { getDB, eq, desc, and } from "@clawnify/db";\nimport * as schema from "./schema";\nimport type { User } from "./auth";\n\nconst t = initTRPC.context<{ env: Env; user: User | null }>().create();\n\nconst authed = t.procedure.use(({ ctx, next }) => {\n if (!ctx.user) throw new Error("UNAUTHORIZED");\n return next({ ctx: { ...ctx, user: ctx.user } });\n});\n\nexport const appRouter = t.router({\n list_notes: authed\n .meta({ mcp: { name: "list_notes", description: "List the user\'s notes." } })\n .input(z.object({ limit: z.number().int().min(1).max(100).default(50) }))\n .output(z.array(z.object({\n id: z.number(),\n title: z.string(),\n body: z.string(),\n tags: z.array(z.string()),\n createdAt: z.string(),\n })))\n .query(async ({ ctx, input }) => {\n const db = getDB(ctx.env, { schema });\n return db\n .select()\n .from(schema.notes)\n .where(eq(schema.notes.orgId, ctx.user.orgId))\n .orderBy(desc(schema.notes.createdAt))\n .limit(input.limit);\n }),\n\n create_note: authed\n .meta({ mcp: { name: "create_note", description: "Create a new note." } })\n .input(z.object({\n title: z.string().min(1),\n body: z.string().default(""),\n tags: z.array(z.string()).default([]),\n }))\n .mutation(async ({ ctx, input }) => {\n const db = getDB(ctx.env, { schema });\n const [row] = await db\n .insert(schema.notes)\n .values({ ...input, orgId: ctx.user.orgId })\n .returning();\n return row;\n }),\n});\n\nexport type AppRouter = typeof appRouter;\n```\n\nPatterns to follow:\n- **Every state-mutating procedure** that an agent might want to\n call gets `.meta({ mcp: { name, description } })`. The build\n picks these up into `clawnify.json api.tools[]`. The Clawnify\n MCP gateway projects them as MCP tools.\n- **Auth via middleware** (`authed`). Never check headers inside\n a procedure body.\n- **Filter by `ctx.user.orgId`** on every query. No exceptions.\n- **Schema-validated input + output** with Zod. The output schema\n is what the agent sees as the tool\'s return shape.\n- **Procedure names are intent verbs** (`archive_old_notes`,\n `publish_post`), not REST resource shapes (`get_notes`,\n `update_note`). Tools describe what the agent wants to do.\n\n## `src/client` \u2014 React + tRPC + shadcn\n\n```tsx\n// src/client/lib/trpc.ts\nimport { createTRPCReact, httpBatchLink } from "@trpc/react-query";\nimport type { AppRouter } from "../../server/router";\n\nexport const trpc = createTRPCReact<AppRouter>();\nexport const trpcClient = trpc.createClient({\n links: [httpBatchLink({ url: "/trpc" })],\n});\n```\n\n```tsx\n// src/client/app.tsx\nimport { useState } from "react";\nimport { QueryClient, QueryClientProvider } from "@tanstack/react-query";\nimport { trpc, trpcClient } from "./lib/trpc";\nimport { Button } from "./components/ui/button";\n\nconst queryClient = new QueryClient();\n\nexport function App() {\n return (\n <trpc.Provider client={trpcClient} queryClient={queryClient}>\n <QueryClientProvider client={queryClient}>\n <NotesList />\n </QueryClientProvider>\n </trpc.Provider>\n );\n}\n\nfunction NotesList() {\n const notes = trpc.list_notes.useQuery({ limit: 50 });\n const create = trpc.create_note.useMutation({\n onSuccess: () => notes.refetch(),\n });\n const [title, setTitle] = useState("");\n\n return (\n <div>\n {notes.data?.map((n) => <div key={n.id}>{n.title}</div>)}\n <Button onClick={() => create.mutate({ title, body: "" })}>\n Add note\n </Button>\n </div>\n );\n}\n```\n\nThe same tRPC procedures power the agent (via MCP) and the UI (via\ntyped client). One backend, two front doors.\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.\nEither way, 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**, using the theme\'s `primary` token.\n Blue is reserved for links and focus rings; never a second accent.\n- **Status colors are muted pairs** (`success` on `success-tint`,\n etc.) \u2014 never pure-saturated fills.\n- **Dark mode comes from the theme tokens** \u2014 don\'t hand-pick dark\n colors.\n- **Stick to shadcn/ui primitives** styled by the theme. Don\'t\n install another component library or write a bespoke CSS system.\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 "icon": "icon.svg",\n "tags": ["productivity"],\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\nIf the app talks to third-party services the user has connected\n(ads platforms, CRMs, messaging), declare them too:\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- **Don\'t hand-edit `api.tools[]`** \u2014 generated at build from tRPC\n `.meta({ mcp: { ... } })` annotations.\n- **Public routes are the exception**, not the default. Every tRPC\n procedure is private (auth-required) unless you explicitly add a\n matching path to `public_routes`. Use only for webhooks, RSS,\n 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 is generated\n from `schema.ts` via drizzle-kit; no `schema.sql` to ship.\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## Migrations\n\nYou don\'t write migration SQL by hand. You don\'t even run a CLI\ncommand. The workflow is:\n\n1. Edit `src/server/schema.ts` to reflect the new shape.\n2. Restart `pnpm dev` (or it auto-restarts on save in some configs).\n\nThat\'s it. `clawnify dev` runs `drizzle-kit generate` under the\nhood, applies the diff to local D1, and tracks what\'s been applied\nin `.clawnify/applied-migrations.json` so reruns are no-ops.\n\nOn deploy, `clawnify deploy` does the same generate step, then the\ndeploy pipeline applies the migrations transactionally to the live\nand preview databases. Tracked in `__clawnify_migrations`.\n\nFor destructive changes (drop column, rename), Drizzle\'s generator\nemits the SQL; the agent should default to additive changes and\nonly do destructive ones when the user explicitly asks. Renames\nare risky on production data \u2014 prefer "add new column, backfill,\nswitch queries, drop old column" over a single-step rename.\n\n## What the agent must NOT do\n\n- Mount `/mcp` manually. The gateway projects tools from the\n manifest.\n- Author `schema.sql` by hand. Use `schema.ts`.\n- Author migration SQL by hand. The CLI runs `drizzle-kit generate`\n on dev + deploy. Never commit `drizzle/` or `.clawnify/drizzle/`.\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\n via Drizzle. The raw API has `json()` as a helper.\n- Bind tRPC procedures by REST resource shape (`get_user_by_id`).\n Use intent verbs (`onboard_user`, `archive_old_orders`).\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\n leak is the worst-class bug we can ship.\n- Read auth from `Authorization` / cookies / `Bearer` tokens. Use\n the `X-Clawnify-*` headers via `auth.ts`.\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.0` pulls it in transitively; only add it if\n you 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`, `sql`, `sqliteTable`, `text`, `integer`,\n etc. are all re-exported there). Drop to `drizzle-orm` directly\n only for things not re-exported.\n- Add `.meta({ mcp: { name, description } })` to every state-\n mutating procedure that the user\'s agent might want to call.\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\n publishing \u2014 the preview tier catches schema drift and\n type errors 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'
|
|
1325
|
+
description: "Author a Clawnify app end-to-end \u2014 the canonical Hono + React + Vite + @hono/zod-openapi + @clawnify/db (Drizzle) stack, schema.ts (typed queries) kept in sync with schema.sql (the DDL the deploy applies), OpenAPIHono routes (createRoute) that auto-generate an OpenAPI spec, and X-Clawnify-* identity headers. Use when building or modifying an app that deploys to the Clawnify platform.",
|
|
1326
|
+
content: '# Build a Clawnify app\n\nCanonical skill: how to author a Clawnify app end-to-end. Same content\nfor humans reading the docs and for AI coding agents injecting this as\ninstructions during an app build.\n\nIf you\'re an agent: this document is enough context to produce a\nworking app from scratch. Follow it literally. The patterns here\nare exactly what `clawnify init` scaffolds and what the platform\nexpects.\n\n## TL;DR\n\n- **One stack.** Hono + React + Vite + `@hono/zod-openapi` +\n `@clawnify/db` (Drizzle) + Tailwind v4. Nothing else.\n- **Schema lives in two files kept in sync** \u2014 `schema.ts` (Drizzle\n DSL, the typed view your queries use) and `schema.sql` (the DDL the\n deploy applies to your app\'s D1). Change one, change the other.\n- **Queries through `getDB`** \u2014 `import { getDB, eq } from\n "@clawnify/db"`. JSON columns auto-serialize.\n- **API routes are `OpenAPIHono` + `createRoute`** \u2014 Zod-validated\n request/response. `app.doc()` auto-generates the OpenAPI spec at\n `/api/openapi.json`. That spec *is* the tool surface.\n- **`clawnify.json`** declares framework, env, and public routes.\n There is no `api.tools[]` \u2014 the agent discovers and calls your\n endpoints by reading the live OpenAPI spec.\n- **Identity flows via `X-Clawnify-*` headers** injected by the\n platform. Read them, don\'t fake them.\n\n## Stack rationale\n\nOne template, one set of decisions. Don\'t deviate unless the user has\nexplicitly asked. `clawnify init` (type `app`) scaffolds either a\n`blank` template (one GET route + a page) or a `crud` template (a\ntable with list/create/update/delete + a form). Both share the exact\nsame stack below.\n\n## File layout\n\n```\nmy-app/\n clawnify.json \u2190 Manifest (validated against /schema/v1/clawnify.json)\n package.json\n tsconfig.json\n vite.config.ts \u2190 @vitejs/plugin-react + @tailwindcss/vite; proxies /api \u2192 :8787\n index.html\n .gitignore\n .clawnify/ \u2190 CLI cache (gitignored)\n wrangler.toml \u2190 Generated per-dev wrangler config\n src/\n server/\n index.ts \u2190 OpenAPIHono entry \u2014 mounts routes, serves /api/openapi.json\n routes.ts \u2190 OpenAPIHono + createRoute definitions \u2014 the API surface\n schema.ts \u2190 Drizzle table definitions (typed view for queries)\n schema.sql \u2190 canonical DDL the deploy applies \u2014 keep in sync with schema.ts\n worker-env.d.ts \u2190 Cloudflare Workers types reference\n uploads.ts \u2190 R2 helpers (only when storage is enabled)\n client/\n main.tsx \u2190 React mount point\n app.tsx \u2190 Root component (plain fetch against /api/*)\n index.css \u2190 @import "tailwindcss"\n```\n\n## Schema \u2014 `schema.ts` + `schema.sql`, kept in sync\n\nTwo files describe the same tables. `schema.ts` (Drizzle DSL) is the\ntyped view your queries compile against; `schema.sql` is the DDL the\ndeploy applies to your app\'s D1. **When you change one, update the\nother** \u2014 they must describe the same tables.\n\nThe scaffold\'s starter table (blank template):\n\n```ts\n// src/server/schema.ts\nimport { sqliteTable, text, integer } from "@clawnify/db";\n\nexport const items = sqliteTable("items", {\n id: integer("id").primaryKey({ autoIncrement: true }),\n name: text("name").notNull(),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n});\n```\n\nReal apps are multi-tenant. Every user-facing table carries an\n`org_id`, every query filters by it. JSON columns and indexes use the\nDrizzle DSL re-exported from `@clawnify/db`:\n\n```ts\nimport { sqliteTable, text, integer, index } from "@clawnify/db";\n\nexport const notes = sqliteTable(\n "notes",\n {\n id: integer("id").primaryKey({ autoIncrement: true }),\n orgId: text("org_id").notNull(), // ALWAYS filter by this in queries\n title: text("title").notNull(),\n body: text("body").notNull().default(""),\n tags: text("tags", { mode: "json" }).$type<string[]>().notNull().default([]),\n createdAt: text("created_at").notNull().$default(() => new Date().toISOString()),\n },\n (t) => ({\n byOrg: index("notes_by_org").on(t.orgId, t.createdAt),\n }),\n);\n```\n\nRules:\n- JSON columns: `text(col, { mode: "json" }).$type<T>()` \u2014 Drizzle\n serializes on write and parses on read.\n- Multi-tenancy: every user-facing table has `org_id`. Every query\n filters by it. No exceptions.\n- Identifiers: snake_case in SQL, camelCase in TS (Drizzle bridges).\n\n## `schema.sql` \u2014 the DDL the deploy applies\n\nAlongside `schema.ts`, keep a `schema.sql` describing the same tables.\nThis is the DDL applied to your app\'s database on deploy.\n\n```sql\n-- src/server/schema.sql (mirror of the schema.ts tables)\nCREATE TABLE IF NOT EXISTS notes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n org_id TEXT NOT NULL,\n title TEXT NOT NULL,\n body TEXT NOT NULL DEFAULT \'\',\n tags TEXT NOT NULL DEFAULT \'[]\', -- JSON column\n created_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS notes_by_org ON notes(org_id, created_at);\n```\n\nRules:\n- Always `CREATE TABLE IF NOT EXISTS` \u2014 the apply is additive and\n re-run-safe.\n- Add a new column with `ALTER TABLE <t> ADD COLUMN \u2026` at the **end** of\n `schema.sql`, and reflect it in `schema.ts`. The deploy adds it.\n- Deploys are **additive**: new tables and columns are added\n automatically. Destructive changes (dropping or retyping a column) are\n not applied automatically \u2014 do those deliberately, and never drop a\n table with user data unless explicitly asked.\n- **Never let `schema.ts` and `schema.sql` drift.** Change one, change\n the other \u2014 they must describe the same tables.\n\n## `src/server/index.ts` \u2014 the OpenAPIHono entry\n\n```ts\nimport { OpenAPIHono } from "@hono/zod-openapi";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.route("/", api);\n\napp.doc("/api/openapi.json", {\n openapi: "3.0.0",\n info: { title: "My app", version: "1.0.0" },\n});\n\nexport default app;\n```\n\nThe entry is thin: mount the routes, then `app.doc()` \u2014 that single\ncall generates a live OpenAPI 3.0 spec from your `createRoute`\ndefinitions and serves it at `/api/openapi.json`. You never write a\n`/openapi.json` handler by hand; the framework derives it.\n\nWhen storage (file uploads) is enabled, the entry also wires the R2\nbucket in a middleware before mounting routes:\n\n```ts\nimport { OpenAPIHono } from "@hono/zod-openapi";\nimport { initUploads } from "./uploads";\nimport api from "./routes";\n\ntype Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };\n\nconst app = new OpenAPIHono<Env>();\n\napp.use("*", async (c, next) => {\n initUploads(c.env.UPLOADS);\n await next();\n});\n\napp.route("/", api);\n\napp.doc("/api/openapi.json", {\n openapi: "3.0.0",\n info: { title: "My app", version: "1.0.0" },\n});\n\nexport default app;\n```\n\n## `src/server/routes.ts` \u2014 OpenAPIHono routes with `createRoute`\n\nEach endpoint is a `createRoute({ method, path, summary, request, responses })`\ndefinition paired with a handler via `api.openapi(route, handler)`.\nRequest bodies and params are Zod-validated (`c.req.valid("json")`,\n`c.req.valid("param")`); response shapes are declared with\n`.openapi("Name")` Zod schemas so they land in the generated spec.\n\nBlank template \u2014 one read route:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";\nimport { getDB, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n name: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\nexport default api;\n```\n\nCRUD template \u2014 the full list/create/update/delete surface:\n\n```ts\nimport { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";\nimport { getDB, eq, desc } from "@clawnify/db";\nimport * as schema from "./schema";\n\ntype Env = { Bindings: { DB: D1Database } };\nconst api = new OpenAPIHono<Env>();\n\nconst ItemSchema = z.object({\n id: z.number(),\n title: z.string(),\n status: z.string(),\n createdAt: z.string(),\n}).openapi("Item");\n\nconst CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");\nconst UpdateItemSchema = z.object({\n title: z.string().min(1).optional(),\n status: z.string().optional(),\n}).openapi("UpdateItem");\nconst IdParamSchema = z.object({ id: z.string() });\nconst OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");\n\napi.openapi(\n createRoute({\n method: "get",\n path: "/api/items",\n summary: "List items",\n responses: {\n 200: {\n description: "List of items",\n content: { "application/json": { schema: z.array(ItemSchema) } },\n },\n },\n }),\n async (c) => {\n const db = getDB(c.env, { schema });\n const items = await db\n .select()\n .from(schema.items)\n .orderBy(desc(schema.items.createdAt));\n return c.json(items);\n },\n);\n\napi.openapi(\n createRoute({\n method: "post",\n path: "/api/items",\n summary: "Create item",\n request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },\n responses: {\n 201: {\n description: "Created item",\n content: { "application/json": { schema: ItemSchema } },\n },\n },\n }),\n async (c) => {\n const { title } = c.req.valid("json");\n const db = getDB(c.env, { schema });\n const [row] = await db\n .insert(schema.items)\n .values({ title: title.trim() })\n .returning();\n return c.json(row, 201);\n },\n);\n\napi.openapi(\n createRoute({\n method: "patch",\n path: "/api/items/:id",\n summary: "Update item",\n request: {\n params: IdParamSchema,\n body: { content: { "application/json": { schema: UpdateItemSchema } } },\n },\n responses: {\n 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const body = c.req.valid("json");\n const patch: Partial<typeof schema.items.$inferInsert> = {};\n if (body.title !== undefined) patch.title = body.title;\n if (body.status !== undefined) patch.status = body.status;\n if (Object.keys(patch).length === 0) return c.json({ ok: false }, 400);\n const db = getDB(c.env, { schema });\n await db.update(schema.items).set(patch).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\napi.openapi(\n createRoute({\n method: "delete",\n path: "/api/items/:id",\n summary: "Delete item",\n request: { params: IdParamSchema },\n responses: {\n 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },\n },\n }),\n async (c) => {\n const { id } = c.req.valid("param");\n const db = getDB(c.env, { schema });\n await db.delete(schema.items).where(eq(schema.items.id, Number(id)));\n return c.json({ ok: true });\n },\n);\n\nexport default api;\n```\n\nPatterns to follow:\n- **Give every route a clear `summary`/`description`.** The generated\n OpenAPI spec is what the agent reads to decide which endpoint to\n call \u2014 a vague summary makes your endpoint invisible in practice.\n- **Validate input with Zod** via `request.body` / `request.params`\n and read it with `c.req.valid("json")` / `c.req.valid("param")`.\n Never parse `c.req.raw` by hand.\n- **Declare response shapes** with `.openapi("Name")` schemas \u2014 they\n become the documented return type in the spec.\n- **Filter by the org** on every user-facing query (see identity\n headers below). No exceptions.\n\n## `src/server` \u2014 reading identity headers\n\nThe scaffold\'s starter routes are single-tenant for brevity. Real\napps read the caller\'s identity from the `X-Clawnify-*` headers the\nplatform injects, using Hono\'s `c.req.header(...)` inside the handler:\n\n```ts\nconst orgId = c.req.header("X-Clawnify-Org-Id");\nif (!orgId) return c.json({ error: "unauthorized" }, 401);\nconst db = getDB(c.env, { schema });\nconst rows = await db\n .select()\n .from(schema.notes)\n .where(eq(schema.notes.orgId, orgId));\n```\n\nThe headers the platform injects (never set by the client \u2014 it strips\nclient-supplied versions and reinjects authenticated ones at the\nperimeter):\n\n| Header | Value |\n|--------|-------|\n| `X-Clawnify-User-Id` | Supabase user UUID |\n| `X-Clawnify-Org-Id` | Organization UUID |\n| `X-Clawnify-User-Email` | User email |\n| `X-Clawnify-Caller` | `user`, `agent`, `agent-browser`, or `system` |\n\nTrust these headers. Never read `Authorization`, `Bearer` tokens, or\nsession cookies directly.\n\n## `src/client` \u2014 React + plain fetch\n\nThe client mounts React and talks to the API with plain `fetch`\nagainst the `/api/*` routes. No data-layer library is scaffolded.\n\n```tsx\n// src/client/main.tsx\nimport { StrictMode } from "react";\nimport { createRoot } from "react-dom/client";\nimport { App } from "./app";\nimport "./index.css";\n\ncreateRoot(document.getElementById("app")!).render(\n <StrictMode>\n <App />\n </StrictMode>\n);\n```\n\n```tsx\n// src/client/app.tsx (CRUD template shape)\nimport { useState, useEffect } from "react";\n\ninterface Item {\n id: number;\n title: string;\n status: string;\n createdAt: string;\n}\n\nexport function App() {\n const [items, setItems] = useState<Item[]>([]);\n const [title, setTitle] = useState("");\n\n async function load() {\n const res = await fetch("/api/items");\n setItems(await res.json());\n }\n\n useEffect(() => { load(); }, []);\n\n async function addItem(e: React.FormEvent) {\n e.preventDefault();\n if (!title.trim()) return;\n await fetch("/api/items", {\n method: "POST",\n headers: { "Content-Type": "application/json" },\n body: JSON.stringify({ title }),\n });\n setTitle("");\n load();\n }\n\n // ...toggleStatus / deleteItem call PATCH/DELETE the same way.\n\n return (\n <div className="max-w-xl mx-auto mt-10 px-4">\n {/* form + list */}\n </div>\n );\n}\n```\n\nIn local dev, Vite proxies `/api` to the Worker on `:8787` (see\n`vite.config.ts`), so the same relative fetch paths work in dev and\nin production. The API is the one contract: the UI calls it over\n`fetch`, and the agent calls it over the OpenAPI spec.\n\n## Design\n\nIf the project contains a `DESIGN.md`, it is the single source of\ntruth for visuals \u2014 follow its tokens, don\'t restyle around it. The\nscaffold ships Tailwind v4 (via `@tailwindcss/vite`, imported with\n`@import "tailwindcss";` in `index.css`) and nothing else \u2014 no\ncomponent library. The rules every Clawnify app follows:\n\n- **Neutral chrome.** White canvas and surfaces, one text ramp\n (foreground \u2192 muted \u2192 faint), hairline borders. Color is for\n meaning, not decoration.\n- **One primary CTA per screen.** Blue is reserved for links and\n focus rings; never a second accent.\n- **Status colors are muted pairs** \u2014 never pure-saturated fills.\n- **Style with Tailwind utilities.** Don\'t install another component\n library or write a bespoke CSS system unless the user asks.\n- **Sizes in rem**, so browser zoom and font settings are respected.\n\n## `clawnify.json` \u2014 the manifest\n\n```json\n{\n "$schema": "https://app.clawnify.com/schema/v1/clawnify.json",\n "version": 1,\n "name": "Notes",\n "description": "Take and organize notes. Searchable by tag.",\n "app": {\n "framework": "react+hono",\n "database": true,\n "storage": false\n },\n "env": {\n "optional": ["OPENROUTER_API_KEY"]\n },\n "api": {\n "public_routes": [\n { "path": "/api/feed", "methods": ["GET"] }\n ]\n }\n}\n```\n\n`clawnify init` writes the minimal form:\n`{ app: { framework: "react+hono", database: true, storage } }`. Add\nthe rest as needed.\n\nIf the app talks to third-party services the user has connected\n(ads platforms, CRMs, messaging), declare them:\n\n```json\n{ "app": { "credentials": ["metaads", "googleads"] } }\n```\n\nGet the ids and names from `clawnify connections list` \u2014 see the\nnaming rule below.\n\n`env` supports `required` (deploy warns if missing), `optional`\n(injected when available), and `oneOf` (at least one per group).\n\nRules:\n- **There is no `api.tools[]`.** The manifest\'s `api` object only\n accepts `public_routes` and `automation_bypass`. Your API surface\n is discovered from the generated OpenAPI spec, not a hand-authored\n tools list (see the next section).\n- **Public routes are the exception**, not the default. Every route\n is behind the Clawnify perimeter (auth-required) unless you\n explicitly add a matching path to `api.public_routes`. Use only for\n webhooks, RSS, embedded feeds.\n- **`framework: "react+hono"`** for new apps. Never `preact+hono` or\n `vite-preact` \u2014 those are legacy.\n- **`database: true`** if the app uses a DB. Ship both `schema.ts`\n (typed) and `schema.sql` (the applied DDL), kept in sync.\n\n## How the agent reaches your API (no `api.tools[]`)\n\nThe old tRPC stack emitted an `api.tools[]` array from procedure meta.\nThat mechanism is gone. Today the flow is:\n\n1. Your `createRoute` definitions + `app.doc("/api/openapi.json", \u2026)`\n auto-generate a live OpenAPI 3.0 spec.\n2. The user\'s agent calls the platform\'s built-in tools \u2014\n `get_app_openapi` (fetch the app\'s OpenAPI JSON) and `call_app_api`\n (invoke a `method` + `path` on the live app) \u2014 to discover and\n drive your endpoints. No per-app MCP registration, no manifest\n tools array.\n\nSo you make an endpoint "agent-callable" simply by shipping it with a\nclear `summary`/`description` and Zod-typed request/response. The\nricher and clearer the spec, the more reliably the agent uses it.\n\n## Connections & secrets \u2014 `@clawnify/connections`\n\n**The naming rule \u2014 never invent an identifier.** Before declaring\n`credentials` or env names, run `clawnify connections list`: it shows\nthe org\'s canonical integration ids (`googleads`, never `google_ads`),\nthe fixed provider-key names (`OPENROUTER_API_KEY`, never\n`OPENROUTER_KEY`), and custom env vars already defined \u2014 each with\nconnected/set state. Reuse those exact identifiers; a misspelled one\ndoesn\'t fail the build, it silently resolves to nothing at runtime. If\nyou need a custom secret that isn\'t listed, pick a clear name and tell\nthe user to set it in the dashboard.\n\nIf the app needs a third-party service or a provider API key, use\nthe `@clawnify/connections` SDK. Never read credential bindings\ndirectly, never paste API keys, never hardcode a token or endpoint.\n\n```ts\nimport { connect, secret, describe, searchActions } from "@clawnify/connections";\n\n// A connected integration:\nconst meta = connect("metaads", env);\nconst accounts = await meta.adAccounts("name,currency");\n\n// A provider key the user supplied (null if absent):\nconst key = secret("OPENROUTER_API_KEY", env);\n\n// What\'s wired vs missing \u2014 drive your setup/empty state from this:\nconst status = await describe(env, undefined, REQUIRES);\n```\n\nHow to call a connected service \u2014 the mistake that silently breaks\nintegration apps, so get it right:\n\n- **Prefer the typed client\'s semantic methods** where they exist\n (`meta.adAccounts(...)`, `googleads.query(gaql)`).\n- **For anything else, discover and run an action:**\n ```ts\n const [best] = await searchActions("list google ads campaigns", env);\n const data = await connect(best.service, env).run(best.slug, body);\n ```\n- Some integrations also expose a raw REST client\n (`connect("bird", env).get("/path")`) \u2014 but if `.get()`/`.post()`\n throws for a service, that service only supports semantic methods\n and `run()`. When unsure, use `run()`.\n- **Need exact paths/arguments for a raw-REST provider?** Some carry\n a `spec_url` (the provider\'s published OpenAPI spec) \u2014\n `clawnify connections list --json` shows it. Download and query it \u2014\n `curl -s <spec_url> -o spec.json && jq \'.paths | keys\' spec.json` \u2014\n never read a whole spec into context (they run to 10+ MB).\n- **Never fall back to raw `fetch`** against a provider API, and\n never invent endpoints or guess tokens.\n\n**The one exception \u2014 a service we don\'t support at all.** If a\nprovider isn\'t in the connections registry (nothing to `connect()`\nto, and `clawnify connections list` doesn\'t show it), the sanctioned\npath *is* a raw call with a user-supplied key: declare the key(s) it\nneeds in `clawnify.json` `env` (`required`/`optional`/`oneOf`), tell\nthe user to set them in the dashboard, read them with\n`secret("THAT_KEY", env)`, and `fetch` the provider\'s documented\nendpoints directly. This is the escape hatch for the long tail of\nintegrations we don\'t model yet \u2014 it does **not** apply to a service\nwe *do* support (use `connect()` / `run()` for those, always). Keep\nthe endpoint and token server-side, never in the client bundle.\n\nBuild a `describe()`-driven setup state instead of assuming\nconnections exist \u2014 show the user what\'s missing and where to\nconnect it.\n\n## Scheduling & deferred work \u2014 the managed queue\n\nA deployed app **cannot bind Cloudflare Queues, Durable Objects, or cron\ntriggers** (the platform builds every app with a fixed binding set: `DB` +\n`ASSETS` + `UPLOADS`). To run work later \u2014 a scheduled publish, a reminder, a\nretry, a "do this in 10 minutes" \u2014 use the **Clawnify managed queue service**\nover HTTP. It owns the clock, retries, and at-least-once delivery, then calls an\nendpoint on *your own app* back at the scheduled time.\n\nIt\'s a thin seam over a platform primitive, same shape as `@clawnify/db` /\n`@clawnify/connections` (a `@clawnify/queue` package is coming; inline the seam\nuntil then). Auth is the build-injected `env.CLAWNIFY_TOKEN`; with no token\n(local dev) the seam degrades to a no-op.\n\n**Enqueue** a deferred call to your own endpoint:\n\n```ts\n// POST https://services.clawnify.com/queue/enqueue (Bearer CLAWNIFY_TOKEN)\nconst res = await fetch("https://services.clawnify.com/queue/enqueue", {\n method: "POST",\n headers: { Authorization: `Bearer ${env.CLAWNIFY_TOKEN}`, "Content-Type": "application/json" },\n body: JSON.stringify({\n target_url: `${origin}/api/internal/publish`, // an endpoint on THIS app\n payload: { post_id: id }, // echoed back to you on fire\n run_at: new Date(whenMs).toISOString(),\n idempotency_key: `post:${id}:${whenMs}`, // same key dedupes; new time = new job\n }),\n});\nconst { job_id } = await res.json(); // store it to cancel/reschedule\n```\n\nPersist `job_id` on the row (e.g. `posts.queue_job_id`). **Cancel / reschedule**:\n`DELETE https://services.clawnify.com/queue/jobs/{job_id}` (Bearer token);\nreschedule = cancel + a fresh enqueue.\n\n**The callback endpoint is a public, signature-verified route.** The queue calls\n`target_url` from outside the perimeter, so the endpoint must be declared in\n`clawnify.json` `public_routes` **and** verify the delivery signature itself \u2014\nthe signature *is* its auth (never trust an unsigned call):\n\n```jsonc\n// clawnify.json\n"api": { "public_routes": [ { "path": "/api/internal/publish", "methods": ["POST"] } ] }\n```\n\nDeliveries are signed with the platform\'s **ECDSA P-256 (ES256)** key,\nStripe-style over `${timestamp}.${rawBody}`, verified against\n`https://services.clawnify.com/.well-known/jwks.json` (public key \u2014 nothing\nbreaks on token rotation). Read the raw body, check the signature + a timestamp\ntolerance (~5 min) before doing anything:\n\n```ts\napp.post("/api/internal/publish", async (c) => {\n const raw = await c.req.text();\n const ok = await verifyDelivery(raw, {\n signature: c.req.header("x-clawnify-signature"),\n timestamp: c.req.header("x-clawnify-timestamp"),\n keyId: c.req.header("x-clawnify-key-id"),\n });\n if (!ok) return c.json({ error: "bad signature" }, 401);\n const { post_id } = JSON.parse(raw);\n // \u2026do the deferred work (short: it\'s one normal Worker invocation)\u2026\n return c.json({ ok: true });\n});\n```\n\nEach fire is a normal Worker request \u2014 size the work to one invocation (publish a\npost, send a digest). For long compute *now* (not deferred), hold the request\nopen and return when done; don\'t fire-and-forget past the response.\n\n## Migrations\n\nKeep `schema.ts` and `schema.sql` in sync by hand. The workflow is:\n\n1. Edit `src/server/schema.ts` for the new shape (types + queries).\n2. Make the matching edit in `src/server/schema.sql` \u2014 a new\n `CREATE TABLE IF NOT EXISTS`, or `ALTER TABLE \u2026 ADD COLUMN \u2026` at the\n **end** of the file for a new column.\n3. Run `clawnify dev` locally, then `clawnify deploy`.\n\nOn deploy your schema changes are applied to the app\'s database \u2014 new\ntables and columns are added automatically.\n\nDestructive changes (drop column, rename) are not applied automatically;\ndo them deliberately, and only when the user explicitly asks. Renames\nare risky on production data \u2014 prefer "add new column, backfill, switch\nqueries, drop old column" over a single-step rename.\n\n## What the agent must NOT do\n\n- Author a `/openapi.json` handler by hand. `app.doc("/api/openapi.json", \u2026)`\n generates it from your `createRoute` definitions.\n- Let `schema.ts` and `schema.sql` drift. They describe the same\n tables \u2014 change both, every time.\n- Hand-author migration SQL files. Make schema changes in `schema.sql`\n (and mirror them in `schema.ts`); the deploy applies them.\n- Invent an `api.tools[]` array in the manifest. It isn\'t a valid\n field \u2014 the OpenAPI spec is the tool surface.\n- Use `JSON.stringify` on query params. JSON columns auto-serialize\n via Drizzle. The raw SQL API has `json()` as a helper.\n- Skip the `org_id` filter on a user-facing query. Multi-tenant\n leak is the worst-class bug we can ship.\n- Read auth from `Authorization` / cookies / `Bearer` tokens. Use\n the `X-Clawnify-*` headers via `c.req.header(...)`.\n- Call third-party APIs with raw `fetch` or hardcoded tokens. Go\n through `@clawnify/connections` (`connect` / `secret` / `run`).\n- Install `drizzle-orm` as a separate top-level dependency.\n `@clawnify/db@^0.4.1` pulls it in transitively; only add it if you\n need to pin a specific version (rare).\n\n## What the agent SHOULD do\n\n- Import everything from `@clawnify/db` where possible\n (`getDB`, `eq`, `and`, `desc`, `sql`, `sqliteTable`, `text`,\n `integer`, `index`, etc. are all re-exported there). Drop to\n `drizzle-orm` directly only for things not re-exported.\n- Give every route a clear `summary`/`description` and Zod-typed\n request/response so the agent can discover and call it via the\n OpenAPI spec.\n- Test on the draft URL (`<slug>.draft.clawnify.com`) before\n publishing \u2014 the preview tier catches schema drift and type errors\n at build time.\n- When unsure about a Drizzle pattern, check the `@clawnify/db`\n README for the current API + version notes.\n\n## Schema-as-data exception\n\nApps that let END users define data shapes at runtime (CMS, no-code\ntable editor) can\'t model their schema in `schema.ts` \u2014 the table\ndefinitions live in rows. Those apps fall back to the raw SQL API\nfrom `@clawnify/db` (`query`, `get`, `run`, `json`). Open-cms is\nthe canonical example.\n\nIf you\'re building this kind of app, you still use Drizzle\'s\n`schema.ts` for the **registry** tables (content types, field\ndefinitions). Only the dynamically-spawned per-collection tables\nneed raw SQL. See open-cms\'s `src/server/schema-sync.ts` for the\nruntime DDL pattern.\n'
|
|
879
1327
|
},
|
|
880
1328
|
{
|
|
881
1329
|
name: "use-the-clawnify-cli",
|
|
882
1330
|
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.",
|
|
883
|
-
content: "# Use the Clawnify CLI\n\nCanonical skill: how to drive the `clawnify` CLI. Same content for\nhumans and for AI coding agents operating a terminal.\n\nFor **authoring app code** (stack, schema, tRPC patterns), use the\n`build-a-clawnify-app` skill \u2014 this one covers the tooling around it.\n\n## TL;DR\n\n```bash\nnpm i -g clawnify # or: npx clawnify@latest <command>\nclawnify login # browser sign-in, paste-code fallback\nclawnify init my-app # scaffold an app or website\ncd my-app && clawnify dev\nclawnify deploy # \u2192 https://<slug>.apps.clawnify.com\n```\n\n- **Auth once, org lazily.** `login` only signs you in; the first\n command that needs an organization asks once and remembers it.\n- **A directory links to one app.** `deploy` from a linked directory\n updates that app; `clawnify link <id-or-slug>` adopts an existing one.\n- **Non-interactive flags exist for every prompt** \u2014 use them in\n scripts and CI (`-y`, `--update-existing`, `--create-new`, `--org`).\n\n## Authenticate\n\n```bash\nclawnify login # opens the browser; also prints the sign-in URL\nclawnify whoami # current user, active org (if linked)\n```\n\n`login` works from any browser: if the browser runs on the same\nmachine, sign-in completes automatically; otherwise the page shows a\ncode to paste back at the `Paste code here if prompted >` prompt\n(useful over SSH \u2014 no port forwarding needed).\n\n### Organizations\n\nYou belong to one or more orgs; apps live inside an org.\n\n```bash\nclawnify org list # orgs you belong to (* marks active)\nclawnify org use <slug-or-id> # switch the active org\n```\n\nNo need to pick one up front \u2014 the first org-scoped command prompts\nonce and persists the choice. Any single command can override with\n`--org <slug-or-id>`.\n\n## Create and run locally\n\n```bash\nclawnify init [dir] # interactive: app or website\nclawnify init my-app -y # non-interactive defaults (blank app)\nclawnify init --type app --template crud --name my-app\nclawnify init --type website --name my-site\nclawnify dev [dir] [--port 8787] # local dev server\n```\n\n`init` also installs AI files (rules + skills + MCP config) for any\ncoding agents detected in the project; skip with `--no-ai-files`.\n\n## Deploy\n\n```bash\nclawnify deploy # deploy the current directory\nclawnify deploy path/to/app\nclawnify deploy --from owner/repo # deploy straight from GitHub\nclawnify deploy --from owner/repo --path apps/web # monorepo subdir\nclawnify deploy --dry-run # list files that would upload\n```\n\nFirst deploy creates the app and links the directory (writes a local\nproject file); later deploys update the same app. On a slug conflict\nyou'll be asked \u2014 or decide up front:\n\n```bash\nclawnify deploy -y # reuse/update the existing app\nclawnify deploy --update-existing # same, explicit\nclawnify deploy --create-new # take the suggested new slug\n```\n\nLink an existing deployed app to the current directory instead of\ncreating a new one:\n\n```bash\nclawnify link <app-id-or-slug>\n```\n\n## Inspect and manage deployed apps\n\n```bash\nclawnify ls # list deployed apps in the active org\nclawnify logs <app-id> # build logs\nclawnify open <slug> # open the live app in the browser\nclawnify rm <app-id> # delete an app\nclawnify pull schema --from <app-id-or-slug> # fetch live schema.sql\nclawnify docs [slug] # usage README for an app (org index if omitted)\n```\n\n`pull schema` refuses to clobber local uncommitted changes unless you\npass `--force`.\n\n## Connections & env names\n\n```bash\nclawnify connections list
|
|
1331
|
+
content: "# Use the Clawnify CLI\n\nCanonical skill: how to drive the `clawnify` CLI. Same content for\nhumans and for AI coding agents operating a terminal.\n\nFor **authoring app code** (stack, schema, tRPC patterns), use the\n`build-a-clawnify-app` skill \u2014 this one covers the tooling around it.\n\n## TL;DR\n\n```bash\nnpm i -g clawnify # or: npx clawnify@latest <command>\nclawnify login # browser sign-in, paste-code fallback\nclawnify init my-app # scaffold an app or website\ncd my-app && clawnify dev\nclawnify deploy # \u2192 https://<slug>.apps.clawnify.com\n```\n\n- **Auth once, org lazily.** `login` only signs you in; the first\n command that needs an organization asks once and remembers it.\n- **A directory links to one app.** `deploy` from a linked directory\n updates that app; `clawnify link <id-or-slug>` adopts an existing one.\n- **Non-interactive flags exist for every prompt** \u2014 use them in\n scripts and CI (`-y`, `--update-existing`, `--create-new`, `--org`).\n\n## Authenticate\n\n```bash\nclawnify login # opens the browser; also prints the sign-in URL\nclawnify whoami # current user, active org (if linked)\n```\n\n`login` works from any browser: if the browser runs on the same\nmachine, sign-in completes automatically; otherwise the page shows a\ncode to paste back at the `Paste code here if prompted >` prompt\n(useful over SSH \u2014 no port forwarding needed).\n\n**Headless / CI / agents \u2014 skip `login` entirely.** Set `CLAWNIFY_TOKEN` (a\nSupabase access token) and it wins over any stored session, reading/writing no\nfiles; `CLAWNIFY_ORG_ID` (or a per-command `--org`) pins the org. This is how a\ncoding agent runs the CLI without a browser.\n\n### Organizations\n\nYou belong to one or more orgs; apps live inside an org.\n\n```bash\nclawnify org list # orgs you belong to (* marks active)\nclawnify org use <slug-or-id> # switch the active org\n```\n\nNo need to pick one up front \u2014 the first org-scoped command prompts\nonce and persists the choice. Any single command can override with\n`--org <slug-or-id>`.\n\n## Create and run locally\n\n```bash\nclawnify init [dir] # interactive: app or website\nclawnify init my-app -y # non-interactive defaults (blank app)\nclawnify init --type app --template crud --name my-app\nclawnify init --type website --name my-site\nclawnify dev [dir] [--port 8787] # local dev server\n```\n\n`init` also installs AI files (rules + skills + MCP config) for any\ncoding agents detected in the project; skip with `--no-ai-files`.\n\n## Deploy\n\n```bash\nclawnify deploy # deploy the current directory\nclawnify deploy path/to/app\nclawnify deploy --from owner/repo # deploy straight from GitHub\nclawnify deploy --from owner/repo --path apps/web # monorepo subdir\nclawnify deploy --dry-run # list files that would upload\n```\n\nFirst deploy creates the app and links the directory (writes a local\nproject file); later deploys update the same app. On a slug conflict\nyou'll be asked \u2014 or decide up front:\n\n```bash\nclawnify deploy -y # reuse/update the existing app\nclawnify deploy --update-existing # same, explicit\nclawnify deploy --create-new # take the suggested new slug\n```\n\nLink an existing deployed app to the current directory instead of\ncreating a new one:\n\n```bash\nclawnify link <app-id-or-slug>\n```\n\n## Inspect and manage deployed apps\n\n```bash\nclawnify ls # list deployed apps in the active org\nclawnify logs <app-id> # build logs\nclawnify open <slug> # open the live app in the browser\nclawnify rm <app-id> # delete an app\nclawnify pull schema --from <app-id-or-slug> # fetch live schema.sql\nclawnify docs [slug] # usage README for an app (org index if omitted)\n```\n\n`pull schema` refuses to clobber local uncommitted changes unless you\npass `--force`.\n\n## Manage agents (the FDE surface)\n\nDrive an org's AI agents from the terminal \u2014 observe them and fix them. See the\n`fix-a-clawnify-agent` skill for the workflow; this is the command list. All\norg-scoped and **repo-independent** (reads session data + the box, never a\nGitHub repo). Add `--server <id>` when the org has more than one server.\n\n```bash\nclawnify servers list # the org's servers (an org can have several)\nclawnify agents list # agents on a server (main + specialists)\nclawnify agents skills [agent] # what an agent can ACTUALLY run (not just its workspace)\nclawnify sessions --agent <slug> --json # stored sessions + token counters (contextTokens = bloat)\nclawnify sessions history <key> --json # one session's transcript \u2014 where it veered\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/ + flows/ to edit\nclawnify agents push [dir] # push edits back (additive; next session, no restart)\nclawnify agents grant-skill <s> --to <a> # share a main-authored skill (or --all for every agent)\nclawnify agents create <slug> --yes # new specialist (RESTARTS the gateway)\nclawnify env set <KEY> <VALUE> # org custom env \u2014 NON-SECRET only (restarts gateway)\nclawnify connections connect <id> # how to connect an integration (dashboard OAuth; you can't)\n```\n\n**Boundary:** everything above is autonomous *except* the human-auth actions \u2014\nconnecting an integration (OAuth) and handing over a secret/API key. For those,\nexplain the dashboard steps; never fake them. `agents create` / `env set`\nrestart the gateway, so confirm before running them on a busy box.\n\n## Connections & env names\n\n```bash\nclawnify connections list # the org's naming catalog (\u25CF connected / \u25CB not)\nclawnify connections connect <id> # how to connect one \u2014 dashboard OAuth; the CLI/agent can't do it for you\n```\n\nLists the active org's integrations (canonical ids + connected state),\nprovider API keys (fixed names + set state), and custom env vars. Read\nit before declaring `credentials` or env names in `clawnify.json` and\nreuse the exact identifiers it shows \u2014 a misspelled id or key name\ndoesn't fail the build, it silently resolves to nothing at runtime.\n\n## Workspaces (one repo, one org's apps)\n\n```bash\nclawnify workspace init [dir] [--org <slug-or-id>]\n```\n\nScaffolds a monorepo bound to an org; apps scaffolded inside land\nunder `apps/` and inherit the org on deploy.\n\n## Wire up coding agents\n\n```bash\nclawnify ai-files install # rules + skills + MCP server in one step\nclawnify skills list # bundled skills\nclawnify skills add <name> # install one into detected agents\nclawnify mcp # stdio MCP bridge (Claude Desktop, etc.)\n```\n\n`ai-files install` detects agent config dirs in the project (Claude\nCode, Cursor, OpenClaw, Codex, Aider) and writes the always-on rules\nblock, installs bundled skills, and adds the Clawnify MCP server to\n`.mcp.json`. Target one agent with `--agent <name>`; undo with\n`clawnify ai-files uninstall`.\n\n## The raw escape hatch\n\n```bash\nclawnify api /servers # any GET\nclawnify api /servers/<id>/agents -X POST -d '{\u2026}' # any method + JSON body\n```\n\n`clawnify api <path>` makes an authenticated request to any Clawnify API path \u2014\nsame auth and org scoping as every other command (it can only do what you can).\nUse it for anything the porcelain doesn't wrap; the curated commands stay small\nbecause this is always there.\n\n## Tips\n\n- `npx clawnify@latest <command>` always runs the newest release.\n- Every org-scoped command accepts `--org` \u2014 prefer it in scripts over\n relying on the saved active org.\n- If sign-in ever fails mid-flow, just run `clawnify login` again; it\n is safe to repeat.\n"
|
|
1332
|
+
},
|
|
1333
|
+
{
|
|
1334
|
+
name: "fix-a-clawnify-agent",
|
|
1335
|
+
description: `Diagnose and fix a Clawnify AI agent that veers off its instructions, ignores specific rules, forgets things, repeats the same mistake, or burns a lot of API credits. Use when someone says their agent (e.g. "Ash") won't follow instructions, keeps going off-path, or is expensive \u2014 read the agent's own sessions, find the real cause, and fix the instructions / sessions / flow instead of patching blind.`,
|
|
1336
|
+
content: "# Fix a misbehaving Clawnify agent\n\nYou are the planner and thinker. The Clawnify agent \u2014 the customer's\nWhatsApp / Telegram / Slack / email \"AI employee\", running OpenClaw on their\nserver \u2014 is the executor. When it misbehaves your job is to **read what it\nactually did, find the real cause, and change the durable inputs.** Not to\npatch instructions blind, and not to burn the agent's own (expensive) model\ntokens on trial-and-error.\n\nThe person you're helping is often **not** an AI specialist. So: diagnose\nfirst, then **explain the cause in plain language and correct the\nmisconception** before you change anything.\n\n## The one rule: don't debug blind\n\n\"Veers off / ignores instructions\" has **three different causes with three\ndifferent fixes.** You can only tell which one by reading the agent's actual\nsession. Patching instructions without looking is exactly why it \"isn't\nheading in the right direction\" \u2014 and every blind test run costs model tokens.\n\n| Cause | What you'll see in the session | Fix |\n|---|---|---|\n| **1. Session bloat** | Was fine early, degrades over a long-running chat; forgets/repeats; high `contextTokens`; compaction/truncation in the transcript; the rule is simply *absent* from recent context | Scope a **fresh session per task**; reset/retire the bloated one |\n| **2. Instruction patchwork** | The rule *was* in context but a **contradicting or older** rule won, or it's buried in a wall of text | **Restructure** `AGENTS.md` (don't add another patch) |\n| **3. Wrong structure** | A repeatable multi-step task the agent improvises differently each time | Move it to a **flow** (deterministic rails) |\n\nBloat and patchwork also explain most **surprise API costs**: a bloated\nsession re-sends a huge context on *every* turn, and the patch-and-rerun loop\nitself burns tokens. Measure it \u2014 don't guess (Step 1).\n\n## Step 1 \u2014 Observe (read what actually happened)\n\n```bash\nclawnify sessions # every agent's sessions on the server, newest first\nclawnify sessions --agent ash --json # ash only, with token counters (contextTokens = bloat signal)\nclawnify sessions history <key> --json # the transcript of one run \u2014 where it actually veered\nclawnify agents skills ash # what ash can ACTUALLY run (workspace + shared skills)\n```\n\nLook for, in order:\n- **Which failure mode** (table above): was the instruction *present and\n ignored* (\u2192 patchwork/structure) or *compacted away / absent* (\u2192 bloat)?\n- **`contextTokens`** on the session \u2014 large and growing = bloat.\n- **A missing skill** \u2014 if the instruction says \"use skill X\" but `agents\n skills` doesn't list it, the agent literally can't. The fix is to grant it\n (`clawnify agents grant-skill X --to ash`, or `--all` for every agent) if it's\n already authored in main, else author it first (`agents pull main` \u2192 add\n `skills/X/SKILL.md` \u2192 `agents push`) \u2014 not to reword the instruction. (Note:\n what's in the agent's *workspace* is only part of it \u2014 `agents skills` shows\n the effective set incl. shared managed-root skills.)\n- **Where the tokens go** \u2014 one giant session, or repeated retries after a\n veer? That's your cost answer, from data, not a hypothesis.\n\n> If `clawnify sessions` isn't available yet in this org, fall back: ask the\n> person to describe (or paste) one failing run, and read the current\n> `AGENTS.md` from the org's synced repo. You still diagnose before you fix.\n\n## Step 2 \u2014 Explain, then fix\n\nTell the person, plainly, which of the three it is and why. Then:\n\n**Bloat \u2192** don't reuse one ever-growing chat for the same task. Start a fresh\nsession per task/topic (or `/reset` the runaway one). This fixes the veer\n*and* the cost.\n\n**Patchwork \u2192** rewrite `AGENTS.md`, don't append to it. Structure it: **role\n\u2192 a short list of hard rules up front \u2192 the steps \u2192 one example of right vs\nwrong.** Delete contradictions. A tight, prioritized instruction set is\nfollowed far better than a long patched one.\n\n**Structure \u2192** author a **flow** for the repeatable task: deterministic steps,\neach with a narrow instruction, and the heavy/deterministic parts (fetch data,\nfill a template, render the deck) run *without* the model \u2014 less veer, less cost.\n\nWhere instructions live and how edits land:\n- Edit **`AGENTS.md`** (and `skills/`, `flows/`). Push via the org's **GitHub\n sync repo** (auto-deploys to the box) or `clawnify deploy`. See the\n `use-the-clawnify-cli` skill for the commands.\n- **No gateway restart needed** \u2014 the agent picks up new `AGENTS.md` / skills /\n flows on its **next session**.\n- **Never edit any `CLAWNIFY-*.md`** file (`CLAWNIFY-SOUL/AGENTS/TOOLS.md`) \u2014\n those are platform-owned and Clawnify overwrites them on every sync. Your\n edits there vanish.\n\n## How Clawnify agents actually work (what people get wrong)\n\nPreempt these \u2014 they cause \"I set it up but the agent ignores it\":\n\n- **Adding a document to Knowledge does NOT mean the agent reads it.**\n (1) A doc must be **published by a human** \u2014 an agent \"proposing\" it only\n creates a draft. (2) Once published, the agent only *automatically* sees its\n **title + one-line description** (a capped, ~30-item index); the **actual\n content is fetched only when the agent chooses to search** it\n (`company_knowledge_search`). So if the agent ignores a doc, check: is it\n published? not hidden? still in the index? does its `AGENTS.md` tell it to\n search? \u2014 **re-uploading won't help.** Depth: the `organize-company-knowledge` skill.\n- **Memory** is written by the agent via a tool (`memory_write`) and surfaced\n as an index + per-turn recall \u2014 it is **not** a file/folder you drop notes\n into.\n- **The dashboard \"recurring skill\" cards are manual-click only** \u2014 the\n cron/every/at schedule shown is **not wired to a scheduler.** For real\n scheduled or event-driven work use a **cron job or a flow/webhook**, not a\n recurring-skill card.\n- **Native channels** (WhatsApp/Telegram/Slack) receive messages \"for free\"\n via the allowlist \u2014 there is **no trigger/webhook to set up** for incoming\n messages. (Only Clawnify *integrations* have dashboard triggers.)\n\n## Answering \"would a different agent / a flow help?\"\n\n- **Same agent for the same task \u2192 confusion?** The agent identity isn't the\n problem; a reused, ever-growing **session** is (bloat, above). A second agent\n doesn't fix the mechanism and doubles what you manage. Fresh sessions do.\n- **Would a flow be better?** Yes *if* the task is repeatable and structured \u2014\n it constrains the agent and moves deterministic work off-model (less veer,\n less cost). No if the underlying step instructions are vague \u2014 a flow\n structures, it doesn't clarify.\n\n## Guardrails\n\n- **Diagnose before you change anything.** One transcript read beats five blind\n patches.\n- **Never** edit `CLAWNIFY-*.md` (overwritten) \u2014 edit `AGENTS.md`.\n- **Confirm with the human before anything irreversible or outward-facing:**\n sending messages on the agent's live channels, deleting an agent or app,\n billing/plan changes, rotating credentials. Self-service is not unattended\n autonomy.\n- **Connecting an integration is a hard stop, not a confirm.** If a fix needs a\n Clawnify integration that `clawnify connections list` shows as not connected\n (\u25CB), you *cannot* connect it \u2014 that needs the user's OAuth sign-in in a\n browser. Run `clawnify connections connect <id>` and relay the steps to the\n user; never attempt it yourself or ask for their password.\n- **Never put a secret through `clawnify env set`** \u2014 it exposes the value in\n the command and your context. Secrets and API keys go in the dashboard\n (Settings \u2192 Environment Variables / API Keys); guide the user there. Use\n `env set` only for non-secret config. And remember `agents create` / `env set`\n **restart the gateway** \u2014 confirm with the user before you run them on a live,\n busy box.\n- Prefer the **smallest durable fix** (a session habit, a tightened `AGENTS.md`,\n one flow) over more instructions.\n"
|
|
884
1337
|
}
|
|
885
1338
|
];
|
|
886
1339
|
var RULES_CONTENT = "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 `X-Clawnify-Org-Id` request header. This is how multi-tenancy works \u2014\n there are no exceptions.\n\n## Identity comes from request headers, never the client\n\nThe platform injects identity headers the client cannot forge:\n`X-Clawnify-User-Id`, `X-Clawnify-Org-Id`, `X-Clawnify-User-Email`,\n`X-Clawnify-Caller`. Read them server-side. Never trust a client-supplied user\nor org id.\n\n## Integrations: use `@clawnify/connections`\n\nDon't store per-service API keys or OAuth secrets in the app. Declare what the\napp needs under `app.credentials` in `clawnify.json`, then call\n`connect(service, env)` and `secret(name, env)` from the SDK. Off-platform\n(local dev, scripts), put a `clw_` org service token in `.dev.vars` as\n`CLAWNIFY_TOKEN` \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";
|
|
@@ -900,10 +1353,10 @@ var VERSION_HEADER_RE = /<!--\s*clawnify-skill:\s*([\w-]+)\s+v([\d.]+)\s*-->/;
|
|
|
900
1353
|
function versionHeader(name) {
|
|
901
1354
|
return `<!-- clawnify-skill: ${name} v${CLI_VERSION} -->`;
|
|
902
1355
|
}
|
|
903
|
-
function readExistingVersion(
|
|
904
|
-
if (!existsSync2(
|
|
1356
|
+
function readExistingVersion(path9) {
|
|
1357
|
+
if (!existsSync2(path9)) return null;
|
|
905
1358
|
try {
|
|
906
|
-
const head = readFileSync(
|
|
1359
|
+
const head = readFileSync(path9, "utf8").slice(0, 500);
|
|
907
1360
|
const match = head.match(VERSION_HEADER_RE);
|
|
908
1361
|
return match ? match[2] : null;
|
|
909
1362
|
} catch {
|
|
@@ -1286,9 +1739,11 @@ function slugify(name) {
|
|
|
1286
1739
|
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
|
|
1287
1740
|
}
|
|
1288
1741
|
async function askProjectType(opts) {
|
|
1289
|
-
if (opts?.type === "app" || opts?.type === "website"
|
|
1742
|
+
if (opts?.type === "app" || opts?.type === "website" || opts?.type === "agent") {
|
|
1743
|
+
return opts.type;
|
|
1744
|
+
}
|
|
1290
1745
|
if (opts?.type) {
|
|
1291
|
-
console.error(`Unknown --type '${opts.type}' (expected 'app' or '
|
|
1746
|
+
console.error(`Unknown --type '${opts.type}' (expected 'app', 'website', or 'agent').`);
|
|
1292
1747
|
process.exit(1);
|
|
1293
1748
|
}
|
|
1294
1749
|
if (opts?.yes) return "app";
|
|
@@ -1296,9 +1751,12 @@ async function askProjectType(opts) {
|
|
|
1296
1751
|
console.log(" What are you creating?");
|
|
1297
1752
|
console.log(" 1) app \u2014 full-stack project (React + Hono + D1)");
|
|
1298
1753
|
console.log(" 2) website \u2014 public site (Astro)");
|
|
1754
|
+
console.log(" 3) agent \u2014 an OpenClaw agent (instructions, skills, flows)");
|
|
1299
1755
|
console.log();
|
|
1300
1756
|
const choice = await ask2("Type [1]: ") || "1";
|
|
1301
|
-
|
|
1757
|
+
if (choice === "2") return "website";
|
|
1758
|
+
if (choice === "3") return "agent";
|
|
1759
|
+
return "app";
|
|
1302
1760
|
}
|
|
1303
1761
|
function detectPackageManager() {
|
|
1304
1762
|
const ua = process.env.npm_config_user_agent ?? "";
|
|
@@ -1312,19 +1770,22 @@ async function initCommand(dir, opts) {
|
|
|
1312
1770
|
if (type === "website") {
|
|
1313
1771
|
return initWebsite(dir, opts);
|
|
1314
1772
|
}
|
|
1773
|
+
if (type === "agent") {
|
|
1774
|
+
return initAgent(dir, opts);
|
|
1775
|
+
}
|
|
1315
1776
|
return initApp(dir, opts);
|
|
1316
1777
|
}
|
|
1317
1778
|
async function initApp(dir, opts) {
|
|
1318
1779
|
const yes = !!opts?.yes;
|
|
1319
|
-
const dirArgName = dir ?
|
|
1780
|
+
const dirArgName = dir ? path4.basename(path4.resolve(dir)) : void 0;
|
|
1320
1781
|
const name = opts?.name || (yes ? dirArgName ?? "my-app" : await ask2("App name: ") || "my-app");
|
|
1321
1782
|
const slug = slugify(name);
|
|
1322
1783
|
let targetDir;
|
|
1323
1784
|
if (dir) {
|
|
1324
|
-
targetDir =
|
|
1785
|
+
targetDir = path4.resolve(dir);
|
|
1325
1786
|
} else {
|
|
1326
1787
|
const ws = findWorkspaceRoot(process.cwd());
|
|
1327
|
-
targetDir = ws ?
|
|
1788
|
+
targetDir = ws ? path4.join(ws.dir, "apps", slug) : path4.resolve(slug);
|
|
1328
1789
|
}
|
|
1329
1790
|
let template;
|
|
1330
1791
|
if (opts?.template) {
|
|
@@ -1340,12 +1801,12 @@ async function initApp(dir, opts) {
|
|
|
1340
1801
|
const templateChoice = await ask2("Template [1]: ") || "1";
|
|
1341
1802
|
template = templateChoice === "2" ? "crud" : "blank";
|
|
1342
1803
|
}
|
|
1343
|
-
if (
|
|
1804
|
+
if (fs4.existsSync(targetDir) && fs4.readdirSync(targetDir).length > 0) {
|
|
1344
1805
|
console.error(`Directory ${targetDir} is not empty.`);
|
|
1345
1806
|
process.exit(1);
|
|
1346
1807
|
}
|
|
1347
|
-
|
|
1348
|
-
|
|
1808
|
+
fs4.mkdirSync(path4.join(targetDir, "src/server"), { recursive: true });
|
|
1809
|
+
fs4.mkdirSync(path4.join(targetDir, "src/client"), { recursive: true });
|
|
1349
1810
|
let storage;
|
|
1350
1811
|
if (opts?.storage !== void 0) {
|
|
1351
1812
|
storage = opts.storage;
|
|
@@ -1589,10 +2050,10 @@ createRoot(document.getElementById("app")!).render(
|
|
|
1589
2050
|
}
|
|
1590
2051
|
const pm = detectPackageManager();
|
|
1591
2052
|
console.log();
|
|
1592
|
-
console.log(` Created ${name} in ${
|
|
2053
|
+
console.log(` Created ${name} in ${path4.relative(process.cwd(), targetDir)}/`);
|
|
1593
2054
|
console.log();
|
|
1594
2055
|
console.log(" Get started:");
|
|
1595
|
-
console.log(` cd ${
|
|
2056
|
+
console.log(` cd ${path4.relative(process.cwd(), targetDir)}`);
|
|
1596
2057
|
console.log(` ${pm} install`);
|
|
1597
2058
|
console.log(` ${pm} ${pm === "npm" ? "run " : ""}dev # local dev at http://localhost:5173`);
|
|
1598
2059
|
console.log(` ${pm} ${pm === "npm" ? "run " : ""}deploy # deploy to production`);
|
|
@@ -1603,21 +2064,21 @@ async function initWebsite(dir, opts) {
|
|
|
1603
2064
|
const slug = slugify(name);
|
|
1604
2065
|
let targetDir;
|
|
1605
2066
|
if (dir) {
|
|
1606
|
-
targetDir =
|
|
2067
|
+
targetDir = path4.resolve(dir);
|
|
1607
2068
|
} else {
|
|
1608
2069
|
const ws = findWorkspaceRoot(process.cwd());
|
|
1609
|
-
targetDir = ws ?
|
|
2070
|
+
targetDir = ws ? path4.join(ws.dir, "website") : path4.resolve(slug);
|
|
1610
2071
|
}
|
|
1611
|
-
if (
|
|
1612
|
-
const entries =
|
|
2072
|
+
if (fs4.existsSync(targetDir)) {
|
|
2073
|
+
const entries = fs4.readdirSync(targetDir);
|
|
1613
2074
|
const onlyGitkeep = entries.length === 1 && entries[0] === ".gitkeep";
|
|
1614
2075
|
if (entries.length > 0 && !onlyGitkeep) {
|
|
1615
2076
|
console.error(`Directory ${targetDir} is not empty.`);
|
|
1616
2077
|
process.exit(1);
|
|
1617
2078
|
}
|
|
1618
|
-
if (onlyGitkeep)
|
|
2079
|
+
if (onlyGitkeep) fs4.rmSync(path4.join(targetDir, ".gitkeep"));
|
|
1619
2080
|
}
|
|
1620
|
-
|
|
2081
|
+
fs4.mkdirSync(targetDir, { recursive: true });
|
|
1621
2082
|
write(targetDir, "clawnify.json", JSON.stringify({
|
|
1622
2083
|
$schema: "https://app.clawnify.com/schema/v1/clawnify.json",
|
|
1623
2084
|
version: 1,
|
|
@@ -1727,15 +2188,80 @@ import BaseLayout from "../layouts/BaseLayout.astro";
|
|
|
1727
2188
|
</BaseLayout>
|
|
1728
2189
|
`);
|
|
1729
2190
|
console.log();
|
|
1730
|
-
console.log(` Created ${name} in ${
|
|
2191
|
+
console.log(` Created ${name} in ${path4.relative(process.cwd(), targetDir)}/`);
|
|
1731
2192
|
console.log();
|
|
1732
2193
|
console.log(" Get started:");
|
|
1733
|
-
console.log(` cd ${
|
|
2194
|
+
console.log(` cd ${path4.relative(process.cwd(), targetDir)}`);
|
|
1734
2195
|
console.log(" pnpm install");
|
|
1735
2196
|
console.log(" pnpm dev # local dev at http://localhost:4321");
|
|
1736
2197
|
console.log(" pnpm deploy # deploy as your org's website");
|
|
1737
2198
|
console.log();
|
|
1738
2199
|
}
|
|
2200
|
+
async function initAgent(dir, opts) {
|
|
2201
|
+
const yes = !!opts?.yes;
|
|
2202
|
+
const dirArgName = dir ? path4.basename(path4.resolve(dir)) : void 0;
|
|
2203
|
+
const name = opts?.name || (yes ? dirArgName ?? "my-agent" : await ask2("Agent name: ") || "my-agent");
|
|
2204
|
+
const slug = slugify(name);
|
|
2205
|
+
let targetDir;
|
|
2206
|
+
if (dir) {
|
|
2207
|
+
targetDir = path4.resolve(dir);
|
|
2208
|
+
} else {
|
|
2209
|
+
const ws = findWorkspaceRoot(process.cwd());
|
|
2210
|
+
targetDir = ws ? path4.join(ws.dir, "agents", slug) : path4.resolve(slug);
|
|
2211
|
+
}
|
|
2212
|
+
if (fs4.existsSync(targetDir) && fs4.readdirSync(targetDir).length > 0) {
|
|
2213
|
+
console.error(`Directory ${targetDir} is not empty.`);
|
|
2214
|
+
process.exit(1);
|
|
2215
|
+
}
|
|
2216
|
+
write(targetDir, "clawnify.json", JSON.stringify({
|
|
2217
|
+
$schema: "https://app.clawnify.com/schema/v1/clawnify.json",
|
|
2218
|
+
version: 1,
|
|
2219
|
+
name,
|
|
2220
|
+
description: "",
|
|
2221
|
+
agent: { harness: "openclaw" }
|
|
2222
|
+
}, null, 2));
|
|
2223
|
+
write(targetDir, "AGENT.md", `# ${name}
|
|
2224
|
+
|
|
2225
|
+
You are ${name}, an OpenClaw agent.
|
|
2226
|
+
|
|
2227
|
+
Describe the agent's role, tone, and boundaries here. This file is the
|
|
2228
|
+
agent's primary instructions \u2014 edit it to shape behavior.
|
|
2229
|
+
|
|
2230
|
+
## Skills
|
|
2231
|
+
|
|
2232
|
+
Reusable procedures live under \`skills/<name>/\`: a \`SKILL.md\` the agent
|
|
2233
|
+
reads when triggered, plus a \`skill.json\` describing when it runs.
|
|
2234
|
+
|
|
2235
|
+
## Flows
|
|
2236
|
+
|
|
2237
|
+
Automations live under \`flows/<name>.json\` \u2014 ClawFlow definitions that run
|
|
2238
|
+
on triggers (webhooks, schedules) without a full agent turn.
|
|
2239
|
+
`);
|
|
2240
|
+
write(targetDir, "skills/.gitkeep", "");
|
|
2241
|
+
write(targetDir, "flows/.gitkeep", "");
|
|
2242
|
+
write(targetDir, ".gitignore", `node_modules
|
|
2243
|
+
.clawnify
|
|
2244
|
+
.env*
|
|
2245
|
+
!.env.example
|
|
2246
|
+
.dev.vars
|
|
2247
|
+
# Runtime state \u2014 never shipped with the agent (ADR \xA7 secret-exclusion)
|
|
2248
|
+
memories/
|
|
2249
|
+
sessions/
|
|
2250
|
+
logs/
|
|
2251
|
+
`);
|
|
2252
|
+
const rel = path4.relative(process.cwd(), targetDir) || ".";
|
|
2253
|
+
console.log();
|
|
2254
|
+
console.log(` Created agent ${name} in ${rel}/`);
|
|
2255
|
+
console.log();
|
|
2256
|
+
console.log(" Layout:");
|
|
2257
|
+
console.log(" AGENT.md \u2014 the agent's instructions");
|
|
2258
|
+
console.log(" skills/ \u2014 reusable procedures (SKILL.md + skill.json)");
|
|
2259
|
+
console.log(" flows/ \u2014 ClawFlow automations (<name>.json)");
|
|
2260
|
+
console.log();
|
|
2261
|
+
console.log(" Author here and commit. Deploying this (config push to the");
|
|
2262
|
+
console.log(" running agent via CAP) lands in a follow-up.");
|
|
2263
|
+
console.log();
|
|
2264
|
+
}
|
|
1739
2265
|
function writeBlankTemplate(dir, name) {
|
|
1740
2266
|
write(dir, "src/server/routes.ts", `import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
|
|
1741
2267
|
import { getDB, desc } from "@clawnify/db";
|
|
@@ -2035,14 +2561,14 @@ export function App() {
|
|
|
2035
2561
|
`);
|
|
2036
2562
|
}
|
|
2037
2563
|
function write(dir, file, content) {
|
|
2038
|
-
const fullPath =
|
|
2039
|
-
|
|
2040
|
-
|
|
2564
|
+
const fullPath = path4.join(dir, file);
|
|
2565
|
+
fs4.mkdirSync(path4.dirname(fullPath), { recursive: true });
|
|
2566
|
+
fs4.writeFileSync(fullPath, content);
|
|
2041
2567
|
}
|
|
2042
2568
|
|
|
2043
2569
|
// src/commands/dev.ts
|
|
2044
|
-
import
|
|
2045
|
-
import
|
|
2570
|
+
import fs5 from "fs";
|
|
2571
|
+
import path5 from "path";
|
|
2046
2572
|
import { spawn as spawn2 } from "child_process";
|
|
2047
2573
|
function slugify2(name) {
|
|
2048
2574
|
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
|
|
@@ -2087,7 +2613,7 @@ function assertNodeVersion2() {
|
|
|
2087
2613
|
}
|
|
2088
2614
|
async function devCommand(dir, options) {
|
|
2089
2615
|
assertNodeVersion2();
|
|
2090
|
-
const resolvedDir = dir ?
|
|
2616
|
+
const resolvedDir = dir ? path5.resolve(dir) : process.cwd();
|
|
2091
2617
|
const manifest = readManifest(resolvedDir);
|
|
2092
2618
|
if (!manifest) {
|
|
2093
2619
|
console.error("No clawnify.json found. Run `clawnify init` first.");
|
|
@@ -2103,21 +2629,21 @@ async function devCommand(dir, options) {
|
|
|
2103
2629
|
const database = manifest.app.database !== false;
|
|
2104
2630
|
const storage = manifest.app.storage === true;
|
|
2105
2631
|
const apiPort = options?.port || "8787";
|
|
2106
|
-
const clawnifyDir =
|
|
2107
|
-
|
|
2108
|
-
const wranglerPath =
|
|
2109
|
-
|
|
2632
|
+
const clawnifyDir = path5.join(resolvedDir, ".clawnify");
|
|
2633
|
+
fs5.mkdirSync(clawnifyDir, { recursive: true });
|
|
2634
|
+
const wranglerPath = path5.join(clawnifyDir, "wrangler.toml");
|
|
2635
|
+
fs5.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
|
|
2110
2636
|
if (database) {
|
|
2111
|
-
const schemaTsPath =
|
|
2112
|
-
const drizzleConfigPath =
|
|
2113
|
-
if (
|
|
2637
|
+
const schemaTsPath = path5.join(resolvedDir, "src/server/schema.ts");
|
|
2638
|
+
const drizzleConfigPath = path5.join(resolvedDir, "drizzle.config.ts");
|
|
2639
|
+
if (fs5.existsSync(schemaTsPath) && fs5.existsSync(drizzleConfigPath)) {
|
|
2114
2640
|
await syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath);
|
|
2115
2641
|
} else {
|
|
2116
2642
|
const schemaCandidates = [
|
|
2117
|
-
|
|
2118
|
-
|
|
2643
|
+
path5.join(resolvedDir, "schema.sql"),
|
|
2644
|
+
path5.join(resolvedDir, "src/server/schema.sql")
|
|
2119
2645
|
];
|
|
2120
|
-
const schemaPath = schemaCandidates.find((p) =>
|
|
2646
|
+
const schemaPath = schemaCandidates.find((p) => fs5.existsSync(p));
|
|
2121
2647
|
if (schemaPath) {
|
|
2122
2648
|
await runQuiet(resolvedDir, "npx", [
|
|
2123
2649
|
"wrangler",
|
|
@@ -2229,15 +2755,15 @@ async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath
|
|
|
2229
2755
|
);
|
|
2230
2756
|
throw err;
|
|
2231
2757
|
}
|
|
2232
|
-
const drizzleDir =
|
|
2233
|
-
if (!
|
|
2234
|
-
const sqlFiles =
|
|
2758
|
+
const drizzleDir = path5.join(clawnifyDir, "drizzle");
|
|
2759
|
+
if (!fs5.existsSync(drizzleDir)) return;
|
|
2760
|
+
const sqlFiles = fs5.readdirSync(drizzleDir).filter((name) => name.endsWith(".sql")).sort();
|
|
2235
2761
|
if (sqlFiles.length === 0) return;
|
|
2236
|
-
const appliedPath =
|
|
2762
|
+
const appliedPath = path5.join(clawnifyDir, "applied-migrations.json");
|
|
2237
2763
|
let applied = [];
|
|
2238
|
-
if (
|
|
2764
|
+
if (fs5.existsSync(appliedPath)) {
|
|
2239
2765
|
try {
|
|
2240
|
-
applied = JSON.parse(
|
|
2766
|
+
applied = JSON.parse(fs5.readFileSync(appliedPath, "utf8"));
|
|
2241
2767
|
if (!Array.isArray(applied)) applied = [];
|
|
2242
2768
|
} catch {
|
|
2243
2769
|
applied = [];
|
|
@@ -2246,7 +2772,7 @@ async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath
|
|
|
2246
2772
|
const appliedSet = new Set(applied);
|
|
2247
2773
|
for (const file of sqlFiles) {
|
|
2248
2774
|
if (appliedSet.has(file)) continue;
|
|
2249
|
-
const filePath =
|
|
2775
|
+
const filePath = path5.join(drizzleDir, file);
|
|
2250
2776
|
await runQuiet(resolvedDir, "npx", [
|
|
2251
2777
|
"wrangler",
|
|
2252
2778
|
"d1",
|
|
@@ -2258,11 +2784,11 @@ async function syncDrizzleToLocalD1(resolvedDir, clawnifyDir, slug, wranglerPath
|
|
|
2258
2784
|
]);
|
|
2259
2785
|
applied.push(file);
|
|
2260
2786
|
}
|
|
2261
|
-
|
|
2787
|
+
fs5.writeFileSync(appliedPath, JSON.stringify(applied, null, 2) + "\n");
|
|
2262
2788
|
}
|
|
2263
2789
|
|
|
2264
2790
|
// src/commands/link.ts
|
|
2265
|
-
import
|
|
2791
|
+
import path6 from "path";
|
|
2266
2792
|
var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
2267
2793
|
async function findByAppId(orgs, appId) {
|
|
2268
2794
|
for (const org of orgs) {
|
|
@@ -2301,7 +2827,7 @@ async function findBySlug(orgs, slug) {
|
|
|
2301
2827
|
return null;
|
|
2302
2828
|
}
|
|
2303
2829
|
async function linkCommand(appIdOrSlug, options) {
|
|
2304
|
-
const dir = options?.dir ?
|
|
2830
|
+
const dir = options?.dir ? path6.resolve(options.dir) : process.cwd();
|
|
2305
2831
|
const orgs = await listMyOrgs();
|
|
2306
2832
|
if (orgs.length === 0) {
|
|
2307
2833
|
console.error("No organizations found. Run `clawnify login` first.");
|
|
@@ -2329,14 +2855,14 @@ async function linkCommand(appIdOrSlug, options) {
|
|
|
2329
2855
|
slug: matched.app.slug,
|
|
2330
2856
|
app_token: matched.app.app_token
|
|
2331
2857
|
});
|
|
2332
|
-
const rel =
|
|
2858
|
+
const rel = path6.relative(process.cwd(), dir) || ".";
|
|
2333
2859
|
console.log(` Linked ${matched.app.name} (${matched.app.slug}) in ${matched.org.name}`);
|
|
2334
2860
|
console.log(` Wrote ${rel}/.clawnify/project.json`);
|
|
2335
2861
|
console.log(` Run \`clawnify deploy\` to push the current source to this app.`);
|
|
2336
2862
|
}
|
|
2337
2863
|
|
|
2338
2864
|
// src/commands/pull.ts
|
|
2339
|
-
import
|
|
2865
|
+
import path7 from "path";
|
|
2340
2866
|
async function pullSchemaCommand(options) {
|
|
2341
2867
|
if (!options.from) {
|
|
2342
2868
|
console.error("Usage: clawnify pull schema --from <app-id-or-slug>");
|
|
@@ -2354,9 +2880,9 @@ async function pullSchemaCommand(options) {
|
|
|
2354
2880
|
console.error(`Failed to fetch schema: ${err.message}`);
|
|
2355
2881
|
process.exit(1);
|
|
2356
2882
|
}
|
|
2357
|
-
const targetPath =
|
|
2883
|
+
const targetPath = path7.resolve(options.out ?? "schema.sql");
|
|
2358
2884
|
const result = await writeSchema(targetPath, schema, { force: options.force });
|
|
2359
|
-
const rel =
|
|
2885
|
+
const rel = path7.relative(process.cwd(), result.path) || result.path;
|
|
2360
2886
|
switch (result.status) {
|
|
2361
2887
|
case "no-schema":
|
|
2362
2888
|
console.log(` ${ref.slug}: no schema.sql in R2 (pre-backfill app, or no database)`);
|
|
@@ -2461,10 +2987,55 @@ async function connectionsListCommand(opts) {
|
|
|
2461
2987
|
}
|
|
2462
2988
|
}
|
|
2463
2989
|
}
|
|
2990
|
+
var INTEGRATIONS_URL = "https://app.clawnify.com/settings/integrations";
|
|
2991
|
+
async function connectionsConnectCommand(id, opts) {
|
|
2992
|
+
const res = await api.get("/v1/connections/catalog");
|
|
2993
|
+
if (!res.ok) {
|
|
2994
|
+
console.error("Failed to fetch the connections catalog.");
|
|
2995
|
+
process.exit(1);
|
|
2996
|
+
}
|
|
2997
|
+
const catalog = await res.json();
|
|
2998
|
+
const match = catalog.integrations.find((i) => i.id === id);
|
|
2999
|
+
if (!match) {
|
|
3000
|
+
console.error(
|
|
3001
|
+
`No integration with id "${id}". Run \`clawnify connections list\` for valid ids.
|
|
3002
|
+
(Provider API keys are set in Settings \u2192 API Keys; custom env in Settings \u2192 Environment Variables.)`
|
|
3003
|
+
);
|
|
3004
|
+
process.exit(1);
|
|
3005
|
+
}
|
|
3006
|
+
if (match.connected) {
|
|
3007
|
+
console.log(`"${match.label}" (${id}) is already connected (\u25CF active). Nothing to do.`);
|
|
3008
|
+
return;
|
|
3009
|
+
}
|
|
3010
|
+
const steps = [
|
|
3011
|
+
`Open ${INTEGRATIONS_URL}`,
|
|
3012
|
+
`Find "${match.label}" and click Connect`,
|
|
3013
|
+
`Complete the sign-in / authorization in the browser`,
|
|
3014
|
+
`Re-run your command once it shows connected`
|
|
3015
|
+
];
|
|
3016
|
+
if (opts?.json) {
|
|
3017
|
+
console.log(
|
|
3018
|
+
JSON.stringify(
|
|
3019
|
+
{ id, label: match.label, connected: false, connect_url: INTEGRATIONS_URL, steps },
|
|
3020
|
+
null,
|
|
3021
|
+
2
|
|
3022
|
+
)
|
|
3023
|
+
);
|
|
3024
|
+
return;
|
|
3025
|
+
}
|
|
3026
|
+
console.log(`"${match.label}" (${id}) is not connected.
|
|
3027
|
+
`);
|
|
3028
|
+
console.log(
|
|
3029
|
+
"Connecting it needs your authorization in a browser \u2014 the CLI and the agent can't do it for you. To connect it:\n"
|
|
3030
|
+
);
|
|
3031
|
+
steps.forEach((s, n) => console.log(` ${n + 1}. ${s}`));
|
|
3032
|
+
console.log(`
|
|
3033
|
+
${INTEGRATIONS_URL}`);
|
|
3034
|
+
}
|
|
2464
3035
|
|
|
2465
3036
|
// src/commands/workspace.ts
|
|
2466
|
-
import
|
|
2467
|
-
import
|
|
3037
|
+
import fs6 from "fs";
|
|
3038
|
+
import path8 from "path";
|
|
2468
3039
|
function slugify3(name) {
|
|
2469
3040
|
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
|
|
2470
3041
|
}
|
|
@@ -2495,15 +3066,15 @@ async function resolveOrg(opts) {
|
|
|
2495
3066
|
process.exit(1);
|
|
2496
3067
|
}
|
|
2497
3068
|
function write2(dir, file, content) {
|
|
2498
|
-
const fullPath =
|
|
2499
|
-
|
|
2500
|
-
|
|
3069
|
+
const fullPath = path8.join(dir, file);
|
|
3070
|
+
fs6.mkdirSync(path8.dirname(fullPath), { recursive: true });
|
|
3071
|
+
fs6.writeFileSync(fullPath, content);
|
|
2501
3072
|
}
|
|
2502
3073
|
async function workspaceInitCommand(dir, opts) {
|
|
2503
3074
|
const org = await resolveOrg(opts);
|
|
2504
3075
|
const name = opts?.name || org.name;
|
|
2505
|
-
const targetDir = dir ?
|
|
2506
|
-
if (
|
|
3076
|
+
const targetDir = dir ? path8.resolve(dir) : path8.resolve(slugify3(org.slug));
|
|
3077
|
+
if (fs6.existsSync(targetDir) && fs6.readdirSync(targetDir).length > 0) {
|
|
2507
3078
|
console.error(`Directory ${targetDir} is not empty.`);
|
|
2508
3079
|
process.exit(1);
|
|
2509
3080
|
}
|
|
@@ -2540,13 +3111,15 @@ Clawnify workspace for the **${org.name}** org (\`${org.slug}\`).
|
|
|
2540
3111
|
Layout:
|
|
2541
3112
|
|
|
2542
3113
|
- \`apps/<name>/\` \u2014 one folder per app; each deploys to this org automatically.
|
|
3114
|
+
- \`agents/<name>/\` \u2014 one folder per OpenClaw agent (AGENT.md, skills/, flows/).
|
|
2543
3115
|
- \`website/\` \u2014 the org's single public website (Astro).
|
|
2544
3116
|
|
|
2545
|
-
## Add an app / the website
|
|
3117
|
+
## Add an app / an agent / the website
|
|
2546
3118
|
|
|
2547
3119
|
\`\`\`bash
|
|
2548
|
-
clawnify init # app
|
|
2549
|
-
clawnify init --type
|
|
3120
|
+
clawnify init # app \u2192 apps/<name>/ (inherits the org)
|
|
3121
|
+
clawnify init --type agent # agent \u2192 agents/<name>/
|
|
3122
|
+
clawnify init --type website # site \u2192 website/
|
|
2550
3123
|
\`\`\`
|
|
2551
3124
|
|
|
2552
3125
|
## Deploy
|
|
@@ -2570,8 +3143,9 @@ repo auto-deploys only the targets whose folder changed; Clawnify mirrors edits
|
|
|
2570
3143
|
back under the same subdirs. See \`docs/internal/adr-company-monorepo.md\` \xA7 "GitHub sync".
|
|
2571
3144
|
`);
|
|
2572
3145
|
write2(targetDir, "apps/.gitkeep", "");
|
|
3146
|
+
write2(targetDir, "agents/.gitkeep", "");
|
|
2573
3147
|
write2(targetDir, "website/.gitkeep", "");
|
|
2574
|
-
const rel =
|
|
3148
|
+
const rel = path8.relative(process.cwd(), targetDir) || ".";
|
|
2575
3149
|
console.log();
|
|
2576
3150
|
console.log(` Created workspace for ${org.name} (${org.slug}) in ${rel}/`);
|
|
2577
3151
|
console.log();
|
|
@@ -2583,7 +3157,7 @@ back under the same subdirs. See \`docs/internal/adr-company-monorepo.md\` \xA7
|
|
|
2583
3157
|
}
|
|
2584
3158
|
|
|
2585
3159
|
// src/commands/execute.ts
|
|
2586
|
-
import
|
|
3160
|
+
import fs7 from "fs";
|
|
2587
3161
|
|
|
2588
3162
|
// src/lib/mcp-client.ts
|
|
2589
3163
|
var MCP_URL = "https://mcp.clawnify.com/mcp";
|
|
@@ -2633,7 +3207,7 @@ async function executeCommand(file, options) {
|
|
|
2633
3207
|
code = options.code;
|
|
2634
3208
|
} else if (file) {
|
|
2635
3209
|
try {
|
|
2636
|
-
code =
|
|
3210
|
+
code = fs7.readFileSync(file, "utf-8");
|
|
2637
3211
|
} catch (err) {
|
|
2638
3212
|
process.stderr.write(`Failed to read ${file}: ${String(err)}
|
|
2639
3213
|
`);
|
|
@@ -2688,8 +3262,8 @@ async function docsCommand(slug, options) {
|
|
|
2688
3262
|
process.exit(1);
|
|
2689
3263
|
}
|
|
2690
3264
|
const caller = options.caller ?? "external";
|
|
2691
|
-
const
|
|
2692
|
-
const res = await fetch(DOCS_URL +
|
|
3265
|
+
const path9 = slug ? `/docs/${auth.org_id}/${slug}.md?caller=${caller}` : `/docs/${auth.org_id}/index.md`;
|
|
3266
|
+
const res = await fetch(DOCS_URL + path9, {
|
|
2693
3267
|
headers: {
|
|
2694
3268
|
authorization: "Bearer " + token
|
|
2695
3269
|
}
|
|
@@ -2884,10 +3458,10 @@ Valid: ${ALL_AGENTS.join(", ")}`
|
|
|
2884
3458
|
async function runCli() {
|
|
2885
3459
|
const program = new Command();
|
|
2886
3460
|
program.name("clawnify").description("Deploy apps to Clawnify").version("0.1.0");
|
|
2887
|
-
program.command("init [dir]").description("Scaffold a new Clawnify project (app or
|
|
3461
|
+
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);
|
|
2888
3462
|
program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
|
|
2889
3463
|
program.command("login").description("Authenticate with Clawnify").action(loginCommand);
|
|
2890
|
-
program.command("deploy [dir]").description("Deploy an app or
|
|
3464
|
+
program.command("deploy [dir]").description("Deploy an app, website, or agent to Clawnify").option("--from <repo>", "Deploy from a GitHub repo (owner/repo)").option("--server <server-id>", "Agent deploy: the server hosting the target agent (saved as a link)").option("--agent <name>", "Agent deploy: the named agent to push to (default: main)").option("--path <subdir>", "Subdirectory within the --from repo that holds the app (monorepo)").option("--name <name>", "Override app name").option("--org <slug-or-id>", "Deploy to a specific org (overrides active org)").option("-y, --yes", "Non-interactive: on slug conflict, update existing app").option("--update-existing", "Non-interactive: on slug conflict, overwrite existing app").option("--create-new", "Non-interactive: on slug conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").option("--no-sync", "Skip the post-deploy schema.sql sync into the local working directory").action(deployCommand);
|
|
2891
3465
|
program.command("link <app-id-or-slug>").description("Link the current directory to an existing Clawnify app (accepts id or slug)").option("--dir <dir>", "Directory to link (default: cwd)").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(linkCommand);
|
|
2892
3466
|
const pull = program.command("pull").description("Pull artifacts from a deployed app into the current directory");
|
|
2893
3467
|
pull.command("schema").description("Fetch the deployed app's current schema.sql snapshot into the local repo").option("--from <app-id-or-slug>", "App to fetch from (required)").option("--out <path>", "Where to write (default: ./schema.sql)").option("--force", "Overwrite a locally-modified or uncommitted schema.sql").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(pullSchemaCommand);
|
|
@@ -2896,10 +3470,27 @@ async function runCli() {
|
|
|
2896
3470
|
org.command("use <slug-or-id>").description("Set the active org for global commands (ls, whoami, etc.)").action(orgUseCommand);
|
|
2897
3471
|
const connections = program.command("connections").description("Org integrations & the naming catalog");
|
|
2898
3472
|
connections.command("list").description("List canonical integration ids, provider keys, and custom env for the active org").option("--json", "Print the full catalog payload (includes docs + spec_url per integration)").action(connectionsListCommand);
|
|
3473
|
+
connections.command("connect <id>").description("Explain how to connect an integration (OAuth in the dashboard \u2014 the CLI/agent can't do it for you)").option("--json", "Print the steps as JSON").action(connectionsConnectCommand);
|
|
2899
3474
|
const workspace = program.command("workspace").description("Manage a monorepo that hosts an org's apps");
|
|
2900
3475
|
workspace.command("init [dir]").description("Scaffold a workspace monorepo bound to an org").option("--org <slug-or-id>", "Org to bind the workspace to (defaults to active org)").option("--name <name>", "Workspace display name (defaults to the org name)").action(workspaceInitCommand);
|
|
2901
3476
|
program.command("ls").description("List deployed apps").action(lsCommand);
|
|
2902
3477
|
program.command("logs <app-id>").description("Show build logs for an app").action(logsCommand);
|
|
3478
|
+
const servers = program.command("servers").description("List the org's agent servers");
|
|
3479
|
+
servers.command("list", { isDefault: true }).description("List the org's agent servers").action(serversListCommand);
|
|
3480
|
+
const sessions = program.command("sessions").description("Observe agent sessions (list + read transcripts)");
|
|
3481
|
+
sessions.command("list", { isDefault: true }).description("List stored sessions across all agents on the server").option("--server <id>", "Target server (default: the org's server, or a linked project)").option("--agent <slug>", "Only this agent's sessions").option("--active <minutes>", "Only sessions active within N minutes").option("--limit <n>", "Max rows (default 100)").option("--json", "Print the raw JSON payload").action(sessionsListCommand);
|
|
3482
|
+
sessions.command("history <key>").description("Read one session's transcript by key (e.g. agent:dnz---theo:lead:row_8268)").option("--server <id>", "Target server (default: the org's server, or a linked project)").option("--agent <slug>", "Owning agent (else derived from the key prefix)").option("--limit <n>", "Max transcript entries (default 100)").option("--json", "Print the raw JSON payload").action(sessionsHistoryCommand);
|
|
3483
|
+
const agents = program.command("agents").description("Manage agents: list, pull config to edit, push edits back");
|
|
3484
|
+
agents.command("list", { isDefault: true }).description("List the agents on the org's server").option("--server <id>", "Target server (default: the org's server)").action(agentsListCommand);
|
|
3485
|
+
agents.command("pull [dir]").description("Fetch an agent's AGENTS.md + skills/ + flows/ into a directory to edit").option("--server <id>", "Target server (default: the org's server)").option("--agent <slug>", "Which agent (default: main)").action(agentsPullCommand);
|
|
3486
|
+
agents.command("push [dir]").description("Push edited AGENTS.md + skills/ + flows/ back (additive; picked up next session)").option("--server <id>", "Target server (default: the linked/org's server)").option("--agent <slug>", "Which agent (default: the pulled agent, else main)").action(agentsPushCommand);
|
|
3487
|
+
agents.command("skills [agent]").description("Show an agent's effective skill inventory (what it can actually run, not just its workspace)").option("--server <id>", "Target server (default: the org's server)").action(agentsSkillsCommand);
|
|
3488
|
+
agents.command("grant-skill <skill>").description("Grant an existing (main-authored) skill to one agent (--to) or every agent (--all)").option("--server <id>", "Target server (default: the org's server)").option("--to <agent>", "Grant to one specialist agent").option("--all", "Grant to every agent (shared managed root; includes future agents)").action(agentsGrantSkillCommand);
|
|
3489
|
+
agents.command("create <slug>").description("Create a new specialist agent (RESTARTS the gateway \u2014 needs --yes)").option("--server <id>", "Target server (default: the org's server)").option("--name <name>", "Display name (default: the slug)").option("--description <role>", "The agent's role/specialization (seeded into its AGENTS.md)").option("--yes", "Confirm \u2014 proceed with the gateway restart").action(agentsCreateCommand);
|
|
3490
|
+
const env = program.command("env").description("Org custom environment variables (read via `connections list`)");
|
|
3491
|
+
env.command("set <key> <value>").description("Set an org-wide custom env var (NON-SECRET config; restarts the gateway to apply)").action(envSetCommand);
|
|
3492
|
+
env.command("unset <key>").description("Remove an org-wide custom env var (restarts the gateway to apply)").action(envUnsetCommand);
|
|
3493
|
+
program.command("api <path>").description("Raw authenticated request to the Clawnify API \u2014 for anything without a dedicated command").option("-X, --method <method>", "HTTP method (default GET, or POST when -d is given)").option("-d, --data <json>", "JSON request body").option("--org <slug-or-id>", "Org to scope the request to").action(apiCommand);
|
|
2903
3494
|
program.command("rm <app-id>").description("Delete an app").action(rmCommand);
|
|
2904
3495
|
program.command("open <slug>").description("Open an app in the browser").action(openCommand);
|
|
2905
3496
|
program.command("whoami").description("Show current user info").action(whoamiCommand);
|
|
@@ -2929,4 +3520,4 @@ async function runCli() {
|
|
|
2929
3520
|
export {
|
|
2930
3521
|
runCli
|
|
2931
3522
|
};
|
|
2932
|
-
//# sourceMappingURL=cli-
|
|
3523
|
+
//# sourceMappingURL=cli-BBJGGLQP.js.map
|