@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/bin/gezel.js CHANGED
@@ -24,11 +24,13 @@ import {
24
24
  GezelApiError,
25
25
  GezelClient,
26
26
  createTrustingFetch,
27
+ discoverOrSpawn,
27
28
  electronNativeBinCandidates,
28
29
  isProcessAlive,
29
30
  readRuntime,
30
31
  readSystemServiceEndpoint,
31
32
  resolveDaemonEntry,
33
+ stopOwnedDaemon,
32
34
  systemSharedAssetsDir
33
35
  } from "@bendyline/gezel-client/node";
34
36
  import { gezelPaths } from "@bendyline/gezel/paths";
@@ -96,6 +98,48 @@ async function connectOwned(globals) {
96
98
  );
97
99
  return connected.client;
98
100
  }
101
+ async function connectForTui(globals) {
102
+ applyHome(globals);
103
+ const preferred = await connectPreferredService(globals);
104
+ if (preferred) return { client: preferred.client };
105
+ const runtime = await readRuntime();
106
+ if (!runtime || !isProcessAlive(runtime.pid)) {
107
+ await prepareStandaloneAssets();
108
+ }
109
+ const result = await discoverOrSpawn({
110
+ daemonEntry: resolveDaemonEntry(import.meta.url),
111
+ detached: false,
112
+ stdio: "pipe",
113
+ env: cliUserDaemonEnv(process.env.GEZEL_HOME, await shouldPreferCanonicalPort()),
114
+ ...process.env.GEZEL_HOME ? { home: process.env.GEZEL_HOME } : {},
115
+ timeoutMs: 2e4
116
+ });
117
+ result.child?.stdout?.resume();
118
+ result.child?.stderr?.resume();
119
+ if (result.outcome !== "spawned") return { client: result.client };
120
+ let stopPromise;
121
+ return {
122
+ client: result.client,
123
+ stop: () => {
124
+ stopPromise ??= stopOwnedDaemon(result.child);
125
+ return stopPromise;
126
+ }
127
+ };
128
+ }
129
+ function cliUserDaemonEnv(home, preferCanonicalPort, inherited = process.env) {
130
+ const {
131
+ GEZEL_PORT: _inheritedPort,
132
+ GEZEL_SERVICE_ROLE: _inheritedRole,
133
+ GEZEL_SYSTEM_SCOPE: _inheritedSystemScope,
134
+ ...rest
135
+ } = inherited;
136
+ return {
137
+ ...rest,
138
+ ...home ? { GEZEL_HOME: home } : {},
139
+ ...preferCanonicalPort ? {} : { GEZEL_PORT: "0" },
140
+ GEZEL_SERVICE_ROLE: "user"
141
+ };
142
+ }
99
143
  async function shouldPreferCanonicalPort() {
100
144
  if (process.env.GEZEL_HOME || process.env.GEZEL_DEV === "1") return false;
101
145
  try {
@@ -152,16 +196,20 @@ async function connectForRun(globals) {
152
196
  token: svc.clientToken,
153
197
  ...svc.cert ? { fetch: createTrustingFetch({ cert: svc.cert.certPem }) } : {}
154
198
  });
155
- const stop = async () => {
156
- await svc.stop();
157
- try {
158
- const paths = gezelPaths();
159
- const pid = (await readFile(paths.runtime.pid, "utf8")).trim();
160
- if (pid === String(process.pid)) {
161
- await rm(paths.runtime.dir, { recursive: true, force: true });
199
+ let stopPromise;
200
+ const stop = () => {
201
+ stopPromise ??= (async () => {
202
+ await svc.stop();
203
+ try {
204
+ const paths = gezelPaths();
205
+ const pid = (await readFile(paths.runtime.pid, "utf8")).trim();
206
+ if (pid === String(process.pid)) {
207
+ await rm(paths.runtime.dir, { recursive: true, force: true });
208
+ }
209
+ } catch {
162
210
  }
163
- } catch {
164
- }
211
+ })();
212
+ return stopPromise;
165
213
  };
166
214
  return { kind: "owned", client, baseUrl, stop };
167
215
  }
@@ -436,15 +484,33 @@ async function ensureProjectForFolder(client, folderPath) {
436
484
  name,
437
485
  description: `CLI workspace at ${wd}`,
438
486
  about: `${name} \u2014 working directory ${wd}. Fill in who this project is for, what's in scope, and what's explicitly out of scope.`,
439
- missionObjectives: `${name} \u2014 fill in concrete success criteria for this project.`
487
+ missionObjectives: `${name} \u2014 fill in concrete success criteria for this project.`,
488
+ mode: "solo",
489
+ workingDir: wd
440
490
  });
441
- await client.setProjectWorkingDir(created.id, wd);
442
491
  return created.id;
443
492
  }
444
493
  async function ensureCliProjectLead(client, projectId) {
445
494
  const project = await client.getProject(projectId);
446
495
  if (project.voormanGezelId) return project.voormanGezelId;
447
- if (project.mode === "solo" && project.gezelIds?.[0]) return project.gezelIds[0];
496
+ if (project.mode === "solo") {
497
+ if (project.gezelIds?.[0]) return project.gezelIds[0];
498
+ if (project.workingDir) {
499
+ const { gezels: gezels2 } = await client.listGezels();
500
+ let builder = gezels2.find(
501
+ (gezel) => gezel.templateId === "builder" || gezel.role?.trim().toLowerCase() === "builder"
502
+ );
503
+ if (!builder) {
504
+ const { name, gender } = pickRandomNameWithGender();
505
+ builder = await client.createGezelFromTemplate("builder", { name, gender });
506
+ }
507
+ const updated2 = await client.updateProject(projectId, { voormanGezelId: builder.id });
508
+ if (!updated2.voormanGezelId) {
509
+ throw new CliError(`project "${updated2.name}" has no Builder`);
510
+ }
511
+ return updated2.voormanGezelId;
512
+ }
513
+ }
448
514
  const { gezels } = await client.listGezels();
449
515
  let voorman = gezels.find(
450
516
  (gezel) => gezel.templateId === "voorman" || gezel.role?.trim().toLowerCase() === "voorman"
@@ -544,6 +610,7 @@ var init_engagement_mode = __esm({
544
610
  // src/tui/bootstrap.ts
545
611
  import {
546
612
  computeModelFit,
613
+ formatModelAttribution,
547
614
  isMoEFromTags,
548
615
  isRecommendedModel,
549
616
  mediaModelFits,
@@ -575,7 +642,8 @@ function rankChatModels(items, device, provider) {
575
642
  // Effective score: a model the shared gate rejects (restricted license,
576
643
  // no tool support) sorts as unscored rather than leading the list.
577
644
  recoScore: isRecommendedModel(manifest) ? manifest.recoScore ?? 0 : 0,
578
- fit
645
+ fit,
646
+ attribution: formatModelAttribution(manifest)
579
647
  });
580
648
  }
581
649
  if (candidates.length === 0) return [];
@@ -609,6 +677,9 @@ function rankChatModels(items, device, provider) {
609
677
  }
610
678
  return pool;
611
679
  }
680
+ function bootstrapChatModelLabel(model2) {
681
+ return `${model2.name} (${model2.attribution})`;
682
+ }
612
683
  function pickAccessoryModels(input, device) {
613
684
  const output = [];
614
685
  const image2 = pickCatalogMedia(input.imageItems, device, "image");
@@ -710,6 +781,97 @@ var init_bootstrap = __esm({
710
781
  }
711
782
  });
712
783
 
784
+ // src/tui/craftbook-start.ts
785
+ import {
786
+ CRAFTBOOK_ROLE_META,
787
+ visibleCatalogItems
788
+ } from "@bendyline/gezel";
789
+ function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
790
+ const byId = /* @__PURE__ */ new Map();
791
+ for (const item of visibleCatalogItems(items, showWorkInProgressFeatures)) {
792
+ if (item.manifest.kind !== "craftbook-template") continue;
793
+ const manifest = item.manifest;
794
+ if (byId.has(manifest.id)) continue;
795
+ byId.set(manifest.id, {
796
+ id: manifest.id,
797
+ name: manifest.name,
798
+ ...manifest.description ? { description: manifest.description } : {},
799
+ version: manifest.version,
800
+ sourceId: item.sourceId,
801
+ source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
802
+ stepCount: manifest.steps.length,
803
+ tags: manifest.tags ?? [],
804
+ role: manifest.role ?? "general"
805
+ });
806
+ }
807
+ return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
808
+ }
809
+ function craftbookCategories(books, suggestedIds, projectType) {
810
+ const categories = [];
811
+ const allIds = new Set(books.map((book) => book.id));
812
+ const recommended = new Set([...suggestedIds].filter((id) => allIds.has(id)));
813
+ if (recommended.size > 0) {
814
+ categories.push({
815
+ id: "recommended",
816
+ label: projectType ? `Recommended for ${projectType.label}` : "Recommended",
817
+ hint: countLabel(recommended.size),
818
+ bookIds: recommended
819
+ });
820
+ }
821
+ const projectBooks = new Set(
822
+ books.filter((book) => book.source === "project").map((book) => book.id)
823
+ );
824
+ if (projectBooks.size > 0) {
825
+ categories.push({
826
+ id: "project",
827
+ label: "Project craftbooks",
828
+ hint: countLabel(projectBooks.size),
829
+ bookIds: projectBooks
830
+ });
831
+ }
832
+ for (const role of CRAFTBOOK_ROLE_META) {
833
+ const bookIds = new Set(books.filter((book) => book.role === role.id).map((book) => book.id));
834
+ if (bookIds.size === 0) continue;
835
+ categories.push({
836
+ id: `role:${role.id}`,
837
+ label: role.label,
838
+ hint: countLabel(bookIds.size),
839
+ bookIds
840
+ });
841
+ }
842
+ categories.push({
843
+ id: "all",
844
+ label: "All craftbooks",
845
+ hint: countLabel(allIds.size),
846
+ bookIds: allIds
847
+ });
848
+ return categories;
849
+ }
850
+ function countLabel(count) {
851
+ return `${count} ${count === 1 ? "craftbook" : "craftbooks"}`;
852
+ }
853
+ function findCraftbook(books, value) {
854
+ const query = value.trim().toLowerCase();
855
+ return books.find((book) => book.id.toLowerCase() === query || book.name.toLowerCase() === query);
856
+ }
857
+ function craftbookStartRequest(book) {
858
+ const summary = book.description?.trim();
859
+ const description = summary ? `Start the "${book.name}" craftbook for this project. ${summary}` : `Start the "${book.name}" craftbook for this project. Follow every step in the recipe and verify its required outcomes before completing the task.`;
860
+ return {
861
+ title: book.name,
862
+ description,
863
+ craftbookId: book.id,
864
+ craftbookSourceId: book.sourceId,
865
+ ...book.version ? { craftbookVersion: book.version } : {},
866
+ dispatchEntry: true
867
+ };
868
+ }
869
+ var init_craftbook_start = __esm({
870
+ "src/tui/craftbook-start.ts"() {
871
+ "use strict";
872
+ }
873
+ });
874
+
713
875
  // src/tui/active-access.ts
714
876
  import * as GezelCore from "@bendyline/gezel";
715
877
  function activeAccessMode(opts) {
@@ -747,13 +909,179 @@ var init_active_access = __esm({
747
909
  }
748
910
  });
749
911
 
912
+ // src/tui/open-command.ts
913
+ function rememberCliOpenReferences(current, observed, max = MAX_RECENT_REFERENCES) {
914
+ const next = [...current];
915
+ for (const reference2 of observed) {
916
+ const index = next.findIndex((candidate) => candidate.key === reference2.key);
917
+ if (index !== -1) next.splice(index, 1);
918
+ next.unshift(reference2);
919
+ }
920
+ return next.slice(0, max);
921
+ }
922
+ function cliOpenReferencesFromEvent(env2) {
923
+ if (env2.event.type === "tool") {
924
+ return referencesFromTool(env2.event, env2.projectId);
925
+ }
926
+ if (env2.event.type === "complete" || env2.event.type === "user_message") {
927
+ return referencesFromMessage(env2.event.message, env2.projectId);
928
+ }
929
+ return [];
930
+ }
931
+ function cliOpenReferencesFromSession(session) {
932
+ let recent = [];
933
+ for (const message of session.messages) {
934
+ recent = rememberCliOpenReferences(recent, referencesFromMessage(message, session.projectId));
935
+ }
936
+ return recent;
937
+ }
938
+ function resolveCliOpenTarget(input, recentReferences) {
939
+ const query = normalizeLookup(input);
940
+ if (query === "workspace" || query === "artifacts") {
941
+ return { type: "folder", folder: query };
942
+ }
943
+ if (!query) return null;
944
+ const exact = recentReferences.find((reference2) => normalizeLookup(reference2.path) === query);
945
+ if (exact) return { type: "reference", reference: exact };
946
+ const basenameMatches = recentReferences.filter(
947
+ (reference2) => normalizeLookup(basename3(reference2.path)) === query
948
+ );
949
+ return basenameMatches.length === 1 ? { type: "reference", reference: basenameMatches[0] } : null;
950
+ }
951
+ function referencesFromMessage(message, projectId) {
952
+ const references = [];
953
+ for (const tool of message.toolCalls ?? []) {
954
+ references.push(...referencesFromTool(tool, projectId));
955
+ }
956
+ for (const path of message.referencedArtifacts ?? []) {
957
+ references.push(reference("artifact", path, projectId));
958
+ }
959
+ return references;
960
+ }
961
+ function referencesFromTool(tool, projectId) {
962
+ if (!tool.success) return [];
963
+ const references = [];
964
+ for (const media of [...tool.images ?? [], ...tool.audios ?? [], ...tool.videos ?? []]) {
965
+ references.push(reference("artifact", media.path, projectId));
966
+ }
967
+ const kind = classifyTool(tool.name);
968
+ if (!kind) return references;
969
+ const paths = tool.paths && tool.paths.length > 0 ? tool.paths : tool.path ? [tool.path] : [];
970
+ for (const path of paths) references.push(reference(kind, path, projectId));
971
+ return references;
972
+ }
973
+ function classifyTool(name) {
974
+ const normalized = name.replaceAll("-", "_").toLowerCase();
975
+ if (["read_artifact", "write_artifact"].includes(normalized)) return "artifact";
976
+ if (["read_document", "write_document"].includes(normalized)) return "document";
977
+ if ([
978
+ "readfile",
979
+ "read_file",
980
+ "read_files",
981
+ "writefile",
982
+ "write_file",
983
+ "replace_in_file",
984
+ "replace_lines",
985
+ "insert_at_marker",
986
+ "apply_patch"
987
+ ].includes(normalized)) {
988
+ return "workspace";
989
+ }
990
+ return null;
991
+ }
992
+ function reference(kind, path, projectId) {
993
+ return {
994
+ key: `${projectId}:${kind}:${normalizeLookup(path)}`,
995
+ kind,
996
+ path,
997
+ projectId
998
+ };
999
+ }
1000
+ function normalizeCliOpenLookup(value) {
1001
+ return normalizeLookup(value);
1002
+ }
1003
+ function cliOpenBasename(path) {
1004
+ return basename3(path);
1005
+ }
1006
+ function normalizeLookup(value) {
1007
+ return value.trim().replaceAll("\\", "/").toLowerCase();
1008
+ }
1009
+ function basename3(path) {
1010
+ const normalized = path.replaceAll("\\", "/");
1011
+ return normalized.slice(normalized.lastIndexOf("/") + 1);
1012
+ }
1013
+ var MAX_RECENT_REFERENCES;
1014
+ var init_open_command = __esm({
1015
+ "src/tui/open-command.ts"() {
1016
+ "use strict";
1017
+ MAX_RECENT_REFERENCES = 12;
1018
+ }
1019
+ });
1020
+
750
1021
  // src/tui/commands.ts
751
1022
  function suggestSlashCommands(input) {
752
1023
  if (!input.startsWith("/") || /\s/.test(input)) return [];
753
1024
  const query = input.slice(1).toLowerCase();
754
1025
  return SLASH_COMMANDS.filter((command) => command.name.startsWith(query));
755
1026
  }
756
- function suggestSlashWordwheel(input, craftbooks) {
1027
+ function parseProjectPermissionName(input) {
1028
+ const normalized = input.trim().toLowerCase();
1029
+ return PROJECT_PERMISSIONS.find((permission) => permission.name === normalized)?.name;
1030
+ }
1031
+ function suggestSlashWordwheel(input, craftbooks, recentReferences = []) {
1032
+ const openMatch = input.match(/^\/open\s+(.*)$/i);
1033
+ if (openMatch) {
1034
+ const query = normalizeCliOpenLookup(openMatch[1] ?? "");
1035
+ const matches = (candidate) => !query || normalizeCliOpenLookup(candidate).includes(query);
1036
+ const folders = ["workspace", "artifacts"].filter(matches).map((folder) => ({
1037
+ key: `open:folder:${folder}`,
1038
+ label: `/open ${folder}`,
1039
+ description: `open the project ${folder} folder`,
1040
+ submit: `/open ${folder}`,
1041
+ completion: `/open ${folder}`
1042
+ }));
1043
+ const seen = /* @__PURE__ */ new Set();
1044
+ const files = [];
1045
+ for (const reference2 of recentReferences) {
1046
+ if (seen.has(reference2.key)) continue;
1047
+ seen.add(reference2.key);
1048
+ if (!matches(reference2.path) && !matches(cliOpenBasename(reference2.path))) continue;
1049
+ files.push({
1050
+ key: `open:reference:${reference2.key}`,
1051
+ label: `/open ${reference2.path}`,
1052
+ description: `open recent ${reference2.kind}`,
1053
+ submit: `/open ${reference2.path}`,
1054
+ completion: `/open ${reference2.path}`
1055
+ });
1056
+ if (files.length >= 8) break;
1057
+ }
1058
+ return [...folders, ...files];
1059
+ }
1060
+ const modelMatch = input.match(/^\/model\s+(.*)$/i);
1061
+ if (modelMatch) {
1062
+ const query = (modelMatch[1] ?? "").trim().toLowerCase();
1063
+ return MODEL_SUBCOMMANDS.filter((command) => command.name.startsWith(query)).map((command) => ({
1064
+ key: `model:${command.name}`,
1065
+ label: `/model ${command.name}`,
1066
+ description: command.description,
1067
+ submit: `/model ${command.name}`,
1068
+ completion: `/model ${command.name}`
1069
+ }));
1070
+ }
1071
+ const permissionMatch = input.match(/^\/(allow|disallow)\s+(.*)$/i);
1072
+ if (permissionMatch) {
1073
+ const command = (permissionMatch[1] ?? "").toLowerCase();
1074
+ const query = (permissionMatch[2] ?? "").trim().toLowerCase();
1075
+ return PROJECT_PERMISSIONS.filter((permission) => permission.name.startsWith(query)).map(
1076
+ (permission) => ({
1077
+ key: `${command}:${permission.name}`,
1078
+ label: `/${command} ${permission.name}`,
1079
+ description: command === "allow" ? permission.allowDescription : permission.disallowDescription,
1080
+ submit: `/${command} ${permission.name}`,
1081
+ completion: `/${command} ${permission.name}`
1082
+ })
1083
+ );
1084
+ }
757
1085
  const modeMatch = input.match(/^\/mode\s+(.*)$/i);
758
1086
  if (modeMatch) {
759
1087
  const query = (modeMatch[1] ?? "").trim().toLowerCase();
@@ -778,9 +1106,9 @@ function suggestSlashWordwheel(input, craftbooks) {
778
1106
  })
779
1107
  );
780
1108
  }
781
- const startMatch = input.match(/^\/start\s+(.*)$/i);
782
- if (startMatch) {
783
- const query = (startMatch[1] ?? "").trim().toLowerCase();
1109
+ const doMatch = input.match(/^\/do\s+(.*)$/i);
1110
+ if (doMatch) {
1111
+ const query = (doMatch[1] ?? "").trim().toLowerCase();
784
1112
  const terms = query.split(/\s+/).filter(Boolean);
785
1113
  return craftbooks.filter((book) => {
786
1114
  const haystack = `${book.id} ${book.name} ${book.description ?? ""}`.toLowerCase();
@@ -791,10 +1119,10 @@ function suggestSlashWordwheel(input, craftbooks) {
791
1119
  return leftRank - rightRank || left.name.localeCompare(right.name);
792
1120
  }).map((book) => ({
793
1121
  key: `craftbook:${book.id}`,
794
- label: `/start ${book.id}`,
1122
+ label: `/do ${book.id}`,
795
1123
  description: `${book.name} \xB7 ${book.stepCount} ${book.stepCount === 1 ? "step" : "steps"} \xB7 ${book.source}`,
796
- submit: `/start ${book.id}`,
797
- completion: `/start ${book.id}`
1124
+ submit: `/do ${book.id}`,
1125
+ completion: `/do ${book.id}`
798
1126
  }));
799
1127
  }
800
1128
  return suggestSlashCommands(input).map((command) => ({
@@ -831,21 +1159,25 @@ function parseInput(raw, cliMode) {
831
1159
  }
832
1160
  return cliMode ? { kind: "shell", text } : { kind: "prompt", text };
833
1161
  }
834
- var SLASH_COMMAND_WORDWHEEL_SIZE, SLASH_COMMANDS, NIGHT_SHIFT_SUBCOMMANDS;
1162
+ var SLASH_COMMAND_WORDWHEEL_SIZE, SLASH_COMMANDS, NIGHT_SHIFT_SUBCOMMANDS, MODEL_SUBCOMMANDS, PROJECT_PERMISSIONS, PROJECT_PERMISSION_USAGE;
835
1163
  var init_commands = __esm({
836
1164
  "src/tui/commands.ts"() {
837
1165
  "use strict";
838
1166
  init_engagement_mode();
1167
+ init_open_command();
839
1168
  SLASH_COMMAND_WORDWHEEL_SIZE = 4;
840
1169
  SLASH_COMMANDS = [
841
1170
  { name: "help", description: "show the command reference" },
842
1171
  { name: "project", description: "switch active project" },
843
1172
  { name: "gezel", description: "switch active gezel" },
1173
+ { name: "allow", description: "allow a project permission" },
1174
+ { name: "disallow", description: "disallow a project permission" },
844
1175
  { name: "mode", description: "set AI activity: read-only through full play" },
845
1176
  { name: "model", description: "switch engine and model" },
846
1177
  { name: "thread", description: "switch the active chat thread" },
1178
+ { name: "open", description: "open a project folder or recent chat file" },
847
1179
  { name: "task", description: "list and manage project tasks" },
848
- { name: "start", description: "start a task from a craftbook" },
1180
+ { name: "do", description: "do a task from a craftbook" },
849
1181
  { name: "continue", description: "process due and active project tasks" },
850
1182
  { name: "nightshift", description: "start, stop, or list night-shift work" },
851
1183
  { name: "focus", description: "send into another active chat" },
@@ -859,6 +1191,29 @@ var init_commands = __esm({
859
1191
  { name: "stop", description: "stop the current night shift" },
860
1192
  { name: "list", description: "show current and upcoming night-shift work" }
861
1193
  ];
1194
+ MODEL_SUBCOMMANDS = [
1195
+ { name: "download", description: "choose and download a new on-device model" }
1196
+ ];
1197
+ PROJECT_PERMISSIONS = [
1198
+ {
1199
+ name: "edits",
1200
+ allowDescription: "let built-in tools and background work edit this project",
1201
+ disallowDescription: "make built-in tools and background work read-only"
1202
+ },
1203
+ {
1204
+ name: "codexedits",
1205
+ allowDescription: "let Codex sessions edit this project",
1206
+ disallowDescription: "put Codex sessions in read-only plan mode"
1207
+ },
1208
+ {
1209
+ name: "claudeedits",
1210
+ allowDescription: "let Claude sessions edit this project",
1211
+ disallowDescription: "put Claude sessions in read-only plan mode"
1212
+ }
1213
+ ];
1214
+ PROJECT_PERMISSION_USAGE = PROJECT_PERMISSIONS.map(
1215
+ (permission) => permission.name
1216
+ ).join("|");
862
1217
  }
863
1218
  });
864
1219
 
@@ -883,6 +1238,24 @@ function reduceFeed(rows, env2) {
883
1238
  open: false
884
1239
  }
885
1240
  ]);
1241
+ case "queue_enqueued": {
1242
+ const key = `queue-${event.queueId}`;
1243
+ const pending = {
1244
+ key,
1245
+ sessionId,
1246
+ gezelId,
1247
+ kind: "pending",
1248
+ text: event.preview,
1249
+ open: false
1250
+ };
1251
+ const idx = rows.findIndex((row) => row.key === key);
1252
+ if (idx === -1) return cap([...rows, pending]);
1253
+ const next = rows.slice();
1254
+ next[idx] = pending;
1255
+ return next;
1256
+ }
1257
+ case "queue_removed":
1258
+ return rows.filter((row) => row.key !== `queue-${event.queueId}`);
886
1259
  case "delta": {
887
1260
  const idx = findOpenAssistant(rows, sessionId);
888
1261
  const open = idx === -1 ? void 0 : rows[idx];
@@ -950,7 +1323,11 @@ function reduceFeed(rows, env2) {
950
1323
  gezelId: "",
951
1324
  kind: "note",
952
1325
  text: `task \xB7 ${event.summary}`,
953
- open: false
1326
+ open: false,
1327
+ taskEvent: {
1328
+ kind: event.kind,
1329
+ ...event.gezelId ? { gezelId: event.gezelId } : {}
1330
+ }
954
1331
  }
955
1332
  ]);
956
1333
  case "error":
@@ -1004,7 +1381,8 @@ function sessionToFeedRows(session) {
1004
1381
  }
1005
1382
  function reduceTurns(turns, env2) {
1006
1383
  const { sessionId, event } = env2;
1007
- const set = (label) => new Map(turns).set(sessionId, label);
1384
+ const prior = turns.get(sessionId);
1385
+ const set = (label, outputChars = prior?.outputChars ?? 0, activeToolName = prior?.activeToolName ?? null) => new Map(turns).set(sessionId, { label, outputChars, activeToolName });
1008
1386
  const clear = () => {
1009
1387
  if (!turns.has(sessionId)) return turns;
1010
1388
  const m = new Map(turns);
@@ -1013,19 +1391,31 @@ function reduceTurns(turns, env2) {
1013
1391
  };
1014
1392
  switch (event.type) {
1015
1393
  case "user_message":
1016
- return set("thinking\u2026");
1394
+ return set("thinking\u2026", 0, null);
1017
1395
  case "queued":
1018
1396
  return set(event.aheadOf > 0 ? `queued \xB7 ${event.aheadOf} ahead` : "queued");
1019
1397
  case "intent":
1020
- return set(event.label);
1398
+ return set(event.label, void 0, null);
1021
1399
  case "engine_phase":
1022
- return set(phaseLabel(event));
1400
+ return set(phaseLabel(event, prior?.outputChars ?? 0), void 0, null);
1023
1401
  case "delta":
1024
- return set("generating");
1025
- case "tool":
1026
- return set("running tool");
1402
+ case "reasoning_delta": {
1403
+ const outputChars = (prior?.outputChars ?? 0) + event.content.length;
1404
+ return set(generationLabel(outputChars), outputChars, null);
1405
+ }
1406
+ case "tool_args_delta": {
1407
+ const outputChars = (prior?.outputChars ?? 0) + event.content.length;
1408
+ const name = event.name.trim() || prior?.activeToolName || null;
1409
+ return set(runningToolLabel(name), outputChars, name);
1410
+ }
1411
+ case "tool": {
1412
+ const name = event.name.trim() || prior?.activeToolName || null;
1413
+ return set(runningToolLabel(name), void 0, name);
1414
+ }
1415
+ case "heartbeat":
1416
+ return event.label ? set(heartbeatLabel(event.label), void 0, null) : turns;
1027
1417
  case "awaiting_gezel":
1028
- return set("awaiting gezel");
1418
+ return set("awaiting gezel", void 0, null);
1029
1419
  case "error":
1030
1420
  case "done":
1031
1421
  return clear();
@@ -1033,7 +1423,7 @@ function reduceTurns(turns, env2) {
1033
1423
  return turns;
1034
1424
  }
1035
1425
  }
1036
- function phaseLabel(event) {
1426
+ function phaseLabel(event, outputChars) {
1037
1427
  const pct = event.progress !== void 0 ? ` ${Math.round(event.progress * 100)}%` : "";
1038
1428
  switch (event.phase) {
1039
1429
  case "starting":
@@ -1043,11 +1433,26 @@ function phaseLabel(event) {
1043
1433
  case "prefill":
1044
1434
  return `reading prompt${pct}`;
1045
1435
  case "generating":
1046
- return "generating";
1436
+ return generationLabel(outputChars);
1047
1437
  default:
1048
1438
  return "ready";
1049
1439
  }
1050
1440
  }
1441
+ function generationLabel(outputChars) {
1442
+ if (!Number.isFinite(outputChars) || outputChars <= 0) return "generating";
1443
+ const tokens = Math.max(1, Math.round(outputChars / 4));
1444
+ return `generating \xB7 ~${tokens.toLocaleString("en-US")} ${tokens === 1 ? "token" : "tokens"}`;
1445
+ }
1446
+ function runningToolLabel(name) {
1447
+ return name ? `running tool \xB7 ${name}` : "running tool";
1448
+ }
1449
+ function heartbeatLabel(label) {
1450
+ const trimmed = label.trim();
1451
+ if (/^(thinking|reasoning|streaming|preparing|working)(?:\b|$)/i.test(trimmed) || /^(running|updating|searching|awaiting|using)(?:\b|$)/i.test(trimmed)) {
1452
+ return trimmed;
1453
+ }
1454
+ return runningToolLabel(trimmed || null);
1455
+ }
1051
1456
  function appendNote(rows, text, kind = "note") {
1052
1457
  const next = [
1053
1458
  ...rows,
@@ -1132,7 +1537,7 @@ function toolRowText(call) {
1132
1537
  }
1133
1538
  function gezelLabel(gezelId, gezels, boring) {
1134
1539
  const g = gezels.find((x) => x.id === gezelId);
1135
- if (!g) return gezelId;
1540
+ if (!g) return boring ? "gezel" : gezelId;
1136
1541
  if (boring) return g.roleBasedName ?? g.role ?? g.id;
1137
1542
  return g.role ? `${g.name} \xB7 ${g.role}` : g.name;
1138
1543
  }
@@ -1276,7 +1681,7 @@ import { jsx, jsxs } from "react/jsx-runtime";
1276
1681
  function ChatFeed(props) {
1277
1682
  const { rows, gezels, boring, focusedSessionId, visible = 16 } = props;
1278
1683
  const shown = rows.slice(Math.max(0, rows.length - visible));
1279
- return /* @__PURE__ */ jsx(Box, { flexDirection: "column", flexGrow: 1, children: shown.length === 0 ? /* @__PURE__ */ jsxs(Box, { flexDirection: "row", marginBottom: 1, children: [
1684
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", flexGrow: 1, marginBottom: 1, children: shown.length === 0 ? /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
1280
1685
  /* @__PURE__ */ jsx(Text, { color: "yellow", children: TABLE_LOGO }),
1281
1686
  /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 3, children: [
1282
1687
  /* @__PURE__ */ jsxs(Text, { children: [
@@ -1290,7 +1695,7 @@ function ChatFeed(props) {
1290
1695
  if (row.kind === "shell" && row.sessionId.startsWith("term-")) {
1291
1696
  return /* @__PURE__ */ jsx(Text, { wrap: "wrap", children: clip(row.text) }, row.key);
1292
1697
  }
1293
- 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";
1698
+ 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";
1294
1699
  const isFocused = focusedSessionId && row.sessionId === focusedSessionId;
1295
1700
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
1296
1701
  /* @__PURE__ */ jsx(Text, { dimColor: !isFocused, color: isFocused ? "green" : void 0, children: isFocused ? "\u258E" : " " }),
@@ -1299,11 +1704,33 @@ function ChatFeed(props) {
1299
1704
  who,
1300
1705
  ": "
1301
1706
  ] }),
1302
- /* @__PURE__ */ jsx(Text, { color: KIND_COLOR[row.kind], children: clip(row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text) })
1707
+ /* @__PURE__ */ jsx(Text, { color: KIND_COLOR[row.kind], dimColor: row.kind === "pending", children: clip(
1708
+ row.taskEvent ? taskEventText(row, gezels, boring) : row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text
1709
+ ) })
1303
1710
  ] })
1304
1711
  ] }, row.key);
1305
1712
  }) });
1306
1713
  }
1714
+ function taskEventText(row, gezels, boring) {
1715
+ const event = row.taskEvent;
1716
+ if (!boring || !event?.gezelId) return row.text;
1717
+ const actor = gezelLabel(event.gezelId, gezels, true);
1718
+ switch (event.kind) {
1719
+ case "task.entry.dispatched":
1720
+ return row.text.replace(/ handed to .*$/, ` handed to ${actor}`);
1721
+ case "tasknote.appended":
1722
+ return row.text.replace(/^task · .*? noted on /, `task \xB7 ${actor} noted on `);
1723
+ case "tasknote.deleted":
1724
+ return row.text.replace(
1725
+ /^task · .*? removed a note from /,
1726
+ `task \xB7 ${actor} removed a note from `
1727
+ );
1728
+ case "tasknote.updated":
1729
+ return row.text.replace(/^task · .*? edited a note on /, `task \xB7 ${actor} edited a note on `);
1730
+ default:
1731
+ return row.text;
1732
+ }
1733
+ }
1307
1734
  function clip(text) {
1308
1735
  const t = text.replace(/\s+$/, "");
1309
1736
  return t.length > MAX_CHARS ? `${t.slice(0, MAX_CHARS)}
@@ -1323,6 +1750,7 @@ var init_ChatFeed = __esm({
1323
1750
  ].join("\n");
1324
1751
  KIND_COLOR = {
1325
1752
  user: "white",
1753
+ pending: "yellow",
1326
1754
  assistant: "cyan",
1327
1755
  tool: "yellow",
1328
1756
  note: "magenta",
@@ -1403,19 +1831,29 @@ var init_Picker = __esm({
1403
1831
 
1404
1832
  // src/tui/components/EnginePill.tsx
1405
1833
  import { Box as Box3, Text as Text3 } from "ink";
1406
- import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1834
+ import { jsxs as jsxs3 } from "react/jsx-runtime";
1407
1835
  function EnginePill(props) {
1408
1836
  const { provider, model: model2, accessMode, busy, label } = props;
1409
- const text = formatEngineStatus(provider, model2, busy, label, accessMode);
1410
- return /* @__PURE__ */ jsx3(Box3, { children: /* @__PURE__ */ jsxs3(Text3, { backgroundColor: busy ? "yellow" : "blackBright", color: busy ? "black" : "white", children: [
1411
- " ",
1412
- text,
1413
- " "
1414
- ] }) });
1837
+ const metadata = formatEngineMetadata(provider, model2, accessMode);
1838
+ const activity = formatEngineActivity(busy, label);
1839
+ return /* @__PURE__ */ jsxs3(Box3, { children: [
1840
+ /* @__PURE__ */ jsxs3(Text3, { children: [
1841
+ " ",
1842
+ metadata,
1843
+ " \xB7"
1844
+ ] }),
1845
+ /* @__PURE__ */ jsxs3(Text3, { backgroundColor: busy ? "yellow" : "blackBright", color: busy ? "black" : "white", children: [
1846
+ " ",
1847
+ activity,
1848
+ " "
1849
+ ] })
1850
+ ] });
1851
+ }
1852
+ function formatEngineMetadata(provider, model2, accessMode) {
1853
+ return [accessMode, formatEngineIdentity(provider, model2)].filter(Boolean).join(" \xB7 ");
1415
1854
  }
1416
- function formatEngineStatus(provider, model2, busy, label, accessMode) {
1417
- const activity = busy ? `\u25CF ${label ?? "working"}` : "\u25CB idle";
1418
- return [activity, accessMode, formatEngineIdentity(provider, model2)].filter(Boolean).join(" \xB7 ");
1855
+ function formatEngineActivity(busy, label) {
1856
+ return busy ? `\u25CF ${label ?? "working"}` : "\u25CB idle";
1419
1857
  }
1420
1858
  function formatEngineIdentity(provider, model2) {
1421
1859
  const engine = provider === "llama-cpp" ? "llama" : provider ?? "on-device";
@@ -1431,7 +1869,7 @@ var init_EnginePill = __esm({
1431
1869
  import { Box as Box4, Text as Text4, useInput as useInput2 } from "ink";
1432
1870
  import TextInput from "ink-text-input";
1433
1871
  import { useEffect, useState as useState2 } from "react";
1434
- import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
1872
+ import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs4 } from "react/jsx-runtime";
1435
1873
  function PromptLine(props) {
1436
1874
  const {
1437
1875
  projectName,
@@ -1447,6 +1885,7 @@ function PromptLine(props) {
1447
1885
  active,
1448
1886
  history,
1449
1887
  craftbooks,
1888
+ recentOpenReferences,
1450
1889
  pendingPrompt,
1451
1890
  pendingMode,
1452
1891
  onChange,
@@ -1454,7 +1893,7 @@ function PromptLine(props) {
1454
1893
  } = props;
1455
1894
  const [cursor, setCursor] = useState2(history.length);
1456
1895
  const [suggestionIndex, setSuggestionIndex] = useState2(0);
1457
- const suggestions = active && !pendingPrompt ? suggestSlashWordwheel(value, craftbooks) : [];
1896
+ const suggestions = active && !pendingPrompt ? suggestSlashWordwheel(value, craftbooks, recentOpenReferences) : [];
1458
1897
  const activeSuggestionIndex = Math.min(suggestionIndex, Math.max(0, suggestions.length - 1));
1459
1898
  const suggestionWindowStart = Math.min(
1460
1899
  Math.max(0, activeSuggestionIndex - SLASH_COMMAND_WORDWHEEL_SIZE + 1),
@@ -1509,18 +1948,18 @@ function PromptLine(props) {
1509
1948
  const placeholder = pendingPrompt ? pendingPrompt : mode === "cli" ? "shell / @tool \u2026 (/chat to exit)" : "message, or /command, !shell, @tool";
1510
1949
  return /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", children: [
1511
1950
  /* @__PURE__ */ jsxs4(Box4, { children: [
1512
- /* @__PURE__ */ jsx4(Text4, { color: "blue", children: projectName }),
1513
- /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: " \xB7 " }),
1514
- /* @__PURE__ */ jsx4(Text4, { color: "magenta", children: gezelLabel2 }),
1951
+ /* @__PURE__ */ jsx3(Text4, { color: "blue", children: projectName }),
1952
+ /* @__PURE__ */ jsx3(Text4, { dimColor: true, children: " \xB7 " }),
1953
+ /* @__PURE__ */ jsx3(Text4, { color: "magenta", children: gezelLabel2 }),
1515
1954
  threadTitle ? /* @__PURE__ */ jsxs4(Fragment2, { children: [
1516
- /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: " \xB7 " }),
1955
+ /* @__PURE__ */ jsx3(Text4, { dimColor: true, children: " \xB7 " }),
1517
1956
  /* @__PURE__ */ jsxs4(Text4, { color: "cyan", children: [
1518
1957
  "\u21B3 ",
1519
1958
  compactThreadTitle(threadTitle)
1520
1959
  ] })
1521
1960
  ] }) : null,
1522
- /* @__PURE__ */ jsx4(Text4, { children: " " }),
1523
- /* @__PURE__ */ jsx4(
1961
+ /* @__PURE__ */ jsx3(Text4, { children: " " }),
1962
+ /* @__PURE__ */ jsx3(
1524
1963
  EnginePill,
1525
1964
  {
1526
1965
  provider,
@@ -1550,8 +1989,8 @@ function PromptLine(props) {
1550
1989
  ] })
1551
1990
  ] }) : null,
1552
1991
  /* @__PURE__ */ jsxs4(Box4, { children: [
1553
- /* @__PURE__ */ jsx4(Text4, { color: pendingPrompt ? "yellow" : mode === "cli" ? "green" : "cyan", children: prefix }),
1554
- /* @__PURE__ */ jsx4(
1992
+ /* @__PURE__ */ jsx3(Text4, { color: pendingPrompt ? "yellow" : mode === "cli" ? "green" : "cyan", children: prefix }),
1993
+ /* @__PURE__ */ jsx3(
1555
1994
  TextInput,
1556
1995
  {
1557
1996
  value,
@@ -1581,7 +2020,7 @@ var init_PromptLine = __esm({
1581
2020
  import { Box as Box5, Text as Text5, useInput as useInput3 } from "ink";
1582
2021
  import TextInput2 from "ink-text-input";
1583
2022
  import { useState as useState3 } from "react";
1584
- import { Fragment as Fragment3, jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
2023
+ import { Fragment as Fragment3, jsx as jsx4, jsxs as jsxs5 } from "react/jsx-runtime";
1585
2024
  function questionOptionCount(question) {
1586
2025
  const choices = question.choices?.length ?? 0;
1587
2026
  const writeIn = question.allowWriteIn ?? true;
@@ -1681,11 +2120,11 @@ function QuestionPrompt(props) {
1681
2120
  askerLabel,
1682
2121
  " asks"
1683
2122
  ] }),
1684
- /* @__PURE__ */ jsx5(Text5, { wrap: "wrap", children: question.prompt }),
2123
+ /* @__PURE__ */ jsx4(Text5, { wrap: "wrap", children: question.prompt }),
1685
2124
  writing ? /* @__PURE__ */ jsxs5(Fragment3, { children: [
1686
2125
  /* @__PURE__ */ jsxs5(Box5, { children: [
1687
- /* @__PURE__ */ jsx5(Text5, { color: "cyan", children: "\u203A " }),
1688
- /* @__PURE__ */ jsx5(
2126
+ /* @__PURE__ */ jsx4(Text5, { color: "cyan", children: "\u203A " }),
2127
+ /* @__PURE__ */ jsx4(
1689
2128
  TextInput2,
1690
2129
  {
1691
2130
  value: writeIn,
@@ -1718,8 +2157,8 @@ function QuestionPrompt(props) {
1718
2157
  options.length > QUESTION_OPTION_WINDOW_SIZE ? ` \xB7 ${activeOptionIndex + 1}/${options.length}` : ""
1719
2158
  ] })
1720
2159
  ] }),
1721
- submitting ? /* @__PURE__ */ jsx5(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
1722
- error ? /* @__PURE__ */ jsx5(Text5, { color: "red", children: error }) : null
2160
+ submitting ? /* @__PURE__ */ jsx4(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
2161
+ error ? /* @__PURE__ */ jsx4(Text5, { color: "red", children: error }) : null
1723
2162
  ] });
1724
2163
  }
1725
2164
  function toggleSet(current, value) {
@@ -1736,97 +2175,10 @@ var init_QuestionPrompt = __esm({
1736
2175
  }
1737
2176
  });
1738
2177
 
1739
- // src/tui/craftbook-start.ts
2178
+ // src/tui/model-picker.ts
1740
2179
  import {
1741
- CRAFTBOOK_ROLE_META
2180
+ formatModelAttribution as formatModelAttribution2
1742
2181
  } from "@bendyline/gezel";
1743
- function normalizeCraftbooks(items) {
1744
- const byId = /* @__PURE__ */ new Map();
1745
- for (const item of items) {
1746
- if (item.manifest.kind !== "craftbook-template") continue;
1747
- const manifest = item.manifest;
1748
- if (byId.has(manifest.id)) continue;
1749
- byId.set(manifest.id, {
1750
- id: manifest.id,
1751
- name: manifest.name,
1752
- ...manifest.description ? { description: manifest.description } : {},
1753
- version: manifest.version,
1754
- sourceId: item.sourceId,
1755
- source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
1756
- stepCount: manifest.steps.length,
1757
- tags: manifest.tags ?? [],
1758
- role: manifest.role ?? "general"
1759
- });
1760
- }
1761
- return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
1762
- }
1763
- function craftbookCategories(books, suggestedIds, projectType) {
1764
- const categories = [];
1765
- const allIds = new Set(books.map((book) => book.id));
1766
- const recommended = new Set([...suggestedIds].filter((id) => allIds.has(id)));
1767
- if (recommended.size > 0) {
1768
- categories.push({
1769
- id: "recommended",
1770
- label: projectType ? `Recommended for ${projectType.label}` : "Recommended",
1771
- hint: countLabel(recommended.size),
1772
- bookIds: recommended
1773
- });
1774
- }
1775
- const projectBooks = new Set(
1776
- books.filter((book) => book.source === "project").map((book) => book.id)
1777
- );
1778
- if (projectBooks.size > 0) {
1779
- categories.push({
1780
- id: "project",
1781
- label: "Project craftbooks",
1782
- hint: countLabel(projectBooks.size),
1783
- bookIds: projectBooks
1784
- });
1785
- }
1786
- for (const role of CRAFTBOOK_ROLE_META) {
1787
- const bookIds = new Set(books.filter((book) => book.role === role.id).map((book) => book.id));
1788
- if (bookIds.size === 0) continue;
1789
- categories.push({
1790
- id: `role:${role.id}`,
1791
- label: role.label,
1792
- hint: countLabel(bookIds.size),
1793
- bookIds
1794
- });
1795
- }
1796
- categories.push({
1797
- id: "all",
1798
- label: "All craftbooks",
1799
- hint: countLabel(allIds.size),
1800
- bookIds: allIds
1801
- });
1802
- return categories;
1803
- }
1804
- function countLabel(count) {
1805
- return `${count} ${count === 1 ? "craftbook" : "craftbooks"}`;
1806
- }
1807
- function findCraftbook(books, value) {
1808
- const query = value.trim().toLowerCase();
1809
- return books.find((book) => book.id.toLowerCase() === query || book.name.toLowerCase() === query);
1810
- }
1811
- function craftbookStartRequest(book) {
1812
- const summary = book.description?.trim();
1813
- const description = summary ? `Start the "${book.name}" craftbook for this project. ${summary}` : `Start the "${book.name}" craftbook for this project. Follow every step in the recipe and verify its required outcomes before completing the task.`;
1814
- return {
1815
- title: book.name,
1816
- description,
1817
- craftbookId: book.id,
1818
- craftbookSourceId: book.sourceId,
1819
- ...book.version ? { craftbookVersion: book.version } : {},
1820
- dispatchEntry: true
1821
- };
1822
- }
1823
- var init_craftbook_start = __esm({
1824
- "src/tui/craftbook-start.ts"() {
1825
- "use strict";
1826
- }
1827
- });
1828
-
1829
- // src/tui/model-picker.ts
1830
2182
  function modelProviderLabel(provider) {
1831
2183
  switch (provider) {
1832
2184
  case "copilot":
@@ -1867,9 +2219,10 @@ function configuredModelProviders(config, opts) {
1867
2219
  return providers.sort((a, b) => PROVIDER_ORDER.indexOf(a) - PROVIDER_ORDER.indexOf(b));
1868
2220
  }
1869
2221
  async function loadModelChoices(client, config, platform = process.platform, arch = process.arch) {
1870
- const [copilot, memory] = await Promise.all([
2222
+ const [copilot, memory, catalog] = await Promise.all([
1871
2223
  client.getCopilotStatus().catch(() => null),
1872
- client.getMemoryProfile().catch(() => null)
2224
+ client.getMemoryProfile().catch(() => null),
2225
+ client.listCatalogItems ? client.listCatalogItems("chat-model").catch(() => null) : Promise.resolve(null)
1873
2226
  ]);
1874
2227
  const providers = configuredModelProviders(config, {
1875
2228
  platform,
@@ -1888,18 +2241,76 @@ async function loadModelChoices(client, config, platform = process.platform, arc
1888
2241
  })
1889
2242
  );
1890
2243
  return inventories.flatMap(
1891
- ({ provider, models }) => models.map((model2) => ({
1892
- provider,
1893
- model: model2,
1894
- value: `${provider}:${model2.id}`,
1895
- label: `${modelProviderLabel(provider)} \xB7 ${model2.name}`
1896
- }))
2244
+ ({ provider, models }) => models.map((model2) => {
2245
+ const manifest = catalogManifestForModel(catalog?.items ?? [], provider, model2.id);
2246
+ const attribution = manifest ? ` (${formatModelAttribution2(manifest)})` : "";
2247
+ return {
2248
+ provider,
2249
+ model: model2,
2250
+ value: `${provider}:${model2.id}`,
2251
+ label: `${modelProviderLabel(provider)} \xB7 ${model2.name}${attribution}`
2252
+ };
2253
+ })
1897
2254
  );
1898
2255
  }
2256
+ async function loadModelDownloadChoices(client, config, platform = process.platform, arch = process.arch) {
2257
+ const [memory, catalog] = await Promise.all([
2258
+ client.getMemoryProfile(),
2259
+ client.listCatalogItems("chat-model")
2260
+ ]);
2261
+ const provider = config.provider === "mlx" || config.provider === "llama-cpp" ? config.provider : memory.platform === "darwin" && platform === "darwin" && arch === "arm64" ? "mlx" : "llama-cpp";
2262
+ const installed = await client.listProviderModels(provider).catch(() => ({ models: [] }));
2263
+ const installedIds = new Set(installed.models.map((model2) => model2.id));
2264
+ const ranked = rankChatModels(
2265
+ catalog.items,
2266
+ {
2267
+ platform: memory.platform,
2268
+ gpuVramBytes: memory.gpuVramBytes,
2269
+ ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
2270
+ totalRamBytes: memory.totalRamBytes,
2271
+ usableBytes: memory.usableBytes,
2272
+ ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
2273
+ },
2274
+ provider
2275
+ );
2276
+ return ranked.filter((model2) => !installedIds.has(model2.id)).map((model2, index) => ({
2277
+ provider,
2278
+ model: model2,
2279
+ value: `${provider}:${model2.id}`,
2280
+ label: bootstrapChatModelLabel(model2),
2281
+ hint: [
2282
+ index === 0 ? "recommended" : null,
2283
+ formatDownloadSize(model2.approxSizeBytes),
2284
+ modelFitLabel(model2.fit)
2285
+ ].filter(Boolean).join(" \xB7 ")
2286
+ }));
2287
+ }
2288
+ function catalogManifestForModel(items, provider, modelId) {
2289
+ for (const item of items) {
2290
+ if (item.manifest.kind !== "chat-model") continue;
2291
+ const manifest = item.manifest;
2292
+ if (manifest.id === modelId) return manifest;
2293
+ if (provider === "ollama" && manifest.ollama?.tag === modelId) return manifest;
2294
+ }
2295
+ return null;
2296
+ }
2297
+ function modelFitLabel(fit) {
2298
+ switch (fit) {
2299
+ case "fits":
2300
+ return "fits this device";
2301
+ case "fits-offload":
2302
+ return "fits with offload";
2303
+ case "tight":
2304
+ return "tight fit";
2305
+ case "too-big":
2306
+ return "larger than recommended";
2307
+ }
2308
+ }
1899
2309
  var PROVIDER_ORDER;
1900
2310
  var init_model_picker = __esm({
1901
2311
  "src/tui/model-picker.ts"() {
1902
2312
  "use strict";
2313
+ init_bootstrap();
1903
2314
  PROVIDER_ORDER = [
1904
2315
  "mlx",
1905
2316
  "llama-cpp",
@@ -2010,7 +2421,7 @@ var init_streams = __esm({
2010
2421
  // src/tui/App.tsx
2011
2422
  import { Box as Box6, Text as Text6, useApp, useInput as useInput4, useStdout } from "ink";
2012
2423
  import { useCallback, useEffect as useEffect3, useMemo, useRef as useRef2, useState as useState4 } from "react";
2013
- import { jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
2424
+ import { jsx as jsx5, jsxs as jsxs6 } from "react/jsx-runtime";
2014
2425
  function useTerminalSize() {
2015
2426
  const { stdout } = useStdout();
2016
2427
  const [size, setSize] = useState4({ rows: stdout?.rows ?? 24, columns: stdout?.columns ?? 80 });
@@ -2040,6 +2451,11 @@ function App(props) {
2040
2451
  );
2041
2452
  const [startCategoryId, setStartCategoryId] = useState4(null);
2042
2453
  const [modelChoices, setModelChoices] = useState4([]);
2454
+ const [modelDownloadChoices, setModelDownloadChoices] = useState4([]);
2455
+ const [modelDownloadProgress, setModelDownloadProgress] = useState4(
2456
+ null
2457
+ );
2458
+ const [modelDownloadReturn, setModelDownloadReturn] = useState4(null);
2043
2459
  const [modelChoicesLoading, setModelChoicesLoading] = useState4(false);
2044
2460
  const [threadsLoading, setThreadsLoading] = useState4(false);
2045
2461
  const [pendingQuestions, setPendingQuestions] = useState4([]);
@@ -2054,6 +2470,8 @@ function App(props) {
2054
2470
  const [value, setValue] = useState4("");
2055
2471
  const [rows, setRows] = useState4([]);
2056
2472
  const [turns, setTurns] = useState4(() => /* @__PURE__ */ new Map());
2473
+ const [recentOpenReferences, setRecentOpenReferences] = useState4([]);
2474
+ const recentOpenReferencesRef = useRef2([]);
2057
2475
  const [status, setStatus] = useState4("Connecting\u2026");
2058
2476
  const [history, setHistory] = useState4([]);
2059
2477
  const [activeRuns, setActiveRuns] = useState4(() => /* @__PURE__ */ new Set());
@@ -2064,11 +2482,11 @@ function App(props) {
2064
2482
  const pendingQuestion = pendingQuestions[0];
2065
2483
  const { rows: termRows, columns: termColumns } = useTerminalSize();
2066
2484
  const shellColumns = Math.min(500, Math.max(20, termColumns - 2));
2067
- const wordwheelCount = overlay === null && !pendingInput && !pendingQuestion ? suggestSlashWordwheel(value, craftbooks).length : 0;
2485
+ const wordwheelCount = overlay === null && !pendingInput && !pendingQuestion ? suggestSlashWordwheel(value, craftbooks, recentOpenReferences).length : 0;
2068
2486
  const wordwheelRows = wordwheelCount > 0 ? Math.min(SLASH_COMMAND_WORDWHEEL_SIZE, wordwheelCount) + 1 : 0;
2069
2487
  const questionRows = pendingQuestion ? Math.min(QUESTION_OPTION_WINDOW_SIZE, Math.max(1, questionOptionCount(pendingQuestion))) + 4 : 0;
2070
2488
  const modelPickerWindowSize = Math.max(4, Math.min(10, termRows - 12));
2071
- const inventoryPickerRows = overlay === "model" || overlay === "start-category" || overlay === "start-craftbook" ? modelPickerWindowSize + 5 : 0;
2489
+ const inventoryPickerRows = overlay === "model" || overlay === "model-download" || overlay === "start-category" || overlay === "start-craftbook" ? modelPickerWindowSize + 5 : 0;
2072
2490
  const visibleRows = Math.max(
2073
2491
  4,
2074
2492
  termRows - 7 - wordwheelRows - questionRows - inventoryPickerRows
@@ -2083,12 +2501,33 @@ function App(props) {
2083
2501
  const effectiveModel = activeGezel?.model ?? (effectiveProvider ? config?.defaultModel?.[effectiveProvider] : void 0);
2084
2502
  const statusLabel = useMemo(() => {
2085
2503
  if (turns.size === 0) return void 0;
2086
- return focusedSessionId && turns.get(focusedSessionId) || ownSessionId && turns.get(ownSessionId) || turns.values().next().value;
2504
+ const turn = focusedSessionId && turns.get(focusedSessionId) || ownSessionId && turns.get(ownSessionId) || turns.values().next().value;
2505
+ return turn?.label;
2087
2506
  }, [turns, focusedSessionId, ownSessionId]);
2088
2507
  const note = useCallback(
2089
2508
  (text, kind = "note") => setRows((r) => appendNote(r, text, kind)),
2090
2509
  []
2091
2510
  );
2511
+ useEffect3(() => {
2512
+ recentOpenReferencesRef.current = recentOpenReferences;
2513
+ }, [recentOpenReferences]);
2514
+ const gezelIds = useRef2(/* @__PURE__ */ new Set());
2515
+ const gezelRefreshInFlight = useRef2(false);
2516
+ const applyGezelSnapshot = useCallback((next) => {
2517
+ gezelIds.current = new Set(next.map((gezel) => gezel.id));
2518
+ setGezels(next);
2519
+ }, []);
2520
+ const refreshGezels = useCallback(async () => {
2521
+ if (gezelRefreshInFlight.current) return;
2522
+ gezelRefreshInFlight.current = true;
2523
+ try {
2524
+ const result = await client.listGezels();
2525
+ applyGezelSnapshot(result.gezels);
2526
+ } catch {
2527
+ } finally {
2528
+ gezelRefreshInFlight.current = false;
2529
+ }
2530
+ }, [applyGezelSnapshot, client]);
2092
2531
  const taskLoadSequence = useRef2(0);
2093
2532
  const refreshTasks = useCallback(async () => {
2094
2533
  const sequence = ++taskLoadSequence.current;
@@ -2104,13 +2543,13 @@ function App(props) {
2104
2543
  const sequence = ++craftbookLoadSequence.current;
2105
2544
  const result = await client.listProjectCraftbooks(projectId);
2106
2545
  if (sequence !== craftbookLoadSequence.current) return [];
2107
- const next = normalizeCraftbooks(result.items);
2546
+ const next = normalizeCraftbooks(result.items, config?.showWorkInProgressFeatures === true);
2108
2547
  setCraftbooks(next);
2109
2548
  setCraftbookProjectType(result.projectType ?? null);
2110
2549
  setSuggestedCraftbookIds(new Set(result.suggestedIds ?? []));
2111
2550
  setCraftbooksNeedingSetup(new Set(Object.keys(result.missingToolsets)));
2112
2551
  return next;
2113
- }, [client, projectId]);
2552
+ }, [client, config?.showWorkInProgressFeatures, projectId]);
2114
2553
  useProjectEvents(
2115
2554
  client,
2116
2555
  projectId,
@@ -2118,6 +2557,14 @@ function App(props) {
2118
2557
  (env2) => {
2119
2558
  setRows((r) => reduceFeed(r, env2));
2120
2559
  setTurns((t) => reduceTurns(t, env2));
2560
+ const observedReferences = cliOpenReferencesFromEvent(env2);
2561
+ if (observedReferences.length > 0) {
2562
+ setRecentOpenReferences(
2563
+ (current) => rememberCliOpenReferences(current, observedReferences)
2564
+ );
2565
+ }
2566
+ const eventGezelId = env2.gezelId || (env2.event.type === "task_event" ? env2.event.gezelId : void 0);
2567
+ if (eventGezelId && !gezelIds.current.has(eventGezelId)) void refreshGezels();
2121
2568
  if (env2.event.type === "task_event") void refreshTasks();
2122
2569
  if (env2.event.type === "user_message" && env2.sessionId === ownSessionId) {
2123
2570
  const nextTitle = env2.event.message.content.slice(0, 60).trim() || "Untitled";
@@ -2133,7 +2580,7 @@ function App(props) {
2133
2580
  setPendingQuestions((questions) => updatePendingQuestion(questions, question));
2134
2581
  }
2135
2582
  },
2136
- [ownSessionId, refreshTasks]
2583
+ [ownSessionId, refreshGezels, refreshTasks]
2137
2584
  )
2138
2585
  );
2139
2586
  useTerminalEvents(
@@ -2172,7 +2619,11 @@ function App(props) {
2172
2619
  const ensureSession = useCallback(
2173
2620
  async (gezelId, pid) => {
2174
2621
  try {
2175
- const session = await client.createChatSession({ gezelId, projectId: pid });
2622
+ const session = await client.createChatSession({
2623
+ gezelId,
2624
+ projectId: pid,
2625
+ roleBasedNameOnlyMode: boring
2626
+ });
2176
2627
  setOwnSessionId(session.id);
2177
2628
  setFocusedSessionId(session.id);
2178
2629
  setActiveThreadTitle(displayThreadTitle(session.title));
@@ -2182,7 +2633,7 @@ function App(props) {
2182
2633
  return false;
2183
2634
  }
2184
2635
  },
2185
- [client, note]
2636
+ [client, note, boring]
2186
2637
  );
2187
2638
  const switchProject = useCallback(
2188
2639
  async (id) => {
@@ -2195,6 +2646,7 @@ function App(props) {
2195
2646
  setProjectName(project.name);
2196
2647
  setActiveGezelId(gezelId);
2197
2648
  setRows([]);
2649
+ setRecentOpenReferences([]);
2198
2650
  setTurns(/* @__PURE__ */ new Map());
2199
2651
  setActiveRuns(/* @__PURE__ */ new Set());
2200
2652
  setPendingInput(null);
@@ -2216,6 +2668,56 @@ function App(props) {
2216
2668
  },
2217
2669
  [client, ensureSession, note, projectId, projects]
2218
2670
  );
2671
+ const openModelPicker = useCallback(async () => {
2672
+ if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2673
+ if (activeGezel.fixedFunction) {
2674
+ return note("this gezel runs a fixed tool and does not use a chat model.", "error");
2675
+ }
2676
+ if (modelChoicesLoading) return note("model choices are already loading.");
2677
+ setModelChoicesLoading(true);
2678
+ note("loading available engines and models\u2026");
2679
+ try {
2680
+ const choices = await loadModelChoices(client, config ?? await client.getConfig());
2681
+ setModelChoices(choices);
2682
+ setOverlay("model");
2683
+ } catch (err) {
2684
+ note(`could not load models: ${errMsg(err)}`, "error");
2685
+ } finally {
2686
+ setModelChoicesLoading(false);
2687
+ }
2688
+ }, [activeGezel, activeGezelId, client, config, modelChoicesLoading, note]);
2689
+ const openModelDownloadPicker = useCallback(
2690
+ async (returnTo = null) => {
2691
+ if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2692
+ if (activeGezel.fixedFunction) {
2693
+ return note("this gezel runs a fixed tool and does not use a chat model.", "error");
2694
+ }
2695
+ if (modelChoicesLoading) return note("model choices are already loading.");
2696
+ setOverlay(null);
2697
+ setModelChoicesLoading(true);
2698
+ note("finding on-device models that fit this machine\u2026");
2699
+ try {
2700
+ const choices = await loadModelDownloadChoices(
2701
+ client,
2702
+ config ?? await client.getConfig()
2703
+ );
2704
+ if (choices.length === 0) {
2705
+ note("no additional compatible on-device models are available to download.");
2706
+ if (returnTo === "model") await openModelPicker();
2707
+ return;
2708
+ }
2709
+ setModelDownloadChoices(choices);
2710
+ setModelDownloadProgress(null);
2711
+ setModelDownloadReturn(returnTo);
2712
+ setOverlay("model-download");
2713
+ } catch (err) {
2714
+ note(`could not load downloadable models: ${errMsg(err)}`, "error");
2715
+ } finally {
2716
+ setModelChoicesLoading(false);
2717
+ }
2718
+ },
2719
+ [activeGezel, activeGezelId, client, config, modelChoicesLoading, note, openModelPicker]
2720
+ );
2219
2721
  const openThreadPicker = useCallback(async () => {
2220
2722
  if (!activeGezelId) return note("no active gezel yet.", "error");
2221
2723
  if (threadsLoading) return;
@@ -2242,6 +2744,7 @@ function App(props) {
2242
2744
  setFocusedSessionId(session.id);
2243
2745
  setActiveThreadTitle(displayThreadTitle(session.title));
2244
2746
  setRows(sessionToFeedRows(session));
2747
+ setRecentOpenReferences(cliOpenReferencesFromSession(session));
2245
2748
  } catch (err) {
2246
2749
  note(`could not switch thread: ${errMsg(err)}`, "error");
2247
2750
  }
@@ -2252,16 +2755,21 @@ function App(props) {
2252
2755
  setOverlay(null);
2253
2756
  if (!activeGezelId) return note("no active gezel yet.", "error");
2254
2757
  try {
2255
- const session = await client.createChatSession({ gezelId: activeGezelId, projectId });
2758
+ const session = await client.createChatSession({
2759
+ gezelId: activeGezelId,
2760
+ projectId,
2761
+ roleBasedNameOnlyMode: boring
2762
+ });
2256
2763
  setOwnSessionId(session.id);
2257
2764
  setFocusedSessionId(session.id);
2258
2765
  setActiveThreadTitle(displayThreadTitle(session.title));
2259
2766
  setRows([]);
2767
+ setRecentOpenReferences([]);
2260
2768
  setThreads((current) => [session, ...current.filter((item) => item.id !== session.id)]);
2261
2769
  } catch (err) {
2262
2770
  note(`could not start a thread: ${errMsg(err)}`, "error");
2263
2771
  }
2264
- }, [activeGezelId, client, note, projectId]);
2772
+ }, [activeGezelId, client, note, projectId, boring]);
2265
2773
  useEffect3(() => {
2266
2774
  let cancelled = false;
2267
2775
  (async () => {
@@ -2273,22 +2781,31 @@ function App(props) {
2273
2781
  ]);
2274
2782
  if (cancelled) return;
2275
2783
  setConfig(cfg);
2276
- setGezels(gz.gezels);
2277
- setProjects(
2278
- pj.projects.map((p) => ({
2279
- id: p.id,
2280
- name: p.name,
2281
- workingDir: p.workingDir,
2282
- voormanGezelId: p.voormanGezelId,
2283
- managedWorkspaceWritePolicy: p.managedWorkspaceWritePolicy,
2284
- allowGezelWrites: p.allowGezelWrites,
2285
- codexPermissionMode: p.codexPermissionMode,
2286
- claudePermissionMode: p.claudePermissionMode
2287
- }))
2288
- );
2784
+ applyGezelSnapshot(gz.gezels);
2785
+ const projectRows = pj.projects.map((p) => ({
2786
+ id: p.id,
2787
+ name: p.name,
2788
+ workingDir: p.workingDir,
2789
+ voormanGezelId: p.voormanGezelId,
2790
+ managedWorkspaceWritePolicy: p.managedWorkspaceWritePolicy,
2791
+ allowGezelWrites: p.allowGezelWrites,
2792
+ codexPermissionMode: p.codexPermissionMode,
2793
+ claudePermissionMode: p.claudePermissionMode
2794
+ }));
2795
+ setProjects(projectRows);
2289
2796
  const gezelId = props.initialGezelId;
2797
+ const initialGezel = gz.gezels.find((gezel) => gezel.id === gezelId);
2798
+ const initialProject = projectRows.find((project) => project.id === projectId);
2290
2799
  setActiveGezelId(gezelId);
2291
2800
  setStatus(null);
2801
+ if (activeAccessMode({
2802
+ provider: initialGezel?.provider ?? cfg.provider,
2803
+ project: initialProject,
2804
+ gezel: initialGezel,
2805
+ config: cfg
2806
+ }) === "read-only") {
2807
+ note(READ_ONLY_BOOT_NOTE);
2808
+ }
2292
2809
  await ensureSession(gezelId, projectId);
2293
2810
  } catch (err) {
2294
2811
  if (!cancelled) setStatus(`Failed to connect: ${errMsg(err)}`);
@@ -2360,7 +2877,8 @@ function App(props) {
2360
2877
  for (const r of rows) {
2361
2878
  if (r.sessionId === "local" || r.sessionId.startsWith("term-")) continue;
2362
2879
  if (!seen.has(r.sessionId)) {
2363
- const label = gezels.find((g) => g.id === r.gezelId)?.name ?? (r.gezelId || r.sessionId);
2880
+ const gezel = gezels.find((candidate) => candidate.id === r.gezelId);
2881
+ const label = boring ? gezelLabel(r.gezelId, gezels, true) : gezel?.name ?? (r.gezelId || r.sessionId);
2364
2882
  seen.set(r.sessionId, label);
2365
2883
  }
2366
2884
  }
@@ -2371,7 +2889,7 @@ function App(props) {
2371
2889
  items.push({ label, value: sid });
2372
2890
  }
2373
2891
  return items;
2374
- }, [rows, gezels, ownSessionId, gezelLine]);
2892
+ }, [rows, gezels, ownSessionId, gezelLine, boring]);
2375
2893
  const cancelActive = useCallback(async () => {
2376
2894
  const sessions = [...turns.keys()];
2377
2895
  const runs = [...activeRuns];
@@ -2404,12 +2922,46 @@ function App(props) {
2404
2922
  },
2405
2923
  [client, note]
2406
2924
  );
2925
+ const applyProjectPermission = useCallback(
2926
+ async (permission, allowed) => {
2927
+ const permissionName = parseProjectPermissionName(permission);
2928
+ if (!permissionName) {
2929
+ note(`usage: /${allowed ? "allow" : "disallow"} ${PROJECT_PERMISSION_USAGE}`, "error");
2930
+ return;
2931
+ }
2932
+ try {
2933
+ const patch = permissionName === "edits" ? { managedWorkspaceWritePolicy: allowed ? "allow" : "deny" } : permissionName === "codexedits" ? { codexPermissionMode: allowed ? "edit" : "plan" } : { claudePermissionMode: allowed ? "acceptEdits" : "plan" };
2934
+ const updated = await client.updateProject(projectId, patch);
2935
+ setProjects(
2936
+ (current) => current.map(
2937
+ (project) => project.id === projectId ? { ...project, ...updated } : project
2938
+ )
2939
+ );
2940
+ if (permissionName === "edits") {
2941
+ note(
2942
+ 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}.`
2943
+ );
2944
+ } else {
2945
+ const provider = permissionName === "codexedits" ? "Codex" : "Claude";
2946
+ note(
2947
+ allowed ? `${provider} edits allowed. ${provider} sessions can now modify ${projectName}.` : `${provider} edits disallowed. ${provider} sessions are now read-only in ${projectName}.`
2948
+ );
2949
+ }
2950
+ } catch (err) {
2951
+ note(`could not change project permission: ${errMsg(err)}`, "error");
2952
+ }
2953
+ },
2954
+ [client, note, projectId, projectName]
2955
+ );
2407
2956
  const startCraftbook = useCallback(
2408
2957
  async (book) => {
2409
2958
  setOverlay(null);
2410
2959
  note(`starting ${book.name}\u2026`);
2411
2960
  try {
2412
- const created = await client.createTask(projectId, craftbookStartRequest(book));
2961
+ const created = await client.createTask(projectId, {
2962
+ ...craftbookStartRequest(book),
2963
+ roleBasedNameOnlyMode: boring
2964
+ });
2413
2965
  rememberTask(created);
2414
2966
  setManagedTaskRef(created.ref);
2415
2967
  note(`started ${created.ref} \u2014 ${created.title}`);
@@ -2417,7 +2969,7 @@ function App(props) {
2417
2969
  note(`could not start ${book.name}: ${errMsg(err)}`, "error");
2418
2970
  }
2419
2971
  },
2420
- [client, note, projectId, rememberTask]
2972
+ [boring, client, note, projectId, rememberTask]
2421
2973
  );
2422
2974
  const submitTaskPrompt = useCallback(
2423
2975
  async (raw) => {
@@ -2436,7 +2988,8 @@ function App(props) {
2436
2988
  title: text,
2437
2989
  description: `${text} \u2014 complete this task and verify that the result meets the requested outcome.`,
2438
2990
  assignee: { kind: "user" },
2439
- steps: [{ name: "Main" }]
2991
+ steps: [{ name: "Main" }],
2992
+ roleBasedNameOnlyMode: boring
2440
2993
  });
2441
2994
  rememberTask(created);
2442
2995
  setManagedTaskRef(created.ref);
@@ -2455,7 +3008,7 @@ function App(props) {
2455
3008
  note(`task update failed: ${errMsg(err)}`, "error");
2456
3009
  }
2457
3010
  },
2458
- [client, note, projectId, rememberTask, taskPrompt, tasks]
3011
+ [boring, client, note, projectId, rememberTask, taskPrompt, tasks]
2459
3012
  );
2460
3013
  const applyTaskStatus = useCallback(
2461
3014
  async (status2) => {
@@ -2520,7 +3073,10 @@ function App(props) {
2520
3073
  const target = focusedSessionId ?? ownSessionId;
2521
3074
  if (!target) return note("no active session yet.", "error");
2522
3075
  try {
2523
- await client.sendToChatSession(target, parsed.text);
3076
+ await client.sendToChatSession(
3077
+ target,
3078
+ turns.has(target) ? { message: parsed.text, nudge: true } : parsed.text
3079
+ );
2524
3080
  } catch (err) {
2525
3081
  note(`send failed: ${errMsg(err)}`, "error");
2526
3082
  }
@@ -2583,7 +3139,8 @@ function App(props) {
2583
3139
  note,
2584
3140
  pendingInput,
2585
3141
  submitTaskPrompt,
2586
- taskPrompt
3142
+ taskPrompt,
3143
+ turns
2587
3144
  ]
2588
3145
  );
2589
3146
  const runCommand = useCallback(
@@ -2597,35 +3154,52 @@ function App(props) {
2597
3154
  return setOverlay("project");
2598
3155
  case "gezel":
2599
3156
  return setOverlay("gezel");
3157
+ case "allow":
3158
+ await applyProjectPermission(rest, true);
3159
+ return;
3160
+ case "disallow":
3161
+ await applyProjectPermission(rest, false);
3162
+ return;
2600
3163
  case "mode":
2601
3164
  if (!rest.trim()) return setOverlay("engagement-mode");
2602
3165
  await applyEngagementMode(rest);
2603
3166
  return;
2604
3167
  case "model": {
2605
- if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2606
- if (activeGezel.fixedFunction) {
2607
- return note("this gezel runs a fixed tool and does not use a chat model.", "error");
3168
+ const subcommand = rest.trim().toLowerCase();
3169
+ if (!subcommand) return openModelPicker();
3170
+ if (subcommand === "download") return openModelDownloadPicker();
3171
+ return note("usage: /model [download]", "error");
3172
+ }
3173
+ case "thread":
3174
+ await openThreadPicker();
3175
+ return;
3176
+ case "open": {
3177
+ const target = resolveCliOpenTarget(rest, recentOpenReferencesRef.current);
3178
+ if (!target) {
3179
+ return note(
3180
+ "usage: /open workspace|artifacts|<recent file> (type /open and a space to browse)",
3181
+ "error"
3182
+ );
2608
3183
  }
2609
- if (modelChoicesLoading) return note("model choices are already loading.");
2610
- setModelChoicesLoading(true);
2611
- note("loading available engines and models\u2026");
2612
3184
  try {
2613
- const choices = await loadModelChoices(client, config ?? await client.getConfig());
2614
- if (choices.length === 0) {
2615
- return note("no engines with available chat models were found.", "error");
3185
+ if (target.type === "folder") {
3186
+ const result = await client.revealProject(projectId, target.folder);
3187
+ note(`opened ${target.folder}: ${result.path}`);
3188
+ } else {
3189
+ const result = await client.revealProjectReference(target.reference.projectId, {
3190
+ kind: target.reference.kind,
3191
+ path: target.reference.path
3192
+ });
3193
+ setRecentOpenReferences(
3194
+ (current) => rememberCliOpenReferences(current, [target.reference])
3195
+ );
3196
+ note(`revealed ${target.reference.path}: ${result.path}`);
2616
3197
  }
2617
- setModelChoices(choices);
2618
- setOverlay("model");
2619
3198
  } catch (err) {
2620
- note(`could not load models: ${errMsg(err)}`, "error");
2621
- } finally {
2622
- setModelChoicesLoading(false);
3199
+ note(`open failed: ${errMsg(err)}`, "error");
2623
3200
  }
2624
3201
  return;
2625
3202
  }
2626
- case "thread":
2627
- await openThreadPicker();
2628
- return;
2629
3203
  case "task":
2630
3204
  setManagedTaskRef(null);
2631
3205
  return setOverlay("task");
@@ -2672,7 +3246,7 @@ function App(props) {
2672
3246
  }
2673
3247
  return;
2674
3248
  }
2675
- case "start": {
3249
+ case "do": {
2676
3250
  let available = craftbooks;
2677
3251
  if (available.length === 0) {
2678
3252
  try {
@@ -2690,7 +3264,7 @@ function App(props) {
2690
3264
  }
2691
3265
  const book = findCraftbook(available, rest);
2692
3266
  if (!book) {
2693
- return note(`craftbook not found: ${rest.trim()} (try /start)`, "error");
3267
+ return note(`craftbook not found: ${rest.trim()} (try /do)`, "error");
2694
3268
  }
2695
3269
  await startCraftbook(book);
2696
3270
  return;
@@ -2748,15 +3322,14 @@ function App(props) {
2748
3322
  }
2749
3323
  },
2750
3324
  [
2751
- activeGezel,
2752
- activeGezelId,
2753
3325
  applyEngagementMode,
3326
+ applyProjectPermission,
2754
3327
  client,
2755
- config,
2756
3328
  craftbooks,
2757
- modelChoicesLoading,
2758
3329
  note,
2759
3330
  exit,
3331
+ openModelDownloadPicker,
3332
+ openModelPicker,
2760
3333
  openThreadPicker,
2761
3334
  projectId,
2762
3335
  projectName,
@@ -2765,11 +3338,10 @@ function App(props) {
2765
3338
  startCraftbook
2766
3339
  ]
2767
3340
  );
2768
- const applyModelChoice = useCallback(
2769
- async (value2) => {
3341
+ const applyModelSelection = useCallback(
3342
+ async (choice) => {
2770
3343
  setOverlay(null);
2771
3344
  if (!activeGezelId || !activeGezel || !config) return;
2772
- const choice = modelChoices.find((item) => item.value === value2);
2773
3345
  const nextProvider = choice?.provider ?? null;
2774
3346
  const nextModel = choice?.model.id;
2775
3347
  const providerChanged = (activeGezel.provider ?? null) !== nextProvider;
@@ -2794,8 +3366,80 @@ function App(props) {
2794
3366
  note(`could not switch model: ${errMsg(err)}`, "error");
2795
3367
  }
2796
3368
  },
2797
- [activeGezel, activeGezelId, client, config, ensureSession, modelChoices, note, projectId]
3369
+ [activeGezel, activeGezelId, client, config, ensureSession, note, projectId]
3370
+ );
3371
+ const applyModelChoice = useCallback(
3372
+ async (value2) => {
3373
+ await applyModelSelection(modelChoices.find((item) => item.value === value2));
3374
+ },
3375
+ [applyModelSelection, modelChoices]
3376
+ );
3377
+ const installModelDownload = useCallback(
3378
+ async (value2) => {
3379
+ const choice = modelDownloadChoices.find((candidate) => candidate.value === value2);
3380
+ if (!choice) return;
3381
+ let terminalError = null;
3382
+ setModelDownloadProgress({
3383
+ choice,
3384
+ bytesWritten: 0,
3385
+ totalBytes: choice.model.approxSizeBytes,
3386
+ pct: 0,
3387
+ phase: "starting"
3388
+ });
3389
+ const onEvent = (event) => {
3390
+ if (event.type === "error") terminalError = event.error;
3391
+ const progress = readModelDownloadProgress(choice, event);
3392
+ if (progress) setModelDownloadProgress(progress);
3393
+ };
3394
+ try {
3395
+ if (choice.provider === "mlx") {
3396
+ await client.installMlxModel(choice.model.id, onEvent);
3397
+ } else {
3398
+ await client.installLlamaCppModel(choice.model.id, onEvent);
3399
+ }
3400
+ if (terminalError) throw new Error(terminalError);
3401
+ const installedChoice = {
3402
+ provider: choice.provider,
3403
+ model: {
3404
+ id: choice.model.id,
3405
+ name: choice.model.name
3406
+ },
3407
+ value: choice.value,
3408
+ label: `${modelProviderLabel(choice.provider)} \xB7 ${choice.model.name}`
3409
+ };
3410
+ setModelChoices((current) => [
3411
+ ...current.filter((candidate) => candidate.value !== installedChoice.value),
3412
+ installedChoice
3413
+ ]);
3414
+ setModelDownloadProgress(null);
3415
+ note(`downloaded ${choice.model.name}; switching this gezel to it\u2026`);
3416
+ await applyModelSelection(installedChoice);
3417
+ } catch (err) {
3418
+ setModelDownloadProgress(null);
3419
+ setOverlay("model-download");
3420
+ note(`model download failed: ${errMsg(err)}`, "error");
3421
+ }
3422
+ },
3423
+ [applyModelSelection, client, modelDownloadChoices, note]
2798
3424
  );
3425
+ const cancelModelDownload = useCallback(async () => {
3426
+ const progress = modelDownloadProgress;
3427
+ if (!progress) return;
3428
+ try {
3429
+ if (progress.choice.provider === "mlx") {
3430
+ await client.cancelMlxModelInstall(progress.choice.model.id);
3431
+ } else {
3432
+ await client.cancelLlamaCppModelInstall(progress.choice.model.id);
3433
+ }
3434
+ note(`canceled the ${progress.choice.model.name} download.`);
3435
+ } catch (err) {
3436
+ note(`could not cancel model download: ${errMsg(err)}`, "error");
3437
+ } finally {
3438
+ setModelDownloadProgress(null);
3439
+ if (modelDownloadReturn === "model") await openModelPicker();
3440
+ else setOverlay(null);
3441
+ }
3442
+ }, [client, modelDownloadProgress, modelDownloadReturn, note, openModelPicker]);
2799
3443
  const onSubmit = useCallback(
2800
3444
  (raw) => {
2801
3445
  setValue("");
@@ -2841,10 +3485,10 @@ function App(props) {
2841
3485
  }
2842
3486
  );
2843
3487
  if (status) {
2844
- return /* @__PURE__ */ jsx6(Box6, { flexDirection: "column", padding: 1, children: /* @__PURE__ */ jsx6(Text6, { color: status.startsWith("Failed") ? "red" : "cyan", children: status }) });
3488
+ return /* @__PURE__ */ jsx5(Box6, { flexDirection: "column", padding: 1, children: /* @__PURE__ */ jsx5(Text6, { color: status.startsWith("Failed") ? "red" : "cyan", children: status }) });
2845
3489
  }
2846
3490
  return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", padding: 1, children: [
2847
- /* @__PURE__ */ jsx6(
3491
+ /* @__PURE__ */ jsx5(
2848
3492
  ChatFeed,
2849
3493
  {
2850
3494
  rows,
@@ -2854,7 +3498,7 @@ function App(props) {
2854
3498
  visible: visibleRows
2855
3499
  }
2856
3500
  ),
2857
- overlay === "project" ? /* @__PURE__ */ jsx6(
3501
+ overlay === "project" ? /* @__PURE__ */ jsx5(
2858
3502
  Picker,
2859
3503
  {
2860
3504
  title: "Switch project",
@@ -2863,7 +3507,7 @@ function App(props) {
2863
3507
  onSelect: (id) => void switchProject(id)
2864
3508
  }
2865
3509
  ) : null,
2866
- overlay === "gezel" ? /* @__PURE__ */ jsx6(
3510
+ overlay === "gezel" ? /* @__PURE__ */ jsx5(
2867
3511
  Picker,
2868
3512
  {
2869
3513
  title: "Switch gezel",
@@ -2883,7 +3527,7 @@ function App(props) {
2883
3527
  }
2884
3528
  }
2885
3529
  ) : null,
2886
- overlay === "engagement-mode" ? /* @__PURE__ */ jsx6(
3530
+ overlay === "engagement-mode" ? /* @__PURE__ */ jsx5(
2887
3531
  Picker,
2888
3532
  {
2889
3533
  title: "Choose AI engagement mode",
@@ -2897,16 +3541,21 @@ function App(props) {
2897
3541
  onSelect: (selected) => void applyEngagementMode(selected)
2898
3542
  }
2899
3543
  ) : null,
2900
- overlay === "model" ? /* @__PURE__ */ jsx6(
3544
+ overlay === "model" ? /* @__PURE__ */ jsx5(
2901
3545
  Picker,
2902
3546
  {
2903
- title: "Choose engine + model",
3547
+ title: "Choose engine + model - models are downloaded from Hugging Face (huggingface.co)",
2904
3548
  items: [
2905
3549
  {
2906
3550
  label: "Use default",
2907
3551
  value: "__default__",
2908
3552
  hint: `${modelProviderLabel(config?.provider ?? "llama-cpp")}${config?.defaultModel?.[config.provider] ? ` \xB7 ${config.defaultModel[config.provider]}` : ""}`
2909
3553
  },
3554
+ {
3555
+ label: "Download a new model\u2026",
3556
+ value: "__download__",
3557
+ hint: "browse on-device models ranked for this machine"
3558
+ },
2910
3559
  ...modelChoices.map((choice) => ({
2911
3560
  label: choice.label,
2912
3561
  value: choice.value,
@@ -2916,10 +3565,36 @@ function App(props) {
2916
3565
  initialValue: activeGezel?.provider && activeGezel.model ? `${activeGezel.provider}:${activeGezel.model}` : "__default__",
2917
3566
  windowSize: modelPickerWindowSize,
2918
3567
  onCancel: () => setOverlay(null),
2919
- onSelect: (value2) => void applyModelChoice(value2)
3568
+ onSelect: (value2) => {
3569
+ if (value2 === "__download__") void openModelDownloadPicker("model");
3570
+ else void applyModelChoice(value2);
3571
+ }
2920
3572
  }
2921
3573
  ) : null,
2922
- overlay === "start-category" ? /* @__PURE__ */ jsx6(
3574
+ overlay === "model-download" ? modelDownloadProgress ? /* @__PURE__ */ jsx5(
3575
+ ModelDownloadProgressPanel,
3576
+ {
3577
+ progress: modelDownloadProgress,
3578
+ onCancel: () => void cancelModelDownload()
3579
+ }
3580
+ ) : /* @__PURE__ */ jsx5(
3581
+ Picker,
3582
+ {
3583
+ title: "Download and use an on-device model",
3584
+ items: modelDownloadChoices.map((choice) => ({
3585
+ label: choice.label,
3586
+ value: choice.value,
3587
+ hint: choice.hint
3588
+ })),
3589
+ windowSize: modelPickerWindowSize,
3590
+ onCancel: () => {
3591
+ if (modelDownloadReturn === "model") setOverlay("model");
3592
+ else setOverlay(null);
3593
+ },
3594
+ onSelect: (value2) => void installModelDownload(value2)
3595
+ }
3596
+ ) : null,
3597
+ overlay === "start-category" ? /* @__PURE__ */ jsx5(
2923
3598
  Picker,
2924
3599
  {
2925
3600
  title: "Choose a craftbook category",
@@ -2936,7 +3611,7 @@ function App(props) {
2936
3611
  }
2937
3612
  }
2938
3613
  ) : null,
2939
- overlay === "start-craftbook" ? /* @__PURE__ */ jsx6(
3614
+ overlay === "start-craftbook" ? /* @__PURE__ */ jsx5(
2940
3615
  Picker,
2941
3616
  {
2942
3617
  title: startCategory?.label ?? "Start a craftbook",
@@ -2953,7 +3628,7 @@ function App(props) {
2953
3628
  }
2954
3629
  }
2955
3630
  ) : null,
2956
- overlay === "thread" ? /* @__PURE__ */ jsx6(
3631
+ overlay === "thread" ? /* @__PURE__ */ jsx5(
2957
3632
  Picker,
2958
3633
  {
2959
3634
  title: `Threads with ${gezelLine}`,
@@ -2974,7 +3649,7 @@ function App(props) {
2974
3649
  }
2975
3650
  }
2976
3651
  ) : null,
2977
- overlay === "task" ? /* @__PURE__ */ jsx6(
3652
+ overlay === "task" ? /* @__PURE__ */ jsx5(
2978
3653
  Picker,
2979
3654
  {
2980
3655
  title: `Tasks \xB7 ${tasks.filter((task2) => task2.status === "active").length} active`,
@@ -2999,7 +3674,7 @@ function App(props) {
2999
3674
  }
3000
3675
  }
3001
3676
  ) : null,
3002
- overlay === "task-actions" && managedTask ? /* @__PURE__ */ jsx6(
3677
+ overlay === "task-actions" && managedTask ? /* @__PURE__ */ jsx5(
3003
3678
  Picker,
3004
3679
  {
3005
3680
  title: `${managedTask.ref} \xB7 ${managedTask.status}`,
@@ -3034,7 +3709,7 @@ function App(props) {
3034
3709
  }
3035
3710
  }
3036
3711
  ) : null,
3037
- overlay === "task-status" && managedTask ? /* @__PURE__ */ jsx6(
3712
+ overlay === "task-status" && managedTask ? /* @__PURE__ */ jsx5(
3038
3713
  Picker,
3039
3714
  {
3040
3715
  title: `Set ${managedTask.ref} status`,
@@ -3043,7 +3718,7 @@ function App(props) {
3043
3718
  onSelect: (status2) => void applyTaskStatus(status2)
3044
3719
  }
3045
3720
  ) : null,
3046
- overlay === "task-assignee" && managedTask ? /* @__PURE__ */ jsx6(
3721
+ overlay === "task-assignee" && managedTask ? /* @__PURE__ */ jsx5(
3047
3722
  Picker,
3048
3723
  {
3049
3724
  title: `Assign ${managedTask.ref}`,
@@ -3063,7 +3738,7 @@ function App(props) {
3063
3738
  onSelect: (assignee) => void applyTaskAssignee(assignee)
3064
3739
  }
3065
3740
  ) : null,
3066
- overlay === "focus" ? /* @__PURE__ */ jsx6(
3741
+ overlay === "focus" ? /* @__PURE__ */ jsx5(
3067
3742
  Picker,
3068
3743
  {
3069
3744
  title: "Send into which chat?",
@@ -3075,7 +3750,7 @@ function App(props) {
3075
3750
  }
3076
3751
  }
3077
3752
  ) : null,
3078
- overlay === null && pendingQuestion ? /* @__PURE__ */ jsx6(
3753
+ overlay === null && pendingQuestion ? /* @__PURE__ */ jsx5(
3079
3754
  QuestionPrompt,
3080
3755
  {
3081
3756
  client,
@@ -3089,7 +3764,7 @@ function App(props) {
3089
3764
  },
3090
3765
  pendingQuestion.id
3091
3766
  ) : null,
3092
- /* @__PURE__ */ jsx6(
3767
+ /* @__PURE__ */ jsx5(
3093
3768
  PromptLine,
3094
3769
  {
3095
3770
  projectName,
@@ -3105,6 +3780,7 @@ function App(props) {
3105
3780
  active: overlay === null && (!pendingQuestion || pendingInput !== null || taskPrompt !== null),
3106
3781
  history,
3107
3782
  craftbooks,
3783
+ recentOpenReferences,
3108
3784
  pendingPrompt: pendingInput?.promptLine ?? taskPrompt?.promptLine,
3109
3785
  pendingMode: pendingInput?.mode ?? (taskPrompt ? "text" : void 0),
3110
3786
  onChange: setValue,
@@ -3113,6 +3789,52 @@ function App(props) {
3113
3789
  )
3114
3790
  ] });
3115
3791
  }
3792
+ function ModelDownloadProgressPanel(props) {
3793
+ const { progress, onCancel } = props;
3794
+ useInput4((input, key) => {
3795
+ if (key.escape || key.ctrl && input === "c") onCancel();
3796
+ });
3797
+ const transferred = progress.totalBytes ? `${formatModelBytes(progress.bytesWritten)} / ${formatModelBytes(progress.totalBytes)}` : formatModelBytes(progress.bytesWritten);
3798
+ return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
3799
+ /* @__PURE__ */ jsxs6(Text6, { bold: true, color: "yellow", children: [
3800
+ "Downloading ",
3801
+ progress.choice.model.name
3802
+ ] }),
3803
+ /* @__PURE__ */ jsxs6(Text6, { children: [
3804
+ progress.pct == null ? "Working\u2026" : `${progress.pct}%`,
3805
+ " \xB7 ",
3806
+ transferred
3807
+ ] }),
3808
+ progress.phase ? /* @__PURE__ */ jsx5(Text6, { dimColor: true, children: progress.phase }) : null,
3809
+ /* @__PURE__ */ jsx5(Text6, { dimColor: true, children: "Esc / Ctrl+C cancel" })
3810
+ ] });
3811
+ }
3812
+ function readModelDownloadProgress(choice, event) {
3813
+ if (event.type === "progress") {
3814
+ const bytesWritten = "bytesWrittenAll" in event ? event.bytesWrittenAll : event.bytesWritten;
3815
+ const totalBytes = "totalBytesAll" in event ? event.totalBytesAll : event.totalBytes;
3816
+ return {
3817
+ choice,
3818
+ bytesWritten,
3819
+ totalBytes,
3820
+ pct: totalBytes > 0 ? Math.min(100, Math.floor(bytesWritten / totalBytes * 100)) : null,
3821
+ phase: "downloading and verifying model files"
3822
+ };
3823
+ }
3824
+ if (event.type === "companion") {
3825
+ return {
3826
+ choice,
3827
+ bytesWritten: event.bytesWritten,
3828
+ totalBytes: event.totalBytes,
3829
+ pct: event.totalBytes > 0 ? Math.min(100, Math.floor(event.bytesWritten / event.totalBytes * 100)) : null,
3830
+ phase: `downloading ${event.name}`
3831
+ };
3832
+ }
3833
+ return null;
3834
+ }
3835
+ function formatModelBytes(bytes) {
3836
+ return bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : `${Math.max(0, Math.round(bytes / 1e6))} MB`;
3837
+ }
3116
3838
  function errMsg(err) {
3117
3839
  return err instanceof Error ? err.message : String(err);
3118
3840
  }
@@ -3180,7 +3902,7 @@ function taskAssigneeLabel(task2, gezels, boring) {
3180
3902
  if (task2.assignee.kind === "user") return "you";
3181
3903
  const gezelId = task2.assignee.gezelId;
3182
3904
  const gezel = gezels.find((item) => item.id === gezelId);
3183
- if (!gezel) return gezelId;
3905
+ if (!gezel) return boring ? "gezel" : gezelId;
3184
3906
  return boring ? gezel.roleBasedName ?? gezel.role ?? gezel.id : gezel.name;
3185
3907
  }
3186
3908
  function taskStatusChoices(task2) {
@@ -3206,7 +3928,7 @@ function formatTaskDetails(task2, gezels, boring) {
3206
3928
  ...steps.length > 0 ? ["steps:", ...steps] : []
3207
3929
  ].join("\n");
3208
3930
  }
3209
- var HELP, TASK_STATUS_ORDER;
3931
+ var HELP, READ_ONLY_BOOT_NOTE, TASK_STATUS_ORDER;
3210
3932
  var init_App = __esm({
3211
3933
  "src/tui/App.tsx"() {
3212
3934
  "use strict";
@@ -3221,14 +3943,20 @@ var init_App = __esm({
3221
3943
  init_craftbook_start();
3222
3944
  init_feed();
3223
3945
  init_model_picker();
3946
+ init_open_command();
3224
3947
  init_question_queue();
3225
3948
  init_streams();
3226
3949
  HELP = [
3227
3950
  "/project \u2014 switch project /gezel \u2014 switch gezel /model \u2014 switch engine + model",
3951
+ "/model download \u2014 choose and download a new on-device model",
3952
+ "/allow edits \u2014 allow tool edits /disallow edits \u2014 make tool edits read-only",
3953
+ "/allow codexedits|claudeedits \u2014 allow provider-native project edits",
3954
+ "/disallow codexedits|claudeedits \u2014 put that provider in read-only plan mode",
3228
3955
  "/mode \u2014 choose read-only, reactive, reactive+tasks, or full-play AI activity",
3229
3956
  "/thread \u2014 switch or start a chat thread",
3957
+ "/open workspace|artifacts|<recent file> \u2014 open a folder or file from chat",
3230
3958
  "/task \u2014 list, inspect, create, edit, assign, or change task status",
3231
- "/start \u2014 choose a craftbook and start it as a task",
3959
+ "/do \u2014 choose a craftbook and start it as a task",
3232
3960
  "/continue \u2014 process due schedules and active tasks in this project",
3233
3961
  "/nightshift start|stop|list \u2014 manage Night Shift",
3234
3962
  "/focus \u2014 send into another active chat /cli \u2014 CLI mode /chat \u2014 chat mode",
@@ -3236,6 +3964,7 @@ var init_App = __esm({
3236
3964
  "/clear \u2014 clear feed /quit \u2014 exit",
3237
3965
  "\u2191/\u2193 \u2014 input history Esc \u2014 interrupt turn Ctrl+C \u2014 interrupt, then again to exit"
3238
3966
  ];
3967
+ 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.";
3239
3968
  TASK_STATUS_ORDER = {
3240
3969
  active: 0,
3241
3970
  draft: 1,
@@ -3247,9 +3976,10 @@ var init_App = __esm({
3247
3976
  });
3248
3977
 
3249
3978
  // src/tui/components/BootstrapGate.tsx
3979
+ import { formatModelAttribution as formatModelAttribution3 } from "@bendyline/gezel";
3250
3980
  import { Box as Box7, Text as Text7, useApp as useApp2, useInput as useInput5 } from "ink";
3251
3981
  import { useCallback as useCallback2, useEffect as useEffect4, useState as useState5 } from "react";
3252
- import { Fragment as Fragment4, jsx as jsx7, jsxs as jsxs7 } from "react/jsx-runtime";
3982
+ import { Fragment as Fragment4, jsx as jsx6, jsxs as jsxs7 } from "react/jsx-runtime";
3253
3983
  function BootstrapGate(props) {
3254
3984
  const { client, children } = props;
3255
3985
  const { exit } = useApp2();
@@ -3271,7 +4001,8 @@ function BootstrapGate(props) {
3271
4001
  async (context) => {
3272
4002
  setScreen({ kind: "loading", message: "Finding the best models for this device\u2026" });
3273
4003
  const installedChat = context.provider === "mlx" ? await client.listMlxModels() : await client.listLlamaCppModels();
3274
- if (installedChat.models.length > 0) {
4004
+ const pinnedModel = context.config.defaultModel?.[context.provider];
4005
+ if (pinnedModel && installedChat.models.some((model2) => model2.id === pinnedModel)) {
3275
4006
  setScreen({ kind: "ready" });
3276
4007
  return;
3277
4008
  }
@@ -3296,8 +4027,20 @@ function BootstrapGate(props) {
3296
4027
  client.listInstalledTtsModels().catch(() => ({ models: [] })),
3297
4028
  client.listInstalledRecognitionModels().catch(() => ({ models: [] }))
3298
4029
  ]);
3299
- const chatModels = rankChatModels(context.chatCatalog, context.device, context.provider);
3300
- if (chatModels.length === 0) {
4030
+ const installedIds = new Set(installedChat.models.map((model2) => model2.id));
4031
+ const rankedChatModels = rankChatModels(
4032
+ context.chatCatalog,
4033
+ context.device,
4034
+ context.provider
4035
+ );
4036
+ const recommendedChatModel = rankedChatModels[0];
4037
+ const chatModels = rankedChatModels.filter((model2) => !installedIds.has(model2.id));
4038
+ const catalogAttributions = new Map(
4039
+ context.chatCatalog.flatMap(
4040
+ (item) => item.manifest.kind === "chat-model" ? [[item.manifest.id, formatModelAttribution3(item.manifest)]] : []
4041
+ )
4042
+ );
4043
+ if (chatModels.length === 0 && installedChat.models.length === 0) {
3301
4044
  setScreen({
3302
4045
  kind: "error",
3303
4046
  title: "No compatible local models found",
@@ -3321,7 +4064,19 @@ function BootstrapGate(props) {
3321
4064
  },
3322
4065
  context.device
3323
4066
  );
3324
- setScreen({ kind: "model-choice", plan: { context, chatModels, accessories } });
4067
+ setScreen({
4068
+ kind: "model-choice",
4069
+ plan: {
4070
+ context,
4071
+ installedChatModels: installedChat.models.map((model2) => {
4072
+ const attribution = catalogAttributions.get(model2.id);
4073
+ return { ...model2, ...attribution ? { attribution } : {} };
4074
+ }),
4075
+ ...recommendedChatModel ? { recommendedChatModel } : {},
4076
+ chatModels,
4077
+ accessories
4078
+ }
4079
+ });
3325
4080
  },
3326
4081
  [client]
3327
4082
  );
@@ -3349,14 +4104,7 @@ function BootstrapGate(props) {
3349
4104
  const context = {
3350
4105
  config,
3351
4106
  provider: config.provider,
3352
- device: {
3353
- platform: memory.platform,
3354
- gpuVramBytes: memory.gpuVramBytes,
3355
- ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
3356
- totalRamBytes: memory.totalRamBytes,
3357
- usableBytes: memory.usableBytes,
3358
- ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
3359
- },
4107
+ device: recoDevice(memory),
3360
4108
  chatCatalog: chatCatalog.items,
3361
4109
  nativeStatus
3362
4110
  };
@@ -3391,12 +4139,19 @@ function BootstrapGate(props) {
3391
4139
  }
3392
4140
  try {
3393
4141
  await installNativeToolkit2(client, context.nativeStatus, missing, setScreen);
3394
- const nativeStatus = await client.getNativeEngineStatus();
3395
- await prepareModels({ ...context, nativeStatus });
4142
+ const [nativeStatus, memory] = await Promise.all([
4143
+ client.getNativeEngineStatus(),
4144
+ client.getMemoryProfile()
4145
+ ]);
4146
+ await prepareModels({
4147
+ ...context,
4148
+ nativeStatus,
4149
+ device: recoDevice(memory)
4150
+ });
3396
4151
  } catch (error) {
3397
4152
  setScreen({
3398
4153
  kind: "error",
3399
- title: "Native toolkit install failed",
4154
+ title: "Gezel native toolkit install failed",
3400
4155
  message: errorMessage2(error),
3401
4156
  retry
3402
4157
  });
@@ -3412,24 +4167,40 @@ function BootstrapGate(props) {
3412
4167
  }
3413
4168
  const retry = () => void installModels(plan, choice);
3414
4169
  try {
4170
+ if (choice.kind === "installed") {
4171
+ const updated2 = await client.updateConfig({
4172
+ provider: plan.context.provider,
4173
+ defaultModel: {
4174
+ ...plan.context.config.defaultModel,
4175
+ [plan.context.provider]: choice.modelId
4176
+ },
4177
+ firstRunInstallError: null
4178
+ });
4179
+ plan.context.config = updated2;
4180
+ setScreen({ kind: "ready" });
4181
+ return;
4182
+ }
3415
4183
  if (choice.kind === "bundle") {
3416
4184
  const missing = missingToolkit(await client.getNativeEngineStatus());
3417
4185
  if (missing.length > 0) {
3418
4186
  await installNativeToolkit2(client, plan.context.nativeStatus, missing, setScreen);
3419
4187
  }
3420
4188
  }
4189
+ const chatAlreadyInstalled = choice.kind === "bundle" && plan.installedChatModels.some((model2) => model2.id === choice.model.id);
3421
4190
  const jobs = [
3422
- { label: choice.model.name, sizeBytes: choice.model.approxSizeBytes },
4191
+ ...!chatAlreadyInstalled ? [{ label: choice.model.name, sizeBytes: choice.model.approxSizeBytes }] : [],
3423
4192
  ...choice.kind === "bundle" ? plan.accessories.map((model2) => ({
3424
4193
  label: model2.name,
3425
4194
  sizeBytes: model2.approxSizeBytes
3426
4195
  })) : []
3427
4196
  ];
3428
4197
  let jobIndex = 0;
3429
- await installChatModel(client, choice.model, (event) => {
3430
- updateDownloadProgress(setScreen, jobs[jobIndex], jobIndex, jobs.length, event);
3431
- });
3432
- jobIndex += 1;
4198
+ if (!chatAlreadyInstalled) {
4199
+ await installChatModel(client, choice.model, (event) => {
4200
+ updateDownloadProgress(setScreen, jobs[jobIndex], jobIndex, jobs.length, event);
4201
+ });
4202
+ jobIndex += 1;
4203
+ }
3433
4204
  const updated = await client.updateConfig({
3434
4205
  provider: choice.model.provider,
3435
4206
  defaultModel: {
@@ -3460,9 +4231,9 @@ function BootstrapGate(props) {
3460
4231
  },
3461
4232
  [client]
3462
4233
  );
3463
- if (screen.kind === "ready") return /* @__PURE__ */ jsx7(Fragment4, { children });
4234
+ if (screen.kind === "ready") return /* @__PURE__ */ jsx6(Fragment4, { children });
3464
4235
  if (screen.kind === "loading") {
3465
- return /* @__PURE__ */ jsx7(BootstrapFrame, { title: "Preparing the workshop", children: /* @__PURE__ */ jsxs7(Text7, { color: "yellow", children: [
4236
+ return /* @__PURE__ */ jsx6(BootstrapFrame, { title: "Preparing the workshop", children: /* @__PURE__ */ jsxs7(Text7, { color: "yellow", children: [
3466
4237
  "\u25CF ",
3467
4238
  screen.message
3468
4239
  ] }) });
@@ -3476,28 +4247,29 @@ function BootstrapGate(props) {
3476
4247
  " ",
3477
4248
  screen.progress.detail
3478
4249
  ] }),
3479
- /* @__PURE__ */ jsx7(ProgressBar, { pct: screen.progress.pct }),
3480
- /* @__PURE__ */ jsx7(Text7, { dimColor: true, children: screen.progress.pct == null ? "Working\u2026" : `${screen.progress.pct}%` })
4250
+ /* @__PURE__ */ jsx6(ProgressBar, { pct: screen.progress.pct }),
4251
+ /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: screen.progress.pct == null ? "Working\u2026" : `${screen.progress.pct}%` })
3481
4252
  ] });
3482
4253
  }
3483
4254
  if (screen.kind === "native-choice") {
3484
4255
  const labels = screen.missing.map(nativeLabel).join(", ");
3485
- return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "Local tools are not installed yet", children: [
4256
+ return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "The Gezel native toolkit -- needed to run AI models locally -- is not installed yet", children: [
4257
+ /* @__PURE__ */ jsx6(Text7, { children: `Gezel can install the verified Gezel native toolkit (native-v${screen.context.nativeStatus.release}) for this device.` }),
3486
4258
  /* @__PURE__ */ jsxs7(Text7, { children: [
3487
- "Gezel can install the verified native-v",
3488
- screen.context.nativeStatus.release,
3489
- " toolkit for this device."
4259
+ "Downloaded from",
4260
+ " ",
4261
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "cyan", children: "https://github.com/bendyline/gezel/releases/" })
3490
4262
  ] }),
3491
4263
  /* @__PURE__ */ jsxs7(Text7, { dimColor: true, children: [
3492
4264
  "Missing: ",
3493
4265
  labels
3494
4266
  ] }),
3495
- /* @__PURE__ */ jsx7(
4267
+ /* @__PURE__ */ jsx6(
3496
4268
  BootstrapChoiceList,
3497
4269
  {
3498
4270
  options: [
3499
4271
  {
3500
- label: "Install the native toolkit",
4272
+ label: "Install the Gezel native toolkit",
3501
4273
  hint: "recommended \xB7 engines for chat, images, speech, and local model helpers",
3502
4274
  value: "install"
3503
4275
  },
@@ -3515,53 +4287,73 @@ function BootstrapGate(props) {
3515
4287
  ] });
3516
4288
  }
3517
4289
  if (screen.kind === "model-choice") {
3518
- const best = screen.plan.chatModels[0];
4290
+ const best = screen.plan.recommendedChatModel;
4291
+ const bestInstalled = best ? screen.plan.installedChatModels.some((model2) => model2.id === best.id) : false;
3519
4292
  const accessoryBytes = screen.plan.accessories.reduce(
3520
4293
  (sum, model2) => sum + model2.approxSizeBytes,
3521
4294
  0
3522
4295
  );
4296
+ const workshopDownloadBytes = accessoryBytes + (best && !bestInstalled ? best.approxSizeBytes : 0);
3523
4297
  const options = [
3524
- {
3525
- label: `Recommended workshop set \u2014 ${best.name} + ${screen.plan.accessories.length} helpers`,
3526
- hint: formatDownloadSize(best.approxSizeBytes + accessoryBytes),
3527
- value: "bundle"
3528
- },
3529
- {
3530
- label: `${best.name} only`,
3531
- hint: `best chat model \xB7 ${formatDownloadSize(best.approxSizeBytes)}`,
3532
- value: `chat:${best.id}`
3533
- },
3534
- ...screen.plan.chatModels.slice(1, MAX_ALTERNATIVE_MODELS + 1).map((model2) => ({
3535
- label: `${model2.name} only`,
4298
+ ...best ? [
4299
+ {
4300
+ label: `Recommended workshop set \u2014 ${bootstrapChatModelLabel(best)} + ${screen.plan.accessories.length} helpers`,
4301
+ hint: `${bestInstalled ? "chat model already available \xB7 " : ""}${workshopDownloadBytes > 0 ? formatDownloadSize(workshopDownloadBytes) : "already available"}`,
4302
+ value: "bundle"
4303
+ },
4304
+ {
4305
+ label: `${bestInstalled ? "Use" : "Download"} ${bootstrapChatModelLabel(best)} only`,
4306
+ hint: `recommended for this device \xB7 ${bestInstalled ? "already available" : formatDownloadSize(best.approxSizeBytes)}`,
4307
+ value: bestInstalled ? `installed:${best.id}` : `chat:${best.id}`
4308
+ }
4309
+ ] : [],
4310
+ ...screen.plan.installedChatModels.filter((model2) => model2.id !== best?.id).map((model2) => ({
4311
+ label: `Use ${model2.name ?? model2.id}${model2.attribution ? ` (${model2.attribution})` : ""}`,
4312
+ hint: `already available on this machine${model2.approxSizeBytes ? ` \xB7 ${formatDownloadSize(model2.approxSizeBytes)}` : ""}`,
4313
+ value: `installed:${model2.id}`
4314
+ })),
4315
+ ...screen.plan.chatModels.filter((model2) => model2.id !== best?.id).slice(0, MAX_ALTERNATIVE_MODELS).map((model2) => ({
4316
+ label: `Download ${bootstrapChatModelLabel(model2)} only`,
3536
4317
  hint: `${formatDownloadSize(model2.approxSizeBytes)} \xB7 ${fitLabel(model2.fit)}`,
3537
4318
  value: `chat:${model2.id}`
3538
4319
  })),
3539
4320
  { label: "Not now", hint: "open the TUI without a local model", value: "skip" }
3540
4321
  ];
3541
- return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "No local chat model is installed", children: [
3542
- /* @__PURE__ */ jsx7(Text7, { children: "Pick a setup for this device. Downloads stay under your Gezel home folder." }),
3543
- /* @__PURE__ */ jsx7(
3544
- BootstrapChoiceList,
3545
- {
3546
- options,
3547
- onSelect: (value) => {
3548
- if (value === "skip") {
3549
- void installModels(screen.plan, { kind: "skip" });
3550
- } else if (value === "bundle") {
3551
- void installModels(screen.plan, { kind: "bundle", model: best });
3552
- } else {
3553
- const id = value.slice("chat:".length);
3554
- const model2 = screen.plan.chatModels.find((candidate) => candidate.id === id);
3555
- if (model2) void installModels(screen.plan, { kind: "chat", model: model2 });
4322
+ return /* @__PURE__ */ jsxs7(
4323
+ BootstrapFrame,
4324
+ {
4325
+ title: screen.plan.installedChatModels.length > 0 ? "Choose a local chat model" : "No local chat model is installed",
4326
+ children: [
4327
+ /* @__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." }),
4328
+ /* @__PURE__ */ jsx6(
4329
+ BootstrapChoiceList,
4330
+ {
4331
+ options,
4332
+ onSelect: (value) => {
4333
+ if (value === "skip") {
4334
+ void installModels(screen.plan, { kind: "skip" });
4335
+ } else if (value === "bundle") {
4336
+ if (best) void installModels(screen.plan, { kind: "bundle", model: best });
4337
+ } else if (value.startsWith("installed:")) {
4338
+ void installModels(screen.plan, {
4339
+ kind: "installed",
4340
+ modelId: value.slice("installed:".length)
4341
+ });
4342
+ } else {
4343
+ const id = value.slice("chat:".length);
4344
+ const model2 = screen.plan.chatModels.find((candidate) => candidate.id === id);
4345
+ if (model2) void installModels(screen.plan, { kind: "chat", model: model2 });
4346
+ }
4347
+ }
3556
4348
  }
3557
- }
3558
- }
3559
- )
3560
- ] });
4349
+ )
4350
+ ]
4351
+ }
4352
+ );
3561
4353
  }
3562
4354
  return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: screen.title, children: [
3563
- /* @__PURE__ */ jsx7(Text7, { color: "red", children: screen.message }),
3564
- /* @__PURE__ */ jsx7(
4355
+ /* @__PURE__ */ jsx6(Text7, { color: "red", children: screen.message }),
4356
+ /* @__PURE__ */ jsx6(
3565
4357
  BootstrapChoiceList,
3566
4358
  {
3567
4359
  options: [
@@ -3578,7 +4370,7 @@ function BootstrapGate(props) {
3578
4370
  }
3579
4371
  function BootstrapFrame(props) {
3580
4372
  return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", paddingX: 1, paddingY: 1, children: [
3581
- /* @__PURE__ */ jsx7(Text7, { bold: true, color: "cyan", children: "gezel \xB7 first-time setup" }),
4373
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "cyan", children: "gezel \xB7 first-time setup" }),
3582
4374
  /* @__PURE__ */ jsxs7(
3583
4375
  Box7,
3584
4376
  {
@@ -3588,14 +4380,24 @@ function BootstrapFrame(props) {
3588
4380
  paddingX: 1,
3589
4381
  marginTop: 1,
3590
4382
  children: [
3591
- /* @__PURE__ */ jsx7(Text7, { bold: true, color: "yellow", children: props.title }),
4383
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "yellow", children: props.title }),
3592
4384
  props.children
3593
4385
  ]
3594
4386
  }
3595
4387
  ),
3596
- /* @__PURE__ */ jsx7(Text7, { dimColor: true, children: "Ctrl+C exit" })
4388
+ /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: "Ctrl+C exit" })
3597
4389
  ] });
3598
4390
  }
4391
+ function recoDevice(memory) {
4392
+ return {
4393
+ platform: memory.platform,
4394
+ gpuVramBytes: memory.gpuVramBytes,
4395
+ ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
4396
+ totalRamBytes: memory.totalRamBytes,
4397
+ usableBytes: memory.usableBytes,
4398
+ ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
4399
+ };
4400
+ }
3599
4401
  function BootstrapChoiceList(props) {
3600
4402
  const [index, setIndex] = useState5(0);
3601
4403
  const options = props.options;
@@ -3668,7 +4470,7 @@ async function installNativeToolkit2(client, status, missing, setScreen) {
3668
4470
  index,
3669
4471
  missing.length,
3670
4472
  event,
3671
- `Installing native-v${status.release}`
4473
+ `Installing the Gezel native toolkit (native-v${status.release})`
3672
4474
  );
3673
4475
  },
3674
4476
  engine === "llama-server" ? status.llamaBackend : void 0
@@ -3706,7 +4508,7 @@ async function installAccessory(client, model2, onEvent) {
3706
4508
  }
3707
4509
  if (terminalError) throw new Error(terminalError);
3708
4510
  }
3709
- function updateDownloadProgress(setScreen, job, index, total, event, title = "Installing local models") {
4511
+ function updateDownloadProgress(setScreen, job, index, total, event, title = "Downloading local models from Hugging Face (huggingface.co)") {
3710
4512
  let pct = null;
3711
4513
  let detail = job.label;
3712
4514
  if (event.type === "progress") {
@@ -3785,10 +4587,10 @@ __export(tui_exports, {
3785
4587
  launchTui: () => launchTui
3786
4588
  });
3787
4589
  import { render } from "ink";
3788
- import { jsx as jsx8 } from "react/jsx-runtime";
4590
+ import { jsx as jsx7 } from "react/jsx-runtime";
3789
4591
  async function launchTui(opts) {
3790
4592
  const instance = render(
3791
- /* @__PURE__ */ jsx8(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx8(
4593
+ /* @__PURE__ */ jsx7(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx7(
3792
4594
  App,
3793
4595
  {
3794
4596
  client: opts.client,
@@ -4444,7 +5246,7 @@ var init_handboek_export = __esm({
4444
5246
  // src/bin/gezel.ts
4445
5247
  init_connection();
4446
5248
  init_engagement_mode();
4447
- import { basename as basename3 } from "path";
5249
+ import { basename as basename4 } from "path";
4448
5250
  import { GEZEL_VERSION as GEZEL_VERSION2 } from "@bendyline/gezel";
4449
5251
  import {
4450
5252
  streamChatEvents
@@ -4452,11 +5254,11 @@ import {
4452
5254
  import {
4453
5255
  GezelClient as GezelClient2,
4454
5256
  createTrustingFetch as createTrustingFetch2,
4455
- discoverOrSpawn,
5257
+ discoverOrSpawn as discoverOrSpawn2,
4456
5258
  isProcessAlive as isProcessAlive2,
4457
5259
  readRuntime as readRuntime2,
4458
5260
  resolveDaemonEntry as resolveDaemonEntry2,
4459
- stopOwnedDaemon,
5261
+ stopOwnedDaemon as stopOwnedDaemon2,
4460
5262
  stopProcessByPid
4461
5263
  } from "@bendyline/gezel-client/node";
4462
5264
  import { Command } from "commander";
@@ -4623,7 +5425,31 @@ function errorMessage(error) {
4623
5425
  return error instanceof Error ? error.message : String(error);
4624
5426
  }
4625
5427
 
5428
+ // src/signal-cleanup.ts
5429
+ function installSignalCleanup(cleanup, options = {}) {
5430
+ if (!cleanup) return () => {
5431
+ };
5432
+ const host = options.host ?? process;
5433
+ let cleanupPromise;
5434
+ const onSignal = (signal) => {
5435
+ host.exitCode = signal === "SIGINT" ? 130 : 143;
5436
+ cleanupPromise ??= cleanup().catch((error) => {
5437
+ options.onError?.(error);
5438
+ host.exitCode = 1;
5439
+ });
5440
+ };
5441
+ const onSigint = () => onSignal("SIGINT");
5442
+ const onSigterm = () => onSignal("SIGTERM");
5443
+ host.on("SIGINT", onSigint);
5444
+ host.on("SIGTERM", onSigterm);
5445
+ return () => {
5446
+ host.off("SIGINT", onSigint);
5447
+ host.off("SIGTERM", onSigterm);
5448
+ };
5449
+ }
5450
+
4626
5451
  // src/bin/gezel.ts
5452
+ init_craftbook_start();
4627
5453
  var program = new Command();
4628
5454
  program.name("gezel").description("Gezel \u2014 build a community of agents that do things.").version(GEZEL_VERSION2).option(
4629
5455
  "--connect <url>",
@@ -4644,17 +5470,22 @@ program.hook("preAction", () => {
4644
5470
  program.action(async () => {
4645
5471
  const globals = cliGlobals();
4646
5472
  resolveDevHome(globals);
4647
- const client = await connectOwned(globals);
4648
- const projectId = await resolveTuiProject(client, globals);
4649
- const gezelId = await ensureCliProjectLead(client, projectId);
4650
- let projectName = basename3(process.cwd()) || "workspace";
5473
+ const connection = await connectForTui(globals);
4651
5474
  try {
4652
- const { projects } = await client.listProjects();
4653
- projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
4654
- } catch {
5475
+ const { client } = connection;
5476
+ const projectId = await resolveTuiProject(client, globals);
5477
+ const gezelId = await ensureCliProjectLead(client, projectId);
5478
+ let projectName = basename4(process.cwd()) || "workspace";
5479
+ try {
5480
+ const { projects } = await client.listProjects();
5481
+ projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
5482
+ } catch {
5483
+ }
5484
+ const { launchTui: launchTui2 } = await Promise.resolve().then(() => (init_tui(), tui_exports));
5485
+ await launchTui2({ client, projectId, projectName, gezelId });
5486
+ } finally {
5487
+ await connection.stop?.();
4655
5488
  }
4656
- const { launchTui: launchTui2 } = await Promise.resolve().then(() => (init_tui(), tui_exports));
4657
- await launchTui2({ client, projectId, projectName, gezelId });
4658
5489
  });
4659
5490
  program.command("start").description("Start the Gezel daemon (no-op if already running)").option(
4660
5491
  "--port <port>",
@@ -4692,7 +5523,7 @@ program.command("start").description("Start the Gezel daemon (no-op if already r
4692
5523
  }
4693
5524
  if (port !== void 0 || opts.web) {
4694
5525
  const entry = resolveDaemonEntry2(import.meta.url);
4695
- const result = await discoverOrSpawn({
5526
+ const result = await discoverOrSpawn2({
4696
5527
  daemonEntry: entry,
4697
5528
  detached: true,
4698
5529
  env: spawnEnv,
@@ -4766,7 +5597,7 @@ async function startForeground(env2) {
4766
5597
  });
4767
5598
  let stopping;
4768
5599
  const requestStop = () => {
4769
- stopping ??= stopOwnedDaemon(child);
5600
+ stopping ??= stopOwnedDaemon2(child);
4770
5601
  void stopping;
4771
5602
  };
4772
5603
  process.on("SIGINT", requestStop);
@@ -4841,10 +5672,33 @@ program.command("status").description("Show daemon status").action(async () => {
4841
5672
  console.error(`health failed: ${err.message}`);
4842
5673
  }
4843
5674
  });
4844
- program.command("stop").description("Stop the user-owned Gezel daemon").action(async () => {
5675
+ program.command("stop").description("Hard stop all AI work and switch Gezel to Reactive mode").option("--daemon", "Shut down the user-owned daemon process itself").action(async (opts) => {
4845
5676
  const globals = cliGlobals();
5677
+ if (opts.daemon) {
5678
+ await stopUserDaemon(globals);
5679
+ return;
5680
+ }
5681
+ if (!globals.connect && !await findHealthySystemService(globals)) {
5682
+ const runtime = await readRuntime2();
5683
+ if (!runtime || !isProcessAlive2(runtime.pid)) {
5684
+ console.log("Gezel has no running AI work to stop.");
5685
+ return;
5686
+ }
5687
+ }
5688
+ const client = await connectOwned(globals);
5689
+ const result = await client.emergencyStopChats();
5690
+ const details = [
5691
+ `${result.cancelledTurns} active ${result.cancelledTurns === 1 ? "chat" : "chats"}`,
5692
+ `${result.clearedQueuedMessages} queued ${result.clearedQueuedMessages === 1 ? "message" : "messages"}`,
5693
+ `${result.clearedDeferredActions} deferred ${result.clearedDeferredActions === 1 ? "action" : "actions"}`
5694
+ ];
5695
+ console.log(
5696
+ `Hard stop complete: ${details.join(", ")}. Local engines unloaded; Gezel is Reactive.`
5697
+ );
5698
+ });
5699
+ async function stopUserDaemon(globals) {
4846
5700
  if (globals.connect) {
4847
- throw new CliError("gezel stop cannot stop an explicit remote service.");
5701
+ throw new CliError("gezel stop --daemon cannot stop an explicit remote service.");
4848
5702
  }
4849
5703
  const system = await findHealthySystemService(globals);
4850
5704
  if (system) {
@@ -4865,7 +5719,7 @@ program.command("stop").description("Stop the user-owned Gezel daemon").action(a
4865
5719
  console.error(`failed to confirm gezeld pid=${runtime.pid} stopped`);
4866
5720
  process.exitCode = 1;
4867
5721
  }
4868
- });
5722
+ }
4869
5723
  program.command("mode [mode]").description("Show or set AI activity (read-only, reactive, reactive+tasks, or full-play)").action(async (requested) => {
4870
5724
  const next = requested ? parseCliEngagementMode(requested) : null;
4871
5725
  if (requested && !next) {
@@ -4892,6 +5746,11 @@ program.command("run [prompt...]").description("Run a prompt through a gezel and
4892
5746
  return;
4893
5747
  }
4894
5748
  const conn = await connectForRun(cliGlobals());
5749
+ const removeSignalCleanup = installSignalCleanup(conn.stop, {
5750
+ onError: (error) => {
5751
+ console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
5752
+ }
5753
+ });
4895
5754
  try {
4896
5755
  const { client } = conn;
4897
5756
  const projectId = await resolveRunProject(client, cliGlobals());
@@ -4922,9 +5781,32 @@ ${ev.error}`);
4922
5781
  if (printed) process.stdout.write("\n");
4923
5782
  if (errored) process.exitCode = 1;
4924
5783
  } finally {
5784
+ removeSignalCleanup();
4925
5785
  if (conn.stop) await conn.stop();
4926
5786
  }
4927
5787
  });
5788
+ program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").action(async (craftbookParts) => {
5789
+ const craftbookRef = craftbookParts.join(" ").trim();
5790
+ const client = await connectOwned(cliGlobals());
5791
+ const projectId = await resolveRunProject(client, cliGlobals());
5792
+ const [config, result] = await Promise.all([
5793
+ client.getConfig(),
5794
+ client.listProjectCraftbooks(projectId)
5795
+ ]);
5796
+ const craftbooks = normalizeCraftbooks(
5797
+ result.items,
5798
+ config.showWorkInProgressFeatures === true
5799
+ );
5800
+ const book = findCraftbook(craftbooks, craftbookRef);
5801
+ if (!book) {
5802
+ throw new CliError(`craftbook not found: ${craftbookRef} (run gezel and type /do to browse)`);
5803
+ }
5804
+ const created = await client.createTask(projectId, {
5805
+ ...craftbookStartRequest(book),
5806
+ roleBasedNameOnlyMode: true
5807
+ });
5808
+ console.log(`started ${created.ref} \u2014 ${created.title}`);
5809
+ });
4928
5810
  var agent = program.command("agent").description("Manage agents");
4929
5811
  agent.command("list").description("List agents").action(async () => {
4930
5812
  const client = await connectOwned(cliGlobals());
@@ -5085,7 +5967,8 @@ task.command("create <projectId> <title>").description("Create a task with a sin
5085
5967
  title,
5086
5968
  description,
5087
5969
  assignee: opts.assignee ? { kind: "gezel", gezelId: opts.assignee } : { kind: "user" },
5088
- steps: [{ name: opts.phase }]
5970
+ steps: [{ name: opts.phase }],
5971
+ roleBasedNameOnlyMode: true
5089
5972
  });
5090
5973
  console.log(`created ${created.ref}`);
5091
5974
  }