@bendyline/gezel-cli 1.1.0 → 1.1.2

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.
package/README.md CHANGED
@@ -89,6 +89,121 @@ gezel --home /path/to/another-home # standalone with an alternate home
89
89
  An explicit `--port 6228` remains available when you intentionally want a
90
90
  CLI-owned daemon on the canonical port.
91
91
 
92
+ ## Provider credentials
93
+
94
+ Manage provider keys through the service credential store, using stdin or an
95
+ existing environment variable so the value does not appear in command arguments:
96
+
97
+ ```bash
98
+ gezel secret list
99
+ gezel secret set braveSearchApiKey --env BRAVE_SEARCH_API_KEY --use-for-search
100
+ gezel secret set openaiApiKey --stdin < /path/to/private-key-file
101
+ gezel secret remove openaiApiKey
102
+ ```
103
+
104
+ `--use-for-search` also selects Brave (or Tavily for `tavilyApiKey`) as the
105
+ search provider while preserving its other settings. Without it, setting a
106
+ credential leaves provider selection unchanged. `secret list` gives the supported
107
+ names and whether each is configured; credentials are write-only and never
108
+ printed. All three commands support `--json`, and honor `--home` / `--connect`.
109
+ This covers the built-in provider credentials, including webhooks; it is not an
110
+ arbitrary environment-variable store. Storage uses the same native keyring or
111
+ encrypted fallback as the application.
112
+
113
+ Search also requires the selected environment to allow external services.
114
+ `gezel security external-services` shows that setting; append `on` or `off` to
115
+ change it explicitly while preserving all other security capabilities. This
116
+ permission covers model-initiated external services, including web search.
117
+ Saving a credential does not silently enable it.
118
+
119
+ `gezel model context <id> 65536` sets a local model's context window for its next
120
+ launch; omit the token count to inspect it, or use `auto` to clear the override.
121
+ Use `--provider llama-cpp|mlx|ds4` to select an engine (defaults to the platform's
122
+ local engine). This can bound memory use for unattended batch tasks.
123
+
124
+ `gezel model concurrency 1` limits the local engine to one inference slot and
125
+ reduces its context-cache reservation. This is useful for serial batches with
126
+ large models. It preserves other providers' limits; `--provider` selects an
127
+ engine, and `auto` restores automatic sizing. Omit the value to inspect it.
128
+
129
+ `gezel env indexing off` disables optional background workspace indexing in
130
+ the current directory's project (or `--project` target). Artifact-driven batch
131
+ workflows over large generated datasets can use this to avoid unnecessary
132
+ indexing. `on` restores it; omitting the value reports its current state.
133
+ Both settings commands support `--json` and the ordinary connection/home flags.
134
+
135
+ ## Batch craftbooks and repository workflows
136
+
137
+ `do` accepts positional parameters in the recipe's `paramSchema.properties`
138
+ order, `key=value` arguments, and repeatable `--param key=value` options:
139
+
140
+ ```bash
141
+ gezel do story-batch c23n limit=3 --wait --json
142
+ gezel task wait my-project/12 --timeout 7200 --json
143
+ gezel task resume my-project/12 --json
144
+ gezel task notes my-project/12 --warnings --json
145
+ ```
146
+
147
+ Only explicit values are sent; the service resolves defaults such as
148
+ `{{task.dir}}` after allocating the task. Waiting exits with 0 for completion,
149
+ 1 for cancellation, 2 for a paused task or pending user question, and 3 for a
150
+ timeout. A timeout leaves the daemon task running. Progress goes to stderr;
151
+ `--json` emits the result on stdout. `resume` retries a paused task using its
152
+ saved recipe. Answer pending questions in Gezel before waiting again.
153
+
154
+ For deterministic orchestration around several craftbooks, create
155
+ `.gezel/workflows/storyify.mjs`:
156
+
157
+ ```js
158
+ export async function run({ client, projectId, workspace, args, log, runCraftbook }) {
159
+ const [region] = args;
160
+ log(`Working on ${region} in ${workspace}`);
161
+ return runCraftbook('story-batch', { region });
162
+ }
163
+ ```
164
+
165
+ Run it with `gezel workflow storyify c23n --json`. The module receives the
166
+ public `GezelClient`, the directory's project id, its absolute workspace,
167
+ arguments, a stderr logger, and `runCraftbook(id, params, options)`. That helper
168
+ starts a **project** craftbook and waits; options include `timeoutMs`, a saved
169
+ `taskRef` to follow, `parentTaskRef` to link the child to its batch, and
170
+ `onCreated(task)` to checkpoint the new reference.
171
+ For drivers that generate craftbook documents, `validateCraftbook(document)`
172
+ checks the same schema and step contracts as the daemon and returns the runtime
173
+ craftbook. Call it before installing files or freezing a batch checkpoint;
174
+ invalid documents throw actionable authoring errors without creating a task.
175
+ Returning an object with `exitCode` sets the shell exit status. Module paths
176
+ also work: `gezel workflow ./pipeline/storyify.mjs c23n`.
177
+
178
+ To expose that driver as one command, add
179
+ `"cliWorkflow": { "module": ".gezel/workflows/storyify.mjs" }` to a project
180
+ craftbook and declare its inputs in `paramSchema`. Then run
181
+ `gezel do my-batch c23n limit=200 --json`. Its module receives `craftbook` and
182
+ validated explicit `params` in addition to the context above. The driver owns
183
+ parent creation, defaults, checkpoints, bounded child concurrency, and the
184
+ final result. Modules must resolve inside the project workspace. Only project
185
+ craftbooks can use this entry point; `--strict-sandbox` rejects it.
186
+
187
+ These drivers run in the foreground even without `--wait`; keep the terminal
188
+ open until completion. A timeout applies to each child wait. If the CLI exits,
189
+ already-created daemon tasks survive, but further orchestration requires the
190
+ workflow's resume command. `gezel task wait` observes a parent and its children;
191
+ it does not restart a repository driver.
192
+
193
+ Project recipes live in `.gezel/craftbooks/<id>/manifest.json` (identity) and
194
+ `versions/<version>/craftbook.json` (the complete recipe, including embedded
195
+ scripts). Legacy version manifests plus `scripts/*.ts` remain supported.
196
+ Changing a recipe affects new tasks; running tasks retain their snapshots.
197
+
198
+ CLI craftbook launches, including TUI `/do`, authorize the exact embedded
199
+ script contents in that task snapshot. On Windows and other platforms without
200
+ an enforceable OS network boundary, those scripts use best-effort network
201
+ isolation. Declared capabilities and project/security policies still apply.
202
+ Use `gezel do ... --strict-sandbox` to require the OS boundary instead. Edited
203
+ scripts do not inherit the old source's trust, and a model session cannot
204
+ grant trust. Workflow modules themselves run as ordinary local Node code,
205
+ with the invoking user's permissions, like an npm script.
206
+
92
207
  ## What you get with no further setup
93
208
 
94
209
  The CLI does not bundle model weights or native inference engines; those are
@@ -145,6 +260,10 @@ Run `gezel --help` for the full list. The most-used ones:
145
260
  | `gezel` | Launch the interactive TUI |
146
261
  | `gezel run [prompt…]` | One-shot prompt in the current directory's project, using its voorman by default; optionally `--gezel <id>` / `--project <folder>` |
147
262
  | `gezel do <craftbook…>` | Start a craftbook as an immediately dispatched task in the current directory's project; accepts its id or display name |
263
+ | `gezel workflow <name-or-file> [args…]` | Run an explicitly trusted repository workflow from `.gezel/workflows/<name>.mjs` or a module path |
264
+ | `gezel secret list / set / remove` | Manage write-only provider credentials, including Brave and Tavily search keys |
265
+ | `gezel task wait <ref>` / `resume <ref>` | Follow a task to completion, or retry a paused task and follow it |
266
+ | `gezel task notes <ref> --warnings` | Read task notes and runtime warnings from its recent sessions |
148
267
  | `gezel start` / `stop` / `status` | Use or inspect the selected service. `stop` is the same hard stop as the desktop UX: cancel work, unload local engines, and switch to Reactive. `stop --daemon` shuts down a user-owned daemon process itself. `start --web` serves the browser UI. On hosts without a Gezel machine service, a started daemon prefers the canonical port 6228 (ephemeral fallback) so third-party OpenAI clients get a stable `https://127.0.0.1:6228/v1` base URL; with a machine service installed, the service owns 6228 and started daemons use an ephemeral port (`--port` pins one explicitly). |
149
268
  | `gezel doctor` | Report on the local install |
150
269
  | `gezel mode [read-only\|reactive\|reactive+tasks\|full-play]` | Show or change how much AI activity is allowed |
@@ -4,7 +4,7 @@
4
4
  import { basename as basename4, isAbsolute as isAbsolutePath, join as joinPath } from "path";
5
5
  import { GEZEL_VERSION, getLogOutput, setLogOutput } from "@bendyline/gezel";
6
6
  import {
7
- GezelApiError as GezelApiError2,
7
+ GezelApiError as GezelApiError3,
8
8
  streamChatEvents
9
9
  } from "@bendyline/gezel-client";
10
10
  import {
@@ -17,6 +17,7 @@ import {
17
17
  stopOwnedDaemon as stopOwnedDaemon2,
18
18
  stopProcessByPid
19
19
  } from "@bendyline/gezel-client/node";
20
+ import { resolveOnDeviceProvider } from "@bendyline/gezel/native";
20
21
  import { Command } from "commander";
21
22
 
22
23
  // src/connection.ts
@@ -568,6 +569,137 @@ async function resolveTuiProject(client, globals) {
568
569
  return ensureProjectForFolder(client, folder);
569
570
  }
570
571
 
572
+ // src/craftbook-command.ts
573
+ import { AwakeBudget } from "@bendyline/gezel";
574
+
575
+ // src/tui/craftbook-start.ts
576
+ import {
577
+ CRAFTBOOK_CATEGORY_FAMILY_META,
578
+ CRAFTBOOK_CATEGORY_META,
579
+ CRAFTBOOK_ROLE_META,
580
+ resolveCraftbookCategory,
581
+ visibleCatalogItems
582
+ } from "@bendyline/gezel";
583
+ function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
584
+ const byId = /* @__PURE__ */ new Map();
585
+ for (const item of visibleCatalogItems(items, showWorkInProgressFeatures)) {
586
+ if (item.manifest.kind !== "craftbook-template") continue;
587
+ const manifest = item.manifest;
588
+ if (byId.has(manifest.id)) continue;
589
+ byId.set(manifest.id, {
590
+ id: manifest.id,
591
+ name: manifest.name,
592
+ ...manifest.description ? { description: manifest.description } : {},
593
+ version: manifest.version,
594
+ sourceId: item.sourceId,
595
+ source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
596
+ stepCount: manifest.steps.length,
597
+ tags: manifest.tags ?? [],
598
+ role: manifest.role ?? "general",
599
+ category: resolveCraftbookCategory(manifest)
600
+ });
601
+ }
602
+ return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
603
+ }
604
+ function findCraftbook(books, value) {
605
+ const query = value.trim().toLowerCase();
606
+ return books.find((book) => book.id.toLowerCase() === query || book.name.toLowerCase() === query);
607
+ }
608
+ function craftbookStartRequest(book) {
609
+ const summary = book.description?.trim();
610
+ const description = summary ? `Start the "${book.name}" craftbook for this project. ${summary}` : `Start the "${book.name}" craftbook for this project. Follow every step in the recipe and verify its required outcomes before completing the task.`;
611
+ return {
612
+ title: book.name,
613
+ description,
614
+ craftbookId: book.id,
615
+ craftbookSourceId: book.sourceId,
616
+ ...book.version ? { craftbookVersion: book.version } : {},
617
+ dispatchEntry: true,
618
+ trustScripts: true
619
+ };
620
+ }
621
+
622
+ // src/craftbook-command.ts
623
+ function resolveCraftbookInvocation(books, tokens) {
624
+ for (let length = tokens.length; length > 0; length--) {
625
+ const book = findCraftbook(books, tokens.slice(0, length).join(" "));
626
+ if (book) return { book, args: tokens.slice(length) };
627
+ }
628
+ throw new CliError(`craftbook not found: ${tokens.join(" ")}`);
629
+ }
630
+ function parseCraftbookParams(book, tokens) {
631
+ const schema = book.paramSchema ?? {};
632
+ const properties = schema.properties ?? {};
633
+ const keys = Object.keys(properties);
634
+ const params = {};
635
+ for (const token of tokens) {
636
+ const match = /^([A-Za-z][\w.-]*)=([\s\S]*)$/.exec(token);
637
+ const key = match?.[1] ?? keys.find((name) => !Object.hasOwn(params, name));
638
+ if (!key || !Object.hasOwn(properties, key))
639
+ throw new CliError(`unknown craftbook argument: ${token}`);
640
+ if (Object.hasOwn(params, key)) throw new CliError(`duplicate craftbook parameter: ${key}`);
641
+ const value = match ? match[2] : token;
642
+ const def = properties[key];
643
+ if (Array.isArray(def.enum) && !def.enum.map(String).includes(value)) {
644
+ throw new CliError(`${key} must be one of: ${def.enum.join(", ")}`);
645
+ }
646
+ if (def.type === "boolean" && !["true", "false"].includes(value))
647
+ throw new CliError(`${key} must be true or false`);
648
+ if (def.type === "number" || def.type === "integer") {
649
+ const number = Number(value);
650
+ if (!value.trim() || !Number.isFinite(number) || def.type === "integer" && !Number.isInteger(number))
651
+ throw new CliError(`${key} must be a ${def.type}`);
652
+ if (typeof def.minimum === "number" && number < def.minimum)
653
+ throw new CliError(`${key} must be at least ${def.minimum}`);
654
+ if (typeof def.maximum === "number" && number > def.maximum)
655
+ throw new CliError(`${key} must be at most ${def.maximum}`);
656
+ }
657
+ if (typeof def.pattern === "string" && !new RegExp(def.pattern).test(value))
658
+ throw new CliError(`${key} must match ${def.pattern}`);
659
+ if (typeof def.minLength === "number" && value.trim().length < def.minLength)
660
+ throw new CliError(`${key} is too short`);
661
+ params[key] = value;
662
+ }
663
+ for (const key of Array.isArray(schema.required) ? schema.required : []) {
664
+ if (typeof key === "string" && !Object.hasOwn(params, key) && properties[key]?.default === void 0)
665
+ throw new CliError(`missing required craftbook parameter: ${key}`);
666
+ }
667
+ return params;
668
+ }
669
+ async function waitForTask(client, ref, options) {
670
+ const budget = new AwakeBudget(options.timeoutMs);
671
+ let previous = "";
672
+ for (; ; ) {
673
+ const task2 = await client.getTaskByRef(ref);
674
+ const progress = `${task2.status}:${task2.activeStepId}`;
675
+ if (progress !== previous) {
676
+ options.onProgress?.(task2);
677
+ previous = progress;
678
+ }
679
+ if (task2.status === "complete") return { task: task2, outcome: "complete", exitCode: 0 };
680
+ if (task2.status === "canceled") return { task: task2, outcome: "canceled", exitCode: 1 };
681
+ if (task2.status === "paused" || task2.status === "draft")
682
+ return { task: task2, outcome: "blocked", exitCode: 2 };
683
+ const refs = /* @__PURE__ */ new Set([task2.ref]);
684
+ if (task2.fanout || task2.craftbook.spawn || task2.craftbook.cliWorkflow) {
685
+ const { tasks } = await client.listTaskChildren(task2.projectId, task2.num);
686
+ if (!task2.craftbook.cliWorkflow && !tasks.some((child) => child.status === "active") && tasks.some((child) => child.status === "paused" || child.status === "canceled"))
687
+ return { task: task2, outcome: "blocked", exitCode: 2 };
688
+ if (!task2.craftbook.cliWorkflow) for (const child of tasks) refs.add(child.ref);
689
+ }
690
+ if (client.listQuestions) {
691
+ const { questions } = await client.listQuestions({
692
+ projectId: task2.projectId,
693
+ pending: true
694
+ });
695
+ const questionIds = questions.filter((q) => q.taskRef && refs.has(q.taskRef)).map((q) => q.id);
696
+ if (questionIds.length) return { task: task2, outcome: "blocked", exitCode: 2, questionIds };
697
+ }
698
+ if (budget.expired()) return { task: task2, outcome: "timeout", exitCode: 3 };
699
+ await new Promise((resolve6) => setTimeout(resolve6, options.pollMs ?? 1e3));
700
+ }
701
+ }
702
+
571
703
  // src/engagement-mode.ts
572
704
  var CLI_ENGAGEMENT_MODES = [
573
705
  {
@@ -982,6 +1114,147 @@ function errorMessage(error) {
982
1114
  return error instanceof Error ? error.message : String(error);
983
1115
  }
984
1116
 
1117
+ // src/secrets-command.ts
1118
+ import { GezelApiError as GezelApiError2 } from "@bendyline/gezel-client";
1119
+ var credentialFlags = {
1120
+ githubToken: "hasGithubToken",
1121
+ openaiApiKey: "hasOpenaiApiKey",
1122
+ openaiOrganization: "hasOpenaiOrganization",
1123
+ anthropicApiKey: "hasAnthropicApiKey",
1124
+ googleAiApiKey: "hasGoogleAiApiKey",
1125
+ webhookBearerToken: "hasWebhookBearerToken",
1126
+ webhookBasicAuth: "hasWebhookBasicAuth",
1127
+ braveSearchApiKey: "hasBraveSearchApiKey",
1128
+ tavilyApiKey: "hasTavilyApiKey"
1129
+ };
1130
+ function credentialName(name) {
1131
+ if (!Object.hasOwn(credentialFlags, name)) {
1132
+ throw new CliError(`Unknown credential. Run "gezel secret list" for supported names.`);
1133
+ }
1134
+ return name;
1135
+ }
1136
+ async function readSecretInput(options, env2 = process.env, input = process.stdin) {
1137
+ if (Number(options.env !== void 0) + Number(options.stdin === true) !== 1) {
1138
+ throw new CliError("Choose exactly one secret input: --env <VARIABLE> or --stdin.");
1139
+ }
1140
+ let value;
1141
+ if (options.env !== void 0) {
1142
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(options.env)) {
1143
+ throw new CliError("Use an environment variable name with --env, not its value.");
1144
+ }
1145
+ value = env2[options.env] ?? "";
1146
+ } else {
1147
+ if (input.isTTY) {
1148
+ throw new CliError("--stdin requires piped input. Use --env for an existing shell variable.");
1149
+ }
1150
+ const chunks = [];
1151
+ let size = 0;
1152
+ for await (const chunk of input) {
1153
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1154
+ size += bytes.length;
1155
+ if (size > 65536) throw new CliError("Secret input exceeds 64 KiB.");
1156
+ chunks.push(bytes);
1157
+ }
1158
+ value = Buffer.concat(chunks).toString("utf8");
1159
+ }
1160
+ value = value.replace(/[\r\n]+$/, "");
1161
+ if (!value.trim())
1162
+ throw new CliError('Secret input is empty; use "gezel secret remove" to clear it.');
1163
+ if (Buffer.byteLength(value) > 65536) throw new CliError("Secret input exceeds 64 KiB.");
1164
+ if (/[\r\n\0]/.test(value))
1165
+ throw new CliError("Secret input must be a single line without NUL bytes.");
1166
+ return value;
1167
+ }
1168
+ async function writeCredential(client, patch) {
1169
+ try {
1170
+ await client.updateConfig(patch);
1171
+ } catch (error) {
1172
+ const status = error instanceof GezelApiError2 ? ` (HTTP ${error.status})` : "";
1173
+ throw new CliError(
1174
+ `Could not update the credential${status}. Check the service connection and permissions.`
1175
+ );
1176
+ }
1177
+ }
1178
+ function registerSecretCommands(program2, connect, output = console.log) {
1179
+ const secret = program2.command("secret").description("Manage write-only provider credentials");
1180
+ secret.command("list").description("Show supported names and whether each is configured").option("--json", "Output names and configured flags as JSON").action(async (options) => {
1181
+ const config = await (await connect()).getConfig();
1182
+ const credentials = Object.entries(credentialFlags).map(([name, flag]) => ({
1183
+ name,
1184
+ configured: config[flag] === true
1185
+ }));
1186
+ output(
1187
+ options.json ? JSON.stringify({ credentials }) : credentials.map((c) => `${c.name} ${c.configured ? "configured" : "not configured"}`).join("\n")
1188
+ );
1189
+ });
1190
+ secret.command("set <name>").description("Save a provider credential in the service credential store").option("--env <VARIABLE>", "Read the value from this environment variable").option("--stdin", "Read the value from piped stdin").option(
1191
+ "--use-for-search",
1192
+ "Also select this Brave or Tavily credential as the web search provider"
1193
+ ).option("--json", "Output status as JSON without the value").action(async (name, options) => {
1194
+ const key = credentialName(name);
1195
+ const provider = key === "braveSearchApiKey" ? "brave" : key === "tavilyApiKey" ? "tavily" : void 0;
1196
+ if (options.useForSearch && !provider)
1197
+ throw new CliError("--use-for-search requires braveSearchApiKey or tavilyApiKey.");
1198
+ const value = await readSecretInput(options);
1199
+ const client = await connect();
1200
+ const patch = { [key]: value };
1201
+ if (options.useForSearch) {
1202
+ const config = await client.getConfig();
1203
+ patch.webSearch = { ...config.webSearch, provider };
1204
+ }
1205
+ await writeCredential(client, patch);
1206
+ output(
1207
+ options.json ? JSON.stringify({
1208
+ name: key,
1209
+ configured: true,
1210
+ ...options.useForSearch ? { searchProvider: provider } : {}
1211
+ }) : `${key}: configured${options.useForSearch ? `; web search: ${provider}` : ""}`
1212
+ );
1213
+ });
1214
+ secret.command("remove <name>").description("Remove a provider credential").option("--json", "Output status as JSON without the value").action(async (name, options) => {
1215
+ const key = credentialName(name);
1216
+ await writeCredential(await connect(), { [key]: "" });
1217
+ output(options.json ? JSON.stringify({ name: key, configured: false }) : `${key}: removed`);
1218
+ });
1219
+ }
1220
+
1221
+ // src/settings-command.ts
1222
+ import { resolveSecurityPolicy } from "@bendyline/gezel";
1223
+ function enabledValue(state) {
1224
+ if (state === void 0) return void 0;
1225
+ if (state === "on") return true;
1226
+ if (state === "off") return false;
1227
+ throw new CliError("Use on or off.");
1228
+ }
1229
+ function registerSecurityCommands(program2, connect) {
1230
+ 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) => {
1231
+ const enabled = enabledValue(state);
1232
+ const client = await connect();
1233
+ const policy = resolveSecurityPolicy(await client.getConfig());
1234
+ if (enabled !== void 0) {
1235
+ await client.updateConfig({
1236
+ securityPolicy: { ...policy, level: "custom", allowExternalServices: enabled }
1237
+ });
1238
+ }
1239
+ const result = { allowExternalServices: enabled ?? policy.allowExternalServices };
1240
+ console.log(
1241
+ options.json ? JSON.stringify(result) : `External services: ${result.allowExternalServices ? "on" : "off"}`
1242
+ );
1243
+ });
1244
+ }
1245
+ function registerProjectSettingsCommands(env2, connect, projectFor) {
1246
+ 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) => {
1247
+ const enabled = enabledValue(state);
1248
+ const client = await connect();
1249
+ const projectId = await projectFor(client);
1250
+ const project = enabled === void 0 ? await client.getProject(projectId) : await client.updateProject(projectId, { indexingEnabled: enabled });
1251
+ const result = { projectId, indexingEnabled: project.indexingEnabled !== false };
1252
+ console.log(
1253
+ options.json ? JSON.stringify(result) : `${projectId}: workspace indexing ${result.indexingEnabled ? "on" : "off"}`
1254
+ );
1255
+ });
1256
+ }
1257
+
985
1258
  // src/signal-cleanup.ts
986
1259
  function installSignalCleanup(cleanup, options = {}) {
987
1260
  if (!cleanup) return () => {
@@ -1186,50 +1459,73 @@ function resolveRestoreSelection(review, opts) {
1186
1459
  return { items, skipped };
1187
1460
  }
1188
1461
 
1189
- // src/tui/craftbook-start.ts
1462
+ // src/workflow-command.ts
1463
+ import { realpath } from "fs/promises";
1464
+ import { isAbsolute as isAbsolute2, relative, resolve as resolve5 } from "path";
1465
+ import { pathToFileURL } from "url";
1190
1466
  import {
1191
- CRAFTBOOK_CATEGORY_FAMILY_META,
1192
- CRAFTBOOK_CATEGORY_META,
1193
- CRAFTBOOK_ROLE_META,
1194
- resolveCraftbookCategory,
1195
- visibleCatalogItems
1467
+ craftbookFromDoc,
1468
+ formatCraftbookDocErrors,
1469
+ nowIso,
1470
+ parseCraftbookDoc
1196
1471
  } from "@bendyline/gezel";
1197
- function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
1198
- const byId = /* @__PURE__ */ new Map();
1199
- for (const item of visibleCatalogItems(items, showWorkInProgressFeatures)) {
1200
- if (item.manifest.kind !== "craftbook-template") continue;
1201
- const manifest = item.manifest;
1202
- if (byId.has(manifest.id)) continue;
1203
- byId.set(manifest.id, {
1204
- id: manifest.id,
1205
- name: manifest.name,
1206
- ...manifest.description ? { description: manifest.description } : {},
1207
- version: manifest.version,
1208
- sourceId: item.sourceId,
1209
- source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
1210
- stepCount: manifest.steps.length,
1211
- tags: manifest.tags ?? [],
1212
- role: manifest.role ?? "general",
1213
- category: resolveCraftbookCategory(manifest)
1214
- });
1472
+ function validateWorkflowCraftbook(document) {
1473
+ const parsed = parseCraftbookDoc(JSON.stringify(document), "json");
1474
+ if (!parsed.ok) throw new CliError(formatCraftbookDocErrors(parsed.errors));
1475
+ const built = craftbookFromDoc(parsed.doc, { now: nowIso() });
1476
+ if (!built.ok) throw new CliError(formatCraftbookDocErrors(built.errors));
1477
+ return built.craftbook;
1478
+ }
1479
+ async function runWorkflow(client, projectId, workspace, file, args, log = console.error, invocation) {
1480
+ const named = /^[a-z][a-z0-9-]*$/.test(file);
1481
+ const path = await realpath(resolve5(workspace, named ? `.gezel/workflows/${file}.mjs` : file));
1482
+ if (invocation) {
1483
+ const local = relative(await realpath(workspace), path);
1484
+ if (isAbsolute2(local) || local === ".." || local.startsWith("../") || local.startsWith("..\\")) {
1485
+ throw new CliError("A craftbook workflow module must remain inside its project workspace.");
1486
+ }
1215
1487
  }
1216
- return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
1217
- }
1218
- function findCraftbook(books, value) {
1219
- const query = value.trim().toLowerCase();
1220
- return books.find((book) => book.id.toLowerCase() === query || book.name.toLowerCase() === query);
1221
- }
1222
- function craftbookStartRequest(book) {
1223
- const summary = book.description?.trim();
1224
- const description = summary ? `Start the "${book.name}" craftbook for this project. ${summary}` : `Start the "${book.name}" craftbook for this project. Follow every step in the recipe and verify its required outcomes before completing the task.`;
1225
- return {
1226
- title: book.name,
1227
- description,
1228
- craftbookId: book.id,
1229
- craftbookSourceId: book.sourceId,
1230
- ...book.version ? { craftbookVersion: book.version } : {},
1231
- dispatchEntry: true
1232
- };
1488
+ const module = await import(pathToFileURL(path).href);
1489
+ if (typeof module.run !== "function")
1490
+ throw new CliError(`workflow ${path} must export an async run(context) function`);
1491
+ return module.run({
1492
+ client,
1493
+ projectId,
1494
+ workspace: resolve5(workspace),
1495
+ args,
1496
+ ...invocation ?? {},
1497
+ log,
1498
+ validateCraftbook: validateWorkflowCraftbook,
1499
+ runCraftbook: async (id, params, options = {}) => {
1500
+ let ref = options.taskRef;
1501
+ if (!ref) {
1502
+ const { craftbook: book } = await client.getCraftbook(id, { projectId, source: "project" });
1503
+ const parsed = parseCraftbookParams(
1504
+ book,
1505
+ Object.entries(params).map(([key, value]) => `${key}=${value}`)
1506
+ );
1507
+ const task2 = await client.createTask(projectId, {
1508
+ title: options.title ?? book.name,
1509
+ description: `Run the project craftbook ${book.name}. Follow every step and satisfy its required outcomes before completing this task.`,
1510
+ craftbookId: id,
1511
+ craftbookSourceId: "project",
1512
+ craftbookVersion: book.version,
1513
+ craftbookParams: parsed,
1514
+ dispatchEntry: true,
1515
+ roleBasedNameOnlyMode: true,
1516
+ trustScripts: true,
1517
+ ...options.parentTaskRef ? { parentTaskRef: options.parentTaskRef } : {}
1518
+ });
1519
+ await options.onCreated?.(task2);
1520
+ ref = task2.ref;
1521
+ }
1522
+ log(`Following ${ref}`);
1523
+ return waitForTask(client, ref, {
1524
+ timeoutMs: options.timeoutMs ?? invocation?.timeoutMs ?? 72e5,
1525
+ onProgress: (task2) => log(`${task2.ref}: ${task2.status} (${task2.activeStepId ?? "finished"})`)
1526
+ });
1527
+ }
1528
+ });
1233
1529
  }
1234
1530
 
1235
1531
  // src/bin/gezel.ts
@@ -1245,6 +1541,8 @@ program.name("gezel").description("Gezel \u2014 build a community of agents that
1245
1541
  "Use this folder as the active project (default and bare flag: cwd)."
1246
1542
  );
1247
1543
  var cliGlobals = () => program.opts();
1544
+ registerSecretCommands(program, () => connectOwned(cliGlobals()));
1545
+ registerSecurityCommands(program, () => connectOwned(cliGlobals()));
1248
1546
  program.hook("preAction", () => {
1249
1547
  const globals = cliGlobals();
1250
1548
  validateGlobals(globals);
@@ -1387,10 +1685,10 @@ async function startForeground(env2) {
1387
1685
  process.on("SIGINT", requestStop);
1388
1686
  process.on("SIGTERM", requestStop);
1389
1687
  try {
1390
- await new Promise((resolve5) => {
1688
+ await new Promise((resolve6) => {
1391
1689
  child.on("exit", (code) => {
1392
1690
  process.exitCode = code ?? 0;
1393
- resolve5();
1691
+ resolve6();
1394
1692
  });
1395
1693
  });
1396
1694
  } finally {
@@ -1579,29 +1877,130 @@ ${ev.error}`);
1579
1877
  }
1580
1878
  }
1581
1879
  });
1582
- program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").action(async (craftbookParts) => {
1583
- const craftbookRef = craftbookParts.join(" ").trim();
1880
+ program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").option(
1881
+ "--param <key=value>",
1882
+ "named craftbook parameter (repeatable)",
1883
+ (value, values) => [...values, value],
1884
+ []
1885
+ ).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(
1886
+ "--strict-sandbox",
1887
+ "require OS network isolation for custom scripts (CLI launches otherwise trust this recipe snapshot)"
1888
+ ).action(
1889
+ async (craftbookParts, opts) => {
1890
+ const timeoutMs = positiveSeconds(opts.timeout);
1891
+ const client = await connectOwned(cliGlobals());
1892
+ const projectId = await resolveRunProject(client, cliGlobals());
1893
+ const [config, result] = await Promise.all([
1894
+ client.getConfig(),
1895
+ client.listProjectCraftbooks(projectId)
1896
+ ]);
1897
+ const craftbooks = normalizeCraftbooks(
1898
+ result.items,
1899
+ config.showWorkInProgressFeatures === true
1900
+ );
1901
+ const { book, args } = resolveCraftbookInvocation(craftbooks, craftbookParts);
1902
+ const { craftbook } = await client.getCraftbook(book.id, {
1903
+ projectId,
1904
+ source: book.source,
1905
+ version: book.version
1906
+ });
1907
+ const craftbookParams = parseCraftbookParams(craftbook, [...args, ...opts.param]);
1908
+ if (craftbook.cliWorkflow) {
1909
+ if (book.source !== "project")
1910
+ throw new CliError("CLI workflow craftbooks must belong to this project.");
1911
+ if (opts.strictSandbox)
1912
+ throw new CliError(
1913
+ "CLI workflows execute ordinary repository code and cannot use --strict-sandbox."
1914
+ );
1915
+ const workspace = typeof cliGlobals().project === "string" ? cliGlobals().project : process.cwd();
1916
+ console.error(`Running ${craftbook.name}: ${craftbook.cliWorkflow.module}`);
1917
+ const result2 = await runWorkflow(
1918
+ client,
1919
+ projectId,
1920
+ workspace,
1921
+ craftbook.cliWorkflow.module,
1922
+ [],
1923
+ console.error,
1924
+ {
1925
+ craftbook,
1926
+ params: craftbookParams,
1927
+ timeoutMs
1928
+ }
1929
+ );
1930
+ printWorkflowResult(result2, opts.json);
1931
+ return;
1932
+ }
1933
+ const created = await client.createTask(projectId, {
1934
+ ...craftbookStartRequest(book),
1935
+ craftbookParams,
1936
+ trustScripts: !opts.strictSandbox,
1937
+ roleBasedNameOnlyMode: true
1938
+ });
1939
+ if (opts.wait) {
1940
+ console.error(`started ${created.ref} \u2014 ${created.title}`);
1941
+ await printTaskWait(client, created.ref, { ...opts, timeoutMs });
1942
+ } else
1943
+ console.log(
1944
+ opts.json ? JSON.stringify(created) : `started ${created.ref} \u2014 ${created.title}`
1945
+ );
1946
+ }
1947
+ );
1948
+ function positiveSeconds(value) {
1949
+ const seconds = Number(value);
1950
+ if (!Number.isFinite(seconds) || seconds <= 0)
1951
+ throw new CliError("--timeout must be a positive number of seconds");
1952
+ return seconds * 1e3;
1953
+ }
1954
+ program.command("workflow <file> [args...]").description(
1955
+ "Run a trusted project workflow module (ordinary local code, with your account permissions); names resolve in .gezel/workflows/"
1956
+ ).option("--json", "emit the workflow result as JSON").action(async (file, args, opts) => {
1584
1957
  const client = await connectOwned(cliGlobals());
1585
1958
  const projectId = await resolveRunProject(client, cliGlobals());
1586
- const [config, result] = await Promise.all([
1587
- client.getConfig(),
1588
- client.listProjectCraftbooks(projectId)
1589
- ]);
1590
- const craftbooks = normalizeCraftbooks(
1591
- result.items,
1592
- config.showWorkInProgressFeatures === true
1593
- );
1594
- const book = findCraftbook(craftbooks, craftbookRef);
1595
- if (!book) {
1596
- throw new CliError(`craftbook not found: ${craftbookRef} (run gezel and type /do to browse)`);
1597
- }
1598
- const created = await client.createTask(projectId, {
1599
- ...craftbookStartRequest(book),
1600
- roleBasedNameOnlyMode: true
1601
- });
1602
- console.log(`started ${created.ref} \u2014 ${created.title}`);
1959
+ const workspace = typeof cliGlobals().project === "string" ? cliGlobals().project : process.cwd();
1960
+ const result = await runWorkflow(client, projectId, workspace, file, args);
1961
+ printWorkflowResult(result, opts.json);
1603
1962
  });
1963
+ function printWorkflowResult(result, json) {
1964
+ if (result !== void 0)
1965
+ console.log(json ? JSON.stringify(result) : JSON.stringify(result, null, 2));
1966
+ if (result && typeof result === "object" && "exitCode" in result) {
1967
+ const code = Number(result.exitCode);
1968
+ if (Number.isInteger(code) && code >= 0 && code <= 255) process.exitCode = code;
1969
+ }
1970
+ }
1971
+ async function printTaskWait(client, ref, opts) {
1972
+ const result = await waitForTask(client, ref, {
1973
+ timeoutMs: opts.timeoutMs,
1974
+ onProgress: (task2) => console.error(
1975
+ `${task2.ref}: ${task2.status}${task2.activeStepId ? ` (${task2.activeStepId})` : ""}`
1976
+ )
1977
+ });
1978
+ console.log(opts.json ? JSON.stringify(result) : `${result.task.ref}: ${result.outcome}`);
1979
+ process.exitCode = result.exitCode;
1980
+ }
1604
1981
  var agent = program.command("agent").description("Manage agents");
1982
+ agent.command("output-limit <id> [tokens]").description(
1983
+ "Show or set one gezel's output-token limit, including reasoning; auto clears its override"
1984
+ ).option("--json", "Output the per-gezel override as JSON").action(async (id, tokens, opts) => {
1985
+ if (tokens !== void 0 && tokens !== "auto" && (!/^\d+$/.test(tokens) || !Number.isSafeInteger(Number(tokens)) || Number(tokens) < 1)) {
1986
+ throw new CliError("Output limit must be a positive integer, or auto.");
1987
+ }
1988
+ const client = await connectOwned(cliGlobals());
1989
+ const { parsed } = await client.getGezel(id);
1990
+ const tuning = { ...parsed.frontmatter.tuning };
1991
+ const sampling = { ...tuning.sampling };
1992
+ if (tokens !== void 0) {
1993
+ if (tokens === "auto") delete sampling.maxTokens;
1994
+ else sampling.maxTokens = Number(tokens);
1995
+ if (Object.keys(sampling).length) tuning.sampling = sampling;
1996
+ else delete tuning.sampling;
1997
+ await client.updateGezelSettings(id, { tuning: Object.keys(tuning).length ? tuning : null });
1998
+ }
1999
+ const result = { gezelId: id, outputTokens: sampling.maxTokens ?? null };
2000
+ console.log(
2001
+ opts.json ? JSON.stringify(result) : `${id}: ${result.outputTokens === null ? "auto (inherits model/profile defaults)" : `${result.outputTokens} output tokens, including reasoning`}`
2002
+ );
2003
+ });
1605
2004
  agent.command("list").description("List agents").action(async () => {
1606
2005
  const client = await connectOwned(cliGlobals());
1607
2006
  const res = await client.listGezels();
@@ -1620,6 +2019,11 @@ agent.command("show <id>").description("Show an agent").action(async (id) => {
1620
2019
  console.log(a.parsed.source);
1621
2020
  });
1622
2021
  var env = program.command("env").description("Manage projects");
2022
+ registerProjectSettingsCommands(
2023
+ env,
2024
+ () => connectOwned(cliGlobals()),
2025
+ (client) => resolveRunProject(client, cliGlobals())
2026
+ );
1623
2027
  env.command("list").description("List projects").action(async () => {
1624
2028
  const client = await connectOwned(cliGlobals());
1625
2029
  const res = await client.listProjects();
@@ -1704,13 +2108,13 @@ skills.command("import <source>").description("Convert a discovered skill (by it
1704
2108
  skills.command("convert <path>").description("Convert a SKILL.md file to a craftbook document on stdout (no daemon)").option("--md", "emit the markdown encoding instead of JSON").option("--released-at <iso>", "stamp releasedAt (catalog authoring)").action(async (path, opts) => {
1705
2109
  const { readFile: readFsFile } = await import("fs/promises");
1706
2110
  const { basename: base, dirname: dir } = await import("path");
1707
- const { parseSkillDoc, skillToCraftbookDoc, serializeCraftbookDoc, craftbookFromDoc } = await import("@bendyline/gezel");
2111
+ const { parseSkillDoc, skillToCraftbookDoc, serializeCraftbookDoc, craftbookFromDoc: craftbookFromDoc2 } = await import("@bendyline/gezel");
1708
2112
  const raw = await readFsFile(path, "utf8");
1709
2113
  const skill = parseSkillDoc(raw, { fallbackName: base(dir(path)) });
1710
2114
  const result = skillToCraftbookDoc(skill, {
1711
2115
  ...opts.releasedAt ? { releasedAt: opts.releasedAt } : {}
1712
2116
  });
1713
- const check = craftbookFromDoc(result.doc, { now: "1970-01-01T00:00:00.000Z" });
2117
+ const check = craftbookFromDoc2(result.doc, { now: "1970-01-01T00:00:00.000Z" });
1714
2118
  if (!check.ok) {
1715
2119
  console.error("conversion produced an invalid craftbook:");
1716
2120
  for (const e of check.errors) console.error(` ${e.where}: ${e.message}`);
@@ -1826,7 +2230,7 @@ knowledge.command("install <source>").description("Install a .gezk catalog into
1826
2230
  try {
1827
2231
  started = await client.installKnowledgeCatalog({ source: installSource });
1828
2232
  } catch (err) {
1829
- if (err instanceof GezelApiError2 && err.status === 403) {
2233
+ if (err instanceof GezelApiError3 && err.status === 403) {
1830
2234
  throw new CliError(
1831
2235
  "Downloading knowledge catalogs needs app network access, which the security policy turns off (Settings \u2192 Security)."
1832
2236
  );
@@ -1991,6 +2395,40 @@ appCmd.command("schemas").description("The JSON Schemas an AI App author codes a
1991
2395
  await runAppSchemas(opts);
1992
2396
  });
1993
2397
  var task = program.command("task").description("Manage tasks");
2398
+ task.command("pause <ref>").description("Pause one active task without stopping other tasks or the daemon").option("--json", "emit the task reference and status as JSON").action(async (ref, opts) => {
2399
+ const client = await connectOwned(cliGlobals());
2400
+ let current = await client.getTaskByRef(ref);
2401
+ if (current.status !== "active" && current.status !== "paused") {
2402
+ throw new CliError(
2403
+ `task ${ref} is ${current.status}; pause requires an active or paused task`
2404
+ );
2405
+ }
2406
+ if (current.status === "active") {
2407
+ current = await client.setTaskStatus(current.projectId, current.num, "paused");
2408
+ }
2409
+ console.log(
2410
+ opts.json ? JSON.stringify({ taskRef: current.ref, status: current.status }) : `paused ${current.ref}`
2411
+ );
2412
+ });
2413
+ for (const verb of ["wait", "resume"]) {
2414
+ task.command(`${verb} <ref>`).description(
2415
+ verb === "wait" ? "Wait for a task to finish or need attention" : "Retry a paused task and wait for its result"
2416
+ ).option(
2417
+ "--timeout <seconds>",
2418
+ "wait budget in seconds; timeout leaves the task running",
2419
+ "7200"
2420
+ ).option("--json", "emit one JSON result on stdout").action(async (ref, opts) => {
2421
+ const timeoutMs = positiveSeconds(opts.timeout);
2422
+ const client = await connectOwned(cliGlobals());
2423
+ if (verb === "resume") {
2424
+ const current = await client.getTaskByRef(ref);
2425
+ if (current.status !== "paused")
2426
+ throw new CliError(`task ${ref} is ${current.status}; resume requires a paused task`);
2427
+ await client.retryTask(current.projectId, current.num);
2428
+ }
2429
+ await printTaskWait(client, ref, { ...opts, timeoutMs });
2430
+ });
2431
+ }
1994
2432
  task.command("list").description("List tasks across every project").option("-s, --status <status>", "filter by status (paused|active|complete|canceled)").action(async (opts) => {
1995
2433
  const client = await connectOwned(cliGlobals());
1996
2434
  const res = await client.listTasks(
@@ -2022,6 +2460,32 @@ task.command("show <ref>").description("Show one task (format: projectId/num)").
2022
2460
  const t = await client.getTaskByRef(ref);
2023
2461
  console.log(JSON.stringify(t, null, 2));
2024
2462
  });
2463
+ task.command("notes <ref>").description("Read task notes, including pause reasons and failed checks").option("--warnings", "Also include model/runtime warnings from the latest 20 task sessions").option("--json", "Output the notes as JSON").action(async (ref, opts) => {
2464
+ const client = await connectOwned(cliGlobals());
2465
+ const current = await client.getTaskByRef(ref);
2466
+ const result = await client.listTaskNotes(current.projectId, current.num);
2467
+ const warnings = [];
2468
+ if (opts.warnings) {
2469
+ const { sessions } = await client.listTaskSessions(current.projectId, current.num);
2470
+ for (const session of sessions.slice(0, 20)) {
2471
+ const full = await client.getChatSession(session.id);
2472
+ for (const message of full.messages) {
2473
+ for (const text of message.warnings ?? [])
2474
+ warnings.push({ sessionId: session.id, at: message.at, text });
2475
+ }
2476
+ }
2477
+ }
2478
+ console.log(
2479
+ opts.json ? JSON.stringify({ ...result, ...opts.warnings ? { warnings } : {} }) : [
2480
+ ...result.notes.map(
2481
+ (note) => `${note.at}${note.stepId ? ` [${note.stepId}]` : ""}
2482
+ ${note.text}`
2483
+ ),
2484
+ ...warnings.map((warning) => `${warning.at} [runtime warning]
2485
+ ${warning.text}`)
2486
+ ].join("\n\n") || "(no task notes)"
2487
+ );
2488
+ });
2025
2489
  program.command("create-image [prompt...]").description("Generate an image from a prompt (or --file) via the configured image engine").option("-f, --file <path>", "read the prompt from a text file instead of the argument").option("-m, --model <id>", "image model catalog id (default: the engine default)").option("-n, --negative <text>", "negative prompt").option("-W, --width <px>", "width in pixels").option("-H, --height <px>", "height in pixels").option("-s, --steps <n>", "sampler steps (default: the model recommendation)").option("--seed <n>", "seed for reproducible output").option("-p, --project <id>", "project to write the artifact under", "default").option("-o, --output <path>", "write the image here (default: ./<artifact name>)").action(
2026
2490
  async (promptParts, opts) => {
2027
2491
  const prompt = await resolvePromptText(promptParts, opts.file, "prompt");
@@ -2208,8 +2672,46 @@ function resolveModelProvider(raw) {
2208
2672
  }
2209
2673
  return raw;
2210
2674
  }
2211
- return process.platform === "darwin" && process.arch === "arm64" ? "mlx" : "llama-cpp";
2675
+ return resolveOnDeviceProvider(process.platform, process.arch);
2212
2676
  }
2677
+ 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) => {
2678
+ const provider = resolveModelProvider(opts.provider);
2679
+ if (slots !== void 0 && slots !== "auto" && (!/^\d+$/.test(slots) || !Number.isSafeInteger(Number(slots)) || Number(slots) < 1)) {
2680
+ throw new CliError("Concurrency must be a positive integer, or auto.");
2681
+ }
2682
+ const client = await connectOwned(cliGlobals());
2683
+ const config = await client.getConfig();
2684
+ const concurrency = { ...config.providerConcurrency };
2685
+ if (slots !== void 0) {
2686
+ if (slots === "auto") delete concurrency[provider];
2687
+ else concurrency[provider] = Number(slots);
2688
+ await client.updateConfig({ providerConcurrency: concurrency });
2689
+ }
2690
+ const result = { provider, slots: concurrency[provider] ?? null };
2691
+ console.log(
2692
+ opts.json ? JSON.stringify(result) : `${provider}: ${result.slots ?? "auto"}${result.slots === null ? "" : " inference slots"}${slots === void 0 ? "" : " (applies when idle sessions reload)"}`
2693
+ );
2694
+ });
2695
+ model.command("context <id> [tokens]").description("Show or set a model context window in tokens; use auto to clear an override").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").option("--json", "Output the context override as JSON").action(
2696
+ async (id, tokens, opts) => {
2697
+ const provider = resolveModelProvider(opts.provider);
2698
+ let contextTokens;
2699
+ if (tokens !== void 0) {
2700
+ contextTokens = tokens === "auto" ? null : Number(tokens);
2701
+ if (contextTokens !== null && (!/^\d+$/.test(tokens) || !Number.isInteger(contextTokens) || contextTokens < 32768 || contextTokens > 4194304)) {
2702
+ throw new CliError("Context must be an integer from 32768 to 4194304 tokens, or auto.");
2703
+ }
2704
+ }
2705
+ const client = await connectOwned(cliGlobals());
2706
+ const result = contextTokens === void 0 ? {
2707
+ modelId: id,
2708
+ contextTokens: (await client.getModelContextOverrides(provider)).overrides[id] ?? null
2709
+ } : await client.updateModelContextOverride(provider, id, contextTokens);
2710
+ console.log(
2711
+ opts.json ? JSON.stringify({ provider, ...result }) : `${provider}/${id}: ${result.contextTokens ?? "auto"}${result.contextTokens === null ? "" : " tokens"}${tokens === void 0 ? "" : " (applies on the next model launch)"}`
2712
+ );
2713
+ }
2714
+ );
2213
2715
  model.command("list").description("List local chat models for an engine").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").action(async (opts) => {
2214
2716
  const client = await connectOwned(cliGlobals());
2215
2717
  const provider = resolveModelProvider(opts.provider);
@@ -2,9 +2,10 @@
2
2
 
3
3
  // src/knowledge-command.ts
4
4
  import { createHash as createHash2 } from "crypto";
5
+ import { existsSync } from "fs";
5
6
  import { mkdir as mkdir2, mkdtemp, readFile as readFile2, rm as rm2, stat, writeFile as writeFile2 } from "fs/promises";
6
7
  import { homedir as homedir2, tmpdir } from "os";
7
- import { basename as basename2, dirname as dirname2, join as join2, resolve as resolve2 } from "path";
8
+ import { basename as basename2, dirname as dirname2, join as join2, relative, resolve as resolve2 } from "path";
8
9
  import { KnowledgeIdSchema, formatKnowledgeUri } from "@bendyline/gezel";
9
10
  import {
10
11
  CatalogHandle,
@@ -13,10 +14,12 @@ import {
13
14
  MARKDOWN_CHUNKS_2,
14
15
  compileKnowledgeCatalog,
15
16
  createProfileEmbedder,
17
+ detectTableOfContents,
16
18
  extractGezkVerified,
17
19
  knowledgeEmbeddingProfile,
18
20
  loadMarkdownCatalog,
19
21
  readGezkManifest,
22
+ readMkdocsDocsDir,
20
23
  signManifest,
21
24
  validateExtractedCatalog
22
25
  } from "@bendyline/gezel-knowledge";
@@ -106,23 +109,59 @@ async function runKnowledgeInit(dir) {
106
109
  console.log(`Initialized knowledge catalog at ${root}`);
107
110
  console.log(` ${CATALOG_JSON} \u2014 identity, license, embedding profile`);
108
111
  console.log(` ${CONTENT_DIR}/ \u2014 Markdown content (folders become topics)`);
112
+ console.log(
113
+ " An outline the tree already has is honored: SUMMARY.md, an mkdocs.yml nav, _toc.yml, or Hugo _index.md pages"
114
+ );
109
115
  console.log(`Build with: gezel knowledge build ${dir}`);
110
116
  }
111
117
  function sanitizeCatalogId(name) {
112
118
  const slug = name.toLowerCase().normalize("NFKD").replace(/\p{Mark}/gu, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 63);
113
119
  return KnowledgeIdSchema.safeParse(slug).success ? slug : "my-catalog";
114
120
  }
115
- async function runKnowledgeBuild(dir, opts, deps = {}) {
116
- const root = resolve2(dir);
117
- const config = await readCatalogConfig(root);
118
- const contentDir = join2(root, CONTENT_DIR);
119
- const hasContentDir = await stat(contentDir).then(
121
+ async function isDirectory(path) {
122
+ return stat(path).then(
120
123
  (s) => s.isDirectory(),
121
124
  () => false
122
125
  );
123
- const source = await loadMarkdownCatalog(hasContentDir ? contentDir : root, {
124
- language: config.language
126
+ }
127
+ async function resolveContentRoot(root, config) {
128
+ if (config.content) {
129
+ const dir = resolve2(root, config.content);
130
+ if (!await isDirectory(dir)) {
131
+ throw new CliError(
132
+ `${CATALOG_JSON} names content '${config.content}', which is not a directory`
133
+ );
134
+ }
135
+ return dir;
136
+ }
137
+ const contentDir = join2(root, CONTENT_DIR);
138
+ if (await isDirectory(contentDir)) return contentDir;
139
+ if (config.toc === void 0 || config.toc.format === "mkdocs") {
140
+ const mkdocs = config.toc?.path ? resolve2(root, config.toc.path) : [join2(root, "mkdocs.yml"), join2(root, "mkdocs.yaml")].find((p) => existsSync(p));
141
+ if (mkdocs && existsSync(mkdocs)) {
142
+ const docsDir = await readMkdocsDocsDir(mkdocs);
143
+ if (await isDirectory(docsDir)) return docsDir;
144
+ }
145
+ }
146
+ return root;
147
+ }
148
+ function describeToc(toc, root) {
149
+ const source = toc.format === "folders" ? "folders" : toc.format === "hugo" ? "Hugo conventions (_index.md, weight)" : toc.format;
150
+ return toc.path ? `${source} (${relative(root, toc.path) || toc.path})` : source;
151
+ }
152
+ async function runKnowledgeBuild(dir, opts, deps = {}) {
153
+ const root = resolve2(dir);
154
+ const config = await readCatalogConfig(root);
155
+ const contentRoot = await resolveContentRoot(root, config);
156
+ const toc = config.toc ?? await detectTableOfContents(contentRoot, root);
157
+ const source = await loadMarkdownCatalog(contentRoot, {
158
+ language: config.language,
159
+ uri: { publisherId: config.publisher.id, catalogId: config.id },
160
+ ...config.ignore ? { ignore: config.ignore } : {},
161
+ toc,
162
+ onWarning: (message) => console.warn(`warning: ${message}`)
125
163
  });
164
+ console.log(`Table of contents: ${describeToc(source.toc, root)}`);
126
165
  const profileId = config.profile ?? "bge-small-en-v1.5@1";
127
166
  const profile = knowledgeEmbeddingProfile(profileId);
128
167
  if (!profile) {
@@ -131,7 +170,7 @@ async function runKnowledgeBuild(dir, opts, deps = {}) {
131
170
  );
132
171
  }
133
172
  console.log(
134
- `Building ${config.id}@${config.version}: ${source.documents.length} documents, profile ${profileId}`
173
+ `Building ${config.id}@${config.version}: ${source.documents.length} documents, ${source.assets.length} assets, profile ${profileId}`
135
174
  );
136
175
  console.log("Loading the embedding model (first run downloads it)\u2026");
137
176
  const embedder = await (deps.createEmbedder ?? defaultCreateEmbedder)(profileId);
@@ -161,6 +200,7 @@ async function runKnowledgeBuild(dir, opts, deps = {}) {
161
200
  embed: (texts) => embedder.embed(texts),
162
201
  countTokens: (text) => embedder.countTokens(text),
163
202
  workDir,
203
+ assets: source.assets,
164
204
  ...signKeyPem ? { finalizeManifest: (manifest) => signManifest(manifest, signKeyPem) } : {},
165
205
  onProgress: ({ done, total }) => {
166
206
  if (!process.stderr.isTTY || total === 0) return;
package/dist/tui/index.js CHANGED
@@ -2304,7 +2304,8 @@ function craftbookStartRequest(book) {
2304
2304
  craftbookId: book.id,
2305
2305
  craftbookSourceId: book.sourceId,
2306
2306
  ...book.version ? { craftbookVersion: book.version } : {},
2307
- dispatchEntry: true
2307
+ dispatchEntry: true,
2308
+ trustScripts: true
2308
2309
  };
2309
2310
  }
2310
2311
 
@@ -2473,6 +2474,7 @@ function resolveGezelArg(arg, inputs) {
2473
2474
  import {
2474
2475
  formatModelAttribution as formatModelAttribution2
2475
2476
  } from "@bendyline/gezel";
2477
+ import { resolveOnDeviceProvider } from "@bendyline/gezel/native";
2476
2478
 
2477
2479
  // src/tui/bootstrap.ts
2478
2480
  import {
@@ -2733,7 +2735,7 @@ async function loadModelDownloadChoices(client, config, platform = process.platf
2733
2735
  client.getMemoryProfile(),
2734
2736
  client.listCatalogItems("chat-model")
2735
2737
  ]);
2736
- const provider = config.provider === "mlx" || config.provider === "llama-cpp" ? config.provider : memory.platform === "darwin" && platform === "darwin" && arch === "arm64" ? "mlx" : "llama-cpp";
2738
+ const provider = config.provider === "mlx" || config.provider === "llama-cpp" ? config.provider : memory.platform === platform ? resolveOnDeviceProvider(platform, arch) : "llama-cpp";
2737
2739
  const installed = await client.listProviderModels(provider).catch(() => ({ models: [] }));
2738
2740
  const installedIds = new Set(installed.models.map((model) => model.id));
2739
2741
  const ranked = rankChatModels(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/gezel-cli",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "The `gezel` command-line tool.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -44,15 +44,15 @@
44
44
  "!dist/**/*.map"
45
45
  ],
46
46
  "dependencies": {
47
- "@bendyline/gezel": "1.1.0",
48
- "@bendyline/gezel-app-sdk": "1.0.8",
49
- "@bendyline/gezel-catalog": "1.1.0",
50
- "@bendyline/gezel-client": "1.1.0",
51
- "@bendyline/gezel-knowledge": "1.1.0",
52
- "@bendyline/gezel-service": "1.1.0",
53
- "@bendyline/squisq": "2.11.0",
54
- "@bendyline/squisq-formats": "2.6.0",
55
- "@bendyline/squisq-react": "2.11.0",
47
+ "@bendyline/gezel": "1.1.2",
48
+ "@bendyline/gezel-app-sdk": "1.0.10",
49
+ "@bendyline/gezel-catalog": "1.1.2",
50
+ "@bendyline/gezel-client": "1.1.2",
51
+ "@bendyline/gezel-knowledge": "1.1.2",
52
+ "@bendyline/gezel-service": "1.1.2",
53
+ "@bendyline/squisq": "2.11.5",
54
+ "@bendyline/squisq-formats": "2.6.5",
55
+ "@bendyline/squisq-react": "2.11.5",
56
56
  "commander": "^15.0.0",
57
57
  "ink": "^7.1.1",
58
58
  "ink-text-input": "^6.0.0",