@bendyline/gezel-cli 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tui/index.js CHANGED
@@ -22,11 +22,13 @@ import {
22
22
  GezelApiError,
23
23
  GezelClient,
24
24
  createTrustingFetch,
25
+ discoverOrSpawn,
25
26
  electronNativeBinCandidates,
26
27
  isProcessAlive,
27
28
  readRuntime,
28
29
  readSystemServiceEndpoint,
29
30
  resolveDaemonEntry,
31
+ stopOwnedDaemon,
30
32
  systemSharedAssetsDir
31
33
  } from "@bendyline/gezel-client/node";
32
34
  import { gezelPaths } from "@bendyline/gezel/paths";
@@ -39,7 +41,24 @@ var CliError = class extends Error {
39
41
  async function ensureCliProjectLead(client, projectId) {
40
42
  const project = await client.getProject(projectId);
41
43
  if (project.voormanGezelId) return project.voormanGezelId;
42
- if (project.mode === "solo" && project.gezelIds?.[0]) return project.gezelIds[0];
44
+ if (project.mode === "solo") {
45
+ if (project.gezelIds?.[0]) return project.gezelIds[0];
46
+ if (project.workingDir) {
47
+ const { gezels: gezels2 } = await client.listGezels();
48
+ let builder = gezels2.find(
49
+ (gezel) => gezel.templateId === "builder" || gezel.role?.trim().toLowerCase() === "builder"
50
+ );
51
+ if (!builder) {
52
+ const { name, gender } = pickRandomNameWithGender();
53
+ builder = await client.createGezelFromTemplate("builder", { name, gender });
54
+ }
55
+ const updated2 = await client.updateProject(projectId, { voormanGezelId: builder.id });
56
+ if (!updated2.voormanGezelId) {
57
+ throw new CliError(`project "${updated2.name}" has no Builder`);
58
+ }
59
+ return updated2.voormanGezelId;
60
+ }
61
+ }
43
62
  const { gezels } = await client.listGezels();
44
63
  let voorman = gezels.find(
45
64
  (gezel) => gezel.templateId === "voorman" || gezel.role?.trim().toLowerCase() === "voorman"
@@ -138,17 +157,123 @@ function activeAccessMode(opts) {
138
157
  return GezelCore.projectWorkspaceWritable(project) ? "editable" : "read-only";
139
158
  }
140
159
 
160
+ // src/tui/open-command.ts
161
+ var MAX_RECENT_REFERENCES = 12;
162
+ function rememberCliOpenReferences(current, observed, max = MAX_RECENT_REFERENCES) {
163
+ const next = [...current];
164
+ for (const reference2 of observed) {
165
+ const index = next.findIndex((candidate) => candidate.key === reference2.key);
166
+ if (index !== -1) next.splice(index, 1);
167
+ next.unshift(reference2);
168
+ }
169
+ return next.slice(0, max);
170
+ }
171
+ function cliOpenReferencesFromEvent(env) {
172
+ if (env.event.type === "tool") {
173
+ return referencesFromTool(env.event, env.projectId);
174
+ }
175
+ if (env.event.type === "complete" || env.event.type === "user_message") {
176
+ return referencesFromMessage(env.event.message, env.projectId);
177
+ }
178
+ return [];
179
+ }
180
+ function cliOpenReferencesFromSession(session) {
181
+ let recent = [];
182
+ for (const message of session.messages) {
183
+ recent = rememberCliOpenReferences(recent, referencesFromMessage(message, session.projectId));
184
+ }
185
+ return recent;
186
+ }
187
+ function resolveCliOpenTarget(input, recentReferences) {
188
+ const query = normalizeLookup(input);
189
+ if (query === "workspace" || query === "artifacts") {
190
+ return { type: "folder", folder: query };
191
+ }
192
+ if (!query) return null;
193
+ const exact = recentReferences.find((reference2) => normalizeLookup(reference2.path) === query);
194
+ if (exact) return { type: "reference", reference: exact };
195
+ const basenameMatches = recentReferences.filter(
196
+ (reference2) => normalizeLookup(basename2(reference2.path)) === query
197
+ );
198
+ return basenameMatches.length === 1 ? { type: "reference", reference: basenameMatches[0] } : null;
199
+ }
200
+ function referencesFromMessage(message, projectId) {
201
+ const references = [];
202
+ for (const tool of message.toolCalls ?? []) {
203
+ references.push(...referencesFromTool(tool, projectId));
204
+ }
205
+ for (const path of message.referencedArtifacts ?? []) {
206
+ references.push(reference("artifact", path, projectId));
207
+ }
208
+ return references;
209
+ }
210
+ function referencesFromTool(tool, projectId) {
211
+ if (!tool.success) return [];
212
+ const references = [];
213
+ for (const media of [...tool.images ?? [], ...tool.audios ?? [], ...tool.videos ?? []]) {
214
+ references.push(reference("artifact", media.path, projectId));
215
+ }
216
+ const kind = classifyTool(tool.name);
217
+ if (!kind) return references;
218
+ const paths = tool.paths && tool.paths.length > 0 ? tool.paths : tool.path ? [tool.path] : [];
219
+ for (const path of paths) references.push(reference(kind, path, projectId));
220
+ return references;
221
+ }
222
+ function classifyTool(name) {
223
+ const normalized = name.replaceAll("-", "_").toLowerCase();
224
+ if (["read_artifact", "write_artifact"].includes(normalized)) return "artifact";
225
+ if (["read_document", "write_document"].includes(normalized)) return "document";
226
+ if ([
227
+ "readfile",
228
+ "read_file",
229
+ "read_files",
230
+ "writefile",
231
+ "write_file",
232
+ "replace_in_file",
233
+ "replace_lines",
234
+ "insert_at_marker",
235
+ "apply_patch"
236
+ ].includes(normalized)) {
237
+ return "workspace";
238
+ }
239
+ return null;
240
+ }
241
+ function reference(kind, path, projectId) {
242
+ return {
243
+ key: `${projectId}:${kind}:${normalizeLookup(path)}`,
244
+ kind,
245
+ path,
246
+ projectId
247
+ };
248
+ }
249
+ function normalizeCliOpenLookup(value) {
250
+ return normalizeLookup(value);
251
+ }
252
+ function cliOpenBasename(path) {
253
+ return basename2(path);
254
+ }
255
+ function normalizeLookup(value) {
256
+ return value.trim().replaceAll("\\", "/").toLowerCase();
257
+ }
258
+ function basename2(path) {
259
+ const normalized = path.replaceAll("\\", "/");
260
+ return normalized.slice(normalized.lastIndexOf("/") + 1);
261
+ }
262
+
141
263
  // src/tui/commands.ts
142
264
  var SLASH_COMMAND_WORDWHEEL_SIZE = 4;
143
265
  var SLASH_COMMANDS = [
144
266
  { name: "help", description: "show the command reference" },
145
267
  { name: "project", description: "switch active project" },
146
268
  { name: "gezel", description: "switch active gezel" },
269
+ { name: "allow", description: "allow a project permission" },
270
+ { name: "disallow", description: "disallow a project permission" },
147
271
  { name: "mode", description: "set AI activity: read-only through full play" },
148
272
  { name: "model", description: "switch engine and model" },
149
273
  { name: "thread", description: "switch the active chat thread" },
274
+ { name: "open", description: "open a project folder or recent chat file" },
150
275
  { name: "task", description: "list and manage project tasks" },
151
- { name: "start", description: "start a task from a craftbook" },
276
+ { name: "do", description: "do a task from a craftbook" },
152
277
  { name: "continue", description: "process due and active project tasks" },
153
278
  { name: "nightshift", description: "start, stop, or list night-shift work" },
154
279
  { name: "focus", description: "send into another active chat" },
@@ -167,7 +292,87 @@ var NIGHT_SHIFT_SUBCOMMANDS = [
167
292
  { name: "stop", description: "stop the current night shift" },
168
293
  { name: "list", description: "show current and upcoming night-shift work" }
169
294
  ];
170
- function suggestSlashWordwheel(input, craftbooks) {
295
+ var MODEL_SUBCOMMANDS = [
296
+ { name: "download", description: "choose and download a new on-device model" }
297
+ ];
298
+ var PROJECT_PERMISSIONS = [
299
+ {
300
+ name: "edits",
301
+ allowDescription: "let built-in tools and background work edit this project",
302
+ disallowDescription: "make built-in tools and background work read-only"
303
+ },
304
+ {
305
+ name: "codexedits",
306
+ allowDescription: "let Codex sessions edit this project",
307
+ disallowDescription: "put Codex sessions in read-only plan mode"
308
+ },
309
+ {
310
+ name: "claudeedits",
311
+ allowDescription: "let Claude sessions edit this project",
312
+ disallowDescription: "put Claude sessions in read-only plan mode"
313
+ }
314
+ ];
315
+ var PROJECT_PERMISSION_USAGE = PROJECT_PERMISSIONS.map(
316
+ (permission) => permission.name
317
+ ).join("|");
318
+ function parseProjectPermissionName(input) {
319
+ const normalized = input.trim().toLowerCase();
320
+ return PROJECT_PERMISSIONS.find((permission) => permission.name === normalized)?.name;
321
+ }
322
+ function suggestSlashWordwheel(input, craftbooks, recentReferences = []) {
323
+ const openMatch = input.match(/^\/open\s+(.*)$/i);
324
+ if (openMatch) {
325
+ const query = normalizeCliOpenLookup(openMatch[1] ?? "");
326
+ const matches = (candidate) => !query || normalizeCliOpenLookup(candidate).includes(query);
327
+ const folders = ["workspace", "artifacts"].filter(matches).map((folder) => ({
328
+ key: `open:folder:${folder}`,
329
+ label: `/open ${folder}`,
330
+ description: `open the project ${folder} folder`,
331
+ submit: `/open ${folder}`,
332
+ completion: `/open ${folder}`
333
+ }));
334
+ const seen = /* @__PURE__ */ new Set();
335
+ const files = [];
336
+ for (const reference2 of recentReferences) {
337
+ if (seen.has(reference2.key)) continue;
338
+ seen.add(reference2.key);
339
+ if (!matches(reference2.path) && !matches(cliOpenBasename(reference2.path))) continue;
340
+ files.push({
341
+ key: `open:reference:${reference2.key}`,
342
+ label: `/open ${reference2.path}`,
343
+ description: `open recent ${reference2.kind}`,
344
+ submit: `/open ${reference2.path}`,
345
+ completion: `/open ${reference2.path}`
346
+ });
347
+ if (files.length >= 8) break;
348
+ }
349
+ return [...folders, ...files];
350
+ }
351
+ const modelMatch = input.match(/^\/model\s+(.*)$/i);
352
+ if (modelMatch) {
353
+ const query = (modelMatch[1] ?? "").trim().toLowerCase();
354
+ return MODEL_SUBCOMMANDS.filter((command) => command.name.startsWith(query)).map((command) => ({
355
+ key: `model:${command.name}`,
356
+ label: `/model ${command.name}`,
357
+ description: command.description,
358
+ submit: `/model ${command.name}`,
359
+ completion: `/model ${command.name}`
360
+ }));
361
+ }
362
+ const permissionMatch = input.match(/^\/(allow|disallow)\s+(.*)$/i);
363
+ if (permissionMatch) {
364
+ const command = (permissionMatch[1] ?? "").toLowerCase();
365
+ const query = (permissionMatch[2] ?? "").trim().toLowerCase();
366
+ return PROJECT_PERMISSIONS.filter((permission) => permission.name.startsWith(query)).map(
367
+ (permission) => ({
368
+ key: `${command}:${permission.name}`,
369
+ label: `/${command} ${permission.name}`,
370
+ description: command === "allow" ? permission.allowDescription : permission.disallowDescription,
371
+ submit: `/${command} ${permission.name}`,
372
+ completion: `/${command} ${permission.name}`
373
+ })
374
+ );
375
+ }
171
376
  const modeMatch = input.match(/^\/mode\s+(.*)$/i);
172
377
  if (modeMatch) {
173
378
  const query = (modeMatch[1] ?? "").trim().toLowerCase();
@@ -192,9 +397,9 @@ function suggestSlashWordwheel(input, craftbooks) {
192
397
  })
193
398
  );
194
399
  }
195
- const startMatch = input.match(/^\/start\s+(.*)$/i);
196
- if (startMatch) {
197
- const query = (startMatch[1] ?? "").trim().toLowerCase();
400
+ const doMatch = input.match(/^\/do\s+(.*)$/i);
401
+ if (doMatch) {
402
+ const query = (doMatch[1] ?? "").trim().toLowerCase();
198
403
  const terms = query.split(/\s+/).filter(Boolean);
199
404
  return craftbooks.filter((book) => {
200
405
  const haystack = `${book.id} ${book.name} ${book.description ?? ""}`.toLowerCase();
@@ -205,10 +410,10 @@ function suggestSlashWordwheel(input, craftbooks) {
205
410
  return leftRank - rightRank || left.name.localeCompare(right.name);
206
411
  }).map((book) => ({
207
412
  key: `craftbook:${book.id}`,
208
- label: `/start ${book.id}`,
413
+ label: `/do ${book.id}`,
209
414
  description: `${book.name} \xB7 ${book.stepCount} ${book.stepCount === 1 ? "step" : "steps"} \xB7 ${book.source}`,
210
- submit: `/start ${book.id}`,
211
- completion: `/start ${book.id}`
415
+ submit: `/do ${book.id}`,
416
+ completion: `/do ${book.id}`
212
417
  }));
213
418
  }
214
419
  return suggestSlashCommands(input).map((command) => ({
@@ -273,6 +478,24 @@ function reduceFeed(rows, env) {
273
478
  open: false
274
479
  }
275
480
  ]);
481
+ case "queue_enqueued": {
482
+ const key = `queue-${event.queueId}`;
483
+ const pending = {
484
+ key,
485
+ sessionId,
486
+ gezelId,
487
+ kind: "pending",
488
+ text: event.preview,
489
+ open: false
490
+ };
491
+ const idx = rows.findIndex((row) => row.key === key);
492
+ if (idx === -1) return cap([...rows, pending]);
493
+ const next = rows.slice();
494
+ next[idx] = pending;
495
+ return next;
496
+ }
497
+ case "queue_removed":
498
+ return rows.filter((row) => row.key !== `queue-${event.queueId}`);
276
499
  case "delta": {
277
500
  const idx = findOpenAssistant(rows, sessionId);
278
501
  const open = idx === -1 ? void 0 : rows[idx];
@@ -340,7 +563,11 @@ function reduceFeed(rows, env) {
340
563
  gezelId: "",
341
564
  kind: "note",
342
565
  text: `task \xB7 ${event.summary}`,
343
- open: false
566
+ open: false,
567
+ taskEvent: {
568
+ kind: event.kind,
569
+ ...event.gezelId ? { gezelId: event.gezelId } : {}
570
+ }
344
571
  }
345
572
  ]);
346
573
  case "error":
@@ -394,7 +621,8 @@ function sessionToFeedRows(session) {
394
621
  }
395
622
  function reduceTurns(turns, env) {
396
623
  const { sessionId, event } = env;
397
- const set = (label) => new Map(turns).set(sessionId, label);
624
+ const prior = turns.get(sessionId);
625
+ const set = (label, outputChars = prior?.outputChars ?? 0, activeToolName = prior?.activeToolName ?? null) => new Map(turns).set(sessionId, { label, outputChars, activeToolName });
398
626
  const clear = () => {
399
627
  if (!turns.has(sessionId)) return turns;
400
628
  const m = new Map(turns);
@@ -403,19 +631,31 @@ function reduceTurns(turns, env) {
403
631
  };
404
632
  switch (event.type) {
405
633
  case "user_message":
406
- return set("thinking\u2026");
634
+ return set("thinking\u2026", 0, null);
407
635
  case "queued":
408
636
  return set(event.aheadOf > 0 ? `queued \xB7 ${event.aheadOf} ahead` : "queued");
409
637
  case "intent":
410
- return set(event.label);
638
+ return set(event.label, void 0, null);
411
639
  case "engine_phase":
412
- return set(phaseLabel(event));
640
+ return set(phaseLabel(event, prior?.outputChars ?? 0), void 0, null);
413
641
  case "delta":
414
- return set("generating");
415
- case "tool":
416
- return set("running tool");
642
+ case "reasoning_delta": {
643
+ const outputChars = (prior?.outputChars ?? 0) + event.content.length;
644
+ return set(generationLabel(outputChars), outputChars, null);
645
+ }
646
+ case "tool_args_delta": {
647
+ const outputChars = (prior?.outputChars ?? 0) + event.content.length;
648
+ const name = event.name.trim() || prior?.activeToolName || null;
649
+ return set(runningToolLabel(name), outputChars, name);
650
+ }
651
+ case "tool": {
652
+ const name = event.name.trim() || prior?.activeToolName || null;
653
+ return set(runningToolLabel(name), void 0, name);
654
+ }
655
+ case "heartbeat":
656
+ return event.label ? set(heartbeatLabel(event.label), void 0, null) : turns;
417
657
  case "awaiting_gezel":
418
- return set("awaiting gezel");
658
+ return set("awaiting gezel", void 0, null);
419
659
  case "error":
420
660
  case "done":
421
661
  return clear();
@@ -423,7 +663,7 @@ function reduceTurns(turns, env) {
423
663
  return turns;
424
664
  }
425
665
  }
426
- function phaseLabel(event) {
666
+ function phaseLabel(event, outputChars) {
427
667
  const pct = event.progress !== void 0 ? ` ${Math.round(event.progress * 100)}%` : "";
428
668
  switch (event.phase) {
429
669
  case "starting":
@@ -433,11 +673,26 @@ function phaseLabel(event) {
433
673
  case "prefill":
434
674
  return `reading prompt${pct}`;
435
675
  case "generating":
436
- return "generating";
676
+ return generationLabel(outputChars);
437
677
  default:
438
678
  return "ready";
439
679
  }
440
680
  }
681
+ function generationLabel(outputChars) {
682
+ if (!Number.isFinite(outputChars) || outputChars <= 0) return "generating";
683
+ const tokens = Math.max(1, Math.round(outputChars / 4));
684
+ return `generating \xB7 ~${tokens.toLocaleString("en-US")} ${tokens === 1 ? "token" : "tokens"}`;
685
+ }
686
+ function runningToolLabel(name) {
687
+ return name ? `running tool \xB7 ${name}` : "running tool";
688
+ }
689
+ function heartbeatLabel(label) {
690
+ const trimmed = label.trim();
691
+ if (/^(thinking|reasoning|streaming|preparing|working)(?:\b|$)/i.test(trimmed) || /^(running|updating|searching|awaiting|using)(?:\b|$)/i.test(trimmed)) {
692
+ return trimmed;
693
+ }
694
+ return runningToolLabel(trimmed || null);
695
+ }
441
696
  function appendNote(rows, text, kind = "note") {
442
697
  const next = [
443
698
  ...rows,
@@ -523,7 +778,7 @@ function toolRowText(call) {
523
778
  }
524
779
  function gezelLabel(gezelId, gezels, boring) {
525
780
  const g = gezels.find((x) => x.id === gezelId);
526
- if (!g) return gezelId;
781
+ if (!g) return boring ? "gezel" : gezelId;
527
782
  if (boring) return g.roleBasedName ?? g.role ?? g.id;
528
783
  return g.role ? `${g.name} \xB7 ${g.role}` : g.name;
529
784
  }
@@ -655,6 +910,7 @@ var TABLE_LOGO = [
655
910
  ].join("\n");
656
911
  var KIND_COLOR = {
657
912
  user: "white",
913
+ pending: "yellow",
658
914
  assistant: "cyan",
659
915
  tool: "yellow",
660
916
  note: "magenta",
@@ -664,7 +920,7 @@ var KIND_COLOR = {
664
920
  function ChatFeed(props) {
665
921
  const { rows, gezels, boring, focusedSessionId, visible = 16 } = props;
666
922
  const shown = rows.slice(Math.max(0, rows.length - visible));
667
- return /* @__PURE__ */ jsx(Box, { flexDirection: "column", flexGrow: 1, children: shown.length === 0 ? /* @__PURE__ */ jsxs(Box, { flexDirection: "row", marginBottom: 1, children: [
923
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", flexGrow: 1, marginBottom: 1, children: shown.length === 0 ? /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
668
924
  /* @__PURE__ */ jsx(Text, { color: "yellow", children: TABLE_LOGO }),
669
925
  /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 3, children: [
670
926
  /* @__PURE__ */ jsxs(Text, { children: [
@@ -678,7 +934,7 @@ function ChatFeed(props) {
678
934
  if (row.kind === "shell" && row.sessionId.startsWith("term-")) {
679
935
  return /* @__PURE__ */ jsx(Text, { wrap: "wrap", children: clip(row.text) }, row.key);
680
936
  }
681
- const who = row.kind === "user" ? "you" : row.gezelId ? gezelLabel(row.gezelId, gezels, boring) : row.kind === "tool" ? "tool" : row.kind === "shell" ? "shell" : row.kind === "error" ? "error" : "system";
937
+ const who = row.kind === "user" ? "you" : row.kind === "pending" ? "pending" : row.gezelId ? gezelLabel(row.gezelId, gezels, boring) : row.kind === "tool" ? "tool" : row.kind === "shell" ? "shell" : row.kind === "error" ? "error" : "system";
682
938
  const isFocused = focusedSessionId && row.sessionId === focusedSessionId;
683
939
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
684
940
  /* @__PURE__ */ jsx(Text, { dimColor: !isFocused, color: isFocused ? "green" : void 0, children: isFocused ? "\u258E" : " " }),
@@ -687,11 +943,33 @@ function ChatFeed(props) {
687
943
  who,
688
944
  ": "
689
945
  ] }),
690
- /* @__PURE__ */ jsx(Text, { color: KIND_COLOR[row.kind], children: clip(row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text) })
946
+ /* @__PURE__ */ jsx(Text, { color: KIND_COLOR[row.kind], dimColor: row.kind === "pending", children: clip(
947
+ row.taskEvent ? taskEventText(row, gezels, boring) : row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text
948
+ ) })
691
949
  ] })
692
950
  ] }, row.key);
693
951
  }) });
694
952
  }
953
+ function taskEventText(row, gezels, boring) {
954
+ const event = row.taskEvent;
955
+ if (!boring || !event?.gezelId) return row.text;
956
+ const actor = gezelLabel(event.gezelId, gezels, true);
957
+ switch (event.kind) {
958
+ case "task.entry.dispatched":
959
+ return row.text.replace(/ handed to .*$/, ` handed to ${actor}`);
960
+ case "tasknote.appended":
961
+ return row.text.replace(/^task · .*? noted on /, `task \xB7 ${actor} noted on `);
962
+ case "tasknote.deleted":
963
+ return row.text.replace(
964
+ /^task · .*? removed a note from /,
965
+ `task \xB7 ${actor} removed a note from `
966
+ );
967
+ case "tasknote.updated":
968
+ return row.text.replace(/^task · .*? edited a note on /, `task \xB7 ${actor} edited a note on `);
969
+ default:
970
+ return row.text;
971
+ }
972
+ }
695
973
  var MAX_CHARS = 8e3;
696
974
  function clip(text) {
697
975
  const t = text.replace(/\s+$/, "");
@@ -769,19 +1047,29 @@ import { useEffect, useState as useState2 } from "react";
769
1047
 
770
1048
  // src/tui/components/EnginePill.tsx
771
1049
  import { Box as Box3, Text as Text3 } from "ink";
772
- import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1050
+ import { jsxs as jsxs3 } from "react/jsx-runtime";
773
1051
  function EnginePill(props) {
774
1052
  const { provider, model, accessMode, busy, label } = props;
775
- const text = formatEngineStatus(provider, model, busy, label, accessMode);
776
- return /* @__PURE__ */ jsx3(Box3, { children: /* @__PURE__ */ jsxs3(Text3, { backgroundColor: busy ? "yellow" : "blackBright", color: busy ? "black" : "white", children: [
777
- " ",
778
- text,
779
- " "
780
- ] }) });
1053
+ const metadata = formatEngineMetadata(provider, model, accessMode);
1054
+ const activity = formatEngineActivity(busy, label);
1055
+ return /* @__PURE__ */ jsxs3(Box3, { children: [
1056
+ /* @__PURE__ */ jsxs3(Text3, { children: [
1057
+ " ",
1058
+ metadata,
1059
+ " \xB7"
1060
+ ] }),
1061
+ /* @__PURE__ */ jsxs3(Text3, { backgroundColor: busy ? "yellow" : "blackBright", color: busy ? "black" : "white", children: [
1062
+ " ",
1063
+ activity,
1064
+ " "
1065
+ ] })
1066
+ ] });
1067
+ }
1068
+ function formatEngineMetadata(provider, model, accessMode) {
1069
+ return [accessMode, formatEngineIdentity(provider, model)].filter(Boolean).join(" \xB7 ");
781
1070
  }
782
- function formatEngineStatus(provider, model, busy, label, accessMode) {
783
- const activity = busy ? `\u25CF ${label ?? "working"}` : "\u25CB idle";
784
- return [activity, accessMode, formatEngineIdentity(provider, model)].filter(Boolean).join(" \xB7 ");
1071
+ function formatEngineActivity(busy, label) {
1072
+ return busy ? `\u25CF ${label ?? "working"}` : "\u25CB idle";
785
1073
  }
786
1074
  function formatEngineIdentity(provider, model) {
787
1075
  const engine = provider === "llama-cpp" ? "llama" : provider ?? "on-device";
@@ -789,7 +1077,7 @@ function formatEngineIdentity(provider, model) {
789
1077
  }
790
1078
 
791
1079
  // src/tui/components/PromptLine.tsx
792
- import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
1080
+ import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs4 } from "react/jsx-runtime";
793
1081
  function PromptLine(props) {
794
1082
  const {
795
1083
  projectName,
@@ -805,6 +1093,7 @@ function PromptLine(props) {
805
1093
  active,
806
1094
  history,
807
1095
  craftbooks,
1096
+ recentOpenReferences,
808
1097
  pendingPrompt,
809
1098
  pendingMode,
810
1099
  onChange,
@@ -812,7 +1101,7 @@ function PromptLine(props) {
812
1101
  } = props;
813
1102
  const [cursor, setCursor] = useState2(history.length);
814
1103
  const [suggestionIndex, setSuggestionIndex] = useState2(0);
815
- const suggestions = active && !pendingPrompt ? suggestSlashWordwheel(value, craftbooks) : [];
1104
+ const suggestions = active && !pendingPrompt ? suggestSlashWordwheel(value, craftbooks, recentOpenReferences) : [];
816
1105
  const activeSuggestionIndex = Math.min(suggestionIndex, Math.max(0, suggestions.length - 1));
817
1106
  const suggestionWindowStart = Math.min(
818
1107
  Math.max(0, activeSuggestionIndex - SLASH_COMMAND_WORDWHEEL_SIZE + 1),
@@ -867,18 +1156,18 @@ function PromptLine(props) {
867
1156
  const placeholder = pendingPrompt ? pendingPrompt : mode === "cli" ? "shell / @tool \u2026 (/chat to exit)" : "message, or /command, !shell, @tool";
868
1157
  return /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", children: [
869
1158
  /* @__PURE__ */ jsxs4(Box4, { children: [
870
- /* @__PURE__ */ jsx4(Text4, { color: "blue", children: projectName }),
871
- /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: " \xB7 " }),
872
- /* @__PURE__ */ jsx4(Text4, { color: "magenta", children: gezelLabel2 }),
1159
+ /* @__PURE__ */ jsx3(Text4, { color: "blue", children: projectName }),
1160
+ /* @__PURE__ */ jsx3(Text4, { dimColor: true, children: " \xB7 " }),
1161
+ /* @__PURE__ */ jsx3(Text4, { color: "magenta", children: gezelLabel2 }),
873
1162
  threadTitle ? /* @__PURE__ */ jsxs4(Fragment2, { children: [
874
- /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: " \xB7 " }),
1163
+ /* @__PURE__ */ jsx3(Text4, { dimColor: true, children: " \xB7 " }),
875
1164
  /* @__PURE__ */ jsxs4(Text4, { color: "cyan", children: [
876
1165
  "\u21B3 ",
877
1166
  compactThreadTitle(threadTitle)
878
1167
  ] })
879
1168
  ] }) : null,
880
- /* @__PURE__ */ jsx4(Text4, { children: " " }),
881
- /* @__PURE__ */ jsx4(
1169
+ /* @__PURE__ */ jsx3(Text4, { children: " " }),
1170
+ /* @__PURE__ */ jsx3(
882
1171
  EnginePill,
883
1172
  {
884
1173
  provider,
@@ -908,8 +1197,8 @@ function PromptLine(props) {
908
1197
  ] })
909
1198
  ] }) : null,
910
1199
  /* @__PURE__ */ jsxs4(Box4, { children: [
911
- /* @__PURE__ */ jsx4(Text4, { color: pendingPrompt ? "yellow" : mode === "cli" ? "green" : "cyan", children: prefix }),
912
- /* @__PURE__ */ jsx4(
1200
+ /* @__PURE__ */ jsx3(Text4, { color: pendingPrompt ? "yellow" : mode === "cli" ? "green" : "cyan", children: prefix }),
1201
+ /* @__PURE__ */ jsx3(
913
1202
  TextInput,
914
1203
  {
915
1204
  value,
@@ -932,7 +1221,7 @@ function compactThreadTitle(title) {
932
1221
  import { Box as Box5, Text as Text5, useInput as useInput3 } from "ink";
933
1222
  import TextInput2 from "ink-text-input";
934
1223
  import { useState as useState3 } from "react";
935
- import { Fragment as Fragment3, jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
1224
+ import { Fragment as Fragment3, jsx as jsx4, jsxs as jsxs5 } from "react/jsx-runtime";
936
1225
  var QUESTION_OPTION_WINDOW_SIZE = 4;
937
1226
  function questionOptionCount(question) {
938
1227
  const choices = question.choices?.length ?? 0;
@@ -1033,11 +1322,11 @@ function QuestionPrompt(props) {
1033
1322
  askerLabel,
1034
1323
  " asks"
1035
1324
  ] }),
1036
- /* @__PURE__ */ jsx5(Text5, { wrap: "wrap", children: question.prompt }),
1325
+ /* @__PURE__ */ jsx4(Text5, { wrap: "wrap", children: question.prompt }),
1037
1326
  writing ? /* @__PURE__ */ jsxs5(Fragment3, { children: [
1038
1327
  /* @__PURE__ */ jsxs5(Box5, { children: [
1039
- /* @__PURE__ */ jsx5(Text5, { color: "cyan", children: "\u203A " }),
1040
- /* @__PURE__ */ jsx5(
1328
+ /* @__PURE__ */ jsx4(Text5, { color: "cyan", children: "\u203A " }),
1329
+ /* @__PURE__ */ jsx4(
1041
1330
  TextInput2,
1042
1331
  {
1043
1332
  value: writeIn,
@@ -1070,8 +1359,8 @@ function QuestionPrompt(props) {
1070
1359
  options.length > QUESTION_OPTION_WINDOW_SIZE ? ` \xB7 ${activeOptionIndex + 1}/${options.length}` : ""
1071
1360
  ] })
1072
1361
  ] }),
1073
- submitting ? /* @__PURE__ */ jsx5(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
1074
- error ? /* @__PURE__ */ jsx5(Text5, { color: "red", children: error }) : null
1362
+ submitting ? /* @__PURE__ */ jsx4(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
1363
+ error ? /* @__PURE__ */ jsx4(Text5, { color: "red", children: error }) : null
1075
1364
  ] });
1076
1365
  }
1077
1366
  function toggleSet(current, value) {
@@ -1083,11 +1372,12 @@ function toggleSet(current, value) {
1083
1372
 
1084
1373
  // src/tui/craftbook-start.ts
1085
1374
  import {
1086
- CRAFTBOOK_ROLE_META
1375
+ CRAFTBOOK_ROLE_META,
1376
+ visibleCatalogItems
1087
1377
  } from "@bendyline/gezel";
1088
- function normalizeCraftbooks(items) {
1378
+ function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
1089
1379
  const byId = /* @__PURE__ */ new Map();
1090
- for (const item of items) {
1380
+ for (const item of visibleCatalogItems(items, showWorkInProgressFeatures)) {
1091
1381
  if (item.manifest.kind !== "craftbook-template") continue;
1092
1382
  const manifest = item.manifest;
1093
1383
  if (byId.has(manifest.id)) continue;
@@ -1166,6 +1456,179 @@ function craftbookStartRequest(book) {
1166
1456
  };
1167
1457
  }
1168
1458
 
1459
+ // src/tui/model-picker.ts
1460
+ import {
1461
+ formatModelAttribution as formatModelAttribution2
1462
+ } from "@bendyline/gezel";
1463
+
1464
+ // src/tui/bootstrap.ts
1465
+ import {
1466
+ computeModelFit,
1467
+ formatModelAttribution,
1468
+ isMoEFromTags,
1469
+ isRecommendedModel,
1470
+ mediaModelFits,
1471
+ pickRecommendedModel
1472
+ } from "@bendyline/gezel";
1473
+ var CHAT_MEMORY_OVERHEAD = {
1474
+ "llama-cpp": 1.2,
1475
+ mlx: 1.3
1476
+ };
1477
+ var NATIVE_TOOLKIT = [
1478
+ "uv",
1479
+ "sd-server",
1480
+ "whisper-server",
1481
+ "llama-server"
1482
+ ];
1483
+ function rankChatModels(items, device, provider) {
1484
+ const candidates = [];
1485
+ for (const item of items) {
1486
+ if (item.manifest.kind !== "chat-model") continue;
1487
+ const manifest = item.manifest;
1488
+ if (manifest.licenseClass !== "open") continue;
1489
+ const source = provider === "mlx" ? manifest.mlx : manifest.llamaCpp;
1490
+ if (!source || provider === "mlx" && manifest.mlx?.disabledReason) continue;
1491
+ const residentBytes = source.residentBytes ?? Math.round(source.approxSizeBytes * CHAT_MEMORY_OVERHEAD[provider]);
1492
+ const fit = computeModelFit({
1493
+ residentBytes,
1494
+ isMoE: isMoEFromTags(manifest.tags),
1495
+ usableBytes: device.usableBytes,
1496
+ totalRamBytes: device.totalRamBytes,
1497
+ gpuVramBytes: device.gpuVramBytes,
1498
+ ...device.budgetBytes !== void 0 ? { admissibleBytes: device.budgetBytes } : {}
1499
+ }).tier;
1500
+ candidates.push({
1501
+ id: manifest.id,
1502
+ name: manifest.name,
1503
+ provider,
1504
+ approxSizeBytes: source.approxSizeBytes,
1505
+ residentBytes,
1506
+ // Effective score: a model the shared gate rejects (restricted license,
1507
+ // no tool support) sorts as unscored rather than leading the list.
1508
+ recoScore: isRecommendedModel(manifest) ? manifest.recoScore ?? 0 : 0,
1509
+ fit,
1510
+ attribution: formatModelAttribution(manifest)
1511
+ });
1512
+ }
1513
+ if (candidates.length === 0) return [];
1514
+ const picked = pickRecommendedModel(
1515
+ candidates.map((model) => ({
1516
+ id: model.id,
1517
+ ...model.recoScore > 0 ? { recoScore: model.recoScore } : {},
1518
+ licenseClass: "open",
1519
+ tags: items.find((item) => item.manifest.kind === "chat-model" && item.manifest.id === model.id)?.manifest?.tags ?? [],
1520
+ residentBytes: model.residentBytes
1521
+ })),
1522
+ device
1523
+ );
1524
+ const comfortable = candidates.filter(
1525
+ (model) => model.fit === "fits" || model.fit === "fits-offload"
1526
+ );
1527
+ const pool = comfortable.length > 0 ? comfortable : candidates;
1528
+ pool.sort(
1529
+ (a, b) => b.recoScore - a.recoScore || fitOrder(a.fit) - fitOrder(b.fit) || b.residentBytes - a.residentBytes || a.name.localeCompare(b.name)
1530
+ );
1531
+ if (!picked) return pool;
1532
+ const bestIndex = pool.findIndex((model) => model.id === picked.id);
1533
+ if (bestIndex < 0) {
1534
+ const best = candidates.find((model) => model.id === picked.id);
1535
+ if (best) pool.unshift(best);
1536
+ return pool;
1537
+ }
1538
+ if (bestIndex > 0) {
1539
+ const [best] = pool.splice(bestIndex, 1);
1540
+ if (best) pool.unshift(best);
1541
+ }
1542
+ return pool;
1543
+ }
1544
+ function bootstrapChatModelLabel(model) {
1545
+ return `${model.name} (${model.attribution})`;
1546
+ }
1547
+ function pickAccessoryModels(input, device) {
1548
+ const output = [];
1549
+ const image = pickCatalogMedia(input.imageItems, device, "image");
1550
+ if (image && !input.installed.image?.has(image.id)) {
1551
+ output.push({
1552
+ kind: "image",
1553
+ id: image.id,
1554
+ name: image.name,
1555
+ approxSizeBytes: image.approxSizeBytes + (image.auxiliaryFiles ?? []).reduce((sum, file) => sum + (file.sizeBytes ?? 0), 0),
1556
+ requiredEngine: "sd-server"
1557
+ });
1558
+ }
1559
+ const recognition = pickScoredOpen(input.recognition, false);
1560
+ if (recognition && !input.installed.recognition?.has(recognition.id)) {
1561
+ output.push({
1562
+ kind: "recognition",
1563
+ id: recognition.id,
1564
+ name: recognition.name,
1565
+ approxSizeBytes: recognition.approxSizeBytes,
1566
+ requiredEngine: "llama-server"
1567
+ });
1568
+ }
1569
+ const stt = pickScoredOpen(input.audio.stt);
1570
+ if (stt && !input.installed.stt?.has(stt.id)) {
1571
+ output.push({
1572
+ kind: "stt",
1573
+ id: stt.id,
1574
+ name: stt.name,
1575
+ approxSizeBytes: stt.approxSizeBytes,
1576
+ requiredEngine: "whisper-server"
1577
+ });
1578
+ }
1579
+ const tts = pickScoredOpen(input.audio.tts);
1580
+ if (tts && !input.installed.tts?.has(tts.id)) {
1581
+ output.push({
1582
+ kind: "tts",
1583
+ id: tts.id,
1584
+ name: tts.name,
1585
+ approxSizeBytes: tts.approxSizeBytes
1586
+ });
1587
+ }
1588
+ const video = pickCatalogMedia(input.videoItems, device, "video");
1589
+ if (video && !input.installed.video?.has(video.id)) {
1590
+ output.push({
1591
+ kind: "video",
1592
+ id: video.id,
1593
+ name: video.name,
1594
+ approxSizeBytes: video.approxSizeBytes,
1595
+ requiredEngine: "uv"
1596
+ });
1597
+ }
1598
+ return output;
1599
+ }
1600
+ function formatDownloadSize(bytes) {
1601
+ if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
1602
+ return `${Math.max(1, Math.round(bytes / 1e6))} MB`;
1603
+ }
1604
+ function fitOrder(fit) {
1605
+ switch (fit) {
1606
+ case "fits":
1607
+ return 0;
1608
+ case "fits-offload":
1609
+ return 1;
1610
+ case "tight":
1611
+ return 2;
1612
+ case "too-big":
1613
+ return 3;
1614
+ }
1615
+ }
1616
+ function pickCatalogMedia(items, device, kind) {
1617
+ const models = items.map((item) => item.manifest).filter((model) => {
1618
+ if (model.licenseClass !== "open" || !model.recoScore) return false;
1619
+ return mediaModelFits(
1620
+ device,
1621
+ kind === "image" ? { minRamGB: model.minRamGB } : { minVramGB: model.minVramGB }
1622
+ );
1623
+ });
1624
+ return pickScoredOpen(models);
1625
+ }
1626
+ function pickScoredOpen(models, requireLicense = true) {
1627
+ return [...models].filter(
1628
+ (model) => typeof model.recoScore === "number" && model.recoScore > 0 && (!requireLicense || model.licenseClass === "open")
1629
+ ).sort((a, b) => (b.recoScore ?? 0) - (a.recoScore ?? 0))[0] ?? null;
1630
+ }
1631
+
1169
1632
  // src/tui/model-picker.ts
1170
1633
  var PROVIDER_ORDER = [
1171
1634
  "mlx",
@@ -1218,9 +1681,10 @@ function configuredModelProviders(config, opts) {
1218
1681
  return providers.sort((a, b) => PROVIDER_ORDER.indexOf(a) - PROVIDER_ORDER.indexOf(b));
1219
1682
  }
1220
1683
  async function loadModelChoices(client, config, platform = process.platform, arch = process.arch) {
1221
- const [copilot, memory] = await Promise.all([
1684
+ const [copilot, memory, catalog] = await Promise.all([
1222
1685
  client.getCopilotStatus().catch(() => null),
1223
- client.getMemoryProfile().catch(() => null)
1686
+ client.getMemoryProfile().catch(() => null),
1687
+ client.listCatalogItems ? client.listCatalogItems("chat-model").catch(() => null) : Promise.resolve(null)
1224
1688
  ]);
1225
1689
  const providers = configuredModelProviders(config, {
1226
1690
  platform,
@@ -1239,21 +1703,78 @@ async function loadModelChoices(client, config, platform = process.platform, arc
1239
1703
  })
1240
1704
  );
1241
1705
  return inventories.flatMap(
1242
- ({ provider, models }) => models.map((model) => ({
1243
- provider,
1244
- model,
1245
- value: `${provider}:${model.id}`,
1246
- label: `${modelProviderLabel(provider)} \xB7 ${model.name}`
1247
- }))
1706
+ ({ provider, models }) => models.map((model) => {
1707
+ const manifest = catalogManifestForModel(catalog?.items ?? [], provider, model.id);
1708
+ const attribution = manifest ? ` (${formatModelAttribution2(manifest)})` : "";
1709
+ return {
1710
+ provider,
1711
+ model,
1712
+ value: `${provider}:${model.id}`,
1713
+ label: `${modelProviderLabel(provider)} \xB7 ${model.name}${attribution}`
1714
+ };
1715
+ })
1248
1716
  );
1249
1717
  }
1250
-
1251
- // src/tui/question-queue.ts
1252
- function plainPendingQuestions(questions) {
1253
- return questions.filter((question) => !question.answer && !question.intent).slice().sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1718
+ async function loadModelDownloadChoices(client, config, platform = process.platform, arch = process.arch) {
1719
+ const [memory, catalog] = await Promise.all([
1720
+ client.getMemoryProfile(),
1721
+ client.listCatalogItems("chat-model")
1722
+ ]);
1723
+ const provider = config.provider === "mlx" || config.provider === "llama-cpp" ? config.provider : memory.platform === "darwin" && platform === "darwin" && arch === "arm64" ? "mlx" : "llama-cpp";
1724
+ const installed = await client.listProviderModels(provider).catch(() => ({ models: [] }));
1725
+ const installedIds = new Set(installed.models.map((model) => model.id));
1726
+ const ranked = rankChatModels(
1727
+ catalog.items,
1728
+ {
1729
+ platform: memory.platform,
1730
+ gpuVramBytes: memory.gpuVramBytes,
1731
+ ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
1732
+ totalRamBytes: memory.totalRamBytes,
1733
+ usableBytes: memory.usableBytes,
1734
+ ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
1735
+ },
1736
+ provider
1737
+ );
1738
+ return ranked.filter((model) => !installedIds.has(model.id)).map((model, index) => ({
1739
+ provider,
1740
+ model,
1741
+ value: `${provider}:${model.id}`,
1742
+ label: bootstrapChatModelLabel(model),
1743
+ hint: [
1744
+ index === 0 ? "recommended" : null,
1745
+ formatDownloadSize(model.approxSizeBytes),
1746
+ modelFitLabel(model.fit)
1747
+ ].filter(Boolean).join(" \xB7 ")
1748
+ }));
1254
1749
  }
1255
- function updatePendingQuestion(questions, question) {
1256
- const withoutCurrent = questions.filter((candidate) => candidate.id !== question.id);
1750
+ function catalogManifestForModel(items, provider, modelId) {
1751
+ for (const item of items) {
1752
+ if (item.manifest.kind !== "chat-model") continue;
1753
+ const manifest = item.manifest;
1754
+ if (manifest.id === modelId) return manifest;
1755
+ if (provider === "ollama" && manifest.ollama?.tag === modelId) return manifest;
1756
+ }
1757
+ return null;
1758
+ }
1759
+ function modelFitLabel(fit) {
1760
+ switch (fit) {
1761
+ case "fits":
1762
+ return "fits this device";
1763
+ case "fits-offload":
1764
+ return "fits with offload";
1765
+ case "tight":
1766
+ return "tight fit";
1767
+ case "too-big":
1768
+ return "larger than recommended";
1769
+ }
1770
+ }
1771
+
1772
+ // src/tui/question-queue.ts
1773
+ function plainPendingQuestions(questions) {
1774
+ return questions.filter((question) => !question.answer && !question.intent).slice().sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1775
+ }
1776
+ function updatePendingQuestion(questions, question) {
1777
+ const withoutCurrent = questions.filter((candidate) => candidate.id !== question.id);
1257
1778
  return plainPendingQuestions(question.answer ? withoutCurrent : [...withoutCurrent, question]);
1258
1779
  }
1259
1780
 
@@ -1332,7 +1853,7 @@ function abortableDelay(ms, signal) {
1332
1853
  }
1333
1854
 
1334
1855
  // src/tui/App.tsx
1335
- import { jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
1856
+ import { jsx as jsx5, jsxs as jsxs6 } from "react/jsx-runtime";
1336
1857
  function useTerminalSize() {
1337
1858
  const { stdout } = useStdout();
1338
1859
  const [size, setSize] = useState4({ rows: stdout?.rows ?? 24, columns: stdout?.columns ?? 80 });
@@ -1348,10 +1869,15 @@ function useTerminalSize() {
1348
1869
  }
1349
1870
  var HELP = [
1350
1871
  "/project \u2014 switch project /gezel \u2014 switch gezel /model \u2014 switch engine + model",
1872
+ "/model download \u2014 choose and download a new on-device model",
1873
+ "/allow edits \u2014 allow tool edits /disallow edits \u2014 make tool edits read-only",
1874
+ "/allow codexedits|claudeedits \u2014 allow provider-native project edits",
1875
+ "/disallow codexedits|claudeedits \u2014 put that provider in read-only plan mode",
1351
1876
  "/mode \u2014 choose read-only, reactive, reactive+tasks, or full-play AI activity",
1352
1877
  "/thread \u2014 switch or start a chat thread",
1878
+ "/open workspace|artifacts|<recent file> \u2014 open a folder or file from chat",
1353
1879
  "/task \u2014 list, inspect, create, edit, assign, or change task status",
1354
- "/start \u2014 choose a craftbook and start it as a task",
1880
+ "/do \u2014 choose a craftbook and start it as a task",
1355
1881
  "/continue \u2014 process due schedules and active tasks in this project",
1356
1882
  "/nightshift start|stop|list \u2014 manage Night Shift",
1357
1883
  "/focus \u2014 send into another active chat /cli \u2014 CLI mode /chat \u2014 chat mode",
@@ -1359,6 +1885,7 @@ var HELP = [
1359
1885
  "/clear \u2014 clear feed /quit \u2014 exit",
1360
1886
  "\u2191/\u2193 \u2014 input history Esc \u2014 interrupt turn Ctrl+C \u2014 interrupt, then again to exit"
1361
1887
  ];
1888
+ var READ_ONLY_BOOT_NOTE = "Note: this folder is read-only to gezel, and can be used for doing analysis and writing reports. Use the /allow edits command to permit gezel to edit this folder's contents.";
1362
1889
  function App(props) {
1363
1890
  const { client } = props;
1364
1891
  const { exit } = useApp();
@@ -1375,6 +1902,11 @@ function App(props) {
1375
1902
  );
1376
1903
  const [startCategoryId, setStartCategoryId] = useState4(null);
1377
1904
  const [modelChoices, setModelChoices] = useState4([]);
1905
+ const [modelDownloadChoices, setModelDownloadChoices] = useState4([]);
1906
+ const [modelDownloadProgress, setModelDownloadProgress] = useState4(
1907
+ null
1908
+ );
1909
+ const [modelDownloadReturn, setModelDownloadReturn] = useState4(null);
1378
1910
  const [modelChoicesLoading, setModelChoicesLoading] = useState4(false);
1379
1911
  const [threadsLoading, setThreadsLoading] = useState4(false);
1380
1912
  const [pendingQuestions, setPendingQuestions] = useState4([]);
@@ -1389,6 +1921,8 @@ function App(props) {
1389
1921
  const [value, setValue] = useState4("");
1390
1922
  const [rows, setRows] = useState4([]);
1391
1923
  const [turns, setTurns] = useState4(() => /* @__PURE__ */ new Map());
1924
+ const [recentOpenReferences, setRecentOpenReferences] = useState4([]);
1925
+ const recentOpenReferencesRef = useRef2([]);
1392
1926
  const [status, setStatus] = useState4("Connecting\u2026");
1393
1927
  const [history, setHistory] = useState4([]);
1394
1928
  const [activeRuns, setActiveRuns] = useState4(() => /* @__PURE__ */ new Set());
@@ -1399,11 +1933,11 @@ function App(props) {
1399
1933
  const pendingQuestion = pendingQuestions[0];
1400
1934
  const { rows: termRows, columns: termColumns } = useTerminalSize();
1401
1935
  const shellColumns = Math.min(500, Math.max(20, termColumns - 2));
1402
- const wordwheelCount = overlay === null && !pendingInput && !pendingQuestion ? suggestSlashWordwheel(value, craftbooks).length : 0;
1936
+ const wordwheelCount = overlay === null && !pendingInput && !pendingQuestion ? suggestSlashWordwheel(value, craftbooks, recentOpenReferences).length : 0;
1403
1937
  const wordwheelRows = wordwheelCount > 0 ? Math.min(SLASH_COMMAND_WORDWHEEL_SIZE, wordwheelCount) + 1 : 0;
1404
1938
  const questionRows = pendingQuestion ? Math.min(QUESTION_OPTION_WINDOW_SIZE, Math.max(1, questionOptionCount(pendingQuestion))) + 4 : 0;
1405
1939
  const modelPickerWindowSize = Math.max(4, Math.min(10, termRows - 12));
1406
- const inventoryPickerRows = overlay === "model" || overlay === "start-category" || overlay === "start-craftbook" ? modelPickerWindowSize + 5 : 0;
1940
+ const inventoryPickerRows = overlay === "model" || overlay === "model-download" || overlay === "start-category" || overlay === "start-craftbook" ? modelPickerWindowSize + 5 : 0;
1407
1941
  const visibleRows = Math.max(
1408
1942
  4,
1409
1943
  termRows - 7 - wordwheelRows - questionRows - inventoryPickerRows
@@ -1418,12 +1952,33 @@ function App(props) {
1418
1952
  const effectiveModel = activeGezel?.model ?? (effectiveProvider ? config?.defaultModel?.[effectiveProvider] : void 0);
1419
1953
  const statusLabel = useMemo(() => {
1420
1954
  if (turns.size === 0) return void 0;
1421
- return focusedSessionId && turns.get(focusedSessionId) || ownSessionId && turns.get(ownSessionId) || turns.values().next().value;
1955
+ const turn = focusedSessionId && turns.get(focusedSessionId) || ownSessionId && turns.get(ownSessionId) || turns.values().next().value;
1956
+ return turn?.label;
1422
1957
  }, [turns, focusedSessionId, ownSessionId]);
1423
1958
  const note = useCallback(
1424
1959
  (text, kind = "note") => setRows((r) => appendNote(r, text, kind)),
1425
1960
  []
1426
1961
  );
1962
+ useEffect3(() => {
1963
+ recentOpenReferencesRef.current = recentOpenReferences;
1964
+ }, [recentOpenReferences]);
1965
+ const gezelIds = useRef2(/* @__PURE__ */ new Set());
1966
+ const gezelRefreshInFlight = useRef2(false);
1967
+ const applyGezelSnapshot = useCallback((next) => {
1968
+ gezelIds.current = new Set(next.map((gezel) => gezel.id));
1969
+ setGezels(next);
1970
+ }, []);
1971
+ const refreshGezels = useCallback(async () => {
1972
+ if (gezelRefreshInFlight.current) return;
1973
+ gezelRefreshInFlight.current = true;
1974
+ try {
1975
+ const result = await client.listGezels();
1976
+ applyGezelSnapshot(result.gezels);
1977
+ } catch {
1978
+ } finally {
1979
+ gezelRefreshInFlight.current = false;
1980
+ }
1981
+ }, [applyGezelSnapshot, client]);
1427
1982
  const taskLoadSequence = useRef2(0);
1428
1983
  const refreshTasks = useCallback(async () => {
1429
1984
  const sequence = ++taskLoadSequence.current;
@@ -1439,13 +1994,13 @@ function App(props) {
1439
1994
  const sequence = ++craftbookLoadSequence.current;
1440
1995
  const result = await client.listProjectCraftbooks(projectId);
1441
1996
  if (sequence !== craftbookLoadSequence.current) return [];
1442
- const next = normalizeCraftbooks(result.items);
1997
+ const next = normalizeCraftbooks(result.items, config?.showWorkInProgressFeatures === true);
1443
1998
  setCraftbooks(next);
1444
1999
  setCraftbookProjectType(result.projectType ?? null);
1445
2000
  setSuggestedCraftbookIds(new Set(result.suggestedIds ?? []));
1446
2001
  setCraftbooksNeedingSetup(new Set(Object.keys(result.missingToolsets)));
1447
2002
  return next;
1448
- }, [client, projectId]);
2003
+ }, [client, config?.showWorkInProgressFeatures, projectId]);
1449
2004
  useProjectEvents(
1450
2005
  client,
1451
2006
  projectId,
@@ -1453,6 +2008,14 @@ function App(props) {
1453
2008
  (env) => {
1454
2009
  setRows((r) => reduceFeed(r, env));
1455
2010
  setTurns((t) => reduceTurns(t, env));
2011
+ const observedReferences = cliOpenReferencesFromEvent(env);
2012
+ if (observedReferences.length > 0) {
2013
+ setRecentOpenReferences(
2014
+ (current) => rememberCliOpenReferences(current, observedReferences)
2015
+ );
2016
+ }
2017
+ const eventGezelId = env.gezelId || (env.event.type === "task_event" ? env.event.gezelId : void 0);
2018
+ if (eventGezelId && !gezelIds.current.has(eventGezelId)) void refreshGezels();
1456
2019
  if (env.event.type === "task_event") void refreshTasks();
1457
2020
  if (env.event.type === "user_message" && env.sessionId === ownSessionId) {
1458
2021
  const nextTitle = env.event.message.content.slice(0, 60).trim() || "Untitled";
@@ -1468,7 +2031,7 @@ function App(props) {
1468
2031
  setPendingQuestions((questions) => updatePendingQuestion(questions, question));
1469
2032
  }
1470
2033
  },
1471
- [ownSessionId, refreshTasks]
2034
+ [ownSessionId, refreshGezels, refreshTasks]
1472
2035
  )
1473
2036
  );
1474
2037
  useTerminalEvents(
@@ -1507,7 +2070,11 @@ function App(props) {
1507
2070
  const ensureSession = useCallback(
1508
2071
  async (gezelId, pid) => {
1509
2072
  try {
1510
- const session = await client.createChatSession({ gezelId, projectId: pid });
2073
+ const session = await client.createChatSession({
2074
+ gezelId,
2075
+ projectId: pid,
2076
+ roleBasedNameOnlyMode: boring
2077
+ });
1511
2078
  setOwnSessionId(session.id);
1512
2079
  setFocusedSessionId(session.id);
1513
2080
  setActiveThreadTitle(displayThreadTitle(session.title));
@@ -1517,7 +2084,7 @@ function App(props) {
1517
2084
  return false;
1518
2085
  }
1519
2086
  },
1520
- [client, note]
2087
+ [client, note, boring]
1521
2088
  );
1522
2089
  const switchProject = useCallback(
1523
2090
  async (id) => {
@@ -1530,6 +2097,7 @@ function App(props) {
1530
2097
  setProjectName(project.name);
1531
2098
  setActiveGezelId(gezelId);
1532
2099
  setRows([]);
2100
+ setRecentOpenReferences([]);
1533
2101
  setTurns(/* @__PURE__ */ new Map());
1534
2102
  setActiveRuns(/* @__PURE__ */ new Set());
1535
2103
  setPendingInput(null);
@@ -1551,6 +2119,56 @@ function App(props) {
1551
2119
  },
1552
2120
  [client, ensureSession, note, projectId, projects]
1553
2121
  );
2122
+ const openModelPicker = useCallback(async () => {
2123
+ if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2124
+ if (activeGezel.fixedFunction) {
2125
+ return note("this gezel runs a fixed tool and does not use a chat model.", "error");
2126
+ }
2127
+ if (modelChoicesLoading) return note("model choices are already loading.");
2128
+ setModelChoicesLoading(true);
2129
+ note("loading available engines and models\u2026");
2130
+ try {
2131
+ const choices = await loadModelChoices(client, config ?? await client.getConfig());
2132
+ setModelChoices(choices);
2133
+ setOverlay("model");
2134
+ } catch (err) {
2135
+ note(`could not load models: ${errMsg(err)}`, "error");
2136
+ } finally {
2137
+ setModelChoicesLoading(false);
2138
+ }
2139
+ }, [activeGezel, activeGezelId, client, config, modelChoicesLoading, note]);
2140
+ const openModelDownloadPicker = useCallback(
2141
+ async (returnTo = null) => {
2142
+ if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2143
+ if (activeGezel.fixedFunction) {
2144
+ return note("this gezel runs a fixed tool and does not use a chat model.", "error");
2145
+ }
2146
+ if (modelChoicesLoading) return note("model choices are already loading.");
2147
+ setOverlay(null);
2148
+ setModelChoicesLoading(true);
2149
+ note("finding on-device models that fit this machine\u2026");
2150
+ try {
2151
+ const choices = await loadModelDownloadChoices(
2152
+ client,
2153
+ config ?? await client.getConfig()
2154
+ );
2155
+ if (choices.length === 0) {
2156
+ note("no additional compatible on-device models are available to download.");
2157
+ if (returnTo === "model") await openModelPicker();
2158
+ return;
2159
+ }
2160
+ setModelDownloadChoices(choices);
2161
+ setModelDownloadProgress(null);
2162
+ setModelDownloadReturn(returnTo);
2163
+ setOverlay("model-download");
2164
+ } catch (err) {
2165
+ note(`could not load downloadable models: ${errMsg(err)}`, "error");
2166
+ } finally {
2167
+ setModelChoicesLoading(false);
2168
+ }
2169
+ },
2170
+ [activeGezel, activeGezelId, client, config, modelChoicesLoading, note, openModelPicker]
2171
+ );
1554
2172
  const openThreadPicker = useCallback(async () => {
1555
2173
  if (!activeGezelId) return note("no active gezel yet.", "error");
1556
2174
  if (threadsLoading) return;
@@ -1577,6 +2195,7 @@ function App(props) {
1577
2195
  setFocusedSessionId(session.id);
1578
2196
  setActiveThreadTitle(displayThreadTitle(session.title));
1579
2197
  setRows(sessionToFeedRows(session));
2198
+ setRecentOpenReferences(cliOpenReferencesFromSession(session));
1580
2199
  } catch (err) {
1581
2200
  note(`could not switch thread: ${errMsg(err)}`, "error");
1582
2201
  }
@@ -1587,16 +2206,21 @@ function App(props) {
1587
2206
  setOverlay(null);
1588
2207
  if (!activeGezelId) return note("no active gezel yet.", "error");
1589
2208
  try {
1590
- const session = await client.createChatSession({ gezelId: activeGezelId, projectId });
2209
+ const session = await client.createChatSession({
2210
+ gezelId: activeGezelId,
2211
+ projectId,
2212
+ roleBasedNameOnlyMode: boring
2213
+ });
1591
2214
  setOwnSessionId(session.id);
1592
2215
  setFocusedSessionId(session.id);
1593
2216
  setActiveThreadTitle(displayThreadTitle(session.title));
1594
2217
  setRows([]);
2218
+ setRecentOpenReferences([]);
1595
2219
  setThreads((current) => [session, ...current.filter((item) => item.id !== session.id)]);
1596
2220
  } catch (err) {
1597
2221
  note(`could not start a thread: ${errMsg(err)}`, "error");
1598
2222
  }
1599
- }, [activeGezelId, client, note, projectId]);
2223
+ }, [activeGezelId, client, note, projectId, boring]);
1600
2224
  useEffect3(() => {
1601
2225
  let cancelled = false;
1602
2226
  (async () => {
@@ -1608,22 +2232,31 @@ function App(props) {
1608
2232
  ]);
1609
2233
  if (cancelled) return;
1610
2234
  setConfig(cfg);
1611
- setGezels(gz.gezels);
1612
- setProjects(
1613
- pj.projects.map((p) => ({
1614
- id: p.id,
1615
- name: p.name,
1616
- workingDir: p.workingDir,
1617
- voormanGezelId: p.voormanGezelId,
1618
- managedWorkspaceWritePolicy: p.managedWorkspaceWritePolicy,
1619
- allowGezelWrites: p.allowGezelWrites,
1620
- codexPermissionMode: p.codexPermissionMode,
1621
- claudePermissionMode: p.claudePermissionMode
1622
- }))
1623
- );
2235
+ applyGezelSnapshot(gz.gezels);
2236
+ const projectRows = pj.projects.map((p) => ({
2237
+ id: p.id,
2238
+ name: p.name,
2239
+ workingDir: p.workingDir,
2240
+ voormanGezelId: p.voormanGezelId,
2241
+ managedWorkspaceWritePolicy: p.managedWorkspaceWritePolicy,
2242
+ allowGezelWrites: p.allowGezelWrites,
2243
+ codexPermissionMode: p.codexPermissionMode,
2244
+ claudePermissionMode: p.claudePermissionMode
2245
+ }));
2246
+ setProjects(projectRows);
1624
2247
  const gezelId = props.initialGezelId;
2248
+ const initialGezel = gz.gezels.find((gezel) => gezel.id === gezelId);
2249
+ const initialProject = projectRows.find((project) => project.id === projectId);
1625
2250
  setActiveGezelId(gezelId);
1626
2251
  setStatus(null);
2252
+ if (activeAccessMode({
2253
+ provider: initialGezel?.provider ?? cfg.provider,
2254
+ project: initialProject,
2255
+ gezel: initialGezel,
2256
+ config: cfg
2257
+ }) === "read-only") {
2258
+ note(READ_ONLY_BOOT_NOTE);
2259
+ }
1627
2260
  await ensureSession(gezelId, projectId);
1628
2261
  } catch (err) {
1629
2262
  if (!cancelled) setStatus(`Failed to connect: ${errMsg(err)}`);
@@ -1695,7 +2328,8 @@ function App(props) {
1695
2328
  for (const r of rows) {
1696
2329
  if (r.sessionId === "local" || r.sessionId.startsWith("term-")) continue;
1697
2330
  if (!seen.has(r.sessionId)) {
1698
- const label = gezels.find((g) => g.id === r.gezelId)?.name ?? (r.gezelId || r.sessionId);
2331
+ const gezel = gezels.find((candidate) => candidate.id === r.gezelId);
2332
+ const label = boring ? gezelLabel(r.gezelId, gezels, true) : gezel?.name ?? (r.gezelId || r.sessionId);
1699
2333
  seen.set(r.sessionId, label);
1700
2334
  }
1701
2335
  }
@@ -1706,7 +2340,7 @@ function App(props) {
1706
2340
  items.push({ label, value: sid });
1707
2341
  }
1708
2342
  return items;
1709
- }, [rows, gezels, ownSessionId, gezelLine]);
2343
+ }, [rows, gezels, ownSessionId, gezelLine, boring]);
1710
2344
  const cancelActive = useCallback(async () => {
1711
2345
  const sessions = [...turns.keys()];
1712
2346
  const runs = [...activeRuns];
@@ -1739,12 +2373,46 @@ function App(props) {
1739
2373
  },
1740
2374
  [client, note]
1741
2375
  );
2376
+ const applyProjectPermission = useCallback(
2377
+ async (permission, allowed) => {
2378
+ const permissionName = parseProjectPermissionName(permission);
2379
+ if (!permissionName) {
2380
+ note(`usage: /${allowed ? "allow" : "disallow"} ${PROJECT_PERMISSION_USAGE}`, "error");
2381
+ return;
2382
+ }
2383
+ try {
2384
+ const patch = permissionName === "edits" ? { managedWorkspaceWritePolicy: allowed ? "allow" : "deny" } : permissionName === "codexedits" ? { codexPermissionMode: allowed ? "edit" : "plan" } : { claudePermissionMode: allowed ? "acceptEdits" : "plan" };
2385
+ const updated = await client.updateProject(projectId, patch);
2386
+ setProjects(
2387
+ (current) => current.map(
2388
+ (project) => project.id === projectId ? { ...project, ...updated } : project
2389
+ )
2390
+ );
2391
+ if (permissionName === "edits") {
2392
+ note(
2393
+ allowed ? `Project edits allowed. Built-in tools and background work can now modify ${projectName}.` : `Project edits disallowed. Built-in tools and background work are now read-only in ${projectName}.`
2394
+ );
2395
+ } else {
2396
+ const provider = permissionName === "codexedits" ? "Codex" : "Claude";
2397
+ note(
2398
+ allowed ? `${provider} edits allowed. ${provider} sessions can now modify ${projectName}.` : `${provider} edits disallowed. ${provider} sessions are now read-only in ${projectName}.`
2399
+ );
2400
+ }
2401
+ } catch (err) {
2402
+ note(`could not change project permission: ${errMsg(err)}`, "error");
2403
+ }
2404
+ },
2405
+ [client, note, projectId, projectName]
2406
+ );
1742
2407
  const startCraftbook = useCallback(
1743
2408
  async (book) => {
1744
2409
  setOverlay(null);
1745
2410
  note(`starting ${book.name}\u2026`);
1746
2411
  try {
1747
- const created = await client.createTask(projectId, craftbookStartRequest(book));
2412
+ const created = await client.createTask(projectId, {
2413
+ ...craftbookStartRequest(book),
2414
+ roleBasedNameOnlyMode: boring
2415
+ });
1748
2416
  rememberTask(created);
1749
2417
  setManagedTaskRef(created.ref);
1750
2418
  note(`started ${created.ref} \u2014 ${created.title}`);
@@ -1752,7 +2420,7 @@ function App(props) {
1752
2420
  note(`could not start ${book.name}: ${errMsg(err)}`, "error");
1753
2421
  }
1754
2422
  },
1755
- [client, note, projectId, rememberTask]
2423
+ [boring, client, note, projectId, rememberTask]
1756
2424
  );
1757
2425
  const submitTaskPrompt = useCallback(
1758
2426
  async (raw) => {
@@ -1771,7 +2439,8 @@ function App(props) {
1771
2439
  title: text,
1772
2440
  description: `${text} \u2014 complete this task and verify that the result meets the requested outcome.`,
1773
2441
  assignee: { kind: "user" },
1774
- steps: [{ name: "Main" }]
2442
+ steps: [{ name: "Main" }],
2443
+ roleBasedNameOnlyMode: boring
1775
2444
  });
1776
2445
  rememberTask(created);
1777
2446
  setManagedTaskRef(created.ref);
@@ -1790,7 +2459,7 @@ function App(props) {
1790
2459
  note(`task update failed: ${errMsg(err)}`, "error");
1791
2460
  }
1792
2461
  },
1793
- [client, note, projectId, rememberTask, taskPrompt, tasks]
2462
+ [boring, client, note, projectId, rememberTask, taskPrompt, tasks]
1794
2463
  );
1795
2464
  const applyTaskStatus = useCallback(
1796
2465
  async (status2) => {
@@ -1855,7 +2524,10 @@ function App(props) {
1855
2524
  const target = focusedSessionId ?? ownSessionId;
1856
2525
  if (!target) return note("no active session yet.", "error");
1857
2526
  try {
1858
- await client.sendToChatSession(target, parsed.text);
2527
+ await client.sendToChatSession(
2528
+ target,
2529
+ turns.has(target) ? { message: parsed.text, nudge: true } : parsed.text
2530
+ );
1859
2531
  } catch (err) {
1860
2532
  note(`send failed: ${errMsg(err)}`, "error");
1861
2533
  }
@@ -1918,7 +2590,8 @@ function App(props) {
1918
2590
  note,
1919
2591
  pendingInput,
1920
2592
  submitTaskPrompt,
1921
- taskPrompt
2593
+ taskPrompt,
2594
+ turns
1922
2595
  ]
1923
2596
  );
1924
2597
  const runCommand = useCallback(
@@ -1932,35 +2605,52 @@ function App(props) {
1932
2605
  return setOverlay("project");
1933
2606
  case "gezel":
1934
2607
  return setOverlay("gezel");
2608
+ case "allow":
2609
+ await applyProjectPermission(rest, true);
2610
+ return;
2611
+ case "disallow":
2612
+ await applyProjectPermission(rest, false);
2613
+ return;
1935
2614
  case "mode":
1936
2615
  if (!rest.trim()) return setOverlay("engagement-mode");
1937
2616
  await applyEngagementMode(rest);
1938
2617
  return;
1939
2618
  case "model": {
1940
- if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
1941
- if (activeGezel.fixedFunction) {
1942
- return note("this gezel runs a fixed tool and does not use a chat model.", "error");
2619
+ const subcommand = rest.trim().toLowerCase();
2620
+ if (!subcommand) return openModelPicker();
2621
+ if (subcommand === "download") return openModelDownloadPicker();
2622
+ return note("usage: /model [download]", "error");
2623
+ }
2624
+ case "thread":
2625
+ await openThreadPicker();
2626
+ return;
2627
+ case "open": {
2628
+ const target = resolveCliOpenTarget(rest, recentOpenReferencesRef.current);
2629
+ if (!target) {
2630
+ return note(
2631
+ "usage: /open workspace|artifacts|<recent file> (type /open and a space to browse)",
2632
+ "error"
2633
+ );
1943
2634
  }
1944
- if (modelChoicesLoading) return note("model choices are already loading.");
1945
- setModelChoicesLoading(true);
1946
- note("loading available engines and models\u2026");
1947
2635
  try {
1948
- const choices = await loadModelChoices(client, config ?? await client.getConfig());
1949
- if (choices.length === 0) {
1950
- return note("no engines with available chat models were found.", "error");
2636
+ if (target.type === "folder") {
2637
+ const result = await client.revealProject(projectId, target.folder);
2638
+ note(`opened ${target.folder}: ${result.path}`);
2639
+ } else {
2640
+ const result = await client.revealProjectReference(target.reference.projectId, {
2641
+ kind: target.reference.kind,
2642
+ path: target.reference.path
2643
+ });
2644
+ setRecentOpenReferences(
2645
+ (current) => rememberCliOpenReferences(current, [target.reference])
2646
+ );
2647
+ note(`revealed ${target.reference.path}: ${result.path}`);
1951
2648
  }
1952
- setModelChoices(choices);
1953
- setOverlay("model");
1954
2649
  } catch (err) {
1955
- note(`could not load models: ${errMsg(err)}`, "error");
1956
- } finally {
1957
- setModelChoicesLoading(false);
2650
+ note(`open failed: ${errMsg(err)}`, "error");
1958
2651
  }
1959
2652
  return;
1960
2653
  }
1961
- case "thread":
1962
- await openThreadPicker();
1963
- return;
1964
2654
  case "task":
1965
2655
  setManagedTaskRef(null);
1966
2656
  return setOverlay("task");
@@ -2007,7 +2697,7 @@ function App(props) {
2007
2697
  }
2008
2698
  return;
2009
2699
  }
2010
- case "start": {
2700
+ case "do": {
2011
2701
  let available = craftbooks;
2012
2702
  if (available.length === 0) {
2013
2703
  try {
@@ -2025,7 +2715,7 @@ function App(props) {
2025
2715
  }
2026
2716
  const book = findCraftbook(available, rest);
2027
2717
  if (!book) {
2028
- return note(`craftbook not found: ${rest.trim()} (try /start)`, "error");
2718
+ return note(`craftbook not found: ${rest.trim()} (try /do)`, "error");
2029
2719
  }
2030
2720
  await startCraftbook(book);
2031
2721
  return;
@@ -2083,15 +2773,14 @@ function App(props) {
2083
2773
  }
2084
2774
  },
2085
2775
  [
2086
- activeGezel,
2087
- activeGezelId,
2088
2776
  applyEngagementMode,
2777
+ applyProjectPermission,
2089
2778
  client,
2090
- config,
2091
2779
  craftbooks,
2092
- modelChoicesLoading,
2093
2780
  note,
2094
2781
  exit,
2782
+ openModelDownloadPicker,
2783
+ openModelPicker,
2095
2784
  openThreadPicker,
2096
2785
  projectId,
2097
2786
  projectName,
@@ -2100,11 +2789,10 @@ function App(props) {
2100
2789
  startCraftbook
2101
2790
  ]
2102
2791
  );
2103
- const applyModelChoice = useCallback(
2104
- async (value2) => {
2792
+ const applyModelSelection = useCallback(
2793
+ async (choice) => {
2105
2794
  setOverlay(null);
2106
2795
  if (!activeGezelId || !activeGezel || !config) return;
2107
- const choice = modelChoices.find((item) => item.value === value2);
2108
2796
  const nextProvider = choice?.provider ?? null;
2109
2797
  const nextModel = choice?.model.id;
2110
2798
  const providerChanged = (activeGezel.provider ?? null) !== nextProvider;
@@ -2129,8 +2817,80 @@ function App(props) {
2129
2817
  note(`could not switch model: ${errMsg(err)}`, "error");
2130
2818
  }
2131
2819
  },
2132
- [activeGezel, activeGezelId, client, config, ensureSession, modelChoices, note, projectId]
2820
+ [activeGezel, activeGezelId, client, config, ensureSession, note, projectId]
2133
2821
  );
2822
+ const applyModelChoice = useCallback(
2823
+ async (value2) => {
2824
+ await applyModelSelection(modelChoices.find((item) => item.value === value2));
2825
+ },
2826
+ [applyModelSelection, modelChoices]
2827
+ );
2828
+ const installModelDownload = useCallback(
2829
+ async (value2) => {
2830
+ const choice = modelDownloadChoices.find((candidate) => candidate.value === value2);
2831
+ if (!choice) return;
2832
+ let terminalError = null;
2833
+ setModelDownloadProgress({
2834
+ choice,
2835
+ bytesWritten: 0,
2836
+ totalBytes: choice.model.approxSizeBytes,
2837
+ pct: 0,
2838
+ phase: "starting"
2839
+ });
2840
+ const onEvent = (event) => {
2841
+ if (event.type === "error") terminalError = event.error;
2842
+ const progress = readModelDownloadProgress(choice, event);
2843
+ if (progress) setModelDownloadProgress(progress);
2844
+ };
2845
+ try {
2846
+ if (choice.provider === "mlx") {
2847
+ await client.installMlxModel(choice.model.id, onEvent);
2848
+ } else {
2849
+ await client.installLlamaCppModel(choice.model.id, onEvent);
2850
+ }
2851
+ if (terminalError) throw new Error(terminalError);
2852
+ const installedChoice = {
2853
+ provider: choice.provider,
2854
+ model: {
2855
+ id: choice.model.id,
2856
+ name: choice.model.name
2857
+ },
2858
+ value: choice.value,
2859
+ label: `${modelProviderLabel(choice.provider)} \xB7 ${choice.model.name}`
2860
+ };
2861
+ setModelChoices((current) => [
2862
+ ...current.filter((candidate) => candidate.value !== installedChoice.value),
2863
+ installedChoice
2864
+ ]);
2865
+ setModelDownloadProgress(null);
2866
+ note(`downloaded ${choice.model.name}; switching this gezel to it\u2026`);
2867
+ await applyModelSelection(installedChoice);
2868
+ } catch (err) {
2869
+ setModelDownloadProgress(null);
2870
+ setOverlay("model-download");
2871
+ note(`model download failed: ${errMsg(err)}`, "error");
2872
+ }
2873
+ },
2874
+ [applyModelSelection, client, modelDownloadChoices, note]
2875
+ );
2876
+ const cancelModelDownload = useCallback(async () => {
2877
+ const progress = modelDownloadProgress;
2878
+ if (!progress) return;
2879
+ try {
2880
+ if (progress.choice.provider === "mlx") {
2881
+ await client.cancelMlxModelInstall(progress.choice.model.id);
2882
+ } else {
2883
+ await client.cancelLlamaCppModelInstall(progress.choice.model.id);
2884
+ }
2885
+ note(`canceled the ${progress.choice.model.name} download.`);
2886
+ } catch (err) {
2887
+ note(`could not cancel model download: ${errMsg(err)}`, "error");
2888
+ } finally {
2889
+ setModelDownloadProgress(null);
2890
+ if (modelDownloadReturn === "model") await openModelPicker();
2891
+ else setOverlay(null);
2892
+ }
2893
+ }, [client, modelDownloadProgress, modelDownloadReturn, note, openModelPicker]);
2134
2894
  const onSubmit = useCallback(
2135
2895
  (raw) => {
2136
2896
  setValue("");
@@ -2176,10 +2936,10 @@ function App(props) {
2176
2936
  }
2177
2937
  );
2178
2938
  if (status) {
2179
- return /* @__PURE__ */ jsx6(Box6, { flexDirection: "column", padding: 1, children: /* @__PURE__ */ jsx6(Text6, { color: status.startsWith("Failed") ? "red" : "cyan", children: status }) });
2939
+ return /* @__PURE__ */ jsx5(Box6, { flexDirection: "column", padding: 1, children: /* @__PURE__ */ jsx5(Text6, { color: status.startsWith("Failed") ? "red" : "cyan", children: status }) });
2180
2940
  }
2181
2941
  return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", padding: 1, children: [
2182
- /* @__PURE__ */ jsx6(
2942
+ /* @__PURE__ */ jsx5(
2183
2943
  ChatFeed,
2184
2944
  {
2185
2945
  rows,
@@ -2189,7 +2949,7 @@ function App(props) {
2189
2949
  visible: visibleRows
2190
2950
  }
2191
2951
  ),
2192
- overlay === "project" ? /* @__PURE__ */ jsx6(
2952
+ overlay === "project" ? /* @__PURE__ */ jsx5(
2193
2953
  Picker,
2194
2954
  {
2195
2955
  title: "Switch project",
@@ -2198,7 +2958,7 @@ function App(props) {
2198
2958
  onSelect: (id) => void switchProject(id)
2199
2959
  }
2200
2960
  ) : null,
2201
- overlay === "gezel" ? /* @__PURE__ */ jsx6(
2961
+ overlay === "gezel" ? /* @__PURE__ */ jsx5(
2202
2962
  Picker,
2203
2963
  {
2204
2964
  title: "Switch gezel",
@@ -2218,7 +2978,7 @@ function App(props) {
2218
2978
  }
2219
2979
  }
2220
2980
  ) : null,
2221
- overlay === "engagement-mode" ? /* @__PURE__ */ jsx6(
2981
+ overlay === "engagement-mode" ? /* @__PURE__ */ jsx5(
2222
2982
  Picker,
2223
2983
  {
2224
2984
  title: "Choose AI engagement mode",
@@ -2232,16 +2992,21 @@ function App(props) {
2232
2992
  onSelect: (selected) => void applyEngagementMode(selected)
2233
2993
  }
2234
2994
  ) : null,
2235
- overlay === "model" ? /* @__PURE__ */ jsx6(
2995
+ overlay === "model" ? /* @__PURE__ */ jsx5(
2236
2996
  Picker,
2237
2997
  {
2238
- title: "Choose engine + model",
2998
+ title: "Choose engine + model - models are downloaded from Hugging Face (huggingface.co)",
2239
2999
  items: [
2240
3000
  {
2241
3001
  label: "Use default",
2242
3002
  value: "__default__",
2243
3003
  hint: `${modelProviderLabel(config?.provider ?? "llama-cpp")}${config?.defaultModel?.[config.provider] ? ` \xB7 ${config.defaultModel[config.provider]}` : ""}`
2244
3004
  },
3005
+ {
3006
+ label: "Download a new model\u2026",
3007
+ value: "__download__",
3008
+ hint: "browse on-device models ranked for this machine"
3009
+ },
2245
3010
  ...modelChoices.map((choice) => ({
2246
3011
  label: choice.label,
2247
3012
  value: choice.value,
@@ -2251,10 +3016,36 @@ function App(props) {
2251
3016
  initialValue: activeGezel?.provider && activeGezel.model ? `${activeGezel.provider}:${activeGezel.model}` : "__default__",
2252
3017
  windowSize: modelPickerWindowSize,
2253
3018
  onCancel: () => setOverlay(null),
2254
- onSelect: (value2) => void applyModelChoice(value2)
3019
+ onSelect: (value2) => {
3020
+ if (value2 === "__download__") void openModelDownloadPicker("model");
3021
+ else void applyModelChoice(value2);
3022
+ }
2255
3023
  }
2256
3024
  ) : null,
2257
- overlay === "start-category" ? /* @__PURE__ */ jsx6(
3025
+ overlay === "model-download" ? modelDownloadProgress ? /* @__PURE__ */ jsx5(
3026
+ ModelDownloadProgressPanel,
3027
+ {
3028
+ progress: modelDownloadProgress,
3029
+ onCancel: () => void cancelModelDownload()
3030
+ }
3031
+ ) : /* @__PURE__ */ jsx5(
3032
+ Picker,
3033
+ {
3034
+ title: "Download and use an on-device model",
3035
+ items: modelDownloadChoices.map((choice) => ({
3036
+ label: choice.label,
3037
+ value: choice.value,
3038
+ hint: choice.hint
3039
+ })),
3040
+ windowSize: modelPickerWindowSize,
3041
+ onCancel: () => {
3042
+ if (modelDownloadReturn === "model") setOverlay("model");
3043
+ else setOverlay(null);
3044
+ },
3045
+ onSelect: (value2) => void installModelDownload(value2)
3046
+ }
3047
+ ) : null,
3048
+ overlay === "start-category" ? /* @__PURE__ */ jsx5(
2258
3049
  Picker,
2259
3050
  {
2260
3051
  title: "Choose a craftbook category",
@@ -2271,7 +3062,7 @@ function App(props) {
2271
3062
  }
2272
3063
  }
2273
3064
  ) : null,
2274
- overlay === "start-craftbook" ? /* @__PURE__ */ jsx6(
3065
+ overlay === "start-craftbook" ? /* @__PURE__ */ jsx5(
2275
3066
  Picker,
2276
3067
  {
2277
3068
  title: startCategory?.label ?? "Start a craftbook",
@@ -2288,7 +3079,7 @@ function App(props) {
2288
3079
  }
2289
3080
  }
2290
3081
  ) : null,
2291
- overlay === "thread" ? /* @__PURE__ */ jsx6(
3082
+ overlay === "thread" ? /* @__PURE__ */ jsx5(
2292
3083
  Picker,
2293
3084
  {
2294
3085
  title: `Threads with ${gezelLine}`,
@@ -2309,7 +3100,7 @@ function App(props) {
2309
3100
  }
2310
3101
  }
2311
3102
  ) : null,
2312
- overlay === "task" ? /* @__PURE__ */ jsx6(
3103
+ overlay === "task" ? /* @__PURE__ */ jsx5(
2313
3104
  Picker,
2314
3105
  {
2315
3106
  title: `Tasks \xB7 ${tasks.filter((task) => task.status === "active").length} active`,
@@ -2334,7 +3125,7 @@ function App(props) {
2334
3125
  }
2335
3126
  }
2336
3127
  ) : null,
2337
- overlay === "task-actions" && managedTask ? /* @__PURE__ */ jsx6(
3128
+ overlay === "task-actions" && managedTask ? /* @__PURE__ */ jsx5(
2338
3129
  Picker,
2339
3130
  {
2340
3131
  title: `${managedTask.ref} \xB7 ${managedTask.status}`,
@@ -2369,7 +3160,7 @@ function App(props) {
2369
3160
  }
2370
3161
  }
2371
3162
  ) : null,
2372
- overlay === "task-status" && managedTask ? /* @__PURE__ */ jsx6(
3163
+ overlay === "task-status" && managedTask ? /* @__PURE__ */ jsx5(
2373
3164
  Picker,
2374
3165
  {
2375
3166
  title: `Set ${managedTask.ref} status`,
@@ -2378,7 +3169,7 @@ function App(props) {
2378
3169
  onSelect: (status2) => void applyTaskStatus(status2)
2379
3170
  }
2380
3171
  ) : null,
2381
- overlay === "task-assignee" && managedTask ? /* @__PURE__ */ jsx6(
3172
+ overlay === "task-assignee" && managedTask ? /* @__PURE__ */ jsx5(
2382
3173
  Picker,
2383
3174
  {
2384
3175
  title: `Assign ${managedTask.ref}`,
@@ -2398,7 +3189,7 @@ function App(props) {
2398
3189
  onSelect: (assignee) => void applyTaskAssignee(assignee)
2399
3190
  }
2400
3191
  ) : null,
2401
- overlay === "focus" ? /* @__PURE__ */ jsx6(
3192
+ overlay === "focus" ? /* @__PURE__ */ jsx5(
2402
3193
  Picker,
2403
3194
  {
2404
3195
  title: "Send into which chat?",
@@ -2410,7 +3201,7 @@ function App(props) {
2410
3201
  }
2411
3202
  }
2412
3203
  ) : null,
2413
- overlay === null && pendingQuestion ? /* @__PURE__ */ jsx6(
3204
+ overlay === null && pendingQuestion ? /* @__PURE__ */ jsx5(
2414
3205
  QuestionPrompt,
2415
3206
  {
2416
3207
  client,
@@ -2424,7 +3215,7 @@ function App(props) {
2424
3215
  },
2425
3216
  pendingQuestion.id
2426
3217
  ) : null,
2427
- /* @__PURE__ */ jsx6(
3218
+ /* @__PURE__ */ jsx5(
2428
3219
  PromptLine,
2429
3220
  {
2430
3221
  projectName,
@@ -2440,6 +3231,7 @@ function App(props) {
2440
3231
  active: overlay === null && (!pendingQuestion || pendingInput !== null || taskPrompt !== null),
2441
3232
  history,
2442
3233
  craftbooks,
3234
+ recentOpenReferences,
2443
3235
  pendingPrompt: pendingInput?.promptLine ?? taskPrompt?.promptLine,
2444
3236
  pendingMode: pendingInput?.mode ?? (taskPrompt ? "text" : void 0),
2445
3237
  onChange: setValue,
@@ -2448,6 +3240,52 @@ function App(props) {
2448
3240
  )
2449
3241
  ] });
2450
3242
  }
3243
+ function ModelDownloadProgressPanel(props) {
3244
+ const { progress, onCancel } = props;
3245
+ useInput4((input, key) => {
3246
+ if (key.escape || key.ctrl && input === "c") onCancel();
3247
+ });
3248
+ const transferred = progress.totalBytes ? `${formatModelBytes(progress.bytesWritten)} / ${formatModelBytes(progress.totalBytes)}` : formatModelBytes(progress.bytesWritten);
3249
+ return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
3250
+ /* @__PURE__ */ jsxs6(Text6, { bold: true, color: "yellow", children: [
3251
+ "Downloading ",
3252
+ progress.choice.model.name
3253
+ ] }),
3254
+ /* @__PURE__ */ jsxs6(Text6, { children: [
3255
+ progress.pct == null ? "Working\u2026" : `${progress.pct}%`,
3256
+ " \xB7 ",
3257
+ transferred
3258
+ ] }),
3259
+ progress.phase ? /* @__PURE__ */ jsx5(Text6, { dimColor: true, children: progress.phase }) : null,
3260
+ /* @__PURE__ */ jsx5(Text6, { dimColor: true, children: "Esc / Ctrl+C cancel" })
3261
+ ] });
3262
+ }
3263
+ function readModelDownloadProgress(choice, event) {
3264
+ if (event.type === "progress") {
3265
+ const bytesWritten = "bytesWrittenAll" in event ? event.bytesWrittenAll : event.bytesWritten;
3266
+ const totalBytes = "totalBytesAll" in event ? event.totalBytesAll : event.totalBytes;
3267
+ return {
3268
+ choice,
3269
+ bytesWritten,
3270
+ totalBytes,
3271
+ pct: totalBytes > 0 ? Math.min(100, Math.floor(bytesWritten / totalBytes * 100)) : null,
3272
+ phase: "downloading and verifying model files"
3273
+ };
3274
+ }
3275
+ if (event.type === "companion") {
3276
+ return {
3277
+ choice,
3278
+ bytesWritten: event.bytesWritten,
3279
+ totalBytes: event.totalBytes,
3280
+ pct: event.totalBytes > 0 ? Math.min(100, Math.floor(event.bytesWritten / event.totalBytes * 100)) : null,
3281
+ phase: `downloading ${event.name}`
3282
+ };
3283
+ }
3284
+ return null;
3285
+ }
3286
+ function formatModelBytes(bytes) {
3287
+ return bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : `${Math.max(0, Math.round(bytes / 1e6))} MB`;
3288
+ }
2451
3289
  function errMsg(err) {
2452
3290
  return err instanceof Error ? err.message : String(err);
2453
3291
  }
@@ -2522,7 +3360,7 @@ function taskAssigneeLabel(task, gezels, boring) {
2522
3360
  if (task.assignee.kind === "user") return "you";
2523
3361
  const gezelId = task.assignee.gezelId;
2524
3362
  const gezel = gezels.find((item) => item.id === gezelId);
2525
- if (!gezel) return gezelId;
3363
+ if (!gezel) return boring ? "gezel" : gezelId;
2526
3364
  return boring ? gezel.roleBasedName ?? gezel.role ?? gezel.id : gezel.name;
2527
3365
  }
2528
3366
  function taskStatusChoices(task) {
@@ -2550,174 +3388,10 @@ function formatTaskDetails(task, gezels, boring) {
2550
3388
  }
2551
3389
 
2552
3390
  // src/tui/components/BootstrapGate.tsx
3391
+ import { formatModelAttribution as formatModelAttribution3 } from "@bendyline/gezel";
2553
3392
  import { Box as Box7, Text as Text7, useApp as useApp2, useInput as useInput5 } from "ink";
2554
3393
  import { useCallback as useCallback2, useEffect as useEffect4, useState as useState5 } from "react";
2555
-
2556
- // src/tui/bootstrap.ts
2557
- import {
2558
- computeModelFit,
2559
- isMoEFromTags,
2560
- isRecommendedModel,
2561
- mediaModelFits,
2562
- pickRecommendedModel
2563
- } from "@bendyline/gezel";
2564
- var CHAT_MEMORY_OVERHEAD = {
2565
- "llama-cpp": 1.2,
2566
- mlx: 1.3
2567
- };
2568
- var NATIVE_TOOLKIT = [
2569
- "uv",
2570
- "sd-server",
2571
- "whisper-server",
2572
- "llama-server"
2573
- ];
2574
- function rankChatModels(items, device, provider) {
2575
- const candidates = [];
2576
- for (const item of items) {
2577
- if (item.manifest.kind !== "chat-model") continue;
2578
- const manifest = item.manifest;
2579
- if (manifest.licenseClass !== "open") continue;
2580
- const source = provider === "mlx" ? manifest.mlx : manifest.llamaCpp;
2581
- if (!source || provider === "mlx" && manifest.mlx?.disabledReason) continue;
2582
- const residentBytes = source.residentBytes ?? Math.round(source.approxSizeBytes * CHAT_MEMORY_OVERHEAD[provider]);
2583
- const fit = computeModelFit({
2584
- residentBytes,
2585
- isMoE: isMoEFromTags(manifest.tags),
2586
- usableBytes: device.usableBytes,
2587
- totalRamBytes: device.totalRamBytes,
2588
- gpuVramBytes: device.gpuVramBytes,
2589
- ...device.budgetBytes !== void 0 ? { admissibleBytes: device.budgetBytes } : {}
2590
- }).tier;
2591
- candidates.push({
2592
- id: manifest.id,
2593
- name: manifest.name,
2594
- provider,
2595
- approxSizeBytes: source.approxSizeBytes,
2596
- residentBytes,
2597
- // Effective score: a model the shared gate rejects (restricted license,
2598
- // no tool support) sorts as unscored rather than leading the list.
2599
- recoScore: isRecommendedModel(manifest) ? manifest.recoScore ?? 0 : 0,
2600
- fit
2601
- });
2602
- }
2603
- if (candidates.length === 0) return [];
2604
- const picked = pickRecommendedModel(
2605
- candidates.map((model) => ({
2606
- id: model.id,
2607
- ...model.recoScore > 0 ? { recoScore: model.recoScore } : {},
2608
- licenseClass: "open",
2609
- tags: items.find((item) => item.manifest.kind === "chat-model" && item.manifest.id === model.id)?.manifest?.tags ?? [],
2610
- residentBytes: model.residentBytes
2611
- })),
2612
- device
2613
- );
2614
- const comfortable = candidates.filter(
2615
- (model) => model.fit === "fits" || model.fit === "fits-offload"
2616
- );
2617
- const pool = comfortable.length > 0 ? comfortable : candidates;
2618
- pool.sort(
2619
- (a, b) => b.recoScore - a.recoScore || fitOrder(a.fit) - fitOrder(b.fit) || b.residentBytes - a.residentBytes || a.name.localeCompare(b.name)
2620
- );
2621
- if (!picked) return pool;
2622
- const bestIndex = pool.findIndex((model) => model.id === picked.id);
2623
- if (bestIndex < 0) {
2624
- const best = candidates.find((model) => model.id === picked.id);
2625
- if (best) pool.unshift(best);
2626
- return pool;
2627
- }
2628
- if (bestIndex > 0) {
2629
- const [best] = pool.splice(bestIndex, 1);
2630
- if (best) pool.unshift(best);
2631
- }
2632
- return pool;
2633
- }
2634
- function pickAccessoryModels(input, device) {
2635
- const output = [];
2636
- const image = pickCatalogMedia(input.imageItems, device, "image");
2637
- if (image && !input.installed.image?.has(image.id)) {
2638
- output.push({
2639
- kind: "image",
2640
- id: image.id,
2641
- name: image.name,
2642
- approxSizeBytes: image.approxSizeBytes + (image.auxiliaryFiles ?? []).reduce((sum, file) => sum + (file.sizeBytes ?? 0), 0),
2643
- requiredEngine: "sd-server"
2644
- });
2645
- }
2646
- const recognition = pickScoredOpen(input.recognition, false);
2647
- if (recognition && !input.installed.recognition?.has(recognition.id)) {
2648
- output.push({
2649
- kind: "recognition",
2650
- id: recognition.id,
2651
- name: recognition.name,
2652
- approxSizeBytes: recognition.approxSizeBytes,
2653
- requiredEngine: "llama-server"
2654
- });
2655
- }
2656
- const stt = pickScoredOpen(input.audio.stt);
2657
- if (stt && !input.installed.stt?.has(stt.id)) {
2658
- output.push({
2659
- kind: "stt",
2660
- id: stt.id,
2661
- name: stt.name,
2662
- approxSizeBytes: stt.approxSizeBytes,
2663
- requiredEngine: "whisper-server"
2664
- });
2665
- }
2666
- const tts = pickScoredOpen(input.audio.tts);
2667
- if (tts && !input.installed.tts?.has(tts.id)) {
2668
- output.push({
2669
- kind: "tts",
2670
- id: tts.id,
2671
- name: tts.name,
2672
- approxSizeBytes: tts.approxSizeBytes
2673
- });
2674
- }
2675
- const video = pickCatalogMedia(input.videoItems, device, "video");
2676
- if (video && !input.installed.video?.has(video.id)) {
2677
- output.push({
2678
- kind: "video",
2679
- id: video.id,
2680
- name: video.name,
2681
- approxSizeBytes: video.approxSizeBytes,
2682
- requiredEngine: "uv"
2683
- });
2684
- }
2685
- return output;
2686
- }
2687
- function formatDownloadSize(bytes) {
2688
- if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
2689
- return `${Math.max(1, Math.round(bytes / 1e6))} MB`;
2690
- }
2691
- function fitOrder(fit) {
2692
- switch (fit) {
2693
- case "fits":
2694
- return 0;
2695
- case "fits-offload":
2696
- return 1;
2697
- case "tight":
2698
- return 2;
2699
- case "too-big":
2700
- return 3;
2701
- }
2702
- }
2703
- function pickCatalogMedia(items, device, kind) {
2704
- const models = items.map((item) => item.manifest).filter((model) => {
2705
- if (model.licenseClass !== "open" || !model.recoScore) return false;
2706
- return mediaModelFits(
2707
- device,
2708
- kind === "image" ? { minRamGB: model.minRamGB } : { minVramGB: model.minVramGB }
2709
- );
2710
- });
2711
- return pickScoredOpen(models);
2712
- }
2713
- function pickScoredOpen(models, requireLicense = true) {
2714
- return [...models].filter(
2715
- (model) => typeof model.recoScore === "number" && model.recoScore > 0 && (!requireLicense || model.licenseClass === "open")
2716
- ).sort((a, b) => (b.recoScore ?? 0) - (a.recoScore ?? 0))[0] ?? null;
2717
- }
2718
-
2719
- // src/tui/components/BootstrapGate.tsx
2720
- import { Fragment as Fragment4, jsx as jsx7, jsxs as jsxs7 } from "react/jsx-runtime";
3394
+ import { Fragment as Fragment4, jsx as jsx6, jsxs as jsxs7 } from "react/jsx-runtime";
2721
3395
  var MAX_ALTERNATIVE_MODELS = 6;
2722
3396
  function BootstrapGate(props) {
2723
3397
  const { client, children } = props;
@@ -2740,7 +3414,8 @@ function BootstrapGate(props) {
2740
3414
  async (context) => {
2741
3415
  setScreen({ kind: "loading", message: "Finding the best models for this device\u2026" });
2742
3416
  const installedChat = context.provider === "mlx" ? await client.listMlxModels() : await client.listLlamaCppModels();
2743
- if (installedChat.models.length > 0) {
3417
+ const pinnedModel = context.config.defaultModel?.[context.provider];
3418
+ if (pinnedModel && installedChat.models.some((model) => model.id === pinnedModel)) {
2744
3419
  setScreen({ kind: "ready" });
2745
3420
  return;
2746
3421
  }
@@ -2765,8 +3440,20 @@ function BootstrapGate(props) {
2765
3440
  client.listInstalledTtsModels().catch(() => ({ models: [] })),
2766
3441
  client.listInstalledRecognitionModels().catch(() => ({ models: [] }))
2767
3442
  ]);
2768
- const chatModels = rankChatModels(context.chatCatalog, context.device, context.provider);
2769
- if (chatModels.length === 0) {
3443
+ const installedIds = new Set(installedChat.models.map((model) => model.id));
3444
+ const rankedChatModels = rankChatModels(
3445
+ context.chatCatalog,
3446
+ context.device,
3447
+ context.provider
3448
+ );
3449
+ const recommendedChatModel = rankedChatModels[0];
3450
+ const chatModels = rankedChatModels.filter((model) => !installedIds.has(model.id));
3451
+ const catalogAttributions = new Map(
3452
+ context.chatCatalog.flatMap(
3453
+ (item) => item.manifest.kind === "chat-model" ? [[item.manifest.id, formatModelAttribution3(item.manifest)]] : []
3454
+ )
3455
+ );
3456
+ if (chatModels.length === 0 && installedChat.models.length === 0) {
2770
3457
  setScreen({
2771
3458
  kind: "error",
2772
3459
  title: "No compatible local models found",
@@ -2790,7 +3477,19 @@ function BootstrapGate(props) {
2790
3477
  },
2791
3478
  context.device
2792
3479
  );
2793
- setScreen({ kind: "model-choice", plan: { context, chatModels, accessories } });
3480
+ setScreen({
3481
+ kind: "model-choice",
3482
+ plan: {
3483
+ context,
3484
+ installedChatModels: installedChat.models.map((model) => {
3485
+ const attribution = catalogAttributions.get(model.id);
3486
+ return { ...model, ...attribution ? { attribution } : {} };
3487
+ }),
3488
+ ...recommendedChatModel ? { recommendedChatModel } : {},
3489
+ chatModels,
3490
+ accessories
3491
+ }
3492
+ });
2794
3493
  },
2795
3494
  [client]
2796
3495
  );
@@ -2818,14 +3517,7 @@ function BootstrapGate(props) {
2818
3517
  const context = {
2819
3518
  config,
2820
3519
  provider: config.provider,
2821
- device: {
2822
- platform: memory.platform,
2823
- gpuVramBytes: memory.gpuVramBytes,
2824
- ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
2825
- totalRamBytes: memory.totalRamBytes,
2826
- usableBytes: memory.usableBytes,
2827
- ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
2828
- },
3520
+ device: recoDevice(memory),
2829
3521
  chatCatalog: chatCatalog.items,
2830
3522
  nativeStatus
2831
3523
  };
@@ -2860,12 +3552,19 @@ function BootstrapGate(props) {
2860
3552
  }
2861
3553
  try {
2862
3554
  await installNativeToolkit(client, context.nativeStatus, missing, setScreen);
2863
- const nativeStatus = await client.getNativeEngineStatus();
2864
- await prepareModels({ ...context, nativeStatus });
3555
+ const [nativeStatus, memory] = await Promise.all([
3556
+ client.getNativeEngineStatus(),
3557
+ client.getMemoryProfile()
3558
+ ]);
3559
+ await prepareModels({
3560
+ ...context,
3561
+ nativeStatus,
3562
+ device: recoDevice(memory)
3563
+ });
2865
3564
  } catch (error) {
2866
3565
  setScreen({
2867
3566
  kind: "error",
2868
- title: "Native toolkit install failed",
3567
+ title: "Gezel native toolkit install failed",
2869
3568
  message: errorMessage(error),
2870
3569
  retry
2871
3570
  });
@@ -2881,24 +3580,40 @@ function BootstrapGate(props) {
2881
3580
  }
2882
3581
  const retry = () => void installModels(plan, choice);
2883
3582
  try {
3583
+ if (choice.kind === "installed") {
3584
+ const updated2 = await client.updateConfig({
3585
+ provider: plan.context.provider,
3586
+ defaultModel: {
3587
+ ...plan.context.config.defaultModel,
3588
+ [plan.context.provider]: choice.modelId
3589
+ },
3590
+ firstRunInstallError: null
3591
+ });
3592
+ plan.context.config = updated2;
3593
+ setScreen({ kind: "ready" });
3594
+ return;
3595
+ }
2884
3596
  if (choice.kind === "bundle") {
2885
3597
  const missing = missingToolkit(await client.getNativeEngineStatus());
2886
3598
  if (missing.length > 0) {
2887
3599
  await installNativeToolkit(client, plan.context.nativeStatus, missing, setScreen);
2888
3600
  }
2889
3601
  }
3602
+ const chatAlreadyInstalled = choice.kind === "bundle" && plan.installedChatModels.some((model) => model.id === choice.model.id);
2890
3603
  const jobs = [
2891
- { label: choice.model.name, sizeBytes: choice.model.approxSizeBytes },
3604
+ ...!chatAlreadyInstalled ? [{ label: choice.model.name, sizeBytes: choice.model.approxSizeBytes }] : [],
2892
3605
  ...choice.kind === "bundle" ? plan.accessories.map((model) => ({
2893
3606
  label: model.name,
2894
3607
  sizeBytes: model.approxSizeBytes
2895
3608
  })) : []
2896
3609
  ];
2897
3610
  let jobIndex = 0;
2898
- await installChatModel(client, choice.model, (event) => {
2899
- updateDownloadProgress(setScreen, jobs[jobIndex], jobIndex, jobs.length, event);
2900
- });
2901
- jobIndex += 1;
3611
+ if (!chatAlreadyInstalled) {
3612
+ await installChatModel(client, choice.model, (event) => {
3613
+ updateDownloadProgress(setScreen, jobs[jobIndex], jobIndex, jobs.length, event);
3614
+ });
3615
+ jobIndex += 1;
3616
+ }
2902
3617
  const updated = await client.updateConfig({
2903
3618
  provider: choice.model.provider,
2904
3619
  defaultModel: {
@@ -2929,9 +3644,9 @@ function BootstrapGate(props) {
2929
3644
  },
2930
3645
  [client]
2931
3646
  );
2932
- if (screen.kind === "ready") return /* @__PURE__ */ jsx7(Fragment4, { children });
3647
+ if (screen.kind === "ready") return /* @__PURE__ */ jsx6(Fragment4, { children });
2933
3648
  if (screen.kind === "loading") {
2934
- return /* @__PURE__ */ jsx7(BootstrapFrame, { title: "Preparing the workshop", children: /* @__PURE__ */ jsxs7(Text7, { color: "yellow", children: [
3649
+ return /* @__PURE__ */ jsx6(BootstrapFrame, { title: "Preparing the workshop", children: /* @__PURE__ */ jsxs7(Text7, { color: "yellow", children: [
2935
3650
  "\u25CF ",
2936
3651
  screen.message
2937
3652
  ] }) });
@@ -2945,28 +3660,29 @@ function BootstrapGate(props) {
2945
3660
  " ",
2946
3661
  screen.progress.detail
2947
3662
  ] }),
2948
- /* @__PURE__ */ jsx7(ProgressBar, { pct: screen.progress.pct }),
2949
- /* @__PURE__ */ jsx7(Text7, { dimColor: true, children: screen.progress.pct == null ? "Working\u2026" : `${screen.progress.pct}%` })
3663
+ /* @__PURE__ */ jsx6(ProgressBar, { pct: screen.progress.pct }),
3664
+ /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: screen.progress.pct == null ? "Working\u2026" : `${screen.progress.pct}%` })
2950
3665
  ] });
2951
3666
  }
2952
3667
  if (screen.kind === "native-choice") {
2953
3668
  const labels = screen.missing.map(nativeLabel).join(", ");
2954
- return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "Local tools are not installed yet", children: [
3669
+ return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "The Gezel native toolkit -- needed to run AI models locally -- is not installed yet", children: [
3670
+ /* @__PURE__ */ jsx6(Text7, { children: `Gezel can install the verified Gezel native toolkit (native-v${screen.context.nativeStatus.release}) for this device.` }),
2955
3671
  /* @__PURE__ */ jsxs7(Text7, { children: [
2956
- "Gezel can install the verified native-v",
2957
- screen.context.nativeStatus.release,
2958
- " toolkit for this device."
3672
+ "Downloaded from",
3673
+ " ",
3674
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "cyan", children: "https://github.com/bendyline/gezel/releases/" })
2959
3675
  ] }),
2960
3676
  /* @__PURE__ */ jsxs7(Text7, { dimColor: true, children: [
2961
3677
  "Missing: ",
2962
3678
  labels
2963
3679
  ] }),
2964
- /* @__PURE__ */ jsx7(
3680
+ /* @__PURE__ */ jsx6(
2965
3681
  BootstrapChoiceList,
2966
3682
  {
2967
3683
  options: [
2968
3684
  {
2969
- label: "Install the native toolkit",
3685
+ label: "Install the Gezel native toolkit",
2970
3686
  hint: "recommended \xB7 engines for chat, images, speech, and local model helpers",
2971
3687
  value: "install"
2972
3688
  },
@@ -2984,53 +3700,73 @@ function BootstrapGate(props) {
2984
3700
  ] });
2985
3701
  }
2986
3702
  if (screen.kind === "model-choice") {
2987
- const best = screen.plan.chatModels[0];
3703
+ const best = screen.plan.recommendedChatModel;
3704
+ const bestInstalled = best ? screen.plan.installedChatModels.some((model) => model.id === best.id) : false;
2988
3705
  const accessoryBytes = screen.plan.accessories.reduce(
2989
3706
  (sum, model) => sum + model.approxSizeBytes,
2990
3707
  0
2991
3708
  );
3709
+ const workshopDownloadBytes = accessoryBytes + (best && !bestInstalled ? best.approxSizeBytes : 0);
2992
3710
  const options = [
2993
- {
2994
- label: `Recommended workshop set \u2014 ${best.name} + ${screen.plan.accessories.length} helpers`,
2995
- hint: formatDownloadSize(best.approxSizeBytes + accessoryBytes),
2996
- value: "bundle"
2997
- },
2998
- {
2999
- label: `${best.name} only`,
3000
- hint: `best chat model \xB7 ${formatDownloadSize(best.approxSizeBytes)}`,
3001
- value: `chat:${best.id}`
3002
- },
3003
- ...screen.plan.chatModels.slice(1, MAX_ALTERNATIVE_MODELS + 1).map((model) => ({
3004
- label: `${model.name} only`,
3711
+ ...best ? [
3712
+ {
3713
+ label: `Recommended workshop set \u2014 ${bootstrapChatModelLabel(best)} + ${screen.plan.accessories.length} helpers`,
3714
+ hint: `${bestInstalled ? "chat model already available \xB7 " : ""}${workshopDownloadBytes > 0 ? formatDownloadSize(workshopDownloadBytes) : "already available"}`,
3715
+ value: "bundle"
3716
+ },
3717
+ {
3718
+ label: `${bestInstalled ? "Use" : "Download"} ${bootstrapChatModelLabel(best)} only`,
3719
+ hint: `recommended for this device \xB7 ${bestInstalled ? "already available" : formatDownloadSize(best.approxSizeBytes)}`,
3720
+ value: bestInstalled ? `installed:${best.id}` : `chat:${best.id}`
3721
+ }
3722
+ ] : [],
3723
+ ...screen.plan.installedChatModels.filter((model) => model.id !== best?.id).map((model) => ({
3724
+ label: `Use ${model.name ?? model.id}${model.attribution ? ` (${model.attribution})` : ""}`,
3725
+ hint: `already available on this machine${model.approxSizeBytes ? ` \xB7 ${formatDownloadSize(model.approxSizeBytes)}` : ""}`,
3726
+ value: `installed:${model.id}`
3727
+ })),
3728
+ ...screen.plan.chatModels.filter((model) => model.id !== best?.id).slice(0, MAX_ALTERNATIVE_MODELS).map((model) => ({
3729
+ label: `Download ${bootstrapChatModelLabel(model)} only`,
3005
3730
  hint: `${formatDownloadSize(model.approxSizeBytes)} \xB7 ${fitLabel(model.fit)}`,
3006
3731
  value: `chat:${model.id}`
3007
3732
  })),
3008
3733
  { label: "Not now", hint: "open the TUI without a local model", value: "skip" }
3009
3734
  ];
3010
- return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "No local chat model is installed", children: [
3011
- /* @__PURE__ */ jsx7(Text7, { children: "Pick a setup for this device. Downloads stay under your Gezel home folder." }),
3012
- /* @__PURE__ */ jsx7(
3013
- BootstrapChoiceList,
3014
- {
3015
- options,
3016
- onSelect: (value) => {
3017
- if (value === "skip") {
3018
- void installModels(screen.plan, { kind: "skip" });
3019
- } else if (value === "bundle") {
3020
- void installModels(screen.plan, { kind: "bundle", model: best });
3021
- } else {
3022
- const id = value.slice("chat:".length);
3023
- const model = screen.plan.chatModels.find((candidate) => candidate.id === id);
3024
- if (model) void installModels(screen.plan, { kind: "chat", model });
3735
+ return /* @__PURE__ */ jsxs7(
3736
+ BootstrapFrame,
3737
+ {
3738
+ title: screen.plan.installedChatModels.length > 0 ? "Choose a local chat model" : "No local chat model is installed",
3739
+ children: [
3740
+ /* @__PURE__ */ jsx6(Text7, { children: screen.plan.installedChatModels.length > 0 ? "These models are already available in your Gezel or shared machine store. You can use one now or download another." : "Pick a setup for this device. Downloads stay under Gezel model storage." }),
3741
+ /* @__PURE__ */ jsx6(
3742
+ BootstrapChoiceList,
3743
+ {
3744
+ options,
3745
+ onSelect: (value) => {
3746
+ if (value === "skip") {
3747
+ void installModels(screen.plan, { kind: "skip" });
3748
+ } else if (value === "bundle") {
3749
+ if (best) void installModels(screen.plan, { kind: "bundle", model: best });
3750
+ } else if (value.startsWith("installed:")) {
3751
+ void installModels(screen.plan, {
3752
+ kind: "installed",
3753
+ modelId: value.slice("installed:".length)
3754
+ });
3755
+ } else {
3756
+ const id = value.slice("chat:".length);
3757
+ const model = screen.plan.chatModels.find((candidate) => candidate.id === id);
3758
+ if (model) void installModels(screen.plan, { kind: "chat", model });
3759
+ }
3760
+ }
3025
3761
  }
3026
- }
3027
- }
3028
- )
3029
- ] });
3762
+ )
3763
+ ]
3764
+ }
3765
+ );
3030
3766
  }
3031
3767
  return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: screen.title, children: [
3032
- /* @__PURE__ */ jsx7(Text7, { color: "red", children: screen.message }),
3033
- /* @__PURE__ */ jsx7(
3768
+ /* @__PURE__ */ jsx6(Text7, { color: "red", children: screen.message }),
3769
+ /* @__PURE__ */ jsx6(
3034
3770
  BootstrapChoiceList,
3035
3771
  {
3036
3772
  options: [
@@ -3047,7 +3783,7 @@ function BootstrapGate(props) {
3047
3783
  }
3048
3784
  function BootstrapFrame(props) {
3049
3785
  return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", paddingX: 1, paddingY: 1, children: [
3050
- /* @__PURE__ */ jsx7(Text7, { bold: true, color: "cyan", children: "gezel \xB7 first-time setup" }),
3786
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "cyan", children: "gezel \xB7 first-time setup" }),
3051
3787
  /* @__PURE__ */ jsxs7(
3052
3788
  Box7,
3053
3789
  {
@@ -3057,14 +3793,24 @@ function BootstrapFrame(props) {
3057
3793
  paddingX: 1,
3058
3794
  marginTop: 1,
3059
3795
  children: [
3060
- /* @__PURE__ */ jsx7(Text7, { bold: true, color: "yellow", children: props.title }),
3796
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "yellow", children: props.title }),
3061
3797
  props.children
3062
3798
  ]
3063
3799
  }
3064
3800
  ),
3065
- /* @__PURE__ */ jsx7(Text7, { dimColor: true, children: "Ctrl+C exit" })
3801
+ /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: "Ctrl+C exit" })
3066
3802
  ] });
3067
3803
  }
3804
+ function recoDevice(memory) {
3805
+ return {
3806
+ platform: memory.platform,
3807
+ gpuVramBytes: memory.gpuVramBytes,
3808
+ ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
3809
+ totalRamBytes: memory.totalRamBytes,
3810
+ usableBytes: memory.usableBytes,
3811
+ ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
3812
+ };
3813
+ }
3068
3814
  function BootstrapChoiceList(props) {
3069
3815
  const [index, setIndex] = useState5(0);
3070
3816
  const options = props.options;
@@ -3137,7 +3883,7 @@ async function installNativeToolkit(client, status, missing, setScreen) {
3137
3883
  index,
3138
3884
  missing.length,
3139
3885
  event,
3140
- `Installing native-v${status.release}`
3886
+ `Installing the Gezel native toolkit (native-v${status.release})`
3141
3887
  );
3142
3888
  },
3143
3889
  engine === "llama-server" ? status.llamaBackend : void 0
@@ -3175,7 +3921,7 @@ async function installAccessory(client, model, onEvent) {
3175
3921
  }
3176
3922
  if (terminalError) throw new Error(terminalError);
3177
3923
  }
3178
- function updateDownloadProgress(setScreen, job, index, total, event, title = "Installing local models") {
3924
+ function updateDownloadProgress(setScreen, job, index, total, event, title = "Downloading local models from Hugging Face (huggingface.co)") {
3179
3925
  let pct = null;
3180
3926
  let detail = job.label;
3181
3927
  if (event.type === "progress") {
@@ -3241,10 +3987,10 @@ function delay(ms) {
3241
3987
  }
3242
3988
 
3243
3989
  // src/tui/index.tsx
3244
- import { jsx as jsx8 } from "react/jsx-runtime";
3990
+ import { jsx as jsx7 } from "react/jsx-runtime";
3245
3991
  async function launchTui(opts) {
3246
3992
  const instance = render(
3247
- /* @__PURE__ */ jsx8(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx8(
3993
+ /* @__PURE__ */ jsx7(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx7(
3248
3994
  App,
3249
3995
  {
3250
3996
  client: opts.client,