@bendyline/gezel-cli 1.0.2 → 1.0.3

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
  }
@@ -544,6 +592,7 @@ var init_engagement_mode = __esm({
544
592
  // src/tui/bootstrap.ts
545
593
  import {
546
594
  computeModelFit,
595
+ formatModelAttribution,
547
596
  isMoEFromTags,
548
597
  isRecommendedModel,
549
598
  mediaModelFits,
@@ -575,7 +624,8 @@ function rankChatModels(items, device, provider) {
575
624
  // Effective score: a model the shared gate rejects (restricted license,
576
625
  // no tool support) sorts as unscored rather than leading the list.
577
626
  recoScore: isRecommendedModel(manifest) ? manifest.recoScore ?? 0 : 0,
578
- fit
627
+ fit,
628
+ attribution: formatModelAttribution(manifest)
579
629
  });
580
630
  }
581
631
  if (candidates.length === 0) return [];
@@ -609,6 +659,9 @@ function rankChatModels(items, device, provider) {
609
659
  }
610
660
  return pool;
611
661
  }
662
+ function bootstrapChatModelLabel(model2) {
663
+ return `${model2.name} (${model2.attribution})`;
664
+ }
612
665
  function pickAccessoryModels(input, device) {
613
666
  const output = [];
614
667
  const image2 = pickCatalogMedia(input.imageItems, device, "image");
@@ -753,7 +806,36 @@ function suggestSlashCommands(input) {
753
806
  const query = input.slice(1).toLowerCase();
754
807
  return SLASH_COMMANDS.filter((command) => command.name.startsWith(query));
755
808
  }
809
+ function parseProjectPermissionName(input) {
810
+ const normalized = input.trim().toLowerCase();
811
+ return PROJECT_PERMISSIONS.find((permission) => permission.name === normalized)?.name;
812
+ }
756
813
  function suggestSlashWordwheel(input, craftbooks) {
814
+ const modelMatch = input.match(/^\/model\s+(.*)$/i);
815
+ if (modelMatch) {
816
+ const query = (modelMatch[1] ?? "").trim().toLowerCase();
817
+ return MODEL_SUBCOMMANDS.filter((command) => command.name.startsWith(query)).map((command) => ({
818
+ key: `model:${command.name}`,
819
+ label: `/model ${command.name}`,
820
+ description: command.description,
821
+ submit: `/model ${command.name}`,
822
+ completion: `/model ${command.name}`
823
+ }));
824
+ }
825
+ const permissionMatch = input.match(/^\/(allow|disallow)\s+(.*)$/i);
826
+ if (permissionMatch) {
827
+ const command = (permissionMatch[1] ?? "").toLowerCase();
828
+ const query = (permissionMatch[2] ?? "").trim().toLowerCase();
829
+ return PROJECT_PERMISSIONS.filter((permission) => permission.name.startsWith(query)).map(
830
+ (permission) => ({
831
+ key: `${command}:${permission.name}`,
832
+ label: `/${command} ${permission.name}`,
833
+ description: command === "allow" ? permission.allowDescription : permission.disallowDescription,
834
+ submit: `/${command} ${permission.name}`,
835
+ completion: `/${command} ${permission.name}`
836
+ })
837
+ );
838
+ }
757
839
  const modeMatch = input.match(/^\/mode\s+(.*)$/i);
758
840
  if (modeMatch) {
759
841
  const query = (modeMatch[1] ?? "").trim().toLowerCase();
@@ -778,9 +860,9 @@ function suggestSlashWordwheel(input, craftbooks) {
778
860
  })
779
861
  );
780
862
  }
781
- const startMatch = input.match(/^\/start\s+(.*)$/i);
782
- if (startMatch) {
783
- const query = (startMatch[1] ?? "").trim().toLowerCase();
863
+ const doMatch = input.match(/^\/do\s+(.*)$/i);
864
+ if (doMatch) {
865
+ const query = (doMatch[1] ?? "").trim().toLowerCase();
784
866
  const terms = query.split(/\s+/).filter(Boolean);
785
867
  return craftbooks.filter((book) => {
786
868
  const haystack = `${book.id} ${book.name} ${book.description ?? ""}`.toLowerCase();
@@ -791,10 +873,10 @@ function suggestSlashWordwheel(input, craftbooks) {
791
873
  return leftRank - rightRank || left.name.localeCompare(right.name);
792
874
  }).map((book) => ({
793
875
  key: `craftbook:${book.id}`,
794
- label: `/start ${book.id}`,
876
+ label: `/do ${book.id}`,
795
877
  description: `${book.name} \xB7 ${book.stepCount} ${book.stepCount === 1 ? "step" : "steps"} \xB7 ${book.source}`,
796
- submit: `/start ${book.id}`,
797
- completion: `/start ${book.id}`
878
+ submit: `/do ${book.id}`,
879
+ completion: `/do ${book.id}`
798
880
  }));
799
881
  }
800
882
  return suggestSlashCommands(input).map((command) => ({
@@ -831,7 +913,7 @@ function parseInput(raw, cliMode) {
831
913
  }
832
914
  return cliMode ? { kind: "shell", text } : { kind: "prompt", text };
833
915
  }
834
- var SLASH_COMMAND_WORDWHEEL_SIZE, SLASH_COMMANDS, NIGHT_SHIFT_SUBCOMMANDS;
916
+ var SLASH_COMMAND_WORDWHEEL_SIZE, SLASH_COMMANDS, NIGHT_SHIFT_SUBCOMMANDS, MODEL_SUBCOMMANDS, PROJECT_PERMISSIONS, PROJECT_PERMISSION_USAGE;
835
917
  var init_commands = __esm({
836
918
  "src/tui/commands.ts"() {
837
919
  "use strict";
@@ -841,11 +923,13 @@ var init_commands = __esm({
841
923
  { name: "help", description: "show the command reference" },
842
924
  { name: "project", description: "switch active project" },
843
925
  { name: "gezel", description: "switch active gezel" },
926
+ { name: "allow", description: "allow a project permission" },
927
+ { name: "disallow", description: "disallow a project permission" },
844
928
  { name: "mode", description: "set AI activity: read-only through full play" },
845
929
  { name: "model", description: "switch engine and model" },
846
930
  { name: "thread", description: "switch the active chat thread" },
847
931
  { name: "task", description: "list and manage project tasks" },
848
- { name: "start", description: "start a task from a craftbook" },
932
+ { name: "do", description: "do a task from a craftbook" },
849
933
  { name: "continue", description: "process due and active project tasks" },
850
934
  { name: "nightshift", description: "start, stop, or list night-shift work" },
851
935
  { name: "focus", description: "send into another active chat" },
@@ -859,6 +943,29 @@ var init_commands = __esm({
859
943
  { name: "stop", description: "stop the current night shift" },
860
944
  { name: "list", description: "show current and upcoming night-shift work" }
861
945
  ];
946
+ MODEL_SUBCOMMANDS = [
947
+ { name: "download", description: "choose and download a new on-device model" }
948
+ ];
949
+ PROJECT_PERMISSIONS = [
950
+ {
951
+ name: "edits",
952
+ allowDescription: "let built-in tools and background work edit this project",
953
+ disallowDescription: "make built-in tools and background work read-only"
954
+ },
955
+ {
956
+ name: "codexedits",
957
+ allowDescription: "let Codex sessions edit this project",
958
+ disallowDescription: "put Codex sessions in read-only plan mode"
959
+ },
960
+ {
961
+ name: "claudeedits",
962
+ allowDescription: "let Claude sessions edit this project",
963
+ disallowDescription: "put Claude sessions in read-only plan mode"
964
+ }
965
+ ];
966
+ PROJECT_PERMISSION_USAGE = PROJECT_PERMISSIONS.map(
967
+ (permission) => permission.name
968
+ ).join("|");
862
969
  }
863
970
  });
864
971
 
@@ -883,6 +990,24 @@ function reduceFeed(rows, env2) {
883
990
  open: false
884
991
  }
885
992
  ]);
993
+ case "queue_enqueued": {
994
+ const key = `queue-${event.queueId}`;
995
+ const pending = {
996
+ key,
997
+ sessionId,
998
+ gezelId,
999
+ kind: "pending",
1000
+ text: event.preview,
1001
+ open: false
1002
+ };
1003
+ const idx = rows.findIndex((row) => row.key === key);
1004
+ if (idx === -1) return cap([...rows, pending]);
1005
+ const next = rows.slice();
1006
+ next[idx] = pending;
1007
+ return next;
1008
+ }
1009
+ case "queue_removed":
1010
+ return rows.filter((row) => row.key !== `queue-${event.queueId}`);
886
1011
  case "delta": {
887
1012
  const idx = findOpenAssistant(rows, sessionId);
888
1013
  const open = idx === -1 ? void 0 : rows[idx];
@@ -950,7 +1075,11 @@ function reduceFeed(rows, env2) {
950
1075
  gezelId: "",
951
1076
  kind: "note",
952
1077
  text: `task \xB7 ${event.summary}`,
953
- open: false
1078
+ open: false,
1079
+ taskEvent: {
1080
+ kind: event.kind,
1081
+ ...event.gezelId ? { gezelId: event.gezelId } : {}
1082
+ }
954
1083
  }
955
1084
  ]);
956
1085
  case "error":
@@ -1132,7 +1261,7 @@ function toolRowText(call) {
1132
1261
  }
1133
1262
  function gezelLabel(gezelId, gezels, boring) {
1134
1263
  const g = gezels.find((x) => x.id === gezelId);
1135
- if (!g) return gezelId;
1264
+ if (!g) return boring ? "gezel" : gezelId;
1136
1265
  if (boring) return g.roleBasedName ?? g.role ?? g.id;
1137
1266
  return g.role ? `${g.name} \xB7 ${g.role}` : g.name;
1138
1267
  }
@@ -1276,7 +1405,7 @@ import { jsx, jsxs } from "react/jsx-runtime";
1276
1405
  function ChatFeed(props) {
1277
1406
  const { rows, gezels, boring, focusedSessionId, visible = 16 } = props;
1278
1407
  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: [
1408
+ return /* @__PURE__ */ jsx(Box, { flexDirection: "column", flexGrow: 1, marginBottom: 1, children: shown.length === 0 ? /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
1280
1409
  /* @__PURE__ */ jsx(Text, { color: "yellow", children: TABLE_LOGO }),
1281
1410
  /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 3, children: [
1282
1411
  /* @__PURE__ */ jsxs(Text, { children: [
@@ -1290,7 +1419,7 @@ function ChatFeed(props) {
1290
1419
  if (row.kind === "shell" && row.sessionId.startsWith("term-")) {
1291
1420
  return /* @__PURE__ */ jsx(Text, { wrap: "wrap", children: clip(row.text) }, row.key);
1292
1421
  }
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";
1422
+ 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
1423
  const isFocused = focusedSessionId && row.sessionId === focusedSessionId;
1295
1424
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
1296
1425
  /* @__PURE__ */ jsx(Text, { dimColor: !isFocused, color: isFocused ? "green" : void 0, children: isFocused ? "\u258E" : " " }),
@@ -1299,11 +1428,33 @@ function ChatFeed(props) {
1299
1428
  who,
1300
1429
  ": "
1301
1430
  ] }),
1302
- /* @__PURE__ */ jsx(Text, { color: KIND_COLOR[row.kind], children: clip(row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text) })
1431
+ /* @__PURE__ */ jsx(Text, { color: KIND_COLOR[row.kind], dimColor: row.kind === "pending", children: clip(
1432
+ row.taskEvent ? taskEventText(row, gezels, boring) : row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text
1433
+ ) })
1303
1434
  ] })
1304
1435
  ] }, row.key);
1305
1436
  }) });
1306
1437
  }
1438
+ function taskEventText(row, gezels, boring) {
1439
+ const event = row.taskEvent;
1440
+ if (!boring || !event?.gezelId) return row.text;
1441
+ const actor = gezelLabel(event.gezelId, gezels, true);
1442
+ switch (event.kind) {
1443
+ case "task.entry.dispatched":
1444
+ return row.text.replace(/ handed to .*$/, ` handed to ${actor}`);
1445
+ case "tasknote.appended":
1446
+ return row.text.replace(/^task · .*? noted on /, `task \xB7 ${actor} noted on `);
1447
+ case "tasknote.deleted":
1448
+ return row.text.replace(
1449
+ /^task · .*? removed a note from /,
1450
+ `task \xB7 ${actor} removed a note from `
1451
+ );
1452
+ case "tasknote.updated":
1453
+ return row.text.replace(/^task · .*? edited a note on /, `task \xB7 ${actor} edited a note on `);
1454
+ default:
1455
+ return row.text;
1456
+ }
1457
+ }
1307
1458
  function clip(text) {
1308
1459
  const t = text.replace(/\s+$/, "");
1309
1460
  return t.length > MAX_CHARS ? `${t.slice(0, MAX_CHARS)}
@@ -1323,6 +1474,7 @@ var init_ChatFeed = __esm({
1323
1474
  ].join("\n");
1324
1475
  KIND_COLOR = {
1325
1476
  user: "white",
1477
+ pending: "yellow",
1326
1478
  assistant: "cyan",
1327
1479
  tool: "yellow",
1328
1480
  note: "magenta",
@@ -1403,19 +1555,29 @@ var init_Picker = __esm({
1403
1555
 
1404
1556
  // src/tui/components/EnginePill.tsx
1405
1557
  import { Box as Box3, Text as Text3 } from "ink";
1406
- import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1558
+ import { jsxs as jsxs3 } from "react/jsx-runtime";
1407
1559
  function EnginePill(props) {
1408
1560
  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
- ] }) });
1561
+ const metadata = formatEngineMetadata(provider, model2, accessMode);
1562
+ const activity = formatEngineActivity(busy, label);
1563
+ return /* @__PURE__ */ jsxs3(Box3, { children: [
1564
+ /* @__PURE__ */ jsxs3(Text3, { children: [
1565
+ " ",
1566
+ metadata,
1567
+ " \xB7"
1568
+ ] }),
1569
+ /* @__PURE__ */ jsxs3(Text3, { backgroundColor: busy ? "yellow" : "blackBright", color: busy ? "black" : "white", children: [
1570
+ " ",
1571
+ activity,
1572
+ " "
1573
+ ] })
1574
+ ] });
1415
1575
  }
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 ");
1576
+ function formatEngineMetadata(provider, model2, accessMode) {
1577
+ return [accessMode, formatEngineIdentity(provider, model2)].filter(Boolean).join(" \xB7 ");
1578
+ }
1579
+ function formatEngineActivity(busy, label) {
1580
+ return busy ? `\u25CF ${label ?? "working"}` : "\u25CB idle";
1419
1581
  }
1420
1582
  function formatEngineIdentity(provider, model2) {
1421
1583
  const engine = provider === "llama-cpp" ? "llama" : provider ?? "on-device";
@@ -1431,7 +1593,7 @@ var init_EnginePill = __esm({
1431
1593
  import { Box as Box4, Text as Text4, useInput as useInput2 } from "ink";
1432
1594
  import TextInput from "ink-text-input";
1433
1595
  import { useEffect, useState as useState2 } from "react";
1434
- import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
1596
+ import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs4 } from "react/jsx-runtime";
1435
1597
  function PromptLine(props) {
1436
1598
  const {
1437
1599
  projectName,
@@ -1509,18 +1671,18 @@ function PromptLine(props) {
1509
1671
  const placeholder = pendingPrompt ? pendingPrompt : mode === "cli" ? "shell / @tool \u2026 (/chat to exit)" : "message, or /command, !shell, @tool";
1510
1672
  return /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", children: [
1511
1673
  /* @__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 }),
1674
+ /* @__PURE__ */ jsx3(Text4, { color: "blue", children: projectName }),
1675
+ /* @__PURE__ */ jsx3(Text4, { dimColor: true, children: " \xB7 " }),
1676
+ /* @__PURE__ */ jsx3(Text4, { color: "magenta", children: gezelLabel2 }),
1515
1677
  threadTitle ? /* @__PURE__ */ jsxs4(Fragment2, { children: [
1516
- /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: " \xB7 " }),
1678
+ /* @__PURE__ */ jsx3(Text4, { dimColor: true, children: " \xB7 " }),
1517
1679
  /* @__PURE__ */ jsxs4(Text4, { color: "cyan", children: [
1518
1680
  "\u21B3 ",
1519
1681
  compactThreadTitle(threadTitle)
1520
1682
  ] })
1521
1683
  ] }) : null,
1522
- /* @__PURE__ */ jsx4(Text4, { children: " " }),
1523
- /* @__PURE__ */ jsx4(
1684
+ /* @__PURE__ */ jsx3(Text4, { children: " " }),
1685
+ /* @__PURE__ */ jsx3(
1524
1686
  EnginePill,
1525
1687
  {
1526
1688
  provider,
@@ -1550,8 +1712,8 @@ function PromptLine(props) {
1550
1712
  ] })
1551
1713
  ] }) : null,
1552
1714
  /* @__PURE__ */ jsxs4(Box4, { children: [
1553
- /* @__PURE__ */ jsx4(Text4, { color: pendingPrompt ? "yellow" : mode === "cli" ? "green" : "cyan", children: prefix }),
1554
- /* @__PURE__ */ jsx4(
1715
+ /* @__PURE__ */ jsx3(Text4, { color: pendingPrompt ? "yellow" : mode === "cli" ? "green" : "cyan", children: prefix }),
1716
+ /* @__PURE__ */ jsx3(
1555
1717
  TextInput,
1556
1718
  {
1557
1719
  value,
@@ -1581,7 +1743,7 @@ var init_PromptLine = __esm({
1581
1743
  import { Box as Box5, Text as Text5, useInput as useInput3 } from "ink";
1582
1744
  import TextInput2 from "ink-text-input";
1583
1745
  import { useState as useState3 } from "react";
1584
- import { Fragment as Fragment3, jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
1746
+ import { Fragment as Fragment3, jsx as jsx4, jsxs as jsxs5 } from "react/jsx-runtime";
1585
1747
  function questionOptionCount(question) {
1586
1748
  const choices = question.choices?.length ?? 0;
1587
1749
  const writeIn = question.allowWriteIn ?? true;
@@ -1681,11 +1843,11 @@ function QuestionPrompt(props) {
1681
1843
  askerLabel,
1682
1844
  " asks"
1683
1845
  ] }),
1684
- /* @__PURE__ */ jsx5(Text5, { wrap: "wrap", children: question.prompt }),
1846
+ /* @__PURE__ */ jsx4(Text5, { wrap: "wrap", children: question.prompt }),
1685
1847
  writing ? /* @__PURE__ */ jsxs5(Fragment3, { children: [
1686
1848
  /* @__PURE__ */ jsxs5(Box5, { children: [
1687
- /* @__PURE__ */ jsx5(Text5, { color: "cyan", children: "\u203A " }),
1688
- /* @__PURE__ */ jsx5(
1849
+ /* @__PURE__ */ jsx4(Text5, { color: "cyan", children: "\u203A " }),
1850
+ /* @__PURE__ */ jsx4(
1689
1851
  TextInput2,
1690
1852
  {
1691
1853
  value: writeIn,
@@ -1718,8 +1880,8 @@ function QuestionPrompt(props) {
1718
1880
  options.length > QUESTION_OPTION_WINDOW_SIZE ? ` \xB7 ${activeOptionIndex + 1}/${options.length}` : ""
1719
1881
  ] })
1720
1882
  ] }),
1721
- submitting ? /* @__PURE__ */ jsx5(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
1722
- error ? /* @__PURE__ */ jsx5(Text5, { color: "red", children: error }) : null
1883
+ submitting ? /* @__PURE__ */ jsx4(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
1884
+ error ? /* @__PURE__ */ jsx4(Text5, { color: "red", children: error }) : null
1723
1885
  ] });
1724
1886
  }
1725
1887
  function toggleSet(current, value) {
@@ -1738,11 +1900,12 @@ var init_QuestionPrompt = __esm({
1738
1900
 
1739
1901
  // src/tui/craftbook-start.ts
1740
1902
  import {
1741
- CRAFTBOOK_ROLE_META
1903
+ CRAFTBOOK_ROLE_META,
1904
+ visibleCatalogItems
1742
1905
  } from "@bendyline/gezel";
1743
- function normalizeCraftbooks(items) {
1906
+ function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
1744
1907
  const byId = /* @__PURE__ */ new Map();
1745
- for (const item of items) {
1908
+ for (const item of visibleCatalogItems(items, showWorkInProgressFeatures)) {
1746
1909
  if (item.manifest.kind !== "craftbook-template") continue;
1747
1910
  const manifest = item.manifest;
1748
1911
  if (byId.has(manifest.id)) continue;
@@ -1827,6 +1990,9 @@ var init_craftbook_start = __esm({
1827
1990
  });
1828
1991
 
1829
1992
  // src/tui/model-picker.ts
1993
+ import {
1994
+ formatModelAttribution as formatModelAttribution2
1995
+ } from "@bendyline/gezel";
1830
1996
  function modelProviderLabel(provider) {
1831
1997
  switch (provider) {
1832
1998
  case "copilot":
@@ -1867,9 +2033,10 @@ function configuredModelProviders(config, opts) {
1867
2033
  return providers.sort((a, b) => PROVIDER_ORDER.indexOf(a) - PROVIDER_ORDER.indexOf(b));
1868
2034
  }
1869
2035
  async function loadModelChoices(client, config, platform = process.platform, arch = process.arch) {
1870
- const [copilot, memory] = await Promise.all([
2036
+ const [copilot, memory, catalog] = await Promise.all([
1871
2037
  client.getCopilotStatus().catch(() => null),
1872
- client.getMemoryProfile().catch(() => null)
2038
+ client.getMemoryProfile().catch(() => null),
2039
+ client.listCatalogItems ? client.listCatalogItems("chat-model").catch(() => null) : Promise.resolve(null)
1873
2040
  ]);
1874
2041
  const providers = configuredModelProviders(config, {
1875
2042
  platform,
@@ -1888,18 +2055,76 @@ async function loadModelChoices(client, config, platform = process.platform, arc
1888
2055
  })
1889
2056
  );
1890
2057
  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
- }))
2058
+ ({ provider, models }) => models.map((model2) => {
2059
+ const manifest = catalogManifestForModel(catalog?.items ?? [], provider, model2.id);
2060
+ const attribution = manifest ? ` (${formatModelAttribution2(manifest)})` : "";
2061
+ return {
2062
+ provider,
2063
+ model: model2,
2064
+ value: `${provider}:${model2.id}`,
2065
+ label: `${modelProviderLabel(provider)} \xB7 ${model2.name}${attribution}`
2066
+ };
2067
+ })
2068
+ );
2069
+ }
2070
+ async function loadModelDownloadChoices(client, config, platform = process.platform, arch = process.arch) {
2071
+ const [memory, catalog] = await Promise.all([
2072
+ client.getMemoryProfile(),
2073
+ client.listCatalogItems("chat-model")
2074
+ ]);
2075
+ const provider = config.provider === "mlx" || config.provider === "llama-cpp" ? config.provider : memory.platform === "darwin" && platform === "darwin" && arch === "arm64" ? "mlx" : "llama-cpp";
2076
+ const installed = await client.listProviderModels(provider).catch(() => ({ models: [] }));
2077
+ const installedIds = new Set(installed.models.map((model2) => model2.id));
2078
+ const ranked = rankChatModels(
2079
+ catalog.items,
2080
+ {
2081
+ platform: memory.platform,
2082
+ gpuVramBytes: memory.gpuVramBytes,
2083
+ ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
2084
+ totalRamBytes: memory.totalRamBytes,
2085
+ usableBytes: memory.usableBytes,
2086
+ ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
2087
+ },
2088
+ provider
1897
2089
  );
2090
+ return ranked.filter((model2) => !installedIds.has(model2.id)).map((model2, index) => ({
2091
+ provider,
2092
+ model: model2,
2093
+ value: `${provider}:${model2.id}`,
2094
+ label: bootstrapChatModelLabel(model2),
2095
+ hint: [
2096
+ index === 0 ? "recommended" : null,
2097
+ formatDownloadSize(model2.approxSizeBytes),
2098
+ modelFitLabel(model2.fit)
2099
+ ].filter(Boolean).join(" \xB7 ")
2100
+ }));
2101
+ }
2102
+ function catalogManifestForModel(items, provider, modelId) {
2103
+ for (const item of items) {
2104
+ if (item.manifest.kind !== "chat-model") continue;
2105
+ const manifest = item.manifest;
2106
+ if (manifest.id === modelId) return manifest;
2107
+ if (provider === "ollama" && manifest.ollama?.tag === modelId) return manifest;
2108
+ }
2109
+ return null;
2110
+ }
2111
+ function modelFitLabel(fit) {
2112
+ switch (fit) {
2113
+ case "fits":
2114
+ return "fits this device";
2115
+ case "fits-offload":
2116
+ return "fits with offload";
2117
+ case "tight":
2118
+ return "tight fit";
2119
+ case "too-big":
2120
+ return "larger than recommended";
2121
+ }
1898
2122
  }
1899
2123
  var PROVIDER_ORDER;
1900
2124
  var init_model_picker = __esm({
1901
2125
  "src/tui/model-picker.ts"() {
1902
2126
  "use strict";
2127
+ init_bootstrap();
1903
2128
  PROVIDER_ORDER = [
1904
2129
  "mlx",
1905
2130
  "llama-cpp",
@@ -2010,7 +2235,7 @@ var init_streams = __esm({
2010
2235
  // src/tui/App.tsx
2011
2236
  import { Box as Box6, Text as Text6, useApp, useInput as useInput4, useStdout } from "ink";
2012
2237
  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";
2238
+ import { jsx as jsx5, jsxs as jsxs6 } from "react/jsx-runtime";
2014
2239
  function useTerminalSize() {
2015
2240
  const { stdout } = useStdout();
2016
2241
  const [size, setSize] = useState4({ rows: stdout?.rows ?? 24, columns: stdout?.columns ?? 80 });
@@ -2040,6 +2265,11 @@ function App(props) {
2040
2265
  );
2041
2266
  const [startCategoryId, setStartCategoryId] = useState4(null);
2042
2267
  const [modelChoices, setModelChoices] = useState4([]);
2268
+ const [modelDownloadChoices, setModelDownloadChoices] = useState4([]);
2269
+ const [modelDownloadProgress, setModelDownloadProgress] = useState4(
2270
+ null
2271
+ );
2272
+ const [modelDownloadReturn, setModelDownloadReturn] = useState4(null);
2043
2273
  const [modelChoicesLoading, setModelChoicesLoading] = useState4(false);
2044
2274
  const [threadsLoading, setThreadsLoading] = useState4(false);
2045
2275
  const [pendingQuestions, setPendingQuestions] = useState4([]);
@@ -2068,7 +2298,7 @@ function App(props) {
2068
2298
  const wordwheelRows = wordwheelCount > 0 ? Math.min(SLASH_COMMAND_WORDWHEEL_SIZE, wordwheelCount) + 1 : 0;
2069
2299
  const questionRows = pendingQuestion ? Math.min(QUESTION_OPTION_WINDOW_SIZE, Math.max(1, questionOptionCount(pendingQuestion))) + 4 : 0;
2070
2300
  const modelPickerWindowSize = Math.max(4, Math.min(10, termRows - 12));
2071
- const inventoryPickerRows = overlay === "model" || overlay === "start-category" || overlay === "start-craftbook" ? modelPickerWindowSize + 5 : 0;
2301
+ const inventoryPickerRows = overlay === "model" || overlay === "model-download" || overlay === "start-category" || overlay === "start-craftbook" ? modelPickerWindowSize + 5 : 0;
2072
2302
  const visibleRows = Math.max(
2073
2303
  4,
2074
2304
  termRows - 7 - wordwheelRows - questionRows - inventoryPickerRows
@@ -2089,6 +2319,23 @@ function App(props) {
2089
2319
  (text, kind = "note") => setRows((r) => appendNote(r, text, kind)),
2090
2320
  []
2091
2321
  );
2322
+ const gezelIds = useRef2(/* @__PURE__ */ new Set());
2323
+ const gezelRefreshInFlight = useRef2(false);
2324
+ const applyGezelSnapshot = useCallback((next) => {
2325
+ gezelIds.current = new Set(next.map((gezel) => gezel.id));
2326
+ setGezels(next);
2327
+ }, []);
2328
+ const refreshGezels = useCallback(async () => {
2329
+ if (gezelRefreshInFlight.current) return;
2330
+ gezelRefreshInFlight.current = true;
2331
+ try {
2332
+ const result = await client.listGezels();
2333
+ applyGezelSnapshot(result.gezels);
2334
+ } catch {
2335
+ } finally {
2336
+ gezelRefreshInFlight.current = false;
2337
+ }
2338
+ }, [applyGezelSnapshot, client]);
2092
2339
  const taskLoadSequence = useRef2(0);
2093
2340
  const refreshTasks = useCallback(async () => {
2094
2341
  const sequence = ++taskLoadSequence.current;
@@ -2104,13 +2351,13 @@ function App(props) {
2104
2351
  const sequence = ++craftbookLoadSequence.current;
2105
2352
  const result = await client.listProjectCraftbooks(projectId);
2106
2353
  if (sequence !== craftbookLoadSequence.current) return [];
2107
- const next = normalizeCraftbooks(result.items);
2354
+ const next = normalizeCraftbooks(result.items, config?.showWorkInProgressFeatures === true);
2108
2355
  setCraftbooks(next);
2109
2356
  setCraftbookProjectType(result.projectType ?? null);
2110
2357
  setSuggestedCraftbookIds(new Set(result.suggestedIds ?? []));
2111
2358
  setCraftbooksNeedingSetup(new Set(Object.keys(result.missingToolsets)));
2112
2359
  return next;
2113
- }, [client, projectId]);
2360
+ }, [client, config?.showWorkInProgressFeatures, projectId]);
2114
2361
  useProjectEvents(
2115
2362
  client,
2116
2363
  projectId,
@@ -2118,6 +2365,8 @@ function App(props) {
2118
2365
  (env2) => {
2119
2366
  setRows((r) => reduceFeed(r, env2));
2120
2367
  setTurns((t) => reduceTurns(t, env2));
2368
+ const eventGezelId = env2.gezelId || (env2.event.type === "task_event" ? env2.event.gezelId : void 0);
2369
+ if (eventGezelId && !gezelIds.current.has(eventGezelId)) void refreshGezels();
2121
2370
  if (env2.event.type === "task_event") void refreshTasks();
2122
2371
  if (env2.event.type === "user_message" && env2.sessionId === ownSessionId) {
2123
2372
  const nextTitle = env2.event.message.content.slice(0, 60).trim() || "Untitled";
@@ -2133,7 +2382,7 @@ function App(props) {
2133
2382
  setPendingQuestions((questions) => updatePendingQuestion(questions, question));
2134
2383
  }
2135
2384
  },
2136
- [ownSessionId, refreshTasks]
2385
+ [ownSessionId, refreshGezels, refreshTasks]
2137
2386
  )
2138
2387
  );
2139
2388
  useTerminalEvents(
@@ -2172,7 +2421,11 @@ function App(props) {
2172
2421
  const ensureSession = useCallback(
2173
2422
  async (gezelId, pid) => {
2174
2423
  try {
2175
- const session = await client.createChatSession({ gezelId, projectId: pid });
2424
+ const session = await client.createChatSession({
2425
+ gezelId,
2426
+ projectId: pid,
2427
+ roleBasedNameOnlyMode: boring
2428
+ });
2176
2429
  setOwnSessionId(session.id);
2177
2430
  setFocusedSessionId(session.id);
2178
2431
  setActiveThreadTitle(displayThreadTitle(session.title));
@@ -2182,7 +2435,7 @@ function App(props) {
2182
2435
  return false;
2183
2436
  }
2184
2437
  },
2185
- [client, note]
2438
+ [client, note, boring]
2186
2439
  );
2187
2440
  const switchProject = useCallback(
2188
2441
  async (id) => {
@@ -2216,6 +2469,56 @@ function App(props) {
2216
2469
  },
2217
2470
  [client, ensureSession, note, projectId, projects]
2218
2471
  );
2472
+ const openModelPicker = useCallback(async () => {
2473
+ if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2474
+ if (activeGezel.fixedFunction) {
2475
+ return note("this gezel runs a fixed tool and does not use a chat model.", "error");
2476
+ }
2477
+ if (modelChoicesLoading) return note("model choices are already loading.");
2478
+ setModelChoicesLoading(true);
2479
+ note("loading available engines and models\u2026");
2480
+ try {
2481
+ const choices = await loadModelChoices(client, config ?? await client.getConfig());
2482
+ setModelChoices(choices);
2483
+ setOverlay("model");
2484
+ } catch (err) {
2485
+ note(`could not load models: ${errMsg(err)}`, "error");
2486
+ } finally {
2487
+ setModelChoicesLoading(false);
2488
+ }
2489
+ }, [activeGezel, activeGezelId, client, config, modelChoicesLoading, note]);
2490
+ const openModelDownloadPicker = useCallback(
2491
+ async (returnTo = null) => {
2492
+ if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2493
+ if (activeGezel.fixedFunction) {
2494
+ return note("this gezel runs a fixed tool and does not use a chat model.", "error");
2495
+ }
2496
+ if (modelChoicesLoading) return note("model choices are already loading.");
2497
+ setOverlay(null);
2498
+ setModelChoicesLoading(true);
2499
+ note("finding on-device models that fit this machine\u2026");
2500
+ try {
2501
+ const choices = await loadModelDownloadChoices(
2502
+ client,
2503
+ config ?? await client.getConfig()
2504
+ );
2505
+ if (choices.length === 0) {
2506
+ note("no additional compatible on-device models are available to download.");
2507
+ if (returnTo === "model") await openModelPicker();
2508
+ return;
2509
+ }
2510
+ setModelDownloadChoices(choices);
2511
+ setModelDownloadProgress(null);
2512
+ setModelDownloadReturn(returnTo);
2513
+ setOverlay("model-download");
2514
+ } catch (err) {
2515
+ note(`could not load downloadable models: ${errMsg(err)}`, "error");
2516
+ } finally {
2517
+ setModelChoicesLoading(false);
2518
+ }
2519
+ },
2520
+ [activeGezel, activeGezelId, client, config, modelChoicesLoading, note, openModelPicker]
2521
+ );
2219
2522
  const openThreadPicker = useCallback(async () => {
2220
2523
  if (!activeGezelId) return note("no active gezel yet.", "error");
2221
2524
  if (threadsLoading) return;
@@ -2252,7 +2555,11 @@ function App(props) {
2252
2555
  setOverlay(null);
2253
2556
  if (!activeGezelId) return note("no active gezel yet.", "error");
2254
2557
  try {
2255
- const session = await client.createChatSession({ gezelId: activeGezelId, projectId });
2558
+ const session = await client.createChatSession({
2559
+ gezelId: activeGezelId,
2560
+ projectId,
2561
+ roleBasedNameOnlyMode: boring
2562
+ });
2256
2563
  setOwnSessionId(session.id);
2257
2564
  setFocusedSessionId(session.id);
2258
2565
  setActiveThreadTitle(displayThreadTitle(session.title));
@@ -2261,7 +2568,7 @@ function App(props) {
2261
2568
  } catch (err) {
2262
2569
  note(`could not start a thread: ${errMsg(err)}`, "error");
2263
2570
  }
2264
- }, [activeGezelId, client, note, projectId]);
2571
+ }, [activeGezelId, client, note, projectId, boring]);
2265
2572
  useEffect3(() => {
2266
2573
  let cancelled = false;
2267
2574
  (async () => {
@@ -2273,22 +2580,31 @@ function App(props) {
2273
2580
  ]);
2274
2581
  if (cancelled) return;
2275
2582
  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
- );
2583
+ applyGezelSnapshot(gz.gezels);
2584
+ const projectRows = pj.projects.map((p) => ({
2585
+ id: p.id,
2586
+ name: p.name,
2587
+ workingDir: p.workingDir,
2588
+ voormanGezelId: p.voormanGezelId,
2589
+ managedWorkspaceWritePolicy: p.managedWorkspaceWritePolicy,
2590
+ allowGezelWrites: p.allowGezelWrites,
2591
+ codexPermissionMode: p.codexPermissionMode,
2592
+ claudePermissionMode: p.claudePermissionMode
2593
+ }));
2594
+ setProjects(projectRows);
2289
2595
  const gezelId = props.initialGezelId;
2596
+ const initialGezel = gz.gezels.find((gezel) => gezel.id === gezelId);
2597
+ const initialProject = projectRows.find((project) => project.id === projectId);
2290
2598
  setActiveGezelId(gezelId);
2291
2599
  setStatus(null);
2600
+ if (activeAccessMode({
2601
+ provider: initialGezel?.provider ?? cfg.provider,
2602
+ project: initialProject,
2603
+ gezel: initialGezel,
2604
+ config: cfg
2605
+ }) === "read-only") {
2606
+ note(READ_ONLY_BOOT_NOTE);
2607
+ }
2292
2608
  await ensureSession(gezelId, projectId);
2293
2609
  } catch (err) {
2294
2610
  if (!cancelled) setStatus(`Failed to connect: ${errMsg(err)}`);
@@ -2360,7 +2676,8 @@ function App(props) {
2360
2676
  for (const r of rows) {
2361
2677
  if (r.sessionId === "local" || r.sessionId.startsWith("term-")) continue;
2362
2678
  if (!seen.has(r.sessionId)) {
2363
- const label = gezels.find((g) => g.id === r.gezelId)?.name ?? (r.gezelId || r.sessionId);
2679
+ const gezel = gezels.find((candidate) => candidate.id === r.gezelId);
2680
+ const label = boring ? gezelLabel(r.gezelId, gezels, true) : gezel?.name ?? (r.gezelId || r.sessionId);
2364
2681
  seen.set(r.sessionId, label);
2365
2682
  }
2366
2683
  }
@@ -2371,7 +2688,7 @@ function App(props) {
2371
2688
  items.push({ label, value: sid });
2372
2689
  }
2373
2690
  return items;
2374
- }, [rows, gezels, ownSessionId, gezelLine]);
2691
+ }, [rows, gezels, ownSessionId, gezelLine, boring]);
2375
2692
  const cancelActive = useCallback(async () => {
2376
2693
  const sessions = [...turns.keys()];
2377
2694
  const runs = [...activeRuns];
@@ -2404,6 +2721,37 @@ function App(props) {
2404
2721
  },
2405
2722
  [client, note]
2406
2723
  );
2724
+ const applyProjectPermission = useCallback(
2725
+ async (permission, allowed) => {
2726
+ const permissionName = parseProjectPermissionName(permission);
2727
+ if (!permissionName) {
2728
+ note(`usage: /${allowed ? "allow" : "disallow"} ${PROJECT_PERMISSION_USAGE}`, "error");
2729
+ return;
2730
+ }
2731
+ try {
2732
+ const patch = permissionName === "edits" ? { managedWorkspaceWritePolicy: allowed ? "allow" : "deny" } : permissionName === "codexedits" ? { codexPermissionMode: allowed ? "edit" : "plan" } : { claudePermissionMode: allowed ? "acceptEdits" : "plan" };
2733
+ const updated = await client.updateProject(projectId, patch);
2734
+ setProjects(
2735
+ (current) => current.map(
2736
+ (project) => project.id === projectId ? { ...project, ...updated } : project
2737
+ )
2738
+ );
2739
+ if (permissionName === "edits") {
2740
+ note(
2741
+ 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}.`
2742
+ );
2743
+ } else {
2744
+ const provider = permissionName === "codexedits" ? "Codex" : "Claude";
2745
+ note(
2746
+ allowed ? `${provider} edits allowed. ${provider} sessions can now modify ${projectName}.` : `${provider} edits disallowed. ${provider} sessions are now read-only in ${projectName}.`
2747
+ );
2748
+ }
2749
+ } catch (err) {
2750
+ note(`could not change project permission: ${errMsg(err)}`, "error");
2751
+ }
2752
+ },
2753
+ [client, note, projectId, projectName]
2754
+ );
2407
2755
  const startCraftbook = useCallback(
2408
2756
  async (book) => {
2409
2757
  setOverlay(null);
@@ -2520,7 +2868,10 @@ function App(props) {
2520
2868
  const target = focusedSessionId ?? ownSessionId;
2521
2869
  if (!target) return note("no active session yet.", "error");
2522
2870
  try {
2523
- await client.sendToChatSession(target, parsed.text);
2871
+ await client.sendToChatSession(
2872
+ target,
2873
+ turns.has(target) ? { message: parsed.text, nudge: true } : parsed.text
2874
+ );
2524
2875
  } catch (err) {
2525
2876
  note(`send failed: ${errMsg(err)}`, "error");
2526
2877
  }
@@ -2583,7 +2934,8 @@ function App(props) {
2583
2934
  note,
2584
2935
  pendingInput,
2585
2936
  submitTaskPrompt,
2586
- taskPrompt
2937
+ taskPrompt,
2938
+ turns
2587
2939
  ]
2588
2940
  );
2589
2941
  const runCommand = useCallback(
@@ -2597,31 +2949,21 @@ function App(props) {
2597
2949
  return setOverlay("project");
2598
2950
  case "gezel":
2599
2951
  return setOverlay("gezel");
2952
+ case "allow":
2953
+ await applyProjectPermission(rest, true);
2954
+ return;
2955
+ case "disallow":
2956
+ await applyProjectPermission(rest, false);
2957
+ return;
2600
2958
  case "mode":
2601
2959
  if (!rest.trim()) return setOverlay("engagement-mode");
2602
2960
  await applyEngagementMode(rest);
2603
2961
  return;
2604
2962
  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");
2608
- }
2609
- if (modelChoicesLoading) return note("model choices are already loading.");
2610
- setModelChoicesLoading(true);
2611
- note("loading available engines and models\u2026");
2612
- 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");
2616
- }
2617
- setModelChoices(choices);
2618
- setOverlay("model");
2619
- } catch (err) {
2620
- note(`could not load models: ${errMsg(err)}`, "error");
2621
- } finally {
2622
- setModelChoicesLoading(false);
2623
- }
2624
- return;
2963
+ const subcommand = rest.trim().toLowerCase();
2964
+ if (!subcommand) return openModelPicker();
2965
+ if (subcommand === "download") return openModelDownloadPicker();
2966
+ return note("usage: /model [download]", "error");
2625
2967
  }
2626
2968
  case "thread":
2627
2969
  await openThreadPicker();
@@ -2672,7 +3014,7 @@ function App(props) {
2672
3014
  }
2673
3015
  return;
2674
3016
  }
2675
- case "start": {
3017
+ case "do": {
2676
3018
  let available = craftbooks;
2677
3019
  if (available.length === 0) {
2678
3020
  try {
@@ -2690,7 +3032,7 @@ function App(props) {
2690
3032
  }
2691
3033
  const book = findCraftbook(available, rest);
2692
3034
  if (!book) {
2693
- return note(`craftbook not found: ${rest.trim()} (try /start)`, "error");
3035
+ return note(`craftbook not found: ${rest.trim()} (try /do)`, "error");
2694
3036
  }
2695
3037
  await startCraftbook(book);
2696
3038
  return;
@@ -2748,15 +3090,14 @@ function App(props) {
2748
3090
  }
2749
3091
  },
2750
3092
  [
2751
- activeGezel,
2752
- activeGezelId,
2753
3093
  applyEngagementMode,
3094
+ applyProjectPermission,
2754
3095
  client,
2755
- config,
2756
3096
  craftbooks,
2757
- modelChoicesLoading,
2758
3097
  note,
2759
3098
  exit,
3099
+ openModelDownloadPicker,
3100
+ openModelPicker,
2760
3101
  openThreadPicker,
2761
3102
  projectId,
2762
3103
  projectName,
@@ -2765,11 +3106,10 @@ function App(props) {
2765
3106
  startCraftbook
2766
3107
  ]
2767
3108
  );
2768
- const applyModelChoice = useCallback(
2769
- async (value2) => {
3109
+ const applyModelSelection = useCallback(
3110
+ async (choice) => {
2770
3111
  setOverlay(null);
2771
3112
  if (!activeGezelId || !activeGezel || !config) return;
2772
- const choice = modelChoices.find((item) => item.value === value2);
2773
3113
  const nextProvider = choice?.provider ?? null;
2774
3114
  const nextModel = choice?.model.id;
2775
3115
  const providerChanged = (activeGezel.provider ?? null) !== nextProvider;
@@ -2794,8 +3134,80 @@ function App(props) {
2794
3134
  note(`could not switch model: ${errMsg(err)}`, "error");
2795
3135
  }
2796
3136
  },
2797
- [activeGezel, activeGezelId, client, config, ensureSession, modelChoices, note, projectId]
3137
+ [activeGezel, activeGezelId, client, config, ensureSession, note, projectId]
2798
3138
  );
3139
+ const applyModelChoice = useCallback(
3140
+ async (value2) => {
3141
+ await applyModelSelection(modelChoices.find((item) => item.value === value2));
3142
+ },
3143
+ [applyModelSelection, modelChoices]
3144
+ );
3145
+ const installModelDownload = useCallback(
3146
+ async (value2) => {
3147
+ const choice = modelDownloadChoices.find((candidate) => candidate.value === value2);
3148
+ if (!choice) return;
3149
+ let terminalError = null;
3150
+ setModelDownloadProgress({
3151
+ choice,
3152
+ bytesWritten: 0,
3153
+ totalBytes: choice.model.approxSizeBytes,
3154
+ pct: 0,
3155
+ phase: "starting"
3156
+ });
3157
+ const onEvent = (event) => {
3158
+ if (event.type === "error") terminalError = event.error;
3159
+ const progress = readModelDownloadProgress(choice, event);
3160
+ if (progress) setModelDownloadProgress(progress);
3161
+ };
3162
+ try {
3163
+ if (choice.provider === "mlx") {
3164
+ await client.installMlxModel(choice.model.id, onEvent);
3165
+ } else {
3166
+ await client.installLlamaCppModel(choice.model.id, onEvent);
3167
+ }
3168
+ if (terminalError) throw new Error(terminalError);
3169
+ const installedChoice = {
3170
+ provider: choice.provider,
3171
+ model: {
3172
+ id: choice.model.id,
3173
+ name: choice.model.name
3174
+ },
3175
+ value: choice.value,
3176
+ label: `${modelProviderLabel(choice.provider)} \xB7 ${choice.model.name}`
3177
+ };
3178
+ setModelChoices((current) => [
3179
+ ...current.filter((candidate) => candidate.value !== installedChoice.value),
3180
+ installedChoice
3181
+ ]);
3182
+ setModelDownloadProgress(null);
3183
+ note(`downloaded ${choice.model.name}; switching this gezel to it\u2026`);
3184
+ await applyModelSelection(installedChoice);
3185
+ } catch (err) {
3186
+ setModelDownloadProgress(null);
3187
+ setOverlay("model-download");
3188
+ note(`model download failed: ${errMsg(err)}`, "error");
3189
+ }
3190
+ },
3191
+ [applyModelSelection, client, modelDownloadChoices, note]
3192
+ );
3193
+ const cancelModelDownload = useCallback(async () => {
3194
+ const progress = modelDownloadProgress;
3195
+ if (!progress) return;
3196
+ try {
3197
+ if (progress.choice.provider === "mlx") {
3198
+ await client.cancelMlxModelInstall(progress.choice.model.id);
3199
+ } else {
3200
+ await client.cancelLlamaCppModelInstall(progress.choice.model.id);
3201
+ }
3202
+ note(`canceled the ${progress.choice.model.name} download.`);
3203
+ } catch (err) {
3204
+ note(`could not cancel model download: ${errMsg(err)}`, "error");
3205
+ } finally {
3206
+ setModelDownloadProgress(null);
3207
+ if (modelDownloadReturn === "model") await openModelPicker();
3208
+ else setOverlay(null);
3209
+ }
3210
+ }, [client, modelDownloadProgress, modelDownloadReturn, note, openModelPicker]);
2799
3211
  const onSubmit = useCallback(
2800
3212
  (raw) => {
2801
3213
  setValue("");
@@ -2841,10 +3253,10 @@ function App(props) {
2841
3253
  }
2842
3254
  );
2843
3255
  if (status) {
2844
- return /* @__PURE__ */ jsx6(Box6, { flexDirection: "column", padding: 1, children: /* @__PURE__ */ jsx6(Text6, { color: status.startsWith("Failed") ? "red" : "cyan", children: status }) });
3256
+ return /* @__PURE__ */ jsx5(Box6, { flexDirection: "column", padding: 1, children: /* @__PURE__ */ jsx5(Text6, { color: status.startsWith("Failed") ? "red" : "cyan", children: status }) });
2845
3257
  }
2846
3258
  return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", padding: 1, children: [
2847
- /* @__PURE__ */ jsx6(
3259
+ /* @__PURE__ */ jsx5(
2848
3260
  ChatFeed,
2849
3261
  {
2850
3262
  rows,
@@ -2854,7 +3266,7 @@ function App(props) {
2854
3266
  visible: visibleRows
2855
3267
  }
2856
3268
  ),
2857
- overlay === "project" ? /* @__PURE__ */ jsx6(
3269
+ overlay === "project" ? /* @__PURE__ */ jsx5(
2858
3270
  Picker,
2859
3271
  {
2860
3272
  title: "Switch project",
@@ -2863,7 +3275,7 @@ function App(props) {
2863
3275
  onSelect: (id) => void switchProject(id)
2864
3276
  }
2865
3277
  ) : null,
2866
- overlay === "gezel" ? /* @__PURE__ */ jsx6(
3278
+ overlay === "gezel" ? /* @__PURE__ */ jsx5(
2867
3279
  Picker,
2868
3280
  {
2869
3281
  title: "Switch gezel",
@@ -2883,7 +3295,7 @@ function App(props) {
2883
3295
  }
2884
3296
  }
2885
3297
  ) : null,
2886
- overlay === "engagement-mode" ? /* @__PURE__ */ jsx6(
3298
+ overlay === "engagement-mode" ? /* @__PURE__ */ jsx5(
2887
3299
  Picker,
2888
3300
  {
2889
3301
  title: "Choose AI engagement mode",
@@ -2897,16 +3309,21 @@ function App(props) {
2897
3309
  onSelect: (selected) => void applyEngagementMode(selected)
2898
3310
  }
2899
3311
  ) : null,
2900
- overlay === "model" ? /* @__PURE__ */ jsx6(
3312
+ overlay === "model" ? /* @__PURE__ */ jsx5(
2901
3313
  Picker,
2902
3314
  {
2903
- title: "Choose engine + model",
3315
+ title: "Choose engine + model - models are downloaded from Hugging Face (huggingface.co)",
2904
3316
  items: [
2905
3317
  {
2906
3318
  label: "Use default",
2907
3319
  value: "__default__",
2908
3320
  hint: `${modelProviderLabel(config?.provider ?? "llama-cpp")}${config?.defaultModel?.[config.provider] ? ` \xB7 ${config.defaultModel[config.provider]}` : ""}`
2909
3321
  },
3322
+ {
3323
+ label: "Download a new model\u2026",
3324
+ value: "__download__",
3325
+ hint: "browse on-device models ranked for this machine"
3326
+ },
2910
3327
  ...modelChoices.map((choice) => ({
2911
3328
  label: choice.label,
2912
3329
  value: choice.value,
@@ -2916,10 +3333,36 @@ function App(props) {
2916
3333
  initialValue: activeGezel?.provider && activeGezel.model ? `${activeGezel.provider}:${activeGezel.model}` : "__default__",
2917
3334
  windowSize: modelPickerWindowSize,
2918
3335
  onCancel: () => setOverlay(null),
2919
- onSelect: (value2) => void applyModelChoice(value2)
3336
+ onSelect: (value2) => {
3337
+ if (value2 === "__download__") void openModelDownloadPicker("model");
3338
+ else void applyModelChoice(value2);
3339
+ }
2920
3340
  }
2921
3341
  ) : null,
2922
- overlay === "start-category" ? /* @__PURE__ */ jsx6(
3342
+ overlay === "model-download" ? modelDownloadProgress ? /* @__PURE__ */ jsx5(
3343
+ ModelDownloadProgressPanel,
3344
+ {
3345
+ progress: modelDownloadProgress,
3346
+ onCancel: () => void cancelModelDownload()
3347
+ }
3348
+ ) : /* @__PURE__ */ jsx5(
3349
+ Picker,
3350
+ {
3351
+ title: "Download and use an on-device model",
3352
+ items: modelDownloadChoices.map((choice) => ({
3353
+ label: choice.label,
3354
+ value: choice.value,
3355
+ hint: choice.hint
3356
+ })),
3357
+ windowSize: modelPickerWindowSize,
3358
+ onCancel: () => {
3359
+ if (modelDownloadReturn === "model") setOverlay("model");
3360
+ else setOverlay(null);
3361
+ },
3362
+ onSelect: (value2) => void installModelDownload(value2)
3363
+ }
3364
+ ) : null,
3365
+ overlay === "start-category" ? /* @__PURE__ */ jsx5(
2923
3366
  Picker,
2924
3367
  {
2925
3368
  title: "Choose a craftbook category",
@@ -2936,7 +3379,7 @@ function App(props) {
2936
3379
  }
2937
3380
  }
2938
3381
  ) : null,
2939
- overlay === "start-craftbook" ? /* @__PURE__ */ jsx6(
3382
+ overlay === "start-craftbook" ? /* @__PURE__ */ jsx5(
2940
3383
  Picker,
2941
3384
  {
2942
3385
  title: startCategory?.label ?? "Start a craftbook",
@@ -2953,7 +3396,7 @@ function App(props) {
2953
3396
  }
2954
3397
  }
2955
3398
  ) : null,
2956
- overlay === "thread" ? /* @__PURE__ */ jsx6(
3399
+ overlay === "thread" ? /* @__PURE__ */ jsx5(
2957
3400
  Picker,
2958
3401
  {
2959
3402
  title: `Threads with ${gezelLine}`,
@@ -2974,7 +3417,7 @@ function App(props) {
2974
3417
  }
2975
3418
  }
2976
3419
  ) : null,
2977
- overlay === "task" ? /* @__PURE__ */ jsx6(
3420
+ overlay === "task" ? /* @__PURE__ */ jsx5(
2978
3421
  Picker,
2979
3422
  {
2980
3423
  title: `Tasks \xB7 ${tasks.filter((task2) => task2.status === "active").length} active`,
@@ -2999,7 +3442,7 @@ function App(props) {
2999
3442
  }
3000
3443
  }
3001
3444
  ) : null,
3002
- overlay === "task-actions" && managedTask ? /* @__PURE__ */ jsx6(
3445
+ overlay === "task-actions" && managedTask ? /* @__PURE__ */ jsx5(
3003
3446
  Picker,
3004
3447
  {
3005
3448
  title: `${managedTask.ref} \xB7 ${managedTask.status}`,
@@ -3034,7 +3477,7 @@ function App(props) {
3034
3477
  }
3035
3478
  }
3036
3479
  ) : null,
3037
- overlay === "task-status" && managedTask ? /* @__PURE__ */ jsx6(
3480
+ overlay === "task-status" && managedTask ? /* @__PURE__ */ jsx5(
3038
3481
  Picker,
3039
3482
  {
3040
3483
  title: `Set ${managedTask.ref} status`,
@@ -3043,7 +3486,7 @@ function App(props) {
3043
3486
  onSelect: (status2) => void applyTaskStatus(status2)
3044
3487
  }
3045
3488
  ) : null,
3046
- overlay === "task-assignee" && managedTask ? /* @__PURE__ */ jsx6(
3489
+ overlay === "task-assignee" && managedTask ? /* @__PURE__ */ jsx5(
3047
3490
  Picker,
3048
3491
  {
3049
3492
  title: `Assign ${managedTask.ref}`,
@@ -3063,7 +3506,7 @@ function App(props) {
3063
3506
  onSelect: (assignee) => void applyTaskAssignee(assignee)
3064
3507
  }
3065
3508
  ) : null,
3066
- overlay === "focus" ? /* @__PURE__ */ jsx6(
3509
+ overlay === "focus" ? /* @__PURE__ */ jsx5(
3067
3510
  Picker,
3068
3511
  {
3069
3512
  title: "Send into which chat?",
@@ -3075,7 +3518,7 @@ function App(props) {
3075
3518
  }
3076
3519
  }
3077
3520
  ) : null,
3078
- overlay === null && pendingQuestion ? /* @__PURE__ */ jsx6(
3521
+ overlay === null && pendingQuestion ? /* @__PURE__ */ jsx5(
3079
3522
  QuestionPrompt,
3080
3523
  {
3081
3524
  client,
@@ -3089,7 +3532,7 @@ function App(props) {
3089
3532
  },
3090
3533
  pendingQuestion.id
3091
3534
  ) : null,
3092
- /* @__PURE__ */ jsx6(
3535
+ /* @__PURE__ */ jsx5(
3093
3536
  PromptLine,
3094
3537
  {
3095
3538
  projectName,
@@ -3113,6 +3556,52 @@ function App(props) {
3113
3556
  )
3114
3557
  ] });
3115
3558
  }
3559
+ function ModelDownloadProgressPanel(props) {
3560
+ const { progress, onCancel } = props;
3561
+ useInput4((input, key) => {
3562
+ if (key.escape || key.ctrl && input === "c") onCancel();
3563
+ });
3564
+ const transferred = progress.totalBytes ? `${formatModelBytes(progress.bytesWritten)} / ${formatModelBytes(progress.totalBytes)}` : formatModelBytes(progress.bytesWritten);
3565
+ return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
3566
+ /* @__PURE__ */ jsxs6(Text6, { bold: true, color: "yellow", children: [
3567
+ "Downloading ",
3568
+ progress.choice.model.name
3569
+ ] }),
3570
+ /* @__PURE__ */ jsxs6(Text6, { children: [
3571
+ progress.pct == null ? "Working\u2026" : `${progress.pct}%`,
3572
+ " \xB7 ",
3573
+ transferred
3574
+ ] }),
3575
+ progress.phase ? /* @__PURE__ */ jsx5(Text6, { dimColor: true, children: progress.phase }) : null,
3576
+ /* @__PURE__ */ jsx5(Text6, { dimColor: true, children: "Esc / Ctrl+C cancel" })
3577
+ ] });
3578
+ }
3579
+ function readModelDownloadProgress(choice, event) {
3580
+ if (event.type === "progress") {
3581
+ const bytesWritten = "bytesWrittenAll" in event ? event.bytesWrittenAll : event.bytesWritten;
3582
+ const totalBytes = "totalBytesAll" in event ? event.totalBytesAll : event.totalBytes;
3583
+ return {
3584
+ choice,
3585
+ bytesWritten,
3586
+ totalBytes,
3587
+ pct: totalBytes > 0 ? Math.min(100, Math.floor(bytesWritten / totalBytes * 100)) : null,
3588
+ phase: "downloading and verifying model files"
3589
+ };
3590
+ }
3591
+ if (event.type === "companion") {
3592
+ return {
3593
+ choice,
3594
+ bytesWritten: event.bytesWritten,
3595
+ totalBytes: event.totalBytes,
3596
+ pct: event.totalBytes > 0 ? Math.min(100, Math.floor(event.bytesWritten / event.totalBytes * 100)) : null,
3597
+ phase: `downloading ${event.name}`
3598
+ };
3599
+ }
3600
+ return null;
3601
+ }
3602
+ function formatModelBytes(bytes) {
3603
+ return bytes >= 1e9 ? `${(bytes / 1e9).toFixed(1)} GB` : `${Math.max(0, Math.round(bytes / 1e6))} MB`;
3604
+ }
3116
3605
  function errMsg(err) {
3117
3606
  return err instanceof Error ? err.message : String(err);
3118
3607
  }
@@ -3180,7 +3669,7 @@ function taskAssigneeLabel(task2, gezels, boring) {
3180
3669
  if (task2.assignee.kind === "user") return "you";
3181
3670
  const gezelId = task2.assignee.gezelId;
3182
3671
  const gezel = gezels.find((item) => item.id === gezelId);
3183
- if (!gezel) return gezelId;
3672
+ if (!gezel) return boring ? "gezel" : gezelId;
3184
3673
  return boring ? gezel.roleBasedName ?? gezel.role ?? gezel.id : gezel.name;
3185
3674
  }
3186
3675
  function taskStatusChoices(task2) {
@@ -3206,7 +3695,7 @@ function formatTaskDetails(task2, gezels, boring) {
3206
3695
  ...steps.length > 0 ? ["steps:", ...steps] : []
3207
3696
  ].join("\n");
3208
3697
  }
3209
- var HELP, TASK_STATUS_ORDER;
3698
+ var HELP, READ_ONLY_BOOT_NOTE, TASK_STATUS_ORDER;
3210
3699
  var init_App = __esm({
3211
3700
  "src/tui/App.tsx"() {
3212
3701
  "use strict";
@@ -3225,10 +3714,14 @@ var init_App = __esm({
3225
3714
  init_streams();
3226
3715
  HELP = [
3227
3716
  "/project \u2014 switch project /gezel \u2014 switch gezel /model \u2014 switch engine + model",
3717
+ "/model download \u2014 choose and download a new on-device model",
3718
+ "/allow edits \u2014 allow tool edits /disallow edits \u2014 make tool edits read-only",
3719
+ "/allow codexedits|claudeedits \u2014 allow provider-native project edits",
3720
+ "/disallow codexedits|claudeedits \u2014 put that provider in read-only plan mode",
3228
3721
  "/mode \u2014 choose read-only, reactive, reactive+tasks, or full-play AI activity",
3229
3722
  "/thread \u2014 switch or start a chat thread",
3230
3723
  "/task \u2014 list, inspect, create, edit, assign, or change task status",
3231
- "/start \u2014 choose a craftbook and start it as a task",
3724
+ "/do \u2014 choose a craftbook and start it as a task",
3232
3725
  "/continue \u2014 process due schedules and active tasks in this project",
3233
3726
  "/nightshift start|stop|list \u2014 manage Night Shift",
3234
3727
  "/focus \u2014 send into another active chat /cli \u2014 CLI mode /chat \u2014 chat mode",
@@ -3236,6 +3729,7 @@ var init_App = __esm({
3236
3729
  "/clear \u2014 clear feed /quit \u2014 exit",
3237
3730
  "\u2191/\u2193 \u2014 input history Esc \u2014 interrupt turn Ctrl+C \u2014 interrupt, then again to exit"
3238
3731
  ];
3732
+ 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
3733
  TASK_STATUS_ORDER = {
3240
3734
  active: 0,
3241
3735
  draft: 1,
@@ -3247,9 +3741,10 @@ var init_App = __esm({
3247
3741
  });
3248
3742
 
3249
3743
  // src/tui/components/BootstrapGate.tsx
3744
+ import { formatModelAttribution as formatModelAttribution3 } from "@bendyline/gezel";
3250
3745
  import { Box as Box7, Text as Text7, useApp as useApp2, useInput as useInput5 } from "ink";
3251
3746
  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";
3747
+ import { Fragment as Fragment4, jsx as jsx6, jsxs as jsxs7 } from "react/jsx-runtime";
3253
3748
  function BootstrapGate(props) {
3254
3749
  const { client, children } = props;
3255
3750
  const { exit } = useApp2();
@@ -3271,7 +3766,8 @@ function BootstrapGate(props) {
3271
3766
  async (context) => {
3272
3767
  setScreen({ kind: "loading", message: "Finding the best models for this device\u2026" });
3273
3768
  const installedChat = context.provider === "mlx" ? await client.listMlxModels() : await client.listLlamaCppModels();
3274
- if (installedChat.models.length > 0) {
3769
+ const pinnedModel = context.config.defaultModel?.[context.provider];
3770
+ if (pinnedModel && installedChat.models.some((model2) => model2.id === pinnedModel)) {
3275
3771
  setScreen({ kind: "ready" });
3276
3772
  return;
3277
3773
  }
@@ -3296,8 +3792,20 @@ function BootstrapGate(props) {
3296
3792
  client.listInstalledTtsModels().catch(() => ({ models: [] })),
3297
3793
  client.listInstalledRecognitionModels().catch(() => ({ models: [] }))
3298
3794
  ]);
3299
- const chatModels = rankChatModels(context.chatCatalog, context.device, context.provider);
3300
- if (chatModels.length === 0) {
3795
+ const installedIds = new Set(installedChat.models.map((model2) => model2.id));
3796
+ const rankedChatModels = rankChatModels(
3797
+ context.chatCatalog,
3798
+ context.device,
3799
+ context.provider
3800
+ );
3801
+ const recommendedChatModel = rankedChatModels[0];
3802
+ const chatModels = rankedChatModels.filter((model2) => !installedIds.has(model2.id));
3803
+ const catalogAttributions = new Map(
3804
+ context.chatCatalog.flatMap(
3805
+ (item) => item.manifest.kind === "chat-model" ? [[item.manifest.id, formatModelAttribution3(item.manifest)]] : []
3806
+ )
3807
+ );
3808
+ if (chatModels.length === 0 && installedChat.models.length === 0) {
3301
3809
  setScreen({
3302
3810
  kind: "error",
3303
3811
  title: "No compatible local models found",
@@ -3321,7 +3829,19 @@ function BootstrapGate(props) {
3321
3829
  },
3322
3830
  context.device
3323
3831
  );
3324
- setScreen({ kind: "model-choice", plan: { context, chatModels, accessories } });
3832
+ setScreen({
3833
+ kind: "model-choice",
3834
+ plan: {
3835
+ context,
3836
+ installedChatModels: installedChat.models.map((model2) => {
3837
+ const attribution = catalogAttributions.get(model2.id);
3838
+ return { ...model2, ...attribution ? { attribution } : {} };
3839
+ }),
3840
+ ...recommendedChatModel ? { recommendedChatModel } : {},
3841
+ chatModels,
3842
+ accessories
3843
+ }
3844
+ });
3325
3845
  },
3326
3846
  [client]
3327
3847
  );
@@ -3349,14 +3869,7 @@ function BootstrapGate(props) {
3349
3869
  const context = {
3350
3870
  config,
3351
3871
  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
- },
3872
+ device: recoDevice(memory),
3360
3873
  chatCatalog: chatCatalog.items,
3361
3874
  nativeStatus
3362
3875
  };
@@ -3391,12 +3904,19 @@ function BootstrapGate(props) {
3391
3904
  }
3392
3905
  try {
3393
3906
  await installNativeToolkit2(client, context.nativeStatus, missing, setScreen);
3394
- const nativeStatus = await client.getNativeEngineStatus();
3395
- await prepareModels({ ...context, nativeStatus });
3907
+ const [nativeStatus, memory] = await Promise.all([
3908
+ client.getNativeEngineStatus(),
3909
+ client.getMemoryProfile()
3910
+ ]);
3911
+ await prepareModels({
3912
+ ...context,
3913
+ nativeStatus,
3914
+ device: recoDevice(memory)
3915
+ });
3396
3916
  } catch (error) {
3397
3917
  setScreen({
3398
3918
  kind: "error",
3399
- title: "Native toolkit install failed",
3919
+ title: "Gezel native toolkit install failed",
3400
3920
  message: errorMessage2(error),
3401
3921
  retry
3402
3922
  });
@@ -3412,24 +3932,40 @@ function BootstrapGate(props) {
3412
3932
  }
3413
3933
  const retry = () => void installModels(plan, choice);
3414
3934
  try {
3935
+ if (choice.kind === "installed") {
3936
+ const updated2 = await client.updateConfig({
3937
+ provider: plan.context.provider,
3938
+ defaultModel: {
3939
+ ...plan.context.config.defaultModel,
3940
+ [plan.context.provider]: choice.modelId
3941
+ },
3942
+ firstRunInstallError: null
3943
+ });
3944
+ plan.context.config = updated2;
3945
+ setScreen({ kind: "ready" });
3946
+ return;
3947
+ }
3415
3948
  if (choice.kind === "bundle") {
3416
3949
  const missing = missingToolkit(await client.getNativeEngineStatus());
3417
3950
  if (missing.length > 0) {
3418
3951
  await installNativeToolkit2(client, plan.context.nativeStatus, missing, setScreen);
3419
3952
  }
3420
3953
  }
3954
+ const chatAlreadyInstalled = choice.kind === "bundle" && plan.installedChatModels.some((model2) => model2.id === choice.model.id);
3421
3955
  const jobs = [
3422
- { label: choice.model.name, sizeBytes: choice.model.approxSizeBytes },
3956
+ ...!chatAlreadyInstalled ? [{ label: choice.model.name, sizeBytes: choice.model.approxSizeBytes }] : [],
3423
3957
  ...choice.kind === "bundle" ? plan.accessories.map((model2) => ({
3424
3958
  label: model2.name,
3425
3959
  sizeBytes: model2.approxSizeBytes
3426
3960
  })) : []
3427
3961
  ];
3428
3962
  let jobIndex = 0;
3429
- await installChatModel(client, choice.model, (event) => {
3430
- updateDownloadProgress(setScreen, jobs[jobIndex], jobIndex, jobs.length, event);
3431
- });
3432
- jobIndex += 1;
3963
+ if (!chatAlreadyInstalled) {
3964
+ await installChatModel(client, choice.model, (event) => {
3965
+ updateDownloadProgress(setScreen, jobs[jobIndex], jobIndex, jobs.length, event);
3966
+ });
3967
+ jobIndex += 1;
3968
+ }
3433
3969
  const updated = await client.updateConfig({
3434
3970
  provider: choice.model.provider,
3435
3971
  defaultModel: {
@@ -3460,9 +3996,9 @@ function BootstrapGate(props) {
3460
3996
  },
3461
3997
  [client]
3462
3998
  );
3463
- if (screen.kind === "ready") return /* @__PURE__ */ jsx7(Fragment4, { children });
3999
+ if (screen.kind === "ready") return /* @__PURE__ */ jsx6(Fragment4, { children });
3464
4000
  if (screen.kind === "loading") {
3465
- return /* @__PURE__ */ jsx7(BootstrapFrame, { title: "Preparing the workshop", children: /* @__PURE__ */ jsxs7(Text7, { color: "yellow", children: [
4001
+ return /* @__PURE__ */ jsx6(BootstrapFrame, { title: "Preparing the workshop", children: /* @__PURE__ */ jsxs7(Text7, { color: "yellow", children: [
3466
4002
  "\u25CF ",
3467
4003
  screen.message
3468
4004
  ] }) });
@@ -3476,28 +4012,29 @@ function BootstrapGate(props) {
3476
4012
  " ",
3477
4013
  screen.progress.detail
3478
4014
  ] }),
3479
- /* @__PURE__ */ jsx7(ProgressBar, { pct: screen.progress.pct }),
3480
- /* @__PURE__ */ jsx7(Text7, { dimColor: true, children: screen.progress.pct == null ? "Working\u2026" : `${screen.progress.pct}%` })
4015
+ /* @__PURE__ */ jsx6(ProgressBar, { pct: screen.progress.pct }),
4016
+ /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: screen.progress.pct == null ? "Working\u2026" : `${screen.progress.pct}%` })
3481
4017
  ] });
3482
4018
  }
3483
4019
  if (screen.kind === "native-choice") {
3484
4020
  const labels = screen.missing.map(nativeLabel).join(", ");
3485
- return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "Local tools are not installed yet", children: [
4021
+ return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "The Gezel native toolkit -- needed to run AI models locally -- is not installed yet", children: [
4022
+ /* @__PURE__ */ jsx6(Text7, { children: `Gezel can install the verified Gezel native toolkit (native-v${screen.context.nativeStatus.release}) for this device.` }),
3486
4023
  /* @__PURE__ */ jsxs7(Text7, { children: [
3487
- "Gezel can install the verified native-v",
3488
- screen.context.nativeStatus.release,
3489
- " toolkit for this device."
4024
+ "Downloaded from",
4025
+ " ",
4026
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "cyan", children: "https://github.com/bendyline/gezel/releases/" })
3490
4027
  ] }),
3491
4028
  /* @__PURE__ */ jsxs7(Text7, { dimColor: true, children: [
3492
4029
  "Missing: ",
3493
4030
  labels
3494
4031
  ] }),
3495
- /* @__PURE__ */ jsx7(
4032
+ /* @__PURE__ */ jsx6(
3496
4033
  BootstrapChoiceList,
3497
4034
  {
3498
4035
  options: [
3499
4036
  {
3500
- label: "Install the native toolkit",
4037
+ label: "Install the Gezel native toolkit",
3501
4038
  hint: "recommended \xB7 engines for chat, images, speech, and local model helpers",
3502
4039
  value: "install"
3503
4040
  },
@@ -3515,53 +4052,73 @@ function BootstrapGate(props) {
3515
4052
  ] });
3516
4053
  }
3517
4054
  if (screen.kind === "model-choice") {
3518
- const best = screen.plan.chatModels[0];
4055
+ const best = screen.plan.recommendedChatModel;
4056
+ const bestInstalled = best ? screen.plan.installedChatModels.some((model2) => model2.id === best.id) : false;
3519
4057
  const accessoryBytes = screen.plan.accessories.reduce(
3520
4058
  (sum, model2) => sum + model2.approxSizeBytes,
3521
4059
  0
3522
4060
  );
4061
+ const workshopDownloadBytes = accessoryBytes + (best && !bestInstalled ? best.approxSizeBytes : 0);
3523
4062
  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`,
4063
+ ...best ? [
4064
+ {
4065
+ label: `Recommended workshop set \u2014 ${bootstrapChatModelLabel(best)} + ${screen.plan.accessories.length} helpers`,
4066
+ hint: `${bestInstalled ? "chat model already available \xB7 " : ""}${workshopDownloadBytes > 0 ? formatDownloadSize(workshopDownloadBytes) : "already available"}`,
4067
+ value: "bundle"
4068
+ },
4069
+ {
4070
+ label: `${bestInstalled ? "Use" : "Download"} ${bootstrapChatModelLabel(best)} only`,
4071
+ hint: `recommended for this device \xB7 ${bestInstalled ? "already available" : formatDownloadSize(best.approxSizeBytes)}`,
4072
+ value: bestInstalled ? `installed:${best.id}` : `chat:${best.id}`
4073
+ }
4074
+ ] : [],
4075
+ ...screen.plan.installedChatModels.filter((model2) => model2.id !== best?.id).map((model2) => ({
4076
+ label: `Use ${model2.name ?? model2.id}${model2.attribution ? ` (${model2.attribution})` : ""}`,
4077
+ hint: `already available on this machine${model2.approxSizeBytes ? ` \xB7 ${formatDownloadSize(model2.approxSizeBytes)}` : ""}`,
4078
+ value: `installed:${model2.id}`
4079
+ })),
4080
+ ...screen.plan.chatModels.filter((model2) => model2.id !== best?.id).slice(0, MAX_ALTERNATIVE_MODELS).map((model2) => ({
4081
+ label: `Download ${bootstrapChatModelLabel(model2)} only`,
3536
4082
  hint: `${formatDownloadSize(model2.approxSizeBytes)} \xB7 ${fitLabel(model2.fit)}`,
3537
4083
  value: `chat:${model2.id}`
3538
4084
  })),
3539
4085
  { label: "Not now", hint: "open the TUI without a local model", value: "skip" }
3540
4086
  ];
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 });
4087
+ return /* @__PURE__ */ jsxs7(
4088
+ BootstrapFrame,
4089
+ {
4090
+ title: screen.plan.installedChatModels.length > 0 ? "Choose a local chat model" : "No local chat model is installed",
4091
+ children: [
4092
+ /* @__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." }),
4093
+ /* @__PURE__ */ jsx6(
4094
+ BootstrapChoiceList,
4095
+ {
4096
+ options,
4097
+ onSelect: (value) => {
4098
+ if (value === "skip") {
4099
+ void installModels(screen.plan, { kind: "skip" });
4100
+ } else if (value === "bundle") {
4101
+ if (best) void installModels(screen.plan, { kind: "bundle", model: best });
4102
+ } else if (value.startsWith("installed:")) {
4103
+ void installModels(screen.plan, {
4104
+ kind: "installed",
4105
+ modelId: value.slice("installed:".length)
4106
+ });
4107
+ } else {
4108
+ const id = value.slice("chat:".length);
4109
+ const model2 = screen.plan.chatModels.find((candidate) => candidate.id === id);
4110
+ if (model2) void installModels(screen.plan, { kind: "chat", model: model2 });
4111
+ }
4112
+ }
3556
4113
  }
3557
- }
3558
- }
3559
- )
3560
- ] });
4114
+ )
4115
+ ]
4116
+ }
4117
+ );
3561
4118
  }
3562
4119
  return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: screen.title, children: [
3563
- /* @__PURE__ */ jsx7(Text7, { color: "red", children: screen.message }),
3564
- /* @__PURE__ */ jsx7(
4120
+ /* @__PURE__ */ jsx6(Text7, { color: "red", children: screen.message }),
4121
+ /* @__PURE__ */ jsx6(
3565
4122
  BootstrapChoiceList,
3566
4123
  {
3567
4124
  options: [
@@ -3578,7 +4135,7 @@ function BootstrapGate(props) {
3578
4135
  }
3579
4136
  function BootstrapFrame(props) {
3580
4137
  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" }),
4138
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "cyan", children: "gezel \xB7 first-time setup" }),
3582
4139
  /* @__PURE__ */ jsxs7(
3583
4140
  Box7,
3584
4141
  {
@@ -3588,14 +4145,24 @@ function BootstrapFrame(props) {
3588
4145
  paddingX: 1,
3589
4146
  marginTop: 1,
3590
4147
  children: [
3591
- /* @__PURE__ */ jsx7(Text7, { bold: true, color: "yellow", children: props.title }),
4148
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "yellow", children: props.title }),
3592
4149
  props.children
3593
4150
  ]
3594
4151
  }
3595
4152
  ),
3596
- /* @__PURE__ */ jsx7(Text7, { dimColor: true, children: "Ctrl+C exit" })
4153
+ /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: "Ctrl+C exit" })
3597
4154
  ] });
3598
4155
  }
4156
+ function recoDevice(memory) {
4157
+ return {
4158
+ platform: memory.platform,
4159
+ gpuVramBytes: memory.gpuVramBytes,
4160
+ ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
4161
+ totalRamBytes: memory.totalRamBytes,
4162
+ usableBytes: memory.usableBytes,
4163
+ ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
4164
+ };
4165
+ }
3599
4166
  function BootstrapChoiceList(props) {
3600
4167
  const [index, setIndex] = useState5(0);
3601
4168
  const options = props.options;
@@ -3668,7 +4235,7 @@ async function installNativeToolkit2(client, status, missing, setScreen) {
3668
4235
  index,
3669
4236
  missing.length,
3670
4237
  event,
3671
- `Installing native-v${status.release}`
4238
+ `Installing the Gezel native toolkit (native-v${status.release})`
3672
4239
  );
3673
4240
  },
3674
4241
  engine === "llama-server" ? status.llamaBackend : void 0
@@ -3785,10 +4352,10 @@ __export(tui_exports, {
3785
4352
  launchTui: () => launchTui
3786
4353
  });
3787
4354
  import { render } from "ink";
3788
- import { jsx as jsx8 } from "react/jsx-runtime";
4355
+ import { jsx as jsx7 } from "react/jsx-runtime";
3789
4356
  async function launchTui(opts) {
3790
4357
  const instance = render(
3791
- /* @__PURE__ */ jsx8(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx8(
4358
+ /* @__PURE__ */ jsx7(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx7(
3792
4359
  App,
3793
4360
  {
3794
4361
  client: opts.client,
@@ -4452,11 +5019,11 @@ import {
4452
5019
  import {
4453
5020
  GezelClient as GezelClient2,
4454
5021
  createTrustingFetch as createTrustingFetch2,
4455
- discoverOrSpawn,
5022
+ discoverOrSpawn as discoverOrSpawn2,
4456
5023
  isProcessAlive as isProcessAlive2,
4457
5024
  readRuntime as readRuntime2,
4458
5025
  resolveDaemonEntry as resolveDaemonEntry2,
4459
- stopOwnedDaemon,
5026
+ stopOwnedDaemon as stopOwnedDaemon2,
4460
5027
  stopProcessByPid
4461
5028
  } from "@bendyline/gezel-client/node";
4462
5029
  import { Command } from "commander";
@@ -4623,6 +5190,29 @@ function errorMessage(error) {
4623
5190
  return error instanceof Error ? error.message : String(error);
4624
5191
  }
4625
5192
 
5193
+ // src/signal-cleanup.ts
5194
+ function installSignalCleanup(cleanup, options = {}) {
5195
+ if (!cleanup) return () => {
5196
+ };
5197
+ const host = options.host ?? process;
5198
+ let cleanupPromise;
5199
+ const onSignal = (signal) => {
5200
+ host.exitCode = signal === "SIGINT" ? 130 : 143;
5201
+ cleanupPromise ??= cleanup().catch((error) => {
5202
+ options.onError?.(error);
5203
+ host.exitCode = 1;
5204
+ });
5205
+ };
5206
+ const onSigint = () => onSignal("SIGINT");
5207
+ const onSigterm = () => onSignal("SIGTERM");
5208
+ host.on("SIGINT", onSigint);
5209
+ host.on("SIGTERM", onSigterm);
5210
+ return () => {
5211
+ host.off("SIGINT", onSigint);
5212
+ host.off("SIGTERM", onSigterm);
5213
+ };
5214
+ }
5215
+
4626
5216
  // src/bin/gezel.ts
4627
5217
  var program = new Command();
4628
5218
  program.name("gezel").description("Gezel \u2014 build a community of agents that do things.").version(GEZEL_VERSION2).option(
@@ -4644,17 +5234,22 @@ program.hook("preAction", () => {
4644
5234
  program.action(async () => {
4645
5235
  const globals = cliGlobals();
4646
5236
  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";
5237
+ const connection = await connectForTui(globals);
4651
5238
  try {
4652
- const { projects } = await client.listProjects();
4653
- projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
4654
- } catch {
5239
+ const { client } = connection;
5240
+ const projectId = await resolveTuiProject(client, globals);
5241
+ const gezelId = await ensureCliProjectLead(client, projectId);
5242
+ let projectName = basename3(process.cwd()) || "workspace";
5243
+ try {
5244
+ const { projects } = await client.listProjects();
5245
+ projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
5246
+ } catch {
5247
+ }
5248
+ const { launchTui: launchTui2 } = await Promise.resolve().then(() => (init_tui(), tui_exports));
5249
+ await launchTui2({ client, projectId, projectName, gezelId });
5250
+ } finally {
5251
+ await connection.stop?.();
4655
5252
  }
4656
- const { launchTui: launchTui2 } = await Promise.resolve().then(() => (init_tui(), tui_exports));
4657
- await launchTui2({ client, projectId, projectName, gezelId });
4658
5253
  });
4659
5254
  program.command("start").description("Start the Gezel daemon (no-op if already running)").option(
4660
5255
  "--port <port>",
@@ -4692,7 +5287,7 @@ program.command("start").description("Start the Gezel daemon (no-op if already r
4692
5287
  }
4693
5288
  if (port !== void 0 || opts.web) {
4694
5289
  const entry = resolveDaemonEntry2(import.meta.url);
4695
- const result = await discoverOrSpawn({
5290
+ const result = await discoverOrSpawn2({
4696
5291
  daemonEntry: entry,
4697
5292
  detached: true,
4698
5293
  env: spawnEnv,
@@ -4766,7 +5361,7 @@ async function startForeground(env2) {
4766
5361
  });
4767
5362
  let stopping;
4768
5363
  const requestStop = () => {
4769
- stopping ??= stopOwnedDaemon(child);
5364
+ stopping ??= stopOwnedDaemon2(child);
4770
5365
  void stopping;
4771
5366
  };
4772
5367
  process.on("SIGINT", requestStop);
@@ -4841,10 +5436,33 @@ program.command("status").description("Show daemon status").action(async () => {
4841
5436
  console.error(`health failed: ${err.message}`);
4842
5437
  }
4843
5438
  });
4844
- program.command("stop").description("Stop the user-owned Gezel daemon").action(async () => {
5439
+ 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
5440
  const globals = cliGlobals();
5441
+ if (opts.daemon) {
5442
+ await stopUserDaemon(globals);
5443
+ return;
5444
+ }
5445
+ if (!globals.connect && !await findHealthySystemService(globals)) {
5446
+ const runtime = await readRuntime2();
5447
+ if (!runtime || !isProcessAlive2(runtime.pid)) {
5448
+ console.log("Gezel has no running AI work to stop.");
5449
+ return;
5450
+ }
5451
+ }
5452
+ const client = await connectOwned(globals);
5453
+ const result = await client.emergencyStopChats();
5454
+ const details = [
5455
+ `${result.cancelledTurns} active ${result.cancelledTurns === 1 ? "chat" : "chats"}`,
5456
+ `${result.clearedQueuedMessages} queued ${result.clearedQueuedMessages === 1 ? "message" : "messages"}`,
5457
+ `${result.clearedDeferredActions} deferred ${result.clearedDeferredActions === 1 ? "action" : "actions"}`
5458
+ ];
5459
+ console.log(
5460
+ `Hard stop complete: ${details.join(", ")}. Local engines unloaded; Gezel is Reactive.`
5461
+ );
5462
+ });
5463
+ async function stopUserDaemon(globals) {
4846
5464
  if (globals.connect) {
4847
- throw new CliError("gezel stop cannot stop an explicit remote service.");
5465
+ throw new CliError("gezel stop --daemon cannot stop an explicit remote service.");
4848
5466
  }
4849
5467
  const system = await findHealthySystemService(globals);
4850
5468
  if (system) {
@@ -4865,7 +5483,7 @@ program.command("stop").description("Stop the user-owned Gezel daemon").action(a
4865
5483
  console.error(`failed to confirm gezeld pid=${runtime.pid} stopped`);
4866
5484
  process.exitCode = 1;
4867
5485
  }
4868
- });
5486
+ }
4869
5487
  program.command("mode [mode]").description("Show or set AI activity (read-only, reactive, reactive+tasks, or full-play)").action(async (requested) => {
4870
5488
  const next = requested ? parseCliEngagementMode(requested) : null;
4871
5489
  if (requested && !next) {
@@ -4892,6 +5510,11 @@ program.command("run [prompt...]").description("Run a prompt through a gezel and
4892
5510
  return;
4893
5511
  }
4894
5512
  const conn = await connectForRun(cliGlobals());
5513
+ const removeSignalCleanup = installSignalCleanup(conn.stop, {
5514
+ onError: (error) => {
5515
+ console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
5516
+ }
5517
+ });
4895
5518
  try {
4896
5519
  const { client } = conn;
4897
5520
  const projectId = await resolveRunProject(client, cliGlobals());
@@ -4922,6 +5545,7 @@ ${ev.error}`);
4922
5545
  if (printed) process.stdout.write("\n");
4923
5546
  if (errored) process.exitCode = 1;
4924
5547
  } finally {
5548
+ removeSignalCleanup();
4925
5549
  if (conn.stop) await conn.stop();
4926
5550
  }
4927
5551
  });