@bendyline/gezel-cli 1.2.3 → 1.2.4

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.
@@ -9,9 +9,7 @@ import {
9
9
  setLogLevel as setLogLevel2,
10
10
  setLogOutput as setLogOutput2
11
11
  } from "@bendyline/gezel";
12
- import {
13
- streamChatEvents
14
- } from "@bendyline/gezel-client";
12
+ import { streamChatEvents } from "@bendyline/gezel-client";
15
13
  import {
16
14
  GezelClient as GezelClient2,
17
15
  createTrustingFetch as createTrustingFetch2,
@@ -22,8 +20,8 @@ import {
22
20
  stopOwnedDaemon as stopOwnedDaemon2,
23
21
  stopProcessByPid
24
22
  } from "@bendyline/gezel-client/node";
25
- import { resolveOnDeviceProvider } from "@bendyline/gezel/native";
26
- import { Command } from "commander";
23
+ import { resolveOnDeviceProvider as resolveOnDeviceProvider2 } from "@bendyline/gezel/native";
24
+ import { Command, Option } from "commander";
27
25
 
28
26
  // src/cli-errors.ts
29
27
  function formatCliFailure(err, env2 = process.env) {
@@ -58,7 +56,7 @@ function detailText(details) {
58
56
 
59
57
  // src/connection.ts
60
58
  import { createHash, randomUUID } from "crypto";
61
- import { chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
59
+ import { chmod, mkdir, readFile, realpath, rm, writeFile } from "fs/promises";
62
60
  import { homedir } from "os";
63
61
  import { basename, dirname, join, resolve } from "path";
64
62
  import {
@@ -687,13 +685,29 @@ async function ensureCliProjectLead(client, projectId) {
687
685
  async function resolveRunProject(client, globals) {
688
686
  return resolveCommandProject(client, globals);
689
687
  }
688
+ async function previewRunProject(client, globals) {
689
+ const p = globals.project;
690
+ const requested = resolve(typeof p === "string" ? p : process.cwd());
691
+ const folder = await realpath(requested).catch(() => requested);
692
+ try {
693
+ const res = await client.inferProjectForPath({ path: folder, kind: "folder", create: false });
694
+ return res.project ? { projectId: res.project.id } : { projectId: null, root: res.root ?? folder };
695
+ } catch (err) {
696
+ if (forbiddenProjectFolderName(err)) return { projectId: DEFAULT_PROJECT_ID };
697
+ throw err;
698
+ }
699
+ }
690
700
  async function resolveTuiProject(client, globals) {
691
701
  return resolveCommandProject(client, globals);
692
702
  }
693
703
 
694
704
  // src/craftbook-command.ts
695
705
  import { setTimeout as delay } from "timers/promises";
696
- import { createAwakeTimeout } from "@bendyline/gezel";
706
+ import {
707
+ composeCraftbookLaunch,
708
+ createAwakeTimeout,
709
+ paramAsksUser
710
+ } from "@bendyline/gezel";
697
711
 
698
712
  // src/tui/craftbook-start.ts
699
713
  import {
@@ -715,6 +729,7 @@ function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
715
729
  ...manifest.description ? { description: manifest.description } : {},
716
730
  version: manifest.version,
717
731
  sourceId: item.sourceId,
732
+ command: manifest.command ?? manifest.id,
718
733
  source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
719
734
  stepCount: manifest.steps.length,
720
735
  tags: manifest.tags ?? [],
@@ -726,7 +741,9 @@ function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
726
741
  }
727
742
  function findCraftbook(books, value) {
728
743
  const query = value.trim().toLowerCase();
729
- return books.find((book) => book.id.toLowerCase() === query || book.name.toLowerCase() === query);
744
+ return books.find(
745
+ (book) => book.id.toLowerCase() === query || book.command?.toLowerCase() === query || book.name.toLowerCase() === query
746
+ );
730
747
  }
731
748
  function craftbookStartRequest(book) {
732
749
  const summary = book.description?.trim();
@@ -750,44 +767,73 @@ function resolveCraftbookInvocation(books, tokens) {
750
767
  }
751
768
  throw new CliError(`craftbook not found: ${tokens.join(" ")}`);
752
769
  }
753
- function parseCraftbookParams(book, tokens) {
770
+ var NAMED_ARGUMENT = /^([A-Za-z][\w.-]*)=([\s\S]*)$/;
771
+ function checkParamValue(key, def, value) {
772
+ if (Array.isArray(def.enum) && !def.enum.map(String).includes(value)) {
773
+ throw new CliError(`${key} must be one of: ${def.enum.join(", ")}`);
774
+ }
775
+ if (def.type === "boolean" && !["true", "false"].includes(value))
776
+ throw new CliError(`${key} must be true or false`);
777
+ if (def.type === "number" || def.type === "integer") {
778
+ const number = Number(value);
779
+ if (!value.trim() || !Number.isFinite(number) || def.type === "integer" && !Number.isInteger(number))
780
+ throw new CliError(`${key} must be a ${def.type}`);
781
+ if (typeof def.minimum === "number" && number < def.minimum)
782
+ throw new CliError(`${key} must be at least ${def.minimum}`);
783
+ if (typeof def.maximum === "number" && number > def.maximum)
784
+ throw new CliError(`${key} must be at most ${def.maximum}`);
785
+ }
786
+ if (typeof def.pattern === "string" && !new RegExp(def.pattern).test(value))
787
+ throw new CliError(`${key} must match ${def.pattern}`);
788
+ if (typeof def.minLength === "number" && value.trim().length < def.minLength)
789
+ throw new CliError(`${key} is too short`);
790
+ }
791
+ function parseCraftbookArguments(book, tokens, named = []) {
754
792
  const schema = book.paramSchema ?? {};
755
793
  const properties = schema.properties ?? {};
756
- const keys = Object.keys(properties);
794
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
795
+ const slots = Object.keys(properties).filter(
796
+ (key) => required.has(key) && properties[key].default === void 0 && paramAsksUser(properties[key], key)
797
+ );
757
798
  const params = {};
758
- for (const token of tokens) {
759
- const match = /^([A-Za-z][\w.-]*)=([\s\S]*)$/.exec(token);
760
- const key = match?.[1] ?? keys.find((name) => !Object.hasOwn(params, name));
761
- if (!key || !Object.hasOwn(properties, key))
762
- throw new CliError(`unknown craftbook argument: ${token}`);
799
+ const requestWords = [];
800
+ const set = (key, value, token) => {
801
+ if (!Object.hasOwn(properties, key)) throw new CliError(`unknown craftbook argument: ${token}`);
763
802
  if (Object.hasOwn(params, key)) throw new CliError(`duplicate craftbook parameter: ${key}`);
764
- const value = match ? match[2] : token;
765
- const def = properties[key];
766
- if (Array.isArray(def.enum) && !def.enum.map(String).includes(value)) {
767
- throw new CliError(`${key} must be one of: ${def.enum.join(", ")}`);
768
- }
769
- if (def.type === "boolean" && !["true", "false"].includes(value))
770
- throw new CliError(`${key} must be true or false`);
771
- if (def.type === "number" || def.type === "integer") {
772
- const number = Number(value);
773
- if (!value.trim() || !Number.isFinite(number) || def.type === "integer" && !Number.isInteger(number))
774
- throw new CliError(`${key} must be a ${def.type}`);
775
- if (typeof def.minimum === "number" && number < def.minimum)
776
- throw new CliError(`${key} must be at least ${def.minimum}`);
777
- if (typeof def.maximum === "number" && number > def.maximum)
778
- throw new CliError(`${key} must be at most ${def.maximum}`);
779
- }
780
- if (typeof def.pattern === "string" && !new RegExp(def.pattern).test(value))
781
- throw new CliError(`${key} must match ${def.pattern}`);
782
- if (typeof def.minLength === "number" && value.trim().length < def.minLength)
783
- throw new CliError(`${key} is too short`);
803
+ checkParamValue(key, properties[key], value);
784
804
  params[key] = value;
805
+ };
806
+ for (const token of tokens) {
807
+ const match = NAMED_ARGUMENT.exec(token);
808
+ if (match) {
809
+ set(match[1], match[2], token);
810
+ continue;
811
+ }
812
+ const slot = slots.find((key) => !Object.hasOwn(params, key));
813
+ if (slot) set(slot, token, token);
814
+ else requestWords.push(token);
785
815
  }
786
- for (const key of Array.isArray(schema.required) ? schema.required : []) {
816
+ for (const token of named) {
817
+ const match = NAMED_ARGUMENT.exec(token);
818
+ if (!match) throw new CliError(`--param expects key=value: ${token}`);
819
+ set(match[1], match[2], token);
820
+ }
821
+ for (const key of required) {
787
822
  if (typeof key === "string" && !Object.hasOwn(params, key) && properties[key]?.default === void 0)
788
823
  throw new CliError(`missing required craftbook parameter: ${key}`);
789
824
  }
790
- return params;
825
+ const request = requestWords.join(" ").trim();
826
+ return request ? { params, request } : { params };
827
+ }
828
+ function craftbookDoLaunch(craftbook, { params, request }) {
829
+ if (!request) return { craftbookParams: params };
830
+ const launch = composeCraftbookLaunch({
831
+ message: request,
832
+ craftbookName: craftbook.name,
833
+ paramSchema: craftbook.paramSchema,
834
+ params
835
+ });
836
+ return { description: launch.description, craftbookParams: launch.params };
791
837
  }
792
838
  var READ_RETRY_DELAYS = [250, 750, 1500];
793
839
  function transientTaskReadError(error) {
@@ -880,6 +926,578 @@ async function waitForTask(client, ref, options) {
880
926
  }
881
927
  }
882
928
 
929
+ // src/craftbook-setup.ts
930
+ import { Writable } from "stream";
931
+ import {
932
+ craftbookSetupGaps,
933
+ isCraftbookModelEngine,
934
+ resolveCraftbookModelNeeds,
935
+ resolveSecurityPolicy as resolveSecurityPolicy2
936
+ } from "@bendyline/gezel";
937
+ import { resolveOnDeviceProvider } from "@bendyline/gezel/native";
938
+
939
+ // src/model-pull.ts
940
+ async function pullChatModel(client, engine, id, writeProgress) {
941
+ let lastPct = -1;
942
+ let pullError;
943
+ const onEvent = (ev) => {
944
+ if (ev.type === "progress") {
945
+ const written = "bytesWrittenAll" in ev ? ev.bytesWrittenAll : ev.bytesWritten;
946
+ const total = "totalBytesAll" in ev ? ev.totalBytesAll : ev.totalBytes ?? 0;
947
+ const pct = total > 0 ? Math.floor(written / total * 100) : 0;
948
+ if (pct === lastPct) return;
949
+ lastPct = pct;
950
+ writeProgress(
951
+ `\rdownloading ${id} (${engine}): ${String(pct).padStart(3)}% ${formatGb(written)}/${formatGb(total)} GB`
952
+ );
953
+ } else if (ev.type === "retrying") {
954
+ writeProgress(`
955
+ retry ${ev.attempt}/${ev.maxAttempts}: ${ev.reason}
956
+ `);
957
+ } else if (ev.type === "error") {
958
+ pullError = ev.error;
959
+ writeProgress("\n");
960
+ } else if (ev.type === "done" && !pullError) {
961
+ writeProgress(`\rdownloaded ${id} (${engine})${" ".repeat(48)}
962
+ `);
963
+ }
964
+ };
965
+ if (engine === "mlx") await client.installMlxModel(id, onEvent);
966
+ else if (engine === "ds4") await client.installDs4Model(id, onEvent);
967
+ else await client.installLlamaCppModel(id, onEvent);
968
+ if (pullError) throw new CliError(`download failed: ${pullError}`);
969
+ }
970
+ function formatGb(bytes) {
971
+ return (bytes / 1e9).toFixed(2);
972
+ }
973
+
974
+ // src/native-command.ts
975
+ import {
976
+ NativeEngineNameSchema
977
+ } from "@bendyline/gezel";
978
+
979
+ // src/tui/bootstrap.ts
980
+ import {
981
+ computeModelFit,
982
+ formatModelAttribution,
983
+ isMoEFromTags,
984
+ isRecommendedModel,
985
+ mediaModelFits,
986
+ pickRecommendedModel
987
+ } from "@bendyline/gezel";
988
+ var NATIVE_TOOLKIT = [
989
+ "uv",
990
+ "sd-server",
991
+ "whisper-server",
992
+ "llama-server"
993
+ ];
994
+
995
+ // src/native-command.ts
996
+ var NATIVE_VARIANTS = ["cuda", "vulkan", "metal", "cpu"];
997
+ function parseNativeVariant(value) {
998
+ if (value === void 0) return void 0;
999
+ if (NATIVE_VARIANTS.includes(value)) return value;
1000
+ throw new CliError(`--variant must be one of ${NATIVE_VARIANTS.join(", ")} (got "${value}")`);
1001
+ }
1002
+ function parseNativeEngine(value) {
1003
+ if (value === void 0) return void 0;
1004
+ const parsed = NativeEngineNameSchema.safeParse(value);
1005
+ if (parsed.success) return parsed.data;
1006
+ throw new CliError(
1007
+ `--engine must be one of ${NativeEngineNameSchema.options.join(", ")} (got "${value}")`
1008
+ );
1009
+ }
1010
+ function formatNativeStatus(status) {
1011
+ const installed = new Set(
1012
+ status.engines.filter((engine) => engine.installed).map((engine) => engine.name)
1013
+ );
1014
+ const toolkitInstalled = NATIVE_TOOLKIT.filter((engine) => installed.has(engine)).length;
1015
+ return [
1016
+ `release: native-v${status.release} (${status.pinned ? "verified pin" : "unpinned \u2014 downloads disabled"})`,
1017
+ `platform: ${status.platformKey ?? "unsupported \u2014 downloads unavailable"}`,
1018
+ `llama backend: ${status.llamaBackend ?? "automatic"}`,
1019
+ // Name the members: `native list` shows every engine the release carries
1020
+ // (ds4, duckdb too), so a bare "0/4" read as a miscount beside it.
1021
+ `toolkit: ${toolkitInstalled}/${NATIVE_TOOLKIT.length} installed (${NATIVE_TOOLKIT.join(", ")}; see \`gezel native list\` for every engine)`
1022
+ ].join("\n");
1023
+ }
1024
+ function formatNativeList(status) {
1025
+ const rows = status.engines.map((engine) => {
1026
+ const state = engine.installed ? "installed" : "missing";
1027
+ return `${engine.name.padEnd(18)} ${state.padEnd(10)}${engine.path ? ` ${engine.path}` : ""}`;
1028
+ });
1029
+ return [
1030
+ `native-v${status.release} \xB7 ${status.platformKey ?? "unsupported platform"} \xB7 ${status.pinned ? "verified" : "unpinned"}`,
1031
+ "engine status path",
1032
+ ...rows
1033
+ ].join("\n");
1034
+ }
1035
+ async function installNativeToolkit(client, options) {
1036
+ const status = await client.getNativeEngineStatus();
1037
+ if (!status.pinned) {
1038
+ throw new CliError(
1039
+ "native downloads are disabled because the connected service has no verified native release pin."
1040
+ );
1041
+ }
1042
+ if (!status.platformKey) {
1043
+ throw new CliError(
1044
+ `native downloads are unavailable on ${process.platform}/${process.arch}: no supported build exists.`
1045
+ );
1046
+ }
1047
+ const llamaVariant = options.variant ?? status.llamaBackend;
1048
+ for (const engine of options.engines ?? NATIVE_TOOLKIT) {
1049
+ await ensureOneEngine(client, engine, llamaVariant, options.output);
1050
+ }
1051
+ return client.getNativeEngineStatus();
1052
+ }
1053
+ async function ensureOneEngine(client, engine, llamaVariant, output) {
1054
+ let terminalError;
1055
+ let progressLineOpen = false;
1056
+ const onEvent = (event) => {
1057
+ if (event.type === "progress") {
1058
+ progressLineOpen = true;
1059
+ output.writeProgress(`\r${formatProgress(engine, event.bytesWritten, event.totalBytes)}`);
1060
+ return;
1061
+ }
1062
+ if (progressLineOpen) {
1063
+ output.writeProgress("\n");
1064
+ progressLineOpen = false;
1065
+ }
1066
+ switch (event.type) {
1067
+ case "retrying":
1068
+ output.writeProgress(
1069
+ `${engine}: retry ${event.attempt}/${event.maxAttempts} in ${event.delayMs}ms \u2014 ${event.reason}
1070
+ `
1071
+ );
1072
+ break;
1073
+ case "verifying":
1074
+ output.writeProgress(`${engine}: verifying ${event.what}
1075
+ `);
1076
+ break;
1077
+ case "done":
1078
+ output.writeProgress(
1079
+ `${engine}: ready${event.cached ? " (cached)" : ` \u2014 ${event.binPath}`}
1080
+ `
1081
+ );
1082
+ break;
1083
+ case "error":
1084
+ terminalError = event.error;
1085
+ output.writeProgress(`${engine}: error \u2014 ${event.error}
1086
+ `);
1087
+ break;
1088
+ }
1089
+ };
1090
+ try {
1091
+ await client.ensureNativeEngine(
1092
+ engine,
1093
+ onEvent,
1094
+ engine === "llama-server" ? llamaVariant : void 0
1095
+ );
1096
+ } catch (error) {
1097
+ if (progressLineOpen) output.writeProgress("\n");
1098
+ throw new CliError(
1099
+ `native install failed for ${engine}: ${terminalError ?? errorMessage(error)}`
1100
+ );
1101
+ }
1102
+ if (progressLineOpen) output.writeProgress("\n");
1103
+ if (terminalError) {
1104
+ throw new CliError(`native install failed for ${engine}: ${terminalError}`);
1105
+ }
1106
+ }
1107
+ function formatProgress(engine, written, total) {
1108
+ if (total <= 0) return `${engine}: ${formatBytes(written)} downloaded`;
1109
+ const pct = Math.min(100, Math.floor(written / total * 100));
1110
+ return `${engine}: ${String(pct).padStart(3)}% ${formatBytes(written)}/${formatBytes(total)}`;
1111
+ }
1112
+ function formatBytes(bytes) {
1113
+ if (bytes < 1024) return `${bytes} B`;
1114
+ if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KiB`;
1115
+ if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(1)} MiB`;
1116
+ return `${(bytes / 1024 ** 3).toFixed(2)} GiB`;
1117
+ }
1118
+ function errorMessage(error) {
1119
+ return error instanceof Error ? error.message : String(error);
1120
+ }
1121
+
1122
+ // src/settings-command.ts
1123
+ import {
1124
+ classifySecurityLevel,
1125
+ resolveSecurityPolicy
1126
+ } from "@bendyline/gezel";
1127
+ var SECURITY_LEVEL_LABELS = {
1128
+ "super-lockdown": "Super Lockdown",
1129
+ lockdown: "Lockdown",
1130
+ free: "Unrestricted",
1131
+ custom: "Custom"
1132
+ };
1133
+ function policyWithExternalServices(config, enabled) {
1134
+ const current = resolveSecurityPolicy(config);
1135
+ const caps = {
1136
+ allowFileEdits: current.allowFileEdits,
1137
+ allowExternalChat: current.allowExternalChat,
1138
+ allowExternalServices: enabled,
1139
+ allowScriptExecution: current.allowScriptExecution,
1140
+ allowAppNetwork: current.allowAppNetwork
1141
+ };
1142
+ return { level: classifySecurityLevel(caps), ...caps };
1143
+ }
1144
+ function enabledValue(state) {
1145
+ if (state === void 0) return void 0;
1146
+ if (state === "on") return true;
1147
+ if (state === "off") return false;
1148
+ throw new CliError("Use on or off.");
1149
+ }
1150
+ function registerSecurityCommands(program2, connect) {
1151
+ program2.command("security").description("Inspect or explicitly change security settings").command("external-services [state]").description("Show or set on/off for model-initiated external services, including web search").option("--json", "Output the setting as JSON").action(async (state, options) => {
1152
+ const enabled = enabledValue(state);
1153
+ const client = await connect();
1154
+ const config = await client.getConfig();
1155
+ const policy = resolveSecurityPolicy(config);
1156
+ if (enabled !== void 0) {
1157
+ await client.updateConfig({ securityPolicy: policyWithExternalServices(config, enabled) });
1158
+ }
1159
+ const result = { allowExternalServices: enabled ?? policy.allowExternalServices };
1160
+ console.log(
1161
+ options.json ? JSON.stringify(result) : `External services: ${result.allowExternalServices ? "on" : "off"}`
1162
+ );
1163
+ });
1164
+ }
1165
+ function registerProjectSettingsCommands(env2, connect, projectFor) {
1166
+ env2.command("indexing [state]").description("Show or set on/off for background workspace indexing in the current project").option("--json", "Output the project setting as JSON").action(async (state, options) => {
1167
+ const enabled = enabledValue(state);
1168
+ const client = await connect();
1169
+ const projectId = await projectFor(client);
1170
+ const project = enabled === void 0 ? await client.getProject(projectId) : await client.updateProject(projectId, { indexingEnabled: enabled });
1171
+ const result = { projectId, indexingEnabled: project.indexingEnabled !== false };
1172
+ console.log(
1173
+ options.json ? JSON.stringify(result) : `${projectId}: workspace indexing ${result.indexingEnabled ? "on" : "off"}`
1174
+ );
1175
+ });
1176
+ }
1177
+
1178
+ // src/craftbook-setup.ts
1179
+ var BRAVE_KEY_URL = "https://brave.com/search/api/";
1180
+ var SEARCH_CHECK = { query: "Gezel web search check", limit: 1 };
1181
+ var ENGINE_BINARY = {
1182
+ "llama-cpp": "llama-server",
1183
+ mlx: "uv",
1184
+ ds4: "ds4-server"
1185
+ };
1186
+ async function ensureCraftbookSetup(client, options) {
1187
+ const services = options.needs.services ?? [];
1188
+ if (!options.needs.models?.length && services.length === 0) return;
1189
+ const config = await client.getConfig();
1190
+ const models = resolveCraftbookModelNeeds(options.needs.models, {
1191
+ ...options.params ? { params: options.params } : {},
1192
+ ...options.paramSchema ? { paramSchema: options.paramSchema } : {},
1193
+ defaultProvider: defaultModelEngine(config, options.platform, options.arch)
1194
+ });
1195
+ const gaps = craftbookSetupGaps(
1196
+ { services, models },
1197
+ await readSetupState(client, config, models)
1198
+ );
1199
+ if (gaps.length === 0) return;
1200
+ const sizes = await modelSizes(client, gaps);
1201
+ const lines = gaps.map((gap) => ` \u2022 ${describeGap(gap, sizes)}`);
1202
+ if (!options.prompter) {
1203
+ throw new CliError(
1204
+ [
1205
+ `${options.label} is not set up to run yet:`,
1206
+ ...lines,
1207
+ "",
1208
+ "Run the same command in a terminal to set it up step by step, or run:",
1209
+ ...instructions(gaps).map((line) => ` ${line}`)
1210
+ ].join("\n")
1211
+ );
1212
+ }
1213
+ options.write(`${options.label} needs some setup first:
1214
+ ${lines.join("\n")}
1215
+
1216
+ `);
1217
+ const prompter = options.prompter;
1218
+ const stop = (from) => {
1219
+ const rest = gaps.slice(gaps.indexOf(from));
1220
+ throw new CliError(
1221
+ [
1222
+ `Not set up, so ${options.label} did not start. To finish later, run:`,
1223
+ ...instructions(rest).map((line) => ` ${line}`)
1224
+ ].join("\n")
1225
+ );
1226
+ };
1227
+ for (const gap of gaps) {
1228
+ if (gap.kind === "external-services") {
1229
+ const next = policyWithExternalServices(config, true);
1230
+ const from = SECURITY_LEVEL_LABELS[resolveSecurityPolicy2(config).level];
1231
+ const to = SECURITY_LEVEL_LABELS[next.level];
1232
+ const change = from === to ? "" : ` This changes your security level from ${from} to ${to}.`;
1233
+ const yes = await prompter.confirm(
1234
+ `Turn on External services, so gezels can search the web and read web pages?${change} [y/N] `
1235
+ );
1236
+ if (!yes) stop(gap);
1237
+ await client.updateConfig({ securityPolicy: next });
1238
+ options.write("External services: on\n");
1239
+ } else if (gap.kind === "web-search") {
1240
+ if (gap.keyMissing) {
1241
+ options.write(
1242
+ `Web search needs a Brave Search API key. Get one at ${BRAVE_KEY_URL} \u2014 Gezel keeps it in this computer's secret store.
1243
+ `
1244
+ );
1245
+ const key = (await prompter.secret("Paste the key (hidden), or press Enter to stop: ")).trim();
1246
+ if (!key) stop(gap);
1247
+ await saveBraveKey(client, config, key, options.projectId);
1248
+ options.write("Web search: Brave (test search passed)\n");
1249
+ } else {
1250
+ const current = config.webSearch?.provider ?? "wikipedia";
1251
+ const yes = await prompter.confirm(
1252
+ `A Brave Search key is saved, but web search uses ${current === "wikipedia" ? "Wikipedia" : current}. Switch web search to Brave? [y/N] `
1253
+ );
1254
+ if (!yes) stop(gap);
1255
+ await client.updateConfig({ webSearch: { ...config.webSearch, provider: "brave" } });
1256
+ options.write("Web search: Brave\n");
1257
+ }
1258
+ }
1259
+ }
1260
+ const downloads = gaps.filter((gap) => gap.kind === "model");
1261
+ if (downloads.length > 0) {
1262
+ const total = downloads.reduce((sum, gap) => sum + (sizes.get(modelKey(gap)) ?? 0), 0);
1263
+ if (total > 0) {
1264
+ const space = await client.checkModelDownloadSpace({ sizeBytes: total });
1265
+ if (space.known && !space.ok) {
1266
+ throw new CliError(
1267
+ `The models need ${formatGb(space.requiredBytes)} GB, and Gezel model storage has ${formatGb(space.freeBytes)} GB free. Free some space, then run again.`
1268
+ );
1269
+ }
1270
+ }
1271
+ const what = downloads.length === 1 ? "this model" : `these ${downloads.length} models`;
1272
+ const yes = await prompter.confirm(
1273
+ `Download ${what} now? It is a one-time download${total > 0 ? ` of ${formatGb(total)} GB` : ""}. [y/N] `
1274
+ );
1275
+ if (!yes) stop(downloads[0]);
1276
+ await ensureEngines(
1277
+ client,
1278
+ downloads.map((gap) => gap.provider),
1279
+ options.write
1280
+ );
1281
+ for (const gap of downloads) await pullChatModel(client, gap.provider, gap.id, options.write);
1282
+ }
1283
+ const after = craftbookSetupGaps(
1284
+ { services, models },
1285
+ await readSetupState(client, await client.getConfig(), models)
1286
+ );
1287
+ if (after.length > 0) {
1288
+ throw new CliError(
1289
+ [
1290
+ `${options.label} is still not set up:`,
1291
+ ...after.map((gap) => ` \u2022 ${describeGap(gap, sizes)}`)
1292
+ ].join("\n")
1293
+ );
1294
+ }
1295
+ options.write("\n");
1296
+ }
1297
+ function terminalPrompter() {
1298
+ if (!process.stdin.isTTY || !process.stderr.isTTY) return null;
1299
+ return {
1300
+ confirm: async (question) => /^(y|yes)$/i.test((await ask(question, false)).trim()),
1301
+ secret: (question) => ask(question, true)
1302
+ };
1303
+ }
1304
+ function ask(question, hidden) {
1305
+ let muted = false;
1306
+ const output = new Writable({
1307
+ write(chunk, encoding, callback) {
1308
+ if (!muted) process.stderr.write(chunk, encoding);
1309
+ callback();
1310
+ }
1311
+ });
1312
+ return import("readline").then(
1313
+ ({ createInterface }) => new Promise((resolve6, reject) => {
1314
+ const rl = createInterface({ input: process.stdin, output, terminal: true });
1315
+ let settled = false;
1316
+ rl.on("SIGINT", () => {
1317
+ settled = true;
1318
+ rl.close();
1319
+ process.stderr.write("\n");
1320
+ reject(new CliError("Cancelled."));
1321
+ });
1322
+ rl.on("close", () => {
1323
+ if (settled) return;
1324
+ settled = true;
1325
+ process.stderr.write("\n");
1326
+ resolve6("");
1327
+ });
1328
+ rl.question(question, (answer) => {
1329
+ settled = true;
1330
+ rl.close();
1331
+ if (hidden) process.stderr.write("\n");
1332
+ resolve6(answer);
1333
+ });
1334
+ muted = hidden;
1335
+ })
1336
+ );
1337
+ }
1338
+ function defaultModelEngine(config, platform = process.platform, arch = process.arch) {
1339
+ const configured = config.provider;
1340
+ return configured && isCraftbookModelEngine(configured) ? configured : resolveOnDeviceProvider(platform, arch);
1341
+ }
1342
+ async function readSetupState(client, config, models) {
1343
+ const engines = [...new Set(models.map((model2) => model2.provider))];
1344
+ const installed = await Promise.all(
1345
+ engines.map(async (engine) => {
1346
+ const { models: list } = engine === "mlx" ? await client.listMlxModels() : engine === "ds4" ? await client.listDs4Models() : await client.listLlamaCppModels();
1347
+ return [engine, list.map((model2) => model2.id)];
1348
+ })
1349
+ );
1350
+ return {
1351
+ allowExternalServices: resolveSecurityPolicy2(config).allowExternalServices,
1352
+ ...config.webSearch?.provider ? { webSearchProvider: config.webSearch.provider } : {},
1353
+ hasBraveSearchApiKey: config.hasBraveSearchApiKey === true,
1354
+ installedModels: Object.fromEntries(installed)
1355
+ };
1356
+ }
1357
+ var modelKey = (model2) => `${model2.provider}:${model2.id}`;
1358
+ async function modelSizes(client, gaps) {
1359
+ const sizes = /* @__PURE__ */ new Map();
1360
+ for (const gap of gaps) {
1361
+ if (gap.kind !== "model") continue;
1362
+ let manifest;
1363
+ try {
1364
+ const item = await client.getCatalogItem("chat-model", gap.id);
1365
+ if (item.manifest.kind !== "chat-model") throw new Error("not a chat model");
1366
+ manifest = item.manifest;
1367
+ } catch {
1368
+ throw new CliError(
1369
+ `This run needs the model ${gap.id}, which is not installed and is not in the model catalog. Check the model name.`
1370
+ );
1371
+ }
1372
+ const source = gap.provider === "mlx" ? manifest.mlx : gap.provider === "ds4" ? manifest.ds4 : manifest.llamaCpp;
1373
+ if (!source) {
1374
+ throw new CliError(
1375
+ `This run needs the model ${gap.id} on ${gap.provider}, and the catalog has no ${gap.provider} download for it.`
1376
+ );
1377
+ }
1378
+ sizes.set(modelKey(gap), source.approxSizeBytes);
1379
+ }
1380
+ return sizes;
1381
+ }
1382
+ function describeGap(gap, sizes) {
1383
+ const why = gap.reasons.length > 0 ? ` (${gap.reasons.join("; ")})` : "";
1384
+ switch (gap.kind) {
1385
+ case "external-services":
1386
+ return `External services are off, so gezels cannot reach the web${why}.`;
1387
+ case "web-search":
1388
+ return gap.keyMissing ? `Web search needs a Brave Search API key, and none is set${why}.` : `Web search is not set to Brave Search${why}.`;
1389
+ case "model": {
1390
+ const size = sizes.get(modelKey(gap));
1391
+ return `${gap.id} is not downloaded yet (${gap.provider}${size ? `, ${formatGb(size)} GB` : ""})${why}.`;
1392
+ }
1393
+ }
1394
+ }
1395
+ function instructions(gaps) {
1396
+ const out = [];
1397
+ for (const gap of gaps) {
1398
+ if (gap.kind === "external-services") out.push("gezel security external-services on");
1399
+ else if (gap.kind === "web-search")
1400
+ out.push(
1401
+ `gezel secret set braveSearchApiKey --env BRAVE_SEARCH_API_KEY --use-for-search (get a key at ${BRAVE_KEY_URL})`
1402
+ );
1403
+ else out.push(`gezel model pull ${gap.id} --provider ${gap.provider}`);
1404
+ }
1405
+ return out;
1406
+ }
1407
+ async function saveBraveKey(client, config, key, projectId) {
1408
+ try {
1409
+ await client.updateConfig({
1410
+ braveSearchApiKey: key,
1411
+ webSearch: { ...config.webSearch, provider: "brave" }
1412
+ });
1413
+ } catch {
1414
+ throw new CliError("Could not save the key. Check the Gezel service, then run again.");
1415
+ }
1416
+ const failure = await client.toolWebSearch(projectId, SEARCH_CHECK).then(
1417
+ () => void 0,
1418
+ (error) => serviceErrorText(error)
1419
+ );
1420
+ if (failure === void 0) return;
1421
+ await client.updateConfig({ braveSearchApiKey: "", webSearch: { ...config.webSearch } }).catch(() => {
1422
+ });
1423
+ throw new CliError(
1424
+ `A test search with that key failed, so it was not kept: ${failure.replaceAll(key, "\u2026")}
1425
+ Check the key at ${BRAVE_KEY_URL}, then run again.`
1426
+ );
1427
+ }
1428
+ function serviceErrorText(error) {
1429
+ const details = error?.details;
1430
+ if (details && typeof details === "object") {
1431
+ const text = details.error;
1432
+ if (typeof text === "string" && text.trim()) return text.trim();
1433
+ }
1434
+ return error instanceof Error ? error.message : String(error);
1435
+ }
1436
+ async function ensureEngines(client, engines, write) {
1437
+ const status = await client.getNativeEngineStatus();
1438
+ if (!status.pinned || !status.platformKey) return;
1439
+ const missing = [...new Set(engines.map((engine) => ENGINE_BINARY[engine]))].filter(
1440
+ (binary) => !status.engines.some((entry) => entry.name === binary && entry.installed)
1441
+ );
1442
+ if (missing.length === 0) return;
1443
+ await installNativeToolkit(client, { engines: missing, output: { writeProgress: write } });
1444
+ }
1445
+
1446
+ // src/craftbook-shorthand.ts
1447
+ import { existsSync } from "fs";
1448
+ import { readFile as readFile2, readdir } from "fs/promises";
1449
+ import { join as join2 } from "path";
1450
+ import { projectLocalCraftbooksRoot } from "@bendyline/gezel/paths";
1451
+ var SHORTHAND_FLAG = "--via-craftbook-shorthand";
1452
+ var VALUE_OPTIONS = /* @__PURE__ */ new Set(["--connect", "--token", "--home"]);
1453
+ var OPTIONAL_VALUE_OPTIONS = /* @__PURE__ */ new Set(["--project"]);
1454
+ var CRAFTBOOK_WORD = /^[a-z0-9][a-z0-9._-]*$/i;
1455
+ function craftbookShorthandArgv(argv, builtins) {
1456
+ for (let index = 2; index < argv.length; index += 1) {
1457
+ const token = argv[index];
1458
+ if (token === "--") return null;
1459
+ if (token.startsWith("-")) {
1460
+ if (VALUE_OPTIONS.has(token)) index += 1;
1461
+ else if (OPTIONAL_VALUE_OPTIONS.has(token) && !(argv[index + 1] ?? "-").startsWith("-")) {
1462
+ index += 1;
1463
+ }
1464
+ continue;
1465
+ }
1466
+ if (builtins.has(token) || !CRAFTBOOK_WORD.test(token)) return null;
1467
+ return {
1468
+ argv: [...argv.slice(0, index), "do", SHORTHAND_FLAG, ...argv.slice(index)],
1469
+ word: token,
1470
+ tail: argv.slice(index + 1)
1471
+ };
1472
+ }
1473
+ return null;
1474
+ }
1475
+ function craftbookForShorthand(books, word) {
1476
+ const query = word.toLowerCase();
1477
+ return books.find((book) => book.command?.toLowerCase() === query) ?? books.find((book) => book.id.toLowerCase() === query);
1478
+ }
1479
+ async function workspaceCraftbookId(workspaceDir, word) {
1480
+ const root = projectLocalCraftbooksRoot(workspaceDir);
1481
+ if (!existsSync(root)) return void 0;
1482
+ const query = word.toLowerCase();
1483
+ const ids = [];
1484
+ for (const entry of await readdir(root, { withFileTypes: true })) {
1485
+ if (!entry.isDirectory()) continue;
1486
+ const manifest = await readFile2(join2(root, entry.name, "manifest.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
1487
+ if (!manifest) continue;
1488
+ const id = typeof manifest.id === "string" ? manifest.id : entry.name;
1489
+ if (typeof manifest.command === "string" && manifest.command.toLowerCase() === query) return id;
1490
+ ids.push(id);
1491
+ }
1492
+ return ids.find((id) => id.toLowerCase() === query);
1493
+ }
1494
+ function shellWord(token) {
1495
+ return /^[\w@%+=:,./-]+$/.test(token) ? token : `'${token.replaceAll("'", `'\\''`)}'`;
1496
+ }
1497
+ function shorthandEcho(id, tail) {
1498
+ return `\u2192 gezel do ${[id, ...tail].map(shellWord).join(" ")}`;
1499
+ }
1500
+
883
1501
  // src/engagement-mode.ts
884
1502
  var CLI_ENGAGEMENT_MODES = [
885
1503
  {
@@ -932,7 +1550,7 @@ var CLI_ENGAGEMENT_MODE_USAGE = CLI_ENGAGEMENT_MODES.map((option) => option.name
932
1550
  );
933
1551
 
934
1552
  // src/generate.ts
935
- import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
1553
+ import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
936
1554
  import { basename as basename2, dirname as dirname2, resolve as resolve2 } from "path";
937
1555
  async function resolvePromptText(parts, file, label) {
938
1556
  const inline = (parts ?? []).join(" ").trim();
@@ -940,7 +1558,7 @@ async function resolvePromptText(parts, file, label) {
940
1558
  if (inline) throw new CliError(`provide either ${label} text or --file, not both.`);
941
1559
  let raw;
942
1560
  try {
943
- raw = await readFile2(resolve2(file), "utf8");
1561
+ raw = await readFile3(resolve2(file), "utf8");
944
1562
  } catch (err) {
945
1563
  throw new CliError(`could not read --file "${file}": ${err.message}`);
946
1564
  }
@@ -974,7 +1592,7 @@ async function saveArtifact(client, projectId, artifactPath, output) {
974
1592
  }
975
1593
 
976
1594
  // src/knowledge-install.ts
977
- import { existsSync } from "fs";
1595
+ import { existsSync as existsSync2 } from "fs";
978
1596
  import { resolve as resolve3 } from "path";
979
1597
  import { KNOWLEDGE_ID_PATTERN } from "@bendyline/gezel";
980
1598
  var SHA256_PATTERN = /^[0-9a-f]{64}$/i;
@@ -1007,7 +1625,7 @@ function resolveKnowledgeInstallSource(source, expectedSha256, opts = {}) {
1007
1625
  function looksLikeCatalogId(source) {
1008
1626
  if (source.includes("/") || source.includes("\\") || source.endsWith(".gezk")) return false;
1009
1627
  if (!KNOWLEDGE_ID_PATTERN.test(source)) return false;
1010
- return !existsSync(source);
1628
+ return !existsSync2(source);
1011
1629
  }
1012
1630
  function assertCatalogOnlyOptions(opts, kind) {
1013
1631
  if (opts.version)
@@ -1054,35 +1672,8 @@ async function isInstalled(client, engine, id) {
1054
1672
  const { models } = engine === "mlx" ? await client.listMlxModels() : engine === "ds4" ? await client.listDs4Models() : await client.listLlamaCppModels();
1055
1673
  return models.some((model2) => model2.id === id);
1056
1674
  }
1057
- async function pull(client, engine, id, output) {
1058
- let lastPct = -1;
1059
- let pullError;
1060
- const onEvent = (ev) => {
1061
- if (ev.type === "progress") {
1062
- const written = "bytesWrittenAll" in ev ? ev.bytesWrittenAll : ev.bytesWritten;
1063
- const total = "totalBytesAll" in ev ? ev.totalBytesAll : ev.totalBytes ?? 0;
1064
- const pct = total > 0 ? Math.floor(written / total * 100) : 0;
1065
- if (pct === lastPct) return;
1066
- lastPct = pct;
1067
- output.writeProgress(
1068
- `\rdownloading ${id} (${engine}): ${String(pct).padStart(3)}% ${formatGb(written)}/${formatGb(total)} GB`
1069
- );
1070
- } else if (ev.type === "retrying") {
1071
- output.writeProgress(`
1072
- retry ${ev.attempt}/${ev.maxAttempts}: ${ev.reason}
1073
- `);
1074
- } else if (ev.type === "error") {
1075
- pullError = ev.error;
1076
- output.writeProgress("\n");
1077
- } else if (ev.type === "done" && !pullError) {
1078
- output.writeProgress(`\rdownloaded ${id} (${engine})${" ".repeat(48)}
1079
- `);
1080
- }
1081
- };
1082
- if (engine === "mlx") await client.installMlxModel(id, onEvent);
1083
- else if (engine === "ds4") await client.installDs4Model(id, onEvent);
1084
- else await client.installLlamaCppModel(id, onEvent);
1085
- if (pullError) throw new CliError(`download failed: ${pullError}`);
1675
+ function pull(client, engine, id, output) {
1676
+ return pullChatModel(client, engine, id, (text) => output.writeProgress(text));
1086
1677
  }
1087
1678
  async function exportModelToFile(client, id, options) {
1088
1679
  const { engine, cwd, output, signal } = options;
@@ -1093,220 +1684,95 @@ async function exportModelToFile(client, id, options) {
1093
1684
  if (!await isExistingDirectory(dirname3(target))) {
1094
1685
  throw new CliError(`${dirname3(target)} does not exist.`);
1095
1686
  }
1096
- let pulled = false;
1097
- if (!await isInstalled(client, engine, id)) {
1098
- if (options.skipPull) {
1099
- throw new CliError(
1100
- `model "${id}" is not installed for ${engine}. Run \`gezel model pull ${id}\` first, or drop --no-pull.`
1101
- );
1102
- }
1103
- await pull(client, engine, id, output);
1104
- pulled = true;
1105
- }
1106
- const name = basename3(target);
1107
- const partial = `${target}.partial-${randomUUID2()}`;
1108
- try {
1109
- output.writeProgress(`preparing ${name}
1110
- `);
1111
- const response = await client.exportModelBundle(engine, id, signal);
1112
- const modelBytes = modelBytesFromResponse(response);
1113
- const bytesWritten = await writeModelBundleResponse(
1114
- response,
1115
- partial,
1116
- ({ bytesCompleted, bytesTotal }) => {
1117
- output.writeProgress(`\rwriting ${name}: ${progressText(bytesCompleted, bytesTotal)}`);
1118
- },
1119
- signal
1120
- );
1121
- output.writeProgress(`\rwriting ${name}: ${progressText(bytesWritten, modelBytes)}
1122
- `);
1123
- await verifyModelBundleArchive(
1124
- partial,
1125
- ({ bytesCompleted, bytesTotal }) => {
1126
- output.writeProgress(`\rverifying ${name}: ${progressText(bytesCompleted, bytesTotal)}`);
1127
- },
1128
- signal
1129
- );
1130
- output.writeProgress(`\rverifying ${name}: done${" ".repeat(32)}
1131
- `);
1132
- signal?.throwIfAborted();
1133
- await publish(partial, target);
1134
- return { path: target, bytesWritten, pulled };
1135
- } catch (error) {
1136
- await rm2(partial, { force: true }).catch(() => {
1137
- });
1138
- throw error;
1139
- }
1140
- }
1141
- async function publish(partial, target) {
1142
- const backup = `${target}.backup-${randomUUID2()}`;
1143
- const backedUp = await isExistingFile(target);
1144
- if (backedUp) await rename(target, backup);
1145
- try {
1146
- await rename(partial, target);
1147
- } catch (error) {
1148
- if (backedUp) await rename(backup, target).catch(() => {
1149
- });
1150
- throw error;
1151
- }
1152
- if (backedUp) await rm2(backup, { force: true }).catch(() => {
1153
- });
1154
- }
1155
- function progressText(bytesCompleted, bytesTotal) {
1156
- if (!bytesTotal) return `${formatGb(bytesCompleted)} GB`;
1157
- const pct = Math.floor(bytesCompleted / bytesTotal * 100);
1158
- return `${String(pct).padStart(3)}% ${formatGb(bytesCompleted)}/${formatGb(bytesTotal)} GB`;
1159
- }
1160
- function formatGb(bytes) {
1161
- return (bytes / 1e9).toFixed(2);
1162
- }
1163
-
1164
- // src/native-command.ts
1165
- import {
1166
- NativeEngineNameSchema
1167
- } from "@bendyline/gezel";
1168
-
1169
- // src/tui/bootstrap.ts
1170
- import {
1171
- computeModelFit,
1172
- formatModelAttribution,
1173
- isMoEFromTags,
1174
- isRecommendedModel,
1175
- mediaModelFits,
1176
- pickRecommendedModel
1177
- } from "@bendyline/gezel";
1178
- var NATIVE_TOOLKIT = [
1179
- "uv",
1180
- "sd-server",
1181
- "whisper-server",
1182
- "llama-server"
1183
- ];
1184
-
1185
- // src/native-command.ts
1186
- var NATIVE_VARIANTS = ["cuda", "vulkan", "metal", "cpu"];
1187
- function parseNativeVariant(value) {
1188
- if (value === void 0) return void 0;
1189
- if (NATIVE_VARIANTS.includes(value)) return value;
1190
- throw new CliError(`--variant must be one of ${NATIVE_VARIANTS.join(", ")} (got "${value}")`);
1191
- }
1192
- function parseNativeEngine(value) {
1193
- if (value === void 0) return void 0;
1194
- const parsed = NativeEngineNameSchema.safeParse(value);
1195
- if (parsed.success) return parsed.data;
1196
- throw new CliError(
1197
- `--engine must be one of ${NativeEngineNameSchema.options.join(", ")} (got "${value}")`
1198
- );
1199
- }
1200
- function formatNativeStatus(status) {
1201
- const installed = new Set(
1202
- status.engines.filter((engine) => engine.installed).map((engine) => engine.name)
1203
- );
1204
- const toolkitInstalled = NATIVE_TOOLKIT.filter((engine) => installed.has(engine)).length;
1205
- return [
1206
- `release: native-v${status.release} (${status.pinned ? "verified pin" : "unpinned \u2014 downloads disabled"})`,
1207
- `platform: ${status.platformKey ?? "unsupported \u2014 downloads unavailable"}`,
1208
- `llama backend: ${status.llamaBackend ?? "automatic"}`,
1209
- // Name the members: `native list` shows every engine the release carries
1210
- // (ds4, duckdb too), so a bare "0/4" read as a miscount beside it.
1211
- `toolkit: ${toolkitInstalled}/${NATIVE_TOOLKIT.length} installed (${NATIVE_TOOLKIT.join(", ")}; see \`gezel native list\` for every engine)`
1212
- ].join("\n");
1213
- }
1214
- function formatNativeList(status) {
1215
- const rows = status.engines.map((engine) => {
1216
- const state = engine.installed ? "installed" : "missing";
1217
- return `${engine.name.padEnd(18)} ${state.padEnd(10)}${engine.path ? ` ${engine.path}` : ""}`;
1218
- });
1219
- return [
1220
- `native-v${status.release} \xB7 ${status.platformKey ?? "unsupported platform"} \xB7 ${status.pinned ? "verified" : "unpinned"}`,
1221
- "engine status path",
1222
- ...rows
1223
- ].join("\n");
1224
- }
1225
- async function installNativeToolkit(client, options) {
1226
- const status = await client.getNativeEngineStatus();
1227
- if (!status.pinned) {
1228
- throw new CliError(
1229
- "native downloads are disabled because the connected service has no verified native release pin."
1230
- );
1231
- }
1232
- if (!status.platformKey) {
1233
- throw new CliError(
1234
- `native downloads are unavailable on ${process.platform}/${process.arch}: no supported build exists.`
1235
- );
1236
- }
1237
- const llamaVariant = options.variant ?? status.llamaBackend;
1238
- for (const engine of options.engines ?? NATIVE_TOOLKIT) {
1239
- await ensureOneEngine(client, engine, llamaVariant, options.output);
1240
- }
1241
- return client.getNativeEngineStatus();
1242
- }
1243
- async function ensureOneEngine(client, engine, llamaVariant, output) {
1244
- let terminalError;
1245
- let progressLineOpen = false;
1246
- const onEvent = (event) => {
1247
- if (event.type === "progress") {
1248
- progressLineOpen = true;
1249
- output.writeProgress(`\r${formatProgress(engine, event.bytesWritten, event.totalBytes)}`);
1250
- return;
1251
- }
1252
- if (progressLineOpen) {
1253
- output.writeProgress("\n");
1254
- progressLineOpen = false;
1687
+ let pulled = false;
1688
+ if (!await isInstalled(client, engine, id)) {
1689
+ if (options.skipPull) {
1690
+ throw new CliError(
1691
+ `model "${id}" is not installed for ${engine}. Run \`gezel model pull ${id}\` first, or drop --no-pull.`
1692
+ );
1255
1693
  }
1256
- switch (event.type) {
1257
- case "retrying":
1258
- output.writeProgress(
1259
- `${engine}: retry ${event.attempt}/${event.maxAttempts} in ${event.delayMs}ms \u2014 ${event.reason}
1260
- `
1261
- );
1262
- break;
1263
- case "verifying":
1264
- output.writeProgress(`${engine}: verifying ${event.what}
1694
+ await pull(client, engine, id, output);
1695
+ pulled = true;
1696
+ }
1697
+ const name = basename3(target);
1698
+ const partial = `${target}.partial-${randomUUID2()}`;
1699
+ try {
1700
+ output.writeProgress(`preparing ${name}
1265
1701
  `);
1266
- break;
1267
- case "done":
1268
- output.writeProgress(
1269
- `${engine}: ready${event.cached ? " (cached)" : ` \u2014 ${event.binPath}`}
1270
- `
1271
- );
1272
- break;
1273
- case "error":
1274
- terminalError = event.error;
1275
- output.writeProgress(`${engine}: error \u2014 ${event.error}
1702
+ const response = await client.exportModelBundle(engine, id, signal);
1703
+ const modelBytes = modelBytesFromResponse(response);
1704
+ const bytesWritten = await writeModelBundleResponse(
1705
+ response,
1706
+ partial,
1707
+ ({ bytesCompleted, bytesTotal }) => {
1708
+ output.writeProgress(`\rwriting ${name}: ${progressText(bytesCompleted, bytesTotal)}`);
1709
+ },
1710
+ signal
1711
+ );
1712
+ output.writeProgress(`\rwriting ${name}: ${progressText(bytesWritten, modelBytes)}
1276
1713
  `);
1277
- break;
1278
- }
1279
- };
1280
- try {
1281
- await client.ensureNativeEngine(
1282
- engine,
1283
- onEvent,
1284
- engine === "llama-server" ? llamaVariant : void 0
1714
+ await verifyModelBundleArchive(
1715
+ partial,
1716
+ ({ bytesCompleted, bytesTotal }) => {
1717
+ output.writeProgress(`\rverifying ${name}: ${progressText(bytesCompleted, bytesTotal)}`);
1718
+ },
1719
+ signal
1285
1720
  );
1721
+ output.writeProgress(`\rverifying ${name}: done${" ".repeat(32)}
1722
+ `);
1723
+ signal?.throwIfAborted();
1724
+ await publish(partial, target);
1725
+ return { path: target, bytesWritten, pulled };
1286
1726
  } catch (error) {
1287
- if (progressLineOpen) output.writeProgress("\n");
1288
- throw new CliError(
1289
- `native install failed for ${engine}: ${terminalError ?? errorMessage(error)}`
1290
- );
1291
- }
1292
- if (progressLineOpen) output.writeProgress("\n");
1293
- if (terminalError) {
1294
- throw new CliError(`native install failed for ${engine}: ${terminalError}`);
1727
+ await rm2(partial, { force: true }).catch(() => {
1728
+ });
1729
+ throw error;
1295
1730
  }
1296
1731
  }
1297
- function formatProgress(engine, written, total) {
1298
- if (total <= 0) return `${engine}: ${formatBytes(written)} downloaded`;
1299
- const pct = Math.min(100, Math.floor(written / total * 100));
1300
- return `${engine}: ${String(pct).padStart(3)}% ${formatBytes(written)}/${formatBytes(total)}`;
1732
+ async function publish(partial, target) {
1733
+ const backup = `${target}.backup-${randomUUID2()}`;
1734
+ const backedUp = await isExistingFile(target);
1735
+ if (backedUp) await rename(target, backup);
1736
+ try {
1737
+ await rename(partial, target);
1738
+ } catch (error) {
1739
+ if (backedUp) await rename(backup, target).catch(() => {
1740
+ });
1741
+ throw error;
1742
+ }
1743
+ if (backedUp) await rm2(backup, { force: true }).catch(() => {
1744
+ });
1301
1745
  }
1302
- function formatBytes(bytes) {
1303
- if (bytes < 1024) return `${bytes} B`;
1304
- if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KiB`;
1305
- if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(1)} MiB`;
1306
- return `${(bytes / 1024 ** 3).toFixed(2)} GiB`;
1746
+ function progressText(bytesCompleted, bytesTotal) {
1747
+ if (!bytesTotal) return `${formatGb(bytesCompleted)} GB`;
1748
+ const pct = Math.floor(bytesCompleted / bytesTotal * 100);
1749
+ return `${String(pct).padStart(3)}% ${formatGb(bytesCompleted)}/${formatGb(bytesTotal)} GB`;
1307
1750
  }
1308
- function errorMessage(error) {
1309
- return error instanceof Error ? error.message : String(error);
1751
+
1752
+ // src/run-prompt.ts
1753
+ async function resolveRunPrompt(parts, input = process.stdin) {
1754
+ if (parts?.length !== 1 || parts[0] !== "-") {
1755
+ const prompt2 = (parts ?? []).join(" ").trim();
1756
+ if (!prompt2) throw new CliError('usage: gezel run "<prompt>" or gezel run -');
1757
+ return prompt2;
1758
+ }
1759
+ if (input.isTTY) {
1760
+ throw new CliError("gezel run - requires piped input or a redirected file.");
1761
+ }
1762
+ const chunks = [];
1763
+ try {
1764
+ for await (const chunk of input) {
1765
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1766
+ }
1767
+ } catch (error) {
1768
+ throw new CliError(
1769
+ `Could not read prompt from stdin: ${error instanceof Error ? error.message : String(error)}`
1770
+ );
1771
+ }
1772
+ const prompt = Buffer.concat(chunks).toString("utf8");
1773
+ if (!prompt.trim())
1774
+ throw new CliError("gezel run - received empty input. Supply a prompt on stdin.");
1775
+ return prompt;
1310
1776
  }
1311
1777
 
1312
1778
  // src/run-readiness.ts
@@ -1492,43 +1958,6 @@ function registerSecretCommands(program2, connect, output = console.log) {
1492
1958
  });
1493
1959
  }
1494
1960
 
1495
- // src/settings-command.ts
1496
- import { resolveSecurityPolicy } from "@bendyline/gezel";
1497
- function enabledValue(state) {
1498
- if (state === void 0) return void 0;
1499
- if (state === "on") return true;
1500
- if (state === "off") return false;
1501
- throw new CliError("Use on or off.");
1502
- }
1503
- function registerSecurityCommands(program2, connect) {
1504
- program2.command("security").description("Inspect or explicitly change security settings").command("external-services [state]").description("Show or set on/off for model-initiated external services, including web search").option("--json", "Output the setting as JSON").action(async (state, options) => {
1505
- const enabled = enabledValue(state);
1506
- const client = await connect();
1507
- const policy = resolveSecurityPolicy(await client.getConfig());
1508
- if (enabled !== void 0) {
1509
- await client.updateConfig({
1510
- securityPolicy: { ...policy, level: "custom", allowExternalServices: enabled }
1511
- });
1512
- }
1513
- const result = { allowExternalServices: enabled ?? policy.allowExternalServices };
1514
- console.log(
1515
- options.json ? JSON.stringify(result) : `External services: ${result.allowExternalServices ? "on" : "off"}`
1516
- );
1517
- });
1518
- }
1519
- function registerProjectSettingsCommands(env2, connect, projectFor) {
1520
- env2.command("indexing [state]").description("Show or set on/off for background workspace indexing in the current project").option("--json", "Output the project setting as JSON").action(async (state, options) => {
1521
- const enabled = enabledValue(state);
1522
- const client = await connect();
1523
- const projectId = await projectFor(client);
1524
- const project = enabled === void 0 ? await client.getProject(projectId) : await client.updateProject(projectId, { indexingEnabled: enabled });
1525
- const result = { projectId, indexingEnabled: project.indexingEnabled !== false };
1526
- console.log(
1527
- options.json ? JSON.stringify(result) : `${projectId}: workspace indexing ${result.indexingEnabled ? "on" : "off"}`
1528
- );
1529
- });
1530
- }
1531
-
1532
1961
  // src/storage-format.ts
1533
1962
  function formatBytes2(bytes) {
1534
1963
  if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
@@ -1664,6 +2093,7 @@ function formatBackupPlan(plan) {
1664
2093
  gezel: "gezels",
1665
2094
  project: "projects",
1666
2095
  "document-root": "documents",
2096
+ "memory-root": "memories about you",
1667
2097
  "settings-file": "settings files"
1668
2098
  };
1669
2099
  for (const [kind, bucket] of byKind) {
@@ -1756,7 +2186,7 @@ function editDistance(a, b) {
1756
2186
  }
1757
2187
 
1758
2188
  // src/workflow-command.ts
1759
- import { realpath } from "fs/promises";
2189
+ import { realpath as realpath2 } from "fs/promises";
1760
2190
  import { isAbsolute as isAbsolute2, relative, resolve as resolve5 } from "path";
1761
2191
  import { pathToFileURL } from "url";
1762
2192
  import {
@@ -1774,9 +2204,9 @@ function validateWorkflowCraftbook(document) {
1774
2204
  }
1775
2205
  async function runWorkflow(client, projectId, workspace, file, args, log = console.error, invocation) {
1776
2206
  const named = /^[a-z][a-z0-9-]*$/.test(file);
1777
- const path = await realpath(resolve5(workspace, named ? `.gezel/workflows/${file}.mjs` : file));
2207
+ const path = await realpath2(resolve5(workspace, named ? `.gezel/workflows/${file}.mjs` : file));
1778
2208
  if (invocation) {
1779
- const local = relative(await realpath(workspace), path);
2209
+ const local = relative(await realpath2(workspace), path);
1780
2210
  if (isAbsolute2(local) || local === ".." || local.startsWith("../") || local.startsWith("..\\")) {
1781
2211
  throw new CliError("A craftbook workflow module must remain inside its project workspace.");
1782
2212
  }
@@ -1784,6 +2214,15 @@ async function runWorkflow(client, projectId, workspace, file, args, log = conso
1784
2214
  const module = await import(pathToFileURL(path).href);
1785
2215
  if (typeof module.run !== "function")
1786
2216
  throw new CliError(`workflow ${path} must export an async run(context) function`);
2217
+ const ensureSetup = (needs, book = invocation?.craftbook, params = invocation?.params) => ensureCraftbookSetup(client, {
2218
+ projectId,
2219
+ label: book?.name ?? "This workflow",
2220
+ needs,
2221
+ ...params ? { params } : {},
2222
+ ...book?.paramSchema ? { paramSchema: book.paramSchema } : {},
2223
+ prompter: terminalPrompter(),
2224
+ write: (text) => process.stderr.write(text)
2225
+ });
1787
2226
  return module.run({
1788
2227
  client,
1789
2228
  projectId,
@@ -1795,41 +2234,66 @@ async function runWorkflow(client, projectId, workspace, file, args, log = conso
1795
2234
  // A bounded model call whose input the driver already holds. Cheaper and
1796
2235
  // more reliable than a task that must read its input back through tools.
1797
2236
  complete: (request, signal) => client.completeInProject(projectId, request, signal),
1798
- runCraftbook: async (id, params, options = {}) => {
1799
- let ref = options.taskRef;
1800
- if (!ref) {
1801
- const { craftbook: book } = await client.getCraftbook(id, { projectId, source: "project" });
1802
- const parsed = parseCraftbookParams(
1803
- book,
1804
- Object.entries(params).map(([key, value]) => `${key}=${value}`)
1805
- );
1806
- const task2 = await client.createTask(projectId, {
1807
- title: options.title ?? book.name,
1808
- description: `Run the project craftbook ${book.name}. Follow every step and satisfy its required outcomes before completing this task.`,
1809
- craftbookId: id,
1810
- craftbookSourceId: "project",
1811
- craftbookVersion: book.version,
1812
- craftbookParams: parsed,
1813
- dispatchEntry: true,
1814
- roleBasedNameOnlyMode: true,
1815
- trustScripts: true,
1816
- ...options.parentTaskRef ? { parentTaskRef: options.parentTaskRef } : {}
2237
+ // Needs the module computes at run time (models chosen by its own
2238
+ // options): asked for at a terminal, otherwise a CliError naming the fix.
2239
+ ensureSetup: (needs) => ensureSetup(needs),
2240
+ runCraftbook: Object.assign(
2241
+ async (id, params, options = {}) => {
2242
+ let ref = options.taskRef;
2243
+ if (!ref) {
2244
+ let book;
2245
+ try {
2246
+ ({ craftbook: book } = await client.getCraftbook(id, { projectId, source: "project" }));
2247
+ } catch (error) {
2248
+ if (error instanceof Error) {
2249
+ Object.assign(error, {
2250
+ taskCreation: { attempted: false, phase: "craftbook-read" }
2251
+ });
2252
+ }
2253
+ throw error;
2254
+ }
2255
+ const { params: parsed } = parseCraftbookArguments(
2256
+ book,
2257
+ [],
2258
+ Object.entries(params).map(([key, value]) => `${key}=${value}`)
2259
+ );
2260
+ await ensureSetup(book, book, parsed);
2261
+ const body = {
2262
+ title: options.title ?? book.name,
2263
+ description: `Run the project craftbook ${book.name}. Follow every step and satisfy its required outcomes before completing this task.`,
2264
+ craftbookId: id,
2265
+ craftbookSourceId: "project",
2266
+ craftbookVersion: book.version,
2267
+ craftbookParams: parsed,
2268
+ dispatchEntry: true,
2269
+ roleBasedNameOnlyMode: true,
2270
+ trustScripts: true,
2271
+ ...options.parentTaskRef ? { parentTaskRef: options.parentTaskRef } : {}
2272
+ };
2273
+ const task2 = options.creationKey ? await client.createWorkflowTask(projectId, {
2274
+ ...body,
2275
+ workflowInvocationKey: options.creationKey
2276
+ }) : await client.createTask(projectId, body);
2277
+ await options.onCreated?.(task2);
2278
+ ref = task2.ref;
2279
+ }
2280
+ log(`Following ${ref}`);
2281
+ return waitForTask(client, ref, {
2282
+ timeoutMs: options.timeoutMs ?? invocation?.timeoutMs ?? 72e5,
2283
+ onProgress: (task2) => log(`${task2.ref}: ${task2.status} (${task2.activeStepId ?? "finished"})`)
1817
2284
  });
1818
- await options.onCreated?.(task2);
1819
- ref = task2.ref;
1820
- }
1821
- log(`Following ${ref}`);
1822
- return waitForTask(client, ref, {
1823
- timeoutMs: options.timeoutMs ?? invocation?.timeoutMs ?? 72e5,
1824
- onProgress: (task2) => log(`${task2.ref}: ${task2.status} (${task2.activeStepId ?? "finished"})`)
1825
- });
1826
- }
2285
+ },
2286
+ { supportsIdempotentCreation: true }
2287
+ )
1827
2288
  });
1828
2289
  }
1829
2290
 
1830
2291
  // src/bin/gezel.ts
1831
2292
  var program = new Command();
1832
- program.name("gezel").description("Gezel \u2014 assemble a team of AI companions (gezels) and put them to work.").version(GEZEL_VERSION).option(
2293
+ program.name("gezel").description("Gezel \u2014 assemble a team of AI companions (gezels) and put them to work.").addHelpText(
2294
+ "after",
2295
+ "\nAny craftbook also runs by name: `gezel <craftbook> \u2026` is `gezel do <craftbook> \u2026`."
2296
+ ).version(GEZEL_VERSION).option(
1833
2297
  "--connect <url>",
1834
2298
  "Connect to this Gezel service (first use asks for approval in the Gezel app)."
1835
2299
  ).option("--token <token>", "Bearer token for --connect (must have CLI access).").option("--http1", "Use HTTP/1.1 for daemon requests, keeping TLS certificate validation.").option(
@@ -1848,10 +2312,35 @@ program.hook("preAction", () => {
1848
2312
  if (globals.http1) process.env.GEZEL_HTTP_VERSION = "1.1";
1849
2313
  applyHome(globals);
1850
2314
  });
2315
+ function builtinCommandNames() {
2316
+ return ["help", ...program.commands.flatMap((command) => [command.name(), ...command.aliases()])];
2317
+ }
2318
+ var shorthandTail = [];
2319
+ async function resolveCraftbookShorthand(parts) {
2320
+ const word = parts[0] ?? "";
2321
+ const unknown = unknownCommandMessage(parts, builtinCommandNames());
2322
+ let client;
2323
+ let id;
2324
+ try {
2325
+ client = await connectOwned(cliGlobals());
2326
+ const preview = await previewRunProject(client, cliGlobals());
2327
+ const [config, items] = await Promise.all([
2328
+ client.getConfig(),
2329
+ preview.projectId ? client.listProjectCraftbooks(preview.projectId).then((result) => result.items) : client.listCatalogItems("craftbook-template").then((result) => result.items)
2330
+ ]);
2331
+ const books = normalizeCraftbooks(items, config.showWorkInProgressFeatures === true);
2332
+ id = craftbookForShorthand(books, word)?.id ?? (preview.projectId === null ? await workspaceCraftbookId(preview.root, word) : void 0);
2333
+ } catch (err) {
2334
+ const reason = formatCliFailure(err) ?? (err instanceof Error ? err.message : String(err));
2335
+ throw new CliError(`${unknown}
2336
+ (Could not look for a craftbook named '${word}': ${reason})`);
2337
+ }
2338
+ if (!id) throw new CliError(unknown);
2339
+ return { client, id };
2340
+ }
1851
2341
  program.action(async () => {
1852
2342
  if (program.args.length > 0) {
1853
- const known = program.commands.flatMap((command) => [command.name(), ...command.aliases()]);
1854
- throw new CliError(unknownCommandMessage(program.args, known));
2343
+ throw new CliError(unknownCommandMessage(program.args, builtinCommandNames()));
1855
2344
  }
1856
2345
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
1857
2346
  throw new CliError(
@@ -1884,79 +2373,106 @@ program.action(async () => {
1884
2373
  });
1885
2374
  program.command("start").description("Start the Gezel daemon (no-op if already running)").option(
1886
2375
  "--port <port>",
1887
- "Bind to a specific port (spawns a fresh daemon, does not adopt a running one)"
2376
+ "Bind to a specific port (reuses a daemon already on it; see --restart for one that is not)"
1888
2377
  ).option(
1889
2378
  "--foreground",
1890
2379
  "Run the daemon attached to this terminal \u2014 stdio streams to this shell, Ctrl+C stops it. Useful for development and CI."
1891
2380
  ).option(
1892
2381
  "--web",
1893
- "Serve the web UI over HTTP on loopback and print a one-time browser URL (spawns a fresh HTTP daemon)."
1894
- ).option("--open", "With --web, open the printed URL in your default browser.").action(async (opts) => {
1895
- const port = opts.port ? Number.parseInt(opts.port, 10) : void 0;
1896
- if (port !== void 0 && !Number.isFinite(port)) {
1897
- console.error(`invalid --port: ${opts.port}`);
1898
- process.exitCode = 1;
1899
- return;
1900
- }
1901
- const userEnv = { ...process.env };
1902
- delete userEnv.GEZEL_SERVICE_ROLE;
1903
- delete userEnv.GEZEL_SYSTEM_SCOPE;
1904
- delete userEnv.GEZEL_PORT;
1905
- const spawnEnv = {
1906
- ...userEnv,
1907
- GEZEL_SERVICE_ROLE: "user"
1908
- };
1909
- const portEnv = resolveStartPortEnv(port, await shouldPreferCanonicalPort());
1910
- if (portEnv !== void 0) spawnEnv.GEZEL_PORT = portEnv;
1911
- if (opts.web) {
1912
- spawnEnv.GEZEL_WEB = "1";
1913
- spawnEnv.GEZEL_INSECURE_TRANSPORT = "1";
1914
- }
1915
- if (opts.foreground) {
1916
- await startForeground(spawnEnv);
1917
- return;
1918
- }
1919
- if (port !== void 0 || opts.web) {
1920
- const entry = resolveDaemonEntry2(import.meta.url);
1921
- const result = await discoverOrSpawn2({
1922
- daemonEntry: entry,
1923
- detached: true,
1924
- env: spawnEnv,
1925
- // Always spawn fresh — don't adopt a running daemon that may be
1926
- // on the wrong port / transport. (forceSpawn keeps the readiness
1927
- // poll working, unlike a null readRuntimeFn override.)
1928
- forceSpawn: true,
1929
- // A cold first boot (fresh home: layout + default gezels +
1930
- // native probe + catalog) routinely exceeds the 5s default, so
1931
- // the spawn would time out while the daemon is still coming up —
1932
- // and in --web mode the user would never see their URL. Give it
1933
- // real headroom.
1934
- timeoutMs: 2e4
1935
- });
1936
- const health2 = await result.client.health();
1937
- console.log(
1938
- `gezeld running (version ${health2.version}) on port ${new URL(result.baseUrl).port}`
1939
- );
1940
- if (opts.web) await printWebUrl(result.baseUrl, opts.open === true);
1941
- return;
2382
+ "Serve the web UI over HTTP on loopback and print a one-time browser URL (reuses a daemon already serving it)."
2383
+ ).option("--open", "With --web, open the printed URL in your default browser.").option(
2384
+ "--restart",
2385
+ "With --web or --port, stop a running daemon started without them and start a new one."
2386
+ ).action(
2387
+ async (opts) => {
2388
+ const port = opts.port ? Number.parseInt(opts.port, 10) : void 0;
2389
+ if (port !== void 0 && !Number.isFinite(port)) {
2390
+ console.error(`invalid --port: ${opts.port}`);
2391
+ process.exitCode = 1;
2392
+ return;
2393
+ }
2394
+ const userEnv = { ...process.env };
2395
+ delete userEnv.GEZEL_SERVICE_ROLE;
2396
+ delete userEnv.GEZEL_SYSTEM_SCOPE;
2397
+ delete userEnv.GEZEL_PORT;
2398
+ const spawnEnv = {
2399
+ ...userEnv,
2400
+ GEZEL_SERVICE_ROLE: "user"
2401
+ };
2402
+ const portEnv = resolveStartPortEnv(port, await shouldPreferCanonicalPort());
2403
+ if (portEnv !== void 0) spawnEnv.GEZEL_PORT = portEnv;
2404
+ if (opts.web) {
2405
+ spawnEnv.GEZEL_WEB = "1";
2406
+ spawnEnv.GEZEL_INSECURE_TRANSPORT = "1";
2407
+ }
2408
+ if (opts.foreground) {
2409
+ await startForeground(spawnEnv);
2410
+ return;
2411
+ }
2412
+ if (port !== void 0 || opts.web) {
2413
+ const runtime = await readRuntime2();
2414
+ const running = runtime && isProcessAlive2(runtime.pid) ? runtime : null;
2415
+ const reuse = running !== null && await runtimeServes(running, { port, web: opts.web === true });
2416
+ if (running && !reuse) {
2417
+ const wanted = opts.web ? "with the web UI" : `on port ${port}`;
2418
+ if (!opts.restart) {
2419
+ const retry = ["gezel start", ...port !== void 0 ? [`--port ${port}`] : []];
2420
+ if (opts.web) retry.push("--web");
2421
+ throw new CliError(
2422
+ `gezeld is already running for this home ${opts.web ? "without the web UI" : `on port ${running.port}`} (pid ${running.pid}).
2423
+ Restart it ${wanted} with \`${[...retry, "--restart"].join(" ")}\`, or stop it first with \`gezel stop --daemon\`.`
2424
+ );
2425
+ }
2426
+ console.error(`Restarting gezeld (pid ${running.pid}) ${wanted}\u2026`);
2427
+ if (!await stopDaemonPid(running.pid)) {
2428
+ throw new CliError(`failed to confirm gezeld pid=${running.pid} stopped`);
2429
+ }
2430
+ }
2431
+ const entry = resolveDaemonEntry2(import.meta.url);
2432
+ const result = await discoverOrSpawn2({
2433
+ daemonEntry: entry,
2434
+ detached: true,
2435
+ env: spawnEnv,
2436
+ // Never adopt a daemon that lacks the requested port or transport.
2437
+ // A forced spawn accepts only its own process, so losing a race
2438
+ // fails here instead of reporting someone else's daemon.
2439
+ forceSpawn: !reuse,
2440
+ // A cold first boot (fresh home: layout + default gezels +
2441
+ // native probe + catalog) routinely exceeds the 5s default, so
2442
+ // the spawn would time out while the daemon is still coming up —
2443
+ // and in --web mode the user would never see their URL. Give it
2444
+ // real headroom.
2445
+ timeoutMs: 2e4
2446
+ });
2447
+ const health2 = await result.client.health();
2448
+ console.log(
2449
+ `gezeld running (version ${health2.version}) on port ${new URL(result.baseUrl).port}`
2450
+ );
2451
+ if (opts.web) await printWebUrl(result.baseUrl, opts.open === true);
2452
+ return;
2453
+ }
2454
+ const client = await connectOwned(cliGlobals(), { announceSpawn: false });
2455
+ const health = await client.health();
2456
+ console.log(`gezeld running (version ${health.version})`);
1942
2457
  }
1943
- const client = await connectOwned(cliGlobals(), { announceSpawn: false });
1944
- const health = await client.health();
1945
- console.log(`gezeld running (version ${health.version})`);
1946
- });
2458
+ );
2459
+ async function runtimeServes(runtime, want) {
2460
+ if (want.port !== void 0 && runtime.port !== want.port) return false;
2461
+ if (!want.web) return true;
2462
+ if (new URL(runtime.baseUrl).protocol !== "http:") return false;
2463
+ const { readFile: readFile4 } = await import("fs/promises");
2464
+ const { gezelPaths: gezelPaths2 } = await import("@bendyline/gezel/paths");
2465
+ const token = await readFile4(gezelPaths2().runtime.webUiToken, "utf8").catch(() => "");
2466
+ return token.trim().length > 0;
2467
+ }
1947
2468
  async function printWebUrl(baseUrl, open) {
1948
- const { readFile: readFile3 } = await import("fs/promises");
2469
+ const { readFile: readFile4 } = await import("fs/promises");
1949
2470
  const { gezelPaths: gezelPaths2 } = await import("@bendyline/gezel/paths");
1950
- let token;
1951
- try {
1952
- token = (await readFile3(gezelPaths2().runtime.webUiToken, "utf8")).trim();
1953
- } catch {
1954
- console.error("web UI: could not read the web-ui token from the runtime files.");
1955
- return;
1956
- }
2471
+ const token = (await readFile4(gezelPaths2().runtime.webUiToken, "utf8").catch(() => "")).trim();
1957
2472
  if (!token) {
1958
- console.error("web UI: the web-ui token file was empty.");
1959
- return;
2473
+ throw new CliError(
2474
+ "gezeld is running, but it published no web UI token, so there is no browser URL to print. Run `gezel start --web --restart`."
2475
+ );
1960
2476
  }
1961
2477
  const url = `${new URL(baseUrl).origin}/?token=${encodeURIComponent(token)}`;
1962
2478
  console.log("");
@@ -2106,11 +2622,11 @@ program.command("stop").description(
2106
2622
  }
2107
2623
  });
2108
2624
  async function clearStaleRuntime(stoppedPid) {
2109
- const { readFile: readFile3, rm: rm3 } = await import("fs/promises");
2625
+ const { readFile: readFile4, rm: rm3 } = await import("fs/promises");
2110
2626
  const { gezelPaths: gezelPaths2 } = await import("@bendyline/gezel/paths");
2111
2627
  const runtime = gezelPaths2().runtime;
2112
2628
  const recorded = Number.parseInt(
2113
- (await readFile3(runtime.pid, "utf8").catch(() => "")).trim(),
2629
+ (await readFile4(runtime.pid, "utf8").catch(() => "")).trim(),
2114
2630
  10
2115
2631
  );
2116
2632
  if (recorded !== stoppedPid || isProcessAlive2(stoppedPid)) return;
@@ -2125,6 +2641,11 @@ async function clearStaleRuntime(stoppedPid) {
2125
2641
  ].map((path) => rm3(path, { force: true }))
2126
2642
  );
2127
2643
  }
2644
+ async function stopDaemonPid(pid) {
2645
+ const stopped = await stopProcessByPid(pid);
2646
+ if (stopped) await clearStaleRuntime(pid);
2647
+ return stopped;
2648
+ }
2128
2649
  async function stopUserDaemon(globals) {
2129
2650
  if (globals.connect) {
2130
2651
  throw new CliError("gezel stop --daemon cannot stop an explicit remote service.");
@@ -2141,9 +2662,7 @@ async function stopUserDaemon(globals) {
2141
2662
  console.log("gezeld is not running");
2142
2663
  return;
2143
2664
  }
2144
- const stopped = await stopProcessByPid(runtime.pid);
2145
- if (stopped) {
2146
- await clearStaleRuntime(runtime.pid);
2665
+ if (await stopDaemonPid(runtime.pid)) {
2147
2666
  console.log(`stopped gezeld pid=${runtime.pid}`);
2148
2667
  } else {
2149
2668
  console.error(`failed to confirm gezeld pid=${runtime.pid} stopped`);
@@ -2168,13 +2687,18 @@ program.command("mode [mode]").description("Show or set AI activity (read-only,
2168
2687
  const current = cliEngagementModeOption(updated.aiEngagementMode);
2169
2688
  console.log(`AI mode \u2192 ${current.name} \u2014 ${current.description}`);
2170
2689
  });
2171
- program.command("run [prompt...]").description("Run a prompt through a gezel and print the reply").option("-g, --gezel <ref>", "gezel id or name (default: this project's voorman)").action(async (promptParts, opts) => {
2172
- const prompt = (promptParts ?? []).join(" ").trim();
2173
- if (!prompt) {
2174
- console.error('usage: gezel run "<prompt>"');
2175
- process.exitCode = 1;
2176
- return;
2177
- }
2690
+ program.command("run [prompt...]").description("Run a prompt through a gezel and print the reply (use - to read stdin)").option("-g, --gezel <ref>", "gezel id or name (default: this project's voorman)").addHelpText(
2691
+ "after",
2692
+ `
2693
+ Examples:
2694
+ gezel run "Summarize this project"
2695
+ printf 'Summarize these notes:\\nThe launch is Friday.\\n' | gezel run -
2696
+ gezel run - < prompt.txt
2697
+
2698
+ A sole - reads UTF-8 stdin to EOF. Empty input is rejected.
2699
+ Replies go to stdout; diagnostics go to stderr.`
2700
+ ).action(async (promptParts, opts) => {
2701
+ const prompt = await resolveRunPrompt(promptParts);
2178
2702
  const previousLogOutput = getLogOutput2();
2179
2703
  setLogOutput2("stderr");
2180
2704
  const previousLogLevel = getLogLevel2();
@@ -2234,7 +2758,19 @@ ${ev.error}`);
2234
2758
  }
2235
2759
  }
2236
2760
  });
2237
- program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").option(
2761
+ program.command("do <craftbook...>").description(
2762
+ "Start a craftbook as a task in the current directory's project; words after its required values are the request"
2763
+ ).addHelpText(
2764
+ "after",
2765
+ `
2766
+ Bare values fill the craftbook's required parameters in order; key=value sets any
2767
+ parameter; every other word is your request, which becomes the task description.
2768
+
2769
+ Examples:
2770
+ gezel do summarize-long "Summarize notes.txt for the board"
2771
+ gezel do ship feature/login --wait
2772
+ gezel do powerpoint-deck "A deck about Delft" audience=investors`
2773
+ ).option(
2238
2774
  "--param <key=value>",
2239
2775
  "named craftbook parameter (repeatable)",
2240
2776
  (value, values) => [...values, value],
@@ -2242,10 +2778,11 @@ program.command("do <craftbook...>").description("Start a craftbook as a task in
2242
2778
  ).option("--wait", "wait for completion; exit nonzero when blocked, canceled, or timed out").option("--timeout <seconds>", "wait budget in seconds; timeout leaves the task running", "7200").option("--json", "emit one JSON result on stdout").option(
2243
2779
  "--strict-sandbox",
2244
2780
  "require OS network isolation for custom scripts (CLI launches otherwise trust this recipe snapshot)"
2245
- ).action(
2781
+ ).addOption(new Option(SHORTHAND_FLAG).hideHelp()).action(
2246
2782
  async (craftbookParts, opts) => {
2247
2783
  const timeoutMs = positiveSeconds(opts.timeout);
2248
- const client = await connectOwned(cliGlobals());
2784
+ const shorthand2 = opts.viaCraftbookShorthand ? await resolveCraftbookShorthand(craftbookParts) : void 0;
2785
+ const client = shorthand2?.client ?? await connectOwned(cliGlobals());
2249
2786
  const projectId = await resolveRunProject(client, cliGlobals());
2250
2787
  const [config, result] = await Promise.all([
2251
2788
  client.getConfig(),
@@ -2255,20 +2792,44 @@ program.command("do <craftbook...>").description("Start a craftbook as a task in
2255
2792
  result.items,
2256
2793
  config.showWorkInProgressFeatures === true
2257
2794
  );
2258
- const { book, args } = resolveCraftbookInvocation(craftbooks, craftbookParts);
2795
+ const shorthandBook = shorthand2 && craftbooks.find((candidate) => candidate.id === shorthand2.id);
2796
+ if (shorthand2 && !shorthandBook) throw new CliError(`craftbook not found: ${shorthand2.id}`);
2797
+ const { book, args } = shorthandBook ? { book: shorthandBook, args: craftbookParts.slice(1) } : resolveCraftbookInvocation(craftbooks, craftbookParts);
2259
2798
  const { craftbook } = await client.getCraftbook(book.id, {
2260
2799
  projectId,
2261
2800
  source: book.source,
2262
2801
  version: book.version
2263
2802
  });
2264
- const craftbookParams = parseCraftbookParams(craftbook, [...args, ...opts.param]);
2803
+ if (shorthand2) {
2804
+ if (craftbook.cliWorkflow)
2805
+ throw new CliError(
2806
+ `${book.id} runs a workflow module from this project's code, so it does not start by name alone. Run it with: gezel do ${book.id}`
2807
+ );
2808
+ process.stderr.write(`${shorthandEcho(book.id, shorthandTail)}
2809
+ `);
2810
+ }
2811
+ const parsed = parseCraftbookArguments(craftbook, args, opts.param);
2812
+ const setUp = () => ensureCraftbookSetup(client, {
2813
+ projectId,
2814
+ label: craftbook.name,
2815
+ needs: craftbook,
2816
+ params: parsed.params,
2817
+ ...craftbook.paramSchema ? { paramSchema: craftbook.paramSchema } : {},
2818
+ prompter: terminalPrompter(),
2819
+ write: (text) => process.stderr.write(text)
2820
+ });
2265
2821
  if (craftbook.cliWorkflow) {
2266
2822
  if (book.source !== "project")
2267
2823
  throw new CliError("CLI workflow craftbooks must belong to this project.");
2824
+ if (parsed.request)
2825
+ throw new CliError(
2826
+ `${craftbook.name} runs a workflow module and takes no request text; pass its parameters as key=value (unused: "${parsed.request}").`
2827
+ );
2268
2828
  if (opts.strictSandbox)
2269
2829
  throw new CliError(
2270
2830
  "CLI workflows execute ordinary repository code and cannot use --strict-sandbox."
2271
2831
  );
2832
+ await setUp();
2272
2833
  const workspace = typeof cliGlobals().project === "string" ? cliGlobals().project : process.cwd();
2273
2834
  console.error(`Running ${craftbook.name}: ${craftbook.cliWorkflow.module}`);
2274
2835
  const result2 = await runWorkflow(
@@ -2280,16 +2841,17 @@ program.command("do <craftbook...>").description("Start a craftbook as a task in
2280
2841
  console.error,
2281
2842
  {
2282
2843
  craftbook,
2283
- params: craftbookParams,
2844
+ params: parsed.params,
2284
2845
  timeoutMs
2285
2846
  }
2286
2847
  );
2287
2848
  printWorkflowResult(result2, opts.json);
2288
2849
  return;
2289
2850
  }
2851
+ await setUp();
2290
2852
  const created = await client.createTask(projectId, {
2291
2853
  ...craftbookStartRequest(book),
2292
- craftbookParams,
2854
+ ...craftbookDoLaunch(craftbook, parsed),
2293
2855
  trustScripts: !opts.strictSandbox,
2294
2856
  roleBasedNameOnlyMode: true
2295
2857
  });
@@ -2538,7 +3100,7 @@ knowledge.command("init <dir>").description("Scaffold a catalog folder (catalog.
2538
3100
  const { runKnowledgeInit } = await loadKnowledgeCommand();
2539
3101
  await runKnowledgeInit(dir);
2540
3102
  });
2541
- 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").option("--skip-images", "Build without image assets, keeping image alt text").action(async (dir, opts) => {
3103
+ 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").option("--skip-images", "Build without image, video or audio assets, keeping their alt text").action(async (dir, opts) => {
2542
3104
  const { runKnowledgeBuild } = await loadKnowledgeCommand();
2543
3105
  await runKnowledgeBuild(dir, opts);
2544
3106
  });
@@ -3046,7 +3608,7 @@ function resolveModelProvider(raw) {
3046
3608
  }
3047
3609
  return raw;
3048
3610
  }
3049
- return resolveOnDeviceProvider(process.platform, process.arch);
3611
+ return resolveOnDeviceProvider2(process.platform, process.arch);
3050
3612
  }
3051
3613
  model.command("concurrency [slots]").description("Show or set local inference slots; use auto to restore automatic sizing").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").option("--json", "Output the slot override as JSON").action(async (slots, opts) => {
3052
3614
  const provider = resolveModelProvider(opts.provider);
@@ -3103,39 +3665,7 @@ model.command("list").description("List local chat models for an engine").option
3103
3665
  model.command("pull <id>").description("Download a local chat model from the catalog (e.g. gemma4-31b-q4)").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").action(async (id, opts) => {
3104
3666
  const client = await connectOwned(cliGlobals());
3105
3667
  const provider = resolveModelProvider(opts.provider);
3106
- let lastPct = -1;
3107
- let pullError;
3108
- const onEvent = (ev) => {
3109
- if (ev.type === "progress") {
3110
- const written = "bytesWrittenAll" in ev ? ev.bytesWrittenAll : ev.bytesWritten;
3111
- const total = "totalBytesAll" in ev ? ev.totalBytesAll : ev.totalBytes ?? 0;
3112
- const pct = total > 0 ? Math.floor(written / total * 100) : 0;
3113
- if (pct !== lastPct) {
3114
- lastPct = pct;
3115
- process.stderr.write(
3116
- `\rpulling ${id} (${provider}): ${String(pct).padStart(3)}% ${(written / 1e9).toFixed(2)}/${(total / 1e9).toFixed(2)} GB`
3117
- );
3118
- }
3119
- } else if (ev.type === "retrying") {
3120
- process.stderr.write(`
3121
- retry ${ev.attempt}/${ev.maxAttempts}: ${ev.reason}
3122
- `);
3123
- } else if (ev.type === "error") {
3124
- pullError = ev.error;
3125
- process.stderr.write("\n");
3126
- } else if (ev.type === "done" && !pullError) {
3127
- process.stderr.write(`\rpulled ${id} (${provider})${" ".repeat(48)}
3128
- `);
3129
- }
3130
- };
3131
- if (provider === "mlx") {
3132
- await client.installMlxModel(id, onEvent);
3133
- } else if (provider === "ds4") {
3134
- await client.installDs4Model(id, onEvent);
3135
- } else {
3136
- await client.installLlamaCppModel(id, onEvent);
3137
- }
3138
- if (pullError) throw new CliError(`pull failed: ${pullError}`);
3668
+ await pullChatModel(client, provider, id, (text) => process.stderr.write(text));
3139
3669
  });
3140
3670
  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) => {
3141
3671
  const client = await connectOwned(cliGlobals());
@@ -3327,7 +3857,9 @@ async function pollStorageJob(client, jobId) {
3327
3857
  }
3328
3858
  }
3329
3859
  program.allowExcessArguments();
3330
- program.parseAsync(process.argv).catch((err) => {
3860
+ var shorthand = craftbookShorthandArgv(process.argv, new Set(builtinCommandNames()));
3861
+ if (shorthand) shorthandTail = shorthand.tail;
3862
+ program.parseAsync(shorthand?.argv ?? process.argv).catch((err) => {
3331
3863
  const friendly = formatCliFailure(err);
3332
3864
  if (friendly !== null) {
3333
3865
  console.error(friendly);