@linxiraos/pi-tui 1.4.4 → 1.4.7

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 (363) hide show
  1. package/CHANGELOG.md +208 -207
  2. package/README.md +34 -34
  3. package/dist/types/app-keybindings.d.ts +20 -0
  4. package/dist/types/apps/session-picker.d.ts +5 -0
  5. package/dist/types/charts/chart-plan.d.ts +9 -7
  6. package/dist/types/chat/assistant-message.d.ts +15 -3
  7. package/dist/types/chat/bash-execution.d.ts +2 -0
  8. package/dist/types/chat/display-preferences.d.ts +2 -0
  9. package/dist/types/chat/extension-types.d.ts +31 -0
  10. package/dist/types/chat/reply-write.d.ts +48 -0
  11. package/dist/types/chat/table-chart.d.ts +4 -3
  12. package/dist/types/chat/tool-execution.d.ts +1 -2
  13. package/dist/types/chat/transcript-outline.d.ts +7 -0
  14. package/dist/types/chat/transcript-render-helpers.d.ts +2 -0
  15. package/dist/types/chrome/context-map.d.ts +15 -0
  16. package/dist/types/chrome/context-presentation.d.ts +48 -0
  17. package/dist/types/chrome/context-view-model.d.ts +77 -0
  18. package/dist/types/chrome/index.d.ts +1 -0
  19. package/dist/types/chrome/transcript-notice.d.ts +35 -0
  20. package/dist/types/chrome/transcript-status.d.ts +20 -8
  21. package/dist/types/components/editor.d.ts +8 -0
  22. package/dist/types/components/image.d.ts +20 -0
  23. package/dist/types/components/loader.d.ts +1 -1
  24. package/dist/types/components/markdown.d.ts +7 -0
  25. package/dist/types/native/blobs.d.ts +11 -1
  26. package/dist/types/native/picker.d.ts +4 -4
  27. package/dist/types/overlays/advisor-config.d.ts +6 -0
  28. package/dist/types/overlays/agent-hub-projection.d.ts +3 -1
  29. package/dist/types/overlays/annotation-overlay.d.ts +7 -1
  30. package/dist/types/overlays/annotation-types.d.ts +28 -0
  31. package/dist/types/overlays/ask-dialog.d.ts +12 -3
  32. package/dist/types/overlays/btw-history-panel.d.ts +16 -2
  33. package/dist/types/overlays/btw-history.d.ts +7 -0
  34. package/dist/types/overlays/btw-panel.d.ts +2 -0
  35. package/dist/types/overlays/context-viewer-format.d.ts +42 -0
  36. package/dist/types/overlays/context-viewer-overview.d.ts +70 -0
  37. package/dist/types/overlays/context-viewer.d.ts +25 -0
  38. package/dist/types/overlays/hook-input.d.ts +1 -0
  39. package/dist/types/overlays/login-dialog.d.ts +5 -1
  40. package/dist/types/overlays/mcp-add-wizard.d.ts +2 -0
  41. package/dist/types/overlays/model-browser.d.ts +10 -1
  42. package/dist/types/overlays/oauth-selector.d.ts +23 -0
  43. package/dist/types/overlays/pause-screen.d.ts +13 -3
  44. package/dist/types/overlays/plan-review-overlay.d.ts +2 -0
  45. package/dist/types/overlays/rewind-selector.d.ts +1 -1
  46. package/dist/types/overlays/running-subagent-badge.d.ts +7 -1
  47. package/dist/types/overlays/session-selector.d.ts +22 -2
  48. package/dist/types/prompt/composer.d.ts +43 -0
  49. package/dist/types/prompt/interactive-context-helpers.d.ts +10 -3
  50. package/dist/types/prompt/macos-spelling.d.ts +2 -2
  51. package/dist/types/render/extension-links.d.ts +65 -0
  52. package/dist/types/render/hyperlink.d.ts +38 -7
  53. package/dist/types/render/index.d.ts +1 -0
  54. package/dist/types/render/output-pane.d.ts +1 -1
  55. package/dist/types/render/render-utils.d.ts +7 -1
  56. package/dist/types/setup/scenes/glyph.d.ts +1 -1
  57. package/dist/types/setup/scenes/model.d.ts +1 -1
  58. package/dist/types/setup/scenes/outro.d.ts +5 -4
  59. package/dist/types/setup/scenes/sign-in.d.ts +13 -8
  60. package/dist/types/setup/scenes/types.d.ts +16 -1
  61. package/dist/types/setup/startup-splash.d.ts +1 -1
  62. package/dist/types/setup/wizard-overlay.d.ts +11 -7
  63. package/dist/types/setup/wizard.d.ts +5 -1
  64. package/dist/types/status-line/component.d.ts +3 -3
  65. package/dist/types/status-line/context-usage.d.ts +42 -35
  66. package/dist/types/status-line/host.d.ts +6 -2
  67. package/dist/types/terminal-capabilities.d.ts +7 -0
  68. package/dist/types/theme/symbols.d.ts +1 -1
  69. package/dist/types/theme/theme.d.ts +0 -23
  70. package/dist/types/tools/ask.d.ts +4 -0
  71. package/dist/types/tools/bash-interactive.d.ts +6 -0
  72. package/dist/types/tools/bash.d.ts +2 -0
  73. package/dist/types/tools/default-renderer.d.ts +6 -4
  74. package/dist/types/tools/edit.d.ts +3 -1
  75. package/dist/types/tools/fetch.d.ts +1 -0
  76. package/dist/types/tools/github.d.ts +3 -0
  77. package/dist/types/tools/grouped-file-output.d.ts +2 -0
  78. package/dist/types/tools/irc.d.ts +6 -0
  79. package/dist/types/tools/json-tree.d.ts +23 -4
  80. package/dist/types/tools/lsp.d.ts +2 -0
  81. package/dist/types/tools/mcp.d.ts +7 -6
  82. package/dist/types/tools/native-view.d.ts +1 -1
  83. package/dist/types/tools/read.d.ts +3 -0
  84. package/dist/types/tools/renderer.d.ts +2 -0
  85. package/dist/types/tools/streaming-output.d.ts +11 -0
  86. package/dist/types/tools/task.d.ts +9 -1
  87. package/dist/types/tools/url-scheme-host.d.ts +17 -0
  88. package/dist/types/tools/wait.d.ts +16 -2
  89. package/dist/types/tools/yield.d.ts +1 -1
  90. package/dist/types/tui.d.ts +9 -2
  91. package/dist/types/vim.d.ts +39 -0
  92. package/package.json +10 -14
  93. package/src/app-keybindings.d.ts +20 -0
  94. package/src/app-keybindings.ts +20 -0
  95. package/src/apps/session-picker.ts +7 -0
  96. package/src/charts/chart-plan.d.ts +9 -7
  97. package/src/charts/chart-plan.ts +20 -50
  98. package/src/chat/advisor-message.ts +2 -0
  99. package/src/chat/assistant-message.d.ts +15 -3
  100. package/src/chat/assistant-message.ts +137 -19
  101. package/src/chat/background-tan-message.ts +4 -0
  102. package/src/chat/bash-execution.d.ts +2 -0
  103. package/src/chat/bash-execution.ts +13 -1
  104. package/src/chat/chat-transcript-builder.ts +58 -28
  105. package/src/chat/compaction-summary-message.ts +2 -1
  106. package/src/chat/display-preferences.d.ts +2 -0
  107. package/src/chat/display-preferences.ts +3 -0
  108. package/src/chat/extension-types.d.ts +31 -0
  109. package/src/chat/extension-types.ts +34 -0
  110. package/src/chat/read-tool-group.ts +1 -2
  111. package/src/chat/reply-write.d.ts +48 -0
  112. package/src/chat/reply-write.ts +127 -0
  113. package/src/chat/skill-message.ts +2 -6
  114. package/src/chat/table-chart.d.ts +4 -3
  115. package/src/chat/table-chart.ts +10 -4
  116. package/src/chat/tool-execution.d.ts +1 -2
  117. package/src/chat/tool-execution.ts +20 -13
  118. package/src/chat/transcript-outline.d.ts +7 -0
  119. package/src/chat/transcript-outline.ts +27 -0
  120. package/src/chat/transcript-render-helpers.d.ts +2 -0
  121. package/src/chat/transcript-render-helpers.ts +66 -24
  122. package/src/chrome/context-map.ts +62 -0
  123. package/src/chrome/context-presentation.ts +26 -0
  124. package/src/chrome/context-view-model.ts +73 -0
  125. package/src/chrome/index.ts +1 -0
  126. package/src/chrome/transcript-container.ts +89 -59
  127. package/src/chrome/transcript-notice.d.ts +35 -0
  128. package/src/chrome/transcript-notice.ts +83 -0
  129. package/src/chrome/transcript-status.d.ts +20 -8
  130. package/src/chrome/transcript-status.ts +29 -29
  131. package/src/components/editor.d.ts +8 -0
  132. package/src/components/editor.ts +465 -14
  133. package/src/components/image.d.ts +20 -0
  134. package/src/components/image.ts +83 -18
  135. package/src/components/loader.d.ts +1 -1
  136. package/src/components/loader.ts +1 -1
  137. package/src/components/markdown.d.ts +7 -0
  138. package/src/components/markdown.ts +225 -13
  139. package/src/hotkeys-markdown.ts +2 -0
  140. package/src/native/backend.ts +5 -66
  141. package/src/native/blobs.d.ts +11 -1
  142. package/src/native/blobs.ts +5 -3
  143. package/src/native/picker.d.ts +4 -4
  144. package/src/native/picker.ts +4 -4
  145. package/src/overlays/advisor-config.ts +10 -12
  146. package/src/overlays/agent-hub-projection.d.ts +3 -1
  147. package/src/overlays/agent-hub-projection.ts +6 -5
  148. package/src/overlays/agent-hub.ts +51 -42
  149. package/src/overlays/annotation-overlay.ts +125 -37
  150. package/src/overlays/annotation-types.ts +24 -0
  151. package/src/overlays/ask-dialog.ts +125 -35
  152. package/src/overlays/btw-history-panel.ts +124 -12
  153. package/src/overlays/btw-history.ts +11 -0
  154. package/src/overlays/btw-panel.ts +8 -4
  155. package/src/overlays/context-viewer-format.ts +145 -0
  156. package/src/overlays/context-viewer-overview.ts +381 -0
  157. package/src/overlays/context-viewer.ts +728 -0
  158. package/src/overlays/hook-input.ts +2 -0
  159. package/src/overlays/hook-selector.ts +2 -2
  160. package/src/overlays/login-dialog.ts +31 -5
  161. package/src/overlays/mcp-add-wizard.ts +6 -1
  162. package/src/overlays/model-browser.ts +37 -0
  163. package/src/overlays/model-hub.ts +1 -7
  164. package/src/overlays/model-picker.ts +1 -10
  165. package/src/overlays/oauth-selector.ts +44 -6
  166. package/src/overlays/pause-screen.ts +166 -33
  167. package/src/overlays/plan-review-overlay.ts +13 -2
  168. package/src/overlays/rewind-selector.ts +29 -12
  169. package/src/overlays/running-subagent-badge.ts +12 -1
  170. package/src/overlays/session-selector.ts +313 -42
  171. package/src/overlays/settings-defs.ts +1 -0
  172. package/src/overlays/usage-dashboard.ts +20 -14
  173. package/src/prompt/composer.ts +216 -1
  174. package/src/prompt/custom-editor.ts +6 -1
  175. package/src/prompt/emoji-autocomplete.ts +0 -2
  176. package/src/prompt/interactive-context-helpers.ts +29 -4
  177. package/src/prompt/macos-spelling.ts +24 -15
  178. package/src/render/extension-links.d.ts +65 -0
  179. package/src/render/extension-links.ts +214 -0
  180. package/src/render/hyperlink.d.ts +38 -7
  181. package/src/render/hyperlink.ts +102 -23
  182. package/src/render/index.d.ts +1 -0
  183. package/src/render/index.ts +1 -0
  184. package/src/render/output-pane.d.ts +1 -1
  185. package/src/render/output-pane.ts +60 -17
  186. package/src/render/render-utils.d.ts +7 -1
  187. package/src/render/render-utils.ts +11 -2
  188. package/src/setup/scenes/composer.ts +2 -0
  189. package/src/setup/scenes/glyph.ts +3 -1
  190. package/src/setup/scenes/model.ts +192 -29
  191. package/src/setup/scenes/outro.ts +33 -15
  192. package/src/setup/scenes/sign-in.ts +194 -392
  193. package/src/setup/scenes/theme.ts +2 -0
  194. package/src/setup/scenes/types.ts +18 -1
  195. package/src/setup/startup-splash.ts +8 -7
  196. package/src/setup/wizard-overlay.ts +164 -35
  197. package/src/setup/wizard.ts +11 -2
  198. package/src/status-line/component.ts +10 -14
  199. package/src/status-line/context-usage.ts +122 -597
  200. package/src/status-line/host.ts +6 -2
  201. package/src/terminal-capabilities.d.ts +7 -0
  202. package/src/terminal-capabilities.ts +10 -0
  203. package/src/terminal.ts +24 -2
  204. package/src/theme/defaults.json +1 -0
  205. package/src/theme/loader.ts +1 -1
  206. package/src/theme/symbols.d.ts +1 -1
  207. package/src/theme/symbols.ts +16 -0
  208. package/src/theme/theme.d.ts +0 -23
  209. package/src/theme/theme.ts +2 -75
  210. package/src/tools/ask.d.ts +4 -0
  211. package/src/tools/ask.ts +4 -0
  212. package/src/tools/ast-grep.ts +3 -2
  213. package/src/tools/bash-interactive.d.ts +49 -0
  214. package/src/tools/bash-interactive.ts +6 -1
  215. package/src/tools/bash.d.ts +2 -0
  216. package/src/tools/bash.ts +7 -23
  217. package/src/tools/default-renderer.d.ts +6 -4
  218. package/src/tools/default-renderer.ts +9 -6
  219. package/src/tools/edit.d.ts +3 -1
  220. package/src/tools/edit.ts +8 -4
  221. package/src/tools/eval.ts +14 -4
  222. package/src/tools/fetch.d.ts +1 -0
  223. package/src/tools/fetch.ts +1 -0
  224. package/src/tools/find.ts +3 -10
  225. package/src/tools/github.d.ts +3 -0
  226. package/src/tools/github.ts +23 -3
  227. package/src/tools/glob.ts +4 -3
  228. package/src/tools/grep.ts +3 -4
  229. package/src/tools/grouped-file-output.d.ts +2 -0
  230. package/src/tools/grouped-file-output.ts +8 -2
  231. package/src/tools/irc.d.ts +6 -0
  232. package/src/tools/irc.ts +6 -0
  233. package/src/tools/job-widget.ts +13 -1
  234. package/src/tools/json-tree.d.ts +23 -4
  235. package/src/tools/json-tree.ts +132 -42
  236. package/src/tools/lsp.d.ts +2 -0
  237. package/src/tools/lsp.ts +36 -15
  238. package/src/tools/mcp.d.ts +7 -6
  239. package/src/tools/mcp.ts +41 -15
  240. package/src/tools/native-view.d.ts +1 -1
  241. package/src/tools/native-view.ts +3 -3
  242. package/src/tools/read.d.ts +3 -0
  243. package/src/tools/read.ts +3 -1
  244. package/src/tools/renderer.d.ts +2 -0
  245. package/src/tools/renderer.ts +2 -0
  246. package/src/tools/streaming-output.d.ts +11 -0
  247. package/src/tools/streaming-output.ts +41 -0
  248. package/src/tools/task.d.ts +9 -1
  249. package/src/tools/task.ts +59 -16
  250. package/src/tools/url-scheme-host.d.ts +17 -0
  251. package/src/tools/url-scheme-host.ts +21 -0
  252. package/src/tools/vibe.ts +14 -3
  253. package/src/tools/wait.d.ts +16 -2
  254. package/src/tools/wait.ts +16 -2
  255. package/src/tools/yield.d.ts +1 -1
  256. package/src/tools/yield.ts +18 -9
  257. package/src/tui.d.ts +9 -2
  258. package/src/tui.ts +102 -34
  259. package/src/vim.d.ts +39 -0
  260. package/src/vim.ts +313 -22
  261. package/dist/types/theme/defaults/index.d.ts +0 -10289
  262. package/src/theme/defaults/alabaster.json +0 -103
  263. package/src/theme/defaults/amethyst.json +0 -106
  264. package/src/theme/defaults/anthracite.json +0 -103
  265. package/src/theme/defaults/basalt.json +0 -101
  266. package/src/theme/defaults/birch.json +0 -105
  267. package/src/theme/defaults/dark-abyss.json +0 -101
  268. package/src/theme/defaults/dark-arctic.json +0 -114
  269. package/src/theme/defaults/dark-aurora.json +0 -105
  270. package/src/theme/defaults/dark-catppuccin.json +0 -117
  271. package/src/theme/defaults/dark-cavern.json +0 -101
  272. package/src/theme/defaults/dark-celestial.json +0 -116
  273. package/src/theme/defaults/dark-copper.json +0 -105
  274. package/src/theme/defaults/dark-cosmos.json +0 -100
  275. package/src/theme/defaults/dark-cyberpunk.json +0 -112
  276. package/src/theme/defaults/dark-dracula.json +0 -108
  277. package/src/theme/defaults/dark-eclipse.json +0 -101
  278. package/src/theme/defaults/dark-ember.json +0 -105
  279. package/src/theme/defaults/dark-equinox.json +0 -100
  280. package/src/theme/defaults/dark-forest.json +0 -106
  281. package/src/theme/defaults/dark-github.json +0 -115
  282. package/src/theme/defaults/dark-gruvbox.json +0 -122
  283. package/src/theme/defaults/dark-lavender.json +0 -105
  284. package/src/theme/defaults/dark-lunar.json +0 -99
  285. package/src/theme/defaults/dark-midnight.json +0 -105
  286. package/src/theme/defaults/dark-monochrome.json +0 -104
  287. package/src/theme/defaults/dark-monokai.json +0 -108
  288. package/src/theme/defaults/dark-nebula.json +0 -100
  289. package/src/theme/defaults/dark-neon-noir.json +0 -110
  290. package/src/theme/defaults/dark-nord.json +0 -108
  291. package/src/theme/defaults/dark-ocean.json +0 -111
  292. package/src/theme/defaults/dark-one.json +0 -110
  293. package/src/theme/defaults/dark-poimandres.json +0 -125
  294. package/src/theme/defaults/dark-rainforest.json +0 -101
  295. package/src/theme/defaults/dark-reef.json +0 -101
  296. package/src/theme/defaults/dark-retro.json +0 -102
  297. package/src/theme/defaults/dark-rose-pine.json +0 -106
  298. package/src/theme/defaults/dark-sakura.json +0 -105
  299. package/src/theme/defaults/dark-slate.json +0 -105
  300. package/src/theme/defaults/dark-solarized.json +0 -107
  301. package/src/theme/defaults/dark-solstice.json +0 -100
  302. package/src/theme/defaults/dark-starfall.json +0 -101
  303. package/src/theme/defaults/dark-sunset.json +0 -109
  304. package/src/theme/defaults/dark-swamp.json +0 -100
  305. package/src/theme/defaults/dark-synthwave.json +0 -113
  306. package/src/theme/defaults/dark-taiga.json +0 -101
  307. package/src/theme/defaults/dark-terminal.json +0 -105
  308. package/src/theme/defaults/dark-tokyo-night.json +0 -111
  309. package/src/theme/defaults/dark-tundra.json +0 -101
  310. package/src/theme/defaults/dark-twilight.json +0 -101
  311. package/src/theme/defaults/dark-volcanic.json +0 -101
  312. package/src/theme/defaults/graphite.json +0 -102
  313. package/src/theme/defaults/index.d.ts +0 -10289
  314. package/src/theme/defaults/index.ts +0 -203
  315. package/src/theme/defaults/light-arctic.json +0 -117
  316. package/src/theme/defaults/light-aurora-day.json +0 -101
  317. package/src/theme/defaults/light-canyon.json +0 -101
  318. package/src/theme/defaults/light-catppuccin.json +0 -116
  319. package/src/theme/defaults/light-cirrus.json +0 -100
  320. package/src/theme/defaults/light-coral.json +0 -105
  321. package/src/theme/defaults/light-cyberpunk.json +0 -106
  322. package/src/theme/defaults/light-dawn.json +0 -100
  323. package/src/theme/defaults/light-dunes.json +0 -101
  324. package/src/theme/defaults/light-eucalyptus.json +0 -105
  325. package/src/theme/defaults/light-forest.json +0 -110
  326. package/src/theme/defaults/light-frost.json +0 -105
  327. package/src/theme/defaults/light-github.json +0 -125
  328. package/src/theme/defaults/light-glacier.json +0 -101
  329. package/src/theme/defaults/light-gruvbox.json +0 -118
  330. package/src/theme/defaults/light-haze.json +0 -100
  331. package/src/theme/defaults/light-honeycomb.json +0 -105
  332. package/src/theme/defaults/light-lagoon.json +0 -101
  333. package/src/theme/defaults/light-lavender.json +0 -105
  334. package/src/theme/defaults/light-meadow.json +0 -101
  335. package/src/theme/defaults/light-mint.json +0 -105
  336. package/src/theme/defaults/light-monochrome.json +0 -111
  337. package/src/theme/defaults/light-ocean.json +0 -109
  338. package/src/theme/defaults/light-one.json +0 -109
  339. package/src/theme/defaults/light-opal.json +0 -101
  340. package/src/theme/defaults/light-orchard.json +0 -101
  341. package/src/theme/defaults/light-paper.json +0 -105
  342. package/src/theme/defaults/light-poimandres.json +0 -125
  343. package/src/theme/defaults/light-prism.json +0 -100
  344. package/src/theme/defaults/light-retro.json +0 -108
  345. package/src/theme/defaults/light-sand.json +0 -105
  346. package/src/theme/defaults/light-savanna.json +0 -101
  347. package/src/theme/defaults/light-solarized.json +0 -112
  348. package/src/theme/defaults/light-soleil.json +0 -100
  349. package/src/theme/defaults/light-sunset.json +0 -109
  350. package/src/theme/defaults/light-synthwave.json +0 -108
  351. package/src/theme/defaults/light-tokyo-night.json +0 -121
  352. package/src/theme/defaults/light-wetland.json +0 -101
  353. package/src/theme/defaults/light-zenith.json +0 -99
  354. package/src/theme/defaults/limestone.json +0 -104
  355. package/src/theme/defaults/mahogany.json +0 -107
  356. package/src/theme/defaults/marble.json +0 -103
  357. package/src/theme/defaults/obsidian.json +0 -101
  358. package/src/theme/defaults/onyx.json +0 -101
  359. package/src/theme/defaults/pearl.json +0 -103
  360. package/src/theme/defaults/porcelain.json +0 -101
  361. package/src/theme/defaults/quartz.json +0 -106
  362. package/src/theme/defaults/sandstone.json +0 -105
  363. package/src/theme/defaults/titanium.json +0 -100
@@ -3,16 +3,7 @@ import type { CompactionSettings } from "@linxiraos/pi-agent-core/compaction";
3
3
  import { effectiveReserveTokens, resolveThresholdTokens } from "@linxiraos/pi-agent-core/compaction";
4
4
  import type { Tool as AiTool, Model } from "@linxiraos/pi-ai";
5
5
  import { renderToolExamples } from "@linxiraos/pi-ai/dialect";
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";
6
+ import { stripSchemaDescriptions, toolWireSchema } from "@linxiraos/pi-ai/utils/schema";
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 {
@@ -149,6 +128,11 @@ export interface NonMessageTokenSource {
149
128
  readonly state?: {
150
129
  readonly tools?: readonly ContextTool[];
151
130
  };
131
+ /**
132
+ * Whether requests to `model` ship description-stripped tool specs because
133
+ * the catalog rides in the system prompt (`Agent.prunesToolDescriptions`).
134
+ */
135
+ prunesToolDescriptions?(model: Model | undefined): boolean;
152
136
  };
153
137
  readonly skills?: readonly ContextSkill[];
154
138
  /** Provider-facing, session-frozen descriptions when available. */
@@ -187,7 +171,10 @@ type ToolSchemaSource = readonly ContextTool[];
187
171
 
188
172
  interface ToolSchemaTokenCache {
189
173
  revision: number;
190
- byTokenizer: WeakMap<Tokenizer, { revision: number; sourceRevision: number; tokens: number }>;
174
+ byTokenizer: WeakMap<
175
+ Tokenizer,
176
+ { revision: number; sourceRevision: number; pruneDescriptions: boolean; tokens: number }
177
+ >;
191
178
  }
192
179
 
193
180
  /**
@@ -227,49 +214,105 @@ export function invalidateToolSchemaMetadata(tools: ToolSchemaSource): void {
227
214
  toolSchemaTokenCache(tools).revision++;
228
215
  }
229
216
 
217
+ /** Provider-visible text of one tool definition, in wire order. */
218
+ export interface ToolSchemaFragments {
219
+ /** Name, description, wire schema JSON, then rendered examples; fields that cannot be serialized are omitted. */
220
+ readonly fragments: string[];
221
+ /** `fragments` with the schema JSON indented for reading; present only when a display indent was requested. */
222
+ readonly display?: string[];
223
+ /** Why serialization stopped; the schema or examples after that point are missing from `fragments`. */
224
+ readonly schemaError?: string;
225
+ }
226
+
227
+ /** How {@link toolSchemaFragments} renders one tool definition. */
228
+ export interface ToolSchemaFragmentOptions {
229
+ /** Also return `display`: the same fragments with the schema JSON indented by this many spaces. */
230
+ displayIndent?: number;
231
+ /**
232
+ * Mirror `normalizeTools({ pruneDescriptions: true })`: the wire spec is the
233
+ * name plus the description-stripped schema, with no description or examples.
234
+ */
235
+ pruneDescriptions?: boolean;
236
+ }
237
+
238
+ /**
239
+ * Provider-visible text of one tool definition. `displayIndent` additionally
240
+ * returns `display`, the same fragments with the schema JSON indented, from
241
+ * the same schema conversion.
242
+ */
243
+ export function toolSchemaFragments(tool: ContextTool, options: ToolSchemaFragmentOptions = {}): ToolSchemaFragments {
244
+ const { displayIndent, pruneDescriptions = false } = options;
245
+ // Extension-supplied tools may carry a non-string name/description or a
246
+ // parameters value whose wire schema stringifies to `undefined` (e.g. a
247
+ // callable schema that escaped normalization). A non-string fragment is
248
+ // fatal inside the native tokenizer, so only real strings are kept.
249
+ const { name, description, parameters } = tool;
250
+ const fragments: string[] = [];
251
+ const display: string[] | undefined = displayIndent === undefined ? undefined : [];
252
+ const push = (wire: string, shown: string = wire): void => {
253
+ fragments.push(wire);
254
+ display?.push(shown);
255
+ };
256
+ if (typeof name === "string") push(name);
257
+ if (!pruneDescriptions && typeof description === "string") push(description);
258
+ try {
259
+ const wireTool: AiTool = {
260
+ name,
261
+ description,
262
+ parameters: parameters as AiTool["parameters"],
263
+ examples: tool.examples,
264
+ };
265
+ const fullSchema = toolWireSchema(wireTool) ?? {};
266
+ const wireSchema = pruneDescriptions ? stripSchemaDescriptions(fullSchema) : fullSchema;
267
+ const wireJson = JSON.stringify(wireSchema);
268
+ if (typeof wireJson === "string")
269
+ push(wireJson, display ? JSON.stringify(wireSchema, null, displayIndent) : wireJson);
270
+ // The agent loop appends rendered examples to the wire description,
271
+ // which pruning empties.
272
+ const examplesBlock = pruneDescriptions ? undefined : renderToolExamples(wireTool);
273
+ if (examplesBlock) push(examplesBlock);
274
+ } catch (error) {
275
+ // Schema may contain functions or cycles.
276
+ return { fragments, display, schemaError: error instanceof Error ? error.message : String(error) };
277
+ }
278
+ return { fragments, display };
279
+ }
280
+
281
+ /** Inputs that select which tool-schema estimate applies, beyond the roster and tokenizer. */
282
+ export interface ToolSchemaEstimateOptions {
283
+ /** Caller settings/source revision; a change invalidates the cached estimate. */
284
+ sourceRevision?: number;
285
+ /** Count the description-stripped specs sent when the catalog rides in the system prompt. */
286
+ pruneDescriptions?: boolean;
287
+ }
288
+
230
289
  /**
231
290
  * Estimate provider-visible tool-schema tokens.
232
291
  *
233
292
  * Results are cached by roster-array identity, tokenizer identity, the
234
- * caller-supplied settings/source revision, and the roster's explicit dynamic
235
- * metadata revision. Callers whose descriptions or schemas are live getters
236
- * must either advance `sourceRevision` or call
293
+ * caller-supplied settings/source revision, the prune mode, and the roster's
294
+ * explicit dynamic metadata revision. Callers whose descriptions or schemas are
295
+ * live getters must either advance `sourceRevision` or call
237
296
  * {@link invalidateToolSchemaMetadata} when those inputs change.
238
297
  */
239
- export function estimateToolSchemaTokens(tools: ToolSchemaSource, tokenizer: Tokenizer, sourceRevision = 0): number {
298
+ export function estimateToolSchemaTokens(
299
+ tools: ToolSchemaSource,
300
+ tokenizer: Tokenizer,
301
+ options: ToolSchemaEstimateOptions = {},
302
+ ): number {
303
+ const { sourceRevision = 0, pruneDescriptions = false } = options;
240
304
  const cache = toolSchemaTokenCache(tools);
241
305
  const cached = cache.byTokenizer.get(tokenizer);
242
- if (cached?.revision === cache.revision && cached.sourceRevision === sourceRevision) return cached.tokens;
306
+ if (
307
+ cached?.revision === cache.revision &&
308
+ cached.sourceRevision === sourceRevision &&
309
+ cached.pruneDescriptions === pruneDescriptions
310
+ )
311
+ return cached.tokens;
243
312
 
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
- }
313
+ const fragments = tools.flatMap(tool => toolSchemaFragments(tool, { pruneDescriptions }).fragments);
271
314
  const tokens = tokenizer.countTokens(fragments);
272
- cache.byTokenizer.set(tokenizer, { revision: cache.revision, sourceRevision, tokens });
315
+ cache.byTokenizer.set(tokenizer, { revision: cache.revision, sourceRevision, pruneDescriptions, tokens });
273
316
  return tokens;
274
317
  }
275
318
 
@@ -278,9 +321,9 @@ export function estimateContextToolSchemaTokens(
278
321
  tools: ToolSchemaSource,
279
322
  tokenizer: Tokenizer,
280
323
  model: Model | undefined,
281
- sourceRevision = 0,
324
+ options: ToolSchemaEstimateOptions = {},
282
325
  ): number {
283
- return model?.toolSchemasInContext === false ? 0 : estimateToolSchemaTokens(tools, tokenizer, sourceRevision);
326
+ return model?.toolSchemasInContext === false ? 0 : estimateToolSchemaTokens(tools, tokenizer, options);
284
327
  }
285
328
 
286
329
  /**
@@ -290,15 +333,17 @@ export function estimateContextToolSchemaTokens(
290
333
  *
291
334
  * Exposed so callers like `StatusLineComponent` can cache the non-message
292
335
  * total separately from the growing message total. A model switch can change
293
- * which tool schemas occupy context without changing the roster.
336
+ * which tool schemas occupy context without changing the roster; a prune-mode
337
+ * change (`Agent.prunesToolDescriptions`) changes how much of each spec ships.
294
338
  */
295
339
  // The per-turn threshold and compaction paths call these helpers repeatedly.
296
- // Cache by prompt, roster, skills, tokenizer, revision, and model schema policy;
297
- // setSystemPrompt/setTools replace their arrays rather than mutating them.
340
+ // Cache by prompt, roster, skills, tokenizer, revision, model schema policy, and
341
+ // prune mode; setSystemPrompt/setTools replace their arrays rather than mutating them.
298
342
  interface NonMessageTokenCache {
299
343
  systemPromptRef: readonly string[];
300
344
  toolsRef: ToolSchemaSource;
301
345
  toolSchemasInContext: boolean;
346
+ pruneToolDescriptions: boolean;
302
347
  toolsRevision: number;
303
348
  sourceRevision: number;
304
349
  skillful: boolean;
@@ -332,6 +377,7 @@ function nonMessageTokenCacheEntry(
332
377
  const systemPromptRef = session.systemPrompt ?? EMPTY_STRING_PARTS;
333
378
  const toolsRef = session.agent?.state?.tools ?? EMPTY_TOOLS;
334
379
  const toolSchemasInContext = session.model?.toolSchemasInContext !== false;
380
+ const pruneToolDescriptions = session.agent?.prunesToolDescriptions?.(session.model) === true;
335
381
  const toolsRevision = getToolSchemaMetadataRevision(toolsRef);
336
382
  const skillsRef = session.renderedSkills ?? session.skills ?? EMPTY_SKILLS;
337
383
  let entry = cachedSession[NON_MESSAGE_TOKEN_CACHE];
@@ -340,6 +386,7 @@ function nonMessageTokenCacheEntry(
340
386
  entry.systemPromptRef === systemPromptRef &&
341
387
  entry.toolsRef === toolsRef &&
342
388
  entry.toolSchemasInContext === toolSchemasInContext &&
389
+ entry.pruneToolDescriptions === pruneToolDescriptions &&
343
390
  entry.toolsRevision === toolsRevision &&
344
391
  entry.sourceRevision === sourceRevision &&
345
392
  entry.skillsRef === skillsRef &&
@@ -351,6 +398,7 @@ function nonMessageTokenCacheEntry(
351
398
  systemPromptRef,
352
399
  toolsRef,
353
400
  toolSchemasInContext,
401
+ pruneToolDescriptions,
354
402
  toolsRevision,
355
403
  sourceRevision,
356
404
  skillful: true,
@@ -374,7 +422,10 @@ export function computeNonMessageTokens(
374
422
  const tools = session.agent?.state?.tools ?? EMPTY_TOOLS;
375
423
  const tokens =
376
424
  tokenizer.countTokens(Array.from(systemPromptParts, part => part ?? "")) +
377
- estimateContextToolSchemaTokens(tools, tokenizer, session.model, sourceRevision);
425
+ estimateContextToolSchemaTokens(tools, tokenizer, session.model, {
426
+ sourceRevision,
427
+ pruneDescriptions: entry.pruneToolDescriptions,
428
+ });
378
429
  entry.tokens = tokens;
379
430
  return tokens;
380
431
  }
@@ -406,7 +457,10 @@ export function computeNonMessageBreakdown(
406
457
  renderedSkills(session.renderedSkills ?? session.skills ?? EMPTY_SKILLS, tools),
407
458
  tokenizer,
408
459
  );
409
- const toolsTokens = estimateContextToolSchemaTokens(tools, tokenizer, session.model, sourceRevision);
460
+ const toolsTokens = estimateContextToolSchemaTokens(tools, tokenizer, session.model, {
461
+ sourceRevision,
462
+ pruneDescriptions: entry.pruneToolDescriptions,
463
+ });
410
464
  const systemPromptParts = session.systemPrompt ?? EMPTY_STRING_PARTS;
411
465
  const systemContextTokens = tokenizer.countTokens(Array.from(systemPromptParts.slice(1), part => part ?? ""));
412
466
  const systemPromptTokens = Math.max(0, tokenizer.countTokens(systemPromptParts[0] ?? "") - skillsTokens);
@@ -454,23 +508,11 @@ export function computeContextBreakdown(session: ContextUsageSession, options: C
454
508
  }
455
509
 
456
510
  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
- },
511
+ { id: "systemPrompt", label: "System prompt", tokens: systemPromptTokens },
512
+ { id: "systemTools", label: "System tools", tokens: toolsTokens },
513
+ { id: "systemContext", label: "System context", tokens: systemContextTokens },
514
+ { id: "skills", label: "Skills", tokens: skillsTokens },
515
+ { id: "messages", label: "Messages", tokens: messagesTokens },
474
516
  ];
475
517
 
476
518
  let autoCompactBufferTokens = 0;
@@ -504,520 +546,3 @@ export function computeContextBreakdown(session: ContextUsageSession, options: C
504
546
  snapcompact: options.snapcompact,
505
547
  };
506
548
  }
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
- }