@bendyline/gezel-cli 1.0.6 → 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, isAbsolute as isAbsolutePath, join as joinPath } 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,
@@ -985,7 +1149,10 @@ function resolveRestoreSelection(review, opts) {
985
1149
 
986
1150
  // src/tui/craftbook-start.ts
987
1151
  import {
1152
+ CRAFTBOOK_CATEGORY_FAMILY_META,
1153
+ CRAFTBOOK_CATEGORY_META,
988
1154
  CRAFTBOOK_ROLE_META,
1155
+ resolveCraftbookCategory,
989
1156
  visibleCatalogItems
990
1157
  } from "@bendyline/gezel";
991
1158
  function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
@@ -1003,7 +1170,8 @@ function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
1003
1170
  source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
1004
1171
  stepCount: manifest.steps.length,
1005
1172
  tags: manifest.tags ?? [],
1006
- role: manifest.role ?? "general"
1173
+ role: manifest.role ?? "general",
1174
+ category: resolveCraftbookCategory(manifest)
1007
1175
  });
1008
1176
  }
1009
1177
  return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
@@ -1051,7 +1219,7 @@ program.action(async () => {
1051
1219
  const { client } = connection;
1052
1220
  const projectId = await resolveTuiProject(client, globals);
1053
1221
  const gezelId = await ensureCliProjectLead(client, projectId);
1054
- let projectName = basename3(process.cwd()) || "workspace";
1222
+ let projectName = basename4(process.cwd()) || "workspace";
1055
1223
  try {
1056
1224
  const { projects } = await client.listProjects();
1057
1225
  projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
@@ -1180,10 +1348,10 @@ async function startForeground(env2) {
1180
1348
  process.on("SIGINT", requestStop);
1181
1349
  process.on("SIGTERM", requestStop);
1182
1350
  try {
1183
- await new Promise((resolve3) => {
1351
+ await new Promise((resolve5) => {
1184
1352
  child.on("exit", (code) => {
1185
1353
  process.exitCode = code ?? 0;
1186
- resolve3();
1354
+ resolve5();
1187
1355
  });
1188
1356
  });
1189
1357
  } finally {
@@ -1322,13 +1490,19 @@ program.command("run [prompt...]").description("Run a prompt through a gezel and
1322
1490
  process.exitCode = 1;
1323
1491
  return;
1324
1492
  }
1325
- const conn = await connectForRun(cliGlobals());
1326
- const removeSignalCleanup = installSignalCleanup(conn.stop, {
1327
- onError: (error) => {
1328
- console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
1329
- }
1330
- });
1493
+ const previousLogOutput = getLogOutput();
1494
+ setLogOutput("stderr");
1495
+ let conn;
1496
+ let removeSignalCleanup;
1331
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
+ });
1332
1506
  const { client } = conn;
1333
1507
  const projectId = await resolveRunProject(client, cliGlobals());
1334
1508
  const gezelId = opts.gezel ?? await ensureCliProjectLead(client, projectId);
@@ -1358,8 +1532,12 @@ ${ev.error}`);
1358
1532
  if (printed) process.stdout.write("\n");
1359
1533
  if (errored) process.exitCode = 1;
1360
1534
  } finally {
1361
- removeSignalCleanup();
1362
- if (conn.stop) await conn.stop();
1535
+ removeSignalCleanup?.();
1536
+ try {
1537
+ if (conn?.stop) await conn.stop();
1538
+ } finally {
1539
+ setLogOutput(previousLogOutput);
1540
+ }
1363
1541
  }
1364
1542
  });
1365
1543
  program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").action(async (craftbookParts) => {
@@ -1513,16 +1691,217 @@ handboek.command("export").description("Render the Handboek as a static HTML sit
1513
1691
  ).option(
1514
1692
  "--site-url <url>",
1515
1693
  "URL of the surrounding site; adds a wordmark link back out of the docs"
1516
- ).action(async (opts) => {
1517
- const handboekModule = "../handboek-export.js";
1518
- const { runHandboekExport } = await import(handboekModule);
1519
- const result = await runHandboekExport({
1520
- out: opts.out,
1521
- css: opts.css,
1522
- 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
1760
+ });
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));
1523
1801
  });
1524
- console.log(`Handboek exported: ${result.pages} pages \u2192 ${result.out}`);
1525
- for (const id of result.skipped) console.error(` skipped (no body): ${id}`);
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);
1526
1905
  });
1527
1906
  var task = program.command("task").description("Manage tasks");
1528
1907
  task.command("list").description("List tasks across every project").option("-s, --status <status>", "filter by status (paused|active|complete|canceled)").action(async (opts) => {
@@ -1795,6 +2174,22 @@ model.command("pull <id>").description("Download a local chat model from the cat
1795
2174
  }
1796
2175
  if (pullError) throw new CliError(`pull failed: ${pullError}`);
1797
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
+ });
1798
2193
  program.command("doctor").description("Check the Gezel installation").action(async () => {
1799
2194
  const globals = cliGlobals();
1800
2195
  const system = globals.connect ? null : await findHealthySystemService(globals);
@@ -1966,7 +2361,10 @@ async function pollStorageJob(client, jobId) {
1966
2361
  }
1967
2362
  }
1968
2363
  program.parseAsync(process.argv).catch((err) => {
1969
- if (err instanceof CliError) console.error(err.message);
1970
- 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
+ }
1971
2369
  process.exit(1);
1972
2370
  });