@bendyline/gezel-cli 1.2.3 → 1.2.5

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,617 @@ 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
+ lowBitScoreFactor,
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(
1246
+ "Paste the key, then press Enter (Enter on its own stops here): ",
1247
+ (length) => `Key received (${length} characters, hidden). Press Enter to continue with this key. `
1248
+ )).trim();
1249
+ if (!key) stop(gap);
1250
+ options.write("Checking the key with one Brave search\u2026\n");
1251
+ await saveBraveKey(client, config, key, options.projectId);
1252
+ options.write("Web search: Brave (test search passed)\n");
1253
+ } else {
1254
+ const current = config.webSearch?.provider ?? "wikipedia";
1255
+ const yes = await prompter.confirm(
1256
+ `A Brave Search key is saved, but web search uses ${current === "wikipedia" ? "Wikipedia" : current}. Switch web search to Brave? [y/N] `
1257
+ );
1258
+ if (!yes) stop(gap);
1259
+ await client.updateConfig({ webSearch: { ...config.webSearch, provider: "brave" } });
1260
+ options.write("Web search: Brave\n");
1261
+ }
1262
+ }
1263
+ }
1264
+ const downloads = gaps.filter((gap) => gap.kind === "model");
1265
+ if (downloads.length > 0) {
1266
+ const total = downloads.reduce((sum, gap) => sum + (sizes.get(modelKey(gap)) ?? 0), 0);
1267
+ if (total > 0) {
1268
+ const space = await client.checkModelDownloadSpace({ sizeBytes: total });
1269
+ if (space.known && !space.ok) {
1270
+ throw new CliError(
1271
+ `The models need ${formatGb(space.requiredBytes)} GB, and Gezel model storage has ${formatGb(space.freeBytes)} GB free. Free some space, then run again.`
1272
+ );
1273
+ }
1274
+ }
1275
+ const what = downloads.length === 1 ? "this model" : `these ${downloads.length} models`;
1276
+ const yes = await prompter.confirm(
1277
+ `Download ${what} now? It is a one-time download${total > 0 ? ` of ${formatGb(total)} GB` : ""}. [y/N] `
1278
+ );
1279
+ if (!yes) stop(downloads[0]);
1280
+ await ensureEngines(
1281
+ client,
1282
+ downloads.map((gap) => gap.provider),
1283
+ options.write
1284
+ );
1285
+ for (const gap of downloads) await pullChatModel(client, gap.provider, gap.id, options.write);
1286
+ }
1287
+ const after = craftbookSetupGaps(
1288
+ { services, models },
1289
+ await readSetupState(client, await client.getConfig(), models)
1290
+ );
1291
+ if (after.length > 0) {
1292
+ throw new CliError(
1293
+ [
1294
+ `${options.label} is still not set up:`,
1295
+ ...after.map((gap) => ` \u2022 ${describeGap(gap, sizes)}`)
1296
+ ].join("\n")
1297
+ );
1298
+ }
1299
+ options.write("\n");
1300
+ }
1301
+ function terminalPrompter(terminal = { input: process.stdin, output: process.stderr }) {
1302
+ if (!terminal.input.isTTY || !terminal.output.isTTY) return null;
1303
+ return {
1304
+ confirm: async (question) => {
1305
+ for (; ; ) {
1306
+ const answer = (await ask(terminal, question)).trim().toLowerCase();
1307
+ if (answer === "y" || answer === "yes") return true;
1308
+ if (answer === "" || answer === "n" || answer === "no") return false;
1309
+ terminal.output.write("Please answer y or n.\n");
1310
+ }
1311
+ },
1312
+ secret: (question, filled) => ask(terminal, question, { filled })
1313
+ };
1314
+ }
1315
+ function ask(terminal, question, secret) {
1316
+ const { input, output } = terminal;
1317
+ return import("readline").then(
1318
+ ({ clearScreenDown, createInterface, cursorTo, moveCursor }) => new Promise((resolve6, reject) => {
1319
+ const rl = createInterface({
1320
+ input,
1321
+ output: secret ? new Writable({ write: (_chunk, _encoding, done) => done() }) : output,
1322
+ terminal: true,
1323
+ ...secret ? { historySize: 0 } : {}
1324
+ });
1325
+ let settled = false;
1326
+ const settle = () => {
1327
+ settled = true;
1328
+ input.removeListener("keypress", onKeypress);
1329
+ };
1330
+ let drawn = "";
1331
+ let shownLength = -1;
1332
+ let pending = false;
1333
+ const draw = () => {
1334
+ pending = false;
1335
+ if (settled || !secret) return;
1336
+ const length = rl.line.length;
1337
+ if (length === shownLength) return;
1338
+ shownLength = length;
1339
+ const text = length > 0 && secret.filled ? secret.filled(length) : question;
1340
+ if (drawn) {
1341
+ const rows = Math.floor((drawn.length - 1) / (output.columns || 80));
1342
+ if (rows > 0) moveCursor(output, 0, -rows);
1343
+ cursorTo(output, 0);
1344
+ clearScreenDown(output);
1345
+ }
1346
+ output.write(text);
1347
+ drawn = text;
1348
+ };
1349
+ function onKeypress() {
1350
+ if (pending) return;
1351
+ pending = true;
1352
+ queueMicrotask(draw);
1353
+ }
1354
+ if (secret) input.on("keypress", onKeypress);
1355
+ rl.on("SIGINT", () => {
1356
+ settle();
1357
+ rl.close();
1358
+ output.write("\n");
1359
+ reject(new CliError("Cancelled."));
1360
+ });
1361
+ rl.on("close", () => {
1362
+ if (settled) return;
1363
+ settle();
1364
+ output.write("\n");
1365
+ resolve6("");
1366
+ });
1367
+ rl.question(question, (answer) => {
1368
+ settle();
1369
+ rl.close();
1370
+ if (secret) output.write("\n");
1371
+ resolve6(answer);
1372
+ });
1373
+ draw();
1374
+ })
1375
+ );
1376
+ }
1377
+ function defaultModelEngine(config, platform = process.platform, arch = process.arch) {
1378
+ const configured = config.provider;
1379
+ return configured && isCraftbookModelEngine(configured) ? configured : resolveOnDeviceProvider(platform, arch);
1380
+ }
1381
+ async function readSetupState(client, config, models) {
1382
+ const engines = [...new Set(models.map((model2) => model2.provider))];
1383
+ const installed = await Promise.all(
1384
+ engines.map(async (engine) => {
1385
+ const { models: list } = engine === "mlx" ? await client.listMlxModels() : engine === "ds4" ? await client.listDs4Models() : await client.listLlamaCppModels();
1386
+ return [engine, list.map((model2) => model2.id)];
1387
+ })
1388
+ );
1389
+ return {
1390
+ allowExternalServices: resolveSecurityPolicy2(config).allowExternalServices,
1391
+ ...config.webSearch?.provider ? { webSearchProvider: config.webSearch.provider } : {},
1392
+ hasBraveSearchApiKey: config.hasBraveSearchApiKey === true,
1393
+ installedModels: Object.fromEntries(installed)
1394
+ };
1395
+ }
1396
+ var modelKey = (model2) => `${model2.provider}:${model2.id}`;
1397
+ async function modelSizes(client, gaps) {
1398
+ const sizes = /* @__PURE__ */ new Map();
1399
+ for (const gap of gaps) {
1400
+ if (gap.kind !== "model") continue;
1401
+ let manifest;
1402
+ try {
1403
+ const item = await client.getCatalogItem("chat-model", gap.id);
1404
+ if (item.manifest.kind !== "chat-model") throw new Error("not a chat model");
1405
+ manifest = item.manifest;
1406
+ } catch {
1407
+ throw new CliError(
1408
+ `This run needs the model ${gap.id}, which is not installed and is not in the model catalog. Check the model name.`
1409
+ );
1410
+ }
1411
+ const source = gap.provider === "mlx" ? manifest.mlx : gap.provider === "ds4" ? manifest.ds4 : manifest.llamaCpp;
1412
+ if (!source) {
1413
+ throw new CliError(
1414
+ `This run needs the model ${gap.id} on ${gap.provider}, and the catalog has no ${gap.provider} download for it.`
1415
+ );
1416
+ }
1417
+ sizes.set(modelKey(gap), source.approxSizeBytes);
1418
+ }
1419
+ return sizes;
1420
+ }
1421
+ function describeGap(gap, sizes) {
1422
+ const why = gap.reasons.length > 0 ? ` (${gap.reasons.join("; ")})` : "";
1423
+ switch (gap.kind) {
1424
+ case "external-services":
1425
+ return `External services are off, so gezels cannot reach the web${why}.`;
1426
+ case "web-search":
1427
+ 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}.`;
1428
+ case "model": {
1429
+ const size = sizes.get(modelKey(gap));
1430
+ return `${gap.id} is not downloaded yet (${gap.provider}${size ? `, ${formatGb(size)} GB` : ""})${why}.`;
1431
+ }
1432
+ }
1433
+ }
1434
+ function instructions(gaps) {
1435
+ const out = [];
1436
+ for (const gap of gaps) {
1437
+ if (gap.kind === "external-services") out.push("gezel security external-services on");
1438
+ else if (gap.kind === "web-search")
1439
+ out.push(
1440
+ `gezel secret set braveSearchApiKey --env BRAVE_SEARCH_API_KEY --use-for-search (get a key at ${BRAVE_KEY_URL})`
1441
+ );
1442
+ else out.push(`gezel model pull ${gap.id} --provider ${gap.provider}`);
1443
+ }
1444
+ return out;
1445
+ }
1446
+ async function saveBraveKey(client, config, key, projectId) {
1447
+ try {
1448
+ await client.updateConfig({
1449
+ braveSearchApiKey: key,
1450
+ webSearch: { ...config.webSearch, provider: "brave" }
1451
+ });
1452
+ } catch {
1453
+ throw new CliError("Could not save the key. Check the Gezel service, then run again.");
1454
+ }
1455
+ const failure = await client.toolWebSearch(projectId, SEARCH_CHECK).then(
1456
+ () => void 0,
1457
+ (error) => serviceErrorText(error)
1458
+ );
1459
+ if (failure === void 0) return;
1460
+ await client.updateConfig({ braveSearchApiKey: "", webSearch: { ...config.webSearch } }).catch(() => {
1461
+ });
1462
+ throw new CliError(
1463
+ `A test search with that key failed, so it was not kept: ${failure.replaceAll(key, "\u2026")}
1464
+ Check the key at ${BRAVE_KEY_URL}, then run again.`
1465
+ );
1466
+ }
1467
+ function serviceErrorText(error) {
1468
+ const details = error?.details;
1469
+ if (details && typeof details === "object") {
1470
+ const text = details.error;
1471
+ if (typeof text === "string" && text.trim()) return text.trim();
1472
+ }
1473
+ return error instanceof Error ? error.message : String(error);
1474
+ }
1475
+ async function ensureEngines(client, engines, write) {
1476
+ const status = await client.getNativeEngineStatus();
1477
+ if (!status.pinned || !status.platformKey) return;
1478
+ const missing = [...new Set(engines.map((engine) => ENGINE_BINARY[engine]))].filter(
1479
+ (binary) => !status.engines.some((entry) => entry.name === binary && entry.installed)
1480
+ );
1481
+ if (missing.length === 0) return;
1482
+ await installNativeToolkit(client, { engines: missing, output: { writeProgress: write } });
1483
+ }
1484
+
1485
+ // src/craftbook-shorthand.ts
1486
+ import { existsSync } from "fs";
1487
+ import { readFile as readFile2, readdir } from "fs/promises";
1488
+ import { join as join2 } from "path";
1489
+ import { projectLocalCraftbooksRoot } from "@bendyline/gezel/paths";
1490
+ var SHORTHAND_FLAG = "--via-craftbook-shorthand";
1491
+ var VALUE_OPTIONS = /* @__PURE__ */ new Set(["--connect", "--token", "--home"]);
1492
+ var OPTIONAL_VALUE_OPTIONS = /* @__PURE__ */ new Set(["--project"]);
1493
+ var CRAFTBOOK_WORD = /^[a-z0-9][a-z0-9._-]*$/i;
1494
+ function craftbookShorthandArgv(argv, builtins) {
1495
+ for (let index = 2; index < argv.length; index += 1) {
1496
+ const token = argv[index];
1497
+ if (token === "--") return null;
1498
+ if (token.startsWith("-")) {
1499
+ if (VALUE_OPTIONS.has(token)) index += 1;
1500
+ else if (OPTIONAL_VALUE_OPTIONS.has(token) && !(argv[index + 1] ?? "-").startsWith("-")) {
1501
+ index += 1;
1502
+ }
1503
+ continue;
1504
+ }
1505
+ if (builtins.has(token) || !CRAFTBOOK_WORD.test(token)) return null;
1506
+ return {
1507
+ argv: [...argv.slice(0, index), "do", SHORTHAND_FLAG, ...argv.slice(index)],
1508
+ word: token,
1509
+ tail: argv.slice(index + 1)
1510
+ };
1511
+ }
1512
+ return null;
1513
+ }
1514
+ function craftbookForShorthand(books, word) {
1515
+ const query = word.toLowerCase();
1516
+ return books.find((book) => book.command?.toLowerCase() === query) ?? books.find((book) => book.id.toLowerCase() === query);
1517
+ }
1518
+ async function workspaceCraftbookId(workspaceDir, word) {
1519
+ const root = projectLocalCraftbooksRoot(workspaceDir);
1520
+ if (!existsSync(root)) return void 0;
1521
+ const query = word.toLowerCase();
1522
+ const ids = [];
1523
+ for (const entry of await readdir(root, { withFileTypes: true })) {
1524
+ if (!entry.isDirectory()) continue;
1525
+ const manifest = await readFile2(join2(root, entry.name, "manifest.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
1526
+ if (!manifest) continue;
1527
+ const id = typeof manifest.id === "string" ? manifest.id : entry.name;
1528
+ if (typeof manifest.command === "string" && manifest.command.toLowerCase() === query) return id;
1529
+ ids.push(id);
1530
+ }
1531
+ return ids.find((id) => id.toLowerCase() === query);
1532
+ }
1533
+ function shellWord(token) {
1534
+ return /^[\w@%+=:,./-]+$/.test(token) ? token : `'${token.replaceAll("'", `'\\''`)}'`;
1535
+ }
1536
+ function shorthandEcho(id, tail) {
1537
+ return `\u2192 gezel do ${[id, ...tail].map(shellWord).join(" ")}`;
1538
+ }
1539
+
883
1540
  // src/engagement-mode.ts
884
1541
  var CLI_ENGAGEMENT_MODES = [
885
1542
  {
@@ -932,7 +1589,7 @@ var CLI_ENGAGEMENT_MODE_USAGE = CLI_ENGAGEMENT_MODES.map((option) => option.name
932
1589
  );
933
1590
 
934
1591
  // src/generate.ts
935
- import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
1592
+ import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
936
1593
  import { basename as basename2, dirname as dirname2, resolve as resolve2 } from "path";
937
1594
  async function resolvePromptText(parts, file, label) {
938
1595
  const inline = (parts ?? []).join(" ").trim();
@@ -940,7 +1597,7 @@ async function resolvePromptText(parts, file, label) {
940
1597
  if (inline) throw new CliError(`provide either ${label} text or --file, not both.`);
941
1598
  let raw;
942
1599
  try {
943
- raw = await readFile2(resolve2(file), "utf8");
1600
+ raw = await readFile3(resolve2(file), "utf8");
944
1601
  } catch (err) {
945
1602
  throw new CliError(`could not read --file "${file}": ${err.message}`);
946
1603
  }
@@ -974,7 +1631,7 @@ async function saveArtifact(client, projectId, artifactPath, output) {
974
1631
  }
975
1632
 
976
1633
  // src/knowledge-install.ts
977
- import { existsSync } from "fs";
1634
+ import { existsSync as existsSync2 } from "fs";
978
1635
  import { resolve as resolve3 } from "path";
979
1636
  import { KNOWLEDGE_ID_PATTERN } from "@bendyline/gezel";
980
1637
  var SHA256_PATTERN = /^[0-9a-f]{64}$/i;
@@ -1007,7 +1664,7 @@ function resolveKnowledgeInstallSource(source, expectedSha256, opts = {}) {
1007
1664
  function looksLikeCatalogId(source) {
1008
1665
  if (source.includes("/") || source.includes("\\") || source.endsWith(".gezk")) return false;
1009
1666
  if (!KNOWLEDGE_ID_PATTERN.test(source)) return false;
1010
- return !existsSync(source);
1667
+ return !existsSync2(source);
1011
1668
  }
1012
1669
  function assertCatalogOnlyOptions(opts, kind) {
1013
1670
  if (opts.version)
@@ -1054,35 +1711,8 @@ async function isInstalled(client, engine, id) {
1054
1711
  const { models } = engine === "mlx" ? await client.listMlxModels() : engine === "ds4" ? await client.listDs4Models() : await client.listLlamaCppModels();
1055
1712
  return models.some((model2) => model2.id === id);
1056
1713
  }
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}`);
1714
+ function pull(client, engine, id, output) {
1715
+ return pullChatModel(client, engine, id, (text) => output.writeProgress(text));
1086
1716
  }
1087
1717
  async function exportModelToFile(client, id, options) {
1088
1718
  const { engine, cwd, output, signal } = options;
@@ -1093,220 +1723,95 @@ async function exportModelToFile(client, id, options) {
1093
1723
  if (!await isExistingDirectory(dirname3(target))) {
1094
1724
  throw new CliError(`${dirname3(target)} does not exist.`);
1095
1725
  }
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;
1726
+ let pulled = false;
1727
+ if (!await isInstalled(client, engine, id)) {
1728
+ if (options.skipPull) {
1729
+ throw new CliError(
1730
+ `model "${id}" is not installed for ${engine}. Run \`gezel model pull ${id}\` first, or drop --no-pull.`
1731
+ );
1255
1732
  }
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}
1733
+ await pull(client, engine, id, output);
1734
+ pulled = true;
1735
+ }
1736
+ const name = basename3(target);
1737
+ const partial = `${target}.partial-${randomUUID2()}`;
1738
+ try {
1739
+ output.writeProgress(`preparing ${name}
1265
1740
  `);
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}
1741
+ const response = await client.exportModelBundle(engine, id, signal);
1742
+ const modelBytes = modelBytesFromResponse(response);
1743
+ const bytesWritten = await writeModelBundleResponse(
1744
+ response,
1745
+ partial,
1746
+ ({ bytesCompleted, bytesTotal }) => {
1747
+ output.writeProgress(`\rwriting ${name}: ${progressText(bytesCompleted, bytesTotal)}`);
1748
+ },
1749
+ signal
1750
+ );
1751
+ output.writeProgress(`\rwriting ${name}: ${progressText(bytesWritten, modelBytes)}
1276
1752
  `);
1277
- break;
1278
- }
1279
- };
1280
- try {
1281
- await client.ensureNativeEngine(
1282
- engine,
1283
- onEvent,
1284
- engine === "llama-server" ? llamaVariant : void 0
1753
+ await verifyModelBundleArchive(
1754
+ partial,
1755
+ ({ bytesCompleted, bytesTotal }) => {
1756
+ output.writeProgress(`\rverifying ${name}: ${progressText(bytesCompleted, bytesTotal)}`);
1757
+ },
1758
+ signal
1285
1759
  );
1760
+ output.writeProgress(`\rverifying ${name}: done${" ".repeat(32)}
1761
+ `);
1762
+ signal?.throwIfAborted();
1763
+ await publish(partial, target);
1764
+ return { path: target, bytesWritten, pulled };
1286
1765
  } 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}`);
1766
+ await rm2(partial, { force: true }).catch(() => {
1767
+ });
1768
+ throw error;
1295
1769
  }
1296
1770
  }
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)}`;
1771
+ async function publish(partial, target) {
1772
+ const backup = `${target}.backup-${randomUUID2()}`;
1773
+ const backedUp = await isExistingFile(target);
1774
+ if (backedUp) await rename(target, backup);
1775
+ try {
1776
+ await rename(partial, target);
1777
+ } catch (error) {
1778
+ if (backedUp) await rename(backup, target).catch(() => {
1779
+ });
1780
+ throw error;
1781
+ }
1782
+ if (backedUp) await rm2(backup, { force: true }).catch(() => {
1783
+ });
1301
1784
  }
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`;
1785
+ function progressText(bytesCompleted, bytesTotal) {
1786
+ if (!bytesTotal) return `${formatGb(bytesCompleted)} GB`;
1787
+ const pct = Math.floor(bytesCompleted / bytesTotal * 100);
1788
+ return `${String(pct).padStart(3)}% ${formatGb(bytesCompleted)}/${formatGb(bytesTotal)} GB`;
1307
1789
  }
1308
- function errorMessage(error) {
1309
- return error instanceof Error ? error.message : String(error);
1790
+
1791
+ // src/run-prompt.ts
1792
+ async function resolveRunPrompt(parts, input = process.stdin) {
1793
+ if (parts?.length !== 1 || parts[0] !== "-") {
1794
+ const prompt2 = (parts ?? []).join(" ").trim();
1795
+ if (!prompt2) throw new CliError('usage: gezel run "<prompt>" or gezel run -');
1796
+ return prompt2;
1797
+ }
1798
+ if (input.isTTY) {
1799
+ throw new CliError("gezel run - requires piped input or a redirected file.");
1800
+ }
1801
+ const chunks = [];
1802
+ try {
1803
+ for await (const chunk of input) {
1804
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1805
+ }
1806
+ } catch (error) {
1807
+ throw new CliError(
1808
+ `Could not read prompt from stdin: ${error instanceof Error ? error.message : String(error)}`
1809
+ );
1810
+ }
1811
+ const prompt = Buffer.concat(chunks).toString("utf8");
1812
+ if (!prompt.trim())
1813
+ throw new CliError("gezel run - received empty input. Supply a prompt on stdin.");
1814
+ return prompt;
1310
1815
  }
1311
1816
 
1312
1817
  // src/run-readiness.ts
@@ -1492,43 +1997,6 @@ function registerSecretCommands(program2, connect, output = console.log) {
1492
1997
  });
1493
1998
  }
1494
1999
 
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
2000
  // src/storage-format.ts
1533
2001
  function formatBytes2(bytes) {
1534
2002
  if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
@@ -1664,6 +2132,7 @@ function formatBackupPlan(plan) {
1664
2132
  gezel: "gezels",
1665
2133
  project: "projects",
1666
2134
  "document-root": "documents",
2135
+ "memory-root": "memories about you",
1667
2136
  "settings-file": "settings files"
1668
2137
  };
1669
2138
  for (const [kind, bucket] of byKind) {
@@ -1756,7 +2225,7 @@ function editDistance(a, b) {
1756
2225
  }
1757
2226
 
1758
2227
  // src/workflow-command.ts
1759
- import { realpath } from "fs/promises";
2228
+ import { realpath as realpath2 } from "fs/promises";
1760
2229
  import { isAbsolute as isAbsolute2, relative, resolve as resolve5 } from "path";
1761
2230
  import { pathToFileURL } from "url";
1762
2231
  import {
@@ -1774,9 +2243,9 @@ function validateWorkflowCraftbook(document) {
1774
2243
  }
1775
2244
  async function runWorkflow(client, projectId, workspace, file, args, log = console.error, invocation) {
1776
2245
  const named = /^[a-z][a-z0-9-]*$/.test(file);
1777
- const path = await realpath(resolve5(workspace, named ? `.gezel/workflows/${file}.mjs` : file));
2246
+ const path = await realpath2(resolve5(workspace, named ? `.gezel/workflows/${file}.mjs` : file));
1778
2247
  if (invocation) {
1779
- const local = relative(await realpath(workspace), path);
2248
+ const local = relative(await realpath2(workspace), path);
1780
2249
  if (isAbsolute2(local) || local === ".." || local.startsWith("../") || local.startsWith("..\\")) {
1781
2250
  throw new CliError("A craftbook workflow module must remain inside its project workspace.");
1782
2251
  }
@@ -1784,6 +2253,15 @@ async function runWorkflow(client, projectId, workspace, file, args, log = conso
1784
2253
  const module = await import(pathToFileURL(path).href);
1785
2254
  if (typeof module.run !== "function")
1786
2255
  throw new CliError(`workflow ${path} must export an async run(context) function`);
2256
+ const ensureSetup = (needs, book = invocation?.craftbook, params = invocation?.params) => ensureCraftbookSetup(client, {
2257
+ projectId,
2258
+ label: book?.name ?? "This workflow",
2259
+ needs,
2260
+ ...params ? { params } : {},
2261
+ ...book?.paramSchema ? { paramSchema: book.paramSchema } : {},
2262
+ prompter: terminalPrompter(),
2263
+ write: (text) => process.stderr.write(text)
2264
+ });
1787
2265
  return module.run({
1788
2266
  client,
1789
2267
  projectId,
@@ -1795,41 +2273,66 @@ async function runWorkflow(client, projectId, workspace, file, args, log = conso
1795
2273
  // A bounded model call whose input the driver already holds. Cheaper and
1796
2274
  // more reliable than a task that must read its input back through tools.
1797
2275
  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 } : {}
2276
+ // Needs the module computes at run time (models chosen by its own
2277
+ // options): asked for at a terminal, otherwise a CliError naming the fix.
2278
+ ensureSetup: (needs) => ensureSetup(needs),
2279
+ runCraftbook: Object.assign(
2280
+ async (id, params, options = {}) => {
2281
+ let ref = options.taskRef;
2282
+ if (!ref) {
2283
+ let book;
2284
+ try {
2285
+ ({ craftbook: book } = await client.getCraftbook(id, { projectId, source: "project" }));
2286
+ } catch (error) {
2287
+ if (error instanceof Error) {
2288
+ Object.assign(error, {
2289
+ taskCreation: { attempted: false, phase: "craftbook-read" }
2290
+ });
2291
+ }
2292
+ throw error;
2293
+ }
2294
+ const { params: parsed } = parseCraftbookArguments(
2295
+ book,
2296
+ [],
2297
+ Object.entries(params).map(([key, value]) => `${key}=${value}`)
2298
+ );
2299
+ await ensureSetup(book, book, parsed);
2300
+ const body = {
2301
+ title: options.title ?? book.name,
2302
+ description: `Run the project craftbook ${book.name}. Follow every step and satisfy its required outcomes before completing this task.`,
2303
+ craftbookId: id,
2304
+ craftbookSourceId: "project",
2305
+ craftbookVersion: book.version,
2306
+ craftbookParams: parsed,
2307
+ dispatchEntry: true,
2308
+ roleBasedNameOnlyMode: true,
2309
+ trustScripts: true,
2310
+ ...options.parentTaskRef ? { parentTaskRef: options.parentTaskRef } : {}
2311
+ };
2312
+ const task2 = options.creationKey ? await client.createWorkflowTask(projectId, {
2313
+ ...body,
2314
+ workflowInvocationKey: options.creationKey
2315
+ }) : await client.createTask(projectId, body);
2316
+ await options.onCreated?.(task2);
2317
+ ref = task2.ref;
2318
+ }
2319
+ log(`Following ${ref}`);
2320
+ return waitForTask(client, ref, {
2321
+ timeoutMs: options.timeoutMs ?? invocation?.timeoutMs ?? 72e5,
2322
+ onProgress: (task2) => log(`${task2.ref}: ${task2.status} (${task2.activeStepId ?? "finished"})`)
1817
2323
  });
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
- }
2324
+ },
2325
+ { supportsIdempotentCreation: true }
2326
+ )
1827
2327
  });
1828
2328
  }
1829
2329
 
1830
2330
  // src/bin/gezel.ts
1831
2331
  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(
2332
+ program.name("gezel").description("Gezel \u2014 assemble a team of AI companions (gezels) and put them to work.").addHelpText(
2333
+ "after",
2334
+ "\nAny craftbook also runs by name: `gezel <craftbook> \u2026` is `gezel do <craftbook> \u2026`."
2335
+ ).version(GEZEL_VERSION).option(
1833
2336
  "--connect <url>",
1834
2337
  "Connect to this Gezel service (first use asks for approval in the Gezel app)."
1835
2338
  ).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 +2351,35 @@ program.hook("preAction", () => {
1848
2351
  if (globals.http1) process.env.GEZEL_HTTP_VERSION = "1.1";
1849
2352
  applyHome(globals);
1850
2353
  });
2354
+ function builtinCommandNames() {
2355
+ return ["help", ...program.commands.flatMap((command) => [command.name(), ...command.aliases()])];
2356
+ }
2357
+ var shorthandTail = [];
2358
+ async function resolveCraftbookShorthand(parts) {
2359
+ const word = parts[0] ?? "";
2360
+ const unknown = unknownCommandMessage(parts, builtinCommandNames());
2361
+ let client;
2362
+ let id;
2363
+ try {
2364
+ client = await connectOwned(cliGlobals());
2365
+ const preview = await previewRunProject(client, cliGlobals());
2366
+ const [config, items] = await Promise.all([
2367
+ client.getConfig(),
2368
+ preview.projectId ? client.listProjectCraftbooks(preview.projectId).then((result) => result.items) : client.listCatalogItems("craftbook-template").then((result) => result.items)
2369
+ ]);
2370
+ const books = normalizeCraftbooks(items, config.showWorkInProgressFeatures === true);
2371
+ id = craftbookForShorthand(books, word)?.id ?? (preview.projectId === null ? await workspaceCraftbookId(preview.root, word) : void 0);
2372
+ } catch (err) {
2373
+ const reason = formatCliFailure(err) ?? (err instanceof Error ? err.message : String(err));
2374
+ throw new CliError(`${unknown}
2375
+ (Could not look for a craftbook named '${word}': ${reason})`);
2376
+ }
2377
+ if (!id) throw new CliError(unknown);
2378
+ return { client, id };
2379
+ }
1851
2380
  program.action(async () => {
1852
2381
  if (program.args.length > 0) {
1853
- const known = program.commands.flatMap((command) => [command.name(), ...command.aliases()]);
1854
- throw new CliError(unknownCommandMessage(program.args, known));
2382
+ throw new CliError(unknownCommandMessage(program.args, builtinCommandNames()));
1855
2383
  }
1856
2384
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
1857
2385
  throw new CliError(
@@ -1884,79 +2412,106 @@ program.action(async () => {
1884
2412
  });
1885
2413
  program.command("start").description("Start the Gezel daemon (no-op if already running)").option(
1886
2414
  "--port <port>",
1887
- "Bind to a specific port (spawns a fresh daemon, does not adopt a running one)"
2415
+ "Bind to a specific port (reuses a daemon already on it; see --restart for one that is not)"
1888
2416
  ).option(
1889
2417
  "--foreground",
1890
2418
  "Run the daemon attached to this terminal \u2014 stdio streams to this shell, Ctrl+C stops it. Useful for development and CI."
1891
2419
  ).option(
1892
2420
  "--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;
2421
+ "Serve the web UI over HTTP on loopback and print a one-time browser URL (reuses a daemon already serving it)."
2422
+ ).option("--open", "With --web, open the printed URL in your default browser.").option(
2423
+ "--restart",
2424
+ "With --web or --port, stop a running daemon started without them and start a new one."
2425
+ ).action(
2426
+ async (opts) => {
2427
+ const port = opts.port ? Number.parseInt(opts.port, 10) : void 0;
2428
+ if (port !== void 0 && !Number.isFinite(port)) {
2429
+ console.error(`invalid --port: ${opts.port}`);
2430
+ process.exitCode = 1;
2431
+ return;
2432
+ }
2433
+ const userEnv = { ...process.env };
2434
+ delete userEnv.GEZEL_SERVICE_ROLE;
2435
+ delete userEnv.GEZEL_SYSTEM_SCOPE;
2436
+ delete userEnv.GEZEL_PORT;
2437
+ const spawnEnv = {
2438
+ ...userEnv,
2439
+ GEZEL_SERVICE_ROLE: "user"
2440
+ };
2441
+ const portEnv = resolveStartPortEnv(port, await shouldPreferCanonicalPort());
2442
+ if (portEnv !== void 0) spawnEnv.GEZEL_PORT = portEnv;
2443
+ if (opts.web) {
2444
+ spawnEnv.GEZEL_WEB = "1";
2445
+ spawnEnv.GEZEL_INSECURE_TRANSPORT = "1";
2446
+ }
2447
+ if (opts.foreground) {
2448
+ await startForeground(spawnEnv);
2449
+ return;
2450
+ }
2451
+ if (port !== void 0 || opts.web) {
2452
+ const runtime = await readRuntime2();
2453
+ const running = runtime && isProcessAlive2(runtime.pid) ? runtime : null;
2454
+ const reuse = running !== null && await runtimeServes(running, { port, web: opts.web === true });
2455
+ if (running && !reuse) {
2456
+ const wanted = opts.web ? "with the web UI" : `on port ${port}`;
2457
+ if (!opts.restart) {
2458
+ const retry = ["gezel start", ...port !== void 0 ? [`--port ${port}`] : []];
2459
+ if (opts.web) retry.push("--web");
2460
+ throw new CliError(
2461
+ `gezeld is already running for this home ${opts.web ? "without the web UI" : `on port ${running.port}`} (pid ${running.pid}).
2462
+ Restart it ${wanted} with \`${[...retry, "--restart"].join(" ")}\`, or stop it first with \`gezel stop --daemon\`.`
2463
+ );
2464
+ }
2465
+ console.error(`Restarting gezeld (pid ${running.pid}) ${wanted}\u2026`);
2466
+ if (!await stopDaemonPid(running.pid)) {
2467
+ throw new CliError(`failed to confirm gezeld pid=${running.pid} stopped`);
2468
+ }
2469
+ }
2470
+ const entry = resolveDaemonEntry2(import.meta.url);
2471
+ const result = await discoverOrSpawn2({
2472
+ daemonEntry: entry,
2473
+ detached: true,
2474
+ env: spawnEnv,
2475
+ // Never adopt a daemon that lacks the requested port or transport.
2476
+ // A forced spawn accepts only its own process, so losing a race
2477
+ // fails here instead of reporting someone else's daemon.
2478
+ forceSpawn: !reuse,
2479
+ // A cold first boot (fresh home: layout + default gezels +
2480
+ // native probe + catalog) routinely exceeds the 5s default, so
2481
+ // the spawn would time out while the daemon is still coming up —
2482
+ // and in --web mode the user would never see their URL. Give it
2483
+ // real headroom.
2484
+ timeoutMs: 2e4
2485
+ });
2486
+ const health2 = await result.client.health();
2487
+ console.log(
2488
+ `gezeld running (version ${health2.version}) on port ${new URL(result.baseUrl).port}`
2489
+ );
2490
+ if (opts.web) await printWebUrl(result.baseUrl, opts.open === true);
2491
+ return;
2492
+ }
2493
+ const client = await connectOwned(cliGlobals(), { announceSpawn: false });
2494
+ const health = await client.health();
2495
+ console.log(`gezeld running (version ${health.version})`);
1942
2496
  }
1943
- const client = await connectOwned(cliGlobals(), { announceSpawn: false });
1944
- const health = await client.health();
1945
- console.log(`gezeld running (version ${health.version})`);
1946
- });
2497
+ );
2498
+ async function runtimeServes(runtime, want) {
2499
+ if (want.port !== void 0 && runtime.port !== want.port) return false;
2500
+ if (!want.web) return true;
2501
+ if (new URL(runtime.baseUrl).protocol !== "http:") return false;
2502
+ const { readFile: readFile4 } = await import("fs/promises");
2503
+ const { gezelPaths: gezelPaths2 } = await import("@bendyline/gezel/paths");
2504
+ const token = await readFile4(gezelPaths2().runtime.webUiToken, "utf8").catch(() => "");
2505
+ return token.trim().length > 0;
2506
+ }
1947
2507
  async function printWebUrl(baseUrl, open) {
1948
- const { readFile: readFile3 } = await import("fs/promises");
2508
+ const { readFile: readFile4 } = await import("fs/promises");
1949
2509
  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
- }
2510
+ const token = (await readFile4(gezelPaths2().runtime.webUiToken, "utf8").catch(() => "")).trim();
1957
2511
  if (!token) {
1958
- console.error("web UI: the web-ui token file was empty.");
1959
- return;
2512
+ throw new CliError(
2513
+ "gezeld is running, but it published no web UI token, so there is no browser URL to print. Run `gezel start --web --restart`."
2514
+ );
1960
2515
  }
1961
2516
  const url = `${new URL(baseUrl).origin}/?token=${encodeURIComponent(token)}`;
1962
2517
  console.log("");
@@ -2106,11 +2661,11 @@ program.command("stop").description(
2106
2661
  }
2107
2662
  });
2108
2663
  async function clearStaleRuntime(stoppedPid) {
2109
- const { readFile: readFile3, rm: rm3 } = await import("fs/promises");
2664
+ const { readFile: readFile4, rm: rm3 } = await import("fs/promises");
2110
2665
  const { gezelPaths: gezelPaths2 } = await import("@bendyline/gezel/paths");
2111
2666
  const runtime = gezelPaths2().runtime;
2112
2667
  const recorded = Number.parseInt(
2113
- (await readFile3(runtime.pid, "utf8").catch(() => "")).trim(),
2668
+ (await readFile4(runtime.pid, "utf8").catch(() => "")).trim(),
2114
2669
  10
2115
2670
  );
2116
2671
  if (recorded !== stoppedPid || isProcessAlive2(stoppedPid)) return;
@@ -2125,6 +2680,11 @@ async function clearStaleRuntime(stoppedPid) {
2125
2680
  ].map((path) => rm3(path, { force: true }))
2126
2681
  );
2127
2682
  }
2683
+ async function stopDaemonPid(pid) {
2684
+ const stopped = await stopProcessByPid(pid);
2685
+ if (stopped) await clearStaleRuntime(pid);
2686
+ return stopped;
2687
+ }
2128
2688
  async function stopUserDaemon(globals) {
2129
2689
  if (globals.connect) {
2130
2690
  throw new CliError("gezel stop --daemon cannot stop an explicit remote service.");
@@ -2141,9 +2701,7 @@ async function stopUserDaemon(globals) {
2141
2701
  console.log("gezeld is not running");
2142
2702
  return;
2143
2703
  }
2144
- const stopped = await stopProcessByPid(runtime.pid);
2145
- if (stopped) {
2146
- await clearStaleRuntime(runtime.pid);
2704
+ if (await stopDaemonPid(runtime.pid)) {
2147
2705
  console.log(`stopped gezeld pid=${runtime.pid}`);
2148
2706
  } else {
2149
2707
  console.error(`failed to confirm gezeld pid=${runtime.pid} stopped`);
@@ -2168,13 +2726,18 @@ program.command("mode [mode]").description("Show or set AI activity (read-only,
2168
2726
  const current = cliEngagementModeOption(updated.aiEngagementMode);
2169
2727
  console.log(`AI mode \u2192 ${current.name} \u2014 ${current.description}`);
2170
2728
  });
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
- }
2729
+ 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(
2730
+ "after",
2731
+ `
2732
+ Examples:
2733
+ gezel run "Summarize this project"
2734
+ printf 'Summarize these notes:\\nThe launch is Friday.\\n' | gezel run -
2735
+ gezel run - < prompt.txt
2736
+
2737
+ A sole - reads UTF-8 stdin to EOF. Empty input is rejected.
2738
+ Replies go to stdout; diagnostics go to stderr.`
2739
+ ).action(async (promptParts, opts) => {
2740
+ const prompt = await resolveRunPrompt(promptParts);
2178
2741
  const previousLogOutput = getLogOutput2();
2179
2742
  setLogOutput2("stderr");
2180
2743
  const previousLogLevel = getLogLevel2();
@@ -2234,7 +2797,19 @@ ${ev.error}`);
2234
2797
  }
2235
2798
  }
2236
2799
  });
2237
- program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").option(
2800
+ program.command("do <craftbook...>").description(
2801
+ "Start a craftbook as a task in the current directory's project; words after its required values are the request"
2802
+ ).addHelpText(
2803
+ "after",
2804
+ `
2805
+ Bare values fill the craftbook's required parameters in order; key=value sets any
2806
+ parameter; every other word is your request, which becomes the task description.
2807
+
2808
+ Examples:
2809
+ gezel do summarize-long "Summarize notes.txt for the board"
2810
+ gezel do ship feature/login --wait
2811
+ gezel do powerpoint-deck "A deck about Delft" audience=investors`
2812
+ ).option(
2238
2813
  "--param <key=value>",
2239
2814
  "named craftbook parameter (repeatable)",
2240
2815
  (value, values) => [...values, value],
@@ -2242,10 +2817,11 @@ program.command("do <craftbook...>").description("Start a craftbook as a task in
2242
2817
  ).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
2818
  "--strict-sandbox",
2244
2819
  "require OS network isolation for custom scripts (CLI launches otherwise trust this recipe snapshot)"
2245
- ).action(
2820
+ ).addOption(new Option(SHORTHAND_FLAG).hideHelp()).action(
2246
2821
  async (craftbookParts, opts) => {
2247
2822
  const timeoutMs = positiveSeconds(opts.timeout);
2248
- const client = await connectOwned(cliGlobals());
2823
+ const shorthand2 = opts.viaCraftbookShorthand ? await resolveCraftbookShorthand(craftbookParts) : void 0;
2824
+ const client = shorthand2?.client ?? await connectOwned(cliGlobals());
2249
2825
  const projectId = await resolveRunProject(client, cliGlobals());
2250
2826
  const [config, result] = await Promise.all([
2251
2827
  client.getConfig(),
@@ -2255,20 +2831,44 @@ program.command("do <craftbook...>").description("Start a craftbook as a task in
2255
2831
  result.items,
2256
2832
  config.showWorkInProgressFeatures === true
2257
2833
  );
2258
- const { book, args } = resolveCraftbookInvocation(craftbooks, craftbookParts);
2834
+ const shorthandBook = shorthand2 && craftbooks.find((candidate) => candidate.id === shorthand2.id);
2835
+ if (shorthand2 && !shorthandBook) throw new CliError(`craftbook not found: ${shorthand2.id}`);
2836
+ const { book, args } = shorthandBook ? { book: shorthandBook, args: craftbookParts.slice(1) } : resolveCraftbookInvocation(craftbooks, craftbookParts);
2259
2837
  const { craftbook } = await client.getCraftbook(book.id, {
2260
2838
  projectId,
2261
2839
  source: book.source,
2262
2840
  version: book.version
2263
2841
  });
2264
- const craftbookParams = parseCraftbookParams(craftbook, [...args, ...opts.param]);
2842
+ if (shorthand2) {
2843
+ if (craftbook.cliWorkflow)
2844
+ throw new CliError(
2845
+ `${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}`
2846
+ );
2847
+ process.stderr.write(`${shorthandEcho(book.id, shorthandTail)}
2848
+ `);
2849
+ }
2850
+ const parsed = parseCraftbookArguments(craftbook, args, opts.param);
2851
+ const setUp = () => ensureCraftbookSetup(client, {
2852
+ projectId,
2853
+ label: craftbook.name,
2854
+ needs: craftbook,
2855
+ params: parsed.params,
2856
+ ...craftbook.paramSchema ? { paramSchema: craftbook.paramSchema } : {},
2857
+ prompter: terminalPrompter(),
2858
+ write: (text) => process.stderr.write(text)
2859
+ });
2265
2860
  if (craftbook.cliWorkflow) {
2266
2861
  if (book.source !== "project")
2267
2862
  throw new CliError("CLI workflow craftbooks must belong to this project.");
2863
+ if (parsed.request)
2864
+ throw new CliError(
2865
+ `${craftbook.name} runs a workflow module and takes no request text; pass its parameters as key=value (unused: "${parsed.request}").`
2866
+ );
2268
2867
  if (opts.strictSandbox)
2269
2868
  throw new CliError(
2270
2869
  "CLI workflows execute ordinary repository code and cannot use --strict-sandbox."
2271
2870
  );
2871
+ await setUp();
2272
2872
  const workspace = typeof cliGlobals().project === "string" ? cliGlobals().project : process.cwd();
2273
2873
  console.error(`Running ${craftbook.name}: ${craftbook.cliWorkflow.module}`);
2274
2874
  const result2 = await runWorkflow(
@@ -2280,16 +2880,17 @@ program.command("do <craftbook...>").description("Start a craftbook as a task in
2280
2880
  console.error,
2281
2881
  {
2282
2882
  craftbook,
2283
- params: craftbookParams,
2883
+ params: parsed.params,
2284
2884
  timeoutMs
2285
2885
  }
2286
2886
  );
2287
2887
  printWorkflowResult(result2, opts.json);
2288
2888
  return;
2289
2889
  }
2890
+ await setUp();
2290
2891
  const created = await client.createTask(projectId, {
2291
2892
  ...craftbookStartRequest(book),
2292
- craftbookParams,
2893
+ ...craftbookDoLaunch(craftbook, parsed),
2293
2894
  trustScripts: !opts.strictSandbox,
2294
2895
  roleBasedNameOnlyMode: true
2295
2896
  });
@@ -2538,7 +3139,7 @@ knowledge.command("init <dir>").description("Scaffold a catalog folder (catalog.
2538
3139
  const { runKnowledgeInit } = await loadKnowledgeCommand();
2539
3140
  await runKnowledgeInit(dir);
2540
3141
  });
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) => {
3142
+ 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
3143
  const { runKnowledgeBuild } = await loadKnowledgeCommand();
2543
3144
  await runKnowledgeBuild(dir, opts);
2544
3145
  });
@@ -3046,7 +3647,7 @@ function resolveModelProvider(raw) {
3046
3647
  }
3047
3648
  return raw;
3048
3649
  }
3049
- return resolveOnDeviceProvider(process.platform, process.arch);
3650
+ return resolveOnDeviceProvider2(process.platform, process.arch);
3050
3651
  }
3051
3652
  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
3653
  const provider = resolveModelProvider(opts.provider);
@@ -3103,39 +3704,7 @@ model.command("list").description("List local chat models for an engine").option
3103
3704
  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
3705
  const client = await connectOwned(cliGlobals());
3105
3706
  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}`);
3707
+ await pullChatModel(client, provider, id, (text) => process.stderr.write(text));
3139
3708
  });
3140
3709
  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
3710
  const client = await connectOwned(cliGlobals());
@@ -3327,7 +3896,9 @@ async function pollStorageJob(client, jobId) {
3327
3896
  }
3328
3897
  }
3329
3898
  program.allowExcessArguments();
3330
- program.parseAsync(process.argv).catch((err) => {
3899
+ var shorthand = craftbookShorthandArgv(process.argv, new Set(builtinCommandNames()));
3900
+ if (shorthand) shorthandTail = shorthand.tail;
3901
+ program.parseAsync(shorthand?.argv ?? process.argv).catch((err) => {
3331
3902
  const friendly = formatCliFailure(err);
3332
3903
  if (friendly !== null) {
3333
3904
  console.error(friendly);