@bendyline/gezel-cli 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tui/index.js CHANGED
@@ -4,8 +4,11 @@
4
4
  import { render } from "ink";
5
5
 
6
6
  // src/tui/App.tsx
7
+ import {
8
+ pickRandomNameWithGender as pickRandomNameWithGender2
9
+ } from "@bendyline/gezel";
7
10
  import { Box as Box6, Text as Text6, useApp, useInput as useInput4, useStdout } from "ink";
8
- import { useCallback, useEffect as useEffect3, useMemo, useRef as useRef2, useState as useState4 } from "react";
11
+ import { useCallback as useCallback2, useEffect as useEffect4, useMemo, useRef as useRef3, useState as useState5 } from "react";
9
12
 
10
13
  // src/connection.ts
11
14
  import { createHash, randomUUID } from "crypto";
@@ -157,6 +160,44 @@ function activeAccessMode(opts) {
157
160
  return GezelCore.projectWorkspaceWritable(project) ? "editable" : "read-only";
158
161
  }
159
162
 
163
+ // src/tui/buffered-state.ts
164
+ import { useCallback, useEffect, useRef, useState } from "react";
165
+ function useBufferedState(initial, intervalMs) {
166
+ const [rendered, setRendered] = useState(initial);
167
+ const valueRef = useRef(rendered);
168
+ const timerRef = useRef(null);
169
+ const cancelTimer = useCallback(() => {
170
+ if (timerRef.current === null) return;
171
+ clearTimeout(timerRef.current);
172
+ timerRef.current = null;
173
+ }, []);
174
+ const apply = useCallback(
175
+ (update, buffered) => {
176
+ const current = valueRef.current;
177
+ const next = typeof update === "function" ? update(current) : update;
178
+ valueRef.current = next;
179
+ if (!buffered) {
180
+ cancelTimer();
181
+ setRendered(next);
182
+ return;
183
+ }
184
+ if (Object.is(current, next) || timerRef.current !== null) return;
185
+ timerRef.current = setTimeout(() => {
186
+ timerRef.current = null;
187
+ setRendered(valueRef.current);
188
+ }, intervalMs);
189
+ },
190
+ [cancelTimer, intervalMs]
191
+ );
192
+ const setImmediate = useCallback(
193
+ (update) => apply(update, false),
194
+ [apply]
195
+ );
196
+ const setBuffered = useCallback((update) => apply(update, true), [apply]);
197
+ useEffect(() => cancelTimer, [cancelTimer]);
198
+ return [rendered, setImmediate, setBuffered];
199
+ }
200
+
160
201
  // src/tui/open-command.ts
161
202
  var MAX_RECENT_REFERENCES = 12;
162
203
  function rememberCliOpenReferences(current, observed, max = MAX_RECENT_REFERENCES) {
@@ -202,8 +243,14 @@ function referencesFromMessage(message, projectId) {
202
243
  for (const tool of message.toolCalls ?? []) {
203
244
  references.push(...referencesFromTool(tool, projectId));
204
245
  }
205
- for (const path of message.referencedArtifacts ?? []) {
206
- references.push(reference("artifact", path, projectId));
246
+ if (message.referencedFiles?.length) {
247
+ for (const file of message.referencedFiles) {
248
+ references.push(reference(file.kind, file.path, projectId));
249
+ }
250
+ } else {
251
+ for (const path of message.referencedArtifacts ?? []) {
252
+ references.push(reference("artifact", path, projectId));
253
+ }
207
254
  }
208
255
  return references;
209
256
  }
@@ -265,9 +312,11 @@ var SLASH_COMMAND_WORDWHEEL_SIZE = 4;
265
312
  var SLASH_COMMANDS = [
266
313
  { name: "help", description: "show the command reference" },
267
314
  { name: "project", description: "switch active project" },
268
- { name: "gezel", description: "switch active gezel" },
315
+ { name: "gezel", description: "switch gezel, or bring a role onto the project" },
269
316
  { name: "allow", description: "allow a project permission" },
270
317
  { name: "disallow", description: "disallow a project permission" },
318
+ { name: "show", description: "show optional chat details" },
319
+ { name: "hide", description: "hide optional chat details" },
271
320
  { name: "mode", description: "set AI activity: read-only through full play" },
272
321
  { name: "model", description: "switch engine and model" },
273
322
  { name: "thread", description: "switch the active chat thread" },
@@ -295,6 +344,18 @@ var NIGHT_SHIFT_SUBCOMMANDS = [
295
344
  var MODEL_SUBCOMMANDS = [
296
345
  { name: "download", description: "choose and download a new on-device model" }
297
346
  ];
347
+ var CHAT_DETAIL_TARGETS = [
348
+ {
349
+ name: "thinking",
350
+ showDescription: "show model thinking inline as it streams",
351
+ hideDescription: "hide model thinking and keep only the activity count"
352
+ },
353
+ {
354
+ name: "writes",
355
+ showDescription: "show file, artifact, and note content as it streams",
356
+ hideDescription: "hide streamed write content and keep compact tool activity"
357
+ }
358
+ ];
298
359
  var PROJECT_PERMISSIONS = [
299
360
  {
300
361
  name: "edits",
@@ -373,6 +434,18 @@ function suggestSlashWordwheel(input, craftbooks, recentReferences = []) {
373
434
  })
374
435
  );
375
436
  }
437
+ const detailMatch = input.match(/^\/(show|hide)\s+(.*)$/i);
438
+ if (detailMatch) {
439
+ const command = (detailMatch[1] ?? "").toLowerCase();
440
+ const query = (detailMatch[2] ?? "").trim().toLowerCase();
441
+ return CHAT_DETAIL_TARGETS.filter((target) => target.name.startsWith(query)).map((target) => ({
442
+ key: `${command}:${target.name}`,
443
+ label: `/${command} ${target.name}`,
444
+ description: command === "show" ? target.showDescription : target.hideDescription,
445
+ submit: `/${command} ${target.name}`,
446
+ completion: `/${command} ${target.name}`
447
+ }));
448
+ }
376
449
  const modeMatch = input.match(/^\/mode\s+(.*)$/i);
377
450
  if (modeMatch) {
378
451
  const query = (modeMatch[1] ?? "").trim().toLowerCase();
@@ -455,26 +528,157 @@ function parseInput(raw, cliMode) {
455
528
  import { GEZEL_VERSION } from "@bendyline/gezel";
456
529
  import { Box, Text } from "ink";
457
530
 
531
+ // src/tui/write-stream.ts
532
+ var WRITE_PAYLOAD_FIELDS = {
533
+ save_memory: "text",
534
+ write_file: "content",
535
+ append_to_file: "content",
536
+ replace_in_file: "replace",
537
+ replace_lines: "content",
538
+ apply_patch: "diff",
539
+ insert_at_marker: "content",
540
+ write_artifact: "content",
541
+ write_document: "content",
542
+ write_task_note: "text"
543
+ };
544
+ function isStreamedWriteTool(name) {
545
+ return writePayloadField(name) !== void 0;
546
+ }
547
+ function createWriteStreamState(toolName) {
548
+ return {
549
+ toolName,
550
+ phase: "seeking",
551
+ carry: "",
552
+ escaped: false,
553
+ unicodeEscape: null
554
+ };
555
+ }
556
+ function appendWriteArgumentChunk(state, chunk) {
557
+ if (state.phase === "done" || chunk.length === 0) return { state, text: "" };
558
+ let next = { ...state };
559
+ let input = chunk;
560
+ if (next.phase === "seeking") {
561
+ const field = writePayloadField(next.toolName);
562
+ if (!field) return { state: { ...next, phase: "done", carry: "" }, text: "" };
563
+ const combined = next.carry + chunk;
564
+ const match = payloadStartPattern(field).exec(combined);
565
+ if (!match || match.index === void 0) {
566
+ const carryChars = Math.max(64, field.length + 16);
567
+ return {
568
+ state: { ...next, carry: combined.slice(-carryChars) },
569
+ text: ""
570
+ };
571
+ }
572
+ input = combined.slice(match.index + match[0].length);
573
+ next = { ...next, phase: "reading", carry: "" };
574
+ }
575
+ let text = "";
576
+ for (const char of input) {
577
+ if (next.unicodeEscape !== null) {
578
+ const unicodeEscape = next.unicodeEscape + char;
579
+ if (unicodeEscape.length < 4) {
580
+ next = { ...next, unicodeEscape };
581
+ continue;
582
+ }
583
+ const code = Number.parseInt(unicodeEscape, 16);
584
+ text += Number.isNaN(code) ? `\\u${unicodeEscape}` : String.fromCharCode(code);
585
+ next = { ...next, unicodeEscape: null, escaped: false };
586
+ continue;
587
+ }
588
+ if (next.escaped) {
589
+ if (char === "u") {
590
+ next = { ...next, unicodeEscape: "" };
591
+ continue;
592
+ }
593
+ text += decodeEscape(char);
594
+ next = { ...next, escaped: false };
595
+ continue;
596
+ }
597
+ if (char === "\\") {
598
+ next = { ...next, escaped: true };
599
+ continue;
600
+ }
601
+ if (char === '"') {
602
+ next = { ...next, phase: "done", carry: "" };
603
+ break;
604
+ }
605
+ text += char;
606
+ }
607
+ return { state: next, text };
608
+ }
609
+ function writePayloadField(name) {
610
+ if (!name) return void 0;
611
+ const normalized = normalizeToolName(name);
612
+ return WRITE_PAYLOAD_FIELDS[normalized];
613
+ }
614
+ function normalizeToolName(name) {
615
+ return name.trim().replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase();
616
+ }
617
+ function payloadStartPattern(field) {
618
+ return new RegExp(`"${field.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"\\s*:\\s*"`);
619
+ }
620
+ function decodeEscape(char) {
621
+ switch (char) {
622
+ case "b":
623
+ return "\b";
624
+ case "f":
625
+ return "\f";
626
+ case "n":
627
+ return "\n";
628
+ case "r":
629
+ return "\r";
630
+ case "t":
631
+ return " ";
632
+ default:
633
+ return char;
634
+ }
635
+ }
636
+
458
637
  // src/tui/feed.ts
459
638
  var MAX_ROWS = 200;
639
+ var MAX_FEED_ROW_CHARS = 8e3;
640
+ function capFeedText(text) {
641
+ return text.length > MAX_FEED_ROW_CHARS ? text.slice(0, MAX_FEED_ROW_CHARS + 1) : text;
642
+ }
643
+ function appendFeedText(current, chunk) {
644
+ if (current.length > MAX_FEED_ROW_CHARS || chunk.length === 0) return current;
645
+ const remaining = MAX_FEED_ROW_CHARS + 1 - current.length;
646
+ return current + chunk.slice(0, remaining);
647
+ }
460
648
  var counter = 0;
461
649
  function nextKey() {
462
650
  counter += 1;
463
651
  return `r${counter}`;
464
652
  }
465
- function reduceFeed(rows, env) {
653
+ function reduceFeed(rows, env, opts = {}) {
466
654
  const { sessionId, gezelId, event } = env;
467
655
  const cap = (next) => next.length > MAX_ROWS ? next.slice(next.length - MAX_ROWS) : next;
468
656
  switch (event.type) {
657
+ case "user_message_pending": {
658
+ const key = `startup-${sessionId}`;
659
+ const pending = {
660
+ key,
661
+ sessionId,
662
+ gezelId,
663
+ kind: "pending",
664
+ text: capFeedText(event.preview),
665
+ open: false
666
+ };
667
+ const idx = rows.findIndex((row) => row.key === key);
668
+ if (idx === -1) return cap([...rows, pending]);
669
+ const next = rows.slice();
670
+ next[idx] = pending;
671
+ return next;
672
+ }
469
673
  case "user_message":
470
674
  return cap([
471
- ...rows,
675
+ ...withoutStartupPending(rows, sessionId),
472
676
  {
473
677
  key: nextKey(),
474
678
  sessionId,
475
679
  gezelId,
476
680
  kind: "user",
477
- text: event.message.content,
681
+ text: capFeedText(event.message.content),
478
682
  open: false
479
683
  }
480
684
  ]);
@@ -485,7 +689,7 @@ function reduceFeed(rows, env) {
485
689
  sessionId,
486
690
  gezelId,
487
691
  kind: "pending",
488
- text: event.preview,
692
+ text: capFeedText(event.preview),
489
693
  open: false
490
694
  };
491
695
  const idx = rows.findIndex((row) => row.key === key);
@@ -496,43 +700,72 @@ function reduceFeed(rows, env) {
496
700
  }
497
701
  case "queue_removed":
498
702
  return rows.filter((row) => row.key !== `queue-${event.queueId}`);
703
+ case "reasoning_delta": {
704
+ const settled = closeWriteRows(rows, sessionId);
705
+ if (opts.showThinking === false) return settled;
706
+ const idx = findOpenRow(settled, sessionId, "thinking");
707
+ const open = idx === -1 ? void 0 : settled[idx];
708
+ if (!open) {
709
+ return cap([
710
+ ...settled,
711
+ {
712
+ key: nextKey(),
713
+ sessionId,
714
+ gezelId,
715
+ kind: "thinking",
716
+ text: capFeedText(event.content),
717
+ open: true
718
+ }
719
+ ]);
720
+ }
721
+ const next = settled.slice();
722
+ const text = appendFeedText(open.text, event.content);
723
+ if (text === open.text) return settled;
724
+ next[idx] = { ...open, text };
725
+ return next;
726
+ }
499
727
  case "delta": {
500
- const idx = findOpenAssistant(rows, sessionId);
501
- const open = idx === -1 ? void 0 : rows[idx];
728
+ const settled = closeWriteRows(closeOpenRows(rows, sessionId, "thinking"), sessionId);
729
+ const idx = findOpenAssistant(settled, sessionId);
730
+ const open = idx === -1 ? void 0 : settled[idx];
502
731
  if (!open) {
503
732
  return cap([
504
- ...rows,
733
+ ...settled,
505
734
  {
506
735
  key: nextKey(),
507
736
  sessionId,
508
737
  gezelId,
509
738
  kind: "assistant",
510
- text: event.content,
739
+ text: capFeedText(event.content),
511
740
  open: true
512
741
  }
513
742
  ]);
514
743
  }
515
- const next = rows.slice();
516
- next[idx] = { ...open, text: open.text + event.content };
744
+ const next = settled.slice();
745
+ const text = appendFeedText(open.text, event.content);
746
+ if (text === open.text) return settled;
747
+ next[idx] = { ...open, text };
517
748
  return next;
518
749
  }
519
750
  case "complete": {
520
- const idx = findOpenAssistant(rows, sessionId);
521
- const open = idx === -1 ? void 0 : rows[idx];
522
- const text = event.message.content;
751
+ const settled = closeWriteRows(closeOpenRows(rows, sessionId, "thinking"), sessionId);
752
+ const idx = findOpenAssistant(settled, sessionId);
753
+ const open = idx === -1 ? void 0 : settled[idx];
754
+ const text = capFeedText(event.message.content);
523
755
  if (!open) {
524
756
  return cap([
525
- ...rows,
757
+ ...settled,
526
758
  { key: nextKey(), sessionId, gezelId, kind: "assistant", text, open: false }
527
759
  ]);
528
760
  }
529
- const next = rows.slice();
761
+ const next = settled.slice();
530
762
  next[idx] = { ...open, text: text || open.text, open: false };
531
763
  return next;
532
764
  }
533
- case "tool":
765
+ case "tool": {
766
+ const settled = closeWriteRows(closeOpenRows(rows, sessionId, "thinking"), sessionId);
534
767
  return cap([
535
- ...rows,
768
+ ...settled,
536
769
  {
537
770
  key: nextKey(),
538
771
  sessionId,
@@ -542,6 +775,14 @@ function reduceFeed(rows, env) {
542
775
  open: false
543
776
  }
544
777
  ]);
778
+ }
779
+ case "tool_args_delta": {
780
+ const settled = closeOpenRows(rows, sessionId, "thinking");
781
+ if (opts.showWrites !== true) {
782
+ return closeWriteRows(settled, sessionId);
783
+ }
784
+ return appendWriteStream(settled, sessionId, gezelId, event.name, event.content);
785
+ }
545
786
  case "awaiting_gezel":
546
787
  return cap([
547
788
  ...rows,
@@ -562,7 +803,7 @@ function reduceFeed(rows, env) {
562
803
  sessionId: "local",
563
804
  gezelId: "",
564
805
  kind: "note",
565
- text: `task \xB7 ${event.summary}`,
806
+ text: capFeedText(`task \xB7 ${event.summary}`),
566
807
  open: false,
567
808
  taskEvent: {
568
809
  kind: event.kind,
@@ -570,22 +811,46 @@ function reduceFeed(rows, env) {
570
811
  }
571
812
  }
572
813
  ]);
573
- case "error":
814
+ case "error": {
815
+ const settled = withoutStartupPending(
816
+ closeWriteRows(closeOpenRows(rows, sessionId, "thinking"), sessionId),
817
+ sessionId
818
+ );
574
819
  return cap([
575
- ...rows,
576
- { key: nextKey(), sessionId, gezelId, kind: "error", text: event.error, open: false }
820
+ ...settled,
821
+ {
822
+ key: nextKey(),
823
+ sessionId,
824
+ gezelId,
825
+ kind: "error",
826
+ text: capFeedText(event.error),
827
+ open: false
828
+ }
577
829
  ]);
578
- case "done":
579
- return rows.map((r) => r.sessionId === sessionId && r.open ? { ...r, open: false } : r);
830
+ }
831
+ case "done": {
832
+ const settled = withoutStartupPending(closeWriteRows(rows, sessionId), sessionId);
833
+ return settled.map((r) => r.sessionId === sessionId && r.open ? { ...r, open: false } : r);
834
+ }
580
835
  default:
581
836
  return rows;
582
837
  }
583
838
  }
584
- function sessionToFeedRows(session) {
839
+ function sessionToFeedRows(session, opts = {}) {
585
840
  const rows = [];
586
841
  for (const message of session.messages) {
587
842
  if (message.hidden) continue;
588
843
  if (message.role === "assistant") {
844
+ if (opts.showThinking !== false && message.reasoning?.trim()) {
845
+ rows.push({
846
+ key: nextKey(),
847
+ sessionId: session.id,
848
+ gezelId: message.from?.gezelId ?? session.gezelId,
849
+ kind: "thinking",
850
+ text: capFeedText(message.reasoning),
851
+ open: false
852
+ });
853
+ }
589
854
  for (const tool of message.toolCalls ?? []) {
590
855
  rows.push({
591
856
  key: nextKey(),
@@ -603,7 +868,7 @@ function sessionToFeedRows(session) {
603
868
  sessionId: session.id,
604
869
  gezelId: message.from?.gezelId ?? session.gezelId,
605
870
  kind: message.role === "user" && !message.from ? "user" : message.from ? "assistant" : message.role,
606
- text: message.content,
871
+ text: capFeedText(message.content),
607
872
  open: false
608
873
  });
609
874
  }
@@ -613,7 +878,7 @@ function sessionToFeedRows(session) {
613
878
  sessionId: session.id,
614
879
  gezelId: session.gezelId,
615
880
  kind: "error",
616
- text: session.lastTurnError,
881
+ text: capFeedText(session.lastTurnError),
617
882
  open: false
618
883
  });
619
884
  }
@@ -630,6 +895,8 @@ function reduceTurns(turns, env) {
630
895
  return m;
631
896
  };
632
897
  switch (event.type) {
898
+ case "user_message_pending":
899
+ return set("preparing chat", 0, null);
633
900
  case "user_message":
634
901
  return set("thinking\u2026", 0, null);
635
902
  case "queued":
@@ -646,11 +913,11 @@ function reduceTurns(turns, env) {
646
913
  case "tool_args_delta": {
647
914
  const outputChars = (prior?.outputChars ?? 0) + event.content.length;
648
915
  const name = event.name.trim() || prior?.activeToolName || null;
649
- return set(runningToolLabel(name), outputChars, name);
916
+ return set(runningToolLabel(name, outputChars), outputChars, name);
650
917
  }
651
918
  case "tool": {
652
919
  const name = event.name.trim() || prior?.activeToolName || null;
653
- return set(runningToolLabel(name), void 0, name);
920
+ return set(runningToolLabel(name, prior?.outputChars ?? 0), void 0, name);
654
921
  }
655
922
  case "heartbeat":
656
923
  return event.label ? set(heartbeatLabel(event.label), void 0, null) : turns;
@@ -663,6 +930,10 @@ function reduceTurns(turns, env) {
663
930
  return turns;
664
931
  }
665
932
  }
933
+ function withoutStartupPending(rows, sessionId) {
934
+ const key = `startup-${sessionId}`;
935
+ return rows.some((row) => row.key === key) ? rows.filter((row) => row.key !== key) : rows;
936
+ }
666
937
  function phaseLabel(event, outputChars) {
667
938
  const pct = event.progress !== void 0 ? ` ${Math.round(event.progress * 100)}%` : "";
668
939
  switch (event.phase) {
@@ -683,8 +954,11 @@ function generationLabel(outputChars) {
683
954
  const tokens = Math.max(1, Math.round(outputChars / 4));
684
955
  return `generating \xB7 ~${tokens.toLocaleString("en-US")} ${tokens === 1 ? "token" : "tokens"}`;
685
956
  }
686
- function runningToolLabel(name) {
687
- return name ? `running tool \xB7 ${name}` : "running tool";
957
+ function runningToolLabel(name, outputChars = 0) {
958
+ const base = name ? `running tool \xB7 ${name}` : "running tool";
959
+ if (!isStreamedWriteTool(name) || outputChars <= 0) return base;
960
+ const tokens = Math.max(1, Math.round(outputChars / 4));
961
+ return `${base} \xB7 ~${tokens.toLocaleString("en-US")} ${tokens === 1 ? "token" : "tokens"}`;
688
962
  }
689
963
  function heartbeatLabel(label) {
690
964
  const trimmed = label.trim();
@@ -696,7 +970,14 @@ function heartbeatLabel(label) {
696
970
  function appendNote(rows, text, kind = "note") {
697
971
  const next = [
698
972
  ...rows,
699
- { key: nextKey(), sessionId: "local", gezelId: "", kind, text, open: false }
973
+ {
974
+ key: nextKey(),
975
+ sessionId: "local",
976
+ gezelId: "",
977
+ kind,
978
+ text: capFeedText(text),
979
+ open: false
980
+ }
700
981
  ];
701
982
  return next.length > MAX_ROWS ? next.slice(next.length - MAX_ROWS) : next;
702
983
  }
@@ -713,7 +994,7 @@ function finalizeShellRun(rows, runId, message) {
713
994
  sessionId: `term-${runId}`,
714
995
  gezelId: "",
715
996
  kind: "shell",
716
- text: text ? `${text}${footer}` : footer.trimStart(),
997
+ text: capFeedText(text ? `${text}${footer}` : footer.trimStart()),
717
998
  open: false
718
999
  }
719
1000
  ];
@@ -722,7 +1003,11 @@ function finalizeShellRun(rows, runId, message) {
722
1003
  const row = rows[idx];
723
1004
  if (!row) return rows;
724
1005
  const next = rows.slice();
725
- next[idx] = { ...row, open: false, text: `${row.text.replace(/\s+$/, "")}${footer}` };
1006
+ next[idx] = {
1007
+ ...row,
1008
+ open: false,
1009
+ text: capFeedText(`${row.text.replace(/\s+$/, "")}${footer}`)
1010
+ };
726
1011
  return next;
727
1012
  }
728
1013
  function shellFooter(message) {
@@ -745,7 +1030,7 @@ function appendShellChunk(rows, runId, chunk) {
745
1030
  sessionId: `term-${runId}`,
746
1031
  gezelId: "",
747
1032
  kind: "shell",
748
- text: chunk,
1033
+ text: capFeedText(chunk),
749
1034
  open: true
750
1035
  }
751
1036
  ];
@@ -753,17 +1038,84 @@ function appendShellChunk(rows, runId, chunk) {
753
1038
  }
754
1039
  const row = rows[idx];
755
1040
  if (!row) return rows;
1041
+ const text = appendFeedText(row.text, chunk);
1042
+ if (text === row.text) return rows;
756
1043
  const next = rows.slice();
757
- next[idx] = { ...row, text: row.text + chunk };
1044
+ next[idx] = { ...row, text };
758
1045
  return next;
759
1046
  }
760
1047
  function findOpenAssistant(rows, sessionId) {
1048
+ return findOpenRow(rows, sessionId, "assistant");
1049
+ }
1050
+ function findOpenRow(rows, sessionId, kind) {
761
1051
  for (let i = rows.length - 1; i >= 0; i--) {
762
1052
  const r = rows[i];
763
- if (r && r.sessionId === sessionId && r.kind === "assistant" && r.open) return i;
1053
+ if (r && r.sessionId === sessionId && r.kind === kind && r.open) return i;
764
1054
  }
765
1055
  return -1;
766
1056
  }
1057
+ function closeOpenRows(rows, sessionId, kind) {
1058
+ let changed = false;
1059
+ const next = rows.map((row) => {
1060
+ if (row.sessionId !== sessionId || row.kind !== kind || !row.open) return row;
1061
+ changed = true;
1062
+ return { ...row, open: false };
1063
+ });
1064
+ return changed ? next : rows;
1065
+ }
1066
+ function appendWriteStream(rows, sessionId, gezelId, eventToolName, chunk) {
1067
+ let idx = findOpenRow(rows, sessionId, "write");
1068
+ let open = idx === -1 ? void 0 : rows[idx];
1069
+ const toolName = eventToolName.trim() || open?.writeStream?.toolName || "";
1070
+ if (!isStreamedWriteTool(toolName)) return closeWriteRows(rows, sessionId);
1071
+ let currentRows = rows;
1072
+ if (open?.writeStream?.toolName !== toolName) {
1073
+ currentRows = closeWriteRows(rows, sessionId);
1074
+ idx = -1;
1075
+ open = void 0;
1076
+ }
1077
+ const decoded = appendWriteArgumentChunk(
1078
+ open?.writeStream ?? createWriteStreamState(toolName),
1079
+ chunk
1080
+ );
1081
+ if (!open) {
1082
+ const next2 = [
1083
+ ...currentRows,
1084
+ {
1085
+ key: nextKey(),
1086
+ sessionId,
1087
+ gezelId,
1088
+ kind: "write",
1089
+ text: capFeedText(decoded.text),
1090
+ open: true,
1091
+ writeStream: decoded.state
1092
+ }
1093
+ ];
1094
+ return next2.length > MAX_ROWS ? next2.slice(next2.length - MAX_ROWS) : next2;
1095
+ }
1096
+ const next = currentRows.slice();
1097
+ next[idx] = {
1098
+ ...open,
1099
+ text: appendFeedText(open.text, decoded.text),
1100
+ writeStream: decoded.state
1101
+ };
1102
+ return next;
1103
+ }
1104
+ function closeWriteRows(rows, sessionId) {
1105
+ let changed = false;
1106
+ const next = [];
1107
+ for (const row of rows) {
1108
+ if (row.sessionId !== sessionId || row.kind !== "write" || !row.writeStream) {
1109
+ next.push(row);
1110
+ continue;
1111
+ }
1112
+ changed = true;
1113
+ if (!row.text) continue;
1114
+ const { writeStream: _writeStream, ...settled } = row;
1115
+ next.push({ ...settled, open: false });
1116
+ }
1117
+ return changed ? next : rows;
1118
+ }
767
1119
  function toolLabel(event) {
768
1120
  return toolRowText(event);
769
1121
  }
@@ -774,7 +1126,7 @@ function toolRowText(call) {
774
1126
  const flat = detail?.replace(/\s+/g, " ").trim();
775
1127
  const clipped = flat && flat.length > MAX_TOOL_DETAIL_CHARS ? `${flat.slice(0, MAX_TOOL_DETAIL_CHARS - 1)}\u2026` : flat;
776
1128
  const failed = call.success === false ? ` \xB7 failed${call.errorMessage ? `: ${call.errorMessage}` : ""}` : "";
777
- return `\u{1F527} ${name}${clipped ? ` \xB7 ${clipped}` : ""}${failed}`;
1129
+ return capFeedText(`\u{1F527} ${name}${clipped ? ` \xB7 ${clipped}` : ""}${failed}`);
778
1130
  }
779
1131
  function gezelLabel(gezelId, gezels, boring) {
780
1132
  const g = gezels.find((x) => x.id === gezelId);
@@ -912,6 +1264,8 @@ var KIND_COLOR = {
912
1264
  user: "white",
913
1265
  pending: "yellow",
914
1266
  assistant: "cyan",
1267
+ thinking: "magenta",
1268
+ write: "yellow",
915
1269
  tool: "yellow",
916
1270
  note: "magenta",
917
1271
  error: "red",
@@ -919,7 +1273,8 @@ var KIND_COLOR = {
919
1273
  };
920
1274
  function ChatFeed(props) {
921
1275
  const { rows, gezels, boring, focusedSessionId, visible = 16 } = props;
922
- const shown = rows.slice(Math.max(0, rows.length - visible));
1276
+ const visibleRows = rows.filter((row) => row.kind !== "write" || row.text.length > 0);
1277
+ const shown = visibleRows.slice(Math.max(0, visibleRows.length - visible));
923
1278
  return /* @__PURE__ */ jsx(Box, { flexDirection: "column", flexGrow: 1, marginBottom: 1, children: shown.length === 0 ? /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
924
1279
  /* @__PURE__ */ jsx(Text, { color: "yellow", children: TABLE_LOGO }),
925
1280
  /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 3, children: [
@@ -934,7 +1289,7 @@ function ChatFeed(props) {
934
1289
  if (row.kind === "shell" && row.sessionId.startsWith("term-")) {
935
1290
  return /* @__PURE__ */ jsx(Text, { wrap: "wrap", children: clip(row.text) }, row.key);
936
1291
  }
937
- const who = row.kind === "user" ? "you" : row.kind === "pending" ? "pending" : row.gezelId ? gezelLabel(row.gezelId, gezels, boring) : row.kind === "tool" ? "tool" : row.kind === "shell" ? "shell" : row.kind === "error" ? "error" : "system";
1292
+ const who = row.kind === "user" ? "you" : row.kind === "pending" ? "pending" : row.kind === "thinking" ? "thinking" : row.kind === "write" ? "writing" : row.gezelId ? gezelLabel(row.gezelId, gezels, boring) : row.kind === "tool" ? "tool" : row.kind === "shell" ? "shell" : row.kind === "error" ? "error" : "system";
938
1293
  const isFocused = focusedSessionId && row.sessionId === focusedSessionId;
939
1294
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
940
1295
  /* @__PURE__ */ jsx(Text, { dimColor: !isFocused, color: isFocused ? "green" : void 0, children: isFocused ? "\u258E" : " " }),
@@ -943,9 +1298,16 @@ function ChatFeed(props) {
943
1298
  who,
944
1299
  ": "
945
1300
  ] }),
946
- /* @__PURE__ */ jsx(Text, { color: KIND_COLOR[row.kind], dimColor: row.kind === "pending", children: clip(
947
- row.taskEvent ? taskEventText(row, gezels, boring) : row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text
948
- ) })
1301
+ /* @__PURE__ */ jsx(
1302
+ Text,
1303
+ {
1304
+ color: KIND_COLOR[row.kind],
1305
+ dimColor: row.kind === "pending" || row.kind === "thinking" || row.kind === "write",
1306
+ children: clip(
1307
+ row.taskEvent ? taskEventText(row, gezels, boring) : row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text
1308
+ )
1309
+ }
1310
+ )
949
1311
  ] })
950
1312
  ] }, row.key);
951
1313
  }) });
@@ -970,20 +1332,19 @@ function taskEventText(row, gezels, boring) {
970
1332
  return row.text;
971
1333
  }
972
1334
  }
973
- var MAX_CHARS = 8e3;
974
1335
  function clip(text) {
975
1336
  const t = text.replace(/\s+$/, "");
976
- return t.length > MAX_CHARS ? `${t.slice(0, MAX_CHARS)}
1337
+ return t.length > MAX_FEED_ROW_CHARS ? `${t.slice(0, MAX_FEED_ROW_CHARS)}
977
1338
  \u2026 (truncated)` : t;
978
1339
  }
979
1340
 
980
1341
  // src/tui/components/Picker.tsx
981
1342
  import { Box as Box2, Text as Text2, useInput } from "ink";
982
- import { useState } from "react";
1343
+ import { useState as useState2 } from "react";
983
1344
  import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
984
1345
  function Picker(props) {
985
1346
  const { title, items, initialValue, windowSize, onSelect, onCancel } = props;
986
- const [index, setIndex] = useState(() => {
1347
+ const [index, setIndex] = useState2(() => {
987
1348
  const initialIndex = initialValue ? items.findIndex((item) => item.value === initialValue) : -1;
988
1349
  return Math.max(initialIndex, 0);
989
1350
  });
@@ -1021,13 +1382,18 @@ function Picker(props) {
1021
1382
  ] }) : null,
1022
1383
  visibleItems.map((item, offset) => {
1023
1384
  const itemIndex = start + offset;
1024
- return /* @__PURE__ */ jsxs2(Text2, { color: itemIndex === index ? "green" : void 0, children: [
1025
- itemIndex === index ? "\u276F " : " ",
1026
- item.label,
1027
- item.hint ? /* @__PURE__ */ jsxs2(Text2, { dimColor: true, children: [
1028
- " \u2014 ",
1029
- item.hint
1030
- ] }) : null
1385
+ const previousSection = offset === 0 ? void 0 : visibleItems[offset - 1]?.section;
1386
+ const showSection = item.section !== void 0 && item.section !== previousSection;
1387
+ return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", children: [
1388
+ showSection ? /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: item.section }) : null,
1389
+ /* @__PURE__ */ jsxs2(Text2, { color: itemIndex === index ? "green" : void 0, children: [
1390
+ itemIndex === index ? "\u276F " : " ",
1391
+ item.label,
1392
+ item.hint ? /* @__PURE__ */ jsxs2(Text2, { dimColor: true, children: [
1393
+ " \u2014 ",
1394
+ item.hint
1395
+ ] }) : null
1396
+ ] })
1031
1397
  ] }, item.value);
1032
1398
  }),
1033
1399
  start + visibleItems.length < items.length ? /* @__PURE__ */ jsxs2(Text2, { dimColor: true, children: [
@@ -1043,7 +1409,7 @@ function Picker(props) {
1043
1409
  // src/tui/components/PromptLine.tsx
1044
1410
  import { Box as Box4, Text as Text4, useInput as useInput2 } from "ink";
1045
1411
  import TextInput from "ink-text-input";
1046
- import { useEffect, useState as useState2 } from "react";
1412
+ import { useEffect as useEffect2, useState as useState3 } from "react";
1047
1413
 
1048
1414
  // src/tui/components/EnginePill.tsx
1049
1415
  import { Box as Box3, Text as Text3 } from "ink";
@@ -1099,8 +1465,8 @@ function PromptLine(props) {
1099
1465
  onChange,
1100
1466
  onSubmit
1101
1467
  } = props;
1102
- const [cursor, setCursor] = useState2(history.length);
1103
- const [suggestionIndex, setSuggestionIndex] = useState2(0);
1468
+ const [cursor, setCursor] = useState3(history.length);
1469
+ const [suggestionIndex, setSuggestionIndex] = useState3(0);
1104
1470
  const suggestions = active && !pendingPrompt ? suggestSlashWordwheel(value, craftbooks, recentOpenReferences) : [];
1105
1471
  const activeSuggestionIndex = Math.min(suggestionIndex, Math.max(0, suggestions.length - 1));
1106
1472
  const suggestionWindowStart = Math.min(
@@ -1119,7 +1485,7 @@ function PromptLine(props) {
1119
1485
  const selected = suggestions[activeSuggestionIndex];
1120
1486
  onSubmit(selected ? selected.submit : submittedValue);
1121
1487
  };
1122
- useEffect(() => {
1488
+ useEffect2(() => {
1123
1489
  setCursor(history.length);
1124
1490
  }, [history.length]);
1125
1491
  useInput2(
@@ -1220,19 +1586,94 @@ function compactThreadTitle(title) {
1220
1586
  // src/tui/components/QuestionPrompt.tsx
1221
1587
  import { Box as Box5, Text as Text5, useInput as useInput3 } from "ink";
1222
1588
  import TextInput2 from "ink-text-input";
1223
- import { useState as useState3 } from "react";
1224
- import { Fragment as Fragment3, jsx as jsx4, jsxs as jsxs5 } from "react/jsx-runtime";
1225
- var QUESTION_OPTION_WINDOW_SIZE = 4;
1589
+ import { useState as useState4 } from "react";
1590
+
1591
+ // src/tui/question-presentation.ts
1592
+ var TUI_APPROVAL_INTENTS = /* @__PURE__ */ new Set([
1593
+ "npm-install-approval",
1594
+ "command-approval",
1595
+ "tool-permission",
1596
+ "toolset-install-approval",
1597
+ "image-generation-approval",
1598
+ "video-generation-approval",
1599
+ "schedule-approval"
1600
+ ]);
1601
+ function canAnswerQuestionInTui(question) {
1602
+ return !question.intent || TUI_APPROVAL_INTENTS.has(question.intent.kind);
1603
+ }
1604
+ function choicesForQuestion(question) {
1605
+ if (question.choices && question.choices.length > 0) return question.choices;
1606
+ switch (question.intent?.kind) {
1607
+ case "command-approval":
1608
+ return ["Approve", "Decline"];
1609
+ case "tool-permission":
1610
+ return ["Allow", "Deny"];
1611
+ case "toolset-install-approval":
1612
+ return ["Install", "Not now"];
1613
+ case "image-generation-approval":
1614
+ case "video-generation-approval":
1615
+ return ["Allow once", "Always allow", "Decline"];
1616
+ case "schedule-approval":
1617
+ return ["Enable schedule", "Keep paused"];
1618
+ default:
1619
+ return [];
1620
+ }
1621
+ }
1622
+ function allowsWriteIn(question) {
1623
+ return question.intent ? false : question.allowWriteIn ?? true;
1624
+ }
1625
+ function questionHeading(question, askerLabel) {
1626
+ switch (question.intent?.kind) {
1627
+ case "npm-install-approval":
1628
+ return "npm package approval";
1629
+ case "command-approval":
1630
+ return "Command approval";
1631
+ case "tool-permission":
1632
+ return "Tool permission";
1633
+ case "toolset-install-approval":
1634
+ return "Toolset install approval";
1635
+ case "image-generation-approval":
1636
+ return "Image generation approval";
1637
+ case "video-generation-approval":
1638
+ return "Video generation approval";
1639
+ case "schedule-approval":
1640
+ return "Schedule approval";
1641
+ default:
1642
+ return `${askerLabel} asks`;
1643
+ }
1644
+ }
1645
+ function npmApprovalPackages(question) {
1646
+ if (question.intent?.kind !== "npm-install-approval") return [];
1647
+ const intent = question.intent;
1648
+ if (Array.isArray(intent.packages) && intent.packages.length > 0) return intent.packages;
1649
+ if (intent.package && intent.version) {
1650
+ return [{ package: intent.package, version: intent.version }];
1651
+ }
1652
+ return [];
1653
+ }
1226
1654
  function questionOptionCount(question) {
1227
- const choices = question.choices?.length ?? 0;
1228
- const writeIn = question.allowWriteIn ?? true;
1655
+ if (question.intent?.kind === "npm-install-approval") {
1656
+ return npmApprovalPackages(question).length > 0 ? 3 : 1;
1657
+ }
1658
+ const choices = choicesForQuestion(question).length;
1659
+ const writeIn = allowsWriteIn(question);
1229
1660
  const submit = question.multiSelect === true && choices > 0;
1230
1661
  return choices + (writeIn ? 1 : 0) + (submit ? 1 : 0);
1231
1662
  }
1663
+
1664
+ // src/tui/components/QuestionPrompt.tsx
1665
+ import { Fragment as Fragment3, jsx as jsx4, jsxs as jsxs5 } from "react/jsx-runtime";
1666
+ var QUESTION_OPTION_WINDOW_SIZE = 4;
1232
1667
  function QuestionPrompt(props) {
1668
+ if (props.question.intent?.kind === "npm-install-approval") {
1669
+ return /* @__PURE__ */ jsx4(NpmInstallApprovalPrompt, { ...props });
1670
+ }
1671
+ return /* @__PURE__ */ jsx4(StandardQuestionPrompt, { ...props });
1672
+ }
1673
+ function StandardQuestionPrompt(props) {
1233
1674
  const { client, question, askerLabel, active, onAnswered } = props;
1234
- const choices = question.choices ?? [];
1235
- const allowWriteIn = question.allowWriteIn ?? true;
1675
+ const choices = choicesForQuestion(question);
1676
+ const allowWriteIn = allowsWriteIn(question);
1236
1677
  const multiSelect = question.multiSelect === true;
1237
1678
  const options = [
1238
1679
  ...choices.map(
@@ -1241,12 +1682,12 @@ function QuestionPrompt(props) {
1241
1682
  ...allowWriteIn ? [{ kind: "write-in", label: "Other\u2026" }] : [],
1242
1683
  ...multiSelect && choices.length > 0 ? [{ kind: "submit", label: "Submit selections" }] : []
1243
1684
  ];
1244
- const [optionIndex, setOptionIndex] = useState3(0);
1245
- const [selected, setSelected] = useState3(() => /* @__PURE__ */ new Set());
1246
- const [writing, setWriting] = useState3(choices.length === 0 && allowWriteIn);
1247
- const [writeIn, setWriteIn] = useState3("");
1248
- const [submitting, setSubmitting] = useState3(false);
1249
- const [error, setError] = useState3(null);
1685
+ const [optionIndex, setOptionIndex] = useState4(0);
1686
+ const [selected, setSelected] = useState4(() => /* @__PURE__ */ new Set());
1687
+ const [writing, setWriting] = useState4(choices.length === 0 && allowWriteIn);
1688
+ const [writeIn, setWriteIn] = useState4("");
1689
+ const [submitting, setSubmitting] = useState4(false);
1690
+ const [error, setError] = useState4(null);
1250
1691
  const activeOptionIndex = Math.min(optionIndex, Math.max(0, options.length - 1));
1251
1692
  const windowStart = Math.min(
1252
1693
  Math.max(0, activeOptionIndex - QUESTION_OPTION_WINDOW_SIZE + 1),
@@ -1318,10 +1759,7 @@ function QuestionPrompt(props) {
1318
1759
  { isActive: active }
1319
1760
  );
1320
1761
  return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
1321
- /* @__PURE__ */ jsxs5(Text5, { bold: true, color: "yellow", children: [
1322
- askerLabel,
1323
- " asks"
1324
- ] }),
1762
+ /* @__PURE__ */ jsx4(Text5, { bold: true, color: "yellow", children: questionHeading(question, askerLabel) }),
1325
1763
  /* @__PURE__ */ jsx4(Text5, { wrap: "wrap", children: question.prompt }),
1326
1764
  writing ? /* @__PURE__ */ jsxs5(Fragment3, { children: [
1327
1765
  /* @__PURE__ */ jsxs5(Box5, { children: [
@@ -1363,6 +1801,128 @@ function QuestionPrompt(props) {
1363
1801
  error ? /* @__PURE__ */ jsx4(Text5, { color: "red", children: error }) : null
1364
1802
  ] });
1365
1803
  }
1804
+ var NPM_DECISIONS = [
1805
+ { value: "install", label: "Install" },
1806
+ { value: "always", label: "Always allow" },
1807
+ { value: "decline", label: "Decline" }
1808
+ ];
1809
+ function NpmInstallApprovalPrompt(props) {
1810
+ const { client, question, active, onAnswered } = props;
1811
+ const packages = npmApprovalPackages(question);
1812
+ const [packageIndex, setPackageIndex] = useState4(0);
1813
+ const [optionIndex, setOptionIndex] = useState4(0);
1814
+ const [decisions, setDecisions] = useState4(
1815
+ () => packages.map(() => void 0)
1816
+ );
1817
+ const [submitting, setSubmitting] = useState4(false);
1818
+ const [error, setError] = useState4(null);
1819
+ const currentPackage = packages[packageIndex];
1820
+ const submit = async (nextDecisions) => {
1821
+ if (submitting) return;
1822
+ setError(null);
1823
+ setSubmitting(true);
1824
+ const body = packages.length === 0 ? { declined: true } : {
1825
+ npmInstallDecisions: packages.map((entry, index) => ({
1826
+ package: entry.package,
1827
+ version: entry.version,
1828
+ decision: nextDecisions[index] ?? "decline"
1829
+ }))
1830
+ };
1831
+ try {
1832
+ onAnswered(await client.answerQuestion(question.id, body));
1833
+ } catch (err) {
1834
+ setError(err instanceof Error ? err.message : String(err));
1835
+ setSubmitting(false);
1836
+ }
1837
+ };
1838
+ useInput3(
1839
+ (_input, key) => {
1840
+ if (submitting) return;
1841
+ if (!currentPackage) {
1842
+ if (key.return) void submit([]);
1843
+ return;
1844
+ }
1845
+ if (key.upArrow) {
1846
+ setOptionIndex((index) => index <= 0 ? NPM_DECISIONS.length - 1 : index - 1);
1847
+ return;
1848
+ }
1849
+ if (key.downArrow) {
1850
+ setOptionIndex((index) => index >= NPM_DECISIONS.length - 1 ? 0 : index + 1);
1851
+ return;
1852
+ }
1853
+ if (key.leftArrow && packageIndex > 0) {
1854
+ const previousIndex = packageIndex - 1;
1855
+ const previousDecision = decisions[previousIndex];
1856
+ setPackageIndex(previousIndex);
1857
+ setOptionIndex(
1858
+ Math.max(
1859
+ 0,
1860
+ NPM_DECISIONS.findIndex((item) => item.value === previousDecision)
1861
+ )
1862
+ );
1863
+ setError(null);
1864
+ return;
1865
+ }
1866
+ if (!key.return) return;
1867
+ const decision = NPM_DECISIONS[optionIndex]?.value ?? "decline";
1868
+ const nextDecisions = decisions.slice();
1869
+ nextDecisions[packageIndex] = decision;
1870
+ setDecisions(nextDecisions);
1871
+ if (packageIndex >= packages.length - 1) {
1872
+ void submit(nextDecisions);
1873
+ return;
1874
+ }
1875
+ const nextPackageIndex = packageIndex + 1;
1876
+ const nextDecision = nextDecisions[nextPackageIndex];
1877
+ setPackageIndex(nextPackageIndex);
1878
+ setOptionIndex(
1879
+ Math.max(
1880
+ 0,
1881
+ NPM_DECISIONS.findIndex((item) => item.value === nextDecision)
1882
+ )
1883
+ );
1884
+ setError(null);
1885
+ },
1886
+ { isActive: active }
1887
+ );
1888
+ return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
1889
+ /* @__PURE__ */ jsx4(Text5, { bold: true, color: "yellow", children: "npm package approval" }),
1890
+ currentPackage ? /* @__PURE__ */ jsxs5(Fragment3, { children: [
1891
+ /* @__PURE__ */ jsxs5(Text5, { wrap: "wrap", children: [
1892
+ "A gezel wants to install ",
1893
+ packages.length === 1 ? "this package" : "packages",
1894
+ " outside the pre-vetted list."
1895
+ ] }),
1896
+ /* @__PURE__ */ jsxs5(Text5, { children: [
1897
+ /* @__PURE__ */ jsxs5(Text5, { bold: true, children: [
1898
+ currentPackage.package,
1899
+ "@",
1900
+ currentPackage.version
1901
+ ] }),
1902
+ packages.length > 1 ? ` \xB7 package ${packageIndex + 1}/${packages.length}` : ""
1903
+ ] }),
1904
+ NPM_DECISIONS.map((option, index) => {
1905
+ const focused = index === optionIndex;
1906
+ const selected = decisions[packageIndex] === option.value;
1907
+ return /* @__PURE__ */ jsxs5(Text5, { color: focused ? "cyan" : void 0, children: [
1908
+ focused ? "\u203A " : " ",
1909
+ selected ? "[x] " : "",
1910
+ option.label
1911
+ ] }, option.value);
1912
+ }),
1913
+ /* @__PURE__ */ jsxs5(Text5, { dimColor: true, children: [
1914
+ "\u2191/\u2193 choose \xB7 Enter answer",
1915
+ packageIndex > 0 ? " \xB7 \u2190 previous package" : ""
1916
+ ] })
1917
+ ] }) : /* @__PURE__ */ jsxs5(Fragment3, { children: [
1918
+ /* @__PURE__ */ jsx4(Text5, { color: "red", children: "This approval has no package details." }),
1919
+ /* @__PURE__ */ jsx4(Text5, { color: "cyan", children: "\u203A Decline and dismiss" }),
1920
+ /* @__PURE__ */ jsx4(Text5, { dimColor: true, children: "Enter dismiss" })
1921
+ ] }),
1922
+ submitting ? /* @__PURE__ */ jsx4(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
1923
+ error ? /* @__PURE__ */ jsx4(Text5, { color: "red", children: error }) : null
1924
+ ] });
1925
+ }
1366
1926
  function toggleSet(current, value) {
1367
1927
  const next = new Set(current);
1368
1928
  if (next.has(value)) next.delete(value);
@@ -1456,6 +2016,167 @@ function craftbookStartRequest(book) {
1456
2016
  };
1457
2017
  }
1458
2018
 
2019
+ // src/tui/gezel-picker.ts
2020
+ import {
2021
+ getProjectType,
2022
+ resolveProjectTypeId
2023
+ } from "@bendyline/gezel";
2024
+ var GEZEL_VALUE_PREFIX = "gezel:";
2025
+ var TEMPLATE_VALUE_PREFIX = "template:";
2026
+ var CORE_ROLE_ORDER = [
2027
+ "voorman",
2028
+ "builder",
2029
+ "developer",
2030
+ "reviewer",
2031
+ "planner",
2032
+ "researcher",
2033
+ "designer",
2034
+ "copywriter",
2035
+ "meester",
2036
+ "image-generator",
2037
+ "video-generator"
2038
+ ];
2039
+ var SECTION_IN_PROJECT = "In this project";
2040
+ var SECTION_RECOMMENDED = "Recommended for this project";
2041
+ var SECTION_OTHER_GEZELS = "Your other gezels";
2042
+ var SECTION_CORE = "Core roles";
2043
+ var SECTION_MORE = "More roles";
2044
+ var DEFAULT_HINT_WIDTH = 76;
2045
+ function clip2(text, width) {
2046
+ const flat = text.replace(/\s+/g, " ").trim();
2047
+ if (flat.length <= width) return flat;
2048
+ return `${flat.slice(0, Math.max(1, width - 1)).trimEnd()}\u2026`;
2049
+ }
2050
+ function roleIdentity(value) {
2051
+ return (value ?? "").trim().toLowerCase();
2052
+ }
2053
+ function displayName(gezel, roleBasedNameOnly) {
2054
+ if (roleBasedNameOnly) return gezel.roleBasedName ?? gezel.role ?? gezel.id;
2055
+ return gezel.name;
2056
+ }
2057
+ function affinityRanks(project) {
2058
+ const type = getProjectType(resolveProjectTypeId(project ?? {}));
2059
+ const out = /* @__PURE__ */ new Map();
2060
+ let rank = 0;
2061
+ const add = (role) => {
2062
+ if (!out.has(role.templateId)) out.set(role.templateId, { rank: rank++, reason: role.reason });
2063
+ };
2064
+ for (const role of type?.gezelRoles.default ?? []) add(role);
2065
+ for (const role of type?.gezelRoles.suggested ?? []) add(role);
2066
+ return out;
2067
+ }
2068
+ function gezelHint(gezel, templatesById, roleBasedNameOnly) {
2069
+ const role = roleBasedNameOnly ? void 0 : gezel.roleBasedName ?? gezel.role;
2070
+ const about = gezel.description ?? (gezel.templateId ? templatesById.get(gezel.templateId)?.description : void 0);
2071
+ return [role, about].filter(Boolean).join(" \xB7 ");
2072
+ }
2073
+ function buildGezelPickerItems(inputs) {
2074
+ const {
2075
+ gezels,
2076
+ templates,
2077
+ memberIds,
2078
+ project,
2079
+ roleBasedNameOnly = false,
2080
+ hintWidth = DEFAULT_HINT_WIDTH
2081
+ } = inputs;
2082
+ const templatesById = new Map(templates.map((t) => [t.id, t]));
2083
+ const members = new Set(memberIds);
2084
+ const affinity = affinityRanks(project);
2085
+ const filledTemplateIds = new Set(gezels.flatMap((g) => g.templateId ? [g.templateId] : []));
2086
+ const filledRoleIdentities = new Set(
2087
+ gezels.flatMap((g) => [roleIdentity(g.role), roleIdentity(g.roleBasedName)].filter(Boolean))
2088
+ );
2089
+ const coreRank = new Map(CORE_ROLE_ORDER.map((id, index) => [id, index]));
2090
+ const items = [];
2091
+ const push = (section, item) => {
2092
+ items.push({ ...item, section });
2093
+ };
2094
+ const gezelItem = (gezel) => ({
2095
+ label: displayName(gezel, roleBasedNameOnly),
2096
+ value: `${GEZEL_VALUE_PREFIX}${gezel.id}`,
2097
+ hint: clip2(gezelHint(gezel, templatesById, roleBasedNameOnly), hintWidth)
2098
+ });
2099
+ const templateItem = (template, reason) => ({
2100
+ label: template.name,
2101
+ value: `${TEMPLATE_VALUE_PREFIX}${template.id}`,
2102
+ hint: clip2(reason ?? template.description, hintWidth)
2103
+ });
2104
+ const onProject = gezels.filter((g) => members.has(g.id));
2105
+ for (const gezel of sortByName(onProject, roleBasedNameOnly)) {
2106
+ push(SECTION_IN_PROJECT, gezelItem(gezel));
2107
+ }
2108
+ const offProject = gezels.filter((g) => !members.has(g.id));
2109
+ const affinityFor = (gezel) => {
2110
+ if (gezel.templateId && affinity.has(gezel.templateId)) return affinity.get(gezel.templateId);
2111
+ for (const [templateId, entry] of affinity) {
2112
+ const template = templatesById.get(templateId);
2113
+ if (!template) continue;
2114
+ if (roleIdentity(template.role) === roleIdentity(gezel.role) || roleIdentity(template.name) === roleIdentity(gezel.roleBasedName)) {
2115
+ return entry;
2116
+ }
2117
+ }
2118
+ return void 0;
2119
+ };
2120
+ const recommendedGezels = offProject.flatMap((gezel) => {
2121
+ const entry = affinityFor(gezel);
2122
+ return entry ? [{ gezel, entry }] : [];
2123
+ }).sort((a, b) => a.entry.rank - b.entry.rank);
2124
+ const recommendedGezelIds = new Set(recommendedGezels.map((r) => r.gezel.id));
2125
+ const availableTemplates = templates.filter(
2126
+ (template) => !filledTemplateIds.has(template.id) && !filledRoleIdentities.has(roleIdentity(template.role)) && !filledRoleIdentities.has(roleIdentity(template.name))
2127
+ );
2128
+ const recommendedTemplates = availableTemplates.flatMap((template) => {
2129
+ const entry = affinity.get(template.id);
2130
+ return entry ? [{ template, entry }] : [];
2131
+ }).sort((a, b) => a.entry.rank - b.entry.rank);
2132
+ const recommendedTemplateIds = new Set(recommendedTemplates.map((r) => r.template.id));
2133
+ for (const { gezel, entry } of recommendedGezels) {
2134
+ push(SECTION_RECOMMENDED, { ...gezelItem(gezel), hint: clip2(entry.reason, hintWidth) });
2135
+ }
2136
+ for (const { template, entry } of recommendedTemplates) {
2137
+ push(SECTION_RECOMMENDED, templateItem(template, entry.reason));
2138
+ }
2139
+ for (const gezel of sortByName(
2140
+ offProject.filter((g) => !recommendedGezelIds.has(g.id)),
2141
+ roleBasedNameOnly
2142
+ )) {
2143
+ push(SECTION_OTHER_GEZELS, gezelItem(gezel));
2144
+ }
2145
+ const remaining = availableTemplates.filter((t) => !recommendedTemplateIds.has(t.id));
2146
+ const core = remaining.filter((t) => coreRank.has(t.id)).sort((a, b) => (coreRank.get(a.id) ?? 0) - (coreRank.get(b.id) ?? 0));
2147
+ const more = remaining.filter((t) => !coreRank.has(t.id)).sort((a, b) => a.name.localeCompare(b.name));
2148
+ for (const template of core) push(SECTION_CORE, templateItem(template));
2149
+ for (const template of more) push(SECTION_MORE, templateItem(template));
2150
+ return items;
2151
+ }
2152
+ function sortByName(gezels, roleBasedNameOnly) {
2153
+ return [...gezels].sort(
2154
+ (a, b) => displayName(a, roleBasedNameOnly).localeCompare(displayName(b, roleBasedNameOnly))
2155
+ );
2156
+ }
2157
+ function resolveGezelArg(arg, inputs) {
2158
+ const query = arg.trim().toLowerCase();
2159
+ if (!query) return { kind: "unknown" };
2160
+ const { gezels, templates } = inputs;
2161
+ const gezelKeys = (g) => [g.id, g.name, g.roleBasedName, g.role].map(roleIdentity).filter(Boolean);
2162
+ const templateKeys = (t) => [t.id, t.role, t.name].map(roleIdentity).filter(Boolean);
2163
+ const exactGezel = gezels.find((g) => gezelKeys(g).includes(query));
2164
+ if (exactGezel) return { kind: "gezel", gezelId: exactGezel.id };
2165
+ const exactTemplate = templates.find((t) => templateKeys(t).includes(query));
2166
+ if (exactTemplate) return { kind: "template", templateId: exactTemplate.id };
2167
+ const prefixGezels = gezels.filter((g) => gezelKeys(g).some((k) => k.startsWith(query)));
2168
+ if (prefixGezels.length === 1) return { kind: "gezel", gezelId: prefixGezels[0].id };
2169
+ if (prefixGezels.length > 1) {
2170
+ return { kind: "ambiguous", labels: prefixGezels.map((g) => g.name) };
2171
+ }
2172
+ const prefixTemplates = templates.filter((t) => templateKeys(t).some((k) => k.startsWith(query)));
2173
+ if (prefixTemplates.length === 1) return { kind: "template", templateId: prefixTemplates[0].id };
2174
+ if (prefixTemplates.length > 1) {
2175
+ return { kind: "ambiguous", labels: prefixTemplates.map((t) => t.name) };
2176
+ }
2177
+ return { kind: "unknown" };
2178
+ }
2179
+
1459
2180
  // src/tui/model-picker.ts
1460
2181
  import {
1461
2182
  formatModelAttribution as formatModelAttribution2
@@ -1770,21 +2491,21 @@ function modelFitLabel(fit) {
1770
2491
  }
1771
2492
 
1772
2493
  // src/tui/question-queue.ts
1773
- function plainPendingQuestions(questions) {
1774
- return questions.filter((question) => !question.answer && !question.intent).slice().sort((a, b) => a.createdAt.localeCompare(b.createdAt));
2494
+ function pendingQuestionsForTui(questions) {
2495
+ return questions.filter((question) => !question.answer && canAnswerQuestionInTui(question)).slice().sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1775
2496
  }
1776
2497
  function updatePendingQuestion(questions, question) {
1777
2498
  const withoutCurrent = questions.filter((candidate) => candidate.id !== question.id);
1778
- return plainPendingQuestions(question.answer ? withoutCurrent : [...withoutCurrent, question]);
2499
+ return pendingQuestionsForTui(question.answer ? withoutCurrent : [...withoutCurrent, question]);
1779
2500
  }
1780
2501
 
1781
2502
  // src/tui/streams.ts
1782
2503
  import { streamProjectChatEvents, streamTerminalEvents } from "@bendyline/gezel-client";
1783
- import { useEffect as useEffect2, useRef } from "react";
2504
+ import { useEffect as useEffect3, useRef as useRef2 } from "react";
1784
2505
  function useProjectEvents(client, projectId, handler) {
1785
- const handlerRef = useRef(handler);
2506
+ const handlerRef = useRef2(handler);
1786
2507
  handlerRef.current = handler;
1787
- useEffect2(() => {
2508
+ useEffect3(() => {
1788
2509
  const controller = new AbortController();
1789
2510
  void consumeWithReconnect(
1790
2511
  async function* () {
@@ -1804,9 +2525,9 @@ function useProjectEvents(client, projectId, handler) {
1804
2525
  }, [client, projectId]);
1805
2526
  }
1806
2527
  function useTerminalEvents(client, projectId, handler) {
1807
- const handlerRef = useRef(handler);
2528
+ const handlerRef = useRef2(handler);
1808
2529
  handlerRef.current = handler;
1809
- useEffect2(() => {
2530
+ useEffect3(() => {
1810
2531
  const controller = new AbortController();
1811
2532
  void consumeWithReconnect(
1812
2533
  async function* () {
@@ -1856,8 +2577,8 @@ function abortableDelay(ms, signal) {
1856
2577
  import { jsx as jsx5, jsxs as jsxs6 } from "react/jsx-runtime";
1857
2578
  function useTerminalSize() {
1858
2579
  const { stdout } = useStdout();
1859
- const [size, setSize] = useState4({ rows: stdout?.rows ?? 24, columns: stdout?.columns ?? 80 });
1860
- useEffect3(() => {
2580
+ const [size, setSize] = useState5({ rows: stdout?.rows ?? 24, columns: stdout?.columns ?? 80 });
2581
+ useEffect4(() => {
1861
2582
  if (!stdout) return;
1862
2583
  const onResize = () => setSize({ rows: stdout.rows ?? 24, columns: stdout.columns ?? 80 });
1863
2584
  stdout.on("resize", onResize);
@@ -1868,11 +2589,14 @@ function useTerminalSize() {
1868
2589
  return size;
1869
2590
  }
1870
2591
  var HELP = [
1871
- "/project \u2014 switch project /gezel \u2014 switch gezel /model \u2014 switch engine + model",
2592
+ "/project \u2014 switch project /model \u2014 switch engine + model",
2593
+ "/gezel \u2014 switch gezel or bring on a role /gezel <role or name> \u2014 go straight there",
1872
2594
  "/model download \u2014 choose and download a new on-device model",
1873
2595
  "/allow edits \u2014 allow tool edits /disallow edits \u2014 make tool edits read-only",
1874
2596
  "/allow codexedits|claudeedits \u2014 allow provider-native project edits",
1875
2597
  "/disallow codexedits|claudeedits \u2014 put that provider in read-only plan mode",
2598
+ "/show thinking \u2014 show model reasoning inline /hide thinking \u2014 hide it",
2599
+ "/show writes \u2014 stream write contents inline /hide writes \u2014 hide them (default)",
1876
2600
  "/mode \u2014 choose read-only, reactive, reactive+tasks, or full-play AI activity",
1877
2601
  "/thread \u2014 switch or start a chat thread",
1878
2602
  "/open workspace|artifacts|<recent file> \u2014 open a folder or file from chat",
@@ -1889,47 +2613,52 @@ var READ_ONLY_BOOT_NOTE = "Note: this folder is read-only to gezel, and can be u
1889
2613
  function App(props) {
1890
2614
  const { client } = props;
1891
2615
  const { exit } = useApp();
1892
- const [config, setConfig] = useState4(null);
1893
- const [gezels, setGezels] = useState4([]);
1894
- const [projects, setProjects] = useState4([]);
1895
- const [threads, setThreads] = useState4([]);
1896
- const [tasks, setTasks] = useState4([]);
1897
- const [craftbooks, setCraftbooks] = useState4([]);
1898
- const [craftbookProjectType, setCraftbookProjectType] = useState4(null);
1899
- const [suggestedCraftbookIds, setSuggestedCraftbookIds] = useState4(() => /* @__PURE__ */ new Set());
1900
- const [craftbooksNeedingSetup, setCraftbooksNeedingSetup] = useState4(
2616
+ const [config, setConfig] = useState5(null);
2617
+ const [gezels, setGezels] = useState5([]);
2618
+ const [projects, setProjects] = useState5([]);
2619
+ const [threads, setThreads] = useState5([]);
2620
+ const [tasks, setTasks] = useState5([]);
2621
+ const [craftbooks, setCraftbooks] = useState5([]);
2622
+ const [craftbookProjectType, setCraftbookProjectType] = useState5(null);
2623
+ const [suggestedCraftbookIds, setSuggestedCraftbookIds] = useState5(() => /* @__PURE__ */ new Set());
2624
+ const [craftbooksNeedingSetup, setCraftbooksNeedingSetup] = useState5(
1901
2625
  () => /* @__PURE__ */ new Set()
1902
2626
  );
1903
- const [startCategoryId, setStartCategoryId] = useState4(null);
1904
- const [modelChoices, setModelChoices] = useState4([]);
1905
- const [modelDownloadChoices, setModelDownloadChoices] = useState4([]);
1906
- const [modelDownloadProgress, setModelDownloadProgress] = useState4(
2627
+ const [startCategoryId, setStartCategoryId] = useState5(null);
2628
+ const [modelChoices, setModelChoices] = useState5([]);
2629
+ const [modelDownloadChoices, setModelDownloadChoices] = useState5([]);
2630
+ const [modelDownloadProgress, setModelDownloadProgress] = useState5(
1907
2631
  null
1908
2632
  );
1909
- const [modelDownloadReturn, setModelDownloadReturn] = useState4(null);
1910
- const [modelChoicesLoading, setModelChoicesLoading] = useState4(false);
1911
- const [threadsLoading, setThreadsLoading] = useState4(false);
1912
- const [pendingQuestions, setPendingQuestions] = useState4([]);
1913
- const [projectId, setProjectId] = useState4(props.initialProjectId);
1914
- const [projectName, setProjectName] = useState4(props.initialProjectName);
1915
- const [activeGezelId, setActiveGezelId] = useState4(null);
1916
- const [ownSessionId, setOwnSessionId] = useState4(null);
1917
- const [focusedSessionId, setFocusedSessionId] = useState4(null);
1918
- const [activeThreadTitle, setActiveThreadTitle] = useState4(null);
1919
- const [mode, setMode] = useState4("chat");
1920
- const [overlay, setOverlay] = useState4(null);
1921
- const [value, setValue] = useState4("");
1922
- const [rows, setRows] = useState4([]);
1923
- const [turns, setTurns] = useState4(() => /* @__PURE__ */ new Map());
1924
- const [recentOpenReferences, setRecentOpenReferences] = useState4([]);
1925
- const recentOpenReferencesRef = useRef2([]);
1926
- const [status, setStatus] = useState4("Connecting\u2026");
1927
- const [history, setHistory] = useState4([]);
1928
- const [activeRuns, setActiveRuns] = useState4(() => /* @__PURE__ */ new Set());
1929
- const [pendingInput, setPendingInput] = useState4(null);
1930
- const [managedTaskRef, setManagedTaskRef] = useState4(null);
1931
- const [taskPrompt, setTaskPrompt] = useState4(null);
1932
- const [exitArmed, setExitArmed] = useState4(false);
2633
+ const [modelDownloadReturn, setModelDownloadReturn] = useState5(null);
2634
+ const [modelChoicesLoading, setModelChoicesLoading] = useState5(false);
2635
+ const [threadsLoading, setThreadsLoading] = useState5(false);
2636
+ const [gezelPickerItems, setGezelPickerItems] = useState5([]);
2637
+ const [roleTemplates, setRoleTemplates] = useState5([]);
2638
+ const [pendingQuestions, setPendingQuestions] = useState5([]);
2639
+ const [projectId, setProjectId] = useState5(props.initialProjectId);
2640
+ const [projectName, setProjectName] = useState5(props.initialProjectName);
2641
+ const [activeGezelId, setActiveGezelId] = useState5(null);
2642
+ const [ownSessionId, setOwnSessionId] = useState5(null);
2643
+ const [focusedSessionId, setFocusedSessionId] = useState5(null);
2644
+ const [activeThreadTitle, setActiveThreadTitle] = useState5(null);
2645
+ const [mode, setMode] = useState5("chat");
2646
+ const [overlay, setOverlay] = useState5(null);
2647
+ const [value, setValue] = useState5("");
2648
+ const [rows, setRows, setRowsBuffered] = useBufferedState([], 50);
2649
+ const [turns, setTurns, setTurnsBuffered] = useBufferedState(() => /* @__PURE__ */ new Map(), 50);
2650
+ const [recentOpenReferences, setRecentOpenReferences] = useState5([]);
2651
+ const recentOpenReferencesRef = useRef3([]);
2652
+ const [status, setStatus] = useState5("Connecting\u2026");
2653
+ const [history, setHistory] = useState5([]);
2654
+ const [activeRuns, setActiveRuns] = useState5(() => /* @__PURE__ */ new Set());
2655
+ const [pendingInput, setPendingInput] = useState5(null);
2656
+ const [managedTaskRef, setManagedTaskRef] = useState5(null);
2657
+ const [taskPrompt, setTaskPrompt] = useState5(null);
2658
+ const [exitArmed, setExitArmed] = useState5(false);
2659
+ useEffect4(() => {
2660
+ props.diagnostics?.recordReactCommit();
2661
+ });
1933
2662
  const pendingQuestion = pendingQuestions[0];
1934
2663
  const { rows: termRows, columns: termColumns } = useTerminalSize();
1935
2664
  const shellColumns = Math.min(500, Math.max(20, termColumns - 2));
@@ -1937,7 +2666,8 @@ function App(props) {
1937
2666
  const wordwheelRows = wordwheelCount > 0 ? Math.min(SLASH_COMMAND_WORDWHEEL_SIZE, wordwheelCount) + 1 : 0;
1938
2667
  const questionRows = pendingQuestion ? Math.min(QUESTION_OPTION_WINDOW_SIZE, Math.max(1, questionOptionCount(pendingQuestion))) + 4 : 0;
1939
2668
  const modelPickerWindowSize = Math.max(4, Math.min(10, termRows - 12));
1940
- const inventoryPickerRows = overlay === "model" || overlay === "model-download" || overlay === "start-category" || overlay === "start-craftbook" ? modelPickerWindowSize + 5 : 0;
2669
+ const gezelPickerWindowSize = Math.max(4, Math.min(10, termRows - 17));
2670
+ const inventoryPickerRows = overlay === "model" || overlay === "model-download" || overlay === "start-category" || overlay === "start-craftbook" ? modelPickerWindowSize + 5 : overlay === "gezel" ? gezelPickerWindowSize + 10 : 0;
1941
2671
  const visibleRows = Math.max(
1942
2672
  4,
1943
2673
  termRows - 7 - wordwheelRows - questionRows - inventoryPickerRows
@@ -1955,20 +2685,20 @@ function App(props) {
1955
2685
  const turn = focusedSessionId && turns.get(focusedSessionId) || ownSessionId && turns.get(ownSessionId) || turns.values().next().value;
1956
2686
  return turn?.label;
1957
2687
  }, [turns, focusedSessionId, ownSessionId]);
1958
- const note = useCallback(
2688
+ const note = useCallback2(
1959
2689
  (text, kind = "note") => setRows((r) => appendNote(r, text, kind)),
1960
- []
2690
+ [setRows]
1961
2691
  );
1962
- useEffect3(() => {
2692
+ useEffect4(() => {
1963
2693
  recentOpenReferencesRef.current = recentOpenReferences;
1964
2694
  }, [recentOpenReferences]);
1965
- const gezelIds = useRef2(/* @__PURE__ */ new Set());
1966
- const gezelRefreshInFlight = useRef2(false);
1967
- const applyGezelSnapshot = useCallback((next) => {
2695
+ const gezelIds = useRef3(/* @__PURE__ */ new Set());
2696
+ const gezelRefreshInFlight = useRef3(false);
2697
+ const applyGezelSnapshot = useCallback2((next) => {
1968
2698
  gezelIds.current = new Set(next.map((gezel) => gezel.id));
1969
2699
  setGezels(next);
1970
2700
  }, []);
1971
- const refreshGezels = useCallback(async () => {
2701
+ const refreshGezels = useCallback2(async () => {
1972
2702
  if (gezelRefreshInFlight.current) return;
1973
2703
  gezelRefreshInFlight.current = true;
1974
2704
  try {
@@ -1979,8 +2709,8 @@ function App(props) {
1979
2709
  gezelRefreshInFlight.current = false;
1980
2710
  }
1981
2711
  }, [applyGezelSnapshot, client]);
1982
- const taskLoadSequence = useRef2(0);
1983
- const refreshTasks = useCallback(async () => {
2712
+ const taskLoadSequence = useRef3(0);
2713
+ const refreshTasks = useCallback2(async () => {
1984
2714
  const sequence = ++taskLoadSequence.current;
1985
2715
  try {
1986
2716
  const res = await client.listProjectTasks(projectId);
@@ -1989,8 +2719,8 @@ function App(props) {
1989
2719
  } catch {
1990
2720
  }
1991
2721
  }, [client, projectId]);
1992
- const craftbookLoadSequence = useRef2(0);
1993
- const refreshCraftbooks = useCallback(async () => {
2722
+ const craftbookLoadSequence = useRef3(0);
2723
+ const refreshCraftbooks = useCallback2(async () => {
1994
2724
  const sequence = ++craftbookLoadSequence.current;
1995
2725
  const result = await client.listProjectCraftbooks(projectId);
1996
2726
  if (sequence !== craftbookLoadSequence.current) return [];
@@ -2004,10 +2734,19 @@ function App(props) {
2004
2734
  useProjectEvents(
2005
2735
  client,
2006
2736
  projectId,
2007
- useCallback(
2737
+ useCallback2(
2008
2738
  (env) => {
2009
- setRows((r) => reduceFeed(r, env));
2010
- setTurns((t) => reduceTurns(t, env));
2739
+ props.diagnostics?.recordChatEvent(env);
2740
+ const streaming = env.event.type === "delta" || env.event.type === "reasoning_delta" || env.event.type === "tool_args_delta";
2741
+ const updateRows = streaming ? setRowsBuffered : setRows;
2742
+ const updateTurns = streaming ? setTurnsBuffered : setTurns;
2743
+ updateRows(
2744
+ (r) => reduceFeed(r, env, {
2745
+ showThinking: config?.cliShowThinking !== false,
2746
+ showWrites: config?.cliShowWrites === true
2747
+ })
2748
+ );
2749
+ updateTurns((t) => reduceTurns(t, env));
2011
2750
  const observedReferences = cliOpenReferencesFromEvent(env);
2012
2751
  if (observedReferences.length > 0) {
2013
2752
  setRecentOpenReferences(
@@ -2031,43 +2770,58 @@ function App(props) {
2031
2770
  setPendingQuestions((questions) => updatePendingQuestion(questions, question));
2032
2771
  }
2033
2772
  },
2034
- [ownSessionId, refreshGezels, refreshTasks]
2773
+ [
2774
+ config?.cliShowThinking,
2775
+ config?.cliShowWrites,
2776
+ ownSessionId,
2777
+ props.diagnostics,
2778
+ refreshGezels,
2779
+ refreshTasks,
2780
+ setRows,
2781
+ setRowsBuffered,
2782
+ setTurns,
2783
+ setTurnsBuffered
2784
+ ]
2035
2785
  )
2036
2786
  );
2037
2787
  useTerminalEvents(
2038
2788
  client,
2039
2789
  projectId,
2040
- useCallback((env) => {
2041
- switch (env.kind) {
2042
- case "runStarted":
2043
- setActiveRuns((s) => new Set(s).add(env.runId));
2044
- return;
2045
- case "outputChunk":
2046
- setRows((r) => appendShellChunk(r, env.runId, env.chunk));
2047
- return;
2048
- case "inputRequested":
2049
- setPendingInput({ runId: env.runId, mode: env.mode, promptLine: env.promptLine });
2050
- setRows((r) => appendNote(r, `\u2328 waiting for input \u2014 ${env.promptLine}`, "note"));
2051
- return;
2052
- case "message": {
2053
- const runId = env.runId;
2054
- if (!runId) return;
2055
- setActiveRuns((s) => {
2056
- if (!s.has(runId)) return s;
2057
- const n = new Set(s);
2058
- n.delete(runId);
2059
- return n;
2060
- });
2061
- setPendingInput((p) => p?.runId === runId ? null : p);
2062
- setRows((r) => finalizeShellRun(r, runId, env.message));
2063
- return;
2790
+ useCallback2(
2791
+ (env) => {
2792
+ props.diagnostics?.recordTerminalEvent(env);
2793
+ switch (env.kind) {
2794
+ case "runStarted":
2795
+ setActiveRuns((s) => new Set(s).add(env.runId));
2796
+ return;
2797
+ case "outputChunk":
2798
+ setRowsBuffered((r) => appendShellChunk(r, env.runId, env.chunk));
2799
+ return;
2800
+ case "inputRequested":
2801
+ setPendingInput({ runId: env.runId, mode: env.mode, promptLine: env.promptLine });
2802
+ setRows((r) => appendNote(r, `\u2328 waiting for input \u2014 ${env.promptLine}`, "note"));
2803
+ return;
2804
+ case "message": {
2805
+ const runId = env.runId;
2806
+ if (!runId) return;
2807
+ setActiveRuns((s) => {
2808
+ if (!s.has(runId)) return s;
2809
+ const n = new Set(s);
2810
+ n.delete(runId);
2811
+ return n;
2812
+ });
2813
+ setPendingInput((p) => p?.runId === runId ? null : p);
2814
+ setRows((r) => finalizeShellRun(r, runId, env.message));
2815
+ return;
2816
+ }
2817
+ default:
2818
+ return;
2064
2819
  }
2065
- default:
2066
- return;
2067
- }
2068
- }, [])
2820
+ },
2821
+ [props.diagnostics, setRows, setRowsBuffered]
2822
+ )
2069
2823
  );
2070
- const ensureSession = useCallback(
2824
+ const ensureSession = useCallback2(
2071
2825
  async (gezelId, pid) => {
2072
2826
  try {
2073
2827
  const session = await client.createChatSession({
@@ -2086,7 +2840,7 @@ function App(props) {
2086
2840
  },
2087
2841
  [client, note, boring]
2088
2842
  );
2089
- const switchProject = useCallback(
2843
+ const switchProject = useCallback2(
2090
2844
  async (id) => {
2091
2845
  setOverlay(null);
2092
2846
  const project = projects.find((candidate) => candidate.id === id);
@@ -2117,9 +2871,122 @@ function App(props) {
2117
2871
  note(`could not switch project: ${errMsg(err)}`, "error");
2118
2872
  }
2119
2873
  },
2120
- [client, ensureSession, note, projectId, projects]
2874
+ [client, ensureSession, note, projectId, projects, setRows, setTurns]
2121
2875
  );
2122
- const openModelPicker = useCallback(async () => {
2876
+ const loadRoleTemplates = useCallback2(async () => {
2877
+ if (roleTemplates.length > 0) return roleTemplates;
2878
+ try {
2879
+ const { items } = await client.listCatalogItems("gezel-template");
2880
+ const byId = /* @__PURE__ */ new Map();
2881
+ for (const item of items) {
2882
+ const manifest = item.manifest;
2883
+ if (manifest.kind !== "gezel-template" || byId.has(manifest.id)) continue;
2884
+ byId.set(manifest.id, {
2885
+ id: manifest.id,
2886
+ name: manifest.name,
2887
+ role: manifest.role,
2888
+ description: manifest.description
2889
+ });
2890
+ }
2891
+ const loaded = [...byId.values()];
2892
+ setRoleTemplates(loaded);
2893
+ return loaded;
2894
+ } catch (err) {
2895
+ note(`could not load the role catalog: ${errMsg(err)}`, "error");
2896
+ return [];
2897
+ }
2898
+ }, [client, note, roleTemplates]);
2899
+ const promoteSoloProject = useCallback2(
2900
+ async (joinedGezelId) => {
2901
+ try {
2902
+ const project = await client.getProject(projectId);
2903
+ if (project.mode !== "solo") return;
2904
+ if (project.voormanGezelId === joinedGezelId) return;
2905
+ await client.updateProject(projectId, { mode: "crew" });
2906
+ note("this job is now a crew project \u2014 gezels here can delegate and recruit.");
2907
+ } catch (err) {
2908
+ note(`could not switch this job to a crew project: ${errMsg(err)}`, "error");
2909
+ }
2910
+ },
2911
+ [client, note, projectId]
2912
+ );
2913
+ const useGezel = useCallback2(
2914
+ async (gezelId) => {
2915
+ if (gezelId === activeGezelId) return;
2916
+ try {
2917
+ const { added } = await client.addGezelToProject(projectId, gezelId);
2918
+ if (added) await promoteSoloProject(gezelId);
2919
+ } catch (err) {
2920
+ note(`could not add to the project roster: ${errMsg(err)}`, "error");
2921
+ }
2922
+ setActiveGezelId(gezelId);
2923
+ setThreads([]);
2924
+ setActiveThreadTitle(null);
2925
+ await ensureSession(gezelId, projectId);
2926
+ },
2927
+ [activeGezelId, client, ensureSession, note, projectId, promoteSoloProject]
2928
+ );
2929
+ const recruitGezel = useCallback2(
2930
+ async (templateId) => {
2931
+ note(`recruiting ${templateId}\u2026`);
2932
+ try {
2933
+ const { name, gender } = pickRandomNameWithGender2();
2934
+ const gezel = await client.createGezelFromTemplate(templateId, { name, gender });
2935
+ await refreshGezels();
2936
+ note(`${gezel.name} joined the project as ${gezel.role ?? templateId}.`);
2937
+ await useGezel(gezel.id);
2938
+ } catch (err) {
2939
+ note(`could not recruit ${templateId}: ${errMsg(err)}`, "error");
2940
+ }
2941
+ },
2942
+ [client, note, refreshGezels, useGezel]
2943
+ );
2944
+ const openGezelPicker = useCallback2(async () => {
2945
+ const templates = await loadRoleTemplates();
2946
+ let project = null;
2947
+ try {
2948
+ project = await client.getProject(projectId);
2949
+ } catch {
2950
+ }
2951
+ setGezelPickerItems(
2952
+ buildGezelPickerItems({
2953
+ gezels,
2954
+ templates,
2955
+ memberIds: [
2956
+ // Without the project record we only know the gezel we are talking
2957
+ // to. Claiming the whole roster is "in this project" would be a
2958
+ // guess the header presents as fact.
2959
+ ...project?.gezelIds ?? (activeGezelId ? [activeGezelId] : []),
2960
+ ...project?.voormanGezelId ? [project.voormanGezelId] : []
2961
+ ],
2962
+ ...project ? { project } : {},
2963
+ roleBasedNameOnly: boring,
2964
+ hintWidth: Math.max(24, shellColumns - 34)
2965
+ })
2966
+ );
2967
+ setOverlay("gezel");
2968
+ }, [activeGezelId, boring, client, gezels, loadRoleTemplates, projectId, shellColumns]);
2969
+ const ensureGezelByName = useCallback2(
2970
+ async (arg) => {
2971
+ const templates = await loadRoleTemplates();
2972
+ const resolved = resolveGezelArg(arg, { gezels, templates });
2973
+ switch (resolved.kind) {
2974
+ case "gezel":
2975
+ return useGezel(resolved.gezelId);
2976
+ case "template":
2977
+ return recruitGezel(resolved.templateId);
2978
+ case "ambiguous":
2979
+ return note(
2980
+ `"${arg}" matches ${resolved.labels.join(", ")} \u2014 be more specific.`,
2981
+ "error"
2982
+ );
2983
+ default:
2984
+ return note(`no gezel or role matches "${arg}". Type /gezel to browse.`, "error");
2985
+ }
2986
+ },
2987
+ [gezels, loadRoleTemplates, note, recruitGezel, useGezel]
2988
+ );
2989
+ const openModelPicker = useCallback2(async () => {
2123
2990
  if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2124
2991
  if (activeGezel.fixedFunction) {
2125
2992
  return note("this gezel runs a fixed tool and does not use a chat model.", "error");
@@ -2137,7 +3004,7 @@ function App(props) {
2137
3004
  setModelChoicesLoading(false);
2138
3005
  }
2139
3006
  }, [activeGezel, activeGezelId, client, config, modelChoicesLoading, note]);
2140
- const openModelDownloadPicker = useCallback(
3007
+ const openModelDownloadPicker = useCallback2(
2141
3008
  async (returnTo = null) => {
2142
3009
  if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2143
3010
  if (activeGezel.fixedFunction) {
@@ -2169,7 +3036,7 @@ function App(props) {
2169
3036
  },
2170
3037
  [activeGezel, activeGezelId, client, config, modelChoicesLoading, note, openModelPicker]
2171
3038
  );
2172
- const openThreadPicker = useCallback(async () => {
3039
+ const openThreadPicker = useCallback2(async () => {
2173
3040
  if (!activeGezelId) return note("no active gezel yet.", "error");
2174
3041
  if (threadsLoading) return;
2175
3042
  setThreadsLoading(true);
@@ -2183,7 +3050,7 @@ function App(props) {
2183
3050
  setThreadsLoading(false);
2184
3051
  }
2185
3052
  }, [activeGezelId, client, note, projectId, threadsLoading]);
2186
- const switchThread = useCallback(
3053
+ const switchThread = useCallback2(
2187
3054
  async (sessionId) => {
2188
3055
  setOverlay(null);
2189
3056
  try {
@@ -2194,15 +3061,15 @@ function App(props) {
2194
3061
  setOwnSessionId(session.id);
2195
3062
  setFocusedSessionId(session.id);
2196
3063
  setActiveThreadTitle(displayThreadTitle(session.title));
2197
- setRows(sessionToFeedRows(session));
3064
+ setRows(sessionToFeedRows(session, { showThinking: config?.cliShowThinking !== false }));
2198
3065
  setRecentOpenReferences(cliOpenReferencesFromSession(session));
2199
3066
  } catch (err) {
2200
3067
  note(`could not switch thread: ${errMsg(err)}`, "error");
2201
3068
  }
2202
3069
  },
2203
- [activeGezelId, client, note, projectId]
3070
+ [activeGezelId, client, config?.cliShowThinking, note, projectId, setRows]
2204
3071
  );
2205
- const startNewThread = useCallback(async () => {
3072
+ const startNewThread = useCallback2(async () => {
2206
3073
  setOverlay(null);
2207
3074
  if (!activeGezelId) return note("no active gezel yet.", "error");
2208
3075
  try {
@@ -2220,8 +3087,8 @@ function App(props) {
2220
3087
  } catch (err) {
2221
3088
  note(`could not start a thread: ${errMsg(err)}`, "error");
2222
3089
  }
2223
- }, [activeGezelId, client, note, projectId, boring]);
2224
- useEffect3(() => {
3090
+ }, [activeGezelId, boring, client, note, projectId, setRows]);
3091
+ useEffect4(() => {
2225
3092
  let cancelled = false;
2226
3093
  (async () => {
2227
3094
  try {
@@ -2266,25 +3133,25 @@ function App(props) {
2266
3133
  cancelled = true;
2267
3134
  };
2268
3135
  }, []);
2269
- useEffect3(() => {
3136
+ useEffect4(() => {
2270
3137
  let cancelled = false;
2271
3138
  setPendingQuestions([]);
2272
3139
  void client.listQuestions({ projectId, pending: true }).then((result) => {
2273
- if (!cancelled) setPendingQuestions(plainPendingQuestions(result.questions));
3140
+ if (!cancelled) setPendingQuestions(pendingQuestionsForTui(result.questions));
2274
3141
  }).catch(() => {
2275
3142
  });
2276
3143
  return () => {
2277
3144
  cancelled = true;
2278
3145
  };
2279
3146
  }, [client, projectId]);
2280
- useEffect3(() => {
3147
+ useEffect4(() => {
2281
3148
  void refreshTasks();
2282
3149
  const id = setInterval(() => void refreshTasks(), 3e4);
2283
3150
  return () => {
2284
3151
  clearInterval(id);
2285
3152
  };
2286
3153
  }, [refreshTasks]);
2287
- useEffect3(() => {
3154
+ useEffect4(() => {
2288
3155
  void refreshCraftbooks().catch(() => {
2289
3156
  });
2290
3157
  }, [refreshCraftbooks]);
@@ -2341,7 +3208,7 @@ function App(props) {
2341
3208
  }
2342
3209
  return items;
2343
3210
  }, [rows, gezels, ownSessionId, gezelLine, boring]);
2344
- const cancelActive = useCallback(async () => {
3211
+ const cancelActive = useCallback2(async () => {
2345
3212
  const sessions = [...turns.keys()];
2346
3213
  const runs = [...activeRuns];
2347
3214
  if (sessions.length === 0 && runs.length === 0) return false;
@@ -2351,10 +3218,10 @@ function App(props) {
2351
3218
  ]);
2352
3219
  return true;
2353
3220
  }, [turns, activeRuns, client, projectId]);
2354
- const rememberTask = useCallback((task) => {
3221
+ const rememberTask = useCallback2((task) => {
2355
3222
  setTasks((current) => sortTasks([...current.filter((item) => item.ref !== task.ref), task]));
2356
3223
  }, []);
2357
- const applyEngagementMode = useCallback(
3224
+ const applyEngagementMode = useCallback2(
2358
3225
  async (requested) => {
2359
3226
  const next = parseCliEngagementMode(requested);
2360
3227
  if (!next) {
@@ -2373,7 +3240,7 @@ function App(props) {
2373
3240
  },
2374
3241
  [client, note]
2375
3242
  );
2376
- const applyProjectPermission = useCallback(
3243
+ const applyProjectPermission = useCallback2(
2377
3244
  async (permission, allowed) => {
2378
3245
  const permissionName = parseProjectPermissionName(permission);
2379
3246
  if (!permissionName) {
@@ -2404,7 +3271,38 @@ function App(props) {
2404
3271
  },
2405
3272
  [client, note, projectId, projectName]
2406
3273
  );
2407
- const startCraftbook = useCallback(
3274
+ const applyChatDetailVisibility = useCallback2(
3275
+ async (requested, visible) => {
3276
+ const target = requested.trim().toLowerCase();
3277
+ if (target !== "thinking" && target !== "writes") {
3278
+ note(`usage: /${visible ? "show" : "hide"} thinking|writes`, "error");
3279
+ return;
3280
+ }
3281
+ try {
3282
+ const updated = await client.updateConfig(
3283
+ target === "thinking" ? { cliShowThinking: visible } : { cliShowWrites: visible }
3284
+ );
3285
+ setConfig(updated);
3286
+ if (!visible) {
3287
+ const kind = target === "thinking" ? "thinking" : "write";
3288
+ setRows((current) => current.filter((row) => row.kind !== kind));
3289
+ }
3290
+ if (target === "thinking") {
3291
+ note(
3292
+ visible ? "Thinking is now shown inline." : "Thinking is now hidden. The live token count still includes it."
3293
+ );
3294
+ } else {
3295
+ note(
3296
+ visible ? "Write content is now shown inline as it streams." : "Write content is now hidden. Tool token counts remain visible."
3297
+ );
3298
+ }
3299
+ } catch (err) {
3300
+ note(`could not ${visible ? "show" : "hide"} ${target}: ${errMsg(err)}`, "error");
3301
+ }
3302
+ },
3303
+ [client, note, setRows]
3304
+ );
3305
+ const startCraftbook = useCallback2(
2408
3306
  async (book) => {
2409
3307
  setOverlay(null);
2410
3308
  note(`starting ${book.name}\u2026`);
@@ -2422,7 +3320,7 @@ function App(props) {
2422
3320
  },
2423
3321
  [boring, client, note, projectId, rememberTask]
2424
3322
  );
2425
- const submitTaskPrompt = useCallback(
3323
+ const submitTaskPrompt = useCallback2(
2426
3324
  async (raw) => {
2427
3325
  const prompt = taskPrompt;
2428
3326
  if (!prompt) return;
@@ -2461,7 +3359,7 @@ function App(props) {
2461
3359
  },
2462
3360
  [boring, client, note, projectId, rememberTask, taskPrompt, tasks]
2463
3361
  );
2464
- const applyTaskStatus = useCallback(
3362
+ const applyTaskStatus = useCallback2(
2465
3363
  async (status2) => {
2466
3364
  const task = managedTask;
2467
3365
  if (!task) return setOverlay("task");
@@ -2477,7 +3375,7 @@ function App(props) {
2477
3375
  },
2478
3376
  [client, managedTask, note, rememberTask]
2479
3377
  );
2480
- const applyTaskAssignee = useCallback(
3378
+ const applyTaskAssignee = useCallback2(
2481
3379
  async (value2) => {
2482
3380
  const task = managedTask;
2483
3381
  if (!task) return setOverlay("task");
@@ -2497,7 +3395,7 @@ function App(props) {
2497
3395
  },
2498
3396
  [client, managedTask, note, rememberTask]
2499
3397
  );
2500
- const runInput = useCallback(
3398
+ const runInput = useCallback2(
2501
3399
  async (raw) => {
2502
3400
  if (pendingInput) {
2503
3401
  const target = pendingInput;
@@ -2594,7 +3492,7 @@ function App(props) {
2594
3492
  turns
2595
3493
  ]
2596
3494
  );
2597
- const runCommand = useCallback(
3495
+ const runCommand = useCallback2(
2598
3496
  async (name, rest) => {
2599
3497
  switch (name) {
2600
3498
  case "help":
@@ -2603,14 +3501,23 @@ function App(props) {
2603
3501
  return;
2604
3502
  case "project":
2605
3503
  return setOverlay("project");
2606
- case "gezel":
2607
- return setOverlay("gezel");
3504
+ case "gezel": {
3505
+ const target = rest.trim();
3506
+ if (target) return ensureGezelByName(target);
3507
+ return openGezelPicker();
3508
+ }
2608
3509
  case "allow":
2609
3510
  await applyProjectPermission(rest, true);
2610
3511
  return;
2611
3512
  case "disallow":
2612
3513
  await applyProjectPermission(rest, false);
2613
3514
  return;
3515
+ case "show":
3516
+ await applyChatDetailVisibility(rest, true);
3517
+ return;
3518
+ case "hide":
3519
+ await applyChatDetailVisibility(rest, false);
3520
+ return;
2614
3521
  case "mode":
2615
3522
  if (!rest.trim()) return setOverlay("engagement-mode");
2616
3523
  await applyEngagementMode(rest);
@@ -2775,10 +3682,13 @@ function App(props) {
2775
3682
  [
2776
3683
  applyEngagementMode,
2777
3684
  applyProjectPermission,
3685
+ applyChatDetailVisibility,
2778
3686
  client,
2779
3687
  craftbooks,
3688
+ ensureGezelByName,
2780
3689
  note,
2781
3690
  exit,
3691
+ openGezelPicker,
2782
3692
  openModelDownloadPicker,
2783
3693
  openModelPicker,
2784
3694
  openThreadPicker,
@@ -2786,10 +3696,12 @@ function App(props) {
2786
3696
  projectName,
2787
3697
  refreshCraftbooks,
2788
3698
  refreshTasks,
3699
+ setRows,
3700
+ setTurns,
2789
3701
  startCraftbook
2790
3702
  ]
2791
3703
  );
2792
- const applyModelSelection = useCallback(
3704
+ const applyModelSelection = useCallback2(
2793
3705
  async (choice) => {
2794
3706
  setOverlay(null);
2795
3707
  if (!activeGezelId || !activeGezel || !config) return;
@@ -2819,17 +3731,21 @@ function App(props) {
2819
3731
  },
2820
3732
  [activeGezel, activeGezelId, client, config, ensureSession, note, projectId]
2821
3733
  );
2822
- const applyModelChoice = useCallback(
3734
+ const applyModelChoice = useCallback2(
2823
3735
  async (value2) => {
2824
3736
  await applyModelSelection(modelChoices.find((item) => item.value === value2));
2825
3737
  },
2826
3738
  [applyModelSelection, modelChoices]
2827
3739
  );
2828
- const installModelDownload = useCallback(
3740
+ const installModelDownload = useCallback2(
2829
3741
  async (value2) => {
2830
3742
  const choice = modelDownloadChoices.find((candidate) => candidate.value === value2);
2831
3743
  if (!choice) return;
2832
3744
  let terminalError = null;
3745
+ const companionResult = {
3746
+ name: null,
3747
+ error: null
3748
+ };
2833
3749
  setModelDownloadProgress({
2834
3750
  choice,
2835
3751
  bytesWritten: 0,
@@ -2839,6 +3755,10 @@ function App(props) {
2839
3755
  });
2840
3756
  const onEvent = (event) => {
2841
3757
  if (event.type === "error") terminalError = event.error;
3758
+ if (event.type === "companion") {
3759
+ companionResult.name = event.name;
3760
+ if (event.error) companionResult.error = event.error;
3761
+ }
2842
3762
  const progress = readModelDownloadProgress(choice, event);
2843
3763
  if (progress) setModelDownloadProgress(progress);
2844
3764
  };
@@ -2863,7 +3783,17 @@ function App(props) {
2863
3783
  installedChoice
2864
3784
  ]);
2865
3785
  setModelDownloadProgress(null);
2866
- note(`downloaded ${choice.model.name}; switching this gezel to it\u2026`);
3786
+ if (companionResult.name && companionResult.error) {
3787
+ note(
3788
+ `downloaded ${choice.model.name}; ${companionResult.name} image reader could not be added: ${companionResult.error}. Switching this gezel to ${choice.model.name}\u2026`
3789
+ );
3790
+ } else if (companionResult.name) {
3791
+ note(
3792
+ `downloaded ${choice.model.name} with ${companionResult.name} for image reading; switching this gezel to it\u2026`
3793
+ );
3794
+ } else {
3795
+ note(`downloaded ${choice.model.name}; switching this gezel to it\u2026`);
3796
+ }
2867
3797
  await applyModelSelection(installedChoice);
2868
3798
  } catch (err) {
2869
3799
  setModelDownloadProgress(null);
@@ -2873,7 +3803,7 @@ function App(props) {
2873
3803
  },
2874
3804
  [applyModelSelection, client, modelDownloadChoices, note]
2875
3805
  );
2876
- const cancelModelDownload = useCallback(async () => {
3806
+ const cancelModelDownload = useCallback2(async () => {
2877
3807
  const progress = modelDownloadProgress;
2878
3808
  if (!progress) return;
2879
3809
  try {
@@ -2891,7 +3821,7 @@ function App(props) {
2891
3821
  else setOverlay(null);
2892
3822
  }
2893
3823
  }, [client, modelDownloadProgress, modelDownloadReturn, note, openModelPicker]);
2894
- const onSubmit = useCallback(
3824
+ const onSubmit = useCallback2(
2895
3825
  (raw) => {
2896
3826
  setValue("");
2897
3827
  const trimmed = raw.trim();
@@ -2902,7 +3832,7 @@ function App(props) {
2902
3832
  },
2903
3833
  [runInput, pendingInput, taskPrompt]
2904
3834
  );
2905
- const cancelActiveRef = useRef2(cancelActive);
3835
+ const cancelActiveRef = useRef3(cancelActive);
2906
3836
  cancelActiveRef.current = cancelActive;
2907
3837
  useInput4(
2908
3838
  (input, key) => {
@@ -2961,20 +3891,17 @@ function App(props) {
2961
3891
  overlay === "gezel" ? /* @__PURE__ */ jsx5(
2962
3892
  Picker,
2963
3893
  {
2964
- title: "Switch gezel",
2965
- items: gezels.map((g) => ({
2966
- label: boring ? g.roleBasedName ?? g.role ?? g.id : g.name,
2967
- value: g.id,
2968
- hint: g.role
2969
- })),
3894
+ title: "Switch gezel, or bring on a role",
3895
+ items: gezelPickerItems,
3896
+ windowSize: gezelPickerWindowSize,
2970
3897
  onCancel: () => setOverlay(null),
2971
- onSelect: (id) => {
3898
+ onSelect: (value2) => {
2972
3899
  setOverlay(null);
2973
- if (id === activeGezelId) return;
2974
- setActiveGezelId(id);
2975
- setThreads([]);
2976
- setActiveThreadTitle(null);
2977
- void ensureSession(id, projectId);
3900
+ if (value2.startsWith(TEMPLATE_VALUE_PREFIX)) {
3901
+ void recruitGezel(value2.slice(TEMPLATE_VALUE_PREFIX.length));
3902
+ return;
3903
+ }
3904
+ void useGezel(value2.slice(GEZEL_VALUE_PREFIX.length));
2978
3905
  }
2979
3906
  }
2980
3907
  ) : null,
@@ -3210,7 +4137,7 @@ function App(props) {
3210
4137
  active: pendingInput === null,
3211
4138
  onAnswered: (question) => {
3212
4139
  setPendingQuestions((questions) => updatePendingQuestion(questions, question));
3213
- setFocusedSessionId(question.sessionId);
4140
+ if (question.sessionId) setFocusedSessionId(question.sessionId);
3214
4141
  }
3215
4142
  },
3216
4143
  pendingQuestion.id
@@ -3242,15 +4169,17 @@ function App(props) {
3242
4169
  }
3243
4170
  function ModelDownloadProgressPanel(props) {
3244
4171
  const { progress, onCancel } = props;
4172
+ const companion = progress.companion;
3245
4173
  useInput4((input, key) => {
3246
4174
  if (key.escape || key.ctrl && input === "c") onCancel();
3247
4175
  });
3248
4176
  const transferred = progress.totalBytes ? `${formatModelBytes(progress.bytesWritten)} / ${formatModelBytes(progress.totalBytes)}` : formatModelBytes(progress.bytesWritten);
3249
4177
  return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
3250
- /* @__PURE__ */ jsxs6(Text6, { bold: true, color: "yellow", children: [
3251
- "Downloading ",
3252
- progress.choice.model.name
3253
- ] }),
4178
+ /* @__PURE__ */ jsx5(Text6, { bold: true, color: "yellow", children: companion ? `Adding image reader: ${companion.name}` : `Downloading ${progress.choice.model.name}` }),
4179
+ companion ? /* @__PURE__ */ jsxs6(Text6, { children: [
4180
+ progress.choice.model.name,
4181
+ " is ready. This separate helper reads images for it."
4182
+ ] }) : null,
3254
4183
  /* @__PURE__ */ jsxs6(Text6, { children: [
3255
4184
  progress.pct == null ? "Working\u2026" : `${progress.pct}%`,
3256
4185
  " \xB7 ",
@@ -3278,7 +4207,11 @@ function readModelDownloadProgress(choice, event) {
3278
4207
  bytesWritten: event.bytesWritten,
3279
4208
  totalBytes: event.totalBytes,
3280
4209
  pct: event.totalBytes > 0 ? Math.min(100, Math.floor(event.bytesWritten / event.totalBytes * 100)) : null,
3281
- phase: `downloading ${event.name}`
4210
+ companion: {
4211
+ kind: event.kind,
4212
+ id: event.id,
4213
+ name: event.name
4214
+ }
3282
4215
  };
3283
4216
  }
3284
4217
  return null;
@@ -3390,13 +4323,13 @@ function formatTaskDetails(task, gezels, boring) {
3390
4323
  // src/tui/components/BootstrapGate.tsx
3391
4324
  import { formatModelAttribution as formatModelAttribution3 } from "@bendyline/gezel";
3392
4325
  import { Box as Box7, Text as Text7, useApp as useApp2, useInput as useInput5 } from "ink";
3393
- import { useCallback as useCallback2, useEffect as useEffect4, useState as useState5 } from "react";
4326
+ import { useCallback as useCallback3, useEffect as useEffect5, useState as useState6 } from "react";
3394
4327
  import { Fragment as Fragment4, jsx as jsx6, jsxs as jsxs7 } from "react/jsx-runtime";
3395
4328
  var MAX_ALTERNATIVE_MODELS = 6;
3396
4329
  function BootstrapGate(props) {
3397
4330
  const { client, children } = props;
3398
4331
  const { exit } = useApp2();
3399
- const [screen, setScreen] = useState5({
4332
+ const [screen, setScreen] = useState6({
3400
4333
  kind: "loading",
3401
4334
  message: "Checking this device\u2026"
3402
4335
  });
@@ -3410,7 +4343,7 @@ function BootstrapGate(props) {
3410
4343
  // deliberate second-press exit.
3411
4344
  { isActive: screen.kind !== "ready" }
3412
4345
  );
3413
- const prepareModels = useCallback2(
4346
+ const prepareModels = useCallback3(
3414
4347
  async (context) => {
3415
4348
  setScreen({ kind: "loading", message: "Finding the best models for this device\u2026" });
3416
4349
  const installedChat = context.provider === "mlx" ? await client.listMlxModels() : await client.listLlamaCppModels();
@@ -3493,7 +4426,7 @@ function BootstrapGate(props) {
3493
4426
  },
3494
4427
  [client]
3495
4428
  );
3496
- const initialize = useCallback2(async () => {
4429
+ const initialize = useCallback3(async () => {
3497
4430
  try {
3498
4431
  setScreen({ kind: "loading", message: "Checking this device\u2026" });
3499
4432
  const [memory, chatCatalog] = await Promise.all([
@@ -3536,10 +4469,10 @@ function BootstrapGate(props) {
3536
4469
  });
3537
4470
  }
3538
4471
  }, [client, prepareModels]);
3539
- useEffect4(() => {
4472
+ useEffect5(() => {
3540
4473
  void initialize();
3541
4474
  }, [initialize]);
3542
- const installNative = useCallback2(
4475
+ const installNative = useCallback3(
3543
4476
  async (context, missing) => {
3544
4477
  const retry = () => void installNative(context, missing);
3545
4478
  if (!context.nativeStatus.pinned) {
@@ -3572,7 +4505,7 @@ function BootstrapGate(props) {
3572
4505
  },
3573
4506
  [client, prepareModels]
3574
4507
  );
3575
- const installModels = useCallback2(
4508
+ const installModels = useCallback3(
3576
4509
  async (plan, choice) => {
3577
4510
  if (choice.kind === "skip") {
3578
4511
  setScreen({ kind: "ready" });
@@ -3707,11 +4640,12 @@ function BootstrapGate(props) {
3707
4640
  0
3708
4641
  );
3709
4642
  const workshopDownloadBytes = accessoryBytes + (best && !bestInstalled ? best.approxSizeBytes : 0);
4643
+ const workshopHelperLabels = screen.plan.accessories.map(accessoryKindLabel).join(", ");
3710
4644
  const options = [
3711
4645
  ...best ? [
3712
4646
  {
3713
4647
  label: `Recommended workshop set \u2014 ${bootstrapChatModelLabel(best)} + ${screen.plan.accessories.length} helpers`,
3714
- hint: `${bestInstalled ? "chat model already available \xB7 " : ""}${workshopDownloadBytes > 0 ? formatDownloadSize(workshopDownloadBytes) : "already available"}`,
4648
+ hint: `${bestInstalled ? "chat model already available \xB7 " : ""}${workshopDownloadBytes > 0 ? formatDownloadSize(workshopDownloadBytes) : "already available"}${workshopHelperLabels ? ` \xB7 includes ${workshopHelperLabels}` : ""}`,
3715
4649
  value: "bundle"
3716
4650
  },
3717
4651
  {
@@ -3812,7 +4746,7 @@ function recoDevice(memory) {
3812
4746
  };
3813
4747
  }
3814
4748
  function BootstrapChoiceList(props) {
3815
- const [index, setIndex] = useState5(0);
4749
+ const [index, setIndex] = useState6(0);
3816
4750
  const options = props.options;
3817
4751
  useInput5((input, key) => {
3818
4752
  if (key.upArrow) {
@@ -3900,7 +4834,9 @@ async function installChatModel(client, model, onEvent) {
3900
4834
  if (model.provider === "mlx") {
3901
4835
  await client.installMlxModel(model.id, listener);
3902
4836
  } else {
3903
- await client.installLlamaCppModel(model.id, listener);
4837
+ await client.installLlamaCppModel(model.id, listener, void 0, {
4838
+ skipCompanion: true
4839
+ });
3904
4840
  }
3905
4841
  if (terminalError) throw new Error(terminalError);
3906
4842
  }
@@ -3934,7 +4870,24 @@ function updateDownloadProgress(setScreen, job, index, total, event, title = "Do
3934
4870
  } else if (event.type === "retrying" && "attempt" in event) {
3935
4871
  detail = `${job.label} \xB7 retrying ${event.attempt}/${event.maxAttempts}`;
3936
4872
  } else if (event.type === "verifying") {
4873
+ pct = 100;
3937
4874
  detail = `${job.label} \xB7 verifying`;
4875
+ } else if (event.type === "extracting-metadata") {
4876
+ pct = 100;
4877
+ detail = `${job.label} \xB7 reading model details`;
4878
+ } else if (event.type === "companion") {
4879
+ const name = "name" in event && typeof event.name === "string" ? event.name : "Image reader";
4880
+ const written = event.bytesWritten;
4881
+ const all = event.totalBytes;
4882
+ if (typeof written === "number" && typeof all === "number" && all > 0) {
4883
+ pct = Math.min(100, Math.floor(written / all * 100));
4884
+ detail = `${name} \xB7 image reader \xB7 ${formatDownloadSize(written)} of ${formatDownloadSize(all)}`;
4885
+ } else {
4886
+ detail = `${name} \xB7 image reader`;
4887
+ }
4888
+ if ("error" in event && typeof event.error === "string") {
4889
+ detail = `${name} \xB7 image reader unavailable: ${event.error}`;
4890
+ }
3938
4891
  } else if (event.type === "done") {
3939
4892
  pct = 100;
3940
4893
  detail = `${job.label} \xB7 ready`;
@@ -3973,6 +4926,20 @@ function nativeLabel(engine) {
3973
4926
  return "ds4";
3974
4927
  }
3975
4928
  }
4929
+ function accessoryKindLabel(model) {
4930
+ switch (model.kind) {
4931
+ case "image":
4932
+ return "image generator";
4933
+ case "recognition":
4934
+ return "image reader";
4935
+ case "stt":
4936
+ return "speech recognition";
4937
+ case "tts":
4938
+ return "voice";
4939
+ case "video":
4940
+ return "video generator";
4941
+ }
4942
+ }
3976
4943
  function fitLabel(fit) {
3977
4944
  if (fit === "fits-offload") return "fits with offload";
3978
4945
  if (fit === "fits") return "good fit";
@@ -3986,14 +4953,149 @@ function delay(ms) {
3986
4953
  return new Promise((resolve2) => setTimeout(resolve2, ms));
3987
4954
  }
3988
4955
 
4956
+ // src/tui/memory-diagnostics.ts
4957
+ import { appendFile, mkdir as mkdir2 } from "fs/promises";
4958
+ import { join as join2 } from "path";
4959
+ import { performance } from "perf_hooks";
4960
+ import { getHeapStatistics } from "v8";
4961
+ import { gezelHome, gezelPaths as gezelPaths2 } from "@bendyline/gezel/paths";
4962
+ var DEFAULT_SAMPLE_INTERVAL_MS = 15e3;
4963
+ var DEFAULT_MEASURE_LIMIT = 2e3;
4964
+ var DEFAULT_PRESSURE_HEAP_BYTES = 256 * 1024 * 1024;
4965
+ var DEFAULT_GROWTH_LOG_BYTES = 64 * 1024 * 1024;
4966
+ var COMMIT_CLEANUP_INTERVAL = 250;
4967
+ function clearRetainedPerformanceMeasures(timeline = performance, limit = DEFAULT_MEASURE_LIMIT) {
4968
+ const count = timeline.getEntriesByType("measure").length;
4969
+ if (count <= limit) return 0;
4970
+ timeline.clearMeasures();
4971
+ return count;
4972
+ }
4973
+ function startTuiRuntimeDiagnostics(options = {}) {
4974
+ const home = options.home ?? gezelHome();
4975
+ const logsDir = gezelPaths2(home).logs;
4976
+ const timeline = options.timeline ?? performance;
4977
+ const measureLimit = options.performanceMeasureLimit ?? DEFAULT_MEASURE_LIMIT;
4978
+ const pressureHeapBytes = options.pressureHeapBytes ?? DEFAULT_PRESSURE_HEAP_BYTES;
4979
+ const growthLogBytes = options.growthLogBytes ?? DEFAULT_GROWTH_LOG_BYTES;
4980
+ const alwaysLog = options.alwaysLog ?? process.env.GEZEL_TUI_MEMORY_DIAGNOSTICS?.trim() === "1";
4981
+ const eventTypes = {};
4982
+ const counters = {
4983
+ chatEvents: 0,
4984
+ streamFragments: 0,
4985
+ streamChars: 0,
4986
+ terminalEvents: 0,
4987
+ terminalChunks: 0,
4988
+ terminalChars: 0,
4989
+ reactCommits: 0
4990
+ };
4991
+ let stopped = false;
4992
+ let lastLoggedHeapUsed = 0;
4993
+ let peakHeapUsed = 0;
4994
+ let peakRss = 0;
4995
+ let writeChain = Promise.resolve();
4996
+ const sample = (phase, force = false, measuresCleared = 0) => {
4997
+ const memory = process.memoryUsage();
4998
+ const heap = getHeapStatistics();
4999
+ peakHeapUsed = Math.max(peakHeapUsed, memory.heapUsed);
5000
+ peakRss = Math.max(peakRss, memory.rss);
5001
+ const performanceMeasures = timeline.getEntriesByType("measure").length;
5002
+ const cleared = measuresCleared || clearRetainedPerformanceMeasures(timeline, measureLimit);
5003
+ const shouldWrite = force || alwaysLog || cleared > 0 || memory.heapUsed >= pressureHeapBytes || memory.heapUsed - lastLoggedHeapUsed >= growthLogBytes;
5004
+ if (!shouldWrite) return;
5005
+ lastLoggedHeapUsed = memory.heapUsed;
5006
+ const at = (/* @__PURE__ */ new Date()).toISOString();
5007
+ const record = {
5008
+ type: "tui.memory",
5009
+ version: 1,
5010
+ at,
5011
+ phase,
5012
+ pid: process.pid,
5013
+ nodeEnv: process.env.NODE_ENV ?? null,
5014
+ nodeVersion: process.version,
5015
+ uptimeMs: Math.round(process.uptime() * 1e3),
5016
+ memory: {
5017
+ rss: memory.rss,
5018
+ heapUsed: memory.heapUsed,
5019
+ heapTotal: memory.heapTotal,
5020
+ external: memory.external,
5021
+ arrayBuffers: memory.arrayBuffers,
5022
+ peakHeapUsed,
5023
+ peakRss,
5024
+ heapSizeLimit: heap.heap_size_limit,
5025
+ totalAvailableSize: heap.total_available_size,
5026
+ mallocedMemory: heap.malloced_memory,
5027
+ peakMallocedMemory: heap.peak_malloced_memory,
5028
+ nativeContexts: heap.number_of_native_contexts,
5029
+ detachedContexts: heap.number_of_detached_contexts
5030
+ },
5031
+ activeResources: countActiveResources(),
5032
+ performanceMeasures,
5033
+ measuresCleared: cleared,
5034
+ counters: { ...counters },
5035
+ eventTypes: { ...eventTypes }
5036
+ };
5037
+ const file = join2(logsDir, `tui-memory-${at.slice(0, 10)}.jsonl`);
5038
+ writeChain = writeChain.then(async () => {
5039
+ await mkdir2(logsDir, { recursive: true });
5040
+ await appendFile(file, `${JSON.stringify(record)}
5041
+ `, "utf8");
5042
+ }).catch(() => void 0);
5043
+ };
5044
+ sample("startup", true);
5045
+ const interval = setInterval(
5046
+ () => sample("interval"),
5047
+ options.intervalMs ?? DEFAULT_SAMPLE_INTERVAL_MS
5048
+ );
5049
+ interval.unref();
5050
+ return {
5051
+ recordChatEvent(env) {
5052
+ counters.chatEvents += 1;
5053
+ eventTypes[env.event.type] = (eventTypes[env.event.type] ?? 0) + 1;
5054
+ if (env.event.type === "delta" || env.event.type === "reasoning_delta" || env.event.type === "tool_args_delta") {
5055
+ counters.streamFragments += 1;
5056
+ counters.streamChars += env.event.content.length;
5057
+ }
5058
+ },
5059
+ recordTerminalEvent(env) {
5060
+ counters.terminalEvents += 1;
5061
+ if (env.kind === "outputChunk") {
5062
+ counters.terminalChunks += 1;
5063
+ counters.terminalChars += env.chunk.length;
5064
+ }
5065
+ },
5066
+ recordReactCommit() {
5067
+ counters.reactCommits += 1;
5068
+ if (counters.reactCommits % COMMIT_CLEANUP_INTERVAL !== 0) return;
5069
+ const cleared = clearRetainedPerformanceMeasures(timeline, measureLimit);
5070
+ if (cleared > 0) sample("performance_cleanup", true, cleared);
5071
+ },
5072
+ async stop() {
5073
+ if (stopped) return;
5074
+ stopped = true;
5075
+ clearInterval(interval);
5076
+ sample("shutdown", true);
5077
+ await writeChain;
5078
+ }
5079
+ };
5080
+ }
5081
+ function countActiveResources() {
5082
+ const counts = {};
5083
+ for (const resource of process.getActiveResourcesInfo()) {
5084
+ counts[resource] = (counts[resource] ?? 0) + 1;
5085
+ }
5086
+ return counts;
5087
+ }
5088
+
3989
5089
  // src/tui/index.tsx
3990
5090
  import { jsx as jsx7 } from "react/jsx-runtime";
3991
5091
  async function launchTui(opts) {
5092
+ const diagnostics = startTuiRuntimeDiagnostics();
3992
5093
  const instance = render(
3993
5094
  /* @__PURE__ */ jsx7(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx7(
3994
5095
  App,
3995
5096
  {
3996
5097
  client: opts.client,
5098
+ diagnostics,
3997
5099
  initialProjectId: opts.projectId,
3998
5100
  initialProjectName: opts.projectName,
3999
5101
  initialGezelId: opts.gezelId
@@ -4002,7 +5104,11 @@ async function launchTui(opts) {
4002
5104
  // We own Ctrl+C (interrupt-then-exit); don't let ink exit on the first press.
4003
5105
  { exitOnCtrlC: false }
4004
5106
  );
4005
- await instance.waitUntilExit();
5107
+ try {
5108
+ await instance.waitUntilExit();
5109
+ } finally {
5110
+ await diagnostics.stop();
5111
+ }
4006
5112
  }
4007
5113
  export {
4008
5114
  launchTui