@bendyline/gezel-cli 1.0.5 → 1.0.7

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.
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/bin/gezel.ts
4
- import { basename as basename3 } from "path";
5
- import { GEZEL_VERSION } from "@bendyline/gezel";
4
+ import { basename as basename4, isAbsolute as isAbsolutePath, join as joinPath } from "path";
5
+ import { GEZEL_VERSION, getLogOutput, setLogOutput } from "@bendyline/gezel";
6
6
  import {
7
7
  streamChatEvents
8
8
  } from "@bendyline/gezel-client";
@@ -646,6 +646,170 @@ async function saveArtifact(client, projectId, artifactPath, output) {
646
646
  return dest;
647
647
  }
648
648
 
649
+ // src/knowledge-install.ts
650
+ import { resolve as resolve3 } from "path";
651
+ var SHA256_PATTERN = /^[0-9a-f]{64}$/i;
652
+ function resolveKnowledgeInstallSource(source, expectedSha256) {
653
+ if (/^https?:\/\//i.test(source)) {
654
+ if (expectedSha256 && !SHA256_PATTERN.test(expectedSha256)) {
655
+ throw new CliError("--sha256 must be exactly 64 hexadecimal characters.");
656
+ }
657
+ return {
658
+ kind: "url",
659
+ url: source,
660
+ ...expectedSha256 ? { expectedSha256: expectedSha256.toLowerCase() } : {}
661
+ };
662
+ }
663
+ if (expectedSha256) {
664
+ throw new CliError("--sha256 is only valid for URL installs.");
665
+ }
666
+ return { kind: "file", path: resolve3(source) };
667
+ }
668
+
669
+ // src/model-export.ts
670
+ import { randomUUID as randomUUID2 } from "crypto";
671
+ import { rename, rm as rm2, stat } from "fs/promises";
672
+ import { basename as basename3, dirname as dirname3, isAbsolute, resolve as resolve4 } from "path";
673
+ import {
674
+ modelBytesFromResponse,
675
+ portableGezmodelFilename,
676
+ verifyModelBundleArchive,
677
+ writeModelBundleResponse
678
+ } from "@bendyline/gezel-client/node";
679
+ async function resolveExportPath(id, destination, cwd) {
680
+ const fallback = portableGezmodelFilename(id);
681
+ if (!destination) return resolve4(cwd, fallback);
682
+ const full = isAbsolute(destination) ? resolve4(destination) : resolve4(cwd, destination);
683
+ const endsWithSeparator = /[/\\]$/.test(destination);
684
+ const isDirectory = endsWithSeparator || await isExistingDirectory(full);
685
+ if (isDirectory) return resolve4(full, fallback);
686
+ return full.toLowerCase().endsWith(".gezmodel") ? full : `${full}.gezmodel`;
687
+ }
688
+ async function isExistingDirectory(path) {
689
+ try {
690
+ return (await stat(path)).isDirectory();
691
+ } catch {
692
+ return false;
693
+ }
694
+ }
695
+ async function isExistingFile(path) {
696
+ try {
697
+ return (await stat(path)).isFile();
698
+ } catch {
699
+ return false;
700
+ }
701
+ }
702
+ async function isInstalled(client, engine, id) {
703
+ const { models } = engine === "mlx" ? await client.listMlxModels() : engine === "ds4" ? await client.listDs4Models() : await client.listLlamaCppModels();
704
+ return models.some((model2) => model2.id === id);
705
+ }
706
+ async function pull(client, engine, id, output) {
707
+ let lastPct = -1;
708
+ let pullError;
709
+ const onEvent = (ev) => {
710
+ if (ev.type === "progress") {
711
+ const written = "bytesWrittenAll" in ev ? ev.bytesWrittenAll : ev.bytesWritten;
712
+ const total = "totalBytesAll" in ev ? ev.totalBytesAll : ev.totalBytes ?? 0;
713
+ const pct = total > 0 ? Math.floor(written / total * 100) : 0;
714
+ if (pct === lastPct) return;
715
+ lastPct = pct;
716
+ output.writeProgress(
717
+ `\rdownloading ${id} (${engine}): ${String(pct).padStart(3)}% ${formatGb(written)}/${formatGb(total)} GB`
718
+ );
719
+ } else if (ev.type === "retrying") {
720
+ output.writeProgress(`
721
+ retry ${ev.attempt}/${ev.maxAttempts}: ${ev.reason}
722
+ `);
723
+ } else if (ev.type === "error") {
724
+ pullError = ev.error;
725
+ output.writeProgress("\n");
726
+ } else if (ev.type === "done" && !pullError) {
727
+ output.writeProgress(`\rdownloaded ${id} (${engine})${" ".repeat(48)}
728
+ `);
729
+ }
730
+ };
731
+ if (engine === "mlx") await client.installMlxModel(id, onEvent);
732
+ else if (engine === "ds4") await client.installDs4Model(id, onEvent);
733
+ else await client.installLlamaCppModel(id, onEvent);
734
+ if (pullError) throw new CliError(`download failed: ${pullError}`);
735
+ }
736
+ async function exportModelToFile(client, id, options) {
737
+ const { engine, cwd, output, signal } = options;
738
+ const target = await resolveExportPath(id, options.destination, cwd);
739
+ if (!options.force && await isExistingFile(target)) {
740
+ throw new CliError(`${target} already exists. Pass --force to overwrite it.`);
741
+ }
742
+ if (!await isExistingDirectory(dirname3(target))) {
743
+ throw new CliError(`${dirname3(target)} does not exist.`);
744
+ }
745
+ let pulled = false;
746
+ if (!await isInstalled(client, engine, id)) {
747
+ if (options.skipPull) {
748
+ throw new CliError(
749
+ `model "${id}" is not installed for ${engine}. Run \`gezel model pull ${id}\` first, or drop --no-pull.`
750
+ );
751
+ }
752
+ await pull(client, engine, id, output);
753
+ pulled = true;
754
+ }
755
+ const name = basename3(target);
756
+ const partial = `${target}.partial-${randomUUID2()}`;
757
+ try {
758
+ output.writeProgress(`preparing ${name}
759
+ `);
760
+ const response = await client.exportModelBundle(engine, id, signal);
761
+ const modelBytes = modelBytesFromResponse(response);
762
+ const bytesWritten = await writeModelBundleResponse(
763
+ response,
764
+ partial,
765
+ ({ bytesCompleted, bytesTotal }) => {
766
+ output.writeProgress(`\rwriting ${name}: ${progressText(bytesCompleted, bytesTotal)}`);
767
+ },
768
+ signal
769
+ );
770
+ output.writeProgress(`\rwriting ${name}: ${progressText(bytesWritten, modelBytes)}
771
+ `);
772
+ await verifyModelBundleArchive(
773
+ partial,
774
+ ({ bytesCompleted, bytesTotal }) => {
775
+ output.writeProgress(`\rverifying ${name}: ${progressText(bytesCompleted, bytesTotal)}`);
776
+ },
777
+ signal
778
+ );
779
+ output.writeProgress(`\rverifying ${name}: done${" ".repeat(32)}
780
+ `);
781
+ signal?.throwIfAborted();
782
+ await publish(partial, target);
783
+ return { path: target, bytesWritten, pulled };
784
+ } catch (error) {
785
+ await rm2(partial, { force: true }).catch(() => {
786
+ });
787
+ throw error;
788
+ }
789
+ }
790
+ async function publish(partial, target) {
791
+ const backup = `${target}.backup-${randomUUID2()}`;
792
+ const backedUp = await isExistingFile(target);
793
+ if (backedUp) await rename(target, backup);
794
+ try {
795
+ await rename(partial, target);
796
+ } catch (error) {
797
+ if (backedUp) await rename(backup, target).catch(() => {
798
+ });
799
+ throw error;
800
+ }
801
+ if (backedUp) await rm2(backup, { force: true }).catch(() => {
802
+ });
803
+ }
804
+ function progressText(bytesCompleted, bytesTotal) {
805
+ if (!bytesTotal) return `${formatGb(bytesCompleted)} GB`;
806
+ const pct = Math.floor(bytesCompleted / bytesTotal * 100);
807
+ return `${String(pct).padStart(3)}% ${formatGb(bytesCompleted)}/${formatGb(bytesTotal)} GB`;
808
+ }
809
+ function formatGb(bytes) {
810
+ return (bytes / 1e9).toFixed(2);
811
+ }
812
+
649
813
  // src/tui/bootstrap.ts
650
814
  import {
651
815
  computeModelFit,
@@ -802,9 +966,193 @@ function installSignalCleanup(cleanup, options = {}) {
802
966
  };
803
967
  }
804
968
 
969
+ // src/storage-format.ts
970
+ function formatBytes2(bytes) {
971
+ if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
972
+ if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(0)} MB`;
973
+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} KB`;
974
+ return `${bytes} B`;
975
+ }
976
+ function formatStorageSummary(summary) {
977
+ const lines = [`Gezel storage in ${summary.home}`, ""];
978
+ lines.push(...group("Can be downloaded again", summary, "redownloadable"));
979
+ lines.push(...group("Your content", summary, "user-content"));
980
+ lines.push(
981
+ ...group("Program files (the uninstaller removes these)", summary, "uninstaller-owned")
982
+ );
983
+ lines.push(
984
+ `Total: ${formatBytes2(summary.redownloadableBytes)} re-downloadable, ${formatBytes2(summary.userContentBytes)} your content`
985
+ );
986
+ const external = summary.categories.flatMap((c) => c.external).sort((a, b) => a.path.localeCompare(b.path));
987
+ if (external.length > 0) {
988
+ lines.push("", "Outside the Gezel folder \u2014 not measured or removed by Gezel:");
989
+ for (const entry of external) {
990
+ lines.push(` ${entry.path}`);
991
+ }
992
+ }
993
+ return lines.join("\n");
994
+ }
995
+ function group(heading, summary, cls) {
996
+ const categories = summary.categories.filter((c) => c.class === cls && c.bytes > 0).sort((a, b) => b.bytes - a.bytes);
997
+ if (categories.length === 0) return [];
998
+ const lines = [`${heading}:`];
999
+ for (const c of categories) {
1000
+ lines.push(` ${pad(formatBytes2(c.bytes), 10)} ${c.label}`);
1001
+ }
1002
+ lines.push("");
1003
+ return lines;
1004
+ }
1005
+ function pad(text, width) {
1006
+ return text.padStart(width, " ");
1007
+ }
1008
+ var CLEANUP_FLAG_CATEGORIES = {
1009
+ models: ["models"],
1010
+ engines: ["native-engines", "engine-caches"],
1011
+ toolsets: ["toolsets"],
1012
+ caches: ["gilde-cache", "derived-caches"],
1013
+ redownloadable: [
1014
+ "models",
1015
+ "native-engines",
1016
+ "engine-caches",
1017
+ "toolsets",
1018
+ "gilde-cache",
1019
+ "derived-caches"
1020
+ ]
1021
+ };
1022
+ var CLEANUP_CONTENT_CATEGORIES = {
1023
+ gezels: ["gezels"],
1024
+ projects: ["projects"],
1025
+ documents: ["documents"],
1026
+ settings: ["settings"],
1027
+ all: ["gezels", "projects", "documents", "settings"]
1028
+ };
1029
+ function resolveCleanupSelection(flags) {
1030
+ const categories = /* @__PURE__ */ new Set();
1031
+ for (const [flag, ids] of Object.entries(CLEANUP_FLAG_CATEGORIES)) {
1032
+ if (flags[flag] === true) for (const id of ids) categories.add(id);
1033
+ }
1034
+ let destroysUserContent = false;
1035
+ if (flags.content !== void 0) {
1036
+ const choice = flags.content;
1037
+ const ids = CLEANUP_CONTENT_CATEGORIES[choice];
1038
+ if (!ids) {
1039
+ throw new Error(
1040
+ `Unknown --content value "${flags.content}". Choose one of: ${Object.keys(
1041
+ CLEANUP_CONTENT_CATEGORIES
1042
+ ).join(", ")}.`
1043
+ );
1044
+ }
1045
+ for (const id of ids) categories.add(id);
1046
+ destroysUserContent = true;
1047
+ }
1048
+ return { categories: [...categories], destroysUserContent };
1049
+ }
1050
+ function formatCleanupResult(job) {
1051
+ const lines = [];
1052
+ if (job.status === "error") {
1053
+ lines.push(`Cleanup failed: ${job.error ?? "unknown error"}`);
1054
+ } else if (job.status === "cancelled") {
1055
+ lines.push(`Cleanup stopped early. Freed ${formatBytes2(job.bytesDone)} before stopping.`);
1056
+ } else {
1057
+ lines.push(`Freed ${formatBytes2(job.bytesDone)} across ${job.itemsDone} item(s).`);
1058
+ }
1059
+ if (job.skippedExternal.length > 0) {
1060
+ lines.push("", "Left alone (stored outside the Gezel folder):");
1061
+ for (const skipped of job.skippedExternal) {
1062
+ lines.push(` ${skipped.label} \u2014 ${skipped.path}`);
1063
+ }
1064
+ }
1065
+ if (job.restartRequired) {
1066
+ lines.push("", "Restart Gezel to pick up the changes.");
1067
+ }
1068
+ return lines.join("\n");
1069
+ }
1070
+ function formatCleanupPreview(summary, categories) {
1071
+ const selected = new Set(categories);
1072
+ const chosen = summary.categories.filter((c) => selected.has(c.id));
1073
+ const total = chosen.reduce((sum, c) => sum + c.bytes, 0);
1074
+ const lines = ["This will delete:"];
1075
+ for (const c of chosen) {
1076
+ lines.push(` ${pad(formatBytes2(c.bytes), 10)} ${c.label}`);
1077
+ }
1078
+ if (chosen.length === 0) lines.push(" (nothing \u2014 these categories are already empty)");
1079
+ lines.push("", `Frees about ${formatBytes2(total)}.`);
1080
+ const external = chosen.flatMap((c) => c.external);
1081
+ if (external.length > 0) {
1082
+ lines.push("", "Not touched (stored outside the Gezel folder):");
1083
+ for (const entry of external) lines.push(` ${entry.path}`);
1084
+ }
1085
+ const userContent = chosen.filter((c) => c.class === "user-content");
1086
+ if (userContent.length > 0) {
1087
+ lines.push("", "WARNING: this includes content only you have. Gezel cannot download it again.");
1088
+ }
1089
+ return lines.join("\n");
1090
+ }
1091
+ function formatBackupPlan(plan) {
1092
+ const lines = ["This backup will include:"];
1093
+ const byKind = /* @__PURE__ */ new Map();
1094
+ for (const item of plan.items) {
1095
+ const bucket = byKind.get(item.kind) ?? { count: 0, bytes: 0 };
1096
+ bucket.count += 1;
1097
+ bucket.bytes += item.bytes;
1098
+ byKind.set(item.kind, bucket);
1099
+ }
1100
+ const labels = {
1101
+ gezel: "gezels",
1102
+ project: "projects",
1103
+ "document-root": "documents",
1104
+ "settings-file": "settings files"
1105
+ };
1106
+ for (const [kind, bucket] of byKind) {
1107
+ lines.push(` ${pad(formatBytes2(bucket.bytes), 10)} ${bucket.count} ${labels[kind] ?? kind}`);
1108
+ }
1109
+ if (plan.items.length === 0) lines.push(" (nothing yet \u2014 this install has no content)");
1110
+ lines.push("", `About ${formatBytes2(plan.totalBytes)} total.`);
1111
+ lines.push("Saved credentials are never included; reconnect services after restoring.");
1112
+ for (const warning of plan.warnings) lines.push(` note: ${warning}`);
1113
+ return lines.join("\n");
1114
+ }
1115
+ function formatRestoreReview(review) {
1116
+ const lines = [
1117
+ `Backup from Gezel ${review.gezelVersion}, made ${new Date(review.createdAt).toLocaleString()}`,
1118
+ ""
1119
+ ];
1120
+ for (const item of review.items) {
1121
+ const flag = item.conflict === "exists" ? " [already here]" : "";
1122
+ lines.push(` ${pad(formatBytes2(item.bytes), 10)} ${item.kind}: ${item.label}${flag}`);
1123
+ }
1124
+ if (review.items.length === 0) lines.push(" (this backup is empty)");
1125
+ if (review.warnings.length > 0) {
1126
+ lines.push("");
1127
+ for (const warning of review.warnings) lines.push(` note: ${warning}`);
1128
+ }
1129
+ return lines.join("\n");
1130
+ }
1131
+ function resolveRestoreSelection(review, opts) {
1132
+ const wanted = opts.only && opts.only.length > 0 ? new Set(opts.only) : null;
1133
+ const items = [];
1134
+ const skipped = [];
1135
+ for (const item of review.items) {
1136
+ if (wanted && !wanted.has(`${item.kind}:${item.id}`) && !wanted.has(item.id)) continue;
1137
+ if (item.conflict === "exists" && !opts.replace) {
1138
+ skipped.push(`${item.label} (already here \u2014 use --replace to overwrite)`);
1139
+ continue;
1140
+ }
1141
+ items.push({
1142
+ kind: item.kind,
1143
+ id: item.id,
1144
+ action: item.conflict === "exists" ? "replace" : "add"
1145
+ });
1146
+ }
1147
+ return { items, skipped };
1148
+ }
1149
+
805
1150
  // src/tui/craftbook-start.ts
806
1151
  import {
1152
+ CRAFTBOOK_CATEGORY_FAMILY_META,
1153
+ CRAFTBOOK_CATEGORY_META,
807
1154
  CRAFTBOOK_ROLE_META,
1155
+ resolveCraftbookCategory,
808
1156
  visibleCatalogItems
809
1157
  } from "@bendyline/gezel";
810
1158
  function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
@@ -822,7 +1170,8 @@ function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
822
1170
  source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
823
1171
  stepCount: manifest.steps.length,
824
1172
  tags: manifest.tags ?? [],
825
- role: manifest.role ?? "general"
1173
+ role: manifest.role ?? "general",
1174
+ category: resolveCraftbookCategory(manifest)
826
1175
  });
827
1176
  }
828
1177
  return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
@@ -870,7 +1219,7 @@ program.action(async () => {
870
1219
  const { client } = connection;
871
1220
  const projectId = await resolveTuiProject(client, globals);
872
1221
  const gezelId = await ensureCliProjectLead(client, projectId);
873
- let projectName = basename3(process.cwd()) || "workspace";
1222
+ let projectName = basename4(process.cwd()) || "workspace";
874
1223
  try {
875
1224
  const { projects } = await client.listProjects();
876
1225
  projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
@@ -999,10 +1348,10 @@ async function startForeground(env2) {
999
1348
  process.on("SIGINT", requestStop);
1000
1349
  process.on("SIGTERM", requestStop);
1001
1350
  try {
1002
- await new Promise((resolve3) => {
1351
+ await new Promise((resolve5) => {
1003
1352
  child.on("exit", (code) => {
1004
1353
  process.exitCode = code ?? 0;
1005
- resolve3();
1354
+ resolve5();
1006
1355
  });
1007
1356
  });
1008
1357
  } finally {
@@ -1141,13 +1490,19 @@ program.command("run [prompt...]").description("Run a prompt through a gezel and
1141
1490
  process.exitCode = 1;
1142
1491
  return;
1143
1492
  }
1144
- const conn = await connectForRun(cliGlobals());
1145
- const removeSignalCleanup = installSignalCleanup(conn.stop, {
1146
- onError: (error) => {
1147
- console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
1148
- }
1149
- });
1493
+ const previousLogOutput = getLogOutput();
1494
+ setLogOutput("stderr");
1495
+ let conn;
1496
+ let removeSignalCleanup;
1150
1497
  try {
1498
+ conn = await connectForRun(cliGlobals());
1499
+ removeSignalCleanup = installSignalCleanup(conn.stop, {
1500
+ onError: (error) => {
1501
+ console.error(
1502
+ `shutdown failed: ${error instanceof Error ? error.message : String(error)}`
1503
+ );
1504
+ }
1505
+ });
1151
1506
  const { client } = conn;
1152
1507
  const projectId = await resolveRunProject(client, cliGlobals());
1153
1508
  const gezelId = opts.gezel ?? await ensureCliProjectLead(client, projectId);
@@ -1177,8 +1532,12 @@ ${ev.error}`);
1177
1532
  if (printed) process.stdout.write("\n");
1178
1533
  if (errored) process.exitCode = 1;
1179
1534
  } finally {
1180
- removeSignalCleanup();
1181
- if (conn.stop) await conn.stop();
1535
+ removeSignalCleanup?.();
1536
+ try {
1537
+ if (conn?.stop) await conn.stop();
1538
+ } finally {
1539
+ setLogOutput(previousLogOutput);
1540
+ }
1182
1541
  }
1183
1542
  });
1184
1543
  program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").action(async (craftbookParts) => {
@@ -1332,16 +1691,217 @@ handboek.command("export").description("Render the Handboek as a static HTML sit
1332
1691
  ).option(
1333
1692
  "--site-url <url>",
1334
1693
  "URL of the surrounding site; adds a wordmark link back out of the docs"
1335
- ).action(async (opts) => {
1336
- const handboekModule = "../handboek-export.js";
1337
- const { runHandboekExport } = await import(handboekModule);
1338
- const result = await runHandboekExport({
1339
- out: opts.out,
1340
- css: opts.css,
1341
- siteUrl: opts.siteUrl
1694
+ ).option(
1695
+ "--canonical-base <url>",
1696
+ "absolute URL the export root is published at (e.g. https://gezel.com/docs/); enables canonical and Open Graph tags"
1697
+ ).option("--og-out <dir>", "directory to render Open Graph cards into; must be outside --out").option(
1698
+ "--og-base <url>",
1699
+ "absolute URL the card directory is served from (e.g. https://gezel.com/og/); required with --og-out"
1700
+ ).action(
1701
+ async (opts) => {
1702
+ if (Boolean(opts.ogOut) !== Boolean(opts.ogBase)) {
1703
+ console.error("--og-out and --og-base go together: cards need a directory and a URL.");
1704
+ process.exitCode = 1;
1705
+ return;
1706
+ }
1707
+ const handboekModule = "../handboek-export.js";
1708
+ const { runHandboekExport } = await import(handboekModule);
1709
+ const result = await runHandboekExport({
1710
+ out: opts.out,
1711
+ css: opts.css,
1712
+ siteUrl: opts.siteUrl,
1713
+ canonicalBase: opts.canonicalBase,
1714
+ ogOut: opts.ogOut,
1715
+ ogBase: opts.ogBase
1716
+ });
1717
+ console.log(`Handboek exported: ${result.pages} pages \u2192 ${result.out}`);
1718
+ for (const id of result.skipped) console.error(` skipped (no body): ${id}`);
1719
+ const cards = result.cards;
1720
+ if (cards?.skipped) {
1721
+ console.error(` no Open Graph cards: ${cards.skipped}`);
1722
+ } else if (cards) {
1723
+ console.log(
1724
+ `Open Graph cards: ${cards.rendered} rendered, ${cards.reused} reused, ${cards.swept} swept`
1725
+ );
1726
+ for (const id of cards.failed) console.error(` card failed: ${id}`);
1727
+ }
1728
+ }
1729
+ );
1730
+ var knowledge = program.command("knowledge").description("Build, validate, inspect and search .gezk knowledge catalogs (no daemon)");
1731
+ var loadKnowledgeCommand = async () => {
1732
+ const knowledgeModule = "../knowledge-command.js";
1733
+ return await import(knowledgeModule);
1734
+ };
1735
+ knowledge.command("init <dir>").description("Scaffold a catalog folder (catalog.json + content/)").action(async (dir) => {
1736
+ const { runKnowledgeInit } = await loadKnowledgeCommand();
1737
+ await runKnowledgeInit(dir);
1738
+ });
1739
+ knowledge.command("build <dir>").description("Compile a catalog folder into a .gezk archive").option("--out <file>", "output path (default <dir>/<id>-<version>.gezk)").option("--sign-key <pemfile>", "Ed25519 private key (PKCS#8 PEM) to sign the manifest").action(async (dir, opts) => {
1740
+ const { runKnowledgeBuild } = await loadKnowledgeCommand();
1741
+ await runKnowledgeBuild(dir, opts);
1742
+ });
1743
+ knowledge.command("validate <path>").description("Verify a .gezk archive or extracted catalog directory").option("--deep", "also run quick_check, vector alignment, self-KNN and smoke queries").action(async (path, opts) => {
1744
+ const { runKnowledgeValidate } = await loadKnowledgeCommand();
1745
+ await runKnowledgeValidate(path, opts);
1746
+ });
1747
+ knowledge.command("inspect <path>").description("Print a catalog summary from its manifest").action(async (path) => {
1748
+ const { runKnowledgeInspect } = await loadKnowledgeCommand();
1749
+ await runKnowledgeInspect(path);
1750
+ });
1751
+ knowledge.command("search <path> <query>").description("Search a catalog file offline (full-text; --semantic adds vector search)").option("--semantic", "embed the query with the catalog profile (loads the model)").option("--limit <n>", "maximum results", (v) => Number.parseInt(v, 10), 10).action(async (path, query, opts) => {
1752
+ const { runKnowledgeSearch } = await loadKnowledgeCommand();
1753
+ await runKnowledgeSearch(path, query, opts);
1754
+ });
1755
+ knowledge.command("install <source>").description("Install a .gezk catalog into the running gezel (file path or URL)").option("--sha256 <digest>", "optional expected SHA-256 digest for URL installs").action(async (source, opts) => {
1756
+ const installSource = resolveKnowledgeInstallSource(source, opts.sha256);
1757
+ const client = await connectOwned(cliGlobals());
1758
+ const { jobId } = await client.installKnowledgeCatalog({
1759
+ source: installSource
1342
1760
  });
1343
- console.log(`Handboek exported: ${result.pages} pages \u2192 ${result.out}`);
1344
- for (const id of result.skipped) console.error(` skipped (no body): ${id}`);
1761
+ for (; ; ) {
1762
+ const job = await client.getKnowledgeJob(jobId);
1763
+ const last = job.events[job.events.length - 1];
1764
+ if (process.stderr.isTTY && last?.type === "progress") {
1765
+ const done = Number(last.bytesDone ?? 0);
1766
+ const total = Number(last.bytesTotal ?? 0);
1767
+ const pct = total > 0 ? ` (${Math.floor(done / total * 100)}%)` : "";
1768
+ process.stderr.write(`\r${String(last.phase ?? "working")}${pct} `);
1769
+ }
1770
+ if (job.finished) {
1771
+ if (process.stderr.isTTY) process.stderr.write("\n");
1772
+ if (job.error) throw new CliError(`install failed: ${job.error}`);
1773
+ const doneEvent = job.events.find((e) => e.type === "done");
1774
+ console.log(
1775
+ `Installed ${doneEvent?.ref?.catalogId ?? "catalog"}@${doneEvent?.ref?.version ?? ""} \u2014 enabled for search.`
1776
+ );
1777
+ return;
1778
+ }
1779
+ await new Promise((r) => setTimeout(r, 250));
1780
+ }
1781
+ });
1782
+ knowledge.command("list").description("List catalogs installed in the running gezel").action(async () => {
1783
+ const client = await connectOwned(cliGlobals());
1784
+ const { catalogs } = await client.listKnowledgeCatalogs();
1785
+ if (catalogs.length === 0) {
1786
+ console.log("No knowledge catalogs installed. Add one with: gezel knowledge install <file>");
1787
+ return;
1788
+ }
1789
+ for (const c of catalogs) {
1790
+ const state = c.disabledReason ? `quarantined \u2014 ${c.disabledReason}` : c.enabled ? c.mounted ? "active" : "enabled" : "disabled";
1791
+ const size = c.sizeBytes ? ` ${(c.sizeBytes / (1024 * 1024)).toFixed(1)} MB` : "";
1792
+ console.log(
1793
+ `${c.ref.catalogId.padEnd(24)} ${c.ref.version.padEnd(10)} ${String(c.documents ?? "?").padStart(6)} docs${size} ${state}`
1794
+ );
1795
+ }
1796
+ });
1797
+ knowledge.command("remove <catalogId>").description("Remove an installed catalog and its private files").action(async (catalogId) => {
1798
+ const client = await connectOwned(cliGlobals());
1799
+ const { ok } = await client.removeKnowledgeCatalog(catalogId).catch((err) => {
1800
+ throw new CliError(err instanceof Error ? err.message : String(err));
1801
+ });
1802
+ if (!ok) throw new CliError(`catalog not found: ${catalogId}`);
1803
+ console.log(`Removed ${catalogId}.`);
1804
+ });
1805
+ knowledge.command("find <query>").description("Search installed catalogs through the running gezel").option("--limit <n>", "maximum results", (v) => Number.parseInt(v, 10), 10).action(async (query, opts) => {
1806
+ const client = await connectOwned(cliGlobals());
1807
+ const { results } = await client.searchKnowledge({
1808
+ query,
1809
+ ...opts.limit ? { maxResults: opts.limit } : {}
1810
+ });
1811
+ if (results.length === 0) {
1812
+ console.log(`No results for "${query}".`);
1813
+ process.exitCode = 1;
1814
+ return;
1815
+ }
1816
+ for (const r of results) {
1817
+ console.log(`${r.title} ${r.uri ?? ""}`);
1818
+ if (r.snippet) console.log(` ${r.snippet.replace(/\s+/g, " ").slice(0, 160)}`);
1819
+ }
1820
+ });
1821
+ var appCmd = program.command("app").description("Manage AI Apps (.gezapp) installed on this machine");
1822
+ var loadAppCommand = async () => {
1823
+ const appModule = "../app-command.js";
1824
+ return await import(appModule);
1825
+ };
1826
+ var loadAppAuthorCommand = async () => {
1827
+ const appAuthorModule = "../app-author-command.js";
1828
+ return await import(appAuthorModule);
1829
+ };
1830
+ appCmd.command("add <file>").description("Install a .gezapp AI App (idempotent; a newer version upgrades)").option("--yes", "skip the confirmation prompt").option("--force", "allow downgrading to an older version").option("--json", "print the machine-readable result").action(async (file, opts) => {
1831
+ const { runAppAdd } = await loadAppCommand();
1832
+ await runAppAdd(await connectOwned(cliGlobals()), file, opts);
1833
+ });
1834
+ appCmd.command("update <file>").description("Upgrade an installed AI App from a newer .gezapp").option("--force", "allow downgrading to an older version").option("--json", "print the machine-readable result").action(async (file, opts) => {
1835
+ const { runAppUpdate } = await loadAppCommand();
1836
+ await runAppUpdate(await connectOwned(cliGlobals()), file, opts);
1837
+ });
1838
+ appCmd.command("list").description("List installed AI Apps").option("--json", "print the machine-readable result").action(async (opts) => {
1839
+ const { runAppList } = await loadAppCommand();
1840
+ await runAppList(await connectOwned(cliGlobals()), opts);
1841
+ });
1842
+ appCmd.command("show <appId>").description("Show one installed AI App: manifest, dependencies, applied projects").option("--json", "print the machine-readable result").action(async (appId, opts) => {
1843
+ const { runAppShow } = await loadAppCommand();
1844
+ await runAppShow(await connectOwned(cliGlobals()), appId, opts);
1845
+ });
1846
+ appCmd.command("remove <appId>").description("Uninstall an AI App (projects it outfitted keep their copies)").option("--yes", "skip the confirmation prompt").option("--keep-files", "unregister only; leave the version dirs on disk").action(async (appId, opts) => {
1847
+ const { runAppRemove } = await loadAppCommand();
1848
+ await runAppRemove(await connectOwned(cliGlobals()), appId, opts);
1849
+ });
1850
+ appCmd.command("enable <appId>").description("Enable a disabled AI App").action(async (appId) => {
1851
+ const { runAppSetEnabled } = await loadAppCommand();
1852
+ await runAppSetEnabled(await connectOwned(cliGlobals()), appId, true);
1853
+ });
1854
+ var appCommandFolder = () => {
1855
+ const p = cliGlobals().project;
1856
+ return p === void 0 || p === true || p === false ? process.cwd() : p;
1857
+ };
1858
+ appCmd.command("apply <appId>").description("Apply an installed AI App to this folder (links or creates a project here)").option("--version <version>", "pin a specific installed type version").option(
1859
+ "--param <key=value>",
1860
+ "set an adoption param (repeatable)",
1861
+ (pair, prior) => [...prior, pair],
1862
+ []
1863
+ ).option("--yes", "skip the confirmation prompt").option("--refresh", "re-apply even when this version is already applied").option("--force", "apply over a different app already applied here").option("--json", "print the machine-readable result").action(
1864
+ async (appId, opts) => {
1865
+ const { runAppApply } = await loadAppCommand();
1866
+ await runAppApply(await connectOwned(cliGlobals()), appId, appCommandFolder(), opts);
1867
+ }
1868
+ );
1869
+ appCmd.command("status").description("Show this folder's applied AI App, drift, and available updates").option("--json", "print the machine-readable result").action(async (opts) => {
1870
+ const { runAppStatus } = await loadAppCommand();
1871
+ await runAppStatus(await connectOwned(cliGlobals()), appCommandFolder(), opts);
1872
+ });
1873
+ appCmd.command("serve [target...]").description(
1874
+ "Serve this folder's applied AI App as a shareable mini-site (`serve status` / `serve stop` manage sites)"
1875
+ ).option("--port <n>", "fixed port (default: ephemeral)", (v) => Number.parseInt(v, 10)).option("--host <ip>", "bind address, an IP literal (default 127.0.0.1)").option(
1876
+ "--allow-host <name>",
1877
+ "accept this reverse-proxy/tunnel hostname (repeatable)",
1878
+ (name, prior) => [...prior, name],
1879
+ []
1880
+ ).option("--chat", "let visitors chat with the project lead (no tools)").option("--public", "skip the site key \u2014 anyone reaching the port may visit").option("--key <site-key>", "pin the site key for a stable share link (min 24 chars)").option("--detach", "leave the site running in the daemon and exit").option("--open", "open the share link in a browser").option("--all", "with `serve stop`: stop every site").option("--json", "print the machine-readable result").action(
1881
+ async (target, opts) => {
1882
+ const { runAppServe } = await loadAppCommand();
1883
+ await runAppServe(await connectOwned(cliGlobals()), target ?? [], appCommandFolder(), opts);
1884
+ }
1885
+ );
1886
+ appCmd.command("disable <appId>").description("Disable an AI App without uninstalling it").action(async (appId) => {
1887
+ const { runAppSetEnabled } = await loadAppCommand();
1888
+ await runAppSetEnabled(await connectOwned(cliGlobals()), appId, false);
1889
+ });
1890
+ appCmd.command("new <id>").description("Scaffold a minimal AI App source folder").option("--dir <parent>", "parent directory (defaults to the current folder)").option("--with-page", "include an Output page wired to the example tool").action(async (id, opts) => {
1891
+ const { runAppNew } = await loadAppAuthorCommand();
1892
+ await runAppNew(id, opts);
1893
+ });
1894
+ appCmd.command("validate <target>").description("Validate an AI App source folder or .gezapp file (no daemon needed)").option("--json", "print the machine-readable findings").action(async (target, opts) => {
1895
+ const { runAppValidate } = await loadAppAuthorCommand();
1896
+ await runAppValidate(target, opts);
1897
+ });
1898
+ appCmd.command("pack <folder>").description("Validate and pack an AI App source folder into a .gezapp").option("-o, --out <file>", "output path (defaults to <appId>-<version>.gezapp)").option("--json", "print the machine-readable result").action(async (folder, opts) => {
1899
+ const { runAppPack } = await loadAppAuthorCommand();
1900
+ await runAppPack(folder, opts);
1901
+ });
1902
+ appCmd.command("schemas").description("The JSON Schemas an AI App author codes against, rendered from this build").option("--out <dir>", "write the schema files into a directory").option("--json", "print one combined JSON object").action(async (opts) => {
1903
+ const { runAppSchemas } = await loadAppAuthorCommand();
1904
+ await runAppSchemas(opts);
1345
1905
  });
1346
1906
  var task = program.command("task").description("Manage tasks");
1347
1907
  task.command("list").description("List tasks across every project").option("-s, --status <status>", "filter by status (paused|active|complete|canceled)").action(async (opts) => {
@@ -1614,6 +2174,22 @@ model.command("pull <id>").description("Download a local chat model from the cat
1614
2174
  }
1615
2175
  if (pullError) throw new CliError(`pull failed: ${pullError}`);
1616
2176
  });
2177
+ model.command("export <id> [file]").description("Export a catalog model to a portable .gezmodel (downloads it first if needed)").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").option("-f, --force", "Overwrite an existing file").option("--no-pull", "Fail instead of downloading a model that is not installed yet").action(async (id, file, opts) => {
2178
+ const client = await connectOwned(cliGlobals());
2179
+ const result = await exportModelToFile(client, id, {
2180
+ engine: resolveModelProvider(opts.provider),
2181
+ cwd: process.cwd(),
2182
+ ...file ? { destination: file } : {},
2183
+ ...opts.force ? { force: true } : {},
2184
+ ...opts.pull === false ? { skipPull: true } : {},
2185
+ output: {
2186
+ writeProgress: (text) => {
2187
+ process.stderr.write(text);
2188
+ }
2189
+ }
2190
+ });
2191
+ console.log(`exported ${id} to ${result.path} (${(result.bytesWritten / 1e9).toFixed(2)} GB)`);
2192
+ });
1617
2193
  program.command("doctor").description("Check the Gezel installation").action(async () => {
1618
2194
  const globals = cliGlobals();
1619
2195
  const system = globals.connect ? null : await findHealthySystemService(globals);
@@ -1656,8 +2232,139 @@ program.command("doctor").description("Check the Gezel installation").action(asy
1656
2232
  }
1657
2233
  }
1658
2234
  });
2235
+ program.command("cleanup").description("Show or reclaim the space Gezel is using on this device").option("--refresh", "Re-measure instead of using the cached sizes").option("--models", "Delete downloaded models").option("--engines", "Delete engine binaries and their caches").option("--toolsets", "Delete installed tools and the automation browser").option("--caches", "Delete catalog content and generated indexes").option("--redownloadable", "Delete everything Gezel can download again").option(
2236
+ "--content <what>",
2237
+ "Delete your own content: gezels, projects, documents, settings, or all"
2238
+ ).option("--dry-run", "Show what would be deleted without deleting anything").option("--yes", "Skip the confirmation prompt").action(async (opts) => {
2239
+ const client = await connectOwned(cliGlobals());
2240
+ const selection = resolveCleanupSelection(opts);
2241
+ if (selection.categories.length === 0) {
2242
+ const summary2 = await client.storageSummary(opts.refresh ? { refresh: true } : void 0);
2243
+ console.log(formatStorageSummary(summary2));
2244
+ if (!opts.dryRun) {
2245
+ console.log(
2246
+ "\nTo reclaim space, re-run with --redownloadable (safe: Gezel downloads these again)."
2247
+ );
2248
+ }
2249
+ return;
2250
+ }
2251
+ const summary = await client.storageSummary({ refresh: true });
2252
+ console.log(formatCleanupPreview(summary, selection.categories));
2253
+ if (opts.dryRun) {
2254
+ console.log("\nDry run \u2014 nothing was deleted.");
2255
+ return;
2256
+ }
2257
+ if (selection.destroysUserContent) {
2258
+ const confirmed = await confirmByTyping(
2259
+ 'This permanently deletes content only you have. Type "delete my content" to continue: ',
2260
+ "delete my content"
2261
+ );
2262
+ if (!confirmed) {
2263
+ console.log("Cancelled.");
2264
+ return;
2265
+ }
2266
+ } else if (!opts.yes) {
2267
+ const confirmed = await confirmByTyping('Delete these? Type "yes" to continue: ', "yes");
2268
+ if (!confirmed) {
2269
+ console.log("Cancelled.");
2270
+ return;
2271
+ }
2272
+ }
2273
+ const { jobId } = await client.startCleanup({
2274
+ categories: selection.categories,
2275
+ ...selection.destroysUserContent ? { confirmUserContent: true } : {}
2276
+ });
2277
+ const job = await pollStorageJob(client, jobId);
2278
+ console.log(formatCleanupResult(job));
2279
+ if (job.status === "error") process.exitCode = 1;
2280
+ });
2281
+ program.command("backup <file>").description("Write your gezels, projects, and documents to a backup file").option("--no-workspaces", "Leave project working files out of the backup").option("--dry-run", "Show what would be included without writing the file").action(async (file, opts) => {
2282
+ const client = await connectOwned(cliGlobals());
2283
+ const outPath = resolvePath(file);
2284
+ const excludeWorkspaces = opts.workspaces === false;
2285
+ const plan = await client.planBackup({ destPath: outPath, excludeWorkspaces });
2286
+ console.log(formatBackupPlan(plan));
2287
+ if (opts.dryRun) {
2288
+ console.log("\nDry run \u2014 no file was written.");
2289
+ return;
2290
+ }
2291
+ if (plan.items.length === 0) throw new CliError("There is nothing to back up yet.");
2292
+ const { jobId } = await client.startBackup({ outPath, excludeWorkspaces });
2293
+ const job = await pollStorageJob(client, jobId);
2294
+ if (job.status === "error") {
2295
+ throw new CliError(`Backup failed: ${job.error ?? "unknown error"}`);
2296
+ }
2297
+ console.log(`
2298
+ Wrote ${outPath}`);
2299
+ });
2300
+ program.command("restore <file>").description("Restore gezels, projects, and documents from a backup file").option("--list", "Show what the backup holds without restoring anything").option(
2301
+ "--only <item...>",
2302
+ "Restore just these items, by id (repeatable, e.g. --only tamsin roof-survey)"
2303
+ ).option("--replace", "Overwrite items that already exist here").option("--settings", "Also restore preferences from the backup").action(
2304
+ async (file, opts) => {
2305
+ const client = await connectOwned(cliGlobals());
2306
+ const review = await client.scanRestore({ path: resolvePath(file) });
2307
+ console.log(formatRestoreReview(review));
2308
+ if (opts.list) return;
2309
+ const selection = resolveRestoreSelection(review, opts);
2310
+ for (const note of selection.skipped) console.log(` skipping ${note}`);
2311
+ if (selection.items.length === 0) {
2312
+ console.log("\nNothing to restore.");
2313
+ await client.cancelRestore(review.restoreId);
2314
+ return;
2315
+ }
2316
+ const { jobId } = await client.confirmRestore(review.restoreId, {
2317
+ items: selection.items,
2318
+ ...opts.settings ? { settings: true } : {}
2319
+ });
2320
+ const job = await pollStorageJob(client, jobId);
2321
+ if (job.status === "error") {
2322
+ throw new CliError(`Restore failed: ${job.error ?? "unknown error"}`);
2323
+ }
2324
+ console.log(`
2325
+ Restored ${selection.items.length} item(s).`);
2326
+ if (job.restartRequired) console.log("Restart Gezel to see them.");
2327
+ }
2328
+ );
2329
+ function resolvePath(file) {
2330
+ return isAbsolutePath(file) ? file : joinPath(process.cwd(), file);
2331
+ }
2332
+ async function confirmByTyping(prompt, required) {
2333
+ if (!process.stdin.isTTY) {
2334
+ throw new CliError(
2335
+ "Refusing to delete without a confirmation. Re-run in a terminal, or use --dry-run to preview."
2336
+ );
2337
+ }
2338
+ const { createInterface } = await import("readline/promises");
2339
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
2340
+ try {
2341
+ const answer = await rl.question(prompt);
2342
+ return answer.trim().toLowerCase() === required;
2343
+ } finally {
2344
+ rl.close();
2345
+ }
2346
+ }
2347
+ async function pollStorageJob(client, jobId) {
2348
+ for (; ; ) {
2349
+ const job = await client.getStorageJob(jobId);
2350
+ if (job.status === "done" || job.status === "error" || job.status === "cancelled") {
2351
+ if (process.stderr.isTTY) process.stderr.write("\n");
2352
+ return job;
2353
+ }
2354
+ if (process.stderr.isTTY) {
2355
+ const label = job.currentLabel ? ` ${job.currentLabel}` : "";
2356
+ process.stderr.write(
2357
+ `\r${job.phase ?? "working"}${label} \u2014 ${job.itemsDone}/${job.totalItems} `
2358
+ );
2359
+ }
2360
+ await new Promise((r) => setTimeout(r, 250));
2361
+ }
2362
+ }
1659
2363
  program.parseAsync(process.argv).catch((err) => {
1660
- if (err instanceof CliError) console.error(err.message);
1661
- else console.error(err);
2364
+ if (err instanceof CliError || err instanceof Error && err.name === "CliError") {
2365
+ console.error(err.message);
2366
+ } else {
2367
+ console.error(err);
2368
+ }
1662
2369
  process.exit(1);
1663
2370
  });