@bendyline/gezel-cli 1.0.1 → 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");
@@ -711,14 +764,35 @@ var init_bootstrap = __esm({
711
764
  });
712
765
 
713
766
  // src/tui/active-access.ts
714
- import {
715
- resolveGezelWorkspaceAccess
716
- } from "@bendyline/gezel";
767
+ import * as GezelCore from "@bendyline/gezel";
717
768
  function activeAccessMode(opts) {
718
- const access = resolveGezelWorkspaceAccess(opts);
719
- if (access.nativeAccess === "reviewed") return "reviewed edits";
720
- if (access.nativeAccess === "full") return "full access";
721
- return access.effectiveWritable ? "editable" : "read-only";
769
+ const resolveAccess = Reflect.get(GezelCore, "resolveGezelWorkspaceAccess");
770
+ if (resolveAccess) {
771
+ const access = resolveAccess(opts);
772
+ if (access.nativeAccess === "reviewed") return "reviewed edits";
773
+ if (access.nativeAccess === "full") return "full access";
774
+ return access.effectiveWritable ? "editable" : "read-only";
775
+ }
776
+ const { provider, project, gezel, config } = opts;
777
+ if (provider === "codex-cli") {
778
+ const mode = GezelCore.normalizeCodexPermissionMode(
779
+ project?.codexPermissionMode ?? gezel?.codexPermissionMode ?? gezel?.claudePermissionMode ?? config?.codexCli?.defaultPermissionMode
780
+ );
781
+ if (mode === "plan") return "read-only";
782
+ if (mode === "reviewed") return "reviewed edits";
783
+ if (mode === "full") return "full access";
784
+ return "editable";
785
+ }
786
+ if (provider === "anthropic-cli") {
787
+ const mode = project?.claudePermissionMode ?? gezel?.claudePermissionMode ?? config?.anthropicCli?.defaultPermissionMode ?? "acceptEdits";
788
+ if (mode === "plan") return "read-only";
789
+ if (mode === "bypassPermissions") return "full access";
790
+ return "editable";
791
+ }
792
+ if (provider === "copilot" && !GezelCore.resolveSandboxCopilot(config?.sandboxCopilot, gezel?.sandboxCopilot)) {
793
+ return "editable";
794
+ }
795
+ return GezelCore.projectWorkspaceWritable(project) ? "editable" : "read-only";
722
796
  }
723
797
  var init_active_access = __esm({
724
798
  "src/tui/active-access.ts"() {
@@ -732,7 +806,36 @@ function suggestSlashCommands(input) {
732
806
  const query = input.slice(1).toLowerCase();
733
807
  return SLASH_COMMANDS.filter((command) => command.name.startsWith(query));
734
808
  }
809
+ function parseProjectPermissionName(input) {
810
+ const normalized = input.trim().toLowerCase();
811
+ return PROJECT_PERMISSIONS.find((permission) => permission.name === normalized)?.name;
812
+ }
735
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
+ }
736
839
  const modeMatch = input.match(/^\/mode\s+(.*)$/i);
737
840
  if (modeMatch) {
738
841
  const query = (modeMatch[1] ?? "").trim().toLowerCase();
@@ -757,9 +860,9 @@ function suggestSlashWordwheel(input, craftbooks) {
757
860
  })
758
861
  );
759
862
  }
760
- const startMatch = input.match(/^\/start\s+(.*)$/i);
761
- if (startMatch) {
762
- const query = (startMatch[1] ?? "").trim().toLowerCase();
863
+ const doMatch = input.match(/^\/do\s+(.*)$/i);
864
+ if (doMatch) {
865
+ const query = (doMatch[1] ?? "").trim().toLowerCase();
763
866
  const terms = query.split(/\s+/).filter(Boolean);
764
867
  return craftbooks.filter((book) => {
765
868
  const haystack = `${book.id} ${book.name} ${book.description ?? ""}`.toLowerCase();
@@ -770,10 +873,10 @@ function suggestSlashWordwheel(input, craftbooks) {
770
873
  return leftRank - rightRank || left.name.localeCompare(right.name);
771
874
  }).map((book) => ({
772
875
  key: `craftbook:${book.id}`,
773
- label: `/start ${book.id}`,
876
+ label: `/do ${book.id}`,
774
877
  description: `${book.name} \xB7 ${book.stepCount} ${book.stepCount === 1 ? "step" : "steps"} \xB7 ${book.source}`,
775
- submit: `/start ${book.id}`,
776
- completion: `/start ${book.id}`
878
+ submit: `/do ${book.id}`,
879
+ completion: `/do ${book.id}`
777
880
  }));
778
881
  }
779
882
  return suggestSlashCommands(input).map((command) => ({
@@ -810,7 +913,7 @@ function parseInput(raw, cliMode) {
810
913
  }
811
914
  return cliMode ? { kind: "shell", text } : { kind: "prompt", text };
812
915
  }
813
- 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;
814
917
  var init_commands = __esm({
815
918
  "src/tui/commands.ts"() {
816
919
  "use strict";
@@ -820,11 +923,13 @@ var init_commands = __esm({
820
923
  { name: "help", description: "show the command reference" },
821
924
  { name: "project", description: "switch active project" },
822
925
  { name: "gezel", description: "switch active gezel" },
926
+ { name: "allow", description: "allow a project permission" },
927
+ { name: "disallow", description: "disallow a project permission" },
823
928
  { name: "mode", description: "set AI activity: read-only through full play" },
824
929
  { name: "model", description: "switch engine and model" },
825
930
  { name: "thread", description: "switch the active chat thread" },
826
931
  { name: "task", description: "list and manage project tasks" },
827
- { name: "start", description: "start a task from a craftbook" },
932
+ { name: "do", description: "do a task from a craftbook" },
828
933
  { name: "continue", description: "process due and active project tasks" },
829
934
  { name: "nightshift", description: "start, stop, or list night-shift work" },
830
935
  { name: "focus", description: "send into another active chat" },
@@ -838,6 +943,29 @@ var init_commands = __esm({
838
943
  { name: "stop", description: "stop the current night shift" },
839
944
  { name: "list", description: "show current and upcoming night-shift work" }
840
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("|");
841
969
  }
842
970
  });
843
971
 
@@ -862,6 +990,24 @@ function reduceFeed(rows, env2) {
862
990
  open: false
863
991
  }
864
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}`);
865
1011
  case "delta": {
866
1012
  const idx = findOpenAssistant(rows, sessionId);
867
1013
  const open = idx === -1 ? void 0 : rows[idx];
@@ -929,7 +1075,11 @@ function reduceFeed(rows, env2) {
929
1075
  gezelId: "",
930
1076
  kind: "note",
931
1077
  text: `task \xB7 ${event.summary}`,
932
- open: false
1078
+ open: false,
1079
+ taskEvent: {
1080
+ kind: event.kind,
1081
+ ...event.gezelId ? { gezelId: event.gezelId } : {}
1082
+ }
933
1083
  }
934
1084
  ]);
935
1085
  case "error":
@@ -1111,7 +1261,7 @@ function toolRowText(call) {
1111
1261
  }
1112
1262
  function gezelLabel(gezelId, gezels, boring) {
1113
1263
  const g = gezels.find((x) => x.id === gezelId);
1114
- if (!g) return gezelId;
1264
+ if (!g) return boring ? "gezel" : gezelId;
1115
1265
  if (boring) return g.roleBasedName ?? g.role ?? g.id;
1116
1266
  return g.role ? `${g.name} \xB7 ${g.role}` : g.name;
1117
1267
  }
@@ -1255,7 +1405,7 @@ import { jsx, jsxs } from "react/jsx-runtime";
1255
1405
  function ChatFeed(props) {
1256
1406
  const { rows, gezels, boring, focusedSessionId, visible = 16 } = props;
1257
1407
  const shown = rows.slice(Math.max(0, rows.length - visible));
1258
- 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: [
1259
1409
  /* @__PURE__ */ jsx(Text, { color: "yellow", children: TABLE_LOGO }),
1260
1410
  /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 3, children: [
1261
1411
  /* @__PURE__ */ jsxs(Text, { children: [
@@ -1269,7 +1419,7 @@ function ChatFeed(props) {
1269
1419
  if (row.kind === "shell" && row.sessionId.startsWith("term-")) {
1270
1420
  return /* @__PURE__ */ jsx(Text, { wrap: "wrap", children: clip(row.text) }, row.key);
1271
1421
  }
1272
- 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";
1273
1423
  const isFocused = focusedSessionId && row.sessionId === focusedSessionId;
1274
1424
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
1275
1425
  /* @__PURE__ */ jsx(Text, { dimColor: !isFocused, color: isFocused ? "green" : void 0, children: isFocused ? "\u258E" : " " }),
@@ -1278,11 +1428,33 @@ function ChatFeed(props) {
1278
1428
  who,
1279
1429
  ": "
1280
1430
  ] }),
1281
- /* @__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
+ ) })
1282
1434
  ] })
1283
1435
  ] }, row.key);
1284
1436
  }) });
1285
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
+ }
1286
1458
  function clip(text) {
1287
1459
  const t = text.replace(/\s+$/, "");
1288
1460
  return t.length > MAX_CHARS ? `${t.slice(0, MAX_CHARS)}
@@ -1302,6 +1474,7 @@ var init_ChatFeed = __esm({
1302
1474
  ].join("\n");
1303
1475
  KIND_COLOR = {
1304
1476
  user: "white",
1477
+ pending: "yellow",
1305
1478
  assistant: "cyan",
1306
1479
  tool: "yellow",
1307
1480
  note: "magenta",
@@ -1382,19 +1555,29 @@ var init_Picker = __esm({
1382
1555
 
1383
1556
  // src/tui/components/EnginePill.tsx
1384
1557
  import { Box as Box3, Text as Text3 } from "ink";
1385
- import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1558
+ import { jsxs as jsxs3 } from "react/jsx-runtime";
1386
1559
  function EnginePill(props) {
1387
1560
  const { provider, model: model2, accessMode, busy, label } = props;
1388
- const text = formatEngineStatus(provider, model2, busy, label, accessMode);
1389
- return /* @__PURE__ */ jsx3(Box3, { children: /* @__PURE__ */ jsxs3(Text3, { backgroundColor: busy ? "yellow" : "blackBright", color: busy ? "black" : "white", children: [
1390
- " ",
1391
- text,
1392
- " "
1393
- ] }) });
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
+ ] });
1394
1575
  }
1395
- function formatEngineStatus(provider, model2, busy, label, accessMode) {
1396
- const activity = busy ? `\u25CF ${label ?? "working"}` : "\u25CB idle";
1397
- 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";
1398
1581
  }
1399
1582
  function formatEngineIdentity(provider, model2) {
1400
1583
  const engine = provider === "llama-cpp" ? "llama" : provider ?? "on-device";
@@ -1410,7 +1593,7 @@ var init_EnginePill = __esm({
1410
1593
  import { Box as Box4, Text as Text4, useInput as useInput2 } from "ink";
1411
1594
  import TextInput from "ink-text-input";
1412
1595
  import { useEffect, useState as useState2 } from "react";
1413
- 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";
1414
1597
  function PromptLine(props) {
1415
1598
  const {
1416
1599
  projectName,
@@ -1488,18 +1671,18 @@ function PromptLine(props) {
1488
1671
  const placeholder = pendingPrompt ? pendingPrompt : mode === "cli" ? "shell / @tool \u2026 (/chat to exit)" : "message, or /command, !shell, @tool";
1489
1672
  return /* @__PURE__ */ jsxs4(Box4, { flexDirection: "column", children: [
1490
1673
  /* @__PURE__ */ jsxs4(Box4, { children: [
1491
- /* @__PURE__ */ jsx4(Text4, { color: "blue", children: projectName }),
1492
- /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: " \xB7 " }),
1493
- /* @__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 }),
1494
1677
  threadTitle ? /* @__PURE__ */ jsxs4(Fragment2, { children: [
1495
- /* @__PURE__ */ jsx4(Text4, { dimColor: true, children: " \xB7 " }),
1678
+ /* @__PURE__ */ jsx3(Text4, { dimColor: true, children: " \xB7 " }),
1496
1679
  /* @__PURE__ */ jsxs4(Text4, { color: "cyan", children: [
1497
1680
  "\u21B3 ",
1498
1681
  compactThreadTitle(threadTitle)
1499
1682
  ] })
1500
1683
  ] }) : null,
1501
- /* @__PURE__ */ jsx4(Text4, { children: " " }),
1502
- /* @__PURE__ */ jsx4(
1684
+ /* @__PURE__ */ jsx3(Text4, { children: " " }),
1685
+ /* @__PURE__ */ jsx3(
1503
1686
  EnginePill,
1504
1687
  {
1505
1688
  provider,
@@ -1529,8 +1712,8 @@ function PromptLine(props) {
1529
1712
  ] })
1530
1713
  ] }) : null,
1531
1714
  /* @__PURE__ */ jsxs4(Box4, { children: [
1532
- /* @__PURE__ */ jsx4(Text4, { color: pendingPrompt ? "yellow" : mode === "cli" ? "green" : "cyan", children: prefix }),
1533
- /* @__PURE__ */ jsx4(
1715
+ /* @__PURE__ */ jsx3(Text4, { color: pendingPrompt ? "yellow" : mode === "cli" ? "green" : "cyan", children: prefix }),
1716
+ /* @__PURE__ */ jsx3(
1534
1717
  TextInput,
1535
1718
  {
1536
1719
  value,
@@ -1560,7 +1743,7 @@ var init_PromptLine = __esm({
1560
1743
  import { Box as Box5, Text as Text5, useInput as useInput3 } from "ink";
1561
1744
  import TextInput2 from "ink-text-input";
1562
1745
  import { useState as useState3 } from "react";
1563
- 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";
1564
1747
  function questionOptionCount(question) {
1565
1748
  const choices = question.choices?.length ?? 0;
1566
1749
  const writeIn = question.allowWriteIn ?? true;
@@ -1660,11 +1843,11 @@ function QuestionPrompt(props) {
1660
1843
  askerLabel,
1661
1844
  " asks"
1662
1845
  ] }),
1663
- /* @__PURE__ */ jsx5(Text5, { wrap: "wrap", children: question.prompt }),
1846
+ /* @__PURE__ */ jsx4(Text5, { wrap: "wrap", children: question.prompt }),
1664
1847
  writing ? /* @__PURE__ */ jsxs5(Fragment3, { children: [
1665
1848
  /* @__PURE__ */ jsxs5(Box5, { children: [
1666
- /* @__PURE__ */ jsx5(Text5, { color: "cyan", children: "\u203A " }),
1667
- /* @__PURE__ */ jsx5(
1849
+ /* @__PURE__ */ jsx4(Text5, { color: "cyan", children: "\u203A " }),
1850
+ /* @__PURE__ */ jsx4(
1668
1851
  TextInput2,
1669
1852
  {
1670
1853
  value: writeIn,
@@ -1697,8 +1880,8 @@ function QuestionPrompt(props) {
1697
1880
  options.length > QUESTION_OPTION_WINDOW_SIZE ? ` \xB7 ${activeOptionIndex + 1}/${options.length}` : ""
1698
1881
  ] })
1699
1882
  ] }),
1700
- submitting ? /* @__PURE__ */ jsx5(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
1701
- 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
1702
1885
  ] });
1703
1886
  }
1704
1887
  function toggleSet(current, value) {
@@ -1717,11 +1900,12 @@ var init_QuestionPrompt = __esm({
1717
1900
 
1718
1901
  // src/tui/craftbook-start.ts
1719
1902
  import {
1720
- CRAFTBOOK_ROLE_META
1903
+ CRAFTBOOK_ROLE_META,
1904
+ visibleCatalogItems
1721
1905
  } from "@bendyline/gezel";
1722
- function normalizeCraftbooks(items) {
1906
+ function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
1723
1907
  const byId = /* @__PURE__ */ new Map();
1724
- for (const item of items) {
1908
+ for (const item of visibleCatalogItems(items, showWorkInProgressFeatures)) {
1725
1909
  if (item.manifest.kind !== "craftbook-template") continue;
1726
1910
  const manifest = item.manifest;
1727
1911
  if (byId.has(manifest.id)) continue;
@@ -1806,6 +1990,9 @@ var init_craftbook_start = __esm({
1806
1990
  });
1807
1991
 
1808
1992
  // src/tui/model-picker.ts
1993
+ import {
1994
+ formatModelAttribution as formatModelAttribution2
1995
+ } from "@bendyline/gezel";
1809
1996
  function modelProviderLabel(provider) {
1810
1997
  switch (provider) {
1811
1998
  case "copilot":
@@ -1846,9 +2033,10 @@ function configuredModelProviders(config, opts) {
1846
2033
  return providers.sort((a, b) => PROVIDER_ORDER.indexOf(a) - PROVIDER_ORDER.indexOf(b));
1847
2034
  }
1848
2035
  async function loadModelChoices(client, config, platform = process.platform, arch = process.arch) {
1849
- const [copilot, memory] = await Promise.all([
2036
+ const [copilot, memory, catalog] = await Promise.all([
1850
2037
  client.getCopilotStatus().catch(() => null),
1851
- client.getMemoryProfile().catch(() => null)
2038
+ client.getMemoryProfile().catch(() => null),
2039
+ client.listCatalogItems ? client.listCatalogItems("chat-model").catch(() => null) : Promise.resolve(null)
1852
2040
  ]);
1853
2041
  const providers = configuredModelProviders(config, {
1854
2042
  platform,
@@ -1867,18 +2055,76 @@ async function loadModelChoices(client, config, platform = process.platform, arc
1867
2055
  })
1868
2056
  );
1869
2057
  return inventories.flatMap(
1870
- ({ provider, models }) => models.map((model2) => ({
1871
- provider,
1872
- model: model2,
1873
- value: `${provider}:${model2.id}`,
1874
- label: `${modelProviderLabel(provider)} \xB7 ${model2.name}`
1875
- }))
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
+ })
1876
2068
  );
1877
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
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
+ }
2122
+ }
1878
2123
  var PROVIDER_ORDER;
1879
2124
  var init_model_picker = __esm({
1880
2125
  "src/tui/model-picker.ts"() {
1881
2126
  "use strict";
2127
+ init_bootstrap();
1882
2128
  PROVIDER_ORDER = [
1883
2129
  "mlx",
1884
2130
  "llama-cpp",
@@ -1989,7 +2235,7 @@ var init_streams = __esm({
1989
2235
  // src/tui/App.tsx
1990
2236
  import { Box as Box6, Text as Text6, useApp, useInput as useInput4, useStdout } from "ink";
1991
2237
  import { useCallback, useEffect as useEffect3, useMemo, useRef as useRef2, useState as useState4 } from "react";
1992
- import { jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
2238
+ import { jsx as jsx5, jsxs as jsxs6 } from "react/jsx-runtime";
1993
2239
  function useTerminalSize() {
1994
2240
  const { stdout } = useStdout();
1995
2241
  const [size, setSize] = useState4({ rows: stdout?.rows ?? 24, columns: stdout?.columns ?? 80 });
@@ -2019,6 +2265,11 @@ function App(props) {
2019
2265
  );
2020
2266
  const [startCategoryId, setStartCategoryId] = useState4(null);
2021
2267
  const [modelChoices, setModelChoices] = useState4([]);
2268
+ const [modelDownloadChoices, setModelDownloadChoices] = useState4([]);
2269
+ const [modelDownloadProgress, setModelDownloadProgress] = useState4(
2270
+ null
2271
+ );
2272
+ const [modelDownloadReturn, setModelDownloadReturn] = useState4(null);
2022
2273
  const [modelChoicesLoading, setModelChoicesLoading] = useState4(false);
2023
2274
  const [threadsLoading, setThreadsLoading] = useState4(false);
2024
2275
  const [pendingQuestions, setPendingQuestions] = useState4([]);
@@ -2047,7 +2298,7 @@ function App(props) {
2047
2298
  const wordwheelRows = wordwheelCount > 0 ? Math.min(SLASH_COMMAND_WORDWHEEL_SIZE, wordwheelCount) + 1 : 0;
2048
2299
  const questionRows = pendingQuestion ? Math.min(QUESTION_OPTION_WINDOW_SIZE, Math.max(1, questionOptionCount(pendingQuestion))) + 4 : 0;
2049
2300
  const modelPickerWindowSize = Math.max(4, Math.min(10, termRows - 12));
2050
- 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;
2051
2302
  const visibleRows = Math.max(
2052
2303
  4,
2053
2304
  termRows - 7 - wordwheelRows - questionRows - inventoryPickerRows
@@ -2068,6 +2319,23 @@ function App(props) {
2068
2319
  (text, kind = "note") => setRows((r) => appendNote(r, text, kind)),
2069
2320
  []
2070
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]);
2071
2339
  const taskLoadSequence = useRef2(0);
2072
2340
  const refreshTasks = useCallback(async () => {
2073
2341
  const sequence = ++taskLoadSequence.current;
@@ -2083,13 +2351,13 @@ function App(props) {
2083
2351
  const sequence = ++craftbookLoadSequence.current;
2084
2352
  const result = await client.listProjectCraftbooks(projectId);
2085
2353
  if (sequence !== craftbookLoadSequence.current) return [];
2086
- const next = normalizeCraftbooks(result.items);
2354
+ const next = normalizeCraftbooks(result.items, config?.showWorkInProgressFeatures === true);
2087
2355
  setCraftbooks(next);
2088
2356
  setCraftbookProjectType(result.projectType ?? null);
2089
2357
  setSuggestedCraftbookIds(new Set(result.suggestedIds ?? []));
2090
2358
  setCraftbooksNeedingSetup(new Set(Object.keys(result.missingToolsets)));
2091
2359
  return next;
2092
- }, [client, projectId]);
2360
+ }, [client, config?.showWorkInProgressFeatures, projectId]);
2093
2361
  useProjectEvents(
2094
2362
  client,
2095
2363
  projectId,
@@ -2097,6 +2365,8 @@ function App(props) {
2097
2365
  (env2) => {
2098
2366
  setRows((r) => reduceFeed(r, env2));
2099
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();
2100
2370
  if (env2.event.type === "task_event") void refreshTasks();
2101
2371
  if (env2.event.type === "user_message" && env2.sessionId === ownSessionId) {
2102
2372
  const nextTitle = env2.event.message.content.slice(0, 60).trim() || "Untitled";
@@ -2112,7 +2382,7 @@ function App(props) {
2112
2382
  setPendingQuestions((questions) => updatePendingQuestion(questions, question));
2113
2383
  }
2114
2384
  },
2115
- [ownSessionId, refreshTasks]
2385
+ [ownSessionId, refreshGezels, refreshTasks]
2116
2386
  )
2117
2387
  );
2118
2388
  useTerminalEvents(
@@ -2151,7 +2421,11 @@ function App(props) {
2151
2421
  const ensureSession = useCallback(
2152
2422
  async (gezelId, pid) => {
2153
2423
  try {
2154
- const session = await client.createChatSession({ gezelId, projectId: pid });
2424
+ const session = await client.createChatSession({
2425
+ gezelId,
2426
+ projectId: pid,
2427
+ roleBasedNameOnlyMode: boring
2428
+ });
2155
2429
  setOwnSessionId(session.id);
2156
2430
  setFocusedSessionId(session.id);
2157
2431
  setActiveThreadTitle(displayThreadTitle(session.title));
@@ -2161,7 +2435,7 @@ function App(props) {
2161
2435
  return false;
2162
2436
  }
2163
2437
  },
2164
- [client, note]
2438
+ [client, note, boring]
2165
2439
  );
2166
2440
  const switchProject = useCallback(
2167
2441
  async (id) => {
@@ -2195,6 +2469,56 @@ function App(props) {
2195
2469
  },
2196
2470
  [client, ensureSession, note, projectId, projects]
2197
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
+ );
2198
2522
  const openThreadPicker = useCallback(async () => {
2199
2523
  if (!activeGezelId) return note("no active gezel yet.", "error");
2200
2524
  if (threadsLoading) return;
@@ -2231,7 +2555,11 @@ function App(props) {
2231
2555
  setOverlay(null);
2232
2556
  if (!activeGezelId) return note("no active gezel yet.", "error");
2233
2557
  try {
2234
- const session = await client.createChatSession({ gezelId: activeGezelId, projectId });
2558
+ const session = await client.createChatSession({
2559
+ gezelId: activeGezelId,
2560
+ projectId,
2561
+ roleBasedNameOnlyMode: boring
2562
+ });
2235
2563
  setOwnSessionId(session.id);
2236
2564
  setFocusedSessionId(session.id);
2237
2565
  setActiveThreadTitle(displayThreadTitle(session.title));
@@ -2240,7 +2568,7 @@ function App(props) {
2240
2568
  } catch (err) {
2241
2569
  note(`could not start a thread: ${errMsg(err)}`, "error");
2242
2570
  }
2243
- }, [activeGezelId, client, note, projectId]);
2571
+ }, [activeGezelId, client, note, projectId, boring]);
2244
2572
  useEffect3(() => {
2245
2573
  let cancelled = false;
2246
2574
  (async () => {
@@ -2252,22 +2580,31 @@ function App(props) {
2252
2580
  ]);
2253
2581
  if (cancelled) return;
2254
2582
  setConfig(cfg);
2255
- setGezels(gz.gezels);
2256
- setProjects(
2257
- pj.projects.map((p) => ({
2258
- id: p.id,
2259
- name: p.name,
2260
- workingDir: p.workingDir,
2261
- voormanGezelId: p.voormanGezelId,
2262
- managedWorkspaceWritePolicy: p.managedWorkspaceWritePolicy,
2263
- allowGezelWrites: p.allowGezelWrites,
2264
- codexPermissionMode: p.codexPermissionMode,
2265
- claudePermissionMode: p.claudePermissionMode
2266
- }))
2267
- );
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);
2268
2595
  const gezelId = props.initialGezelId;
2596
+ const initialGezel = gz.gezels.find((gezel) => gezel.id === gezelId);
2597
+ const initialProject = projectRows.find((project) => project.id === projectId);
2269
2598
  setActiveGezelId(gezelId);
2270
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
+ }
2271
2608
  await ensureSession(gezelId, projectId);
2272
2609
  } catch (err) {
2273
2610
  if (!cancelled) setStatus(`Failed to connect: ${errMsg(err)}`);
@@ -2339,7 +2676,8 @@ function App(props) {
2339
2676
  for (const r of rows) {
2340
2677
  if (r.sessionId === "local" || r.sessionId.startsWith("term-")) continue;
2341
2678
  if (!seen.has(r.sessionId)) {
2342
- 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);
2343
2681
  seen.set(r.sessionId, label);
2344
2682
  }
2345
2683
  }
@@ -2350,7 +2688,7 @@ function App(props) {
2350
2688
  items.push({ label, value: sid });
2351
2689
  }
2352
2690
  return items;
2353
- }, [rows, gezels, ownSessionId, gezelLine]);
2691
+ }, [rows, gezels, ownSessionId, gezelLine, boring]);
2354
2692
  const cancelActive = useCallback(async () => {
2355
2693
  const sessions = [...turns.keys()];
2356
2694
  const runs = [...activeRuns];
@@ -2383,6 +2721,37 @@ function App(props) {
2383
2721
  },
2384
2722
  [client, note]
2385
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
+ );
2386
2755
  const startCraftbook = useCallback(
2387
2756
  async (book) => {
2388
2757
  setOverlay(null);
@@ -2499,7 +2868,10 @@ function App(props) {
2499
2868
  const target = focusedSessionId ?? ownSessionId;
2500
2869
  if (!target) return note("no active session yet.", "error");
2501
2870
  try {
2502
- await client.sendToChatSession(target, parsed.text);
2871
+ await client.sendToChatSession(
2872
+ target,
2873
+ turns.has(target) ? { message: parsed.text, nudge: true } : parsed.text
2874
+ );
2503
2875
  } catch (err) {
2504
2876
  note(`send failed: ${errMsg(err)}`, "error");
2505
2877
  }
@@ -2562,7 +2934,8 @@ function App(props) {
2562
2934
  note,
2563
2935
  pendingInput,
2564
2936
  submitTaskPrompt,
2565
- taskPrompt
2937
+ taskPrompt,
2938
+ turns
2566
2939
  ]
2567
2940
  );
2568
2941
  const runCommand = useCallback(
@@ -2576,31 +2949,21 @@ function App(props) {
2576
2949
  return setOverlay("project");
2577
2950
  case "gezel":
2578
2951
  return setOverlay("gezel");
2952
+ case "allow":
2953
+ await applyProjectPermission(rest, true);
2954
+ return;
2955
+ case "disallow":
2956
+ await applyProjectPermission(rest, false);
2957
+ return;
2579
2958
  case "mode":
2580
2959
  if (!rest.trim()) return setOverlay("engagement-mode");
2581
2960
  await applyEngagementMode(rest);
2582
2961
  return;
2583
2962
  case "model": {
2584
- if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2585
- if (activeGezel.fixedFunction) {
2586
- return note("this gezel runs a fixed tool and does not use a chat model.", "error");
2587
- }
2588
- if (modelChoicesLoading) return note("model choices are already loading.");
2589
- setModelChoicesLoading(true);
2590
- note("loading available engines and models\u2026");
2591
- try {
2592
- const choices = await loadModelChoices(client, config ?? await client.getConfig());
2593
- if (choices.length === 0) {
2594
- return note("no engines with available chat models were found.", "error");
2595
- }
2596
- setModelChoices(choices);
2597
- setOverlay("model");
2598
- } catch (err) {
2599
- note(`could not load models: ${errMsg(err)}`, "error");
2600
- } finally {
2601
- setModelChoicesLoading(false);
2602
- }
2603
- 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");
2604
2967
  }
2605
2968
  case "thread":
2606
2969
  await openThreadPicker();
@@ -2651,7 +3014,7 @@ function App(props) {
2651
3014
  }
2652
3015
  return;
2653
3016
  }
2654
- case "start": {
3017
+ case "do": {
2655
3018
  let available = craftbooks;
2656
3019
  if (available.length === 0) {
2657
3020
  try {
@@ -2669,7 +3032,7 @@ function App(props) {
2669
3032
  }
2670
3033
  const book = findCraftbook(available, rest);
2671
3034
  if (!book) {
2672
- return note(`craftbook not found: ${rest.trim()} (try /start)`, "error");
3035
+ return note(`craftbook not found: ${rest.trim()} (try /do)`, "error");
2673
3036
  }
2674
3037
  await startCraftbook(book);
2675
3038
  return;
@@ -2727,15 +3090,14 @@ function App(props) {
2727
3090
  }
2728
3091
  },
2729
3092
  [
2730
- activeGezel,
2731
- activeGezelId,
2732
3093
  applyEngagementMode,
3094
+ applyProjectPermission,
2733
3095
  client,
2734
- config,
2735
3096
  craftbooks,
2736
- modelChoicesLoading,
2737
3097
  note,
2738
3098
  exit,
3099
+ openModelDownloadPicker,
3100
+ openModelPicker,
2739
3101
  openThreadPicker,
2740
3102
  projectId,
2741
3103
  projectName,
@@ -2744,11 +3106,10 @@ function App(props) {
2744
3106
  startCraftbook
2745
3107
  ]
2746
3108
  );
2747
- const applyModelChoice = useCallback(
2748
- async (value2) => {
3109
+ const applyModelSelection = useCallback(
3110
+ async (choice) => {
2749
3111
  setOverlay(null);
2750
3112
  if (!activeGezelId || !activeGezel || !config) return;
2751
- const choice = modelChoices.find((item) => item.value === value2);
2752
3113
  const nextProvider = choice?.provider ?? null;
2753
3114
  const nextModel = choice?.model.id;
2754
3115
  const providerChanged = (activeGezel.provider ?? null) !== nextProvider;
@@ -2773,8 +3134,80 @@ function App(props) {
2773
3134
  note(`could not switch model: ${errMsg(err)}`, "error");
2774
3135
  }
2775
3136
  },
2776
- [activeGezel, activeGezelId, client, config, ensureSession, modelChoices, note, projectId]
3137
+ [activeGezel, activeGezelId, client, config, ensureSession, note, projectId]
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]
2777
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]);
2778
3211
  const onSubmit = useCallback(
2779
3212
  (raw) => {
2780
3213
  setValue("");
@@ -2820,10 +3253,10 @@ function App(props) {
2820
3253
  }
2821
3254
  );
2822
3255
  if (status) {
2823
- 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 }) });
2824
3257
  }
2825
3258
  return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", padding: 1, children: [
2826
- /* @__PURE__ */ jsx6(
3259
+ /* @__PURE__ */ jsx5(
2827
3260
  ChatFeed,
2828
3261
  {
2829
3262
  rows,
@@ -2833,7 +3266,7 @@ function App(props) {
2833
3266
  visible: visibleRows
2834
3267
  }
2835
3268
  ),
2836
- overlay === "project" ? /* @__PURE__ */ jsx6(
3269
+ overlay === "project" ? /* @__PURE__ */ jsx5(
2837
3270
  Picker,
2838
3271
  {
2839
3272
  title: "Switch project",
@@ -2842,7 +3275,7 @@ function App(props) {
2842
3275
  onSelect: (id) => void switchProject(id)
2843
3276
  }
2844
3277
  ) : null,
2845
- overlay === "gezel" ? /* @__PURE__ */ jsx6(
3278
+ overlay === "gezel" ? /* @__PURE__ */ jsx5(
2846
3279
  Picker,
2847
3280
  {
2848
3281
  title: "Switch gezel",
@@ -2862,7 +3295,7 @@ function App(props) {
2862
3295
  }
2863
3296
  }
2864
3297
  ) : null,
2865
- overlay === "engagement-mode" ? /* @__PURE__ */ jsx6(
3298
+ overlay === "engagement-mode" ? /* @__PURE__ */ jsx5(
2866
3299
  Picker,
2867
3300
  {
2868
3301
  title: "Choose AI engagement mode",
@@ -2876,16 +3309,21 @@ function App(props) {
2876
3309
  onSelect: (selected) => void applyEngagementMode(selected)
2877
3310
  }
2878
3311
  ) : null,
2879
- overlay === "model" ? /* @__PURE__ */ jsx6(
3312
+ overlay === "model" ? /* @__PURE__ */ jsx5(
2880
3313
  Picker,
2881
3314
  {
2882
- title: "Choose engine + model",
3315
+ title: "Choose engine + model - models are downloaded from Hugging Face (huggingface.co)",
2883
3316
  items: [
2884
3317
  {
2885
3318
  label: "Use default",
2886
3319
  value: "__default__",
2887
3320
  hint: `${modelProviderLabel(config?.provider ?? "llama-cpp")}${config?.defaultModel?.[config.provider] ? ` \xB7 ${config.defaultModel[config.provider]}` : ""}`
2888
3321
  },
3322
+ {
3323
+ label: "Download a new model\u2026",
3324
+ value: "__download__",
3325
+ hint: "browse on-device models ranked for this machine"
3326
+ },
2889
3327
  ...modelChoices.map((choice) => ({
2890
3328
  label: choice.label,
2891
3329
  value: choice.value,
@@ -2895,10 +3333,36 @@ function App(props) {
2895
3333
  initialValue: activeGezel?.provider && activeGezel.model ? `${activeGezel.provider}:${activeGezel.model}` : "__default__",
2896
3334
  windowSize: modelPickerWindowSize,
2897
3335
  onCancel: () => setOverlay(null),
2898
- onSelect: (value2) => void applyModelChoice(value2)
3336
+ onSelect: (value2) => {
3337
+ if (value2 === "__download__") void openModelDownloadPicker("model");
3338
+ else void applyModelChoice(value2);
3339
+ }
2899
3340
  }
2900
3341
  ) : null,
2901
- 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(
2902
3366
  Picker,
2903
3367
  {
2904
3368
  title: "Choose a craftbook category",
@@ -2915,7 +3379,7 @@ function App(props) {
2915
3379
  }
2916
3380
  }
2917
3381
  ) : null,
2918
- overlay === "start-craftbook" ? /* @__PURE__ */ jsx6(
3382
+ overlay === "start-craftbook" ? /* @__PURE__ */ jsx5(
2919
3383
  Picker,
2920
3384
  {
2921
3385
  title: startCategory?.label ?? "Start a craftbook",
@@ -2932,7 +3396,7 @@ function App(props) {
2932
3396
  }
2933
3397
  }
2934
3398
  ) : null,
2935
- overlay === "thread" ? /* @__PURE__ */ jsx6(
3399
+ overlay === "thread" ? /* @__PURE__ */ jsx5(
2936
3400
  Picker,
2937
3401
  {
2938
3402
  title: `Threads with ${gezelLine}`,
@@ -2953,7 +3417,7 @@ function App(props) {
2953
3417
  }
2954
3418
  }
2955
3419
  ) : null,
2956
- overlay === "task" ? /* @__PURE__ */ jsx6(
3420
+ overlay === "task" ? /* @__PURE__ */ jsx5(
2957
3421
  Picker,
2958
3422
  {
2959
3423
  title: `Tasks \xB7 ${tasks.filter((task2) => task2.status === "active").length} active`,
@@ -2978,7 +3442,7 @@ function App(props) {
2978
3442
  }
2979
3443
  }
2980
3444
  ) : null,
2981
- overlay === "task-actions" && managedTask ? /* @__PURE__ */ jsx6(
3445
+ overlay === "task-actions" && managedTask ? /* @__PURE__ */ jsx5(
2982
3446
  Picker,
2983
3447
  {
2984
3448
  title: `${managedTask.ref} \xB7 ${managedTask.status}`,
@@ -3013,7 +3477,7 @@ function App(props) {
3013
3477
  }
3014
3478
  }
3015
3479
  ) : null,
3016
- overlay === "task-status" && managedTask ? /* @__PURE__ */ jsx6(
3480
+ overlay === "task-status" && managedTask ? /* @__PURE__ */ jsx5(
3017
3481
  Picker,
3018
3482
  {
3019
3483
  title: `Set ${managedTask.ref} status`,
@@ -3022,7 +3486,7 @@ function App(props) {
3022
3486
  onSelect: (status2) => void applyTaskStatus(status2)
3023
3487
  }
3024
3488
  ) : null,
3025
- overlay === "task-assignee" && managedTask ? /* @__PURE__ */ jsx6(
3489
+ overlay === "task-assignee" && managedTask ? /* @__PURE__ */ jsx5(
3026
3490
  Picker,
3027
3491
  {
3028
3492
  title: `Assign ${managedTask.ref}`,
@@ -3042,7 +3506,7 @@ function App(props) {
3042
3506
  onSelect: (assignee) => void applyTaskAssignee(assignee)
3043
3507
  }
3044
3508
  ) : null,
3045
- overlay === "focus" ? /* @__PURE__ */ jsx6(
3509
+ overlay === "focus" ? /* @__PURE__ */ jsx5(
3046
3510
  Picker,
3047
3511
  {
3048
3512
  title: "Send into which chat?",
@@ -3054,7 +3518,7 @@ function App(props) {
3054
3518
  }
3055
3519
  }
3056
3520
  ) : null,
3057
- overlay === null && pendingQuestion ? /* @__PURE__ */ jsx6(
3521
+ overlay === null && pendingQuestion ? /* @__PURE__ */ jsx5(
3058
3522
  QuestionPrompt,
3059
3523
  {
3060
3524
  client,
@@ -3068,7 +3532,7 @@ function App(props) {
3068
3532
  },
3069
3533
  pendingQuestion.id
3070
3534
  ) : null,
3071
- /* @__PURE__ */ jsx6(
3535
+ /* @__PURE__ */ jsx5(
3072
3536
  PromptLine,
3073
3537
  {
3074
3538
  projectName,
@@ -3092,6 +3556,52 @@ function App(props) {
3092
3556
  )
3093
3557
  ] });
3094
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
+ }
3095
3605
  function errMsg(err) {
3096
3606
  return err instanceof Error ? err.message : String(err);
3097
3607
  }
@@ -3159,7 +3669,7 @@ function taskAssigneeLabel(task2, gezels, boring) {
3159
3669
  if (task2.assignee.kind === "user") return "you";
3160
3670
  const gezelId = task2.assignee.gezelId;
3161
3671
  const gezel = gezels.find((item) => item.id === gezelId);
3162
- if (!gezel) return gezelId;
3672
+ if (!gezel) return boring ? "gezel" : gezelId;
3163
3673
  return boring ? gezel.roleBasedName ?? gezel.role ?? gezel.id : gezel.name;
3164
3674
  }
3165
3675
  function taskStatusChoices(task2) {
@@ -3185,7 +3695,7 @@ function formatTaskDetails(task2, gezels, boring) {
3185
3695
  ...steps.length > 0 ? ["steps:", ...steps] : []
3186
3696
  ].join("\n");
3187
3697
  }
3188
- var HELP, TASK_STATUS_ORDER;
3698
+ var HELP, READ_ONLY_BOOT_NOTE, TASK_STATUS_ORDER;
3189
3699
  var init_App = __esm({
3190
3700
  "src/tui/App.tsx"() {
3191
3701
  "use strict";
@@ -3204,10 +3714,14 @@ var init_App = __esm({
3204
3714
  init_streams();
3205
3715
  HELP = [
3206
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",
3207
3721
  "/mode \u2014 choose read-only, reactive, reactive+tasks, or full-play AI activity",
3208
3722
  "/thread \u2014 switch or start a chat thread",
3209
3723
  "/task \u2014 list, inspect, create, edit, assign, or change task status",
3210
- "/start \u2014 choose a craftbook and start it as a task",
3724
+ "/do \u2014 choose a craftbook and start it as a task",
3211
3725
  "/continue \u2014 process due schedules and active tasks in this project",
3212
3726
  "/nightshift start|stop|list \u2014 manage Night Shift",
3213
3727
  "/focus \u2014 send into another active chat /cli \u2014 CLI mode /chat \u2014 chat mode",
@@ -3215,6 +3729,7 @@ var init_App = __esm({
3215
3729
  "/clear \u2014 clear feed /quit \u2014 exit",
3216
3730
  "\u2191/\u2193 \u2014 input history Esc \u2014 interrupt turn Ctrl+C \u2014 interrupt, then again to exit"
3217
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.";
3218
3733
  TASK_STATUS_ORDER = {
3219
3734
  active: 0,
3220
3735
  draft: 1,
@@ -3226,9 +3741,10 @@ var init_App = __esm({
3226
3741
  });
3227
3742
 
3228
3743
  // src/tui/components/BootstrapGate.tsx
3744
+ import { formatModelAttribution as formatModelAttribution3 } from "@bendyline/gezel";
3229
3745
  import { Box as Box7, Text as Text7, useApp as useApp2, useInput as useInput5 } from "ink";
3230
3746
  import { useCallback as useCallback2, useEffect as useEffect4, useState as useState5 } from "react";
3231
- 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";
3232
3748
  function BootstrapGate(props) {
3233
3749
  const { client, children } = props;
3234
3750
  const { exit } = useApp2();
@@ -3250,7 +3766,8 @@ function BootstrapGate(props) {
3250
3766
  async (context) => {
3251
3767
  setScreen({ kind: "loading", message: "Finding the best models for this device\u2026" });
3252
3768
  const installedChat = context.provider === "mlx" ? await client.listMlxModels() : await client.listLlamaCppModels();
3253
- if (installedChat.models.length > 0) {
3769
+ const pinnedModel = context.config.defaultModel?.[context.provider];
3770
+ if (pinnedModel && installedChat.models.some((model2) => model2.id === pinnedModel)) {
3254
3771
  setScreen({ kind: "ready" });
3255
3772
  return;
3256
3773
  }
@@ -3275,8 +3792,20 @@ function BootstrapGate(props) {
3275
3792
  client.listInstalledTtsModels().catch(() => ({ models: [] })),
3276
3793
  client.listInstalledRecognitionModels().catch(() => ({ models: [] }))
3277
3794
  ]);
3278
- const chatModels = rankChatModels(context.chatCatalog, context.device, context.provider);
3279
- 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) {
3280
3809
  setScreen({
3281
3810
  kind: "error",
3282
3811
  title: "No compatible local models found",
@@ -3300,7 +3829,19 @@ function BootstrapGate(props) {
3300
3829
  },
3301
3830
  context.device
3302
3831
  );
3303
- 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
+ });
3304
3845
  },
3305
3846
  [client]
3306
3847
  );
@@ -3328,14 +3869,7 @@ function BootstrapGate(props) {
3328
3869
  const context = {
3329
3870
  config,
3330
3871
  provider: config.provider,
3331
- device: {
3332
- platform: memory.platform,
3333
- gpuVramBytes: memory.gpuVramBytes,
3334
- ...memory.gpuMemoryKind ? { gpuMemoryKind: memory.gpuMemoryKind } : {},
3335
- totalRamBytes: memory.totalRamBytes,
3336
- usableBytes: memory.usableBytes,
3337
- ...memory.budgetBytes !== void 0 ? { budgetBytes: memory.budgetBytes } : {}
3338
- },
3872
+ device: recoDevice(memory),
3339
3873
  chatCatalog: chatCatalog.items,
3340
3874
  nativeStatus
3341
3875
  };
@@ -3370,12 +3904,19 @@ function BootstrapGate(props) {
3370
3904
  }
3371
3905
  try {
3372
3906
  await installNativeToolkit2(client, context.nativeStatus, missing, setScreen);
3373
- const nativeStatus = await client.getNativeEngineStatus();
3374
- 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
+ });
3375
3916
  } catch (error) {
3376
3917
  setScreen({
3377
3918
  kind: "error",
3378
- title: "Native toolkit install failed",
3919
+ title: "Gezel native toolkit install failed",
3379
3920
  message: errorMessage2(error),
3380
3921
  retry
3381
3922
  });
@@ -3391,24 +3932,40 @@ function BootstrapGate(props) {
3391
3932
  }
3392
3933
  const retry = () => void installModels(plan, choice);
3393
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
+ }
3394
3948
  if (choice.kind === "bundle") {
3395
3949
  const missing = missingToolkit(await client.getNativeEngineStatus());
3396
3950
  if (missing.length > 0) {
3397
3951
  await installNativeToolkit2(client, plan.context.nativeStatus, missing, setScreen);
3398
3952
  }
3399
3953
  }
3954
+ const chatAlreadyInstalled = choice.kind === "bundle" && plan.installedChatModels.some((model2) => model2.id === choice.model.id);
3400
3955
  const jobs = [
3401
- { label: choice.model.name, sizeBytes: choice.model.approxSizeBytes },
3956
+ ...!chatAlreadyInstalled ? [{ label: choice.model.name, sizeBytes: choice.model.approxSizeBytes }] : [],
3402
3957
  ...choice.kind === "bundle" ? plan.accessories.map((model2) => ({
3403
3958
  label: model2.name,
3404
3959
  sizeBytes: model2.approxSizeBytes
3405
3960
  })) : []
3406
3961
  ];
3407
3962
  let jobIndex = 0;
3408
- await installChatModel(client, choice.model, (event) => {
3409
- updateDownloadProgress(setScreen, jobs[jobIndex], jobIndex, jobs.length, event);
3410
- });
3411
- 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
+ }
3412
3969
  const updated = await client.updateConfig({
3413
3970
  provider: choice.model.provider,
3414
3971
  defaultModel: {
@@ -3439,9 +3996,9 @@ function BootstrapGate(props) {
3439
3996
  },
3440
3997
  [client]
3441
3998
  );
3442
- if (screen.kind === "ready") return /* @__PURE__ */ jsx7(Fragment4, { children });
3999
+ if (screen.kind === "ready") return /* @__PURE__ */ jsx6(Fragment4, { children });
3443
4000
  if (screen.kind === "loading") {
3444
- 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: [
3445
4002
  "\u25CF ",
3446
4003
  screen.message
3447
4004
  ] }) });
@@ -3455,28 +4012,29 @@ function BootstrapGate(props) {
3455
4012
  " ",
3456
4013
  screen.progress.detail
3457
4014
  ] }),
3458
- /* @__PURE__ */ jsx7(ProgressBar, { pct: screen.progress.pct }),
3459
- /* @__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}%` })
3460
4017
  ] });
3461
4018
  }
3462
4019
  if (screen.kind === "native-choice") {
3463
4020
  const labels = screen.missing.map(nativeLabel).join(", ");
3464
- 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.` }),
3465
4023
  /* @__PURE__ */ jsxs7(Text7, { children: [
3466
- "Gezel can install the verified native-v",
3467
- screen.context.nativeStatus.release,
3468
- " toolkit for this device."
4024
+ "Downloaded from",
4025
+ " ",
4026
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "cyan", children: "https://github.com/bendyline/gezel/releases/" })
3469
4027
  ] }),
3470
4028
  /* @__PURE__ */ jsxs7(Text7, { dimColor: true, children: [
3471
4029
  "Missing: ",
3472
4030
  labels
3473
4031
  ] }),
3474
- /* @__PURE__ */ jsx7(
4032
+ /* @__PURE__ */ jsx6(
3475
4033
  BootstrapChoiceList,
3476
4034
  {
3477
4035
  options: [
3478
4036
  {
3479
- label: "Install the native toolkit",
4037
+ label: "Install the Gezel native toolkit",
3480
4038
  hint: "recommended \xB7 engines for chat, images, speech, and local model helpers",
3481
4039
  value: "install"
3482
4040
  },
@@ -3494,53 +4052,73 @@ function BootstrapGate(props) {
3494
4052
  ] });
3495
4053
  }
3496
4054
  if (screen.kind === "model-choice") {
3497
- 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;
3498
4057
  const accessoryBytes = screen.plan.accessories.reduce(
3499
4058
  (sum, model2) => sum + model2.approxSizeBytes,
3500
4059
  0
3501
4060
  );
4061
+ const workshopDownloadBytes = accessoryBytes + (best && !bestInstalled ? best.approxSizeBytes : 0);
3502
4062
  const options = [
3503
- {
3504
- label: `Recommended workshop set \u2014 ${best.name} + ${screen.plan.accessories.length} helpers`,
3505
- hint: formatDownloadSize(best.approxSizeBytes + accessoryBytes),
3506
- value: "bundle"
3507
- },
3508
- {
3509
- label: `${best.name} only`,
3510
- hint: `best chat model \xB7 ${formatDownloadSize(best.approxSizeBytes)}`,
3511
- value: `chat:${best.id}`
3512
- },
3513
- ...screen.plan.chatModels.slice(1, MAX_ALTERNATIVE_MODELS + 1).map((model2) => ({
3514
- 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`,
3515
4082
  hint: `${formatDownloadSize(model2.approxSizeBytes)} \xB7 ${fitLabel(model2.fit)}`,
3516
4083
  value: `chat:${model2.id}`
3517
4084
  })),
3518
4085
  { label: "Not now", hint: "open the TUI without a local model", value: "skip" }
3519
4086
  ];
3520
- return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: "No local chat model is installed", children: [
3521
- /* @__PURE__ */ jsx7(Text7, { children: "Pick a setup for this device. Downloads stay under your Gezel home folder." }),
3522
- /* @__PURE__ */ jsx7(
3523
- BootstrapChoiceList,
3524
- {
3525
- options,
3526
- onSelect: (value) => {
3527
- if (value === "skip") {
3528
- void installModels(screen.plan, { kind: "skip" });
3529
- } else if (value === "bundle") {
3530
- void installModels(screen.plan, { kind: "bundle", model: best });
3531
- } else {
3532
- const id = value.slice("chat:".length);
3533
- const model2 = screen.plan.chatModels.find((candidate) => candidate.id === id);
3534
- 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
+ }
3535
4113
  }
3536
- }
3537
- }
3538
- )
3539
- ] });
4114
+ )
4115
+ ]
4116
+ }
4117
+ );
3540
4118
  }
3541
4119
  return /* @__PURE__ */ jsxs7(BootstrapFrame, { title: screen.title, children: [
3542
- /* @__PURE__ */ jsx7(Text7, { color: "red", children: screen.message }),
3543
- /* @__PURE__ */ jsx7(
4120
+ /* @__PURE__ */ jsx6(Text7, { color: "red", children: screen.message }),
4121
+ /* @__PURE__ */ jsx6(
3544
4122
  BootstrapChoiceList,
3545
4123
  {
3546
4124
  options: [
@@ -3557,7 +4135,7 @@ function BootstrapGate(props) {
3557
4135
  }
3558
4136
  function BootstrapFrame(props) {
3559
4137
  return /* @__PURE__ */ jsxs7(Box7, { flexDirection: "column", paddingX: 1, paddingY: 1, children: [
3560
- /* @__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" }),
3561
4139
  /* @__PURE__ */ jsxs7(
3562
4140
  Box7,
3563
4141
  {
@@ -3567,14 +4145,24 @@ function BootstrapFrame(props) {
3567
4145
  paddingX: 1,
3568
4146
  marginTop: 1,
3569
4147
  children: [
3570
- /* @__PURE__ */ jsx7(Text7, { bold: true, color: "yellow", children: props.title }),
4148
+ /* @__PURE__ */ jsx6(Text7, { bold: true, color: "yellow", children: props.title }),
3571
4149
  props.children
3572
4150
  ]
3573
4151
  }
3574
4152
  ),
3575
- /* @__PURE__ */ jsx7(Text7, { dimColor: true, children: "Ctrl+C exit" })
4153
+ /* @__PURE__ */ jsx6(Text7, { dimColor: true, children: "Ctrl+C exit" })
3576
4154
  ] });
3577
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
+ }
3578
4166
  function BootstrapChoiceList(props) {
3579
4167
  const [index, setIndex] = useState5(0);
3580
4168
  const options = props.options;
@@ -3647,7 +4235,7 @@ async function installNativeToolkit2(client, status, missing, setScreen) {
3647
4235
  index,
3648
4236
  missing.length,
3649
4237
  event,
3650
- `Installing native-v${status.release}`
4238
+ `Installing the Gezel native toolkit (native-v${status.release})`
3651
4239
  );
3652
4240
  },
3653
4241
  engine === "llama-server" ? status.llamaBackend : void 0
@@ -3764,10 +4352,10 @@ __export(tui_exports, {
3764
4352
  launchTui: () => launchTui
3765
4353
  });
3766
4354
  import { render } from "ink";
3767
- import { jsx as jsx8 } from "react/jsx-runtime";
4355
+ import { jsx as jsx7 } from "react/jsx-runtime";
3768
4356
  async function launchTui(opts) {
3769
4357
  const instance = render(
3770
- /* @__PURE__ */ jsx8(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx8(
4358
+ /* @__PURE__ */ jsx7(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx7(
3771
4359
  App,
3772
4360
  {
3773
4361
  client: opts.client,
@@ -4431,11 +5019,11 @@ import {
4431
5019
  import {
4432
5020
  GezelClient as GezelClient2,
4433
5021
  createTrustingFetch as createTrustingFetch2,
4434
- discoverOrSpawn,
5022
+ discoverOrSpawn as discoverOrSpawn2,
4435
5023
  isProcessAlive as isProcessAlive2,
4436
5024
  readRuntime as readRuntime2,
4437
5025
  resolveDaemonEntry as resolveDaemonEntry2,
4438
- stopOwnedDaemon,
5026
+ stopOwnedDaemon as stopOwnedDaemon2,
4439
5027
  stopProcessByPid
4440
5028
  } from "@bendyline/gezel-client/node";
4441
5029
  import { Command } from "commander";
@@ -4602,6 +5190,29 @@ function errorMessage(error) {
4602
5190
  return error instanceof Error ? error.message : String(error);
4603
5191
  }
4604
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
+
4605
5216
  // src/bin/gezel.ts
4606
5217
  var program = new Command();
4607
5218
  program.name("gezel").description("Gezel \u2014 build a community of agents that do things.").version(GEZEL_VERSION2).option(
@@ -4623,17 +5234,22 @@ program.hook("preAction", () => {
4623
5234
  program.action(async () => {
4624
5235
  const globals = cliGlobals();
4625
5236
  resolveDevHome(globals);
4626
- const client = await connectOwned(globals);
4627
- const projectId = await resolveTuiProject(client, globals);
4628
- const gezelId = await ensureCliProjectLead(client, projectId);
4629
- let projectName = basename3(process.cwd()) || "workspace";
5237
+ const connection = await connectForTui(globals);
4630
5238
  try {
4631
- const { projects } = await client.listProjects();
4632
- projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
4633
- } 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?.();
4634
5252
  }
4635
- const { launchTui: launchTui2 } = await Promise.resolve().then(() => (init_tui(), tui_exports));
4636
- await launchTui2({ client, projectId, projectName, gezelId });
4637
5253
  });
4638
5254
  program.command("start").description("Start the Gezel daemon (no-op if already running)").option(
4639
5255
  "--port <port>",
@@ -4671,7 +5287,7 @@ program.command("start").description("Start the Gezel daemon (no-op if already r
4671
5287
  }
4672
5288
  if (port !== void 0 || opts.web) {
4673
5289
  const entry = resolveDaemonEntry2(import.meta.url);
4674
- const result = await discoverOrSpawn({
5290
+ const result = await discoverOrSpawn2({
4675
5291
  daemonEntry: entry,
4676
5292
  detached: true,
4677
5293
  env: spawnEnv,
@@ -4745,7 +5361,7 @@ async function startForeground(env2) {
4745
5361
  });
4746
5362
  let stopping;
4747
5363
  const requestStop = () => {
4748
- stopping ??= stopOwnedDaemon(child);
5364
+ stopping ??= stopOwnedDaemon2(child);
4749
5365
  void stopping;
4750
5366
  };
4751
5367
  process.on("SIGINT", requestStop);
@@ -4820,10 +5436,33 @@ program.command("status").description("Show daemon status").action(async () => {
4820
5436
  console.error(`health failed: ${err.message}`);
4821
5437
  }
4822
5438
  });
4823
- 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) => {
4824
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) {
4825
5464
  if (globals.connect) {
4826
- throw new CliError("gezel stop cannot stop an explicit remote service.");
5465
+ throw new CliError("gezel stop --daemon cannot stop an explicit remote service.");
4827
5466
  }
4828
5467
  const system = await findHealthySystemService(globals);
4829
5468
  if (system) {
@@ -4844,7 +5483,7 @@ program.command("stop").description("Stop the user-owned Gezel daemon").action(a
4844
5483
  console.error(`failed to confirm gezeld pid=${runtime.pid} stopped`);
4845
5484
  process.exitCode = 1;
4846
5485
  }
4847
- });
5486
+ }
4848
5487
  program.command("mode [mode]").description("Show or set AI activity (read-only, reactive, reactive+tasks, or full-play)").action(async (requested) => {
4849
5488
  const next = requested ? parseCliEngagementMode(requested) : null;
4850
5489
  if (requested && !next) {
@@ -4871,6 +5510,11 @@ program.command("run [prompt...]").description("Run a prompt through a gezel and
4871
5510
  return;
4872
5511
  }
4873
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
+ });
4874
5518
  try {
4875
5519
  const { client } = conn;
4876
5520
  const projectId = await resolveRunProject(client, cliGlobals());
@@ -4901,6 +5545,7 @@ ${ev.error}`);
4901
5545
  if (printed) process.stdout.write("\n");
4902
5546
  if (errored) process.exitCode = 1;
4903
5547
  } finally {
5548
+ removeSignalCleanup();
4904
5549
  if (conn.stop) await conn.stop();
4905
5550
  }
4906
5551
  });