@songtonyli/dsh-cli 0.1.78 → 0.1.80

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/README.md CHANGED
@@ -26,7 +26,7 @@ workspace and no build step. Native packages that ship one build per platform
26
26
  ripgrep, the PTY backend's addons, sharp, koffi, and the Landlock launcher — are
27
27
  ordinary optional dependencies, so npm resolves the right one for your machine.
28
28
 
29
- Requires Node `^22.19.0 || >=24.0.0`. Version 0.1.78; `dsh --version`
29
+ Requires Node `^22.19.0 || >=24.0.0`. Version 0.1.80; `dsh --version`
30
30
  also reports the harness build the package was assembled from.
31
31
 
32
32
  ## License
package/bin/dsh.mjs CHANGED
@@ -18,7 +18,7 @@ const argv = process.argv.slice(2)
18
18
  // version this package publishes. Reporting only one of the two would make an
19
19
  // ordinary `npm install @songtonyli/dsh-cli@x` look like it installed something else.
20
20
  if (argv.length === 1 && (argv[0] === '--version' || argv[0] === '-V')) {
21
- console.log('@songtonyli/dsh-cli 0.1.78 (deepseek-harness 0.2.1-rc.2)')
21
+ console.log('@songtonyli/dsh-cli 0.1.80 (deepseek-harness 0.2.1-rc.2)')
22
22
  process.exit(0)
23
23
  }
24
24
 
@@ -537,7 +537,7 @@ var ClientModuleRegistry = class extends Service {
537
537
  constructor(ctx) {
538
538
  super(ctx, "clientModules");
539
539
  const { version } = createRequire(import.meta.url)("../package.json");
540
- const commit = "511caad";
540
+ const commit = "f517a47";
541
541
  this.release = {
542
542
  version,
543
543
  commit
@@ -167,7 +167,7 @@ window.__ModuleLoader__.load({
167
167
  const SCROLLBAR_LINGER_MS = 2e3;
168
168
  /** Format complete-build metadata for the local brand badge. */
169
169
  function localBuildVersion() {
170
- return `0.2.1-rc.2-511caad` + ({}.DSH_CLIENT_GIT_DIRTY === "true" ? "-dirty" : "");
170
+ return `0.2.1-rc.2-f517a47-dirty`;
171
171
  }
172
172
  /** Each panel row subscribes only to its own selection state. */
173
173
  function PanelRow({ id, label, wide, usePanelInfo, selectPanel, renderSlot }) {
@@ -264,59 +264,101 @@ function toPiAssistant(message, onDegrade) {
264
264
  * @module dsh-llm-pi-ai/catalog-supplement
265
265
  */
266
266
  /** One provider route's supplemental models, keyed by model id. */
267
- const SUPPLEMENT = { anthropic: { "claude-haiku-5-5": {
268
- id: "claude-haiku-5-5",
269
- name: "Claude Haiku 5.5",
270
- api: "anthropic-messages",
271
- provider: "anthropic",
272
- baseUrl: "https://api.anthropic.com",
273
- reasoning: true,
274
- input: ["text", "image"],
275
- cost: {
276
- input: .1,
277
- output: .5,
278
- cacheRead: .01,
279
- cacheWrite: .125,
280
- tiers: [{
281
- inputTokensAbove: 1e5,
282
- input: .5,
283
- output: 2.5,
284
- cacheRead: .05,
285
- cacheWrite: .625
286
- }]
287
- },
288
- contextWindow: 1e6,
289
- maxTokens: 128e3,
290
- compat: {
291
- supportsMidConvoEffort: true,
292
- supportsMidConvoSystemMessages: true,
293
- supportsMidConvoToolChanges: true,
294
- forceAdaptiveThinking: true,
295
- supportsStrictTools: true
296
- },
297
- thinkingLevelMap: {
298
- off: null,
299
- xhigh: "xhigh",
300
- max: "max"
301
- },
302
- promptCache: {
303
- short: 300,
304
- long: 3600
305
- },
306
- inputLimits: {
307
- maxRequestBytes: 33554432,
308
- images: {
309
- maxPerRequest: 600,
310
- resize: {
311
- maxWidth: 2e3,
312
- maxHeight: 2e3,
313
- maxBytes: 4718592,
314
- jpegQuality: 80
267
+ const SUPPLEMENT = {
268
+ anthropic: { "claude-haiku-5-5": {
269
+ id: "claude-haiku-5-5",
270
+ name: "Claude Haiku 5.5",
271
+ api: "anthropic-messages",
272
+ provider: "anthropic",
273
+ baseUrl: "https://api.anthropic.com",
274
+ reasoning: true,
275
+ input: ["text", "image"],
276
+ cost: {
277
+ input: .1,
278
+ output: .5,
279
+ cacheRead: .01,
280
+ cacheWrite: .125,
281
+ tiers: [{
282
+ inputTokensAbove: 1e5,
283
+ input: .5,
284
+ output: 2.5,
285
+ cacheRead: .05,
286
+ cacheWrite: .625
287
+ }]
288
+ },
289
+ contextWindow: 1e6,
290
+ maxTokens: 128e3,
291
+ compat: {
292
+ supportsMidConvoEffort: true,
293
+ supportsMidConvoSystemMessages: true,
294
+ supportsMidConvoToolChanges: true,
295
+ forceAdaptiveThinking: true,
296
+ supportsStrictTools: true
297
+ },
298
+ thinkingLevelMap: {
299
+ off: null,
300
+ xhigh: "xhigh",
301
+ max: "max"
302
+ },
303
+ promptCache: {
304
+ short: 300,
305
+ long: 3600
306
+ },
307
+ inputLimits: {
308
+ maxRequestBytes: 33554432,
309
+ images: {
310
+ maxPerRequest: 600,
311
+ resize: {
312
+ maxWidth: 2e3,
313
+ maxHeight: 2e3,
314
+ maxBytes: 4718592,
315
+ jpegQuality: 80
316
+ }
315
317
  }
316
- }
317
- },
318
- type: "chat"
319
- } } };
318
+ },
319
+ type: "chat"
320
+ } },
321
+ openrouter: { "deepseek/deepseek-v4.1-flash-1017": {
322
+ id: "deepseek/deepseek-v4.1-flash-1017",
323
+ name: "DeepSeek: DeepSeek V4.1 Flash (1017)",
324
+ api: "openai-completions",
325
+ provider: "openrouter",
326
+ baseUrl: "https://openrouter.ai/api/v1",
327
+ reasoning: true,
328
+ input: ["text", "image"],
329
+ cost: {
330
+ input: .05,
331
+ output: .6,
332
+ cacheRead: .006,
333
+ cacheWrite: 0
334
+ },
335
+ contextWindow: 1e6,
336
+ maxTokens: 943718,
337
+ compat: {
338
+ supportsDeveloperRole: false,
339
+ thinkingFormat: "openrouter",
340
+ supportsStrictMode: true,
341
+ sendSessionAffinityHeaders: true,
342
+ requiresReasoningContentOnAssistantMessages: true
343
+ },
344
+ thinkingLevelMap: {
345
+ off: "none",
346
+ minimal: null,
347
+ low: "low",
348
+ medium: null,
349
+ high: "high",
350
+ xhigh: null,
351
+ max: "max"
352
+ },
353
+ inputLimits: { images: { resize: {
354
+ maxWidth: 2e3,
355
+ maxHeight: 2e3,
356
+ maxBytes: 4718592,
357
+ jpegQuality: 80
358
+ } } },
359
+ type: "chat"
360
+ } }
361
+ };
320
362
  /**
321
363
  * Supplemental catalog models for one pi-ai provider route.
322
364
  * @param provider - provider route key.
@@ -24,8 +24,8 @@
24
24
  en: 365ce77bf78accd5
25
25
  zh: e945a1f209e18f36
26
26
  /deepseek-ai-dsh-tui-app/use-this-package/keys-and-commands:
27
- en: e3650a069cc84840
28
- zh: b8428946ec8beab1
27
+ en: 8397ec35de157ed5
28
+ zh: 135411de6c63f306
29
29
  /deepseek-ai-dsh-tui-app/use-this-package/background-tool-calls:
30
30
  en: 322ae3c6d76383ec
31
31
  zh: 8c38eee4b57ed8dd
@@ -48,14 +48,14 @@
48
48
  en: 843f7f46161ca8d3
49
49
  zh: ddff3216005e2b57
50
50
  /deepseek-ai-dsh-tui-app/understand-the-implementation/rendering-model:
51
- en: fb43018b679482fb
52
- zh: e60cc1d0cbaa40a0
51
+ en: 42cc6ac3475fba61
52
+ zh: 450342bc7b31cb61
53
53
  /deepseek-ai-dsh-tui-app/understand-the-implementation/patch-surface-over-base:
54
54
  en: 142f04bf29e981dd
55
55
  zh: a1689297b06c9ca6
56
56
  /deepseek-ai-dsh-tui-app/understand-the-implementation/source-map:
57
- en: db616267d54607c0
58
- zh: 37ac9d793fbce025
57
+ en: a1b526bb25bf3096
58
+ zh: 36d8f8acc73700fd
59
59
  /deepseek-ai-dsh-tui-app/understand-the-implementation/invariant-ownership:
60
60
  en: 0ddf6de8928026d5
61
61
  zh: 24feedcbb9e9d676
@@ -190,6 +190,7 @@ Typing `/` at the start of the editor completes the terminal's own commands and
190
190
  | `/login` | Sign in with a provider subscription (hides key-collecting logins); `/login <key>` skips the picker |
191
191
  | `/export [dir]` | Write this session's log ZIP (sub-sessions and attachments included) into `dir`, default the workspace |
192
192
  | `/status` | Context window usage and breakdown, token totals with cache hit, session stats, todos, goal, plan mode, and permission |
193
+ | `/context` | How the context window is used right now: a grid of 200 cells beside the model, the occupancy, and the estimated tokens of the system prompt, tool definitions, instruction files, skills, other injected context, and messages, then the free space. The cells holding the tokens the newest turn added are the hot region, drawn bold and counted on the `▲ hot` row. Where the terminal runs motion, the grid fills on open and a bright band sweeps through the hot region; while a turn runs the report re-reads the usage every quarter second, marks itself `live`, and blinks the first free cell. It settles once no turn runs and its open animation ended, when another `/context` opens, on a session switch, or once it leaves the repaint window. Reduced motion draws only the settled report |
193
194
  | `/todos` | Browse the agent's todo list; completed rows are scratched out; `Enter` opens one item in full with its status, position, and turns |
194
195
  | `/outline` | The turns of this session with their prompt and reply previews |
195
196
  | `/deliverables` | The files the agent presented, grouped by turn |
@@ -269,7 +270,7 @@ The runner awaits the complete application (`ctx.get('loader')?.await()`) and bu
269
270
 
270
271
  ### Rendering model
271
272
 
272
- Durable facts come from the session log: `system/message` (a nonempty prompt draws in full; an empty rendering is omitted), `user/message` (own submissions are drawn once and their echo skipped by message id; injected context — instructions, catalogs, snapshots, notices, relays, recalls, and undeclared forms — draws in full as a dim `⬡` row, a snapshot as one named contribution per part; compaction checkpoints and tool or model sources are omitted), `compaction/start`, `compaction/summary`, the checkpoint replacement, and `compaction/end` (a mirror of the surface kept from each event's `surfaceOp` names the replaced and remaining nodes, and the closing marker draws the compaction block or a failed `/compact` notice; a turn-owned `compaction/start` relabels the running spinner), `assistant/message` (which replaces the streamed block with the committed text and folds usage into the footer), `tool/call` and `tool/result` (drawn through the tool's `presentCall` and `presentResult` views when it declares them, with a raw-argument and raw-result fallback), `turn/end` notices, `workspace/changes` (one notice with the turn's file and line counts while the Host still holds the summary), `session/title` (header), `permission/preset` (footer), and `todo/write` under the enclosing `turn/start` (the turns one todo item's page reports; the list carries no per-item identity, so a reworded item counts as a new one; the same write refreshes the activity board from the `todos` projection). A descendant `tool/call`, `tool/result`, or `turn/end`, and a `subagent/start` or `subagent/end` for the bound parent, replace that board's one-line summary — tool title or first result row, never child assistant prose; `turn/end` on the bound session and bind clear the board. Live incrementality comes from `agent/assistant-stream` text, reasoning, tool-call, and usage deltas: a card is mounted when the model names the tool, and the working spinner follows that stream plus durable `tool/call` / `tool/result` so it says `thinking`, `writing`, or `calling <tool>` with live `↑` send and `↓` receive for that call. Session facts outside the log come from the same services the browser reads: `sessionTitle`, `permissionPresets`, `sessionQuery` for the picker identities, the live or cached `title` projection for picker titles, `/deliverables`, and subagent details, `sessionProjections` for the footer, `/status`, `/todos`, and `/outline`, `fileReferences` and `sessionReferenceResolver` for `@` completion, `attachments`, `skills`, `authorization`, `settings`, `subagents`, and the Loader's entries for `/plugins`. Modal prompts are process-local presentation and are never logged.
273
+ Durable facts come from the session log: `system/message` (a nonempty prompt draws in full; an empty rendering is omitted), `user/message` (own submissions are drawn once and their echo skipped by message id; injected context — instructions, catalogs, snapshots, notices, relays, recalls, and undeclared forms — draws in full as a dim `⬡` row, a snapshot as one named contribution per part; compaction checkpoints and tool or model sources are omitted), `compaction/start`, `compaction/summary`, the checkpoint replacement, and `compaction/end` (a mirror of the surface kept from each event's `surfaceOp` names the replaced and remaining nodes, and the closing marker draws the compaction block or a failed `/compact` notice; a turn-owned `compaction/start` relabels the running spinner), `assistant/message` (which replaces the streamed block with the committed text and folds usage into the footer), `tool/call` and `tool/result` (drawn through the tool's `presentCall` and `presentResult` views when it declares them, with a raw-argument and raw-result fallback), `turn/end` notices, `workspace/changes` (one notice with the turn's file and line counts while the Host still holds the summary), `session/title` (header), `permission/preset` (footer), and `todo/write` under the enclosing `turn/start` (the turns one todo item's page reports; the list carries no per-item identity, so a reworded item counts as a new one; the same write refreshes the activity board from the `todos` projection). A descendant `tool/call`, `tool/result`, or `turn/end`, and a `subagent/start` or `subagent/end` for the bound parent, replace that board's one-line summary — tool title or first result row, never child assistant prose; `turn/end` on the bound session and bind clear the board. Live incrementality comes from `agent/assistant-stream` text, reasoning, tool-call, and usage deltas: a card is mounted when the model names the tool, and the working spinner follows that stream plus durable `tool/call` / `tool/result` so it says `thinking`, `writing`, or `calling <tool>` with live `↑` send and `↓` receive for that call. Session facts outside the log come from the same services the browser reads: `sessionTitle`, `permissionPresets`, `sessionQuery` for the picker identities, the live or cached `title` projection for picker titles, `/deliverables`, and subagent details, `sessionProjections` for the footer, `/status`, `/context`, `/todos`, and `/outline`, `tokenMeter` for `/context`, `fileReferences` and `sessionReferenceResolver` for `@` completion, `attachments`, `skills`, `authorization`, `settings`, `subagents`, and the Loader's entries for `/plugins`. Modal prompts are process-local presentation and are never logged.
273
274
 
274
275
  ### Patch surface over base
275
276
 
@@ -293,7 +294,8 @@ The patch rides over `dsh-base`: it sets the coding persona prefix and cwd suffi
293
294
  | [`src/export.ts`](src/export.ts) | `/export`: the session-log ZIP written through the export package's archive helpers |
294
295
  | [`src/blocks.ts`](src/blocks.ts) | Transcript components: user prompt, user-shell run, assistant reply, tool card, system prompt and injected context, notice; the navigable blocks expose their sections and draw the focus gutter, and the foldable ones carry the marker both fold keys name. Each block keeps the lines it last drew and a reply keeps the coloured fences of its last Markdown parse and re-lexes only the open tail after the last closed fence, so a frame of a settled transcript costs one key comparison per block and a stream delta colours only the fence that changed |
295
296
  | [`src/context.ts`](src/context.ts) | Project logged system prompts and injected user messages into transcript sections |
296
- | [`src/compaction.ts`](src/compaction.ts) | The compaction account: the surface mirror that names what each compaction replaced and what stays verbatim, and the title and sections of its block |
297
+ | [`src/context-usage.ts`](src/context-usage.ts) | The `/context` report: measured surface nodes attributed to categories and the hot region, the cell grid and legend, and the animated block |
298
+ | [`src/compaction.ts`](src/compaction.ts) | The compaction account: the surface mirror that names what each compaction replaced and what stays verbatim, which `/context` also reads, and the title and sections of its block |
297
299
  | [`src/navigation.ts`](src/navigation.ts) | The transcript as sections, the cursor that walks them along four axes, the turns those sections group into, and the inspector heading |
298
300
  | [`src/inspector.ts`](src/inspector.ts) | The docked inspector: the framed pane with its mode chip, the section heading, the numbered wrapping parts strip, the folded rows, and its mounted component |
299
301
  | [`src/frame.ts`](src/frame.ts) | Pure box drawing: the rounded rules, the inverse mode chip, body rows, and the legend step a width holds |
@@ -358,6 +360,8 @@ The patch rides over `dsh-base`: it sets the coding persona prefix and cwd suffi
358
360
  | [`tests/panels.spec.ts`](tests/panels.spec.ts) | Status footer and report, the navigable subagent and todo lists, catalog commands, command hints, and the approval detail |
359
361
  | [`tests/transcript-focus.spec.ts`](tests/transcript-focus.spec.ts) | Walking the conversation, the region stack, the inspector, the reader over a live session with the terminal it takes and gives back, and the in-place gutter inside the repaint window |
360
362
  | [`tests/context.spec.ts`](tests/context.spec.ts) | Projection of system prompts and injected context into transcript sections |
363
+ | [`tests/context-usage.spec.ts`](tests/context-usage.spec.ts) | `/context` attribution, cell grid, legend, and block animation |
364
+ | [`tests/context-usage-app.spec.ts`](tests/context-usage-app.spec.ts) | `/context` in the terminal: the report over the token meter, live re-reads on the fade tick, settling, and the missing meter |
361
365
  | [`tests/compaction.spec.ts`](tests/compaction.spec.ts) | The compaction account over real session appends: replaced and remaining nodes, repeated compactions, failures, and the formatted rows |
362
366
  | [`tests/compaction-app.spec.ts`](tests/compaction-app.spec.ts) | `/compact` in the terminal: the spinner, `Esc`, queued prompts, the refused switch, the block in place of the result, and the block from a replayed log |
363
367
  | [`tests/sessions.spec.ts`](tests/sessions.spec.ts) | Session picker listing: newest first, live or cached titles, hidden subagents |
@@ -190,6 +190,7 @@ follow-ups 面板持有键盘时:
190
190
  | `/login` | 用提供方订阅登录(隐藏仅收集密钥的登录);`/login <key>` 跳过选择器 |
191
191
  | `/export [dir]` | 把本会话的日志 ZIP(含子会话与附件)写入 `dir`,默认 workspace |
192
192
  | `/status` | 上下文窗口用量与构成、含缓存命中的 token 总计、会话统计、todo、目标、计划模式与权限 |
193
+ | `/context` | 上下文窗口此刻的用法:200 个单元格的网格,旁边是模型、占用,以及系统提示词、工具定义、指令文件、技能、其他注入上下文与消息的估算 token,最后是剩余空间。保存最新一轮新增 token 的单元格是热区,以粗体绘制,并在 `▲ hot` 行计数。终端运行动效时,网格在打开时逐格填充,一道亮带扫过热区;轮次进行期间,报告每四分之一秒重新读取用量、标记为 `live`,并让第一个空闲单元格闪烁。当没有轮次进行且打开动画结束、另一个 `/context` 打开、会话切换,或它离开重绘窗口时,报告定格。减弱动效时只绘制定格后的报告 |
193
194
  | `/todos` | 浏览 agent 的 todo 列表;已完成行会被划掉;`Enter` 完整打开其中一条,含其状态、位置与轮次 |
194
195
  | `/outline` | 本会话各轮次及其提示与回复预览 |
195
196
  | `/deliverables` | agent 交付的文件,按轮次分组 |
@@ -269,7 +270,7 @@ runner 等待完整应用就绪(`ctx.get('loader')?.await()`),并在核心
269
270
 
270
271
  ### 渲染模型
271
272
 
272
- 持久事实来自会话日志:`system/message`(非空提示词完整画出;空的绘制则省略)、`user/message`(自己提交的消息只绘制一次,其回显按消息 id 跳过;注入的上下文——instructions、catalogs、snapshots、notices、relays、recalls 以及未声明的形式——以暗色 `⬡` 行完整画出,快照按具名贡献各成一部分;压缩检查点以及工具或模型来源则省略)、`compaction/start`、`compaction/summary`、检查点替换与 `compaction/end`(依据每个事件的 `surfaceOp` 维护的 surface 镜像写明被替换与仍保留的节点,结束标记绘出压缩块或失败的 `/compact` 通知;归属于轮次的 `compaction/start` 会改写运行中的旋转指示标签)、`assistant/message`(用已提交文本替换流式块,并把用量折入页脚)、`tool/call` 与 `tool/result`(工具声明 `presentCall` 与 `presentResult` 视图时据此绘制,否则回退到原始参数与原始结果)、`turn/end` 通知、`workspace/changes`(在 Host 仍保存摘要时,以一行通知给出该轮的文件数与行数)、`session/title`(页眉)、`permission/preset`(页脚),以及所属 `turn/start` 之下的 `todo/write`(某条 todo 的详情页所报告的轮次;该列表不带逐条标识,因此改写措辞的条目算作新条目;同一次写入还从 `todos` 投影刷新 activity board)。后代会话的 `tool/call`、`tool/result` 或 `turn/end`,以及绑定父会话的 `subagent/start` / `subagent/end`,会替换该板上的一行摘要——工具标题或结果首行,从不使用子会话的 assistant 正文;绑定会话的 `turn/end` 与 bind 会清空该板。实时增量来自 `agent/assistant-stream` 的文本、推理、工具调用与用量增量:模型一报出工具名就挂上卡片,工作时的旋转指示跟随该流以及持久的 `tool/call` / `tool/result`,从而标出 `thinking`、`writing` 或 `calling <tool>`,并带着该次调用的实时 `↑` 发送与 `↓` 接收。日志之外的会话事实来自浏览器读取的同一批服务:`sessionTitle`、`permissionPresets`、供选择器身份、`/deliverables` 与子 agent 详情使用的 `sessionQuery`、供选择器标题使用的实时或缓存 `title` 投影、供页脚、`/status`、`/todos` 与 `/outline` 使用的 `sessionProjections`、供 `@` 补全使用的 `fileReferences` 与 `sessionReferenceResolver`、`attachments`、`skills`、`authorization`、`settings`、`subagents`,以及供 `/plugins` 使用的 Loader 条目。模态提示是进程本地的呈现,从不写入日志。
273
+ 持久事实来自会话日志:`system/message`(非空提示词完整画出;空的绘制则省略)、`user/message`(自己提交的消息只绘制一次,其回显按消息 id 跳过;注入的上下文——instructions、catalogs、snapshots、notices、relays、recalls 以及未声明的形式——以暗色 `⬡` 行完整画出,快照按具名贡献各成一部分;压缩检查点以及工具或模型来源则省略)、`compaction/start`、`compaction/summary`、检查点替换与 `compaction/end`(依据每个事件的 `surfaceOp` 维护的 surface 镜像写明被替换与仍保留的节点,结束标记绘出压缩块或失败的 `/compact` 通知;归属于轮次的 `compaction/start` 会改写运行中的旋转指示标签)、`assistant/message`(用已提交文本替换流式块,并把用量折入页脚)、`tool/call` 与 `tool/result`(工具声明 `presentCall` 与 `presentResult` 视图时据此绘制,否则回退到原始参数与原始结果)、`turn/end` 通知、`workspace/changes`(在 Host 仍保存摘要时,以一行通知给出该轮的文件数与行数)、`session/title`(页眉)、`permission/preset`(页脚),以及所属 `turn/start` 之下的 `todo/write`(某条 todo 的详情页所报告的轮次;该列表不带逐条标识,因此改写措辞的条目算作新条目;同一次写入还从 `todos` 投影刷新 activity board)。后代会话的 `tool/call`、`tool/result` 或 `turn/end`,以及绑定父会话的 `subagent/start` / `subagent/end`,会替换该板上的一行摘要——工具标题或结果首行,从不使用子会话的 assistant 正文;绑定会话的 `turn/end` 与 bind 会清空该板。实时增量来自 `agent/assistant-stream` 的文本、推理、工具调用与用量增量:模型一报出工具名就挂上卡片,工作时的旋转指示跟随该流以及持久的 `tool/call` / `tool/result`,从而标出 `thinking`、`writing` 或 `calling <tool>`,并带着该次调用的实时 `↑` 发送与 `↓` 接收。日志之外的会话事实来自浏览器读取的同一批服务:`sessionTitle`、`permissionPresets`、供选择器身份、`/deliverables` 与子 agent 详情使用的 `sessionQuery`、供选择器标题使用的实时或缓存 `title` 投影、供页脚、`/status`、`/context`、`/todos` 与 `/outline` 使用的 `sessionProjections`、供 `/context` 使用的 `tokenMeter`、供 `@` 补全使用的 `fileReferences` 与 `sessionReferenceResolver`、`attachments`、`skills`、`authorization`、`settings`、`subagents`,以及供 `/plugins` 使用的 Loader 条目。模态提示是进程本地的呈现,从不写入日志。
273
274
 
274
275
  ### 基于 base 的 patch 面
275
276
 
@@ -293,7 +294,8 @@ runner 等待完整应用就绪(`ctx.get('loader')?.await()`),并在核心
293
294
  | [`src/export.ts`](src/export.ts) | `/export`:通过导出包的归档辅助函数写出会话日志 ZIP |
294
295
  | [`src/blocks.ts`](src/blocks.ts) | 对话记录组件:用户提示、用户 shell 运行、assistant 回复、工具卡片、系统提示词与注入上下文、通知;可导航的块暴露其各小节并绘制焦点标记条,可折叠的块则承载两个折叠键共用的那条标记。每个块保留上次画出的行,回复还保留上次 Markdown 解析所着色的代码围栏,并只对最后一个已关闭围栏之后仍打开的尾部重新词法分析,因此已稳定的对话记录每帧只花每块一次键比较,一次流式增量也只为发生变化的那个围栏着色 |
295
296
  | [`src/context.ts`](src/context.ts) | 把已记录的系统提示词与注入的用户消息投影为对话记录小节 |
296
- | [`src/compaction.ts`](src/compaction.ts) | 压缩说明:写明每次压缩替换了什么、什么仍逐字保留的 surface 镜像,以及其块的标题与小节 |
297
+ | [`src/context-usage.ts`](src/context-usage.ts) | `/context` 报告:把测量的 surface 节点归入各类别与热区、单元格网格与图例,以及带动画的块 |
298
+ | [`src/compaction.ts`](src/compaction.ts) | 压缩说明:写明每次压缩替换了什么、什么仍逐字保留的 surface 镜像(`/context` 也读取它),以及其块的标题与小节 |
297
299
  | [`src/navigation.ts`](src/navigation.ts) | 把对话记录看作各个小节、沿四条轴走遍它们的光标、这些小节归入的各轮次,以及检视面板的标题 |
298
300
  | [`src/inspector.ts`](src/inspector.ts) | 停靠的检视面板:带模式徽标的边框面板、小节标题、带编号且会折行的各部分选择行、折叠后的各行,及其挂载的组件 |
299
301
  | [`src/frame.ts`](src/frame.ts) | 纯粹的画框:圆角边框线、反白的模式徽标、正文行,以及某个宽度容纳得下的按键提示级别 |
@@ -358,6 +360,8 @@ runner 等待完整应用就绪(`ctx.get('loader')?.await()`),并在核心
358
360
  | [`tests/panels.spec.ts`](tests/panels.spec.ts) | 状态页脚与报告、可导航的子 agent 与 todo 列表、目录命令、命令提示与审批详情 |
359
361
  | [`tests/transcript-focus.spec.ts`](tests/transcript-focus.spec.ts) | 走遍对话记录、区域序列、检视面板、实时会话上的阅读器连同它接管与交还的终端,以及重绘窗口内的原地标记条 |
360
362
  | [`tests/context.spec.ts`](tests/context.spec.ts) | 把系统提示词与注入上下文投影为对话记录小节 |
363
+ | [`tests/context-usage.spec.ts`](tests/context-usage.spec.ts) | `/context` 的归类、单元格网格、图例与块动画 |
364
+ | [`tests/context-usage-app.spec.ts`](tests/context-usage-app.spec.ts) | 终端中的 `/context`:基于 token 计量器的报告、在淡入节拍上的实时重读、定格,以及缺少计量器的情形 |
361
365
  | [`tests/compaction.spec.ts`](tests/compaction.spec.ts) | 基于真实会话追加的压缩说明:被替换与保留的节点、多次压缩、失败,以及格式化后的各行 |
362
366
  | [`tests/compaction-app.spec.ts`](tests/compaction-app.spec.ts) | 终端中的 `/compact`:旋转指示、`Esc`、排队的提示、被拒绝的切换、取代结果的压缩块,以及从重放日志绘出的压缩块 |
363
367
  | [`tests/sessions.spec.ts`](tests/sessions.spec.ts) | 会话选择器列表:最新在前、实时或缓存标题、隐藏子 agent |
@@ -6137,6 +6137,458 @@ function sameIds(left, right) {
6137
6137
  return true;
6138
6138
  }
6139
6139
  //#endregion
6140
+ //#region lib/types/context-usage.js
6141
+ /**
6142
+ * The `/context` report: how the bound session's context window splits
6143
+ * across the system prompt, tool definitions, instruction files, skills,
6144
+ * other injected context, and the conversation, drawn as a grid of cells
6145
+ * beside a legend.
6146
+ *
6147
+ * {@link contextUsage} joins the token meter's per-node prices with the
6148
+ * transcript's surface mirror (`./compaction.ts`), so no historical event is
6149
+ * read again. The cells holding tokens the newest turn added are the hot
6150
+ * region. {@link ContextUsageBlock} fills the grid on open, sweeps a shimmer
6151
+ * through the hot region, blinks the first free cell, and re-reads the usage
6152
+ * while a turn runs; it then settles on the drawing
6153
+ * {@link contextUsageLines} returns at rest, which is also all a terminal
6154
+ * without motion draws. Every frame of one block at one width has the same
6155
+ * line count.
6156
+ * @module @deepseek-ai/dsh-tui-app/context-usage
6157
+ */
6158
+ /** Every category, in the order the grid fills and the legend lists them. */
6159
+ const CONTEXT_CATEGORIES = [
6160
+ "system",
6161
+ "tools",
6162
+ "instructions",
6163
+ "skills",
6164
+ "context",
6165
+ "messages"
6166
+ ];
6167
+ /** The legend label of each category. */
6168
+ const CATEGORY_LABEL = {
6169
+ system: "System prompt",
6170
+ tools: "System tools",
6171
+ instructions: "Instructions",
6172
+ skills: "Skills",
6173
+ context: "Injected context",
6174
+ messages: "Messages"
6175
+ };
6176
+ /**
6177
+ * Attribute every priced node to a category and to the hot region.
6178
+ * @param input - the measurement, the surface mirror, and the occupancy facts.
6179
+ * @returns the usage; a node the mirror does not name counts as `messages`.
6180
+ */
6181
+ function contextUsage(input) {
6182
+ const named = new Map(input.surface.map((node) => [node.seq, node]));
6183
+ const tokens = /* @__PURE__ */ new Map();
6184
+ const hot = /* @__PURE__ */ new Map();
6185
+ tokens.set("tools", input.toolsTokens);
6186
+ for (const { seq, tokens: price } of input.priced) {
6187
+ const node = named.get(seq);
6188
+ const id = categoryOf(node);
6189
+ tokens.set(id, (tokens.get(id) ?? 0) + price);
6190
+ const fact = node?.fact;
6191
+ if (input.turn > 0 && fact !== void 0 && fact.kind !== "system" && fact.turn === input.turn) hot.set(id, (hot.get(id) ?? 0) + price);
6192
+ }
6193
+ const categories = CONTEXT_CATEGORIES.map((id) => ({
6194
+ id,
6195
+ tokens: tokens.get(id) ?? 0,
6196
+ hotTokens: hot.get(id) ?? 0
6197
+ }));
6198
+ const total = categories.reduce((sum, category) => sum + category.tokens, 0);
6199
+ return {
6200
+ model: input.model,
6201
+ used: input.used ?? total,
6202
+ ...input.window === void 0 ? {} : { window: input.window },
6203
+ turn: input.turn,
6204
+ categories
6205
+ };
6206
+ }
6207
+ /**
6208
+ * The category one mirrored node belongs to.
6209
+ * @param node - the node, or undefined when the mirror does not hold it.
6210
+ * @returns the category.
6211
+ */
6212
+ function categoryOf(node) {
6213
+ if (node === void 0) return "messages";
6214
+ const { fact } = node;
6215
+ switch (fact.kind) {
6216
+ case "system": return "system";
6217
+ case "context": return node.group ?? "context";
6218
+ case "prompt":
6219
+ case "summary":
6220
+ case "reply":
6221
+ case "result":
6222
+ case "developer": return "messages";
6223
+ /* v8 ignore next 2 -- closed-union exhaustiveness guard */
6224
+ default: return assertNever(fact, "surface fact");
6225
+ }
6226
+ }
6227
+ /** Cells per grid row when the width allows; narrower widths draw half as many. */
6228
+ const WIDE_GRID_COLUMNS = 20;
6229
+ /** Columns between the grid and the legend. */
6230
+ const LEGEND_GAP = 3;
6231
+ /**
6232
+ * Columns kept for the legend beside the grid. The layout depends on this
6233
+ * reserve rather than on the legend's own width, so a live re-read whose
6234
+ * numbers grow never moves the legend under the grid.
6235
+ */
6236
+ const LEGEND_COLUMNS = 36;
6237
+ /** A used cell. */
6238
+ const FULL_GLYPH = "⛁";
6239
+ /** A free cell. */
6240
+ const FREE_GLYPH = "⛶";
6241
+ /** The hot-region marker in the legend. */
6242
+ const HOT_GLYPH = "▲";
6243
+ /**
6244
+ * Lay the usage out on {@link GRID_CELLS} cells: the used share of the
6245
+ * window split across the categories by their estimates, each category's hot
6246
+ * cells at its own end, then free space. A nonzero category always gets a
6247
+ * cell. Without a known window the categories share every cell.
6248
+ * @param usage - one read of the usage.
6249
+ * @returns the cells in fill order.
6250
+ */
6251
+ function gridCells(usage) {
6252
+ const used = usage.categories.filter((category) => category.tokens > 0);
6253
+ const share = usage.window === void 0 ? 200 : Math.round(Math.min(1, usage.used / usage.window) * 200);
6254
+ const cells = [];
6255
+ const target = used.length === 0 ? 0 : Math.min(200, Math.max(share, used.length));
6256
+ for (const { category, count } of allocate(used, target)) {
6257
+ const hot = category.hotTokens === 0 ? 0 : Math.min(count, Math.max(1, Math.round(count * category.hotTokens / category.tokens)));
6258
+ for (let cell = 0; cell < count; cell++) cells.push({
6259
+ category: category.id,
6260
+ hot: cell >= count - hot
6261
+ });
6262
+ }
6263
+ while (cells.length < 200) cells.push(void 0);
6264
+ return cells;
6265
+ }
6266
+ /**
6267
+ * Split `target` cells across categories by tokens with the largest-remainder
6268
+ * rule, giving each category at least one cell.
6269
+ * @param categories - the categories with tokens, in fill order.
6270
+ * @param target - the cells to hand out; at least one per category, and 0 for none.
6271
+ * @returns one count per category, in the same order, summing to `target`.
6272
+ */
6273
+ function allocate(categories, target) {
6274
+ const sum = categories.reduce((total, category) => total + category.tokens, 0);
6275
+ const shares = categories.map((category, index) => {
6276
+ const exact = category.tokens / sum * target;
6277
+ return {
6278
+ category,
6279
+ index,
6280
+ count: Math.max(1, Math.floor(exact)),
6281
+ remainder: exact - Math.floor(exact)
6282
+ };
6283
+ });
6284
+ let left = target - shares.reduce((total, entry) => total + entry.count, 0);
6285
+ const byRemainder = [...shares].sort((a, b) => b.remainder - a.remainder || a.index - b.index);
6286
+ while (left > 0) {
6287
+ for (const entry of byRemainder.slice(0, left)) entry.count++;
6288
+ left = target - shares.reduce((total, entry) => total + entry.count, 0);
6289
+ }
6290
+ while (left < 0) {
6291
+ const largest = shares.reduce((most, entry) => entry.count > most.count ? entry : most);
6292
+ largest.count--;
6293
+ left++;
6294
+ }
6295
+ return shares;
6296
+ }
6297
+ /** The resting drawing: every cell filled, no shimmer, no lit frontier. */
6298
+ const AT_REST = {
6299
+ fill: 1,
6300
+ frontier: false,
6301
+ live: false
6302
+ };
6303
+ /** Hot cells the shimmer's head travels past the region's end before it starts over. */
6304
+ const WAVE_TRAIL = 6;
6305
+ /**
6306
+ * Draw the report.
6307
+ * @param usage - one read of the usage.
6308
+ * @param palette - the terminal palette.
6309
+ * @param width - the columns the block lays out in.
6310
+ * @param frame - the animation frame; defaults to {@link AT_REST}.
6311
+ * @returns the lines, each at most `width` columns, as many for every frame
6312
+ * and usage at one width.
6313
+ */
6314
+ function contextUsageLines(usage, palette, width, frame = AT_REST) {
6315
+ const columns = width >= gridWidth(WIDE_GRID_COLUMNS) ? WIDE_GRID_COLUMNS : WIDE_GRID_COLUMNS / 2;
6316
+ const grid = gridRows(gridCells(usage), columns, palette, frame);
6317
+ const legend = legendRows(usage, palette, frame);
6318
+ const left = gridWidth(columns);
6319
+ const body = width >= left + LEGEND_GAP + LEGEND_COLUMNS ? legend.map((entry, row) => {
6320
+ const cells = grid[row] ?? " ".repeat(left);
6321
+ return entry === "" ? cells : `${cells}${" ".repeat(LEGEND_GAP)}${entry}`;
6322
+ }) : [
6323
+ ...grid,
6324
+ "",
6325
+ ...legend
6326
+ ];
6327
+ return [
6328
+ "",
6329
+ palette.bold("Context usage"),
6330
+ ...body,
6331
+ ""
6332
+ ].map((line) => truncateToWidth(line, width, "…"));
6333
+ }
6334
+ /**
6335
+ * Columns one grid row takes.
6336
+ * @param columns - cells per row.
6337
+ * @returns the width, one space between each two cells.
6338
+ */
6339
+ function gridWidth(columns) {
6340
+ return columns * 2 - 1;
6341
+ }
6342
+ /**
6343
+ * The grid rows of one frame.
6344
+ * @param cells - the laid-out cells.
6345
+ * @param columns - cells per row.
6346
+ * @param palette - the terminal palette.
6347
+ * @param frame - the animation frame.
6348
+ * @returns the rows.
6349
+ */
6350
+ function gridRows(cells, columns, palette, frame) {
6351
+ const usedCount = cells.filter((cell) => cell !== void 0).length;
6352
+ const hotCount = cells.filter((cell) => cell?.hot === true).length;
6353
+ const filled = Math.ceil(Math.min(1, Math.max(0, frame.fill)) * usedCount);
6354
+ const head = frame.wave === void 0 || hotCount === 0 ? void 0 : frame.wave % (hotCount + WAVE_TRAIL);
6355
+ const drawn = [];
6356
+ let used = 0;
6357
+ let hot = 0;
6358
+ for (const [index, cell] of cells.entries()) {
6359
+ if (cell === void 0 || used >= filled) {
6360
+ const lit = frame.frontier && index === usedCount && filled === usedCount;
6361
+ drawn.push(lit ? palette.bold(palette.accent(FREE_GLYPH)) : palette.dim(FREE_GLYPH));
6362
+ if (cell !== void 0) used++;
6363
+ continue;
6364
+ }
6365
+ used++;
6366
+ const color = categoryStyle(palette, cell.category);
6367
+ if (!cell.hot) {
6368
+ drawn.push(color(FULL_GLYPH));
6369
+ continue;
6370
+ }
6371
+ drawn.push(hotCell(palette, color, head === void 0 ? void 0 : head - hot));
6372
+ hot++;
6373
+ }
6374
+ const rows = [];
6375
+ for (let start = 0; start < drawn.length; start += columns) rows.push(drawn.slice(start, start + columns).join(" "));
6376
+ return rows;
6377
+ }
6378
+ /**
6379
+ * One hot cell: bold at rest; under the shimmer, inverse at the head, bold
6380
+ * in the two cells behind it, and plain elsewhere, so a bright band sweeps
6381
+ * through the region.
6382
+ * @param palette - the terminal palette.
6383
+ * @param color - the cell's category color.
6384
+ * @param behind - how many cells the shimmer's head is past this cell; undefined at rest.
6385
+ * @returns the drawn cell.
6386
+ */
6387
+ function hotCell(palette, color, behind) {
6388
+ if (behind === void 0) return palette.bold(color(FULL_GLYPH));
6389
+ if (behind === 0) return palette.inverse(palette.bold(color(FULL_GLYPH)));
6390
+ if (behind === 1 || behind === 2) return palette.bold(color(FULL_GLYPH));
6391
+ return color(FULL_GLYPH);
6392
+ }
6393
+ /**
6394
+ * The legend rows: the model, the occupancy, the hot region, then one row per
6395
+ * category and the free space. The row count never depends on the usage.
6396
+ * @param usage - one read of the usage.
6397
+ * @param palette - the terminal palette.
6398
+ * @param frame - the animation frame, which marks a live read.
6399
+ * @returns the rows.
6400
+ */
6401
+ function legendRows(usage, palette, frame) {
6402
+ const { window, used } = usage;
6403
+ const occupancy = window === void 0 ? `${formatTokens(used)} tokens · window not reported yet` : `${formatTokens(used)}/${formatTokens(window)} tokens (${percent(used / window, true)})`;
6404
+ const share = (tokens) => {
6405
+ const base = window ?? usage.categories.reduce((sum, category) => sum + category.tokens, 0);
6406
+ return base > 0 ? ` (${percent(tokens / base, false)})` : "";
6407
+ };
6408
+ const rows = [
6409
+ palette.bold(usage.model),
6410
+ occupancy,
6411
+ hotRow(usage, palette, frame),
6412
+ "",
6413
+ palette.dim(palette.italic("Estimated usage by category")),
6414
+ ...usage.categories.map((category) => `${categoryStyle(palette, category.id)(FULL_GLYPH)} ${CATEGORY_LABEL[category.id]}: ${formatTokens(category.tokens)} tokens${share(category.tokens)}`)
6415
+ ];
6416
+ rows.push(window === void 0 ? `${palette.dim(FREE_GLYPH)} Free space: unknown` : `${palette.dim(FREE_GLYPH)} Free space: ${formatTokens(Math.max(0, window - used))}${share(Math.max(0, window - used))}`);
6417
+ return rows;
6418
+ }
6419
+ /**
6420
+ * The hot-region row.
6421
+ * @param usage - one read of the usage.
6422
+ * @param palette - the terminal palette.
6423
+ * @param frame - the animation frame.
6424
+ * @returns e.g. `▲ hot: +2.1k tokens in turn 3 · live`.
6425
+ */
6426
+ function hotRow(usage, palette, frame) {
6427
+ const live = frame.live ? palette.dim(" · live") : "";
6428
+ if (usage.turn === 0) return palette.dim(`${HOT_GLYPH} hot: no turn yet`) + live;
6429
+ const tokens = usage.categories.reduce((sum, category) => sum + category.hotTokens, 0);
6430
+ if (tokens === 0) return palette.dim(`${HOT_GLYPH} hot: nothing added in turn ${String(usage.turn)}`) + live;
6431
+ return `${palette.bold(palette.error(HOT_GLYPH))} hot: +${formatTokens(tokens)} tokens in turn ${String(usage.turn)}${live}`;
6432
+ }
6433
+ /**
6434
+ * The color one category draws in.
6435
+ * @param palette - the terminal palette.
6436
+ * @param id - the category.
6437
+ * @returns its style.
6438
+ */
6439
+ function categoryStyle(palette, id) {
6440
+ switch (id) {
6441
+ case "system": return palette.dim;
6442
+ case "tools": return palette.accent;
6443
+ case "instructions": return palette.heading;
6444
+ case "skills": return palette.warning;
6445
+ case "context": return palette.success;
6446
+ case "messages": return palette.link;
6447
+ /* v8 ignore next 2 -- closed-union exhaustiveness guard */
6448
+ default: return assertNever(id, "context category");
6449
+ }
6450
+ }
6451
+ /**
6452
+ * A ratio as a percentage to one decimal, dropping a trailing `.0` from 10% up.
6453
+ * @param ratio - the share, from 0.
6454
+ * @param whole - round to a whole number, as the occupancy does.
6455
+ * @returns e.g. `0.0%`, `0.2%`, `98.8%`, `100%`.
6456
+ */
6457
+ function percent(ratio, whole) {
6458
+ const value = ratio * 100;
6459
+ if (whole) return `${String(Math.round(value))}%`;
6460
+ const tenths = Math.round(value * 10) / 10;
6461
+ return tenths >= 10 && Number.isInteger(tenths) ? `${String(tenths)}%` : `${tenths.toFixed(1)}%`;
6462
+ }
6463
+ /** Milliseconds the grid takes to fill on open. */
6464
+ const FILL_MS = 480;
6465
+ /** Milliseconds the hot region shimmers after open before a settled turn lets the block rest. */
6466
+ const SHIMMER_MS = 3200;
6467
+ /** Milliseconds per shimmer step. */
6468
+ const WAVE_STEP_MS = 70;
6469
+ /** Milliseconds the first free cell stays lit, then dark, while live. */
6470
+ const BLINK_MS = 400;
6471
+ /** Milliseconds between re-reads of the usage. */
6472
+ const REFRESH_MS = 250;
6473
+ /**
6474
+ * The `/context` transcript block. While it moves it is a
6475
+ * {@link RegisteredFade}: the application calls {@link ContextUsageBlock.tick}
6476
+ * on each fade period, and it settles once the open animation ran and no
6477
+ * turn runs, when it is retired, or once every row left the repaint window.
6478
+ * Rows above the repaint floor keep the text last drawn there.
6479
+ */
6480
+ var ContextUsageBlock = class {
6481
+ palette;
6482
+ options;
6483
+ usage;
6484
+ frame;
6485
+ bornAt;
6486
+ refreshedAt;
6487
+ settled;
6488
+ floor = 0;
6489
+ shown;
6490
+ memo;
6491
+ /**
6492
+ * @param palette - the terminal palette.
6493
+ * @param options - the usage reader, the live check, and the clock.
6494
+ */
6495
+ constructor(palette, options) {
6496
+ this.palette = palette;
6497
+ this.options = options;
6498
+ this.usage = options.read();
6499
+ const now = options.now?.();
6500
+ this.bornAt = now ?? 0;
6501
+ this.refreshedAt = this.bornAt;
6502
+ this.settled = now === void 0;
6503
+ this.frame = this.settled ? AT_REST : frameAt(0, options.live());
6504
+ }
6505
+ /** @returns true until the block settled. */
6506
+ needsRepaint() {
6507
+ return !this.settled;
6508
+ }
6509
+ /** Advance one fade period: re-read the usage when it is due, then move the animation or settle. */
6510
+ tick() {
6511
+ const clock = this.options.now;
6512
+ if (this.settled || clock === void 0) return;
6513
+ const now = clock();
6514
+ const live = this.options.live();
6515
+ if (!live && now - this.bornAt >= SHIMMER_MS) {
6516
+ this.usage = this.options.read();
6517
+ this.rest();
6518
+ return;
6519
+ }
6520
+ if (now - this.refreshedAt >= REFRESH_MS) {
6521
+ this.usage = this.options.read();
6522
+ this.refreshedAt = now;
6523
+ }
6524
+ const next = frameAt(now - this.bornAt, live);
6525
+ if (frameKey(next) !== frameKey(this.frame)) this.frame = next;
6526
+ }
6527
+ /** Settle on the last read without reading again, for a session switch or a newer `/context`. */
6528
+ retire() {
6529
+ this.rest();
6530
+ }
6531
+ /**
6532
+ * Hold the rows the renderer can no longer repaint.
6533
+ * @param floor - the first block line the renderer may repaint.
6534
+ */
6535
+ setRepaintFloor(floor) {
6536
+ this.floor = floor;
6537
+ if (this.shown !== void 0 && floor >= this.shown.lines.length) this.rest();
6538
+ }
6539
+ invalidate() {
6540
+ this.memo = void 0;
6541
+ }
6542
+ render(width) {
6543
+ const memo = this.memo;
6544
+ if (memo?.width === width && memo.usage === this.usage && memo.frame === this.frame && memo.floor === this.floor) return memo.lines;
6545
+ const lines = contextUsageLines(this.usage, this.palette, width, this.frame);
6546
+ const shown = this.shown;
6547
+ if (shown?.width === width) {
6548
+ const held = Math.min(this.floor, lines.length, shown.lines.length);
6549
+ lines.splice(0, held, ...shown.lines.slice(0, held));
6550
+ }
6551
+ this.shown = {
6552
+ width,
6553
+ lines
6554
+ };
6555
+ this.memo = {
6556
+ width,
6557
+ usage: this.usage,
6558
+ frame: this.frame,
6559
+ floor: this.floor,
6560
+ lines
6561
+ };
6562
+ return lines;
6563
+ }
6564
+ rest() {
6565
+ this.settled = true;
6566
+ this.frame = AT_REST;
6567
+ }
6568
+ };
6569
+ /**
6570
+ * The animation frame at one moment after open.
6571
+ * @param elapsed - milliseconds since the block opened.
6572
+ * @param live - whether a turn runs.
6573
+ * @returns the frame.
6574
+ */
6575
+ function frameAt(elapsed, live) {
6576
+ return {
6577
+ fill: Math.min(1, elapsed / FILL_MS),
6578
+ wave: Math.floor(elapsed / WAVE_STEP_MS),
6579
+ frontier: live && Math.floor(elapsed / BLINK_MS) % 2 === 0,
6580
+ live
6581
+ };
6582
+ }
6583
+ /**
6584
+ * A key equal for exactly the frames that draw the same.
6585
+ * @param frame - the frame.
6586
+ * @returns its fields joined.
6587
+ */
6588
+ function frameKey(frame) {
6589
+ return `${String(frame.fill)}|${String(frame.wave)}|${String(frame.frontier)}|${String(frame.live)}`;
6590
+ }
6591
+ //#endregion
6140
6592
  //#region lib/types/workflow-panel.js
6141
6593
  /**
6142
6594
  * Rows of the `/workflows` pickers: one row per workflow run of the bound
@@ -6363,6 +6815,19 @@ function injectedContextTitle(source) {
6363
6815
  const context = contextSource(source);
6364
6816
  return context === void 0 ? void 0 : contextTitle(context);
6365
6817
  }
6818
+ /** Source kinds the skill packages stamp on their catalog and on an invoked skill's body. */
6819
+ const SKILL_KINDS = ["skill-catalog", "skill-invocation"];
6820
+ /**
6821
+ * Attribute one injected `user/message` to a {@link ContextGroup}.
6822
+ * @param source - the message's durable source.
6823
+ * @returns the group, or undefined when this message is not injected context.
6824
+ */
6825
+ function contextGroup(source) {
6826
+ const context = contextSource(source);
6827
+ if (context === void 0) return void 0;
6828
+ if (SKILL_KINDS.includes(context.kind)) return "skills";
6829
+ return context.form === "instructions" ? "instructions" : "context";
6830
+ }
6366
6831
  /**
6367
6832
  * Narrow a message source to injected context.
6368
6833
  * @param source - the message's durable source.
@@ -12827,6 +13292,13 @@ var CompactionLedger = class {
12827
13292
  constructor(estimate) {
12828
13293
  this.estimate = estimate;
12829
13294
  }
13295
+ /**
13296
+ * The mirrored surface as it stands now.
13297
+ * @returns the nodes in surface order; the array is the ledger's own and changes with the next observed event.
13298
+ */
13299
+ surface() {
13300
+ return this.nodes;
13301
+ }
12830
13302
  /** Forget the mirrored surface and every open transaction. */
12831
13303
  clear() {
12832
13304
  this.nodes.length = 0;
@@ -12858,9 +13330,15 @@ var CompactionLedger = class {
12858
13330
  default: break;
12859
13331
  }
12860
13332
  if (!isSurfaceEvent(event)) return void 0;
12861
- const node = {
13333
+ const fact = this.factOf(event, turn);
13334
+ const group = fact.kind === "context" && event.type === "user/message" ? contextGroup(event.data.source) : void 0;
13335
+ const node = group === void 0 ? {
13336
+ seq: event.seq,
13337
+ fact
13338
+ } : {
12862
13339
  seq: event.seq,
12863
- fact: this.factOf(event, turn)
13340
+ fact,
13341
+ group
12864
13342
  };
12865
13343
  if (event.surfaceOp === "append") {
12866
13344
  this.nodes.push(node);
@@ -13674,6 +14152,10 @@ const LOCAL_COMMANDS = [
13674
14152
  name: "status",
13675
14153
  description: "Show context usage, token totals, session stats, todos, goal, plan, and permission"
13676
14154
  },
14155
+ {
14156
+ name: "context",
14157
+ description: "Show how the context window is used right now, by category, with the newest turn's tokens highlighted"
14158
+ },
13677
14159
  {
13678
14160
  name: "todos",
13679
14161
  description: "Browse the agent's todo list (Enter shows one item in full)"
@@ -13950,6 +14432,8 @@ var TuiApp = class {
13950
14432
  * terminal that fades nothing.
13951
14433
  */
13952
14434
  motions = new FadeRegistry();
14435
+ /** The newest `/context` block while it still animates or re-reads. */
14436
+ contextUsageBlock;
13953
14437
  /** The transient line on screen right now, with the clock that takes it down. */
13954
14438
  toast;
13955
14439
  /** The chrome motion running right now, and how much of the focused surface it lifts. */
@@ -14308,6 +14792,7 @@ var TuiApp = class {
14308
14792
  this.streaming = void 0;
14309
14793
  this.endFade();
14310
14794
  this.blockFades.clear();
14795
+ this.retireContextUsage();
14311
14796
  this.usage = EMPTY_USAGE;
14312
14797
  this.clearLiveUsage();
14313
14798
  this.pending = [];
@@ -15543,6 +16028,54 @@ var TuiApp = class {
15543
16028
  showStatus() {
15544
16029
  this.showBlock(statusReport(this.statusFacts()));
15545
16030
  }
16031
+ /**
16032
+ * Print the `/context` report for the bound session. It animates on a
16033
+ * terminal that runs motion, and re-reads the usage while a turn runs; a
16034
+ * newer report or a session switch settles the one before it.
16035
+ */
16036
+ showContextUsage() {
16037
+ const meter = this.deps.ctx.get("tokenMeter");
16038
+ if (meter === void 0) {
16039
+ this.notice("/context needs the token meter in this composition", "error");
16040
+ return;
16041
+ }
16042
+ this.retireContextUsage();
16043
+ const bound = this.bound;
16044
+ const read = () => {
16045
+ const { session } = bound.agent;
16046
+ const projections = this.deps.ctx.get("sessionProjections");
16047
+ const facts = projections === void 0 ? {} : readStatusFacts(projections, session);
16048
+ const selection = this.currentSelection(bound);
16049
+ const window = facts.context?.window ?? session.requestContext()?.contextWindow;
16050
+ return contextUsage({
16051
+ model: `${selection.provider}/${selection.model}`,
16052
+ turn: this.turn,
16053
+ priced: meter.measure(session).nodes,
16054
+ surface: this.compactions.surface(),
16055
+ toolsTokens: facts.breakdown?.toolsTokens ?? 0,
16056
+ ...facts.context === void 0 ? {} : { used: facts.context.used },
16057
+ ...window === void 0 ? {} : { window }
16058
+ });
16059
+ };
16060
+ const animate = this.fading && !this.deps.reducedMotion;
16061
+ const block = new ContextUsageBlock(this.deps.palette, {
16062
+ read,
16063
+ live: () => this.turnStartedAt !== void 0,
16064
+ ...animate ? { now: () => this.deps.now() } : {}
16065
+ });
16066
+ this.chat.addChild(block);
16067
+ if (block.needsRepaint()) {
16068
+ this.contextUsageBlock = block;
16069
+ this.motions.add(block);
16070
+ this.updateFadeTicker();
16071
+ }
16072
+ this.tui.requestRender();
16073
+ }
16074
+ /** Settle the running `/context` block, if any, on what it last read. */
16075
+ retireContextUsage() {
16076
+ this.contextUsageBlock?.retire();
16077
+ this.contextUsageBlock = void 0;
16078
+ }
15546
16079
  currentSelection(bound = this.bound) {
15547
16080
  const { selection, agent } = bound;
15548
16081
  const selected = selection.current ?? agent.session.requestHeader()?.config;
@@ -16666,6 +17199,9 @@ var TuiApp = class {
16666
17199
  case "status":
16667
17200
  this.showStatus();
16668
17201
  return;
17202
+ case "context":
17203
+ this.showContextUsage();
17204
+ return;
16669
17205
  case "todos":
16670
17206
  await this.browseTodos();
16671
17207
  return;
@@ -17753,6 +18289,7 @@ var TuiApp = class {
17753
18289
  if (child instanceof WorkflowBlock) {
17754
18290
  if (child.setRepaintFloor(repaintFloor(start, viewportTop))) changed = true;
17755
18291
  }
18292
+ if (child instanceof ContextUsageBlock) child.setRepaintFloor(repaintFloor(start, viewportTop));
17756
18293
  if (fades && (child instanceof AssistantBlock || child instanceof ToolBlock)) {
17757
18294
  if (child.setRepaintFloor(repaintFloor(start, viewportTop))) changed = true;
17758
18295
  }
@@ -17781,6 +18318,8 @@ var TuiApp = class {
17781
18318
  if (this.toast?.clock.expired() === true) this.hideToast();
17782
18319
  if (this.panelLift !== this.panelLiftNow()) this.refreshSubagentPanel();
17783
18320
  if (this.activitySlot.children.length > 0) this.refreshActivityBoard();
18321
+ this.contextUsageBlock?.tick();
18322
+ if (this.contextUsageBlock?.needsRepaint() === false) this.contextUsageBlock = void 0;
17784
18323
  this.motions.tick();
17785
18324
  this.tui.requestRender();
17786
18325
  this.updateFadeTicker();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@songtonyli/dsh-cli",
3
- "version": "0.1.78",
3
+ "version": "0.1.80",
4
4
  "description": "The dsh terminal agent: an interactive TUI over the DeepSeek Harness, with its whole Node runtime bundled in one install.",
5
5
  "license": "MIT",
6
6
  "type": "module",