@bendyline/gezel-cli 1.0.4 → 1.0.5

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
@@ -5,7 +5,7 @@ import { render } from "ink";
5
5
 
6
6
  // src/tui/App.tsx
7
7
  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";
8
+ import { useCallback as useCallback2, useEffect as useEffect4, useMemo, useRef as useRef3, useState as useState5 } from "react";
9
9
 
10
10
  // src/connection.ts
11
11
  import { createHash, randomUUID } from "crypto";
@@ -157,6 +157,44 @@ function activeAccessMode(opts) {
157
157
  return GezelCore.projectWorkspaceWritable(project) ? "editable" : "read-only";
158
158
  }
159
159
 
160
+ // src/tui/buffered-state.ts
161
+ import { useCallback, useEffect, useRef, useState } from "react";
162
+ function useBufferedState(initial, intervalMs) {
163
+ const [rendered, setRendered] = useState(initial);
164
+ const valueRef = useRef(rendered);
165
+ const timerRef = useRef(null);
166
+ const cancelTimer = useCallback(() => {
167
+ if (timerRef.current === null) return;
168
+ clearTimeout(timerRef.current);
169
+ timerRef.current = null;
170
+ }, []);
171
+ const apply = useCallback(
172
+ (update, buffered) => {
173
+ const current = valueRef.current;
174
+ const next = typeof update === "function" ? update(current) : update;
175
+ valueRef.current = next;
176
+ if (!buffered) {
177
+ cancelTimer();
178
+ setRendered(next);
179
+ return;
180
+ }
181
+ if (Object.is(current, next) || timerRef.current !== null) return;
182
+ timerRef.current = setTimeout(() => {
183
+ timerRef.current = null;
184
+ setRendered(valueRef.current);
185
+ }, intervalMs);
186
+ },
187
+ [cancelTimer, intervalMs]
188
+ );
189
+ const setImmediate = useCallback(
190
+ (update) => apply(update, false),
191
+ [apply]
192
+ );
193
+ const setBuffered = useCallback((update) => apply(update, true), [apply]);
194
+ useEffect(() => cancelTimer, [cancelTimer]);
195
+ return [rendered, setImmediate, setBuffered];
196
+ }
197
+
160
198
  // src/tui/open-command.ts
161
199
  var MAX_RECENT_REFERENCES = 12;
162
200
  function rememberCliOpenReferences(current, observed, max = MAX_RECENT_REFERENCES) {
@@ -268,6 +306,8 @@ var SLASH_COMMANDS = [
268
306
  { name: "gezel", description: "switch active gezel" },
269
307
  { name: "allow", description: "allow a project permission" },
270
308
  { name: "disallow", description: "disallow a project permission" },
309
+ { name: "show", description: "show optional chat details" },
310
+ { name: "hide", description: "hide optional chat details" },
271
311
  { name: "mode", description: "set AI activity: read-only through full play" },
272
312
  { name: "model", description: "switch engine and model" },
273
313
  { name: "thread", description: "switch the active chat thread" },
@@ -295,6 +335,18 @@ var NIGHT_SHIFT_SUBCOMMANDS = [
295
335
  var MODEL_SUBCOMMANDS = [
296
336
  { name: "download", description: "choose and download a new on-device model" }
297
337
  ];
338
+ var CHAT_DETAIL_TARGETS = [
339
+ {
340
+ name: "thinking",
341
+ showDescription: "show model thinking inline as it streams",
342
+ hideDescription: "hide model thinking and keep only the activity count"
343
+ },
344
+ {
345
+ name: "writes",
346
+ showDescription: "show file, artifact, and note content as it streams",
347
+ hideDescription: "hide streamed write content and keep compact tool activity"
348
+ }
349
+ ];
298
350
  var PROJECT_PERMISSIONS = [
299
351
  {
300
352
  name: "edits",
@@ -373,6 +425,18 @@ function suggestSlashWordwheel(input, craftbooks, recentReferences = []) {
373
425
  })
374
426
  );
375
427
  }
428
+ const detailMatch = input.match(/^\/(show|hide)\s+(.*)$/i);
429
+ if (detailMatch) {
430
+ const command = (detailMatch[1] ?? "").toLowerCase();
431
+ const query = (detailMatch[2] ?? "").trim().toLowerCase();
432
+ return CHAT_DETAIL_TARGETS.filter((target) => target.name.startsWith(query)).map((target) => ({
433
+ key: `${command}:${target.name}`,
434
+ label: `/${command} ${target.name}`,
435
+ description: command === "show" ? target.showDescription : target.hideDescription,
436
+ submit: `/${command} ${target.name}`,
437
+ completion: `/${command} ${target.name}`
438
+ }));
439
+ }
376
440
  const modeMatch = input.match(/^\/mode\s+(.*)$/i);
377
441
  if (modeMatch) {
378
442
  const query = (modeMatch[1] ?? "").trim().toLowerCase();
@@ -455,26 +519,157 @@ function parseInput(raw, cliMode) {
455
519
  import { GEZEL_VERSION } from "@bendyline/gezel";
456
520
  import { Box, Text } from "ink";
457
521
 
522
+ // src/tui/write-stream.ts
523
+ var WRITE_PAYLOAD_FIELDS = {
524
+ save_memory: "text",
525
+ write_file: "content",
526
+ append_to_file: "content",
527
+ replace_in_file: "replace",
528
+ replace_lines: "content",
529
+ apply_patch: "diff",
530
+ insert_at_marker: "content",
531
+ write_artifact: "content",
532
+ write_document: "content",
533
+ write_task_note: "text"
534
+ };
535
+ function isStreamedWriteTool(name) {
536
+ return writePayloadField(name) !== void 0;
537
+ }
538
+ function createWriteStreamState(toolName) {
539
+ return {
540
+ toolName,
541
+ phase: "seeking",
542
+ carry: "",
543
+ escaped: false,
544
+ unicodeEscape: null
545
+ };
546
+ }
547
+ function appendWriteArgumentChunk(state, chunk) {
548
+ if (state.phase === "done" || chunk.length === 0) return { state, text: "" };
549
+ let next = { ...state };
550
+ let input = chunk;
551
+ if (next.phase === "seeking") {
552
+ const field = writePayloadField(next.toolName);
553
+ if (!field) return { state: { ...next, phase: "done", carry: "" }, text: "" };
554
+ const combined = next.carry + chunk;
555
+ const match = payloadStartPattern(field).exec(combined);
556
+ if (!match || match.index === void 0) {
557
+ const carryChars = Math.max(64, field.length + 16);
558
+ return {
559
+ state: { ...next, carry: combined.slice(-carryChars) },
560
+ text: ""
561
+ };
562
+ }
563
+ input = combined.slice(match.index + match[0].length);
564
+ next = { ...next, phase: "reading", carry: "" };
565
+ }
566
+ let text = "";
567
+ for (const char of input) {
568
+ if (next.unicodeEscape !== null) {
569
+ const unicodeEscape = next.unicodeEscape + char;
570
+ if (unicodeEscape.length < 4) {
571
+ next = { ...next, unicodeEscape };
572
+ continue;
573
+ }
574
+ const code = Number.parseInt(unicodeEscape, 16);
575
+ text += Number.isNaN(code) ? `\\u${unicodeEscape}` : String.fromCharCode(code);
576
+ next = { ...next, unicodeEscape: null, escaped: false };
577
+ continue;
578
+ }
579
+ if (next.escaped) {
580
+ if (char === "u") {
581
+ next = { ...next, unicodeEscape: "" };
582
+ continue;
583
+ }
584
+ text += decodeEscape(char);
585
+ next = { ...next, escaped: false };
586
+ continue;
587
+ }
588
+ if (char === "\\") {
589
+ next = { ...next, escaped: true };
590
+ continue;
591
+ }
592
+ if (char === '"') {
593
+ next = { ...next, phase: "done", carry: "" };
594
+ break;
595
+ }
596
+ text += char;
597
+ }
598
+ return { state: next, text };
599
+ }
600
+ function writePayloadField(name) {
601
+ if (!name) return void 0;
602
+ const normalized = normalizeToolName(name);
603
+ return WRITE_PAYLOAD_FIELDS[normalized];
604
+ }
605
+ function normalizeToolName(name) {
606
+ return name.trim().replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase();
607
+ }
608
+ function payloadStartPattern(field) {
609
+ return new RegExp(`"${field.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"\\s*:\\s*"`);
610
+ }
611
+ function decodeEscape(char) {
612
+ switch (char) {
613
+ case "b":
614
+ return "\b";
615
+ case "f":
616
+ return "\f";
617
+ case "n":
618
+ return "\n";
619
+ case "r":
620
+ return "\r";
621
+ case "t":
622
+ return " ";
623
+ default:
624
+ return char;
625
+ }
626
+ }
627
+
458
628
  // src/tui/feed.ts
459
629
  var MAX_ROWS = 200;
630
+ var MAX_FEED_ROW_CHARS = 8e3;
631
+ function capFeedText(text) {
632
+ return text.length > MAX_FEED_ROW_CHARS ? text.slice(0, MAX_FEED_ROW_CHARS + 1) : text;
633
+ }
634
+ function appendFeedText(current, chunk) {
635
+ if (current.length > MAX_FEED_ROW_CHARS || chunk.length === 0) return current;
636
+ const remaining = MAX_FEED_ROW_CHARS + 1 - current.length;
637
+ return current + chunk.slice(0, remaining);
638
+ }
460
639
  var counter = 0;
461
640
  function nextKey() {
462
641
  counter += 1;
463
642
  return `r${counter}`;
464
643
  }
465
- function reduceFeed(rows, env) {
644
+ function reduceFeed(rows, env, opts = {}) {
466
645
  const { sessionId, gezelId, event } = env;
467
646
  const cap = (next) => next.length > MAX_ROWS ? next.slice(next.length - MAX_ROWS) : next;
468
647
  switch (event.type) {
648
+ case "user_message_pending": {
649
+ const key = `startup-${sessionId}`;
650
+ const pending = {
651
+ key,
652
+ sessionId,
653
+ gezelId,
654
+ kind: "pending",
655
+ text: capFeedText(event.preview),
656
+ open: false
657
+ };
658
+ const idx = rows.findIndex((row) => row.key === key);
659
+ if (idx === -1) return cap([...rows, pending]);
660
+ const next = rows.slice();
661
+ next[idx] = pending;
662
+ return next;
663
+ }
469
664
  case "user_message":
470
665
  return cap([
471
- ...rows,
666
+ ...withoutStartupPending(rows, sessionId),
472
667
  {
473
668
  key: nextKey(),
474
669
  sessionId,
475
670
  gezelId,
476
671
  kind: "user",
477
- text: event.message.content,
672
+ text: capFeedText(event.message.content),
478
673
  open: false
479
674
  }
480
675
  ]);
@@ -485,7 +680,7 @@ function reduceFeed(rows, env) {
485
680
  sessionId,
486
681
  gezelId,
487
682
  kind: "pending",
488
- text: event.preview,
683
+ text: capFeedText(event.preview),
489
684
  open: false
490
685
  };
491
686
  const idx = rows.findIndex((row) => row.key === key);
@@ -496,43 +691,72 @@ function reduceFeed(rows, env) {
496
691
  }
497
692
  case "queue_removed":
498
693
  return rows.filter((row) => row.key !== `queue-${event.queueId}`);
694
+ case "reasoning_delta": {
695
+ const settled = closeWriteRows(rows, sessionId);
696
+ if (opts.showThinking === false) return settled;
697
+ const idx = findOpenRow(settled, sessionId, "thinking");
698
+ const open = idx === -1 ? void 0 : settled[idx];
699
+ if (!open) {
700
+ return cap([
701
+ ...settled,
702
+ {
703
+ key: nextKey(),
704
+ sessionId,
705
+ gezelId,
706
+ kind: "thinking",
707
+ text: capFeedText(event.content),
708
+ open: true
709
+ }
710
+ ]);
711
+ }
712
+ const next = settled.slice();
713
+ const text = appendFeedText(open.text, event.content);
714
+ if (text === open.text) return settled;
715
+ next[idx] = { ...open, text };
716
+ return next;
717
+ }
499
718
  case "delta": {
500
- const idx = findOpenAssistant(rows, sessionId);
501
- const open = idx === -1 ? void 0 : rows[idx];
719
+ const settled = closeWriteRows(closeOpenRows(rows, sessionId, "thinking"), sessionId);
720
+ const idx = findOpenAssistant(settled, sessionId);
721
+ const open = idx === -1 ? void 0 : settled[idx];
502
722
  if (!open) {
503
723
  return cap([
504
- ...rows,
724
+ ...settled,
505
725
  {
506
726
  key: nextKey(),
507
727
  sessionId,
508
728
  gezelId,
509
729
  kind: "assistant",
510
- text: event.content,
730
+ text: capFeedText(event.content),
511
731
  open: true
512
732
  }
513
733
  ]);
514
734
  }
515
- const next = rows.slice();
516
- next[idx] = { ...open, text: open.text + event.content };
735
+ const next = settled.slice();
736
+ const text = appendFeedText(open.text, event.content);
737
+ if (text === open.text) return settled;
738
+ next[idx] = { ...open, text };
517
739
  return next;
518
740
  }
519
741
  case "complete": {
520
- const idx = findOpenAssistant(rows, sessionId);
521
- const open = idx === -1 ? void 0 : rows[idx];
522
- const text = event.message.content;
742
+ const settled = closeWriteRows(closeOpenRows(rows, sessionId, "thinking"), sessionId);
743
+ const idx = findOpenAssistant(settled, sessionId);
744
+ const open = idx === -1 ? void 0 : settled[idx];
745
+ const text = capFeedText(event.message.content);
523
746
  if (!open) {
524
747
  return cap([
525
- ...rows,
748
+ ...settled,
526
749
  { key: nextKey(), sessionId, gezelId, kind: "assistant", text, open: false }
527
750
  ]);
528
751
  }
529
- const next = rows.slice();
752
+ const next = settled.slice();
530
753
  next[idx] = { ...open, text: text || open.text, open: false };
531
754
  return next;
532
755
  }
533
- case "tool":
756
+ case "tool": {
757
+ const settled = closeWriteRows(closeOpenRows(rows, sessionId, "thinking"), sessionId);
534
758
  return cap([
535
- ...rows,
759
+ ...settled,
536
760
  {
537
761
  key: nextKey(),
538
762
  sessionId,
@@ -542,6 +766,14 @@ function reduceFeed(rows, env) {
542
766
  open: false
543
767
  }
544
768
  ]);
769
+ }
770
+ case "tool_args_delta": {
771
+ const settled = closeOpenRows(rows, sessionId, "thinking");
772
+ if (opts.showWrites !== true) {
773
+ return closeWriteRows(settled, sessionId);
774
+ }
775
+ return appendWriteStream(settled, sessionId, gezelId, event.name, event.content);
776
+ }
545
777
  case "awaiting_gezel":
546
778
  return cap([
547
779
  ...rows,
@@ -562,7 +794,7 @@ function reduceFeed(rows, env) {
562
794
  sessionId: "local",
563
795
  gezelId: "",
564
796
  kind: "note",
565
- text: `task \xB7 ${event.summary}`,
797
+ text: capFeedText(`task \xB7 ${event.summary}`),
566
798
  open: false,
567
799
  taskEvent: {
568
800
  kind: event.kind,
@@ -570,22 +802,46 @@ function reduceFeed(rows, env) {
570
802
  }
571
803
  }
572
804
  ]);
573
- case "error":
805
+ case "error": {
806
+ const settled = withoutStartupPending(
807
+ closeWriteRows(closeOpenRows(rows, sessionId, "thinking"), sessionId),
808
+ sessionId
809
+ );
574
810
  return cap([
575
- ...rows,
576
- { key: nextKey(), sessionId, gezelId, kind: "error", text: event.error, open: false }
811
+ ...settled,
812
+ {
813
+ key: nextKey(),
814
+ sessionId,
815
+ gezelId,
816
+ kind: "error",
817
+ text: capFeedText(event.error),
818
+ open: false
819
+ }
577
820
  ]);
578
- case "done":
579
- return rows.map((r) => r.sessionId === sessionId && r.open ? { ...r, open: false } : r);
821
+ }
822
+ case "done": {
823
+ const settled = withoutStartupPending(closeWriteRows(rows, sessionId), sessionId);
824
+ return settled.map((r) => r.sessionId === sessionId && r.open ? { ...r, open: false } : r);
825
+ }
580
826
  default:
581
827
  return rows;
582
828
  }
583
829
  }
584
- function sessionToFeedRows(session) {
830
+ function sessionToFeedRows(session, opts = {}) {
585
831
  const rows = [];
586
832
  for (const message of session.messages) {
587
833
  if (message.hidden) continue;
588
834
  if (message.role === "assistant") {
835
+ if (opts.showThinking !== false && message.reasoning?.trim()) {
836
+ rows.push({
837
+ key: nextKey(),
838
+ sessionId: session.id,
839
+ gezelId: message.from?.gezelId ?? session.gezelId,
840
+ kind: "thinking",
841
+ text: capFeedText(message.reasoning),
842
+ open: false
843
+ });
844
+ }
589
845
  for (const tool of message.toolCalls ?? []) {
590
846
  rows.push({
591
847
  key: nextKey(),
@@ -603,7 +859,7 @@ function sessionToFeedRows(session) {
603
859
  sessionId: session.id,
604
860
  gezelId: message.from?.gezelId ?? session.gezelId,
605
861
  kind: message.role === "user" && !message.from ? "user" : message.from ? "assistant" : message.role,
606
- text: message.content,
862
+ text: capFeedText(message.content),
607
863
  open: false
608
864
  });
609
865
  }
@@ -613,7 +869,7 @@ function sessionToFeedRows(session) {
613
869
  sessionId: session.id,
614
870
  gezelId: session.gezelId,
615
871
  kind: "error",
616
- text: session.lastTurnError,
872
+ text: capFeedText(session.lastTurnError),
617
873
  open: false
618
874
  });
619
875
  }
@@ -630,6 +886,8 @@ function reduceTurns(turns, env) {
630
886
  return m;
631
887
  };
632
888
  switch (event.type) {
889
+ case "user_message_pending":
890
+ return set("preparing chat", 0, null);
633
891
  case "user_message":
634
892
  return set("thinking\u2026", 0, null);
635
893
  case "queued":
@@ -646,11 +904,11 @@ function reduceTurns(turns, env) {
646
904
  case "tool_args_delta": {
647
905
  const outputChars = (prior?.outputChars ?? 0) + event.content.length;
648
906
  const name = event.name.trim() || prior?.activeToolName || null;
649
- return set(runningToolLabel(name), outputChars, name);
907
+ return set(runningToolLabel(name, outputChars), outputChars, name);
650
908
  }
651
909
  case "tool": {
652
910
  const name = event.name.trim() || prior?.activeToolName || null;
653
- return set(runningToolLabel(name), void 0, name);
911
+ return set(runningToolLabel(name, prior?.outputChars ?? 0), void 0, name);
654
912
  }
655
913
  case "heartbeat":
656
914
  return event.label ? set(heartbeatLabel(event.label), void 0, null) : turns;
@@ -663,6 +921,10 @@ function reduceTurns(turns, env) {
663
921
  return turns;
664
922
  }
665
923
  }
924
+ function withoutStartupPending(rows, sessionId) {
925
+ const key = `startup-${sessionId}`;
926
+ return rows.some((row) => row.key === key) ? rows.filter((row) => row.key !== key) : rows;
927
+ }
666
928
  function phaseLabel(event, outputChars) {
667
929
  const pct = event.progress !== void 0 ? ` ${Math.round(event.progress * 100)}%` : "";
668
930
  switch (event.phase) {
@@ -683,8 +945,11 @@ function generationLabel(outputChars) {
683
945
  const tokens = Math.max(1, Math.round(outputChars / 4));
684
946
  return `generating \xB7 ~${tokens.toLocaleString("en-US")} ${tokens === 1 ? "token" : "tokens"}`;
685
947
  }
686
- function runningToolLabel(name) {
687
- return name ? `running tool \xB7 ${name}` : "running tool";
948
+ function runningToolLabel(name, outputChars = 0) {
949
+ const base = name ? `running tool \xB7 ${name}` : "running tool";
950
+ if (!isStreamedWriteTool(name) || outputChars <= 0) return base;
951
+ const tokens = Math.max(1, Math.round(outputChars / 4));
952
+ return `${base} \xB7 ~${tokens.toLocaleString("en-US")} ${tokens === 1 ? "token" : "tokens"}`;
688
953
  }
689
954
  function heartbeatLabel(label) {
690
955
  const trimmed = label.trim();
@@ -696,7 +961,14 @@ function heartbeatLabel(label) {
696
961
  function appendNote(rows, text, kind = "note") {
697
962
  const next = [
698
963
  ...rows,
699
- { key: nextKey(), sessionId: "local", gezelId: "", kind, text, open: false }
964
+ {
965
+ key: nextKey(),
966
+ sessionId: "local",
967
+ gezelId: "",
968
+ kind,
969
+ text: capFeedText(text),
970
+ open: false
971
+ }
700
972
  ];
701
973
  return next.length > MAX_ROWS ? next.slice(next.length - MAX_ROWS) : next;
702
974
  }
@@ -713,7 +985,7 @@ function finalizeShellRun(rows, runId, message) {
713
985
  sessionId: `term-${runId}`,
714
986
  gezelId: "",
715
987
  kind: "shell",
716
- text: text ? `${text}${footer}` : footer.trimStart(),
988
+ text: capFeedText(text ? `${text}${footer}` : footer.trimStart()),
717
989
  open: false
718
990
  }
719
991
  ];
@@ -722,7 +994,11 @@ function finalizeShellRun(rows, runId, message) {
722
994
  const row = rows[idx];
723
995
  if (!row) return rows;
724
996
  const next = rows.slice();
725
- next[idx] = { ...row, open: false, text: `${row.text.replace(/\s+$/, "")}${footer}` };
997
+ next[idx] = {
998
+ ...row,
999
+ open: false,
1000
+ text: capFeedText(`${row.text.replace(/\s+$/, "")}${footer}`)
1001
+ };
726
1002
  return next;
727
1003
  }
728
1004
  function shellFooter(message) {
@@ -745,7 +1021,7 @@ function appendShellChunk(rows, runId, chunk) {
745
1021
  sessionId: `term-${runId}`,
746
1022
  gezelId: "",
747
1023
  kind: "shell",
748
- text: chunk,
1024
+ text: capFeedText(chunk),
749
1025
  open: true
750
1026
  }
751
1027
  ];
@@ -753,17 +1029,84 @@ function appendShellChunk(rows, runId, chunk) {
753
1029
  }
754
1030
  const row = rows[idx];
755
1031
  if (!row) return rows;
1032
+ const text = appendFeedText(row.text, chunk);
1033
+ if (text === row.text) return rows;
756
1034
  const next = rows.slice();
757
- next[idx] = { ...row, text: row.text + chunk };
1035
+ next[idx] = { ...row, text };
758
1036
  return next;
759
1037
  }
760
1038
  function findOpenAssistant(rows, sessionId) {
1039
+ return findOpenRow(rows, sessionId, "assistant");
1040
+ }
1041
+ function findOpenRow(rows, sessionId, kind) {
761
1042
  for (let i = rows.length - 1; i >= 0; i--) {
762
1043
  const r = rows[i];
763
- if (r && r.sessionId === sessionId && r.kind === "assistant" && r.open) return i;
1044
+ if (r && r.sessionId === sessionId && r.kind === kind && r.open) return i;
764
1045
  }
765
1046
  return -1;
766
1047
  }
1048
+ function closeOpenRows(rows, sessionId, kind) {
1049
+ let changed = false;
1050
+ const next = rows.map((row) => {
1051
+ if (row.sessionId !== sessionId || row.kind !== kind || !row.open) return row;
1052
+ changed = true;
1053
+ return { ...row, open: false };
1054
+ });
1055
+ return changed ? next : rows;
1056
+ }
1057
+ function appendWriteStream(rows, sessionId, gezelId, eventToolName, chunk) {
1058
+ let idx = findOpenRow(rows, sessionId, "write");
1059
+ let open = idx === -1 ? void 0 : rows[idx];
1060
+ const toolName = eventToolName.trim() || open?.writeStream?.toolName || "";
1061
+ if (!isStreamedWriteTool(toolName)) return closeWriteRows(rows, sessionId);
1062
+ let currentRows = rows;
1063
+ if (open?.writeStream?.toolName !== toolName) {
1064
+ currentRows = closeWriteRows(rows, sessionId);
1065
+ idx = -1;
1066
+ open = void 0;
1067
+ }
1068
+ const decoded = appendWriteArgumentChunk(
1069
+ open?.writeStream ?? createWriteStreamState(toolName),
1070
+ chunk
1071
+ );
1072
+ if (!open) {
1073
+ const next2 = [
1074
+ ...currentRows,
1075
+ {
1076
+ key: nextKey(),
1077
+ sessionId,
1078
+ gezelId,
1079
+ kind: "write",
1080
+ text: capFeedText(decoded.text),
1081
+ open: true,
1082
+ writeStream: decoded.state
1083
+ }
1084
+ ];
1085
+ return next2.length > MAX_ROWS ? next2.slice(next2.length - MAX_ROWS) : next2;
1086
+ }
1087
+ const next = currentRows.slice();
1088
+ next[idx] = {
1089
+ ...open,
1090
+ text: appendFeedText(open.text, decoded.text),
1091
+ writeStream: decoded.state
1092
+ };
1093
+ return next;
1094
+ }
1095
+ function closeWriteRows(rows, sessionId) {
1096
+ let changed = false;
1097
+ const next = [];
1098
+ for (const row of rows) {
1099
+ if (row.sessionId !== sessionId || row.kind !== "write" || !row.writeStream) {
1100
+ next.push(row);
1101
+ continue;
1102
+ }
1103
+ changed = true;
1104
+ if (!row.text) continue;
1105
+ const { writeStream: _writeStream, ...settled } = row;
1106
+ next.push({ ...settled, open: false });
1107
+ }
1108
+ return changed ? next : rows;
1109
+ }
767
1110
  function toolLabel(event) {
768
1111
  return toolRowText(event);
769
1112
  }
@@ -774,7 +1117,7 @@ function toolRowText(call) {
774
1117
  const flat = detail?.replace(/\s+/g, " ").trim();
775
1118
  const clipped = flat && flat.length > MAX_TOOL_DETAIL_CHARS ? `${flat.slice(0, MAX_TOOL_DETAIL_CHARS - 1)}\u2026` : flat;
776
1119
  const failed = call.success === false ? ` \xB7 failed${call.errorMessage ? `: ${call.errorMessage}` : ""}` : "";
777
- return `\u{1F527} ${name}${clipped ? ` \xB7 ${clipped}` : ""}${failed}`;
1120
+ return capFeedText(`\u{1F527} ${name}${clipped ? ` \xB7 ${clipped}` : ""}${failed}`);
778
1121
  }
779
1122
  function gezelLabel(gezelId, gezels, boring) {
780
1123
  const g = gezels.find((x) => x.id === gezelId);
@@ -912,6 +1255,8 @@ var KIND_COLOR = {
912
1255
  user: "white",
913
1256
  pending: "yellow",
914
1257
  assistant: "cyan",
1258
+ thinking: "magenta",
1259
+ write: "yellow",
915
1260
  tool: "yellow",
916
1261
  note: "magenta",
917
1262
  error: "red",
@@ -919,7 +1264,8 @@ var KIND_COLOR = {
919
1264
  };
920
1265
  function ChatFeed(props) {
921
1266
  const { rows, gezels, boring, focusedSessionId, visible = 16 } = props;
922
- const shown = rows.slice(Math.max(0, rows.length - visible));
1267
+ const visibleRows = rows.filter((row) => row.kind !== "write" || row.text.length > 0);
1268
+ const shown = visibleRows.slice(Math.max(0, visibleRows.length - visible));
923
1269
  return /* @__PURE__ */ jsx(Box, { flexDirection: "column", flexGrow: 1, marginBottom: 1, children: shown.length === 0 ? /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
924
1270
  /* @__PURE__ */ jsx(Text, { color: "yellow", children: TABLE_LOGO }),
925
1271
  /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginLeft: 3, children: [
@@ -934,7 +1280,7 @@ function ChatFeed(props) {
934
1280
  if (row.kind === "shell" && row.sessionId.startsWith("term-")) {
935
1281
  return /* @__PURE__ */ jsx(Text, { wrap: "wrap", children: clip(row.text) }, row.key);
936
1282
  }
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";
1283
+ 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
1284
  const isFocused = focusedSessionId && row.sessionId === focusedSessionId;
939
1285
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
940
1286
  /* @__PURE__ */ jsx(Text, { dimColor: !isFocused, color: isFocused ? "green" : void 0, children: isFocused ? "\u258E" : " " }),
@@ -943,9 +1289,16 @@ function ChatFeed(props) {
943
1289
  who,
944
1290
  ": "
945
1291
  ] }),
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
- ) })
1292
+ /* @__PURE__ */ jsx(
1293
+ Text,
1294
+ {
1295
+ color: KIND_COLOR[row.kind],
1296
+ dimColor: row.kind === "pending" || row.kind === "thinking" || row.kind === "write",
1297
+ children: clip(
1298
+ row.taskEvent ? taskEventText(row, gezels, boring) : row.kind === "assistant" ? humanizeToolMarkup(row.text) : row.text
1299
+ )
1300
+ }
1301
+ )
949
1302
  ] })
950
1303
  ] }, row.key);
951
1304
  }) });
@@ -970,20 +1323,19 @@ function taskEventText(row, gezels, boring) {
970
1323
  return row.text;
971
1324
  }
972
1325
  }
973
- var MAX_CHARS = 8e3;
974
1326
  function clip(text) {
975
1327
  const t = text.replace(/\s+$/, "");
976
- return t.length > MAX_CHARS ? `${t.slice(0, MAX_CHARS)}
1328
+ return t.length > MAX_FEED_ROW_CHARS ? `${t.slice(0, MAX_FEED_ROW_CHARS)}
977
1329
  \u2026 (truncated)` : t;
978
1330
  }
979
1331
 
980
1332
  // src/tui/components/Picker.tsx
981
1333
  import { Box as Box2, Text as Text2, useInput } from "ink";
982
- import { useState } from "react";
1334
+ import { useState as useState2 } from "react";
983
1335
  import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
984
1336
  function Picker(props) {
985
1337
  const { title, items, initialValue, windowSize, onSelect, onCancel } = props;
986
- const [index, setIndex] = useState(() => {
1338
+ const [index, setIndex] = useState2(() => {
987
1339
  const initialIndex = initialValue ? items.findIndex((item) => item.value === initialValue) : -1;
988
1340
  return Math.max(initialIndex, 0);
989
1341
  });
@@ -1043,7 +1395,7 @@ function Picker(props) {
1043
1395
  // src/tui/components/PromptLine.tsx
1044
1396
  import { Box as Box4, Text as Text4, useInput as useInput2 } from "ink";
1045
1397
  import TextInput from "ink-text-input";
1046
- import { useEffect, useState as useState2 } from "react";
1398
+ import { useEffect as useEffect2, useState as useState3 } from "react";
1047
1399
 
1048
1400
  // src/tui/components/EnginePill.tsx
1049
1401
  import { Box as Box3, Text as Text3 } from "ink";
@@ -1099,8 +1451,8 @@ function PromptLine(props) {
1099
1451
  onChange,
1100
1452
  onSubmit
1101
1453
  } = props;
1102
- const [cursor, setCursor] = useState2(history.length);
1103
- const [suggestionIndex, setSuggestionIndex] = useState2(0);
1454
+ const [cursor, setCursor] = useState3(history.length);
1455
+ const [suggestionIndex, setSuggestionIndex] = useState3(0);
1104
1456
  const suggestions = active && !pendingPrompt ? suggestSlashWordwheel(value, craftbooks, recentOpenReferences) : [];
1105
1457
  const activeSuggestionIndex = Math.min(suggestionIndex, Math.max(0, suggestions.length - 1));
1106
1458
  const suggestionWindowStart = Math.min(
@@ -1119,7 +1471,7 @@ function PromptLine(props) {
1119
1471
  const selected = suggestions[activeSuggestionIndex];
1120
1472
  onSubmit(selected ? selected.submit : submittedValue);
1121
1473
  };
1122
- useEffect(() => {
1474
+ useEffect2(() => {
1123
1475
  setCursor(history.length);
1124
1476
  }, [history.length]);
1125
1477
  useInput2(
@@ -1220,19 +1572,94 @@ function compactThreadTitle(title) {
1220
1572
  // src/tui/components/QuestionPrompt.tsx
1221
1573
  import { Box as Box5, Text as Text5, useInput as useInput3 } from "ink";
1222
1574
  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;
1575
+ import { useState as useState4 } from "react";
1576
+
1577
+ // src/tui/question-presentation.ts
1578
+ var TUI_APPROVAL_INTENTS = /* @__PURE__ */ new Set([
1579
+ "npm-install-approval",
1580
+ "command-approval",
1581
+ "tool-permission",
1582
+ "toolset-install-approval",
1583
+ "image-generation-approval",
1584
+ "video-generation-approval",
1585
+ "schedule-approval"
1586
+ ]);
1587
+ function canAnswerQuestionInTui(question) {
1588
+ return !question.intent || TUI_APPROVAL_INTENTS.has(question.intent.kind);
1589
+ }
1590
+ function choicesForQuestion(question) {
1591
+ if (question.choices && question.choices.length > 0) return question.choices;
1592
+ switch (question.intent?.kind) {
1593
+ case "command-approval":
1594
+ return ["Approve", "Decline"];
1595
+ case "tool-permission":
1596
+ return ["Allow", "Deny"];
1597
+ case "toolset-install-approval":
1598
+ return ["Install", "Not now"];
1599
+ case "image-generation-approval":
1600
+ case "video-generation-approval":
1601
+ return ["Allow once", "Always allow", "Decline"];
1602
+ case "schedule-approval":
1603
+ return ["Enable schedule", "Keep paused"];
1604
+ default:
1605
+ return [];
1606
+ }
1607
+ }
1608
+ function allowsWriteIn(question) {
1609
+ return question.intent ? false : question.allowWriteIn ?? true;
1610
+ }
1611
+ function questionHeading(question, askerLabel) {
1612
+ switch (question.intent?.kind) {
1613
+ case "npm-install-approval":
1614
+ return "npm package approval";
1615
+ case "command-approval":
1616
+ return "Command approval";
1617
+ case "tool-permission":
1618
+ return "Tool permission";
1619
+ case "toolset-install-approval":
1620
+ return "Toolset install approval";
1621
+ case "image-generation-approval":
1622
+ return "Image generation approval";
1623
+ case "video-generation-approval":
1624
+ return "Video generation approval";
1625
+ case "schedule-approval":
1626
+ return "Schedule approval";
1627
+ default:
1628
+ return `${askerLabel} asks`;
1629
+ }
1630
+ }
1631
+ function npmApprovalPackages(question) {
1632
+ if (question.intent?.kind !== "npm-install-approval") return [];
1633
+ const intent = question.intent;
1634
+ if (Array.isArray(intent.packages) && intent.packages.length > 0) return intent.packages;
1635
+ if (intent.package && intent.version) {
1636
+ return [{ package: intent.package, version: intent.version }];
1637
+ }
1638
+ return [];
1639
+ }
1226
1640
  function questionOptionCount(question) {
1227
- const choices = question.choices?.length ?? 0;
1228
- const writeIn = question.allowWriteIn ?? true;
1641
+ if (question.intent?.kind === "npm-install-approval") {
1642
+ return npmApprovalPackages(question).length > 0 ? 3 : 1;
1643
+ }
1644
+ const choices = choicesForQuestion(question).length;
1645
+ const writeIn = allowsWriteIn(question);
1229
1646
  const submit = question.multiSelect === true && choices > 0;
1230
1647
  return choices + (writeIn ? 1 : 0) + (submit ? 1 : 0);
1231
1648
  }
1649
+
1650
+ // src/tui/components/QuestionPrompt.tsx
1651
+ import { Fragment as Fragment3, jsx as jsx4, jsxs as jsxs5 } from "react/jsx-runtime";
1652
+ var QUESTION_OPTION_WINDOW_SIZE = 4;
1232
1653
  function QuestionPrompt(props) {
1654
+ if (props.question.intent?.kind === "npm-install-approval") {
1655
+ return /* @__PURE__ */ jsx4(NpmInstallApprovalPrompt, { ...props });
1656
+ }
1657
+ return /* @__PURE__ */ jsx4(StandardQuestionPrompt, { ...props });
1658
+ }
1659
+ function StandardQuestionPrompt(props) {
1233
1660
  const { client, question, askerLabel, active, onAnswered } = props;
1234
- const choices = question.choices ?? [];
1235
- const allowWriteIn = question.allowWriteIn ?? true;
1661
+ const choices = choicesForQuestion(question);
1662
+ const allowWriteIn = allowsWriteIn(question);
1236
1663
  const multiSelect = question.multiSelect === true;
1237
1664
  const options = [
1238
1665
  ...choices.map(
@@ -1241,12 +1668,12 @@ function QuestionPrompt(props) {
1241
1668
  ...allowWriteIn ? [{ kind: "write-in", label: "Other\u2026" }] : [],
1242
1669
  ...multiSelect && choices.length > 0 ? [{ kind: "submit", label: "Submit selections" }] : []
1243
1670
  ];
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);
1671
+ const [optionIndex, setOptionIndex] = useState4(0);
1672
+ const [selected, setSelected] = useState4(() => /* @__PURE__ */ new Set());
1673
+ const [writing, setWriting] = useState4(choices.length === 0 && allowWriteIn);
1674
+ const [writeIn, setWriteIn] = useState4("");
1675
+ const [submitting, setSubmitting] = useState4(false);
1676
+ const [error, setError] = useState4(null);
1250
1677
  const activeOptionIndex = Math.min(optionIndex, Math.max(0, options.length - 1));
1251
1678
  const windowStart = Math.min(
1252
1679
  Math.max(0, activeOptionIndex - QUESTION_OPTION_WINDOW_SIZE + 1),
@@ -1318,10 +1745,7 @@ function QuestionPrompt(props) {
1318
1745
  { isActive: active }
1319
1746
  );
1320
1747
  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
- ] }),
1748
+ /* @__PURE__ */ jsx4(Text5, { bold: true, color: "yellow", children: questionHeading(question, askerLabel) }),
1325
1749
  /* @__PURE__ */ jsx4(Text5, { wrap: "wrap", children: question.prompt }),
1326
1750
  writing ? /* @__PURE__ */ jsxs5(Fragment3, { children: [
1327
1751
  /* @__PURE__ */ jsxs5(Box5, { children: [
@@ -1363,6 +1787,128 @@ function QuestionPrompt(props) {
1363
1787
  error ? /* @__PURE__ */ jsx4(Text5, { color: "red", children: error }) : null
1364
1788
  ] });
1365
1789
  }
1790
+ var NPM_DECISIONS = [
1791
+ { value: "install", label: "Install" },
1792
+ { value: "always", label: "Always allow" },
1793
+ { value: "decline", label: "Decline" }
1794
+ ];
1795
+ function NpmInstallApprovalPrompt(props) {
1796
+ const { client, question, active, onAnswered } = props;
1797
+ const packages = npmApprovalPackages(question);
1798
+ const [packageIndex, setPackageIndex] = useState4(0);
1799
+ const [optionIndex, setOptionIndex] = useState4(0);
1800
+ const [decisions, setDecisions] = useState4(
1801
+ () => packages.map(() => void 0)
1802
+ );
1803
+ const [submitting, setSubmitting] = useState4(false);
1804
+ const [error, setError] = useState4(null);
1805
+ const currentPackage = packages[packageIndex];
1806
+ const submit = async (nextDecisions) => {
1807
+ if (submitting) return;
1808
+ setError(null);
1809
+ setSubmitting(true);
1810
+ const body = packages.length === 0 ? { declined: true } : {
1811
+ npmInstallDecisions: packages.map((entry, index) => ({
1812
+ package: entry.package,
1813
+ version: entry.version,
1814
+ decision: nextDecisions[index] ?? "decline"
1815
+ }))
1816
+ };
1817
+ try {
1818
+ onAnswered(await client.answerQuestion(question.id, body));
1819
+ } catch (err) {
1820
+ setError(err instanceof Error ? err.message : String(err));
1821
+ setSubmitting(false);
1822
+ }
1823
+ };
1824
+ useInput3(
1825
+ (_input, key) => {
1826
+ if (submitting) return;
1827
+ if (!currentPackage) {
1828
+ if (key.return) void submit([]);
1829
+ return;
1830
+ }
1831
+ if (key.upArrow) {
1832
+ setOptionIndex((index) => index <= 0 ? NPM_DECISIONS.length - 1 : index - 1);
1833
+ return;
1834
+ }
1835
+ if (key.downArrow) {
1836
+ setOptionIndex((index) => index >= NPM_DECISIONS.length - 1 ? 0 : index + 1);
1837
+ return;
1838
+ }
1839
+ if (key.leftArrow && packageIndex > 0) {
1840
+ const previousIndex = packageIndex - 1;
1841
+ const previousDecision = decisions[previousIndex];
1842
+ setPackageIndex(previousIndex);
1843
+ setOptionIndex(
1844
+ Math.max(
1845
+ 0,
1846
+ NPM_DECISIONS.findIndex((item) => item.value === previousDecision)
1847
+ )
1848
+ );
1849
+ setError(null);
1850
+ return;
1851
+ }
1852
+ if (!key.return) return;
1853
+ const decision = NPM_DECISIONS[optionIndex]?.value ?? "decline";
1854
+ const nextDecisions = decisions.slice();
1855
+ nextDecisions[packageIndex] = decision;
1856
+ setDecisions(nextDecisions);
1857
+ if (packageIndex >= packages.length - 1) {
1858
+ void submit(nextDecisions);
1859
+ return;
1860
+ }
1861
+ const nextPackageIndex = packageIndex + 1;
1862
+ const nextDecision = nextDecisions[nextPackageIndex];
1863
+ setPackageIndex(nextPackageIndex);
1864
+ setOptionIndex(
1865
+ Math.max(
1866
+ 0,
1867
+ NPM_DECISIONS.findIndex((item) => item.value === nextDecision)
1868
+ )
1869
+ );
1870
+ setError(null);
1871
+ },
1872
+ { isActive: active }
1873
+ );
1874
+ return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [
1875
+ /* @__PURE__ */ jsx4(Text5, { bold: true, color: "yellow", children: "npm package approval" }),
1876
+ currentPackage ? /* @__PURE__ */ jsxs5(Fragment3, { children: [
1877
+ /* @__PURE__ */ jsxs5(Text5, { wrap: "wrap", children: [
1878
+ "A gezel wants to install ",
1879
+ packages.length === 1 ? "this package" : "packages",
1880
+ " outside the pre-vetted list."
1881
+ ] }),
1882
+ /* @__PURE__ */ jsxs5(Text5, { children: [
1883
+ /* @__PURE__ */ jsxs5(Text5, { bold: true, children: [
1884
+ currentPackage.package,
1885
+ "@",
1886
+ currentPackage.version
1887
+ ] }),
1888
+ packages.length > 1 ? ` \xB7 package ${packageIndex + 1}/${packages.length}` : ""
1889
+ ] }),
1890
+ NPM_DECISIONS.map((option, index) => {
1891
+ const focused = index === optionIndex;
1892
+ const selected = decisions[packageIndex] === option.value;
1893
+ return /* @__PURE__ */ jsxs5(Text5, { color: focused ? "cyan" : void 0, children: [
1894
+ focused ? "\u203A " : " ",
1895
+ selected ? "[x] " : "",
1896
+ option.label
1897
+ ] }, option.value);
1898
+ }),
1899
+ /* @__PURE__ */ jsxs5(Text5, { dimColor: true, children: [
1900
+ "\u2191/\u2193 choose \xB7 Enter answer",
1901
+ packageIndex > 0 ? " \xB7 \u2190 previous package" : ""
1902
+ ] })
1903
+ ] }) : /* @__PURE__ */ jsxs5(Fragment3, { children: [
1904
+ /* @__PURE__ */ jsx4(Text5, { color: "red", children: "This approval has no package details." }),
1905
+ /* @__PURE__ */ jsx4(Text5, { color: "cyan", children: "\u203A Decline and dismiss" }),
1906
+ /* @__PURE__ */ jsx4(Text5, { dimColor: true, children: "Enter dismiss" })
1907
+ ] }),
1908
+ submitting ? /* @__PURE__ */ jsx4(Text5, { color: "yellow", children: "Submitting\u2026" }) : null,
1909
+ error ? /* @__PURE__ */ jsx4(Text5, { color: "red", children: error }) : null
1910
+ ] });
1911
+ }
1366
1912
  function toggleSet(current, value) {
1367
1913
  const next = new Set(current);
1368
1914
  if (next.has(value)) next.delete(value);
@@ -1770,21 +2316,21 @@ function modelFitLabel(fit) {
1770
2316
  }
1771
2317
 
1772
2318
  // 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));
2319
+ function pendingQuestionsForTui(questions) {
2320
+ return questions.filter((question) => !question.answer && canAnswerQuestionInTui(question)).slice().sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1775
2321
  }
1776
2322
  function updatePendingQuestion(questions, question) {
1777
2323
  const withoutCurrent = questions.filter((candidate) => candidate.id !== question.id);
1778
- return plainPendingQuestions(question.answer ? withoutCurrent : [...withoutCurrent, question]);
2324
+ return pendingQuestionsForTui(question.answer ? withoutCurrent : [...withoutCurrent, question]);
1779
2325
  }
1780
2326
 
1781
2327
  // src/tui/streams.ts
1782
2328
  import { streamProjectChatEvents, streamTerminalEvents } from "@bendyline/gezel-client";
1783
- import { useEffect as useEffect2, useRef } from "react";
2329
+ import { useEffect as useEffect3, useRef as useRef2 } from "react";
1784
2330
  function useProjectEvents(client, projectId, handler) {
1785
- const handlerRef = useRef(handler);
2331
+ const handlerRef = useRef2(handler);
1786
2332
  handlerRef.current = handler;
1787
- useEffect2(() => {
2333
+ useEffect3(() => {
1788
2334
  const controller = new AbortController();
1789
2335
  void consumeWithReconnect(
1790
2336
  async function* () {
@@ -1804,9 +2350,9 @@ function useProjectEvents(client, projectId, handler) {
1804
2350
  }, [client, projectId]);
1805
2351
  }
1806
2352
  function useTerminalEvents(client, projectId, handler) {
1807
- const handlerRef = useRef(handler);
2353
+ const handlerRef = useRef2(handler);
1808
2354
  handlerRef.current = handler;
1809
- useEffect2(() => {
2355
+ useEffect3(() => {
1810
2356
  const controller = new AbortController();
1811
2357
  void consumeWithReconnect(
1812
2358
  async function* () {
@@ -1856,8 +2402,8 @@ function abortableDelay(ms, signal) {
1856
2402
  import { jsx as jsx5, jsxs as jsxs6 } from "react/jsx-runtime";
1857
2403
  function useTerminalSize() {
1858
2404
  const { stdout } = useStdout();
1859
- const [size, setSize] = useState4({ rows: stdout?.rows ?? 24, columns: stdout?.columns ?? 80 });
1860
- useEffect3(() => {
2405
+ const [size, setSize] = useState5({ rows: stdout?.rows ?? 24, columns: stdout?.columns ?? 80 });
2406
+ useEffect4(() => {
1861
2407
  if (!stdout) return;
1862
2408
  const onResize = () => setSize({ rows: stdout.rows ?? 24, columns: stdout.columns ?? 80 });
1863
2409
  stdout.on("resize", onResize);
@@ -1873,6 +2419,8 @@ var HELP = [
1873
2419
  "/allow edits \u2014 allow tool edits /disallow edits \u2014 make tool edits read-only",
1874
2420
  "/allow codexedits|claudeedits \u2014 allow provider-native project edits",
1875
2421
  "/disallow codexedits|claudeedits \u2014 put that provider in read-only plan mode",
2422
+ "/show thinking \u2014 show model reasoning inline /hide thinking \u2014 hide it",
2423
+ "/show writes \u2014 stream write contents inline /hide writes \u2014 hide them (default)",
1876
2424
  "/mode \u2014 choose read-only, reactive, reactive+tasks, or full-play AI activity",
1877
2425
  "/thread \u2014 switch or start a chat thread",
1878
2426
  "/open workspace|artifacts|<recent file> \u2014 open a folder or file from chat",
@@ -1889,47 +2437,50 @@ var READ_ONLY_BOOT_NOTE = "Note: this folder is read-only to gezel, and can be u
1889
2437
  function App(props) {
1890
2438
  const { client } = props;
1891
2439
  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(
2440
+ const [config, setConfig] = useState5(null);
2441
+ const [gezels, setGezels] = useState5([]);
2442
+ const [projects, setProjects] = useState5([]);
2443
+ const [threads, setThreads] = useState5([]);
2444
+ const [tasks, setTasks] = useState5([]);
2445
+ const [craftbooks, setCraftbooks] = useState5([]);
2446
+ const [craftbookProjectType, setCraftbookProjectType] = useState5(null);
2447
+ const [suggestedCraftbookIds, setSuggestedCraftbookIds] = useState5(() => /* @__PURE__ */ new Set());
2448
+ const [craftbooksNeedingSetup, setCraftbooksNeedingSetup] = useState5(
1901
2449
  () => /* @__PURE__ */ new Set()
1902
2450
  );
1903
- const [startCategoryId, setStartCategoryId] = useState4(null);
1904
- const [modelChoices, setModelChoices] = useState4([]);
1905
- const [modelDownloadChoices, setModelDownloadChoices] = useState4([]);
1906
- const [modelDownloadProgress, setModelDownloadProgress] = useState4(
2451
+ const [startCategoryId, setStartCategoryId] = useState5(null);
2452
+ const [modelChoices, setModelChoices] = useState5([]);
2453
+ const [modelDownloadChoices, setModelDownloadChoices] = useState5([]);
2454
+ const [modelDownloadProgress, setModelDownloadProgress] = useState5(
1907
2455
  null
1908
2456
  );
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);
2457
+ const [modelDownloadReturn, setModelDownloadReturn] = useState5(null);
2458
+ const [modelChoicesLoading, setModelChoicesLoading] = useState5(false);
2459
+ const [threadsLoading, setThreadsLoading] = useState5(false);
2460
+ const [pendingQuestions, setPendingQuestions] = useState5([]);
2461
+ const [projectId, setProjectId] = useState5(props.initialProjectId);
2462
+ const [projectName, setProjectName] = useState5(props.initialProjectName);
2463
+ const [activeGezelId, setActiveGezelId] = useState5(null);
2464
+ const [ownSessionId, setOwnSessionId] = useState5(null);
2465
+ const [focusedSessionId, setFocusedSessionId] = useState5(null);
2466
+ const [activeThreadTitle, setActiveThreadTitle] = useState5(null);
2467
+ const [mode, setMode] = useState5("chat");
2468
+ const [overlay, setOverlay] = useState5(null);
2469
+ const [value, setValue] = useState5("");
2470
+ const [rows, setRows, setRowsBuffered] = useBufferedState([], 50);
2471
+ const [turns, setTurns, setTurnsBuffered] = useBufferedState(() => /* @__PURE__ */ new Map(), 50);
2472
+ const [recentOpenReferences, setRecentOpenReferences] = useState5([]);
2473
+ const recentOpenReferencesRef = useRef3([]);
2474
+ const [status, setStatus] = useState5("Connecting\u2026");
2475
+ const [history, setHistory] = useState5([]);
2476
+ const [activeRuns, setActiveRuns] = useState5(() => /* @__PURE__ */ new Set());
2477
+ const [pendingInput, setPendingInput] = useState5(null);
2478
+ const [managedTaskRef, setManagedTaskRef] = useState5(null);
2479
+ const [taskPrompt, setTaskPrompt] = useState5(null);
2480
+ const [exitArmed, setExitArmed] = useState5(false);
2481
+ useEffect4(() => {
2482
+ props.diagnostics?.recordReactCommit();
2483
+ });
1933
2484
  const pendingQuestion = pendingQuestions[0];
1934
2485
  const { rows: termRows, columns: termColumns } = useTerminalSize();
1935
2486
  const shellColumns = Math.min(500, Math.max(20, termColumns - 2));
@@ -1955,20 +2506,20 @@ function App(props) {
1955
2506
  const turn = focusedSessionId && turns.get(focusedSessionId) || ownSessionId && turns.get(ownSessionId) || turns.values().next().value;
1956
2507
  return turn?.label;
1957
2508
  }, [turns, focusedSessionId, ownSessionId]);
1958
- const note = useCallback(
2509
+ const note = useCallback2(
1959
2510
  (text, kind = "note") => setRows((r) => appendNote(r, text, kind)),
1960
- []
2511
+ [setRows]
1961
2512
  );
1962
- useEffect3(() => {
2513
+ useEffect4(() => {
1963
2514
  recentOpenReferencesRef.current = recentOpenReferences;
1964
2515
  }, [recentOpenReferences]);
1965
- const gezelIds = useRef2(/* @__PURE__ */ new Set());
1966
- const gezelRefreshInFlight = useRef2(false);
1967
- const applyGezelSnapshot = useCallback((next) => {
2516
+ const gezelIds = useRef3(/* @__PURE__ */ new Set());
2517
+ const gezelRefreshInFlight = useRef3(false);
2518
+ const applyGezelSnapshot = useCallback2((next) => {
1968
2519
  gezelIds.current = new Set(next.map((gezel) => gezel.id));
1969
2520
  setGezels(next);
1970
2521
  }, []);
1971
- const refreshGezels = useCallback(async () => {
2522
+ const refreshGezels = useCallback2(async () => {
1972
2523
  if (gezelRefreshInFlight.current) return;
1973
2524
  gezelRefreshInFlight.current = true;
1974
2525
  try {
@@ -1979,8 +2530,8 @@ function App(props) {
1979
2530
  gezelRefreshInFlight.current = false;
1980
2531
  }
1981
2532
  }, [applyGezelSnapshot, client]);
1982
- const taskLoadSequence = useRef2(0);
1983
- const refreshTasks = useCallback(async () => {
2533
+ const taskLoadSequence = useRef3(0);
2534
+ const refreshTasks = useCallback2(async () => {
1984
2535
  const sequence = ++taskLoadSequence.current;
1985
2536
  try {
1986
2537
  const res = await client.listProjectTasks(projectId);
@@ -1989,8 +2540,8 @@ function App(props) {
1989
2540
  } catch {
1990
2541
  }
1991
2542
  }, [client, projectId]);
1992
- const craftbookLoadSequence = useRef2(0);
1993
- const refreshCraftbooks = useCallback(async () => {
2543
+ const craftbookLoadSequence = useRef3(0);
2544
+ const refreshCraftbooks = useCallback2(async () => {
1994
2545
  const sequence = ++craftbookLoadSequence.current;
1995
2546
  const result = await client.listProjectCraftbooks(projectId);
1996
2547
  if (sequence !== craftbookLoadSequence.current) return [];
@@ -2004,10 +2555,19 @@ function App(props) {
2004
2555
  useProjectEvents(
2005
2556
  client,
2006
2557
  projectId,
2007
- useCallback(
2558
+ useCallback2(
2008
2559
  (env) => {
2009
- setRows((r) => reduceFeed(r, env));
2010
- setTurns((t) => reduceTurns(t, env));
2560
+ props.diagnostics?.recordChatEvent(env);
2561
+ const streaming = env.event.type === "delta" || env.event.type === "reasoning_delta" || env.event.type === "tool_args_delta";
2562
+ const updateRows = streaming ? setRowsBuffered : setRows;
2563
+ const updateTurns = streaming ? setTurnsBuffered : setTurns;
2564
+ updateRows(
2565
+ (r) => reduceFeed(r, env, {
2566
+ showThinking: config?.cliShowThinking !== false,
2567
+ showWrites: config?.cliShowWrites === true
2568
+ })
2569
+ );
2570
+ updateTurns((t) => reduceTurns(t, env));
2011
2571
  const observedReferences = cliOpenReferencesFromEvent(env);
2012
2572
  if (observedReferences.length > 0) {
2013
2573
  setRecentOpenReferences(
@@ -2031,43 +2591,58 @@ function App(props) {
2031
2591
  setPendingQuestions((questions) => updatePendingQuestion(questions, question));
2032
2592
  }
2033
2593
  },
2034
- [ownSessionId, refreshGezels, refreshTasks]
2594
+ [
2595
+ config?.cliShowThinking,
2596
+ config?.cliShowWrites,
2597
+ ownSessionId,
2598
+ props.diagnostics,
2599
+ refreshGezels,
2600
+ refreshTasks,
2601
+ setRows,
2602
+ setRowsBuffered,
2603
+ setTurns,
2604
+ setTurnsBuffered
2605
+ ]
2035
2606
  )
2036
2607
  );
2037
2608
  useTerminalEvents(
2038
2609
  client,
2039
2610
  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;
2611
+ useCallback2(
2612
+ (env) => {
2613
+ props.diagnostics?.recordTerminalEvent(env);
2614
+ switch (env.kind) {
2615
+ case "runStarted":
2616
+ setActiveRuns((s) => new Set(s).add(env.runId));
2617
+ return;
2618
+ case "outputChunk":
2619
+ setRowsBuffered((r) => appendShellChunk(r, env.runId, env.chunk));
2620
+ return;
2621
+ case "inputRequested":
2622
+ setPendingInput({ runId: env.runId, mode: env.mode, promptLine: env.promptLine });
2623
+ setRows((r) => appendNote(r, `\u2328 waiting for input \u2014 ${env.promptLine}`, "note"));
2624
+ return;
2625
+ case "message": {
2626
+ const runId = env.runId;
2627
+ if (!runId) return;
2628
+ setActiveRuns((s) => {
2629
+ if (!s.has(runId)) return s;
2630
+ const n = new Set(s);
2631
+ n.delete(runId);
2632
+ return n;
2633
+ });
2634
+ setPendingInput((p) => p?.runId === runId ? null : p);
2635
+ setRows((r) => finalizeShellRun(r, runId, env.message));
2636
+ return;
2637
+ }
2638
+ default:
2639
+ return;
2064
2640
  }
2065
- default:
2066
- return;
2067
- }
2068
- }, [])
2641
+ },
2642
+ [props.diagnostics, setRows, setRowsBuffered]
2643
+ )
2069
2644
  );
2070
- const ensureSession = useCallback(
2645
+ const ensureSession = useCallback2(
2071
2646
  async (gezelId, pid) => {
2072
2647
  try {
2073
2648
  const session = await client.createChatSession({
@@ -2086,7 +2661,7 @@ function App(props) {
2086
2661
  },
2087
2662
  [client, note, boring]
2088
2663
  );
2089
- const switchProject = useCallback(
2664
+ const switchProject = useCallback2(
2090
2665
  async (id) => {
2091
2666
  setOverlay(null);
2092
2667
  const project = projects.find((candidate) => candidate.id === id);
@@ -2117,9 +2692,9 @@ function App(props) {
2117
2692
  note(`could not switch project: ${errMsg(err)}`, "error");
2118
2693
  }
2119
2694
  },
2120
- [client, ensureSession, note, projectId, projects]
2695
+ [client, ensureSession, note, projectId, projects, setRows, setTurns]
2121
2696
  );
2122
- const openModelPicker = useCallback(async () => {
2697
+ const openModelPicker = useCallback2(async () => {
2123
2698
  if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2124
2699
  if (activeGezel.fixedFunction) {
2125
2700
  return note("this gezel runs a fixed tool and does not use a chat model.", "error");
@@ -2137,7 +2712,7 @@ function App(props) {
2137
2712
  setModelChoicesLoading(false);
2138
2713
  }
2139
2714
  }, [activeGezel, activeGezelId, client, config, modelChoicesLoading, note]);
2140
- const openModelDownloadPicker = useCallback(
2715
+ const openModelDownloadPicker = useCallback2(
2141
2716
  async (returnTo = null) => {
2142
2717
  if (!activeGezelId || !activeGezel) return note("no active gezel yet.", "error");
2143
2718
  if (activeGezel.fixedFunction) {
@@ -2169,7 +2744,7 @@ function App(props) {
2169
2744
  },
2170
2745
  [activeGezel, activeGezelId, client, config, modelChoicesLoading, note, openModelPicker]
2171
2746
  );
2172
- const openThreadPicker = useCallback(async () => {
2747
+ const openThreadPicker = useCallback2(async () => {
2173
2748
  if (!activeGezelId) return note("no active gezel yet.", "error");
2174
2749
  if (threadsLoading) return;
2175
2750
  setThreadsLoading(true);
@@ -2183,7 +2758,7 @@ function App(props) {
2183
2758
  setThreadsLoading(false);
2184
2759
  }
2185
2760
  }, [activeGezelId, client, note, projectId, threadsLoading]);
2186
- const switchThread = useCallback(
2761
+ const switchThread = useCallback2(
2187
2762
  async (sessionId) => {
2188
2763
  setOverlay(null);
2189
2764
  try {
@@ -2194,15 +2769,15 @@ function App(props) {
2194
2769
  setOwnSessionId(session.id);
2195
2770
  setFocusedSessionId(session.id);
2196
2771
  setActiveThreadTitle(displayThreadTitle(session.title));
2197
- setRows(sessionToFeedRows(session));
2772
+ setRows(sessionToFeedRows(session, { showThinking: config?.cliShowThinking !== false }));
2198
2773
  setRecentOpenReferences(cliOpenReferencesFromSession(session));
2199
2774
  } catch (err) {
2200
2775
  note(`could not switch thread: ${errMsg(err)}`, "error");
2201
2776
  }
2202
2777
  },
2203
- [activeGezelId, client, note, projectId]
2778
+ [activeGezelId, client, config?.cliShowThinking, note, projectId, setRows]
2204
2779
  );
2205
- const startNewThread = useCallback(async () => {
2780
+ const startNewThread = useCallback2(async () => {
2206
2781
  setOverlay(null);
2207
2782
  if (!activeGezelId) return note("no active gezel yet.", "error");
2208
2783
  try {
@@ -2220,8 +2795,8 @@ function App(props) {
2220
2795
  } catch (err) {
2221
2796
  note(`could not start a thread: ${errMsg(err)}`, "error");
2222
2797
  }
2223
- }, [activeGezelId, client, note, projectId, boring]);
2224
- useEffect3(() => {
2798
+ }, [activeGezelId, boring, client, note, projectId, setRows]);
2799
+ useEffect4(() => {
2225
2800
  let cancelled = false;
2226
2801
  (async () => {
2227
2802
  try {
@@ -2266,25 +2841,25 @@ function App(props) {
2266
2841
  cancelled = true;
2267
2842
  };
2268
2843
  }, []);
2269
- useEffect3(() => {
2844
+ useEffect4(() => {
2270
2845
  let cancelled = false;
2271
2846
  setPendingQuestions([]);
2272
2847
  void client.listQuestions({ projectId, pending: true }).then((result) => {
2273
- if (!cancelled) setPendingQuestions(plainPendingQuestions(result.questions));
2848
+ if (!cancelled) setPendingQuestions(pendingQuestionsForTui(result.questions));
2274
2849
  }).catch(() => {
2275
2850
  });
2276
2851
  return () => {
2277
2852
  cancelled = true;
2278
2853
  };
2279
2854
  }, [client, projectId]);
2280
- useEffect3(() => {
2855
+ useEffect4(() => {
2281
2856
  void refreshTasks();
2282
2857
  const id = setInterval(() => void refreshTasks(), 3e4);
2283
2858
  return () => {
2284
2859
  clearInterval(id);
2285
2860
  };
2286
2861
  }, [refreshTasks]);
2287
- useEffect3(() => {
2862
+ useEffect4(() => {
2288
2863
  void refreshCraftbooks().catch(() => {
2289
2864
  });
2290
2865
  }, [refreshCraftbooks]);
@@ -2341,7 +2916,7 @@ function App(props) {
2341
2916
  }
2342
2917
  return items;
2343
2918
  }, [rows, gezels, ownSessionId, gezelLine, boring]);
2344
- const cancelActive = useCallback(async () => {
2919
+ const cancelActive = useCallback2(async () => {
2345
2920
  const sessions = [...turns.keys()];
2346
2921
  const runs = [...activeRuns];
2347
2922
  if (sessions.length === 0 && runs.length === 0) return false;
@@ -2351,10 +2926,10 @@ function App(props) {
2351
2926
  ]);
2352
2927
  return true;
2353
2928
  }, [turns, activeRuns, client, projectId]);
2354
- const rememberTask = useCallback((task) => {
2929
+ const rememberTask = useCallback2((task) => {
2355
2930
  setTasks((current) => sortTasks([...current.filter((item) => item.ref !== task.ref), task]));
2356
2931
  }, []);
2357
- const applyEngagementMode = useCallback(
2932
+ const applyEngagementMode = useCallback2(
2358
2933
  async (requested) => {
2359
2934
  const next = parseCliEngagementMode(requested);
2360
2935
  if (!next) {
@@ -2373,7 +2948,7 @@ function App(props) {
2373
2948
  },
2374
2949
  [client, note]
2375
2950
  );
2376
- const applyProjectPermission = useCallback(
2951
+ const applyProjectPermission = useCallback2(
2377
2952
  async (permission, allowed) => {
2378
2953
  const permissionName = parseProjectPermissionName(permission);
2379
2954
  if (!permissionName) {
@@ -2404,7 +2979,38 @@ function App(props) {
2404
2979
  },
2405
2980
  [client, note, projectId, projectName]
2406
2981
  );
2407
- const startCraftbook = useCallback(
2982
+ const applyChatDetailVisibility = useCallback2(
2983
+ async (requested, visible) => {
2984
+ const target = requested.trim().toLowerCase();
2985
+ if (target !== "thinking" && target !== "writes") {
2986
+ note(`usage: /${visible ? "show" : "hide"} thinking|writes`, "error");
2987
+ return;
2988
+ }
2989
+ try {
2990
+ const updated = await client.updateConfig(
2991
+ target === "thinking" ? { cliShowThinking: visible } : { cliShowWrites: visible }
2992
+ );
2993
+ setConfig(updated);
2994
+ if (!visible) {
2995
+ const kind = target === "thinking" ? "thinking" : "write";
2996
+ setRows((current) => current.filter((row) => row.kind !== kind));
2997
+ }
2998
+ if (target === "thinking") {
2999
+ note(
3000
+ visible ? "Thinking is now shown inline." : "Thinking is now hidden. The live token count still includes it."
3001
+ );
3002
+ } else {
3003
+ note(
3004
+ visible ? "Write content is now shown inline as it streams." : "Write content is now hidden. Tool token counts remain visible."
3005
+ );
3006
+ }
3007
+ } catch (err) {
3008
+ note(`could not ${visible ? "show" : "hide"} ${target}: ${errMsg(err)}`, "error");
3009
+ }
3010
+ },
3011
+ [client, note, setRows]
3012
+ );
3013
+ const startCraftbook = useCallback2(
2408
3014
  async (book) => {
2409
3015
  setOverlay(null);
2410
3016
  note(`starting ${book.name}\u2026`);
@@ -2422,7 +3028,7 @@ function App(props) {
2422
3028
  },
2423
3029
  [boring, client, note, projectId, rememberTask]
2424
3030
  );
2425
- const submitTaskPrompt = useCallback(
3031
+ const submitTaskPrompt = useCallback2(
2426
3032
  async (raw) => {
2427
3033
  const prompt = taskPrompt;
2428
3034
  if (!prompt) return;
@@ -2461,7 +3067,7 @@ function App(props) {
2461
3067
  },
2462
3068
  [boring, client, note, projectId, rememberTask, taskPrompt, tasks]
2463
3069
  );
2464
- const applyTaskStatus = useCallback(
3070
+ const applyTaskStatus = useCallback2(
2465
3071
  async (status2) => {
2466
3072
  const task = managedTask;
2467
3073
  if (!task) return setOverlay("task");
@@ -2477,7 +3083,7 @@ function App(props) {
2477
3083
  },
2478
3084
  [client, managedTask, note, rememberTask]
2479
3085
  );
2480
- const applyTaskAssignee = useCallback(
3086
+ const applyTaskAssignee = useCallback2(
2481
3087
  async (value2) => {
2482
3088
  const task = managedTask;
2483
3089
  if (!task) return setOverlay("task");
@@ -2497,7 +3103,7 @@ function App(props) {
2497
3103
  },
2498
3104
  [client, managedTask, note, rememberTask]
2499
3105
  );
2500
- const runInput = useCallback(
3106
+ const runInput = useCallback2(
2501
3107
  async (raw) => {
2502
3108
  if (pendingInput) {
2503
3109
  const target = pendingInput;
@@ -2594,7 +3200,7 @@ function App(props) {
2594
3200
  turns
2595
3201
  ]
2596
3202
  );
2597
- const runCommand = useCallback(
3203
+ const runCommand = useCallback2(
2598
3204
  async (name, rest) => {
2599
3205
  switch (name) {
2600
3206
  case "help":
@@ -2611,6 +3217,12 @@ function App(props) {
2611
3217
  case "disallow":
2612
3218
  await applyProjectPermission(rest, false);
2613
3219
  return;
3220
+ case "show":
3221
+ await applyChatDetailVisibility(rest, true);
3222
+ return;
3223
+ case "hide":
3224
+ await applyChatDetailVisibility(rest, false);
3225
+ return;
2614
3226
  case "mode":
2615
3227
  if (!rest.trim()) return setOverlay("engagement-mode");
2616
3228
  await applyEngagementMode(rest);
@@ -2775,6 +3387,7 @@ function App(props) {
2775
3387
  [
2776
3388
  applyEngagementMode,
2777
3389
  applyProjectPermission,
3390
+ applyChatDetailVisibility,
2778
3391
  client,
2779
3392
  craftbooks,
2780
3393
  note,
@@ -2786,10 +3399,12 @@ function App(props) {
2786
3399
  projectName,
2787
3400
  refreshCraftbooks,
2788
3401
  refreshTasks,
3402
+ setRows,
3403
+ setTurns,
2789
3404
  startCraftbook
2790
3405
  ]
2791
3406
  );
2792
- const applyModelSelection = useCallback(
3407
+ const applyModelSelection = useCallback2(
2793
3408
  async (choice) => {
2794
3409
  setOverlay(null);
2795
3410
  if (!activeGezelId || !activeGezel || !config) return;
@@ -2819,17 +3434,21 @@ function App(props) {
2819
3434
  },
2820
3435
  [activeGezel, activeGezelId, client, config, ensureSession, note, projectId]
2821
3436
  );
2822
- const applyModelChoice = useCallback(
3437
+ const applyModelChoice = useCallback2(
2823
3438
  async (value2) => {
2824
3439
  await applyModelSelection(modelChoices.find((item) => item.value === value2));
2825
3440
  },
2826
3441
  [applyModelSelection, modelChoices]
2827
3442
  );
2828
- const installModelDownload = useCallback(
3443
+ const installModelDownload = useCallback2(
2829
3444
  async (value2) => {
2830
3445
  const choice = modelDownloadChoices.find((candidate) => candidate.value === value2);
2831
3446
  if (!choice) return;
2832
3447
  let terminalError = null;
3448
+ const companionResult = {
3449
+ name: null,
3450
+ error: null
3451
+ };
2833
3452
  setModelDownloadProgress({
2834
3453
  choice,
2835
3454
  bytesWritten: 0,
@@ -2839,6 +3458,10 @@ function App(props) {
2839
3458
  });
2840
3459
  const onEvent = (event) => {
2841
3460
  if (event.type === "error") terminalError = event.error;
3461
+ if (event.type === "companion") {
3462
+ companionResult.name = event.name;
3463
+ if (event.error) companionResult.error = event.error;
3464
+ }
2842
3465
  const progress = readModelDownloadProgress(choice, event);
2843
3466
  if (progress) setModelDownloadProgress(progress);
2844
3467
  };
@@ -2863,7 +3486,17 @@ function App(props) {
2863
3486
  installedChoice
2864
3487
  ]);
2865
3488
  setModelDownloadProgress(null);
2866
- note(`downloaded ${choice.model.name}; switching this gezel to it\u2026`);
3489
+ if (companionResult.name && companionResult.error) {
3490
+ note(
3491
+ `downloaded ${choice.model.name}; ${companionResult.name} image reader could not be added: ${companionResult.error}. Switching this gezel to ${choice.model.name}\u2026`
3492
+ );
3493
+ } else if (companionResult.name) {
3494
+ note(
3495
+ `downloaded ${choice.model.name} with ${companionResult.name} for image reading; switching this gezel to it\u2026`
3496
+ );
3497
+ } else {
3498
+ note(`downloaded ${choice.model.name}; switching this gezel to it\u2026`);
3499
+ }
2867
3500
  await applyModelSelection(installedChoice);
2868
3501
  } catch (err) {
2869
3502
  setModelDownloadProgress(null);
@@ -2873,7 +3506,7 @@ function App(props) {
2873
3506
  },
2874
3507
  [applyModelSelection, client, modelDownloadChoices, note]
2875
3508
  );
2876
- const cancelModelDownload = useCallback(async () => {
3509
+ const cancelModelDownload = useCallback2(async () => {
2877
3510
  const progress = modelDownloadProgress;
2878
3511
  if (!progress) return;
2879
3512
  try {
@@ -2891,7 +3524,7 @@ function App(props) {
2891
3524
  else setOverlay(null);
2892
3525
  }
2893
3526
  }, [client, modelDownloadProgress, modelDownloadReturn, note, openModelPicker]);
2894
- const onSubmit = useCallback(
3527
+ const onSubmit = useCallback2(
2895
3528
  (raw) => {
2896
3529
  setValue("");
2897
3530
  const trimmed = raw.trim();
@@ -2902,7 +3535,7 @@ function App(props) {
2902
3535
  },
2903
3536
  [runInput, pendingInput, taskPrompt]
2904
3537
  );
2905
- const cancelActiveRef = useRef2(cancelActive);
3538
+ const cancelActiveRef = useRef3(cancelActive);
2906
3539
  cancelActiveRef.current = cancelActive;
2907
3540
  useInput4(
2908
3541
  (input, key) => {
@@ -3210,7 +3843,7 @@ function App(props) {
3210
3843
  active: pendingInput === null,
3211
3844
  onAnswered: (question) => {
3212
3845
  setPendingQuestions((questions) => updatePendingQuestion(questions, question));
3213
- setFocusedSessionId(question.sessionId);
3846
+ if (question.sessionId) setFocusedSessionId(question.sessionId);
3214
3847
  }
3215
3848
  },
3216
3849
  pendingQuestion.id
@@ -3242,15 +3875,17 @@ function App(props) {
3242
3875
  }
3243
3876
  function ModelDownloadProgressPanel(props) {
3244
3877
  const { progress, onCancel } = props;
3878
+ const companion = progress.companion;
3245
3879
  useInput4((input, key) => {
3246
3880
  if (key.escape || key.ctrl && input === "c") onCancel();
3247
3881
  });
3248
3882
  const transferred = progress.totalBytes ? `${formatModelBytes(progress.bytesWritten)} / ${formatModelBytes(progress.totalBytes)}` : formatModelBytes(progress.bytesWritten);
3249
3883
  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
- ] }),
3884
+ /* @__PURE__ */ jsx5(Text6, { bold: true, color: "yellow", children: companion ? `Adding image reader: ${companion.name}` : `Downloading ${progress.choice.model.name}` }),
3885
+ companion ? /* @__PURE__ */ jsxs6(Text6, { children: [
3886
+ progress.choice.model.name,
3887
+ " is ready. This separate helper reads images for it."
3888
+ ] }) : null,
3254
3889
  /* @__PURE__ */ jsxs6(Text6, { children: [
3255
3890
  progress.pct == null ? "Working\u2026" : `${progress.pct}%`,
3256
3891
  " \xB7 ",
@@ -3278,7 +3913,11 @@ function readModelDownloadProgress(choice, event) {
3278
3913
  bytesWritten: event.bytesWritten,
3279
3914
  totalBytes: event.totalBytes,
3280
3915
  pct: event.totalBytes > 0 ? Math.min(100, Math.floor(event.bytesWritten / event.totalBytes * 100)) : null,
3281
- phase: `downloading ${event.name}`
3916
+ companion: {
3917
+ kind: event.kind,
3918
+ id: event.id,
3919
+ name: event.name
3920
+ }
3282
3921
  };
3283
3922
  }
3284
3923
  return null;
@@ -3390,13 +4029,13 @@ function formatTaskDetails(task, gezels, boring) {
3390
4029
  // src/tui/components/BootstrapGate.tsx
3391
4030
  import { formatModelAttribution as formatModelAttribution3 } from "@bendyline/gezel";
3392
4031
  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";
4032
+ import { useCallback as useCallback3, useEffect as useEffect5, useState as useState6 } from "react";
3394
4033
  import { Fragment as Fragment4, jsx as jsx6, jsxs as jsxs7 } from "react/jsx-runtime";
3395
4034
  var MAX_ALTERNATIVE_MODELS = 6;
3396
4035
  function BootstrapGate(props) {
3397
4036
  const { client, children } = props;
3398
4037
  const { exit } = useApp2();
3399
- const [screen, setScreen] = useState5({
4038
+ const [screen, setScreen] = useState6({
3400
4039
  kind: "loading",
3401
4040
  message: "Checking this device\u2026"
3402
4041
  });
@@ -3410,7 +4049,7 @@ function BootstrapGate(props) {
3410
4049
  // deliberate second-press exit.
3411
4050
  { isActive: screen.kind !== "ready" }
3412
4051
  );
3413
- const prepareModels = useCallback2(
4052
+ const prepareModels = useCallback3(
3414
4053
  async (context) => {
3415
4054
  setScreen({ kind: "loading", message: "Finding the best models for this device\u2026" });
3416
4055
  const installedChat = context.provider === "mlx" ? await client.listMlxModels() : await client.listLlamaCppModels();
@@ -3493,7 +4132,7 @@ function BootstrapGate(props) {
3493
4132
  },
3494
4133
  [client]
3495
4134
  );
3496
- const initialize = useCallback2(async () => {
4135
+ const initialize = useCallback3(async () => {
3497
4136
  try {
3498
4137
  setScreen({ kind: "loading", message: "Checking this device\u2026" });
3499
4138
  const [memory, chatCatalog] = await Promise.all([
@@ -3536,10 +4175,10 @@ function BootstrapGate(props) {
3536
4175
  });
3537
4176
  }
3538
4177
  }, [client, prepareModels]);
3539
- useEffect4(() => {
4178
+ useEffect5(() => {
3540
4179
  void initialize();
3541
4180
  }, [initialize]);
3542
- const installNative = useCallback2(
4181
+ const installNative = useCallback3(
3543
4182
  async (context, missing) => {
3544
4183
  const retry = () => void installNative(context, missing);
3545
4184
  if (!context.nativeStatus.pinned) {
@@ -3572,7 +4211,7 @@ function BootstrapGate(props) {
3572
4211
  },
3573
4212
  [client, prepareModels]
3574
4213
  );
3575
- const installModels = useCallback2(
4214
+ const installModels = useCallback3(
3576
4215
  async (plan, choice) => {
3577
4216
  if (choice.kind === "skip") {
3578
4217
  setScreen({ kind: "ready" });
@@ -3707,11 +4346,12 @@ function BootstrapGate(props) {
3707
4346
  0
3708
4347
  );
3709
4348
  const workshopDownloadBytes = accessoryBytes + (best && !bestInstalled ? best.approxSizeBytes : 0);
4349
+ const workshopHelperLabels = screen.plan.accessories.map(accessoryKindLabel).join(", ");
3710
4350
  const options = [
3711
4351
  ...best ? [
3712
4352
  {
3713
4353
  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"}`,
4354
+ hint: `${bestInstalled ? "chat model already available \xB7 " : ""}${workshopDownloadBytes > 0 ? formatDownloadSize(workshopDownloadBytes) : "already available"}${workshopHelperLabels ? ` \xB7 includes ${workshopHelperLabels}` : ""}`,
3715
4355
  value: "bundle"
3716
4356
  },
3717
4357
  {
@@ -3812,7 +4452,7 @@ function recoDevice(memory) {
3812
4452
  };
3813
4453
  }
3814
4454
  function BootstrapChoiceList(props) {
3815
- const [index, setIndex] = useState5(0);
4455
+ const [index, setIndex] = useState6(0);
3816
4456
  const options = props.options;
3817
4457
  useInput5((input, key) => {
3818
4458
  if (key.upArrow) {
@@ -3900,7 +4540,9 @@ async function installChatModel(client, model, onEvent) {
3900
4540
  if (model.provider === "mlx") {
3901
4541
  await client.installMlxModel(model.id, listener);
3902
4542
  } else {
3903
- await client.installLlamaCppModel(model.id, listener);
4543
+ await client.installLlamaCppModel(model.id, listener, void 0, {
4544
+ skipCompanion: true
4545
+ });
3904
4546
  }
3905
4547
  if (terminalError) throw new Error(terminalError);
3906
4548
  }
@@ -3934,7 +4576,24 @@ function updateDownloadProgress(setScreen, job, index, total, event, title = "Do
3934
4576
  } else if (event.type === "retrying" && "attempt" in event) {
3935
4577
  detail = `${job.label} \xB7 retrying ${event.attempt}/${event.maxAttempts}`;
3936
4578
  } else if (event.type === "verifying") {
4579
+ pct = 100;
3937
4580
  detail = `${job.label} \xB7 verifying`;
4581
+ } else if (event.type === "extracting-metadata") {
4582
+ pct = 100;
4583
+ detail = `${job.label} \xB7 reading model details`;
4584
+ } else if (event.type === "companion") {
4585
+ const name = "name" in event && typeof event.name === "string" ? event.name : "Image reader";
4586
+ const written = event.bytesWritten;
4587
+ const all = event.totalBytes;
4588
+ if (typeof written === "number" && typeof all === "number" && all > 0) {
4589
+ pct = Math.min(100, Math.floor(written / all * 100));
4590
+ detail = `${name} \xB7 image reader \xB7 ${formatDownloadSize(written)} of ${formatDownloadSize(all)}`;
4591
+ } else {
4592
+ detail = `${name} \xB7 image reader`;
4593
+ }
4594
+ if ("error" in event && typeof event.error === "string") {
4595
+ detail = `${name} \xB7 image reader unavailable: ${event.error}`;
4596
+ }
3938
4597
  } else if (event.type === "done") {
3939
4598
  pct = 100;
3940
4599
  detail = `${job.label} \xB7 ready`;
@@ -3973,6 +4632,20 @@ function nativeLabel(engine) {
3973
4632
  return "ds4";
3974
4633
  }
3975
4634
  }
4635
+ function accessoryKindLabel(model) {
4636
+ switch (model.kind) {
4637
+ case "image":
4638
+ return "image generator";
4639
+ case "recognition":
4640
+ return "image reader";
4641
+ case "stt":
4642
+ return "speech recognition";
4643
+ case "tts":
4644
+ return "voice";
4645
+ case "video":
4646
+ return "video generator";
4647
+ }
4648
+ }
3976
4649
  function fitLabel(fit) {
3977
4650
  if (fit === "fits-offload") return "fits with offload";
3978
4651
  if (fit === "fits") return "good fit";
@@ -3986,14 +4659,149 @@ function delay(ms) {
3986
4659
  return new Promise((resolve2) => setTimeout(resolve2, ms));
3987
4660
  }
3988
4661
 
4662
+ // src/tui/memory-diagnostics.ts
4663
+ import { appendFile, mkdir as mkdir2 } from "fs/promises";
4664
+ import { join as join2 } from "path";
4665
+ import { performance } from "perf_hooks";
4666
+ import { getHeapStatistics } from "v8";
4667
+ import { gezelHome, gezelPaths as gezelPaths2 } from "@bendyline/gezel/paths";
4668
+ var DEFAULT_SAMPLE_INTERVAL_MS = 15e3;
4669
+ var DEFAULT_MEASURE_LIMIT = 2e3;
4670
+ var DEFAULT_PRESSURE_HEAP_BYTES = 256 * 1024 * 1024;
4671
+ var DEFAULT_GROWTH_LOG_BYTES = 64 * 1024 * 1024;
4672
+ var COMMIT_CLEANUP_INTERVAL = 250;
4673
+ function clearRetainedPerformanceMeasures(timeline = performance, limit = DEFAULT_MEASURE_LIMIT) {
4674
+ const count = timeline.getEntriesByType("measure").length;
4675
+ if (count <= limit) return 0;
4676
+ timeline.clearMeasures();
4677
+ return count;
4678
+ }
4679
+ function startTuiRuntimeDiagnostics(options = {}) {
4680
+ const home = options.home ?? gezelHome();
4681
+ const logsDir = gezelPaths2(home).logs;
4682
+ const timeline = options.timeline ?? performance;
4683
+ const measureLimit = options.performanceMeasureLimit ?? DEFAULT_MEASURE_LIMIT;
4684
+ const pressureHeapBytes = options.pressureHeapBytes ?? DEFAULT_PRESSURE_HEAP_BYTES;
4685
+ const growthLogBytes = options.growthLogBytes ?? DEFAULT_GROWTH_LOG_BYTES;
4686
+ const alwaysLog = options.alwaysLog ?? process.env.GEZEL_TUI_MEMORY_DIAGNOSTICS?.trim() === "1";
4687
+ const eventTypes = {};
4688
+ const counters = {
4689
+ chatEvents: 0,
4690
+ streamFragments: 0,
4691
+ streamChars: 0,
4692
+ terminalEvents: 0,
4693
+ terminalChunks: 0,
4694
+ terminalChars: 0,
4695
+ reactCommits: 0
4696
+ };
4697
+ let stopped = false;
4698
+ let lastLoggedHeapUsed = 0;
4699
+ let peakHeapUsed = 0;
4700
+ let peakRss = 0;
4701
+ let writeChain = Promise.resolve();
4702
+ const sample = (phase, force = false, measuresCleared = 0) => {
4703
+ const memory = process.memoryUsage();
4704
+ const heap = getHeapStatistics();
4705
+ peakHeapUsed = Math.max(peakHeapUsed, memory.heapUsed);
4706
+ peakRss = Math.max(peakRss, memory.rss);
4707
+ const performanceMeasures = timeline.getEntriesByType("measure").length;
4708
+ const cleared = measuresCleared || clearRetainedPerformanceMeasures(timeline, measureLimit);
4709
+ const shouldWrite = force || alwaysLog || cleared > 0 || memory.heapUsed >= pressureHeapBytes || memory.heapUsed - lastLoggedHeapUsed >= growthLogBytes;
4710
+ if (!shouldWrite) return;
4711
+ lastLoggedHeapUsed = memory.heapUsed;
4712
+ const at = (/* @__PURE__ */ new Date()).toISOString();
4713
+ const record = {
4714
+ type: "tui.memory",
4715
+ version: 1,
4716
+ at,
4717
+ phase,
4718
+ pid: process.pid,
4719
+ nodeEnv: process.env.NODE_ENV ?? null,
4720
+ nodeVersion: process.version,
4721
+ uptimeMs: Math.round(process.uptime() * 1e3),
4722
+ memory: {
4723
+ rss: memory.rss,
4724
+ heapUsed: memory.heapUsed,
4725
+ heapTotal: memory.heapTotal,
4726
+ external: memory.external,
4727
+ arrayBuffers: memory.arrayBuffers,
4728
+ peakHeapUsed,
4729
+ peakRss,
4730
+ heapSizeLimit: heap.heap_size_limit,
4731
+ totalAvailableSize: heap.total_available_size,
4732
+ mallocedMemory: heap.malloced_memory,
4733
+ peakMallocedMemory: heap.peak_malloced_memory,
4734
+ nativeContexts: heap.number_of_native_contexts,
4735
+ detachedContexts: heap.number_of_detached_contexts
4736
+ },
4737
+ activeResources: countActiveResources(),
4738
+ performanceMeasures,
4739
+ measuresCleared: cleared,
4740
+ counters: { ...counters },
4741
+ eventTypes: { ...eventTypes }
4742
+ };
4743
+ const file = join2(logsDir, `tui-memory-${at.slice(0, 10)}.jsonl`);
4744
+ writeChain = writeChain.then(async () => {
4745
+ await mkdir2(logsDir, { recursive: true });
4746
+ await appendFile(file, `${JSON.stringify(record)}
4747
+ `, "utf8");
4748
+ }).catch(() => void 0);
4749
+ };
4750
+ sample("startup", true);
4751
+ const interval = setInterval(
4752
+ () => sample("interval"),
4753
+ options.intervalMs ?? DEFAULT_SAMPLE_INTERVAL_MS
4754
+ );
4755
+ interval.unref();
4756
+ return {
4757
+ recordChatEvent(env) {
4758
+ counters.chatEvents += 1;
4759
+ eventTypes[env.event.type] = (eventTypes[env.event.type] ?? 0) + 1;
4760
+ if (env.event.type === "delta" || env.event.type === "reasoning_delta" || env.event.type === "tool_args_delta") {
4761
+ counters.streamFragments += 1;
4762
+ counters.streamChars += env.event.content.length;
4763
+ }
4764
+ },
4765
+ recordTerminalEvent(env) {
4766
+ counters.terminalEvents += 1;
4767
+ if (env.kind === "outputChunk") {
4768
+ counters.terminalChunks += 1;
4769
+ counters.terminalChars += env.chunk.length;
4770
+ }
4771
+ },
4772
+ recordReactCommit() {
4773
+ counters.reactCommits += 1;
4774
+ if (counters.reactCommits % COMMIT_CLEANUP_INTERVAL !== 0) return;
4775
+ const cleared = clearRetainedPerformanceMeasures(timeline, measureLimit);
4776
+ if (cleared > 0) sample("performance_cleanup", true, cleared);
4777
+ },
4778
+ async stop() {
4779
+ if (stopped) return;
4780
+ stopped = true;
4781
+ clearInterval(interval);
4782
+ sample("shutdown", true);
4783
+ await writeChain;
4784
+ }
4785
+ };
4786
+ }
4787
+ function countActiveResources() {
4788
+ const counts = {};
4789
+ for (const resource of process.getActiveResourcesInfo()) {
4790
+ counts[resource] = (counts[resource] ?? 0) + 1;
4791
+ }
4792
+ return counts;
4793
+ }
4794
+
3989
4795
  // src/tui/index.tsx
3990
4796
  import { jsx as jsx7 } from "react/jsx-runtime";
3991
4797
  async function launchTui(opts) {
4798
+ const diagnostics = startTuiRuntimeDiagnostics();
3992
4799
  const instance = render(
3993
4800
  /* @__PURE__ */ jsx7(BootstrapGate, { client: opts.client, children: /* @__PURE__ */ jsx7(
3994
4801
  App,
3995
4802
  {
3996
4803
  client: opts.client,
4804
+ diagnostics,
3997
4805
  initialProjectId: opts.projectId,
3998
4806
  initialProjectName: opts.projectName,
3999
4807
  initialGezelId: opts.gezelId
@@ -4002,7 +4810,11 @@ async function launchTui(opts) {
4002
4810
  // We own Ctrl+C (interrupt-then-exit); don't let ink exit on the first press.
4003
4811
  { exitOnCtrlC: false }
4004
4812
  );
4005
- await instance.waitUntilExit();
4813
+ try {
4814
+ await instance.waitUntilExit();
4815
+ } finally {
4816
+ await diagnostics.stop();
4817
+ }
4006
4818
  }
4007
4819
  export {
4008
4820
  launchTui