@linxiraos/pi-tui 1.4.3 → 1.4.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.
Files changed (117) hide show
  1. package/CHANGELOG.md +29 -23
  2. package/THIRD-PARTY-NOTICES.txt +14 -0
  3. package/dist/types/app-keybindings.d.ts +5 -0
  4. package/dist/types/chrome/context-map.d.ts +15 -0
  5. package/dist/types/chrome/context-presentation.d.ts +48 -0
  6. package/dist/types/chrome/context-view-model.d.ts +77 -0
  7. package/dist/types/components/image.d.ts +20 -0
  8. package/dist/types/components/loader.d.ts +1 -1
  9. package/dist/types/native/blobs.d.ts +9 -0
  10. package/dist/types/overlays/advisor-config.d.ts +6 -0
  11. package/dist/types/overlays/agent-hub-projection.d.ts +3 -1
  12. package/dist/types/overlays/ask-dialog.d.ts +12 -3
  13. package/dist/types/overlays/btw-history-panel.d.ts +16 -2
  14. package/dist/types/overlays/btw-history.d.ts +7 -0
  15. package/dist/types/overlays/btw-panel.d.ts +2 -0
  16. package/dist/types/overlays/context-viewer-format.d.ts +42 -0
  17. package/dist/types/overlays/context-viewer-overview.d.ts +70 -0
  18. package/dist/types/overlays/context-viewer.d.ts +25 -0
  19. package/dist/types/overlays/hook-input.d.ts +1 -0
  20. package/dist/types/overlays/mcp-add-wizard.d.ts +2 -0
  21. package/dist/types/overlays/pause-screen.d.ts +13 -3
  22. package/dist/types/overlays/running-subagent-badge.d.ts +7 -1
  23. package/dist/types/prompt/macos-spelling.d.ts +2 -2
  24. package/dist/types/render/hyperlink.d.ts +15 -2
  25. package/dist/types/render/output-pane.d.ts +1 -1
  26. package/dist/types/render/render-utils.d.ts +7 -1
  27. package/dist/types/status-line/component.d.ts +2 -2
  28. package/dist/types/status-line/context-usage.d.ts +15 -30
  29. package/dist/types/terminal-capabilities.d.ts +7 -0
  30. package/dist/types/theme/symbols.d.ts +1 -1
  31. package/dist/types/tools/ask.d.ts +4 -0
  32. package/dist/types/tools/edit.d.ts +3 -1
  33. package/dist/types/tools/fetch.d.ts +1 -0
  34. package/dist/types/tools/github.d.ts +3 -0
  35. package/dist/types/tools/grouped-file-output.d.ts +2 -0
  36. package/dist/types/tools/mcp.d.ts +3 -3
  37. package/dist/types/tools/read.d.ts +3 -0
  38. package/dist/types/tools/wait.d.ts +16 -2
  39. package/dist/types/tui.d.ts +2 -0
  40. package/dist/types/vim.d.ts +39 -0
  41. package/package.json +9 -9
  42. package/src/app-keybindings.d.ts +5 -0
  43. package/src/app-keybindings.ts +5 -0
  44. package/src/chat/bash-execution.ts +7 -1
  45. package/src/chat/read-tool-group.ts +1 -2
  46. package/src/chat/skill-message.ts +2 -6
  47. package/src/chrome/context-map.ts +62 -0
  48. package/src/chrome/context-presentation.ts +26 -0
  49. package/src/chrome/context-view-model.ts +73 -0
  50. package/src/chrome/transcript-container.ts +89 -59
  51. package/src/components/editor.ts +455 -13
  52. package/src/components/image.d.ts +20 -0
  53. package/src/components/image.ts +83 -18
  54. package/src/components/loader.d.ts +1 -1
  55. package/src/components/loader.ts +1 -1
  56. package/src/components/markdown.ts +109 -7
  57. package/src/hotkeys-markdown.ts +1 -0
  58. package/src/native/blobs.d.ts +9 -0
  59. package/src/native/blobs.ts +3 -2
  60. package/src/overlays/advisor-config.ts +9 -2
  61. package/src/overlays/agent-hub-projection.d.ts +3 -1
  62. package/src/overlays/agent-hub-projection.ts +6 -5
  63. package/src/overlays/agent-hub.ts +51 -42
  64. package/src/overlays/ask-dialog.ts +125 -35
  65. package/src/overlays/btw-history-panel.ts +124 -12
  66. package/src/overlays/btw-history.ts +11 -0
  67. package/src/overlays/btw-panel.ts +8 -4
  68. package/src/overlays/context-viewer-format.ts +145 -0
  69. package/src/overlays/context-viewer-overview.ts +381 -0
  70. package/src/overlays/context-viewer.ts +728 -0
  71. package/src/overlays/hook-input.ts +2 -0
  72. package/src/overlays/mcp-add-wizard.ts +5 -0
  73. package/src/overlays/pause-screen.ts +166 -33
  74. package/src/overlays/running-subagent-badge.ts +12 -1
  75. package/src/overlays/settings-defs.ts +1 -0
  76. package/src/overlays/usage-dashboard.ts +15 -2
  77. package/src/prompt/macos-spelling.ts +24 -15
  78. package/src/render/hyperlink.d.ts +15 -2
  79. package/src/render/hyperlink.ts +41 -18
  80. package/src/render/output-pane.d.ts +1 -1
  81. package/src/render/output-pane.ts +60 -17
  82. package/src/render/render-utils.d.ts +7 -1
  83. package/src/render/render-utils.ts +11 -2
  84. package/src/setup/scenes/sign-in.ts +6 -0
  85. package/src/status-line/component.ts +6 -4
  86. package/src/status-line/context-usage.ts +56 -582
  87. package/src/terminal-capabilities.d.ts +7 -0
  88. package/src/terminal-capabilities.ts +10 -0
  89. package/src/theme/symbols.d.ts +1 -1
  90. package/src/theme/symbols.ts +16 -0
  91. package/src/tools/ask.d.ts +4 -0
  92. package/src/tools/ask.ts +4 -0
  93. package/src/tools/ast-grep.ts +3 -2
  94. package/src/tools/bash.ts +5 -23
  95. package/src/tools/edit.d.ts +3 -1
  96. package/src/tools/edit.ts +8 -4
  97. package/src/tools/fetch.d.ts +1 -0
  98. package/src/tools/fetch.ts +1 -0
  99. package/src/tools/find.ts +3 -10
  100. package/src/tools/github.d.ts +3 -0
  101. package/src/tools/github.ts +23 -3
  102. package/src/tools/glob.ts +4 -3
  103. package/src/tools/grep.ts +3 -4
  104. package/src/tools/grouped-file-output.d.ts +2 -0
  105. package/src/tools/grouped-file-output.ts +8 -2
  106. package/src/tools/mcp.d.ts +3 -3
  107. package/src/tools/mcp.ts +27 -9
  108. package/src/tools/native-view.ts +2 -2
  109. package/src/tools/read.d.ts +3 -0
  110. package/src/tools/read.ts +3 -1
  111. package/src/tools/vibe.ts +14 -3
  112. package/src/tools/wait.d.ts +16 -2
  113. package/src/tools/wait.ts +16 -2
  114. package/src/tui.d.ts +2 -0
  115. package/src/tui.ts +59 -19
  116. package/src/vim.d.ts +39 -0
  117. package/src/vim.ts +313 -22
@@ -4,15 +4,6 @@ import { effectiveReserveTokens, resolveThresholdTokens } from "@linxiraos/pi-ag
4
4
  import type { Tool as AiTool, Model } from "@linxiraos/pi-ai";
5
5
  import { renderToolExamples } from "@linxiraos/pi-ai/dialect";
6
6
  import { toolWireSchema } from "@linxiraos/pi-ai/utils/schema";
7
- import { formatNumber } from "@linxiraos/pi-utils";
8
- import type { Theme, ThemeColor } from "../theme";
9
- import { Container } from "../tui";
10
- import { Text } from "../components/text";
11
- import { Spacer } from "../components/spacer";
12
- import { DynamicBorder } from "../chrome/dynamic-border";
13
- import type { TspSpan, TspText } from "@linxiraos/pi-wire";
14
- import type { DescribeContext, NativeNode } from "../native/node";
15
- import { col, node, row, span, text } from "../native/describe";
16
7
 
17
8
  interface ContextSkill {
18
9
  readonly name: string;
@@ -72,24 +63,12 @@ export interface ContextUsageOptions {
72
63
  snapcompact?: ContextSavingsEstimate;
73
64
  }
74
65
 
75
- const GRID_COLS = 20;
76
- const GRID_ROWS = 10;
77
- const GRID_CELLS = GRID_COLS * GRID_ROWS;
78
- const GRID_GUTTER = " ";
79
-
80
- const CELL_FILLED = "⛁";
81
- const CELL_FILLED_MESSAGES = "⛃";
82
- const CELL_FREE = "⛶";
83
- const CELL_BUFFER = "⛝";
84
-
85
66
  type CategoryId = "systemPrompt" | "systemContext" | "systemTools" | "skills" | "messages";
86
67
 
87
68
  interface CategoryInfo {
88
69
  id: CategoryId;
89
70
  label: string;
90
71
  tokens: number;
91
- color: "accent" | "warning" | "success" | "userMessageText" | "customMessageLabel";
92
- glyph: string;
93
72
  }
94
73
 
95
74
  export interface ContextBreakdown {
@@ -227,6 +206,56 @@ export function invalidateToolSchemaMetadata(tools: ToolSchemaSource): void {
227
206
  toolSchemaTokenCache(tools).revision++;
228
207
  }
229
208
 
209
+ /** Provider-visible text of one tool definition, in wire order. */
210
+ export interface ToolSchemaFragments {
211
+ /** Name, description, wire schema JSON, then rendered examples; fields that cannot be serialized are omitted. */
212
+ readonly fragments: string[];
213
+ /** `fragments` with the schema JSON indented for reading; present only when a display indent was requested. */
214
+ readonly display?: string[];
215
+ /** Why serialization stopped; the schema or examples after that point are missing from `fragments`. */
216
+ readonly schemaError?: string;
217
+ }
218
+
219
+ /**
220
+ * Provider-visible text of one tool definition. `displayIndent` additionally
221
+ * returns `display`, the same fragments with the schema JSON indented, from
222
+ * the same schema conversion.
223
+ */
224
+ export function toolSchemaFragments(tool: ContextTool, displayIndent?: number): ToolSchemaFragments {
225
+ // Extension-supplied tools may carry a non-string name/description or a
226
+ // parameters value whose wire schema stringifies to `undefined` (e.g. a
227
+ // callable schema that escaped normalization). A non-string fragment is
228
+ // fatal inside the native tokenizer, so only real strings are kept.
229
+ const { name, description, parameters } = tool;
230
+ const fragments: string[] = [];
231
+ const display: string[] | undefined = displayIndent === undefined ? undefined : [];
232
+ const push = (wire: string, shown: string = wire): void => {
233
+ fragments.push(wire);
234
+ display?.push(shown);
235
+ };
236
+ if (typeof name === "string") push(name);
237
+ if (typeof description === "string") push(description);
238
+ try {
239
+ const wireTool: AiTool = {
240
+ name,
241
+ description,
242
+ parameters: parameters as AiTool["parameters"],
243
+ examples: tool.examples,
244
+ };
245
+ const wireSchema = toolWireSchema(wireTool) ?? {};
246
+ const wireJson = JSON.stringify(wireSchema);
247
+ if (typeof wireJson === "string")
248
+ push(wireJson, display ? JSON.stringify(wireSchema, null, displayIndent) : wireJson);
249
+ // The agent loop appends rendered examples to the wire description.
250
+ const examplesBlock = renderToolExamples(wireTool);
251
+ if (examplesBlock) push(examplesBlock);
252
+ } catch (error) {
253
+ // Schema may contain functions or cycles.
254
+ return { fragments, display, schemaError: error instanceof Error ? error.message : String(error) };
255
+ }
256
+ return { fragments, display };
257
+ }
258
+
230
259
  /**
231
260
  * Estimate provider-visible tool-schema tokens.
232
261
  *
@@ -241,33 +270,7 @@ export function estimateToolSchemaTokens(tools: ToolSchemaSource, tokenizer: Tok
241
270
  const cached = cache.byTokenizer.get(tokenizer);
242
271
  if (cached?.revision === cache.revision && cached.sourceRevision === sourceRevision) return cached.tokens;
243
272
 
244
- const fragments: string[] = [];
245
- for (const tool of tools) {
246
- // Extension-supplied tools may carry a non-string name/description or a
247
- // parameters value whose wire schema stringifies to `undefined` (e.g. a
248
- // callable schema that escaped normalization). A non-string fragment is
249
- // fatal inside the native tokenizer, so only real strings are counted.
250
- const name = tool.name;
251
- const description = tool.description;
252
- const parameters = tool.parameters;
253
- if (typeof name === "string") fragments.push(name);
254
- if (typeof description === "string") fragments.push(description);
255
- try {
256
- const wireTool: AiTool = {
257
- name,
258
- description,
259
- parameters: parameters as AiTool["parameters"],
260
- examples: tool.examples,
261
- };
262
- const wireJson = JSON.stringify(toolWireSchema(wireTool) ?? {});
263
- if (typeof wireJson === "string") fragments.push(wireJson);
264
- // The agent loop appends rendered examples to the wire description.
265
- const examplesBlock = renderToolExamples(wireTool);
266
- if (examplesBlock) fragments.push(examplesBlock);
267
- } catch {
268
- // Schema may contain functions or cycles; ignore.
269
- }
270
- }
273
+ const fragments = tools.flatMap(tool => toolSchemaFragments(tool).fragments);
271
274
  const tokens = tokenizer.countTokens(fragments);
272
275
  cache.byTokenizer.set(tokenizer, { revision: cache.revision, sourceRevision, tokens });
273
276
  return tokens;
@@ -454,23 +457,11 @@ export function computeContextBreakdown(session: ContextUsageSession, options: C
454
457
  }
455
458
 
456
459
  const categories: CategoryInfo[] = [
457
- { id: "systemPrompt", label: "System prompt", tokens: systemPromptTokens, color: "accent", glyph: CELL_FILLED },
458
- { id: "systemTools", label: "System tools", tokens: toolsTokens, color: "warning", glyph: CELL_FILLED },
459
- {
460
- id: "systemContext",
461
- label: "System context",
462
- tokens: systemContextTokens,
463
- color: "customMessageLabel",
464
- glyph: CELL_FILLED,
465
- },
466
- { id: "skills", label: "Skills", tokens: skillsTokens, color: "success", glyph: CELL_FILLED },
467
- {
468
- id: "messages",
469
- label: "Messages",
470
- tokens: messagesTokens,
471
- color: "userMessageText",
472
- glyph: CELL_FILLED_MESSAGES,
473
- },
460
+ { id: "systemPrompt", label: "System prompt", tokens: systemPromptTokens },
461
+ { id: "systemTools", label: "System tools", tokens: toolsTokens },
462
+ { id: "systemContext", label: "System context", tokens: systemContextTokens },
463
+ { id: "skills", label: "Skills", tokens: skillsTokens },
464
+ { id: "messages", label: "Messages", tokens: messagesTokens },
474
465
  ];
475
466
 
476
467
  let autoCompactBufferTokens = 0;
@@ -504,520 +495,3 @@ export function computeContextBreakdown(session: ContextUsageSession, options: C
504
495
  snapcompact: options.snapcompact,
505
496
  };
506
497
  }
507
-
508
- interface CellSpec {
509
- glyph: string;
510
- color: "accent" | "warning" | "success" | "userMessageText" | "customMessageLabel" | "muted" | "dim";
511
- }
512
-
513
- function planCells(breakdown: ContextBreakdown): CellSpec[] {
514
- const cells: CellSpec[] = [];
515
- const window = breakdown.contextWindow;
516
-
517
- if (window <= 0) {
518
- for (let i = 0; i < GRID_CELLS; i++) {
519
- cells.push({ glyph: CELL_FREE, color: "dim" });
520
- }
521
- return cells;
522
- }
523
-
524
- const tokensPerCell = window / GRID_CELLS;
525
-
526
- const ratioCells = (tokens: number): number => {
527
- if (tokens <= 0) return 0;
528
- return Math.max(1, Math.round(tokens / tokensPerCell));
529
- };
530
-
531
- const categoryCounts = breakdown.categories.map(category => ({
532
- category,
533
- count: ratioCells(category.tokens),
534
- }));
535
-
536
- let bufferCount = ratioCells(breakdown.autoCompactBufferTokens);
537
-
538
- let usedCount = categoryCounts.reduce((sum, c) => sum + c.count, 0);
539
-
540
- // Prevent the visualization from over-running the grid.
541
- const maxUsable = GRID_CELLS - bufferCount;
542
- if (usedCount > maxUsable) {
543
- // Scale categories proportionally down to fit.
544
- let overflow = usedCount - maxUsable;
545
- // Trim from the largest categories first to preserve visibility for small ones.
546
- const order = [...categoryCounts].sort((a, b) => b.count - a.count);
547
- for (const entry of order) {
548
- while (overflow > 0 && entry.count > 1) {
549
- entry.count -= 1;
550
- overflow -= 1;
551
- }
552
- }
553
- usedCount = categoryCounts.reduce((sum, c) => sum + c.count, 0);
554
- if (usedCount + bufferCount > GRID_CELLS) {
555
- bufferCount = Math.max(0, GRID_CELLS - usedCount);
556
- }
557
- }
558
-
559
- for (const { category, count } of categoryCounts) {
560
- for (let i = 0; i < count; i++) {
561
- cells.push({ glyph: category.glyph, color: category.color });
562
- }
563
- }
564
-
565
- const freeCount = Math.max(0, GRID_CELLS - cells.length - bufferCount);
566
- for (let i = 0; i < freeCount; i++) {
567
- cells.push({ glyph: CELL_FREE, color: "dim" });
568
- }
569
- for (let i = 0; i < bufferCount; i++) {
570
- cells.push({ glyph: CELL_BUFFER, color: "warning" });
571
- }
572
-
573
- // Pad to exactly GRID_CELLS in case rounding undershot.
574
- while (cells.length < GRID_CELLS) {
575
- cells.push({ glyph: CELL_FREE, color: "dim" });
576
- }
577
- return cells.slice(0, GRID_CELLS);
578
- }
579
-
580
- function percentString(part: number, whole: number, fractionDigits = 1): string {
581
- if (whole <= 0) return "0%";
582
- const pct = (part / whole) * 100;
583
- if (pct > 0 && pct < 0.05) return "<0.1%";
584
- return `${pct.toFixed(fractionDigits)}%`;
585
- }
586
-
587
- /** One styled run of a legend line: bold (`strong`), a theme color, or plain. */
588
- interface LegendPart {
589
- t: string;
590
- s?: ThemeColor | "strong";
591
- }
592
-
593
- /** Legend lines as styled runs, shared by the ANSI panel and the native description. */
594
- function buildLegendParts(breakdown: ContextBreakdown): LegendPart[][] {
595
- const lines: LegendPart[][] = [];
596
- const { model, contextWindow, categories, usedTokens, autoCompactBufferTokens, freeTokens } = breakdown;
597
-
598
- const modelName = model?.name ?? model?.id ?? "no model";
599
- const modelId = model?.id ?? "unknown";
600
- const windowLabel = formatNumber(contextWindow).toLowerCase();
601
-
602
- lines.push([
603
- { t: `${modelName}`, s: "strong" },
604
- { t: ` (${windowLabel} context)`, s: "dim" },
605
- ]);
606
- lines.push([{ t: `${modelId}[${windowLabel}]`, s: "muted" }]);
607
- lines.push([
608
- { t: formatNumber(usedTokens), s: "strong" },
609
- { t: `/${windowLabel} tokens`, s: "dim" },
610
- { t: ` (${percentString(usedTokens, contextWindow)})`, s: "muted" },
611
- ]);
612
- lines.push([]);
613
- lines.push([{ t: "Estimated usage by category", s: "muted" }]);
614
-
615
- for (const category of categories) {
616
- const pct = percentString(category.tokens, contextWindow);
617
- lines.push([
618
- { t: category.glyph, s: category.color },
619
- { t: ` ${category.label}: ` },
620
- { t: formatNumber(category.tokens), s: "strong" },
621
- { t: " " },
622
- { t: `tokens (${pct})`, s: "dim" },
623
- ]);
624
- }
625
-
626
- lines.push([
627
- { t: CELL_FREE, s: "dim" },
628
- { t: " Free space: " },
629
- { t: formatNumber(freeTokens), s: "strong" },
630
- { t: " " },
631
- { t: `(${percentString(freeTokens, contextWindow)})`, s: "dim" },
632
- ]);
633
-
634
- if (autoCompactBufferTokens > 0) {
635
- lines.push([
636
- { t: CELL_BUFFER, s: "warning" },
637
- { t: " Autocompact buffer: " },
638
- { t: formatNumber(autoCompactBufferTokens), s: "strong" },
639
- { t: " " },
640
- { t: `tokens (${percentString(autoCompactBufferTokens, contextWindow)})`, s: "dim" },
641
- ]);
642
- }
643
-
644
- const snap = buildSnapcompactParts(breakdown);
645
- if (snap.length > 0) lines.push([], ...snap);
646
- return lines;
647
- }
648
-
649
- /** Snapcompact savings lines of the legend; empty when no snapcompact setting is on. */
650
- function buildSnapcompactParts(breakdown: ContextBreakdown): LegendPart[][] {
651
- const lines: LegendPart[][] = [];
652
- const { usedTokens } = breakdown;
653
- const snap = breakdown.snapcompact;
654
- if (snap) {
655
- if (!snap.visionCapable) {
656
- lines.push([{ t: "Snapcompact: inactive (model has no image input)", s: "muted" }]);
657
- } else {
658
- lines.push([{ t: "Snapcompact (estimated wire savings)", s: "muted" }]);
659
- if (snap.systemPrompt) {
660
- const sp = snap.systemPrompt;
661
- const scope = sp.scope === "agents-md" ? "AGENTS.md" : "all";
662
- if (sp.applied) {
663
- lines.push([
664
- { t: ` System prompt (${scope}): saves ` },
665
- { t: `~${formatNumber(sp.savedTokens)}`, s: "strong" },
666
- { t: " " },
667
- {
668
- t: `(${formatNumber(sp.textTokens)} text → ${sp.frames} frame${sp.frames === 1 ? "" : "s"} ≈ ${formatNumber(sp.imageTokens)})`,
669
- s: "dim",
670
- },
671
- ]);
672
- } else {
673
- const reason =
674
- sp.reason === "budget"
675
- ? "image budget exhausted"
676
- : sp.reason === "empty"
677
- ? "nothing to image"
678
- : "frames would not save tokens";
679
- lines.push([{ t: ` System prompt (${scope}): ` }, { t: `stays text (${reason})`, s: "dim" }]);
680
- }
681
- }
682
- if (snap.toolResults) {
683
- const tr = snap.toolResults;
684
- if (tr.swapped > 0) {
685
- lines.push([
686
- { t: " Tool results: saves " },
687
- { t: `~${formatNumber(tr.savedTokens)}`, s: "strong" },
688
- { t: " " },
689
- {
690
- t: `(${tr.swapped}/${tr.total} imaged, ${formatNumber(tr.textTokens)} text → ${tr.frames} frames ≈ ${formatNumber(tr.imageTokens)})`,
691
- s: "dim",
692
- },
693
- ]);
694
- } else {
695
- lines.push([{ t: " Tool results: " }, { t: `none imaged (${tr.total} in history)`, s: "dim" }]);
696
- }
697
- }
698
- if (snap.savedTokens > 0) {
699
- lines.push([
700
- { t: " Next request: " },
701
- { t: `~${formatNumber(Math.max(0, usedTokens - snap.savedTokens))}`, s: "strong" },
702
- { t: " " },
703
- { t: "tokens on the wire", s: "dim" },
704
- ]);
705
- }
706
- }
707
- }
708
-
709
- return lines;
710
- }
711
-
712
- function buildLegendLines(breakdown: ContextBreakdown, theme: Theme): string[] {
713
- return buildLegendParts(breakdown).map(line => {
714
- let out = "";
715
- for (const part of line) {
716
- out += part.s === "strong" ? theme.bold(part.t) : part.s ? theme.fg(part.s, part.t) : part.t;
717
- }
718
- return out;
719
- });
720
- }
721
-
722
- /** Stacked meter parts in grid order: the categories, free space as the empty track, then the hatched buffer. */
723
- function contextMeterParts(
724
- breakdown: ContextBreakdown,
725
- ): { value: number; token?: string; label?: string; hatch?: boolean }[] {
726
- const window = breakdown.contextWindow;
727
- const parts: { value: number; token?: string; label?: string; hatch?: boolean }[] = breakdown.categories
728
- .filter(category => category.tokens > 0)
729
- .map(category => ({
730
- value: category.tokens / window,
731
- token: category.color,
732
- label: `${category.label} · ${formatNumber(category.tokens)} tokens (${percentString(category.tokens, window)})`,
733
- }));
734
- parts.push({
735
- value: breakdown.freeTokens / window,
736
- token: "track",
737
- label: `Free space · ${formatNumber(breakdown.freeTokens)} tokens (${percentString(breakdown.freeTokens, window)})`,
738
- });
739
- if (breakdown.autoCompactBufferTokens > 0) {
740
- parts.push({
741
- value: breakdown.autoCompactBufferTokens / window,
742
- token: "warning",
743
- hatch: true,
744
- label: `Autocompact buffer · ${formatNumber(breakdown.autoCompactBufferTokens)} tokens (${percentString(breakdown.autoCompactBufferTokens, window)})`,
745
- });
746
- }
747
- return parts;
748
- }
749
-
750
- /**
751
- * One line of the native `/context` breakdown: a swatch in the part's bar
752
- * color, its name, its tokens and its share of the window; the exact count
753
- * is its tooltip.
754
- */
755
- function contextShareRow(
756
- key: string,
757
- role: string,
758
- swatch: TspSpan,
759
- label: string,
760
- tokens: number,
761
- window: number,
762
- ): NativeNode {
763
- return node(
764
- "row",
765
- { role, align: "center", title: `${label} · ${tokens.toLocaleString("en-US")} tokens` },
766
- [
767
- text([swatch], { role: "zeta.context.swatch", wrap: "none" }),
768
- text(label, { role: "zeta.context.label", grow: 1, wrap: "none", truncate: "end" }),
769
- text(formatNumber(tokens), { role: "zeta.context.tokens", wrap: "none" }),
770
- text(percentString(tokens, window), { role: "zeta.context.share", wrap: "none" }),
771
- ],
772
- key,
773
- );
774
- }
775
-
776
- /**
777
- * The snapcompact estimate as a titled group of lines (what is imaged, how,
778
- * and what it saves), or a note saying why it is inactive; `undefined` when
779
- * no snapcompact setting is on.
780
- */
781
- function describeSnapcompact(breakdown: ContextBreakdown): NativeNode | undefined {
782
- const snap = breakdown.snapcompact;
783
- if (!snap) return undefined;
784
- const head = text([span("Snapcompact", "strong"), span(" · estimated savings on the wire", "dim")], {
785
- role: "zeta.context.snap.head",
786
- });
787
- if (!snap.visionCapable) {
788
- const note = text("Inactive: the model has no image input.", { role: "zeta.context.snap.note" });
789
- return node("col", { role: "zeta.context.snap" }, [head, note], "snapcompact");
790
- }
791
- const lines: { label: string; detail: string; value?: TspSpan }[] = [];
792
- const sp = snap.systemPrompt;
793
- if (sp) {
794
- const label = `System prompt · ${sp.scope === "agents-md" ? "AGENTS.md" : "all"}`;
795
- if (sp.applied) {
796
- lines.push({
797
- label,
798
- detail: `${formatNumber(sp.textTokens)} text → ${sp.frames} frame${sp.frames === 1 ? "" : "s"} ≈ ${formatNumber(sp.imageTokens)}`,
799
- value: span(`−${formatNumber(sp.savedTokens)}`, "success"),
800
- });
801
- } else {
802
- const reason =
803
- sp.reason === "budget"
804
- ? "image budget exhausted"
805
- : sp.reason === "empty"
806
- ? "nothing to image"
807
- : "frames would not save tokens";
808
- lines.push({ label, detail: `Stays text: ${reason}` });
809
- }
810
- }
811
- const tr = snap.toolResults;
812
- if (tr) {
813
- lines.push(
814
- tr.swapped > 0
815
- ? {
816
- label: "Tool results",
817
- detail: `${tr.swapped} of ${tr.total} imaged · ${formatNumber(tr.textTokens)} text → ${tr.frames} frames ≈ ${formatNumber(tr.imageTokens)}`,
818
- value: span(`−${formatNumber(tr.savedTokens)}`, "success"),
819
- }
820
- : { label: "Tool results", detail: `None imaged · ${tr.total} in history` },
821
- );
822
- }
823
- if (snap.savedTokens > 0) {
824
- lines.push({
825
- label: "Next request",
826
- detail: "tokens on the wire",
827
- value: span(`~${formatNumber(Math.max(0, breakdown.usedTokens - snap.savedTokens))}`, "strong"),
828
- });
829
- }
830
- const rows = lines.map((line, index) =>
831
- node(
832
- "row",
833
- { role: "zeta.context.snap.row", align: "baseline" },
834
- [
835
- text(line.label, { role: "zeta.context.label", wrap: "none" }),
836
- text(line.detail, { role: "zeta.context.detail", grow: 1, wrap: "none", truncate: "end" }),
837
- ...(line.value ? [text([line.value], { role: "zeta.context.tokens", wrap: "none" })] : []),
838
- ],
839
- `snap-${index}`,
840
- ),
841
- );
842
- return node("col", { role: "zeta.context.snap" }, [head, ...rows], "snapcompact");
843
- }
844
-
845
- /**
846
- * The `/context` body for terminals that draw `meter`: the tokens used as
847
- * the figure that leads, beside the room left before auto-compaction; one
848
- * stacked bar of the parts (categories, free space as the empty track, the
849
- * hatched buffer) ticked where compaction fires; the breakdown in the bar's
850
- * order with free space and the buffer under it; then the snapcompact
851
- * estimate when one is on. {@link contextUsageHead} names the model.
852
- */
853
- function describeContextFrame(breakdown: ContextBreakdown): NativeNode {
854
- const { contextWindow: window, usedTokens, freeTokens, autoCompactBufferTokens, thresholdTokens } = breakdown;
855
- const parts = contextMeterParts(breakdown);
856
- const used = Math.min(1, usedTokens / window);
857
- const room =
858
- thresholdTokens === undefined
859
- ? `${formatNumber(freeTokens)} free`
860
- : usedTokens >= thresholdTokens
861
- ? `Past auto-compaction at ${percentString(thresholdTokens, window, 0)}`
862
- : `${formatNumber(thresholdTokens - usedTokens)} left before auto-compaction at ${percentString(thresholdTokens, window, 0)}`;
863
- const summary = node(
864
- "row",
865
- { role: "zeta.context.summary", align: "baseline", wrap: true },
866
- [
867
- text(
868
- [
869
- span(formatNumber(usedTokens), "strong"),
870
- span(` of ${formatNumber(window)} tokens · ${percentString(usedTokens, window, 0)}`, "dim"),
871
- ],
872
- { role: "zeta.context.used", grow: 1, wrap: "none" },
873
- ),
874
- text(room, { role: "zeta.context.room", wrap: "none" }),
875
- ],
876
- "summary",
877
- );
878
- const marks =
879
- thresholdTokens !== undefined
880
- ? [
881
- {
882
- at: thresholdTokens / window,
883
- tone: "warning" as const,
884
- title: `Auto-compaction at ${percentString(thresholdTokens, window, 0)} · ${formatNumber(thresholdTokens)} tokens`,
885
- },
886
- ]
887
- : undefined;
888
- const bar = node(
889
- "meter",
890
- { value: used, style: "bar", size: "lg", parts, ...(marks ? { marks } : {}), aria: "Context usage by category" },
891
- undefined,
892
- "bar",
893
- );
894
- const shares = breakdown.categories.map(category =>
895
- contextShareRow(
896
- category.id,
897
- "zeta.context.cat",
898
- span("■", category.color),
899
- category.label,
900
- category.tokens,
901
- window,
902
- ),
903
- );
904
- shares.push(contextShareRow("free", "zeta.context.cat.free", span("□", "dim"), "Free space", freeTokens, window));
905
- if (autoCompactBufferTokens > 0) {
906
- shares.push(
907
- contextShareRow(
908
- "buffer",
909
- "zeta.context.cat.buffer",
910
- span("▨", "warning"),
911
- "Autocompact buffer",
912
- autoCompactBufferTokens,
913
- window,
914
- ),
915
- );
916
- }
917
- const children = [summary, bar, node("col", { role: "zeta.context.cats" }, shares, "cats")];
918
- const snap = describeSnapcompact(breakdown);
919
- if (snap) children.push(snap);
920
- return col(children, { role: "zeta.context" });
921
- }
922
-
923
- /** The `/context` title: the model once one is selected (the body leads with its window). */
924
- export function contextUsageHead(breakdown: ContextBreakdown): TspText {
925
- if (breakdown.contextWindow <= 0) return [span("Context usage", "strong")];
926
- const modelName = breakdown.model?.name ?? breakdown.model?.id ?? "no model";
927
- return [span("Context", "strong"), span(` · ${modelName}`, "muted")];
928
- }
929
-
930
- /**
931
- * Native context-usage panel for terminals without `meter`: the cell grid as
932
- * unwrapped styled rows beside the legend. The terminal places the legend
933
- * beside the grid, or below it when narrow.
934
- */
935
- export function describeContextUsage(breakdown: ContextBreakdown): NativeNode {
936
- if (breakdown.contextWindow <= 0) {
937
- return text([{ t: "Context usage is unavailable: no model is selected for this session.", s: "muted" }]);
938
- }
939
- const cells = planCells(breakdown);
940
- const grid: NativeNode[] = [];
941
- for (let gridRow = 0; gridRow < GRID_ROWS; gridRow++) {
942
- const spans: TspSpan[] = [];
943
- for (let gridCol = 0; gridCol < GRID_COLS; gridCol++) {
944
- const cell = cells[gridRow * GRID_COLS + gridCol]!;
945
- spans.push({ t: gridCol === 0 ? cell.glyph : ` ${cell.glyph}`, s: cell.color });
946
- }
947
- grid.push(node("text", { spans, wrap: "none" }, undefined, `row-${gridRow}`));
948
- }
949
- const legend = buildLegendParts(breakdown).map((line, index) =>
950
- node("text", { spans: line.length > 0 ? line : [{ t: " " }] }, undefined, `legend-${index}`),
951
- );
952
- return row([col(grid), col(legend)], {
953
- gap: "lg",
954
- wrap: true,
955
- role: "zeta.context.usage",
956
- });
957
- }
958
-
959
- /**
960
- * The `/context` report body, without a frame or title of its own (the panel
961
- * showing it is titled {@link contextUsageHead}): ANSI renders the cell grid
962
- * beside the legend; natively it is drawn with `meter`s where the terminal has
963
- * them and as the glyph grid otherwise.
964
- */
965
- export class ContextUsageView extends Container {
966
- readonly #breakdown: ContextBreakdown;
967
- #native: { meter: boolean; node: NativeNode } | undefined;
968
-
969
- constructor(breakdown: ContextBreakdown, theme: Theme) {
970
- super();
971
- this.#breakdown = breakdown;
972
- this.addChild(new Text(renderContextUsage(breakdown, theme), 0, 0));
973
- }
974
-
975
- override describe(cx: DescribeContext): NativeNode {
976
- const meter = cx.supports("meter");
977
- if (this.#native?.meter === meter) return this.#native.node;
978
- const breakdown = this.#breakdown;
979
- const described =
980
- meter && breakdown.contextWindow > 0 ? describeContextFrame(breakdown) : describeContextUsage(breakdown);
981
- this.#native = { meter, node: described };
982
- return described;
983
- }
984
- }
985
-
986
- /**
987
- * Render a colorful context-usage panel as ANSI text. Output is a series of
988
- * lines pairing the grid (left) with the legend (right).
989
- */
990
- export function renderContextUsage(breakdown: ContextBreakdown, theme: Theme): string {
991
- if (breakdown.contextWindow <= 0) {
992
- return theme.fg("muted", "Context usage is unavailable: no model is selected for this session.");
993
- }
994
-
995
- const cells = planCells(breakdown);
996
- const legend = buildLegendLines(breakdown, theme);
997
-
998
- const totalLines = Math.max(GRID_ROWS, legend.length);
999
- const lines: string[] = [];
1000
-
1001
- for (let row = 0; row < totalLines; row++) {
1002
- let gridSegment = "";
1003
- if (row < GRID_ROWS) {
1004
- const rowCells: string[] = [];
1005
- for (let col = 0; col < GRID_COLS; col++) {
1006
- const cell = cells[row * GRID_COLS + col];
1007
- rowCells.push(theme.fg(cell.color, cell.glyph));
1008
- }
1009
- gridSegment = rowCells.join(" ");
1010
- } else {
1011
- // Pad with blanks the same visible width as a grid row so legend lines
1012
- // past the grid stay aligned with their column.
1013
- const blank = " ".repeat(GRID_COLS * 2 - 1);
1014
- gridSegment = blank;
1015
- }
1016
-
1017
- const legendSegment = legend[row] ?? "";
1018
- const line = legendSegment.length > 0 ? `${gridSegment}${GRID_GUTTER}${legendSegment}` : gridSegment;
1019
- lines.push(line);
1020
- }
1021
-
1022
- return lines.join("\n");
1023
- }
@@ -354,6 +354,13 @@ export declare function parseKittyDirectPlacementLine(line: string): ParsedKitty
354
354
  * byte-identical between frames, so the diff never rewrites them.
355
355
  */
356
356
  export declare function directPlacementLift(line: string): number;
357
+ /**
358
+ * Re-anchor an {@link Image} direct-placement line `lift` rows above its own
359
+ * row instead of its encoded `CUU(rows-1)`. The renderer lowers the lift when
360
+ * the block's top is clipped by the frame: the cursor-up would otherwise climb
361
+ * past the frame's first row into whatever the terminal shows above it.
362
+ */
363
+ export declare function withDirectPlacementLift(line: string, lift: number): string;
357
364
  /**
358
365
  * Rebuild an {@link Image} direct-placement line for the viewport row it is
359
366
  * written at. The component-rendered line encodes `CUU(rows-1)`, which clamps