clawnify 0.12.2 → 0.13.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.
@@ -593,7 +593,7 @@ async function pollUntilReady(resourceId, options = {}) {
593
593
  }
594
594
 
595
595
  // src/version.ts
596
- var VERSION = "0.12.2";
596
+ var VERSION = "0.13.0";
597
597
 
598
598
  export {
599
599
  OAUTH_CLIENT_ID,
@@ -617,4 +617,4 @@ export {
617
617
  pollUntilReady,
618
618
  VERSION
619
619
  };
620
- //# sourceMappingURL=chunk-KUCNO2UZ.js.map
620
+ //# sourceMappingURL=chunk-K5JOOOE5.js.map
@@ -20,10 +20,10 @@ import {
20
20
  resolveOrgContext,
21
21
  saveAuth,
22
22
  saveProject
23
- } from "./chunk-KUCNO2UZ.js";
23
+ } from "./chunk-K5JOOOE5.js";
24
24
 
25
25
  // src/cli.ts
26
- import { Command } from "commander";
26
+ import { Command, Option } from "commander";
27
27
 
28
28
  // src/commands/login.ts
29
29
  import crypto from "crypto";
@@ -274,6 +274,33 @@ function hasUncommittedChanges(dir, filePath) {
274
274
  }
275
275
  }
276
276
 
277
+ // src/lib/servers.ts
278
+ async function resolveServerId(explicit) {
279
+ if (explicit) return explicit;
280
+ const linked = readProject()?.server_id;
281
+ if (linked) return linked;
282
+ const res = await api.get("/servers");
283
+ if (!res.ok) {
284
+ console.error("Failed to list agents. Run `clawnify login` and try again.");
285
+ process.exit(1);
286
+ }
287
+ const { servers } = await res.json();
288
+ if (!servers || servers.length === 0) {
289
+ console.error(
290
+ "No agents in this org yet. Hire one at https://app.clawnify.com."
291
+ );
292
+ process.exit(1);
293
+ }
294
+ if (servers.length === 1) return servers[0].id;
295
+ console.error(
296
+ "This org has several agents \u2014 pick one with --agent-id <id> (see `clawnify agents list`):\n"
297
+ );
298
+ for (const s of servers) {
299
+ console.error(` ${s.id} ${s.name ?? "(unnamed)"} [${s.status}]`);
300
+ }
301
+ process.exit(1);
302
+ }
303
+
277
304
  // src/commands/deploy.ts
278
305
  var EXIT_USAGE = 64;
279
306
  var EXIT_CONFLICT_NEEDS_DECISION = 75;
@@ -589,17 +616,8 @@ function assembleAgentFiles(dir) {
589
616
  async function deployAgent(dir, options) {
590
617
  const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
591
618
  const linked = readProject(resolvedDir);
592
- const serverId = options.server || linked?.server_id;
619
+ const serverId = await resolveServerId(options.server || linked?.server_id);
593
620
  const agentName = options.agent || linked?.agent_name || "main";
594
- if (!serverId) {
595
- console.error(
596
- `This agent isn't linked to a server yet.
597
- Link it on first deploy:
598
- clawnify deploy --server <server-id> --agent <name>
599
- (agent defaults to "main" if omitted).`
600
- );
601
- process.exit(EXIT_USAGE);
602
- }
603
621
  const files = assembleAgentFiles(resolvedDir);
604
622
  if (files.length === 0) {
605
623
  console.error(
@@ -623,14 +641,14 @@ async function deployAgent(dir, options) {
623
641
  }
624
642
  if (options.dryRun) {
625
643
  console.log(`
626
- Dry run \u2014 would deploy to server ${serverId}, agent "${agentName}"`);
644
+ Dry run \u2014 would deploy to agent "${agentName}" (${serverId})`);
627
645
  for (const f of files) {
628
646
  console.log(` ${f.path} (${Buffer.byteLength(f.content, "utf8")} bytes)`);
629
647
  }
630
648
  console.log();
631
649
  return;
632
650
  }
633
- console.log(`Deploying agent \u2192 server ${serverId}, agent "${agentName}"...`);
651
+ console.log(`Deploying \u2192 agent "${agentName}" (${serverId})...`);
634
652
  const res = await api.post(
635
653
  `/servers/${serverId}/deploy-agent`,
636
654
  { agent: agentName, files },
@@ -925,33 +943,6 @@ async function logsCommand(appId) {
925
943
  }
926
944
  }
927
945
 
928
- // src/lib/servers.ts
929
- async function resolveServerId(explicit) {
930
- if (explicit) return explicit;
931
- const linked = readProject()?.server_id;
932
- if (linked) return linked;
933
- const res = await api.get("/servers");
934
- if (!res.ok) {
935
- console.error("Failed to list servers. Run `clawnify login` and try again.");
936
- process.exit(1);
937
- }
938
- const { servers } = await res.json();
939
- if (!servers || servers.length === 0) {
940
- console.error(
941
- "No agent server in this org yet. Provision one at https://app.clawnify.com."
942
- );
943
- process.exit(1);
944
- }
945
- if (servers.length === 1) return servers[0].id;
946
- console.error(
947
- "This org has multiple servers \u2014 pick one with --server <id> (or run `clawnify servers`):\n"
948
- );
949
- for (const s of servers) {
950
- console.error(` ${s.id} ${s.name ?? "(unnamed)"} [${s.status}]`);
951
- }
952
- process.exit(1);
953
- }
954
-
955
946
  // src/commands/sessions.ts
956
947
  async function sessionsListCommand(opts) {
957
948
  const serverId = await resolveServerId(opts.server);
@@ -1035,35 +1026,48 @@ async function sessionsHistoryCommand(key, opts) {
1035
1026
  // src/commands/agents.ts
1036
1027
  import fs3 from "fs";
1037
1028
  import path3 from "path";
1038
- async function agentsListCommand(opts) {
1039
- const serverId = await resolveServerId(opts.server);
1040
- const res = await api.get(`/servers/${serverId}/agents`);
1029
+ async function agentsListCommand() {
1030
+ const res = await api.get("/agents");
1041
1031
  if (!res.ok) {
1042
1032
  console.error(`Failed to list agents (${res.status}).`);
1043
1033
  process.exit(1);
1044
1034
  }
1045
- const payload = await res.json();
1046
- const agents = Array.isArray(payload) ? payload : payload.agents;
1035
+ const { agents } = await res.json();
1047
1036
  if (!agents || agents.length === 0) {
1048
- console.log("No agents on this server.");
1037
+ console.log("No agents in this org yet. Hire one at https://app.clawnify.com.");
1049
1038
  return;
1050
1039
  }
1051
- const idW = Math.max(2, ...agents.map((a) => (a.id ?? "").length));
1052
- const nameW = Math.max(4, ...agents.map((a) => (a.name ?? "").length));
1053
- console.log(`${"ID".padEnd(idW)} ${"Name".padEnd(nameW)} ${"Status".padEnd(8)} Sessions`);
1054
- console.log(`${"\u2500".repeat(idW)} ${"\u2500".repeat(nameW)} ${"\u2500".repeat(8)} ${"\u2500".repeat(8)}`);
1055
1040
  for (const a of agents) {
1056
- console.log(
1057
- `${(a.id ?? "").padEnd(idW)} ${(a.name ?? "").padEnd(nameW)} ${(a.status ?? "").padEnd(8)} ${a.sessionCount ?? 0}`
1058
- );
1041
+ const label = a.name?.trim() || "(unnamed)";
1042
+ const meta = [a.status, a.region].filter(Boolean).join(", ");
1043
+ console.log(`
1044
+ ${label}${meta ? ` (${meta})` : ""}`);
1045
+ console.log(` id: ${a.agent_id}`);
1046
+ if (a.sub_agents_unavailable) {
1047
+ console.log(" sub-agents: unavailable (agent unreachable right now)");
1048
+ continue;
1049
+ }
1050
+ const subs = a.sub_agents ?? [];
1051
+ if (subs.length === 0) {
1052
+ console.log(" sub-agents: none");
1053
+ continue;
1054
+ }
1055
+ console.log(" sub-agents:");
1056
+ for (const s of subs) {
1057
+ const sessions = s.session_count ?? 0;
1058
+ console.log(
1059
+ ` \u2514\u2500 ${s.id}${s.name && s.name !== s.id ? ` (${s.name})` : ""} ${sessions} session${sessions === 1 ? "" : "s"}`
1060
+ );
1061
+ }
1059
1062
  }
1063
+ console.log();
1060
1064
  }
1061
1065
  async function agentsPullCommand(dir, opts) {
1062
1066
  const serverId = await resolveServerId(opts.server);
1063
1067
  const agent = opts.agent || "main";
1064
1068
  const res = await api.get(`/servers/${serverId}/agent-config?agent=${encodeURIComponent(agent)}`);
1065
1069
  if (!res.ok) {
1066
- if (res.status === 404) console.error(`Agent "${agent}" not found on this server.`);
1070
+ if (res.status === 404) console.error(`No agent or sub-agent named "${agent}" in this org.`);
1067
1071
  else console.error(`Failed to read agent config (${res.status}).`);
1068
1072
  process.exit(1);
1069
1073
  }
@@ -1141,7 +1145,7 @@ async function agentsSkillsCommand(agent, opts) {
1141
1145
  const who = agent || "main";
1142
1146
  const res = await api.get(`/servers/${serverId}/agent-skills?agent=${encodeURIComponent(who)}`);
1143
1147
  if (!res.ok) {
1144
- if (res.status === 404) console.error(`Agent "${who}" not found on this server.`);
1148
+ if (res.status === 404) console.error(`No agent or sub-agent named "${who}" in this org.`);
1145
1149
  else console.error(`Failed to read skills (${res.status}).`);
1146
1150
  process.exit(1);
1147
1151
  }
@@ -1152,7 +1156,7 @@ async function agentsGrantSkillCommand(skill, opts) {
1152
1156
  const serverId = await resolveServerId(opts.server);
1153
1157
  if (!opts.all && !opts.to) {
1154
1158
  console.error(
1155
- "Specify who gets the skill: --to <agent> (one specialist) or --all (every agent on the box)."
1159
+ "Specify who gets the skill: --to <agent> (one sub-agent) or --all (every agent)."
1156
1160
  );
1157
1161
  process.exit(1);
1158
1162
  }
@@ -1179,7 +1183,7 @@ async function agentsCreateCommand(slug, opts) {
1179
1183
  const serverId = await resolveServerId(opts.server);
1180
1184
  if (!opts.yes) {
1181
1185
  console.error(
1182
- `This creates agent "${slug}" and RESTARTS the gateway (~20-40s), briefly interrupting every agent on the server.
1186
+ `This creates agent "${slug}" and RESTARTS the gateway (~20-40s), briefly interrupting this agent and its sub-agents.
1183
1187
  Re-run with --yes once the user has confirmed: clawnify agents create ${slug} --yes`
1184
1188
  );
1185
1189
  process.exit(1);
@@ -1402,7 +1406,7 @@ function agentByName(name) {
1402
1406
  var ALL_AGENTS = DETECTORS.map((d) => d.agent);
1403
1407
 
1404
1408
  // src/lib/skills/content.gen.ts
1405
- var CLI_VERSION = "0.12.2";
1409
+ var CLI_VERSION = "0.13.0";
1406
1410
  var BUNDLED_SKILLS = [
1407
1411
  {
1408
1412
  name: "build-a-clawnify-app",
@@ -1412,12 +1416,12 @@ var BUNDLED_SKILLS = [
1412
1416
  {
1413
1417
  name: "use-the-clawnify-cli",
1414
1418
  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.",
1415
- content: "# Use the Clawnify CLI\n\nCanonical skill: how to drive the `clawnify` CLI. Same content for\nhumans and for AI coding agents operating a terminal.\n\nFor **authoring app code** (stack, schema, tRPC patterns), use the\n`build-a-clawnify-app` skill \u2014 this one covers the tooling around it.\n\n## TL;DR\n\n```bash\nnpm i -g clawnify # or: npx clawnify@latest <command>\nclawnify login # browser sign-in, paste-code fallback\nclawnify init my-app # scaffold an app or website\ncd my-app && clawnify dev\nclawnify deploy # \u2192 https://<slug>.apps.clawnify.com\n```\n\n- **Auth once, org lazily.** `login` only signs you in; the first\n command that needs an organization asks once and remembers it.\n- **A directory links to one app.** `deploy` from a linked directory\n updates that app; `clawnify link <id-or-slug>` adopts an existing one.\n- **Non-interactive flags exist for every prompt** \u2014 use them in\n scripts and CI (`-y`, `--update-existing`, `--create-new`, `--org`).\n\n## Authenticate\n\n```bash\nclawnify login # opens the browser; also prints the sign-in URL\nclawnify whoami # current user, active org (if linked)\n```\n\n`login` works from any browser: if the browser runs on the same\nmachine, sign-in completes automatically; otherwise the page shows a\ncode to paste back at the `Paste code here if prompted >` prompt\n(useful over SSH \u2014 no port forwarding needed).\n\n**Headless / CI / agents \u2014 skip `login` entirely.** Set `CLAWNIFY_TOKEN` (a\nSupabase access token) and it wins over any stored session, reading/writing no\nfiles; `CLAWNIFY_ORG_ID` (or a per-command `--org`) pins the org. This is how a\ncoding agent runs the CLI without a browser.\n\n### Organizations\n\nYou belong to one or more orgs; apps live inside an org.\n\n```bash\nclawnify org list # orgs you belong to (* marks active)\nclawnify org use <slug-or-id> # switch the active org\n```\n\nNo need to pick one up front \u2014 the first org-scoped command prompts\nonce and persists the choice. Any single command can override with\n`--org <slug-or-id>`.\n\n## Create and run locally\n\n```bash\nclawnify init [dir] # interactive: app or website\nclawnify init my-app -y # non-interactive defaults (blank app)\nclawnify init --type app --template crud --name my-app\nclawnify init --type website --name my-site\nclawnify dev [dir] [--port 8787] # local dev server\n```\n\n`init` also installs AI files (rules + skills + MCP config) for any\ncoding agents detected in the project; skip with `--no-ai-files`.\n\n## Deploy\n\n```bash\nclawnify deploy # deploy the current directory\nclawnify deploy path/to/app\nclawnify deploy --from owner/repo # deploy straight from GitHub\nclawnify deploy --from owner/repo --path apps/web # monorepo subdir\nclawnify deploy --dry-run # list files that would upload\n```\n\nFirst deploy creates the app and links the directory (writes a local\nproject file); later deploys update the same app. On a slug conflict\nyou'll be asked \u2014 or decide up front:\n\n```bash\nclawnify deploy -y # reuse/update the existing app\nclawnify deploy --update-existing # same, explicit\nclawnify deploy --create-new # take the suggested new slug\n```\n\nLink an existing deployed app to the current directory instead of\ncreating a new one:\n\n```bash\nclawnify link <app-id-or-slug>\n```\n\n## Inspect and manage deployed apps\n\n```bash\nclawnify ls # list deployed apps in the active org\nclawnify logs <app-id> # build logs\nclawnify open <slug> # open the live app in the browser\nclawnify rm <app-id> # delete an app\nclawnify pull schema --from <app-id-or-slug> # fetch live schema.sql\nclawnify docs [slug] # usage README for an app (org index if omitted)\n```\n\n`pull schema` refuses to clobber local uncommitted changes unless you\npass `--force`.\n\n## Manage agents (the FDE surface)\n\nDrive an org's AI agents from the terminal \u2014 observe them and fix them. See the\n`fix-a-clawnify-agent` skill for the workflow; this is the command list. All\norg-scoped and **repo-independent** (reads session data + the box, never a\nGitHub repo). Add `--server <id>` when the org has more than one server.\n\n```bash\nclawnify servers list # the org's servers (an org can have several)\nclawnify agents list # agents on a server (main + specialists)\nclawnify agents skills [agent] # what an agent can ACTUALLY run (not just its workspace)\nclawnify sessions --agent <slug> --json # stored sessions + token counters (contextTokens = bloat)\nclawnify sessions history <key> --json # one session's transcript \u2014 where it veered\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/ to edit (flows/ come with main only \u2014 flows belong to the main agent)\nclawnify agents push [dir] # push edits back (additive; next session, no restart)\nclawnify agents grant-skill <s> --to <a> # share a main-authored skill (or --all for every agent)\nclawnify agents create <slug> --yes # new 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)\nclawnify flows list # the main agent's flows + latest published version\nclawnify flows read <name> # print a flow's draft\nclawnify flows create <name> --file f.json # new draft (validated on save)\nclawnify flows edit <name> # edit the draft ($EDITOR, or --file to replace)\nclawnify flows publish <name> # cut the next numbered live version\n```\n\n**Flows:** runs and triggers use the latest **published** version, so editing a\ndraft doesn't change what's live \u2014 until a flow's first publish, though, the\ndraft *is* what runs. `create`/`edit`/`publish` validate automatically and\nreport per-node errors; fix and re-save. Prefer these verbs over pushing raw\n`flows/*.json` edits (which skip validation and versioning).\n\n**Boundary:** everything above is autonomous *except* the human-auth actions \u2014\nconnecting an integration (OAuth) and handing over a secret/API key. For those,\nexplain the dashboard steps; never fake them. `agents create` / `env set`\nrestart the gateway, so confirm before running them on a busy 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"
1419
+ 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 live agent state, never a GitHub\nrepo).\n\n**The model \u2014 two levels, and only two.** An org has one or more **agents** (the\nAI employees, e.g. \"Ash\"). Each agent can have **sub-agents**: narrower helpers\nit delegates to. `clawnify agents list` prints both, sub-agents indented under\nthe agent that owns them:\n\n```\nAsh (ready, nbg1)\n id: 7c2f\u2026\n sub-agents:\n \u2514\u2500 research (Research) 4 sessions\n```\n\nAn org normally has exactly one agent, so nothing needs to be selected. When it\nhas several, pass `--agent-id <id>` (the `id:` line above).\n\n```bash\nclawnify agents list # the org's agents, each with its sub-agents\nclawnify agents skills [agent] # what an agent can ACTUALLY run (not just its workspace)\nclawnify sessions --agent <slug> --json # stored sessions + token counters (contextTokens = bloat)\nclawnify sessions history <key> --json # one session's transcript \u2014 where it veered\nclawnify agents pull [dir] --agent <slug> # fetch AGENTS.md + skills/ to edit (flows/ come with main only \u2014 flows belong to the main agent)\nclawnify agents push [dir] # push edits back (additive; next session, no restart)\nclawnify agents grant-skill <s> --to <a> # share a main-authored skill (or --all for every agent)\nclawnify agents create <slug> --yes # new SUB-AGENT (RESTARTS the gateway)\nclawnify env set <KEY> <VALUE> # org custom env \u2014 NON-SECRET only (restarts gateway)\nclawnify connections connect <id> # how to connect an integration (dashboard OAuth; you can't)\nclawnify flows list # the main agent's flows + latest published version\nclawnify flows read <name> # print a flow's draft\nclawnify flows create <name> --file f.json # new draft (validated on save)\nclawnify flows edit <name> # edit the draft ($EDITOR, or --file to replace)\nclawnify flows publish <name> # cut the next numbered live version\n```\n\n**Flows:** runs and triggers use the latest **published** version, so editing a\ndraft doesn't change what's live \u2014 until a flow's first publish, though, the\ndraft *is* what runs. `create`/`edit`/`publish` validate automatically and\nreport per-node errors; fix and re-save. Prefer these verbs over pushing raw\n`flows/*.json` edits (which skip validation and versioning).\n\n**Boundary:** everything above is autonomous *except* the human-auth actions \u2014\nconnecting an integration (OAuth) and handing over a secret/API key. For those,\nexplain the dashboard steps; never fake them. `agents create` / `env set`\nrestart the gateway, so confirm before running them on a busy agent.\n\n**`agents create` makes a NEW sub-agent \u2014 it is never the way to \"find\" an\nexisting one.** If you were looking for an agent and `agents list` didn't show\nit, the answer is that the org doesn't have it, or you're in the wrong org\n(`clawnify org list`). Creating one restarts the gateway and leaves a duplicate\nbehind.\n\n## Connections & env names\n\n```bash\nclawnify connections list # the org's naming catalog (\u25CF connected / \u25CB not)\nclawnify connections connect <id> # how to connect one \u2014 dashboard OAuth; the CLI/agent can't do it for you\n```\n\nLists the active org's integrations (canonical ids + connected state),\nprovider API keys (fixed names + set state), and custom env vars. Read\nit before declaring `credentials` or env names in `clawnify.json` and\nreuse the exact identifiers it shows \u2014 a misspelled id or key name\ndoesn't fail the build, it silently resolves to nothing at runtime.\n\n## Workspaces (one repo, one org's apps)\n\n```bash\nclawnify workspace init [dir] [--org <slug-or-id>]\n```\n\nScaffolds a monorepo bound to an org; apps scaffolded inside land\nunder `apps/` and inherit the org on deploy.\n\n## Wire up coding agents\n\n```bash\nclawnify ai-files install # rules + skills + MCP server in one step\nclawnify skills list # bundled skills\nclawnify skills add <name> # install one into detected agents\nclawnify mcp # stdio MCP bridge (Claude Desktop, etc.)\n```\n\n`ai-files install` detects agent config dirs in the project (Claude\nCode, Cursor, OpenClaw, Codex, Aider) and writes the always-on rules\nblock, installs bundled skills, and adds the Clawnify MCP server to\n`.mcp.json`. Target one agent with `--agent <name>`; undo with\n`clawnify ai-files uninstall`.\n\n## The raw escape hatch\n\n```bash\nclawnify api /agents # any GET\nclawnify api /apps -X POST -d '{\u2026}' # any method + JSON body\n```\n\n`clawnify api <path>` makes an authenticated request to any Clawnify API path \u2014\nsame auth and org scoping as every other command (it can only do what you can).\nUse it for anything the porcelain doesn't wrap; the curated commands stay small\nbecause this is always there.\n\n## Tips\n\n- `npx clawnify@latest <command>` always runs the newest release.\n- Every org-scoped command accepts `--org` \u2014 prefer it in scripts over\n relying on the saved active org.\n- If sign-in ever fails mid-flow, just run `clawnify login` again; it\n is safe to repeat.\n"
1416
1420
  },
1417
1421
  {
1418
1422
  name: "fix-a-clawnify-agent",
1419
1423
  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.`,
1420
- 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/`). 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- Edit **flows** with `clawnify flows edit <name>` then `clawnify flows\n publish <name>` \u2014 validated on save; once a flow has a published version,\n runs and triggers keep using it until you publish again (before the first\n publish, the draft is what runs). Raw `flows/*.json` edits via the repo also\n land, but skip validation and versioning.\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"
1424
+ 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\" \u2014 is the executor. When it\nmisbehaves your job is to **read what it actually did, find the real cause, and\nchange the durable inputs.** Not to patch instructions blind, and not to burn\nthe agent's own (expensive) model tokens on trial-and-error.\n\n**Know what you're looking at.** An org has one or more **agents** (the\nemployees). Each may have **sub-agents** \u2014 narrower helpers it delegates to.\n`clawnify agents list` shows both, sub-agents indented under their agent. That\nis the whole hierarchy; there is no other tier to go looking for.\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 agents list # the org's agents + their sub-agents \u2014 START HERE\nclawnify sessions # every agent's sessions, 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/`). Push via the org's **GitHub\n sync repo** (auto-deploys to the agent) or `clawnify deploy`. See the\n `use-the-clawnify-cli` skill for the commands.\n- Edit **flows** with `clawnify flows edit <name>` then `clawnify flows\n publish <name>` \u2014 validated on save; once a flow has a published version,\n runs and triggers keep using it until you publish again (before the first\n publish, the draft is what runs). Raw `flows/*.json` edits via the repo also\n land, but skip validation and versioning.\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 agent.\n- **Never run `agents create` to \"find\" an agent.** It creates a *new sub-agent*\n and restarts the gateway. If the agent you expected isn't in `clawnify agents\n list`, you are in the wrong org (`clawnify org list`) or it genuinely doesn't\n exist \u2014 ask. Creating one leaves a duplicate the customer then has to live\n with, and interrupts the real agent while it does.\n- Prefer the **smallest durable fix** (a session habit, a tightened `AGENTS.md`,\n one flow) over more instructions.\n"
1421
1425
  }
1422
1426
  ];
1423
1427
  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";
@@ -3793,7 +3797,7 @@ async function flowsListCommand(opts) {
3793
3797
  return;
3794
3798
  }
3795
3799
  if (!flows || flows.length === 0) {
3796
- console.log("No flows on this server. Create one with: clawnify flows create <name> --file flow.json");
3800
+ console.log("This agent has no flows yet. Create one with: clawnify flows create <name> --file flow.json");
3797
3801
  return;
3798
3802
  }
3799
3803
  const nameW = Math.max(4, ...flows.map((f) => f.flow.length));
@@ -3809,7 +3813,7 @@ async function flowsReadCommand(name, opts) {
3809
3813
  const serverId = await resolveServerId(opts.server);
3810
3814
  const res = await api.get(`/servers/${serverId}/flows?name=${encodeURIComponent(flowFileName(name))}`);
3811
3815
  if (!res.ok) {
3812
- if (res.status === 404) console.error(`No draft flow named "${name}" on this server.`);
3816
+ if (res.status === 404) console.error(`No draft flow named "${name}" on this agent.`);
3813
3817
  else console.error(`Failed to read flow (${res.status}).`);
3814
3818
  process.exit(1);
3815
3819
  }
@@ -3835,7 +3839,7 @@ async function flowsEditCommand(name, opts) {
3835
3839
  const serverId = await resolveServerId(opts.server);
3836
3840
  const existing = await findDraft(serverId, name);
3837
3841
  if (!existing) {
3838
- console.error(`No draft flow named "${name}" on this server. Create it with: clawnify flows create ${name} --file flow.json`);
3842
+ console.error(`No draft flow named "${name}" on this agent. Create it with: clawnify flows create ${name} --file flow.json`);
3839
3843
  process.exit(1);
3840
3844
  }
3841
3845
  let flow;
@@ -3884,7 +3888,7 @@ async function flowsPublishCommand(name, opts) {
3884
3888
  const res = await api.post(`/servers/${serverId}/flows/publish`, { name });
3885
3889
  const payload = await res.json().catch(() => ({}));
3886
3890
  if (res.status === 404) {
3887
- console.error(`No draft flow named "${name}" on this server \u2014 nothing to publish.`);
3891
+ console.error(`No draft flow named "${name}" on this agent \u2014 nothing to publish.`);
3888
3892
  process.exit(1);
3889
3893
  }
3890
3894
  if (res.status === 422 && payload.errors) failValidation(payload);
@@ -3896,16 +3900,34 @@ async function flowsPublishCommand(name, opts) {
3896
3900
  }
3897
3901
 
3898
3902
  // src/cli.ts
3903
+ function agentIdOption() {
3904
+ return new Option(
3905
+ "--agent-id <id>",
3906
+ "Target agent (default: the org's agent, or a linked project)"
3907
+ );
3908
+ }
3909
+ function legacyServerOption() {
3910
+ return new Option("--server <id>").hideHelp();
3911
+ }
3899
3912
  async function runCli() {
3900
3913
  const program = new Command();
3901
3914
  program.name("clawnify").description("Deploy apps to Clawnify").version(VERSION).addHelpText(
3902
3915
  "after",
3903
3916
  "\nCoding agent? Start with `clawnify workspace` \u2014 it prints the org's synced\nGitHub repo, what maps where, and how local editing works.\n"
3904
3917
  );
3918
+ program.hook("preAction", (_program, actionCommand) => {
3919
+ const opts = actionCommand.opts();
3920
+ if (opts.agentId && !opts.server) actionCommand.setOptionValue("server", opts.agentId);
3921
+ });
3905
3922
  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);
3906
3923
  program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
3907
3924
  program.command("login").description("Authenticate with Clawnify").action(loginCommand);
3908
- 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 conflict, update the existing app").option("--update-existing", "Non-interactive: on conflict, overwrite the existing app").option("--create-new", "Non-interactive: on conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").option("--no-sync", "Skip the post-deploy schema.sql sync into the local working directory").action(deployCommand);
3925
+ program.command("deploy [dir]").description("Deploy an app, website, or agent to Clawnify").option("--from <repo>", "Deploy from a GitHub repo (owner/repo)").addOption(
3926
+ new Option(
3927
+ "--agent-id <id>",
3928
+ "Agent deploy: which agent to push to when the org has several (saved as a link)"
3929
+ )
3930
+ ).addOption(legacyServerOption()).option("--agent <name>", "Agent deploy: the named agent to push to (default: main)").option("--path <subdir>", "Subdirectory within the --from repo that holds the app (monorepo)").option("--name <name>", "Override app name").option("--org <slug-or-id>", "Deploy to a specific org (overrides active org)").option("-y, --yes", "Non-interactive: on conflict, update the existing app").option("--update-existing", "Non-interactive: on conflict, overwrite the existing app").option("--create-new", "Non-interactive: on conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").option("--no-sync", "Skip the post-deploy schema.sql sync into the local working directory").action(deployCommand);
3909
3931
  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);
3910
3932
  const pull = program.command("pull").description("Pull artifacts from a deployed app into the current directory");
3911
3933
  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);
@@ -3920,24 +3942,24 @@ async function runCli() {
3920
3942
  workspace.command("connect").description("Enable GitHub sync: create/join the org's workspace repo and link the website").option("--account <login-or-id>", "GitHub account to use when several are connected").action(workspaceConnectCommand);
3921
3943
  program.command("ls").description("List deployed apps").action(lsCommand);
3922
3944
  program.command("logs <app-id>").description("Show build logs for an app").action(logsCommand);
3923
- const servers = program.command("servers").description("List the org's agent servers");
3924
- servers.command("list", { isDefault: true }).description("List the org's agent servers").action(serversListCommand);
3945
+ const servers = program.command("servers", { hidden: true }).description("Deprecated \u2014 use `clawnify agents list`");
3946
+ servers.command("list", { isDefault: true }).description("Deprecated \u2014 use `clawnify agents list`").action(serversListCommand);
3925
3947
  const sessions = program.command("sessions").description("Observe agent sessions (list + read transcripts)");
3926
- 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);
3927
- 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);
3948
+ sessions.command("list", { isDefault: true }).description("List stored sessions across an agent and its sub-agents").addOption(agentIdOption()).addOption(legacyServerOption()).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);
3949
+ sessions.command("history <key>").description("Read one session's transcript by key (e.g. agent:dnz---theo:lead:row_8268)").addOption(agentIdOption()).addOption(legacyServerOption()).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);
3928
3950
  const agents = program.command("agents").description("Manage agents: list, pull config to edit, push edits back");
3929
- 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);
3930
- 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);
3931
- 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);
3932
- 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);
3933
- 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);
3934
- 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);
3951
+ agents.command("list", { isDefault: true }).description("List the org's agents and their sub-agents").addOption(agentIdOption()).addOption(legacyServerOption()).action(agentsListCommand);
3952
+ agents.command("pull [dir]").description("Fetch an agent's AGENTS.md + skills/ + flows/ into a directory to edit").addOption(agentIdOption()).addOption(legacyServerOption()).option("--agent <slug>", "Which agent (default: main)").action(agentsPullCommand);
3953
+ agents.command("push [dir]").description("Push edited AGENTS.md + skills/ + flows/ back (additive; picked up next session)").addOption(agentIdOption()).addOption(legacyServerOption()).option("--agent <slug>", "Which agent (default: the pulled agent, else main)").action(agentsPushCommand);
3954
+ agents.command("skills [agent]").description("Show an agent's effective skill inventory (what it can actually run, not just its workspace)").addOption(agentIdOption()).addOption(legacyServerOption()).action(agentsSkillsCommand);
3955
+ agents.command("grant-skill <skill>").description("Grant an existing (main-authored) skill to one agent (--to) or every agent (--all)").addOption(agentIdOption()).addOption(legacyServerOption()).option("--to <agent>", "Grant to one sub-agent").option("--all", "Grant to every agent (shared managed root; includes future agents)").action(agentsGrantSkillCommand);
3956
+ agents.command("create <slug>").description("Create a new sub-agent (RESTARTS the gateway \u2014 needs --yes)").addOption(agentIdOption()).addOption(legacyServerOption()).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);
3935
3957
  const flows = program.command("flows").description("Manage the main agent's ClawFlows: create/edit drafts, publish versions");
3936
- flows.command("list", { isDefault: true }).description("List flow drafts and their latest published version").option("--server <id>", "Target server (default: the org's server)").option("--json", "Print the raw JSON payload").action(flowsListCommand);
3937
- flows.command("read <name>").description("Print a flow's current draft definition").option("--server <id>", "Target server (default: the org's server)").action(flowsReadCommand);
3938
- flows.command("create <name>").description("Create a flow draft from a local JSON definition").option("--file <path>", "Flow definition JSON (required)").option("--server <id>", "Target server (default: the org's server)").action(flowsCreateCommand);
3939
- flows.command("edit <name>").description("Replace a flow draft \u2014 from --file, or interactively via $EDITOR").option("--file <path>", "Flow definition JSON (default: open the current draft in $EDITOR)").option("--server <id>", "Target server (default: the org's server)").action(flowsEditCommand);
3940
- flows.command("publish <name>").description("Validate the draft and publish it as the next numbered version").option("--server <id>", "Target server (default: the org's server)").action(flowsPublishCommand);
3958
+ flows.command("list", { isDefault: true }).description("List flow drafts and their latest published version").addOption(agentIdOption()).addOption(legacyServerOption()).option("--json", "Print the raw JSON payload").action(flowsListCommand);
3959
+ flows.command("read <name>").description("Print a flow's current draft definition").addOption(agentIdOption()).addOption(legacyServerOption()).action(flowsReadCommand);
3960
+ flows.command("create <name>").description("Create a flow draft from a local JSON definition").option("--file <path>", "Flow definition JSON (required)").addOption(agentIdOption()).addOption(legacyServerOption()).action(flowsCreateCommand);
3961
+ flows.command("edit <name>").description("Replace a flow draft \u2014 from --file, or interactively via $EDITOR").option("--file <path>", "Flow definition JSON (default: open the current draft in $EDITOR)").addOption(agentIdOption()).addOption(legacyServerOption()).action(flowsEditCommand);
3962
+ flows.command("publish <name>").description("Validate the draft and publish it as the next numbered version").addOption(agentIdOption()).addOption(legacyServerOption()).action(flowsPublishCommand);
3941
3963
  const env = program.command("env").description("Org custom environment variables (read via `connections list`)");
3942
3964
  env.command("set <key> <value>").description("Set an org-wide custom env var (NON-SECRET config; restarts the gateway to apply)").action(envSetCommand);
3943
3965
  env.command("unset <key>").description("Remove an org-wide custom env var (restarts the gateway to apply)").action(envUnsetCommand);
@@ -3971,4 +3993,4 @@ async function runCli() {
3971
3993
  export {
3972
3994
  runCli
3973
3995
  };
3974
- //# sourceMappingURL=cli-XNXKX3EA.js.map
3996
+ //# sourceMappingURL=cli-JMDZKGYU.js.map