@songtonyli/dsh-cli 0.1.28 → 0.1.30

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.28; `dsh --version`
29
+ Requires Node `^22.19.0 || >=24.0.0`. Version 0.1.30; `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.28 (deepseek-harness 0.1.6-alpha.2)')
21
+ console.log('@songtonyli/dsh-cli 0.1.30 (deepseek-harness 0.1.6-alpha.2)')
22
22
  process.exit(0)
23
23
  }
24
24
 
@@ -160,7 +160,7 @@ window.__ModuleLoader__.load({
160
160
  const SCROLLBAR_LINGER_MS = 2e3;
161
161
  /** Format complete-build metadata for the local brand badge. */
162
162
  function localBuildVersion() {
163
- return `0.1.6-alpha.2-b764393` + ({}.DSH_CLIENT_GIT_DIRTY === "true" ? "-dirty" : "");
163
+ return `0.1.6-alpha.2-34239dd` + ({}.DSH_CLIENT_GIT_DIRTY === "true" ? "-dirty" : "");
164
164
  }
165
165
  /** Each panel row subscribes only to its own selection state. */
166
166
  function PanelRow({ id, label, wide, usePanelInfo, selectPanel, renderSlot }) {
@@ -2,5 +2,5 @@
2
2
  # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
3
  # after editing either side, bring the other along and re-record with:
4
4
  # pnpm run verify-translation-pairing --write packages/bundle/tui-app/README.md
5
- README.md: aa8b58adb4cf1e76bf811e4630b15bba6c1a3653
6
- README.zh.md: bb19e39d7c185602a27debdd956406d422aec462
5
+ README.md: 6ca72d9a72b85bcc8de665c41bdeafd25d379632
6
+ README.zh.md: 4389467ff6efc4267033b3cb5353c568120e3e93
@@ -40,9 +40,9 @@ On quit the app prints `dsh: session <id> saved; resume with: dsh --profile tui
40
40
 
41
41
  ### The screen
42
42
 
43
- The header names the session by its title once one is generated or set, with the id beside it. The transcript grows in the terminal's own scrollback: your prompts start with `›` (attachments listed under them), assistant reasoning is dim above the Markdown reply, and each tool call is a card with a status glyph, the tool name, the presenter headline, and a body folded to `toolPreviewLines` rows. A nonempty system prompt and each injected context — instructions, catalogs, snapshots, notices, relays, and recalls — draw as a dim `⬡` title over the first `contextPreviewLines` rows of their model-facing text, with each snapshot contribution named above its own rows; an empty system prompt and a compaction replacement are omitted. A tool card and a context block that carry more rows than they draw end on one marker: `… <n> more rows · Space expands` while the conversation's focus holds that block, and `… <n> more rows · Ctrl+O expands` otherwise. Fenced code in a reply, the file rows of a `read` card, and the changed rows of an `edit` or `write` diff card — with `+` additions marked green, `-` removals red, and source text behind those signs drawn in the language the file's extension names — use syntax colours from a theme the terminal's own background picks, light or dark; the grammar of a language loads on the first block that asks for it, so that block draws plain and is repainted in colour a moment later, and a language with no grammar here, a terminal that reports neither 24-bit nor 256 colours, and `codeHighlight: false` each draw every block plain. Headings, links, list markers, quotes, and inline code share one cool dark-mode scale — a pale cyan, a deeper blue, and dim — so a reply sits beside a highlighted fence without contrasting hues. Streamed reply text fades in and every word keeps its own clock: a word enters near the terminal's background color and brightens to the color it settles in over `streamFadeSteps` ticks of `streamFadeStepMs` each, so a fast stream leaves a longer trail of brightening words rather than a darker one. Streamed reasoning and a tool card float out over the same duration: they appear at a lifted color and recede to the dim italic or palette colors they settle in; a card redrawn from persisted history carries no fade, and text that has settled is never dimmed again.
43
+ The header names the session by its title once one is generated or set, with the id beside it. The transcript grows in the terminal's own scrollback: your prompts start with `›` (attachments listed under them), assistant reasoning is dim above the Markdown reply, and each tool call is a card with a status glyph, the tool name, the presenter headline, a loading row while it runs, and a body folded to `toolPreviewLines` rows. The card appears when the model starts the call; the result rows float out when the tool answers. A nonempty system prompt and each injected context — instructions, catalogs, snapshots, notices, relays, and recalls — draw as a dim `⬡` title over the first `contextPreviewLines` rows of their model-facing text, with each snapshot contribution named above its own rows; an empty system prompt and a compaction replacement are omitted. A tool card and a context block that carry more rows than they draw end on one marker: `… <n> more rows · Space expands` while the conversation's focus holds that block, and `… <n> more rows · Ctrl+O expands` otherwise. Fenced code in a reply, the file rows of a `read` card, and the changed rows of an `edit` or `write` diff card — with `+` additions marked green, `-` removals red, and source text behind those signs drawn in the language the file's extension names — use syntax colours from a theme the terminal's own background picks, light or dark; the grammar of a language loads on the first block that asks for it, so that block draws plain and is repainted in colour a moment later, and a language with no grammar here, a terminal that reports neither 24-bit nor 256 colours, and `codeHighlight: false` each draw every block plain. Headings, links, list markers, quotes, and inline code share one cool dark-mode scale — a pale cyan, a deeper blue, and dim — so a reply sits beside a highlighted fence without contrasting hues. Streamed reply text fades in and every word keeps its own clock: a word enters near the terminal's background color and brightens to the color it settles in over `streamFadeSteps` ticks of `streamFadeStepMs` each, so a fast stream leaves a longer trail of brightening words rather than a darker one. Streamed reasoning and a tool card float out over the same duration: they appear at a lifted color and recede to the dim italic or palette colors they settle in; a card redrawn from persisted history carries no fade, and text that has settled is never dimmed again.
44
44
 
45
- Below the transcript sit a spinner while the agent works, any open prompt, a boxed follow-ups list while messages wait, the editor, the subagent panel, and the footer: a status bar that, unfocused, is one line built from both ends inward. The editor's caret is the terminal's own blinking bar: the app asks for that shape at start, gives your default back on quit, and draws no caret at all while the status bar or the panel holds the keyboard. The model is anchored at the left edge and is never dropped — past 20 columns it falls back to the bare model name, and only a label still too wide for that is ellipsized — and the two keys that leave the input are anchored at the right edge as `Shift+↑ read · Shift+↓ status`, narrowing to `Shift+↑↓ nav` and dropped below 40 columns. The key facts fill whatever middle is left, in bar order: effort (`effort default` when the selection leaves reasoning to the model), the running turn's elapsed time, the context window percentage, the todo counts, and the workspace path (shortened with `~` and `…/` when long). Every segment that middle cannot hold folds into a trailing `+N`, together with the segments the unfocused line never draws — the permission preset, cumulative token usage, the goal and plan-mode markers from the projection seam, and the count of pending attachments. Compaction and model-request retries appear as notices, the same facts the browser's markers carry.
45
+ Below the transcript sit a spinner while the agent works — its label carries live `↑` send and `↓` receive tokens for the current model call, as compact `k` / `M` / `B` counts, growing as the stream arrives and settling on the provider usage chunk — any open prompt, a boxed follow-ups list while messages wait, the editor, the subagent panel, and the footer: a status bar that, unfocused, is one line built from both ends inward. The editor's caret is the terminal's own blinking bar: the app asks for that shape at start, gives your default back on quit, and draws no caret at all while the status bar or the panel holds the keyboard. The model is anchored at the left edge and is never dropped — past 20 columns it falls back to the bare model name, and only a label still too wide for that is ellipsized — and the two keys that leave the input are anchored at the right edge as `Shift+↑ read · Shift+↓ status`, narrowing to `Shift+↑↓ nav` and dropped below 40 columns. The key facts fill whatever middle is left, in bar order: effort (`effort default` when the selection leaves reasoning to the model), the running turn's elapsed time, the context window percentage, the todo counts, and the workspace path (shortened with `~` and `…/` when long). Every segment that middle cannot hold folds into a trailing `+N`, together with the segments the unfocused line never draws — the permission preset, token usage (session totals plus the in-flight call), the goal and plan-mode markers from the projection seam, and the count of pending attachments. Compaction and model-request retries appear as notices, the same facts the browser's markers carry.
46
46
 
47
47
  While the keyboard walks the conversation a framed inspector is docked directly above the editor, and the frame is the mode: it is drawn exactly while the conversation holds the keyboard. Its top rule carries an inverse ` ● READ ` chip and the focused section's heading — the section's position among the navigable blocks, the turn it belongs to, and what the section is — as in `╭ ● READ ─ 3/12 · turn 2 · bash git status · result ─╮`. Under it the block's parts draw as a numbered wrapping strip like `← 1 call · [2 result] →` when the block has more than one, the held label bracketed as well as accented so the selection is legible with no color at all; then the section's own source rows, each prefixed with `│ ` and wrapped two columns narrower, folded at `focusPreviewLines` for every section kind — a system prompt and an injected context included — with `… <n> more rows · Ctrl+G reads it` under them. The bottom rule carries the keys the conversation answers, `↑↓ sections · ←→ parts · Space folds · Ctrl+G reader · Esc input`, narrowed to `↑↓ ←→ · Space folds · Esc input` and then to `Esc input` as the terminal loses columns.
48
48
 
@@ -238,11 +238,11 @@ The runner is a direct driver over the core API carrier, like `dsh-headless`, th
238
238
 
239
239
  ### Run flow
240
240
 
241
- The runner awaits the complete application (`ctx.get('loader')?.await()`) and builds a session host over the core registry with three operations: `create` makes one fresh persisted Agent with the shared [`agentDefaultModel`](../../core/agent-default-model/README.md) selection, `resume` reads the persisted log in pages through a read handle of `ctx.sessionPersistence` and resumes the Agent through the registry, and `fork` observes the source through `ctx.sessionQuery`, cuts after the chosen (by default the last) `turn/end` up to the next `turn/start`, and creates a seeded Agent with `parentSession` and `isSeeded` metadata. Every operation installs a `ModelSelectionRef` in the Agent's scoped setup so `/model` changes the next request. The terminal application starts on the session `--resume` or a fresh `create` yields, subscribes to `session/event`, `agent/assistant-stream`, and `agent/status`, answers the `approval/request` and `user-questions/request` waterfalls for the bound Agent only, and switches sessions by binding the next one and disposing the previous handle; while the host opens the next session the editor refuses input, and a quit during that wait releases the session that arrives afterwards. Quitting cancels any running turn, waits for quiescence, flushes the bound Session, disposes its handle, and requests exit 0; a driver failure writes `dsh: <message>` to stderr and requests exit 1. `/resume` and `/sessions` share the persisted-session chooser. Editor `Shift+Tab` dispatches empty `/effort` to open its current-model picker, and editor `Shift+Left` / `Shift+Right` use pi-tui's word navigation. `/login` starts `authorization.begin` with only subscription methods (every method except a key-collecting `api-key` login). A notice the flow marks with `openInBrowser` is handed to the default browser through `dsh-native-command`'s credential-scrubbed helper while the URL stays printed; the handoff is suppressed when `openBrowser` is false, the launch came through SSH, or the host has no desktop, and an opener failure becomes a notice beside the URL rather than a sign-in failure. A nonempty `!` or `!!` line submitted in the editor runs through `ctx.shell` in this process; `!` injects a next-step notice and `!!` stays local.
241
+ The runner awaits the complete application (`ctx.get('loader')?.await()`) and builds a session host over the core registry with three operations: `create` makes one fresh persisted Agent with the shared [`agentDefaultModel`](../../core/agent-default-model/README.md) selection, `resume` takes the Agent write handle first and then observes the live Session through `ctx.sessionQuery` so bind draws every persisted event including resume closers, and `fork` observes the source through `ctx.sessionQuery`, cuts after the chosen (by default the last) `turn/end` up to the next `turn/start`, and creates a seeded Agent with `parentSession` and `isSeeded` metadata. Every operation installs a `ModelSelectionRef` in the Agent's scoped setup so `/model` changes the next request. The terminal application starts on the session `--resume` or a fresh `create` yields, subscribes to `session/event`, `agent/assistant-stream`, and `agent/status`, answers the `approval/request` and `user-questions/request` waterfalls for the bound Agent only, and switches sessions by binding the next one and disposing the previous handle; while the host opens the next session the editor refuses input, and a quit during that wait releases the session that arrives afterwards. Quitting cancels any running turn, waits for quiescence, flushes the bound Session, disposes its handle, and requests exit 0; a driver failure writes `dsh: <message>` to stderr and requests exit 1. `/resume` and `/sessions` share the persisted-session chooser. Editor `Shift+Tab` dispatches empty `/effort` to open its current-model picker, and editor `Shift+Left` / `Shift+Right` use pi-tui's word navigation. `/login` starts `authorization.begin` with only subscription methods (every method except a key-collecting `api-key` login). A notice the flow marks with `openInBrowser` is handed to the default browser through `dsh-native-command`'s credential-scrubbed helper while the URL stays printed; the handoff is suppressed when `openBrowser` is false, the launch came through SSH, or the host has no desktop, and an opener failure becomes a notice beside the URL rather than a sign-in failure. A nonempty `!` or `!!` line submitted in the editor runs through `ctx.shell` in this process; `!` injects a next-step notice and `!!` stays local.
242
242
 
243
243
  ### Rendering model
244
244
 
245
- 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 replacements and tool or model sources are omitted), `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). Live incrementality comes from `agent/assistant-stream` text and reasoning deltas. Session facts outside the log come from the same services the browser reads: `sessionTitle`, `permissionPresets`, `sessionQuery` for the picker, `/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.
245
+ 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 replacements and tool or model sources are omitted), `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). 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 carries 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, `/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.
246
246
 
247
247
  ### Patch surface over base
248
248
 
@@ -252,7 +252,7 @@ The patch rides over `dsh-base`: it sets the coding persona prefix and cwd suffi
252
252
 
253
253
  | File | Role |
254
254
  |---|---|
255
- | [`src/index.ts`](src/index.ts) | The `tui-app` plugin: the session host (create, resume, fork), history read, quit flow, exit mapping |
255
+ | [`src/index.ts`](src/index.ts) | The `tui-app` plugin: the session host (create, resume, fork), resume observation, quit flow, exit mapping |
256
256
  | [`src/startup.ts`](src/startup.ts) | The `tui-app-startup` provider: prompt positional, `--resume`, `--no-open`, and `--help` |
257
257
  | [`src/app.ts`](src/app.ts) | The terminal application: layout, the key router, commands, session binding, seams, log and stream folding, the stop arm, the transient line it mounts, the terminal handover the reader runs on, and prefix-on-submit `!` / `!!` |
258
258
  | [`src/keys.ts`](src/keys.ts) | The key model: the focus regions, what one press means in each, the legends they degrade through, the entry keys, the `/help` lines, and the handoff window |
@@ -261,7 +261,7 @@ The patch rides over `dsh-base`: it sets the coding persona prefix and cwd suffi
261
261
  | [`src/permission.ts`](src/permission.ts) | Permission-preset names and picker rows for `/permission` |
262
262
  | [`src/attach.ts`](src/attach.ts) | `/attach`: local files into image or file blocks through the attachment store |
263
263
  | [`src/export.ts`](src/export.ts) | `/export`: the session-log ZIP written through the export package's archive helpers |
264
- | [`src/blocks.ts`](src/blocks.ts) | Transcript components: user prompt, 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, so a frame of a settled transcript costs one key comparison per block and a stream delta colours only the fence that changed |
264
+ | [`src/blocks.ts`](src/blocks.ts) | Transcript components: user prompt, 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 |
265
265
  | [`src/context.ts`](src/context.ts) | Project logged system prompts and injected user messages into transcript sections |
266
266
  | [`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 |
267
267
  | [`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 |
@@ -40,9 +40,9 @@ dsh tui --no-open # print sign-in URLs without opening a
40
40
 
41
41
  ### 屏幕布局
42
42
 
43
- 页眉在标题生成或设置后以标题命名会话,并在旁边显示 id。对话记录在终端自身的回滚区中增长:你的提示以 `›` 开头(附件列在其下),assistant 的推理以暗色显示在 Markdown 回复上方,每次工具调用是一张卡片,含状态符号、工具名、呈现器标题,以及折叠到 `toolPreviewLines` 行的正文。非空的系统提示词与每一条注入的上下文——instructions、catalogs、snapshots、notices、relays 与 recalls——绘制为暗色 `⬡` 标题,其下是面向模型文本的前 `contextPreviewLines` 行,快照的每一份贡献具名写在其自身各行上方;空的系统提示词与压缩替换则省略。承载的行数多于其绘制行数的工具卡片与上下文块,结尾都是同一条标记:该块被对话记录的焦点持有时为 `… <n> more rows · Space expands`,否则为 `… <n> more rows · Ctrl+O expands`。回复中的围栏代码、`read` 卡片的文件行,以及 `edit` 或 `write` diff 卡片的变更行——其中 `+` 新增项标为绿色、`-` 删除项标为红色,符号后的源文本按文件扩展名对应的语言绘制——都使用语法高亮,配色主题由终端自身的背景在明暗之间选定;某种语言的语法会在第一个用到它的代码块出现时才加载,因此该块先以纯文本绘制、随后被重绘为彩色;这里没有对应语法的语言、既不支持 24 位也不支持 256 色的终端,以及 `codeHighlight: false`,都会把每个代码块画成纯文本。标题、链接、列表标记、引用与行内代码共用一套暗色冷色阶——浅青、更深的蓝与暗色——因此回复能挨着高亮围栏,而不靠对比色相。流式回复文字会淡入,而且每个词各走各的时钟:一个词以接近终端背景色的亮度出现,并经 `streamFadeSteps` 次、每次 `streamFadeStepMs` 提亮到它最终稳定的颜色,因此流得更快只会留下更长的一串正在提亮的词,而不会更暗。流式推理与工具卡片在同一时长内浮出:它们以抬高的颜色出现,再退回到稳定时的暗色斜体或调色板颜色;从持久化历史重绘的卡片不带淡入,已经稳定下来的文字也不会再被调暗。
43
+ 页眉在标题生成或设置后以标题命名会话,并在旁边显示 id。对话记录在终端自身的回滚区中增长:你的提示以 `›` 开头(附件列在其下),assistant 的推理以暗色显示在 Markdown 回复上方,每次工具调用是一张卡片,含状态符号、工具名、呈现器标题、运行中的一行加载标记,以及折叠到 `toolPreviewLines` 行的正文。卡片在模型开始调用时出现;结果行在工具回答后浮出。非空的系统提示词与每一条注入的上下文——instructions、catalogs、snapshots、notices、relays 与 recalls——绘制为暗色 `⬡` 标题,其下是面向模型文本的前 `contextPreviewLines` 行,快照的每一份贡献具名写在其自身各行上方;空的系统提示词与压缩替换则省略。承载的行数多于其绘制行数的工具卡片与上下文块,结尾都是同一条标记:该块被对话记录的焦点持有时为 `… <n> more rows · Space expands`,否则为 `… <n> more rows · Ctrl+O expands`。回复中的围栏代码、`read` 卡片的文件行,以及 `edit` 或 `write` diff 卡片的变更行——其中 `+` 新增项标为绿色、`-` 删除项标为红色,符号后的源文本按文件扩展名对应的语言绘制——都使用语法高亮,配色主题由终端自身的背景在明暗之间选定;某种语言的语法会在第一个用到它的代码块出现时才加载,因此该块先以纯文本绘制、随后被重绘为彩色;这里没有对应语法的语言、既不支持 24 位也不支持 256 色的终端,以及 `codeHighlight: false`,都会把每个代码块画成纯文本。标题、链接、列表标记、引用与行内代码共用一套暗色冷色阶——浅青、更深的蓝与暗色——因此回复能挨着高亮围栏,而不靠对比色相。流式回复文字会淡入,而且每个词各走各的时钟:一个词以接近终端背景色的亮度出现,并经 `streamFadeSteps` 次、每次 `streamFadeStepMs` 提亮到它最终稳定的颜色,因此流得更快只会留下更长的一串正在提亮的词,而不会更暗。流式推理与工具卡片在同一时长内浮出:它们以抬高的颜色出现,再退回到稳定时的暗色斜体或调色板颜色;从持久化历史重绘的卡片不带淡入,已经稳定下来的文字也不会再被调暗。
44
44
 
45
- 对话记录下方依次是 agent 工作时的旋转指示、任何打开的提示、有消息等待时的带框 follow-ups 列表、编辑器、子 agent 面板,以及页脚:未聚焦时是一行由两端向内构建的状态栏。编辑器的光标是终端自身的闪烁竖条:应用在启动时请求这一形状,退出时把你的默认形状还回去,而状态栏或面板持有键盘期间完全不绘制光标。模型锚定在左端且永不丢弃——超过 20 列时退回到裸模型名,只有仍然过宽的标签才会被省略号截断——离开编辑器的那两个按键则锚定在右端,写作 `Shift+↑ read · Shift+↓ status`,窄到一定程度收缩为 `Shift+↑↓ nav`,不足 40 列时整体丢弃。关键事实填满剩下的中间部分,按状态栏顺序排列:推理强度(选择把推理交给模型时标为 `effort default`)、进行中轮次的已用时间、上下文窗口百分比、todo 计数,以及 workspace 路径(过长时以 `~` 与 `…/` 缩短)。中间部分容纳不下的每个分段都折进末尾的 `+N`,未聚焦行从不绘制的那些分段也一并折入——权限预设、累计 token 用量、来自投影接缝的目标与计划模式标记,以及待发送附件的数量。压缩与模型请求重试以通知形式出现,与浏览器标记承载的事实相同。
45
+ 对话记录下方依次是 agent 工作时的旋转指示——其标签带着当前这次模型调用的实时 `↑` 发送与 `↓` 接收 token,以紧凑的 `k` / `M` / `B` 计数,随数据流入增长,并在提供方的 usage 块到达后落定——任何打开的提示、有消息等待时的带框 follow-ups 列表、编辑器、子 agent 面板,以及页脚:未聚焦时是一行由两端向内构建的状态栏。编辑器的光标是终端自身的闪烁竖条:应用在启动时请求这一形状,退出时把你的默认形状还回去,而状态栏或面板持有键盘期间完全不绘制光标。模型锚定在左端且永不丢弃——超过 20 列时退回到裸模型名,只有仍然过宽的标签才会被省略号截断——离开编辑器的那两个按键则锚定在右端,写作 `Shift+↑ read · Shift+↓ status`,窄到一定程度收缩为 `Shift+↑↓ nav`,不足 40 列时整体丢弃。关键事实填满剩下的中间部分,按状态栏顺序排列:推理强度(选择把推理交给模型时标为 `effort default`)、进行中轮次的已用时间、上下文窗口百分比、todo 计数,以及 workspace 路径(过长时以 `~` 与 `…/` 缩短)。中间部分容纳不下的每个分段都折进末尾的 `+N`,未聚焦行从不绘制的那些分段也一并折入——权限预设、token 用量(会话合计加上进行中的这次调用)、来自投影接缝的目标与计划模式标记,以及待发送附件的数量。压缩与模型请求重试以通知形式出现,与浏览器标记承载的事实相同。
46
46
 
47
47
  键盘在对话记录中移动时,编辑器正上方停靠着一个带边框的检视面板,边框即模式:它恰好在对话记录持有键盘时绘制。其顶边线带有一个反白的 ` ● READ ` 徽标与当前聚焦小节的标题——该小节在可导航块中的位置、所属轮次,以及这是哪一种小节——例如 `╭ ● READ ─ 3/12 · turn 2 · bash git status · result ─╮`。其下在块含多个部分时,把这些部分绘制成形如 `← 1 call · [2 result] →` 的带编号、会折行的选择行,被持有的标签除强调色外还加上方括号,因此完全无颜色时选择仍然可读;再往下是该小节自身的源文本行,每行以 `│ ` 起头并按窄两列换行,对每一种小节——含系统提示词与注入的上下文——都折叠到 `focusPreviewLines` 行,其下写出 `… <n> more rows · Ctrl+G reads it`。底边线列出对话记录所应答的按键 `↑↓ sections · ←→ parts · Space folds · Ctrl+G reader · Esc input`,随着终端列数减少收缩为 `↑↓ ←→ · Space folds · Esc input`,再收缩为 `Esc input`。
48
48
 
@@ -238,11 +238,11 @@ runner 与 `dsh-headless` 一样是核心 API 载体之上的直接驱动器,
238
238
 
239
239
  ### 运行流程
240
240
 
241
- runner 等待完整应用就绪(`ctx.get('loader')?.await()`),并在核心注册表之上构建含三个操作的会话宿主:`create` 用共享的 [`agentDefaultModel`](../../core/agent-default-model/README.zh.md) 选择创建一个全新的持久化 Agent,`resume` 通过 `ctx.sessionPersistence` 的只读句柄分页读取持久化日志并经注册表恢复 Agent,`fork` 通过 `ctx.sessionQuery` 观察源会话、在所选(默认最后一个)`turn/end` 之后直到下一个 `turn/start` 处切割,并创建带 `parentSession` 与 `isSeeded` 元数据的种子 Agent。每个操作都在 Agent 的作用域 setup 中安装 `ModelSelectionRef`,因此 `/model` 会改变下一次请求。终端应用从 `--resume` 或一次新的 `create` 产生的会话开始,订阅 `session/event`、`agent/assistant-stream` 与 `agent/status`,只为绑定的 Agent 应答 `approval/request` 与 `user-questions/request` waterfall,并通过绑定下一个会话、dispose 先前句柄来切换会话;宿主打开下一个会话期间编辑器拒绝输入,等待期间退出会释放随后到达的会话。退出时取消任何进行中的轮次、等待完全停稳、flush 绑定的会话、dispose 其句柄并请求以 0 退出;驱动器失败会向 stderr 写入 `dsh: <message>` 并请求以 1 退出。`/resume` 与 `/sessions` 共用持久化会话选择器。编辑器中的 `Shift+Tab` 会派发空参数 `/effort` 以打开当前模型的推理强度选择器,而编辑器中的 `Shift+Left` / `Shift+Right` 使用 pi-tui 的词导航。`/login` 只带着订阅方法(除收集密钥的 `api-key` 登录外的每一种方法)启动 `authorization.begin`。flow 用 `openInBrowser` 标记的 notice 会经 `dsh-native-command` 的凭据擦除辅助进程交给默认浏览器,URL 同时保持打印;当 `openBrowser` 为 false、启动经过 SSH 或宿主没有桌面时抑制该交接,打开器失败则成为 URL 旁的一条通知,而非登录失败。编辑器里提交的非空 `!` 或 `!!` 行经本进程的 `ctx.shell` 运行;`!` 注入一条下一步通知,`!!` 只留在本地。
241
+ runner 等待完整应用就绪(`ctx.get('loader')?.await()`),并在核心注册表之上构建含三个操作的会话宿主:`create` 用共享的 [`agentDefaultModel`](../../core/agent-default-model/README.zh.md) 选择创建一个全新的持久化 Agent,`resume` 先拿到 Agent 写句柄,再经 `ctx.sessionQuery` 观察实时 Session,使 bind 画出每条持久化事件(包括恢复时的闭合事件),`fork` 通过 `ctx.sessionQuery` 观察源会话、在所选(默认最后一个)`turn/end` 之后直到下一个 `turn/start` 处切割,并创建带 `parentSession` 与 `isSeeded` 元数据的种子 Agent。每个操作都在 Agent 的作用域 setup 中安装 `ModelSelectionRef`,因此 `/model` 会改变下一次请求。终端应用从 `--resume` 或一次新的 `create` 产生的会话开始,订阅 `session/event`、`agent/assistant-stream` 与 `agent/status`,只为绑定的 Agent 应答 `approval/request` 与 `user-questions/request` waterfall,并通过绑定下一个会话、dispose 先前句柄来切换会话;宿主打开下一个会话期间编辑器拒绝输入,等待期间退出会释放随后到达的会话。退出时取消任何进行中的轮次、等待完全停稳、flush 绑定的会话、dispose 其句柄并请求以 0 退出;驱动器失败会向 stderr 写入 `dsh: <message>` 并请求以 1 退出。`/resume` 与 `/sessions` 共用持久化会话选择器。编辑器中的 `Shift+Tab` 会派发空参数 `/effort` 以打开当前模型的推理强度选择器,而编辑器中的 `Shift+Left` / `Shift+Right` 使用 pi-tui 的词导航。`/login` 只带着订阅方法(除收集密钥的 `api-key` 登录外的每一种方法)启动 `authorization.begin`。flow 用 `openInBrowser` 标记的 notice 会经 `dsh-native-command` 的凭据擦除辅助进程交给默认浏览器,URL 同时保持打印;当 `openBrowser` 为 false、启动经过 SSH 或宿主没有桌面时抑制该交接,打开器失败则成为 URL 旁的一条通知,而非登录失败。编辑器里提交的非空 `!` 或 `!!` 行经本进程的 `ctx.shell` 运行;`!` 注入一条下一步通知,`!!` 只留在本地。
242
242
 
243
243
  ### 渲染模型
244
244
 
245
- 持久事实来自会话日志:`system/message`(非空提示词完整画出;空的绘制则省略)、`user/message`(自己提交的消息只绘制一次,其回显按消息 id 跳过;注入的上下文——instructions、catalogs、snapshots、notices、relays、recalls 以及未声明的形式——以暗色 `⬡` 行完整画出,快照按具名贡献各成一部分;压缩替换以及工具或模型来源则省略)、`assistant/message`(用已提交文本替换流式块,并把用量折入页脚)、`tool/call` 与 `tool/result`(工具声明 `presentCall` 与 `presentResult` 视图时据此绘制,否则回退到原始参数与原始结果)、`turn/end` 通知、`workspace/changes`(在 Host 仍保存摘要时,以一行通知给出该轮的文件数与行数)、`session/title`(页眉)、`permission/preset`(页脚),以及所属 `turn/start` 之下的 `todo/write`(某条 todo 的详情页所报告的轮次;该列表不带逐条标识,因此改写措辞的条目算作新条目)。实时增量来自 `agent/assistant-stream` 的文本与推理增量。日志之外的会话事实来自浏览器读取的同一批服务:`sessionTitle`、`permissionPresets`、供选择器、`/deliverables` 与子 agent 详情使用的 `sessionQuery`、供页脚、`/status`、`/todos` 与 `/outline` 使用的 `sessionProjections`、供 `@` 补全使用的 `fileReferences` 与 `sessionReferenceResolver`、`attachments`、`skills`、`authorization`、`settings`、`subagents`,以及供 `/plugins` 使用的 Loader 条目。模态提示是进程本地的呈现,从不写入日志。
245
+ 持久事实来自会话日志:`system/message`(非空提示词完整画出;空的绘制则省略)、`user/message`(自己提交的消息只绘制一次,其回显按消息 id 跳过;注入的上下文——instructions、catalogs、snapshots、notices、relays、recalls 以及未声明的形式——以暗色 `⬡` 行完整画出,快照按具名贡献各成一部分;压缩替换以及工具或模型来源则省略)、`assistant/message`(用已提交文本替换流式块,并把用量折入页脚)、`tool/call` 与 `tool/result`(工具声明 `presentCall` 与 `presentResult` 视图时据此绘制,否则回退到原始参数与原始结果)、`turn/end` 通知、`workspace/changes`(在 Host 仍保存摘要时,以一行通知给出该轮的文件数与行数)、`session/title`(页眉)、`permission/preset`(页脚),以及所属 `turn/start` 之下的 `todo/write`(某条 todo 的详情页所报告的轮次;该列表不带逐条标识,因此改写措辞的条目算作新条目)。实时增量来自 `agent/assistant-stream` 的文本、推理、工具调用与用量增量:模型一报出工具名就挂上卡片,工作时的旋转指示带着该次调用的实时 `↑` 发送与 `↓` 接收。日志之外的会话事实来自浏览器读取的同一批服务:`sessionTitle`、`permissionPresets`、供选择器、`/deliverables` 与子 agent 详情使用的 `sessionQuery`、供页脚、`/status`、`/todos` 与 `/outline` 使用的 `sessionProjections`、供 `@` 补全使用的 `fileReferences` 与 `sessionReferenceResolver`、`attachments`、`skills`、`authorization`、`settings`、`subagents`,以及供 `/plugins` 使用的 Loader 条目。模态提示是进程本地的呈现,从不写入日志。
246
246
 
247
247
  ### 基于 base 的 patch 面
248
248
 
@@ -252,7 +252,7 @@ runner 等待完整应用就绪(`ctx.get('loader')?.await()`),并在核心
252
252
 
253
253
  | 文件 | 职责 |
254
254
  |---|---|
255
- | [`src/index.ts`](src/index.ts) | `tui-app` 插件:会话宿主(创建、恢复、fork)、历史读取、退出流程、退出码映射 |
255
+ | [`src/index.ts`](src/index.ts) | `tui-app` 插件:会话宿主(创建、恢复、fork)、恢复观察、退出流程、退出码映射 |
256
256
  | [`src/startup.ts`](src/startup.ts) | `tui-app-startup` 提供方:提示位置参数、`--resume`、`--no-open` 与 `--help` |
257
257
  | [`src/app.ts`](src/app.ts) | 终端应用:布局、按键路由、命令、会话绑定、接缝、日志与流的折叠、停止装填、它挂载的临时提示行、阅读器所依托的终端交接,以及提交时解析的 `!` / `!!` |
258
258
  | [`src/keys.ts`](src/keys.ts) | 按键模型:各焦点区域、一次按键在每个区域中的含义、它们逐级收缩的按键提示、进入用的按键、`/help` 的各行,以及交接窗口 |
@@ -261,7 +261,7 @@ runner 等待完整应用就绪(`ctx.get('loader')?.await()`),并在核心
261
261
  | [`src/permission.ts`](src/permission.ts) | `/permission` 的权限预设名称及选择器行 |
262
262
  | [`src/attach.ts`](src/attach.ts) | `/attach`:本地文件经附件存储成为图片或文件块 |
263
263
  | [`src/export.ts`](src/export.ts) | `/export`:通过导出包的归档辅助函数写出会话日志 ZIP |
264
- | [`src/blocks.ts`](src/blocks.ts) | 对话记录组件:用户提示、assistant 回复、工具卡片、系统提示词与注入上下文、通知;可导航的块暴露其各小节并绘制焦点标记条,可折叠的块则承载两个折叠键共用的那条标记。每个块保留上次画出的行,回复还保留上次 Markdown 解析所着色的代码围栏,因此已稳定的对话记录每帧只花每块一次键比较,一次流式增量也只为发生变化的那个围栏着色 |
264
+ | [`src/blocks.ts`](src/blocks.ts) | 对话记录组件:用户提示、assistant 回复、工具卡片、系统提示词与注入上下文、通知;可导航的块暴露其各小节并绘制焦点标记条,可折叠的块则承载两个折叠键共用的那条标记。每个块保留上次画出的行,回复还保留上次 Markdown 解析所着色的代码围栏,并只对最后一个已关闭围栏之后仍打开的尾部重新词法分析,因此已稳定的对话记录每帧只花每块一次键比较,一次流式增量也只为发生变化的那个围栏着色 |
265
265
  | [`src/context.ts`](src/context.ts) | 把已记录的系统提示词与注入的用户消息投影为对话记录小节 |
266
266
  | [`src/navigation.ts`](src/navigation.ts) | 把对话记录看作各个小节、沿四条轴走遍它们的光标、这些小节归入的各轮次,以及检视面板的标题 |
267
267
  | [`src/inspector.ts`](src/inspector.ts) | 停靠的检视面板:带模式徽标的边框面板、小节标题、带编号且会折行的各部分选择行、折叠后的各行,及其挂载的组件 |
@@ -345,14 +345,26 @@ function contentText(blocks) {
345
345
  }).filter((part) => part !== "").join("\n");
346
346
  }
347
347
  /**
348
- * Compact token count: `950`, `1.2k`, `3.4M`.
348
+ * Compact token count with a thousands/millions/billions unit: `950`, `1.2k`,
349
+ * `12.3k`, `3.4M`, `1.2B`. A trailing `.0` is dropped so `1000` reads `1k`.
349
350
  * @param count - a non-negative token count.
350
351
  * @returns the formatted count.
351
352
  */
352
353
  function formatTokens(count) {
353
354
  if (count < 1e3) return String(count);
354
- if (count < 1e6) return `${(count / 1e3).toFixed(count < 1e4 ? 1 : 0)}k`;
355
- return `${(count / 1e6).toFixed(1)}M`;
355
+ if (count < 1e6) return formatScaled(count / 1e3, "k");
356
+ if (count < 1e9) return formatScaled(count / 1e6, "M");
357
+ return formatScaled(count / 1e9, "B");
358
+ }
359
+ /**
360
+ * One decimal place and a unit letter, dropping a trailing `.0`.
361
+ * @param value - the count already divided by the unit's base.
362
+ * @param unit - `k`, `M`, or `B`.
363
+ * @returns the compact count.
364
+ */
365
+ function formatScaled(value, unit) {
366
+ const fixed = value.toFixed(1);
367
+ return `${fixed.endsWith(".0") ? fixed.slice(0, -2) : fixed}${unit}`;
356
368
  }
357
369
  /**
358
370
  * Compact elapsed time for the live counters: `0s`, `8s`, `1m12s`, `1h04m`,
@@ -391,6 +403,59 @@ const EMPTY_USAGE = {
391
403
  cacheReadTokens: 0,
392
404
  lastInputTokens: 0
393
405
  };
406
+ /** Characters treated as one token when the provider has not yet reported usage. */
407
+ const CHARS_PER_TOKEN = 4;
408
+ /**
409
+ * Approximate a token count from streamed character length, the same 4-chars
410
+ * rule the Cursor adapter uses when a provider omits prompt usage.
411
+ * @param chars - non-negative character count; a negative value counts as 0.
412
+ * @returns `ceil(chars / 4)`.
413
+ */
414
+ function estimateTokens(chars) {
415
+ return Math.ceil(Math.max(0, chars) / CHARS_PER_TOKEN);
416
+ }
417
+ /** Prompt tokens occupying the context window: uncached input plus cache read. */
418
+ function promptTokens(usage) {
419
+ return usage.inputTokens + (usage.cacheReadTokens ?? 0);
420
+ }
421
+ /**
422
+ * Billed prompt tokens of one usage record: uncached input plus cache read
423
+ * and cache write.
424
+ * @param usage - one model call's usage.
425
+ * @returns the billed send count.
426
+ */
427
+ function billedInputTokens(usage) {
428
+ return promptTokens(usage) + (usage.cacheWriteTokens ?? 0);
429
+ }
430
+ /**
431
+ * Fold an in-flight model call into the session totals for the footer.
432
+ * @param totals - committed totals so far.
433
+ * @param live - the current call; absent leaves `totals` unchanged.
434
+ * @returns the totals the footer should draw right now.
435
+ */
436
+ function withLiveUsage(totals, live) {
437
+ if (live === void 0) return totals;
438
+ const prompt = promptTokens(live);
439
+ return {
440
+ inputTokens: totals.inputTokens + live.inputTokens,
441
+ outputTokens: totals.outputTokens + live.outputTokens,
442
+ cacheReadTokens: totals.cacheReadTokens + (live.cacheReadTokens ?? 0),
443
+ lastInputTokens: prompt > 0 ? prompt : totals.lastInputTokens
444
+ };
445
+ }
446
+ /**
447
+ * The ↑send ↓receive suffix the working spinner draws for the current call.
448
+ * @param usage - the in-flight call; absent or zero draws nothing.
449
+ * @returns the suffix without a leading space, or the empty string.
450
+ */
451
+ function formatLiveUsage(usage) {
452
+ if (usage === void 0) return "";
453
+ const send = billedInputTokens(usage);
454
+ const parts = [];
455
+ if (send > 0) parts.push(`↑${formatTokens(send)}`);
456
+ if (usage.outputTokens > 0) parts.push(`↓${formatTokens(usage.outputTokens)}`);
457
+ return parts.length === 0 ? "" : `${parts.join(" ")} tokens`;
458
+ }
394
459
  /**
395
460
  * Fold one committed usage record into the totals.
396
461
  * @param totals - the totals so far.
@@ -402,7 +467,7 @@ function addUsage(totals, usage) {
402
467
  inputTokens: totals.inputTokens + usage.inputTokens,
403
468
  outputTokens: totals.outputTokens + usage.outputTokens,
404
469
  cacheReadTokens: totals.cacheReadTokens + (usage.cacheReadTokens ?? 0),
405
- lastInputTokens: usage.inputTokens + (usage.cacheReadTokens ?? 0)
470
+ lastInputTokens: promptTokens(usage)
406
471
  };
407
472
  }
408
473
  /**
@@ -2377,10 +2442,11 @@ function editorTheme(palette) {
2377
2442
  * changes per frame - a fade's level, the focus mark's lift - is drawn over
2378
2443
  * those kept lines. Fenced code is the expensive part of a reply, so a reply
2379
2444
  * also keeps the coloured fences of its last Markdown parse
2380
- * ({@link FenceMemo}): a stream delta re-parses the whole message but colours
2381
- * only the fence that changed. `invalidate()` drops all of it, which the
2382
- * application calls on every block when a grammar lands; a new terminal width
2383
- * needs no call, because it misses every key on its own.
2445
+ * ({@link FenceMemo}): a stream delta re-lexes only the open tail after the
2446
+ * last closed fence and colours only the fence that changed. `invalidate()`
2447
+ * drops all of it, which the application calls on every block when a grammar
2448
+ * lands; a new terminal width needs no call, because it misses every key on
2449
+ * its own.
2384
2450
  * @module @deepseek-ai/dsh-tui-app/blocks
2385
2451
  */
2386
2452
  /** Columns the focus gutter takes from the width a block's content wraps at. */
@@ -2470,9 +2536,9 @@ var LastDrawn = class {
2470
2536
  /**
2471
2537
  * The coloured fences of one reply, kept from one Markdown parse to the next.
2472
2538
  *
2473
- * pi-tui's `Markdown` re-parses the whole message whenever its text changes
2474
- * and asks the theme to colour every fence it finds, so a streaming reply
2475
- * that already carries three fences would colour all three on every delta.
2539
+ * pi-tui's `Markdown` re-parses whenever its text changes and asks the theme
2540
+ * to colour every fence it finds, so a streaming reply that already carries
2541
+ * three fences would colour all three on every delta of the open tail.
2476
2542
  * This keeps what the last parse asked for: a fence that is asked for again
2477
2543
  * is answered from memory, and a fence the last parse did not ask for is
2478
2544
  * dropped at the next {@link FenceMemo.settle}, so the memo never holds more
@@ -2709,6 +2775,59 @@ var ContextBlock = class {
2709
2775
  }
2710
2776
  };
2711
2777
  /**
2778
+ * Source through the last closed fenced block, including the newline that
2779
+ * follows the closer when the message still has one. An unclosed fence, or a
2780
+ * reply with no fence, yields an empty prefix so the whole message is lexed.
2781
+ * @param text - the live Markdown source.
2782
+ * @returns the closed prefix, or the empty string.
2783
+ */
2784
+ function closedFencePrefix(text) {
2785
+ let last = 0;
2786
+ let index = 0;
2787
+ let open;
2788
+ while (index <= text.length) {
2789
+ const newline = text.indexOf("\n", index);
2790
+ const end = newline === -1 ? text.length : newline;
2791
+ const line = text.slice(index, end);
2792
+ let indent = 0;
2793
+ while (indent < 3 && line[indent] === " ") indent += 1;
2794
+ const rest = line.slice(indent);
2795
+ const marker = /^(`{3,}|~{3,})/.exec(rest)?.[1];
2796
+ if (marker !== void 0) {
2797
+ const info = rest.slice(marker.length);
2798
+ if (open === void 0) {
2799
+ if (!(marker.startsWith("`") && info.includes("`"))) open = {
2800
+ char: marker[0],
2801
+ length: marker.length
2802
+ };
2803
+ } else if (marker[0] === open.char && marker.length >= open.length && info.trim() === "") {
2804
+ last = newline === -1 ? text.length : newline + 1;
2805
+ open = void 0;
2806
+ }
2807
+ }
2808
+ if (newline === -1) break;
2809
+ index = newline + 1;
2810
+ }
2811
+ return text.slice(0, last);
2812
+ }
2813
+ /**
2814
+ * Stack a closed-fence drawing and the open tail the way one Markdown parse
2815
+ * would: a fence adds a blank line before the next block unless that block
2816
+ * is a blank-line token (the tail then starts with a newline).
2817
+ * @param prefixLines - the cached prefix drawing.
2818
+ * @param tail - the unparsed tail source.
2819
+ * @param tailLines - the tail drawing.
2820
+ * @returns the combined Markdown lines.
2821
+ */
2822
+ function joinFencePrefix(prefixLines, tail, tailLines) {
2823
+ if (tail.startsWith("\n")) return [...prefixLines, ...tailLines];
2824
+ return [
2825
+ ...prefixLines,
2826
+ "",
2827
+ ...tailLines
2828
+ ];
2829
+ }
2830
+ /**
2712
2831
  * An assistant reply: streamed reasoning above streamed Markdown text. The
2713
2832
  * durable `assistant/message` replaces both with the committed content.
2714
2833
  *
@@ -2728,6 +2847,14 @@ var AssistantBlock = class {
2728
2847
  text = "";
2729
2848
  interrupted = false;
2730
2849
  markdown;
2850
+ /** Closed-fence prefix, parsed only when that prefix or the width changes. */
2851
+ prefixMarkdown;
2852
+ /** Last prefix drawing, reused while the closed fences and width hold. */
2853
+ prefixCache;
2854
+ /** Last text handed to {@link AssistantBlock.markdown}, so fade ticks do not re-lex. */
2855
+ appliedTail;
2856
+ /** Last text handed to {@link AssistantBlock.prefixMarkdown}. */
2857
+ appliedPrefix;
2731
2858
  reasoningText;
2732
2859
  fade;
2733
2860
  /** Width of the last render that drew a text tail; absent before the first one. */
@@ -2752,7 +2879,9 @@ var AssistantBlock = class {
2752
2879
  this.turn = turn;
2753
2880
  const palette = theme.palette;
2754
2881
  this.fences = theme.codeHighlight === void 0 ? void 0 : new FenceMemo(theme.codeHighlight);
2755
- this.markdown = new Markdown("", 0, 0, markdownTheme(palette, this.fences));
2882
+ const themeForMarkdown = markdownTheme(palette, this.fences);
2883
+ this.markdown = new Markdown("", 0, 0, themeForMarkdown);
2884
+ this.prefixMarkdown = new Markdown("", 0, 0, themeForMarkdown);
2756
2885
  this.reasoningText = new Text("", 0, 0);
2757
2886
  }
2758
2887
  /**
@@ -2817,7 +2946,6 @@ var AssistantBlock = class {
2817
2946
  appendText(delta) {
2818
2947
  this.text += delta;
2819
2948
  this.revision += 1;
2820
- this.markdown.setText(this.text);
2821
2949
  }
2822
2950
  /**
2823
2951
  * Append streamed reasoning text.
@@ -2841,11 +2969,17 @@ var AssistantBlock = class {
2841
2969
  this.revision += 1;
2842
2970
  this.fade = void 0;
2843
2971
  this.reasoningFade = void 0;
2844
- this.markdown.setText(text);
2972
+ this.prefixCache = void 0;
2973
+ this.appliedPrefix = void 0;
2974
+ this.appliedTail = void 0;
2845
2975
  this.reasoningText.setText(this.theme.palette.dim(this.theme.palette.italic(reasoning.trimEnd())));
2846
2976
  }
2847
2977
  invalidate() {
2848
2978
  this.markdown.invalidate();
2979
+ this.prefixMarkdown.invalidate();
2980
+ this.prefixCache = void 0;
2981
+ this.appliedPrefix = void 0;
2982
+ this.appliedTail = void 0;
2849
2983
  this.reasoningText.invalidate();
2850
2984
  this.fences?.clear();
2851
2985
  this.drawn.clear();
@@ -2921,25 +3055,70 @@ var AssistantBlock = class {
2921
3055
  */
2922
3056
  renderText(width, at) {
2923
3057
  const fade = this.fade;
2924
- const lines = this.markdown.render(width);
3058
+ const lines = this.renderMarkdown(width);
2925
3059
  this.fences?.settle();
2926
3060
  if (fade === void 0) return lines;
2927
3061
  if (this.fadeWidth !== void 0 && this.fadeWidth !== width) fade.flush();
2928
3062
  this.fadeWidth = width;
2929
3063
  return recolorTail(lines, fadingInSpans(fade), fade.style(), this.repaintFloor - at);
2930
3064
  }
3065
+ /**
3066
+ * Lex the open tail and reuse the closed-fence prefix at this width.
3067
+ * @param width - the width the Markdown lays out in.
3068
+ * @returns the Markdown lines, fade not yet applied.
3069
+ */
3070
+ renderMarkdown(width) {
3071
+ const prefix = closedFencePrefix(this.text);
3072
+ if (prefix.length === 0) {
3073
+ this.prefixCache = void 0;
3074
+ this.appliedPrefix = void 0;
3075
+ this.applyMarkdown(this.markdown, this.text, "tail");
3076
+ return this.markdown.render(width);
3077
+ }
3078
+ const tail = this.text.slice(prefix.length);
3079
+ let prefixLines = this.prefixCache;
3080
+ if (prefixLines === void 0 || prefixLines.text !== prefix || prefixLines.width !== width) {
3081
+ this.applyMarkdown(this.prefixMarkdown, prefix, "prefix");
3082
+ prefixLines = {
3083
+ text: prefix,
3084
+ width,
3085
+ lines: this.prefixMarkdown.render(width)
3086
+ };
3087
+ this.prefixCache = prefixLines;
3088
+ }
3089
+ if (tail.trim() === "") return prefixLines.lines;
3090
+ this.applyMarkdown(this.markdown, tail, "tail");
3091
+ return joinFencePrefix(prefixLines.lines, tail, this.markdown.render(width));
3092
+ }
3093
+ /**
3094
+ * Hand `text` to `markdown` only when it differs, so a fade tick does not re-lex.
3095
+ * @param markdown - the prefix or tail instance.
3096
+ * @param text - the source that instance should hold.
3097
+ * @param which - which applied-text slot to update.
3098
+ */
3099
+ applyMarkdown(markdown, text, which) {
3100
+ if (which === "prefix") {
3101
+ if (this.appliedPrefix === text) return;
3102
+ markdown.setText(text);
3103
+ this.appliedPrefix = text;
3104
+ return;
3105
+ }
3106
+ if (this.appliedTail === text) return;
3107
+ markdown.setText(text);
3108
+ this.appliedTail = text;
3109
+ }
2931
3110
  };
2932
3111
  /**
2933
3112
  * A tool call card: status glyph, tool name, headline, then a foldable body.
2934
3113
  *
2935
3114
  * The card arrives in two pieces, and each floats out on its own: the header
2936
- * and the call rows when the call is logged, the result rows when the tool
2937
- * answers. A card rebuilt from history carries neither fade.
3115
+ * and the call rows when the model starts the call (a stream delta, or the
3116
+ * logged `tool/call`), the result rows when the tool answers. While it runs
3117
+ * the body carries {@link TOOL_RUNNING_ROW} in place of a result. A card
3118
+ * rebuilt from history carries neither fade.
2938
3119
  */
2939
3120
  var ToolBlock = class {
2940
3121
  theme;
2941
- name;
2942
- call;
2943
3122
  turn;
2944
3123
  navigable = true;
2945
3124
  blockKind = "tool";
@@ -2959,13 +3138,19 @@ var ToolBlock = class {
2959
3138
  highlightLevel = 0;
2960
3139
  /** The coloured, folded, wrapped body, by width, fold, focus, status, and result. */
2961
3140
  drawn = new LastDrawn();
2962
- /** Counts every result the card was given. */
3141
+ /** Counts every call or result the card was given. */
2963
3142
  revision = 0;
3143
+ toolName;
3144
+ call;
2964
3145
  constructor(theme, name, call, turn) {
2965
3146
  this.theme = theme;
2966
- this.name = name;
2967
- this.call = call;
2968
3147
  this.turn = turn;
3148
+ this.toolName = name;
3149
+ this.call = call;
3150
+ }
3151
+ /** The tool the model called. */
3152
+ get name() {
3153
+ return this.toolName;
2969
3154
  }
2970
3155
  /** The card headline, as the section heading names this call. */
2971
3156
  get title() {
@@ -2997,6 +3182,17 @@ var ToolBlock = class {
2997
3182
  this.highlightLevel = level;
2998
3183
  }
2999
3184
  /**
3185
+ * Replace the call half as streamed arguments arrive or the logged call
3186
+ * confirms them.
3187
+ * @param name - the tool the model called.
3188
+ * @param call - the headline and rows for those arguments.
3189
+ */
3190
+ setCall(name, call) {
3191
+ this.toolName = name;
3192
+ this.call = call;
3193
+ this.revision += 1;
3194
+ }
3195
+ /**
3000
3196
  * Draw the header and the call rows through `fade` until it settles.
3001
3197
  * @param fade - the level and drawing settings of this card's own fade.
3002
3198
  */
@@ -3090,12 +3286,21 @@ var ToolBlock = class {
3090
3286
  */
3091
3287
  layout(outer, marked) {
3092
3288
  const palette = this.theme.palette;
3093
- const header = `${this.status === "running" ? palette.warning("●") : this.status === "done" ? palette.success("●") : palette.error("●")} ${palette.bold(this.name)}${this.call.title === "" ? "" : ` ${palette.dim(this.call.title)}`}`;
3094
- const body = [...this.call.lines, ...this.resultLines];
3095
- const code = this.call.code === void 0 && this.resultCode === void 0 ? void 0 : [...this.call.code ?? new Array(this.call.lines.length).fill(void 0), ...this.resultCode ?? new Array(this.resultLines.length).fill(void 0)];
3289
+ const header = `${this.status === "running" ? palette.warning("●") : this.status === "done" ? palette.success("●") : palette.error("●")} ${palette.bold(this.toolName)}${this.call.title === "" ? "" : ` ${palette.dim(this.call.title)}`}`;
3290
+ const loading = this.status === "running" ? ["…"] : [];
3291
+ const body = [
3292
+ ...this.call.lines,
3293
+ ...loading,
3294
+ ...this.resultLines
3295
+ ];
3296
+ const code = this.call.code === void 0 && this.resultCode === void 0 ? void 0 : [
3297
+ ...this.call.code ?? new Array(this.call.lines.length).fill(void 0),
3298
+ ...new Array(loading.length).fill(void 0),
3299
+ ...this.resultCode ?? new Array(this.resultLines.length).fill(void 0)
3300
+ ];
3096
3301
  const kept = this.expanded ? body : foldRows(body, this.theme.toolPreviewLines, (hidden) => foldMarker(hidden, marked ? "marked" : "transcript"));
3097
3302
  const shown = paintDiffRows(paintCodeRows(kept, code, this.theme.codeHighlight), kept, palette);
3098
- const callCount = Math.min(this.call.lines.length, shown.length);
3303
+ const callCount = Math.min(this.call.lines.length + loading.length, shown.length);
3099
3304
  const inner = Math.max(1, outer - 4);
3100
3305
  const rows = (lines) => lines.flatMap((line) => wrapTextWithAnsi(line, inner).map((part) => ` ${palette.dim("│")} ${part}`));
3101
3306
  const call = [...wrapTextWithAnsi(header, outer), ...rows(shown.slice(0, callCount))];
@@ -8466,6 +8671,10 @@ var TuiApp = class {
8466
8671
  theme;
8467
8672
  toolBlocks = /* @__PURE__ */ new Map();
8468
8673
  toolArguments = /* @__PURE__ */ new Map();
8674
+ /** Raw argument text accumulated from `tool-call-delta` chunks, keyed by call id. */
8675
+ toolStreamArgs = /* @__PURE__ */ new Map();
8676
+ /** Cards mounted from the live stream that no logged `tool/call` has confirmed yet. */
8677
+ unconfirmedTools = /* @__PURE__ */ new Map();
8469
8678
  submittedIds = /* @__PURE__ */ new Set();
8470
8679
  disposers = [];
8471
8680
  /** Turn facts of the bound session's todo lines, keyed by content. */
@@ -8565,6 +8774,14 @@ var TuiApp = class {
8565
8774
  /** Serializes `/attach` reads so pending attachments keep the typed order. */
8566
8775
  attaching = Promise.resolve();
8567
8776
  usage = EMPTY_USAGE;
8777
+ /** The in-flight model call's tokens, shown on the spinner and in the footer. */
8778
+ liveUsage;
8779
+ /** Streamed characters of the current call, used until a usage chunk arrives. */
8780
+ streamedChars = 0;
8781
+ /** Whether {@link TuiApp.liveUsage} came from a provider `usage` chunk. */
8782
+ usageExact = false;
8783
+ /** Spinner label without the live ↑↓ suffix (`thinking`, `calling read`, …). */
8784
+ loaderActivity = "thinking";
8568
8785
  lastCtrlC = 0;
8569
8786
  stopped = false;
8570
8787
  constructor(deps) {
@@ -8762,6 +8979,8 @@ var TuiApp = class {
8762
8979
  this.chat.clear();
8763
8980
  this.toolBlocks.clear();
8764
8981
  this.toolArguments.clear();
8982
+ this.toolStreamArgs.clear();
8983
+ this.unconfirmedTools.clear();
8765
8984
  this.submittedIds.clear();
8766
8985
  this.todoTurns.clear();
8767
8986
  this.turn = 0;
@@ -8771,6 +8990,7 @@ var TuiApp = class {
8771
8990
  this.endFade();
8772
8991
  this.blockFades.clear();
8773
8992
  this.usage = EMPTY_USAGE;
8993
+ this.clearLiveUsage();
8774
8994
  this.pending = [];
8775
8995
  this.queueView = [];
8776
8996
  this.queueSelection = void 0;
@@ -8875,9 +9095,12 @@ var TuiApp = class {
8875
9095
  this.statusSlot.addChild(this.loader);
8876
9096
  this.loader.start();
8877
9097
  }
9098
+ this.refreshLoader();
8878
9099
  } else if (this.statusSlot.children.length > 0) {
8879
9100
  this.loader.stop();
8880
9101
  this.statusSlot.removeChild(this.loader);
9102
+ this.loaderActivity = "thinking";
9103
+ this.clearLiveUsage();
8881
9104
  this.loader.setMessage("thinking");
8882
9105
  }
8883
9106
  this.tui.requestRender();
@@ -8904,7 +9127,7 @@ var TuiApp = class {
8904
9127
  queuedNextTurn: inbox.nextTurn.length,
8905
9128
  queuedNextStep: inbox.nextStep.length
8906
9129
  } },
8907
- usage: formatUsage(this.usage),
9130
+ usage: formatUsage(withLiveUsage(this.usage, this.liveUsage)),
8908
9131
  facts: this.statusFacts(),
8909
9132
  cwd: this.deps.cwd,
8910
9133
  home: this.home,
@@ -11213,22 +11436,33 @@ var TuiApp = class {
11213
11436
  case "start":
11214
11437
  this.streaming = void 0;
11215
11438
  this.endFade();
11439
+ this.beginLiveUsage();
11440
+ if (this.dropUnconfirmedTools()) this.tui.requestRender();
11216
11441
  return;
11217
11442
  case "chunk": {
11218
11443
  const chunk = frame.chunk;
11219
11444
  switch (chunk.type) {
11220
11445
  case "text-delta":
11221
- if (chunk.text !== "") this.appendStreamedText(chunk.text);
11446
+ if (chunk.text !== "") {
11447
+ this.appendStreamedText(chunk.text);
11448
+ this.noteStreamedChars(chunk.text.length);
11449
+ }
11222
11450
  break;
11223
11451
  case "reasoning-delta":
11224
- if (chunk.text !== "") this.appendStreamedReasoning(chunk.text);
11452
+ if (chunk.text !== "") {
11453
+ this.appendStreamedReasoning(chunk.text);
11454
+ this.noteStreamedChars(chunk.text.length);
11455
+ }
11225
11456
  break;
11226
11457
  case "tool-call-delta":
11227
- if (chunk.name !== void 0) this.loader.setMessage(`calling ${chunk.name}`);
11458
+ this.onToolCallDelta(chunk);
11459
+ this.noteStreamedChars(chunk.argumentsDelta.length);
11460
+ break;
11461
+ case "usage":
11462
+ this.applyLiveUsage(chunk.usage);
11228
11463
  break;
11229
11464
  case "block-start":
11230
11465
  case "block-end":
11231
- case "usage":
11232
11466
  case "finish": break;
11233
11467
  /* v8 ignore next -- closed-union exhaustiveness guard */
11234
11468
  default: assertNever(chunk, "tui stream chunk");
@@ -11239,6 +11473,7 @@ var TuiApp = class {
11239
11473
  case "end":
11240
11474
  this.streaming = void 0;
11241
11475
  this.endFade();
11476
+ if (frame.outcome.kind === "abandoned" || frame.outcome.kind === "committed" && frame.outcome.eventType === "assistant/attempt") this.dropUnconfirmedTools();
11242
11477
  this.tui.requestRender();
11243
11478
  return;
11244
11479
  /* v8 ignore next -- closed-union exhaustiveness guard */
@@ -11273,23 +11508,15 @@ var TuiApp = class {
11273
11508
  this.streamingBlock().commit(text, reasoning, interrupted === true);
11274
11509
  this.streaming = void 0;
11275
11510
  this.endFade();
11276
- if (usage !== void 0) {
11277
- this.usage = addUsage(this.usage, usage);
11278
- this.refreshFooter();
11279
- }
11511
+ this.clearLiveUsage();
11512
+ if (usage !== void 0) this.usage = addUsage(this.usage, usage);
11513
+ this.refreshFooter();
11280
11514
  break;
11281
11515
  }
11282
11516
  case "tool/call": {
11283
11517
  const { callId, name, arguments: argumentsJson } = event.data;
11284
- const args = parseArguments(argumentsJson);
11285
- this.toolArguments.set(callId, args);
11286
- const block = new ToolBlock(this.theme, name, toolCallText(argumentsJson, this.presentCall(name, args)), this.turn);
11287
- block.setExpanded(this.toolsExpanded);
11288
- this.toolBlocks.set(callId, block);
11289
- this.chat.addChild(block);
11290
- this.fadeBlock((fade) => {
11291
- block.setFade(fade);
11292
- });
11518
+ this.toolStreamArgs.delete(callId);
11519
+ this.upsertToolCard(callId, name, argumentsJson, "log");
11293
11520
  break;
11294
11521
  }
11295
11522
  case "tool/result": {
@@ -11302,13 +11529,14 @@ var TuiApp = class {
11302
11529
  this.fadeBlock((fade) => {
11303
11530
  block.setResultFade(fade);
11304
11531
  });
11305
- this.loader.setMessage("thinking");
11532
+ this.setLoaderActivity("thinking");
11306
11533
  break;
11307
11534
  }
11308
11535
  case "turn/end": {
11309
11536
  this.turnStartedAt = void 0;
11310
11537
  this.updateTicker();
11311
11538
  this.endFade();
11539
+ this.clearLiveUsage();
11312
11540
  this.refreshFooter();
11313
11541
  const notice = turnEndNotice(event.data.reason);
11314
11542
  if (notice !== void 0) this.notice(notice, event.data.reason.kind === "error" ? "error" : "dim");
@@ -11330,11 +11558,12 @@ var TuiApp = class {
11330
11558
  break;
11331
11559
  }
11332
11560
  case "llm/retry":
11333
- this.loader.setMessage(retryMessage(event.data));
11561
+ this.setLoaderActivity(retryMessage(event.data));
11334
11562
  break;
11335
11563
  default: return;
11336
11564
  }
11337
11565
  this.tui.requestRender();
11566
+ if (event.type === "tool/call" && !this.replaying) this.tui.renderNow();
11338
11567
  }
11339
11568
  /**
11340
11569
  * Fold one whole-list todo write into the turn facts: a content this
@@ -11395,6 +11624,140 @@ var TuiApp = class {
11395
11624
  block.setExpanded(this.toolsExpanded);
11396
11625
  this.chat.addChild(block);
11397
11626
  }
11627
+ /**
11628
+ * Replace the spinner's activity word and redraw its live ↑↓ suffix.
11629
+ * @param activity - `thinking`, `calling <name>`, or a retry notice.
11630
+ */
11631
+ setLoaderActivity(activity) {
11632
+ this.loaderActivity = activity;
11633
+ this.refreshLoader();
11634
+ }
11635
+ /**
11636
+ * Start a new model call's live counters: seed send from the projected
11637
+ * next-request size or the last committed prompt, and zero receive.
11638
+ */
11639
+ beginLiveUsage() {
11640
+ this.streamedChars = 0;
11641
+ this.usageExact = false;
11642
+ this.liveUsage = {
11643
+ inputTokens: this.seedLiveSend(),
11644
+ outputTokens: 0
11645
+ };
11646
+ this.loaderActivity = "thinking";
11647
+ this.refreshLiveUsage();
11648
+ }
11649
+ /**
11650
+ * Prompt tokens the current call is likely sending, before a usage chunk.
11651
+ * @returns context occupancy when the projection has one, else the last
11652
+ * committed prompt size, else 0.
11653
+ */
11654
+ seedLiveSend() {
11655
+ const used = this.statusFacts().context?.used;
11656
+ if (used !== void 0 && used > 0) return used;
11657
+ return this.usage.lastInputTokens;
11658
+ }
11659
+ /**
11660
+ * Grow the receive estimate from streamed characters until the provider
11661
+ * reports usage.
11662
+ * @param chars - characters just appended to the live stream.
11663
+ */
11664
+ noteStreamedChars(chars) {
11665
+ if (chars <= 0 || this.usageExact) return;
11666
+ this.streamedChars += chars;
11667
+ const send = this.liveUsage === void 0 ? this.seedLiveSend() : this.liveUsage.inputTokens;
11668
+ this.liveUsage = {
11669
+ inputTokens: send,
11670
+ outputTokens: estimateTokens(this.streamedChars)
11671
+ };
11672
+ this.refreshLiveUsage();
11673
+ }
11674
+ /**
11675
+ * Replace the live counters with a provider usage chunk.
11676
+ * @param usage - the call's reported usage.
11677
+ */
11678
+ applyLiveUsage(usage) {
11679
+ this.usageExact = true;
11680
+ this.liveUsage = usage;
11681
+ this.refreshLiveUsage();
11682
+ }
11683
+ /** Forget the in-flight call's counters and drop them from the spinner and footer. */
11684
+ clearLiveUsage() {
11685
+ this.liveUsage = void 0;
11686
+ this.streamedChars = 0;
11687
+ this.usageExact = false;
11688
+ this.refreshLiveUsage();
11689
+ }
11690
+ /** Redraw the spinner and the footer from the current live counters. */
11691
+ refreshLiveUsage() {
11692
+ this.refreshLoader();
11693
+ this.refreshFooter();
11694
+ }
11695
+ /** Draw the spinner label plus the current call's ↑send ↓receive suffix. */
11696
+ refreshLoader() {
11697
+ const suffix = formatLiveUsage(this.liveUsage);
11698
+ this.loader.setMessage(suffix === "" ? this.loaderActivity : `${this.loaderActivity} ${suffix}`);
11699
+ }
11700
+ /**
11701
+ * Mount or refresh a tool card from a stream delta: the name as soon as
11702
+ * the model sends one, then the presenter headline once the arguments
11703
+ * parse as JSON.
11704
+ * @param chunk - one `tool-call-delta` of the live assistant stream.
11705
+ */
11706
+ onToolCallDelta(chunk) {
11707
+ if (chunk.name !== void 0 && chunk.name !== "") this.setLoaderActivity(`calling ${chunk.name}`);
11708
+ if (chunk.id === "") return;
11709
+ const argumentsJson = (this.toolStreamArgs.get(chunk.id) ?? "") + chunk.argumentsDelta;
11710
+ this.toolStreamArgs.set(chunk.id, argumentsJson);
11711
+ const name = chunk.name === "" ? void 0 : chunk.name ?? this.toolBlocks.get(chunk.id)?.name;
11712
+ if (name === void 0) return;
11713
+ this.upsertToolCard(chunk.id, name, argumentsJson, "stream");
11714
+ }
11715
+ /**
11716
+ * Draw one tool card, creating it on the first sighting and updating the
11717
+ * call half when later arguments arrive. A streamed card stays unconfirmed
11718
+ * until the matching `tool/call` is logged.
11719
+ * @param callId - the model's call id.
11720
+ * @param name - the tool name.
11721
+ * @param argumentsJson - arguments accumulated so far, or the logged string.
11722
+ * @param source - `stream` for a live delta, `log` for the durable call.
11723
+ */
11724
+ upsertToolCard(callId, name, argumentsJson, source) {
11725
+ const args = parseArguments(argumentsJson);
11726
+ if (args !== void 0) this.toolArguments.set(callId, args);
11727
+ const call = source === "stream" && args === void 0 ? {
11728
+ title: "",
11729
+ lines: []
11730
+ } : toolCallText(argumentsJson, args === void 0 ? void 0 : this.presentCall(name, args));
11731
+ const existing = this.toolBlocks.get(callId);
11732
+ if (existing !== void 0) {
11733
+ existing.setCall(name, call);
11734
+ if (source === "log") this.unconfirmedTools.delete(callId);
11735
+ return;
11736
+ }
11737
+ const block = new ToolBlock(this.theme, name, call, this.turn);
11738
+ block.setExpanded(this.toolsExpanded);
11739
+ this.toolBlocks.set(callId, block);
11740
+ this.chat.addChild(block);
11741
+ this.fadeBlock((fade) => {
11742
+ block.setFade(fade);
11743
+ });
11744
+ if (source === "stream") this.unconfirmedTools.set(callId, block);
11745
+ }
11746
+ /**
11747
+ * Take down every card the live stream mounted that no `tool/call` confirmed.
11748
+ * @returns true when at least one card left the transcript.
11749
+ */
11750
+ dropUnconfirmedTools() {
11751
+ if (this.unconfirmedTools.size === 0) return false;
11752
+ for (const [callId, block] of this.unconfirmedTools) {
11753
+ this.chat.removeChild(block);
11754
+ this.toolBlocks.delete(callId);
11755
+ this.toolArguments.delete(callId);
11756
+ this.toolStreamArgs.delete(callId);
11757
+ }
11758
+ this.unconfirmedTools.clear();
11759
+ return true;
11760
+ }
11398
11761
  presentCall(name, args) {
11399
11762
  const definition = this.deps.ctx.get("tools")?.get(name, this.agent);
11400
11763
  if (definition?.presentCall === void 0) return void 0;
@@ -11523,28 +11886,29 @@ const internals = {
11523
11886
  canOpenUrl: () => canOpenNativePath(),
11524
11887
  openUrl: openNativeUrl
11525
11888
  };
11526
- /** Events read per page when a persisted session is resumed, through the storage handle before the Agent takes the log over. */
11527
- const HISTORY_PAGE = 256;
11528
- /**
11529
- * Read a persisted session's complete event log in pages, so the terminal
11530
- * can draw the earlier conversation before resuming it.
11531
- * @param ctx - plugin context carrying the persistence service.
11532
- * @param id - the session to read.
11533
- * @returns the persisted events in log order.
11534
- */
11535
- async function readHistory(ctx, id) {
11536
- const persistence = ctx.get("sessionPersistence");
11537
- if (persistence === void 0) throw new Error("tui-app: resuming a session needs a composed session persistence provider");
11538
- const handle = await persistence.open(id, "read");
11889
+ /**
11890
+ * Events the terminal binds after the Agent has taken the write handle.
11891
+ * The live Session already includes interrupted-turn closers resume appended.
11892
+ * @param ctx - plugin context carrying the session query engine.
11893
+ * @param id - the session the Agent just resumed.
11894
+ * @returns the persisted events in log order, closers included.
11895
+ * @throws when no query engine is composed.
11896
+ */
11897
+ async function observeBoundHistory(ctx, id) {
11898
+ const env_1 = {
11899
+ stack: [],
11900
+ error: void 0,
11901
+ hasError: false
11902
+ };
11539
11903
  try {
11540
- const events = [];
11541
- for (;;) {
11542
- const page = await handle.read(events.length, HISTORY_PAGE);
11543
- events.push(...page.events);
11544
- if (page.events.length < HISTORY_PAGE) return events;
11545
- }
11904
+ const query = ctx.get("sessionQuery");
11905
+ if (query === void 0) throw new Error("tui-app: resuming a session needs a composed session query engine");
11906
+ return __addDisposableResource(env_1, await query.observeSession(id, { projectionMode: "none" }), false).events;
11907
+ } catch (e_1) {
11908
+ env_1.error = e_1;
11909
+ env_1.hasError = true;
11546
11910
  } finally {
11547
- await handle[Symbol.asyncDispose]();
11911
+ __disposeResources(env_1);
11548
11912
  }
11549
11913
  }
11550
11914
  /**
@@ -11573,7 +11937,7 @@ function coreServices(ctx) {
11573
11937
  * @throws when no query engine is composed or the session has no such completed turn.
11574
11938
  */
11575
11939
  async function forkSeed(ctx, id, turn) {
11576
- const env_1 = {
11940
+ const env_2 = {
11577
11941
  stack: [],
11578
11942
  error: void 0,
11579
11943
  hasError: false
@@ -11581,17 +11945,17 @@ async function forkSeed(ctx, id, turn) {
11581
11945
  try {
11582
11946
  const query = ctx.get("sessionQuery");
11583
11947
  if (query === void 0) throw new Error("forking a session needs a composed session query engine");
11584
- const source = __addDisposableResource(env_1, await query.observeSession(id), false);
11948
+ const source = __addDisposableResource(env_2, await query.observeSession(id), false);
11585
11949
  const boundary = source.events.findLast((event) => event.type === "turn/end" && (turn === void 0 || event.data.turn === turn));
11586
11950
  if (boundary === void 0) throw new Error(turn === void 0 ? `session ${id} has no completed turn to fork from` : `session ${id} has no completed turn ${String(turn)} to fork from`);
11587
11951
  let cut = boundary.seq + 1;
11588
11952
  while (cut < source.events.length && source.events[cut]?.type !== "turn/start") cut += 1;
11589
11953
  return source.events.slice(0, cut);
11590
- } catch (e_1) {
11591
- env_1.error = e_1;
11592
- env_1.hasError = true;
11954
+ } catch (e_2) {
11955
+ env_2.error = e_2;
11956
+ env_2.hasError = true;
11593
11957
  } finally {
11594
- __disposeResources(env_1);
11958
+ __disposeResources(env_2);
11595
11959
  }
11596
11960
  }
11597
11961
  /**
@@ -11645,10 +12009,25 @@ function sessionHost(ctx, core, cwd) {
11645
12009
  }, seed ?? []);
11646
12010
  return {
11647
12011
  create: () => create(void 0, void 0),
11648
- resume: async (id) => bind((_selection, setup) => agents.resume({
11649
- resumeSessionId: id,
11650
- setup
11651
- }), await readHistory(ctx, id)),
12012
+ resume: async (id) => {
12013
+ const selection = {
12014
+ current: void 0,
12015
+ assembled: void 0
12016
+ };
12017
+ const handle = await agents.resume({
12018
+ resumeSessionId: id,
12019
+ setup: (agentCtx) => {
12020
+ installModelSelection(agentCtx, selection);
12021
+ }
12022
+ });
12023
+ await handle.agent.whenIdle();
12024
+ return {
12025
+ agent: handle.agent,
12026
+ selection,
12027
+ history: await observeBoundHistory(ctx, id),
12028
+ dispose: () => handle.dispose()
12029
+ };
12030
+ },
11652
12031
  fork: async (id, turn) => create(await forkSeed(ctx, id, turn), id)
11653
12032
  };
11654
12033
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@songtonyli/dsh-cli",
3
- "version": "0.1.28",
3
+ "version": "0.1.30",
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",