modkh 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +42 -0
  2. package/dist/agent/bundled-skills.d.ts +1 -1
  3. package/dist/agent/bundled-skills.js +1 -1
  4. package/dist/agent/compaction.d.ts +53 -0
  5. package/dist/agent/compaction.js +191 -0
  6. package/dist/agent/loop.d.ts +55 -8
  7. package/dist/agent/loop.js +119 -7
  8. package/dist/agent/skills.d.ts +7 -1
  9. package/dist/agent/skills.js +26 -5
  10. package/dist/agent/types.d.ts +14 -9
  11. package/dist/cli/agenticreplay.d.ts +1 -0
  12. package/dist/cli/agenticreplay.js +66 -0
  13. package/dist/cli/answer-markdown.d.ts +3 -0
  14. package/dist/cli/answer-markdown.js +29 -0
  15. package/dist/cli/approval.d.ts +2 -0
  16. package/dist/cli/approval.js +35 -5
  17. package/dist/cli/catalog.d.ts +30 -32
  18. package/dist/cli/catalog.js +37 -67
  19. package/dist/cli/chat.js +406 -78
  20. package/dist/cli/clipboard.d.ts +2 -0
  21. package/dist/cli/clipboard.js +28 -0
  22. package/dist/cli/color.d.ts +20 -3
  23. package/dist/cli/color.js +87 -19
  24. package/dist/cli/compaction-settings.d.ts +21 -0
  25. package/dist/cli/compaction-settings.js +54 -0
  26. package/dist/cli/completion-art.d.ts +2 -0
  27. package/dist/cli/completion-art.js +62 -0
  28. package/dist/cli/config.d.ts +9 -0
  29. package/dist/cli/config.js +5 -1
  30. package/dist/cli/editor.d.ts +7 -0
  31. package/dist/cli/editor.js +43 -5
  32. package/dist/cli/file-mentions.d.ts +14 -0
  33. package/dist/cli/file-mentions.js +141 -0
  34. package/dist/cli/head-checks.d.ts +41 -0
  35. package/dist/cli/head-checks.js +146 -0
  36. package/dist/cli/initial-connection.d.ts +7 -0
  37. package/dist/cli/initial-connection.js +20 -0
  38. package/dist/cli/keys.d.ts +12 -1
  39. package/dist/cli/keys.js +29 -4
  40. package/dist/cli/model-catalog.d.ts +16 -0
  41. package/dist/cli/model-catalog.js +130 -0
  42. package/dist/cli/models.d.ts +2 -2
  43. package/dist/cli/models.js +51 -19
  44. package/dist/cli/official-models.d.ts +6 -0
  45. package/dist/cli/official-models.js +77 -0
  46. package/dist/cli/pdf.d.ts +8 -0
  47. package/dist/cli/pdf.js +71 -0
  48. package/dist/cli/providers.d.ts +6 -42
  49. package/dist/cli/providers.js +44 -38
  50. package/dist/cli/shell-display.d.ts +6 -0
  51. package/dist/cli/shell-display.js +35 -0
  52. package/dist/cli/stateright.d.ts +1 -0
  53. package/dist/cli/stateright.js +37 -0
  54. package/dist/cli/terminal-mouse.d.ts +21 -0
  55. package/dist/cli/terminal-mouse.js +51 -0
  56. package/dist/cli/terminal.d.ts +95 -7
  57. package/dist/cli/terminal.js +783 -108
  58. package/dist/cli/tool-display.d.ts +9 -0
  59. package/dist/cli/tool-display.js +87 -0
  60. package/dist/cli/transcript-selection.d.ts +22 -0
  61. package/dist/cli/transcript-selection.js +75 -0
  62. package/dist/cli/usage.d.ts +9 -16
  63. package/dist/cli/usage.js +60 -18
  64. package/dist/cli/waiting-nyan.d.ts +3 -0
  65. package/dist/cli/waiting-nyan.js +17 -0
  66. package/dist/cli/waiting-whales.d.ts +3 -0
  67. package/dist/cli/waiting-whales.js +24 -0
  68. package/dist/index.js +30 -8
  69. package/dist/language/commonlisp-install.d.ts +1 -0
  70. package/dist/language/commonlisp-install.js +3 -2
  71. package/dist/language/lsp/client.js +4 -1
  72. package/dist/language/lsp/pool.d.ts +8 -0
  73. package/dist/language/lsp/pool.js +21 -3
  74. package/dist/language/lsp/service.d.ts +8 -4
  75. package/dist/language/lsp/service.js +51 -15
  76. package/dist/language/syntax/parser.d.ts +10 -1
  77. package/dist/language/syntax/parser.js +34 -16
  78. package/dist/lisp/builtin-agents.d.ts +5 -0
  79. package/dist/lisp/builtin-agents.js +52 -0
  80. package/dist/lisp/config.d.ts +9 -0
  81. package/dist/lisp/config.js +50 -7
  82. package/dist/lisp/routing.js +2 -2
  83. package/dist/lisp/runtime.d.ts +5 -0
  84. package/dist/lisp/runtime.js +26 -2
  85. package/dist/model/ai-sdk.js +13 -8
  86. package/dist/model/chatgpt/login.js +1 -1
  87. package/dist/model/chatgpt/responses.js +56 -4
  88. package/dist/model/connection.js +2 -0
  89. package/dist/model/context-window.d.ts +3 -0
  90. package/dist/model/context-window.js +64 -0
  91. package/dist/model/context.d.ts +3 -1
  92. package/dist/model/context.js +24 -24
  93. package/dist/model/factory.d.ts +3 -1
  94. package/dist/model/factory.js +28 -27
  95. package/dist/model/harness-profile.d.ts +6 -0
  96. package/dist/model/harness-profile.js +23 -0
  97. package/dist/model/providers.d.ts +32 -0
  98. package/dist/model/providers.js +72 -0
  99. package/dist/model/reasoning.d.ts +3 -3
  100. package/dist/model/reasoning.js +30 -8
  101. package/dist/model/record-fetch.d.ts +2 -0
  102. package/dist/model/record-fetch.js +19 -0
  103. package/dist/plugins/manager.d.ts +2 -1
  104. package/dist/plugins/manager.js +21 -2
  105. package/dist/session/store.d.ts +11 -0
  106. package/dist/session/store.js +27 -1
  107. package/dist/subagents/head-assignment.d.ts +11 -0
  108. package/dist/subagents/head-assignment.js +47 -0
  109. package/dist/subagents/limits.d.ts +4 -0
  110. package/dist/subagents/limits.js +6 -0
  111. package/dist/subagents/request.js +18 -1
  112. package/dist/subagents/service.d.ts +36 -2
  113. package/dist/subagents/service.js +331 -38
  114. package/dist/subagents/types.d.ts +20 -0
  115. package/dist/subagents/verification.d.ts +5 -2
  116. package/dist/subagents/verification.js +59 -22
  117. package/dist/tools/browse.d.ts +13 -0
  118. package/dist/tools/browse.js +117 -0
  119. package/dist/tools/browser-capability.d.ts +3 -0
  120. package/dist/tools/browser-capability.js +29 -0
  121. package/dist/tools/formal-input.d.ts +6 -0
  122. package/dist/tools/formal-input.js +29 -0
  123. package/dist/tools/formal.d.ts +3 -2
  124. package/dist/tools/formal.js +54 -52
  125. package/dist/tools/jobs.d.ts +2 -0
  126. package/dist/tools/jobs.js +5 -0
  127. package/dist/tools/language.js +25 -27
  128. package/dist/tools/lean-proof.d.ts +38 -0
  129. package/dist/tools/lean-proof.js +83 -0
  130. package/dist/tools/registry.d.ts +5 -3
  131. package/dist/tools/registry.js +13 -5
  132. package/dist/tools/run.js +13 -9
  133. package/dist/tools/shell-process.js +17 -6
  134. package/dist/tools/stateright-runtime.d.ts +3 -0
  135. package/dist/tools/stateright-runtime.js +16 -0
  136. package/dist/tools/stateright.d.ts +3 -0
  137. package/dist/tools/stateright.js +78 -0
  138. package/dist/tools/web.js +7 -2
  139. package/dist/version.d.ts +2 -0
  140. package/dist/version.js +2 -0
  141. package/docs/commonlisp-build-output.md +14 -0
  142. package/docs/context-efficiency.md +25 -3
  143. package/docs/input.md +63 -3
  144. package/docs/languages.md +3 -3
  145. package/docs/models.md +30 -6
  146. package/docs/modkh.md +11 -7
  147. package/docs/presets.md +45 -0
  148. package/docs/setup.md +3 -16
  149. package/docs/stateright.md +45 -0
  150. package/docs/subagents.md +21 -3
  151. package/docs/web.md +1 -1
  152. package/experiments/presets/formal.lisp +15 -4
  153. package/experiments/presets/language-microagents.lisp +29 -0
  154. package/native/stateright/Cargo.lock +478 -0
  155. package/native/stateright/Cargo.toml +11 -0
  156. package/native/stateright/src/lib.rs +163 -0
  157. package/native/stateright/src/main.rs +38 -0
  158. package/package.json +10 -2
@@ -1,21 +1,39 @@
1
1
  import { emitKeypressEvents } from 'node:readline';
2
- import { usageFooter, usageBadgeLine } from "./usage.js";
3
- import { chars, clean, fitText, textWidth, wrap, editorLayout, verticalCursor, lineEdge } from "./editor.js";
2
+ import { activeFileMention, fileCandidates, formatFileMention } from "./file-mentions.js";
3
+ import { isPdfPathPrefix } from "./pdf.js";
4
+ import path from 'node:path';
5
+ import { PassThrough } from 'node:stream';
6
+ import { TerminalMouseInput } from "./terminal-mouse.js";
7
+ import { reflowTranscript, selectedTranscript, transcriptLine, transcriptLines } from "./transcript-selection.js";
8
+ import { EMPTY_USAGE, USAGE_HEADING, usageFooter, usageBadgeLine, usageBreakdownLines } from "./usage.js";
9
+ import { chars, clean, fitText, textWidth, wrap, wrapText, editorLayout, verticalCursor, lineEdge } from "./editor.js";
4
10
  export { textWidth, fitText } from "./editor.js";
5
- import { readClipboardImage } from "./clipboard.js";
11
+ import { readClipboardImage, writeClipboardText } from "./clipboard.js";
6
12
  import { MAX_IMAGES, parseImage } from "../agent/images.js";
7
13
  import { LineSource } from "./lines.js";
8
- import { TranscriptColorizer, classifyBackground, parseOscBackground, paletteFor, } from "./color.js";
14
+ import { WHALE_FRAME_MS, whaleRow } from "./waiting-whales.js";
15
+ import { TranscriptColorizer, classifyBackground, parseOscBackground, paletteFor, READABLE_TEXT_STYLE, } from "./color.js";
16
+ const APPROVAL_CHOICES = [{ value: 'n', label: '拒否' }, { value: 'y', label: '承認' }];
9
17
  export const COMMANDS = [
10
18
  { value: '/connect', label: '/connect', detail: 'プロバイダーに接続' },
11
19
  { value: '/models', label: '/models', detail: 'モデルを選択' },
12
- { value: '/reasoning', label: '/reasoning', detail: '推論レベル (off/minimal/low/medium/high)' },
13
- { value: '/agents', label: '/agents', detail: '子エージェントの一覧・委譲' },
20
+ { value: '/reasoning', label: '/reasoning', detail: '推論レベル (off/minimal/low/medium/high/max)' },
21
+ { value: '/annimation', label: '/annimation', detail: '待機アニメーション (on/off)' },
22
+ { value: '/agents', label: '/agents', detail: '子の一覧・委譲・同時実行数' },
23
+ { value: '/usage', label: '/usage', detail: 'トークン使用量の内訳' },
24
+ { value: '/pdf', label: '/pdf', detail: 'PDFの本文と画像を送る · /pdf パス | 依頼文' },
25
+ { value: '/tools', label: '/tools', detail: 'ツール履歴 · /tools <番号> で全文' },
14
26
  { value: '/allow', label: '/allow', detail: '承認ポリシー (all / workspace / none)' },
15
27
  { value: '/keys', label: '/keys', detail: '保存済みAPIキー' },
16
28
  { value: '/help', label: '/help', detail: '操作ガイド' },
17
29
  { value: '/exit', label: '/exit', detail: '終了' },
18
30
  ];
31
+ function isChatCommand(text) {
32
+ if (text.includes('\n'))
33
+ return false;
34
+ const command = text.trim().split(/\s+/, 1)[0];
35
+ return command === '/quit' || command === '/head' || COMMANDS.some(choice => choice.value === command);
36
+ }
19
37
  const LOGO = [
20
38
  '███╗ ███╗ ██████╗ ██╗ ██╗ ██╗ ██╗',
21
39
  '████╗ ████║ ██╔══██╗ ██║ ██╔╝ ██║ ██║',
@@ -26,6 +44,8 @@ const LOGO = [
26
44
  ];
27
45
  const logoForWidth = (width) => width >= Math.max(...LOGO.map(textWidth)) ? LOGO : ['MoDKH'];
28
46
  const ACCENT = '34'; // Use the terminal theme's blue; NO_COLOR is respected by paint().
47
+ /** The composer sits on a painted panel, so the theme blue can sink into it (dark) or glare (light). */
48
+ const PANEL_ACCENT = { dark: '38;5;117', light: '38;5;25' };
29
49
  /** Every term must appear in any order, so "seek deep" finds deepseek. Pinned rows always survive. */
30
50
  function matching(choices, query) {
31
51
  const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
@@ -37,6 +57,10 @@ class PlainTerminal {
37
57
  lines = new LineSource();
38
58
  reasoning = '';
39
59
  write(text) { process.stdout.write(text); }
60
+ showPage(title, text) {
61
+ this.write(`${title}\n\n${text}\n`);
62
+ return Promise.resolve();
63
+ }
40
64
  next(signal) { return this.lines.next(signal); }
41
65
  unread(line) { this.lines.unread(line); }
42
66
  setModel(_model) { }
@@ -57,8 +81,27 @@ class PlainTerminal {
57
81
  if (line)
58
82
  this.write(`\n(使用量: ${line})\n`);
59
83
  }
84
+ /** Line mode has no pane, so only a start is announced; the same id is never repeated. */
85
+ announcedServers = new Set();
86
+ setServers(servers) {
87
+ for (const server of servers) {
88
+ if (this.announcedServers.has(server.id))
89
+ continue;
90
+ this.announcedServers.add(server.id);
91
+ this.write(`\n(言語サーバー: ${server.id} 起動)\n`);
92
+ }
93
+ }
94
+ browseAnnounced = false;
95
+ /** Line mode has no pane; announce each transition so piped runs stay observable. */
96
+ setBrowse(active) {
97
+ if (this.browseAnnounced === active)
98
+ return;
99
+ this.browseAnnounced = active;
100
+ this.write(active ? `\n(${BROWSE_ACTIVE_LABEL})\n` : '\n(browse 終了)\n');
101
+ }
60
102
  close() { this.lines.close(); }
61
103
  ask(title, signal) { this.write(`${title}\n`); return this.next(signal); }
104
+ confirm(title, signal) { return this.ask(title + ' [y/N]', signal); }
62
105
  async choose(title, choices, query = '') {
63
106
  for (;;) {
64
107
  const matches = matching(choices, query);
@@ -87,11 +130,36 @@ class PlainTerminal {
87
130
  }
88
131
  }
89
132
  const MAX_INPUT_BYTES = 128 * 1024;
133
+ const SIDEBAR_WIDTH = 36;
134
+ function serverRow(server, workspace) {
135
+ const relative = path.relative(workspace, server.root);
136
+ const outside = path.isAbsolute(relative) || relative === '..' || relative.startsWith(`..${path.sep}`);
137
+ const root = clean(outside ? server.root : relative || path.basename(server.root) || server.root).replace(/[\r\n\t]/g, ' ');
138
+ const label = `${server.id} · `;
139
+ const room = SIDEBAR_WIDTH - 4 - textWidth(label);
140
+ if (textWidth(root) <= room)
141
+ return label + root;
142
+ // Keep the distinguishing end of long roots visible within the sidebar.
143
+ let suffix = '';
144
+ for (const char of chars(root).reverse()) {
145
+ if (textWidth(char + suffix) >= room)
146
+ break;
147
+ suffix = char + suffix;
148
+ }
149
+ return `${label}…${suffix}`;
150
+ }
151
+ /** At most this many language servers are listed; the rest are counted, never silently dropped. */
152
+ const SIDEBAR_SERVER_ROWS = 3;
153
+ const SERVERS_HEADING = '言語サーバー';
154
+ /** 右欄に出す browse 実行中の表示。行全体がこの文字列になる。 */
155
+ const BROWSE_ACTIVE_LABEL = 'browse in use';
156
+ const SUBAGENTS_HEADING = 'サブエージェント';
157
+ const TRANSCRIPT_HISTORY_ROWS = 4000;
90
158
  /**
91
159
  * メインスクリーンに流し込むストリーミングUI。
92
160
  * - 完成したトランスクリプト行は一度だけ出力し、その後は端末のスクロールバックへ流れる
93
161
  * - 起動時はロゴと入力欄を中央にまとめ、会話開始後は入力欄を最下部に描画する
94
- * 代替スクリーン(?1049)は使わない。これが「起動前バッファしか辿れない」問題の原因だった。
162
+ * 通常はメインスクリーンを使う。マウス操作で履歴を開く間だけ別画面に切り替える。
95
163
  */
96
164
  export class TerminalUI {
97
165
  interactive = true;
@@ -100,11 +168,26 @@ export class TerminalUI {
100
168
  selection = 0;
101
169
  pending;
102
170
  queued = [];
103
- /** スクロールバックへ確定待ちの完成行(折り返し済み)。 */
171
+ /** 描画を待っている、折り返し前の論理行。 */
104
172
  queue = [];
173
+ transcriptRows = new Map();
174
+ liveTranscriptRows = new Map();
175
+ drag;
176
+ selectionRows = [];
177
+ mouseInput;
178
+ keyInput;
179
+ copyText;
180
+ copyQueue = Promise.resolve();
181
+ historyRows = [];
182
+ history;
183
+ page;
105
184
  /** まだ改行が来ていない最終行。ライブブロックの一部として再描画する。 */
106
185
  partial = '';
186
+ partialKind = 'system';
107
187
  started = false;
188
+ usageVisible = false;
189
+ delegationCount = 0;
190
+ sidebarPainted = false;
108
191
  /** 会話開始前の案内行(ウェルカムブロックに表示し、会話開始時に本文へ流す)。 */
109
192
  bootLines = [];
110
193
  bootFlushed = false;
@@ -116,11 +199,21 @@ export class TerminalUI {
116
199
  clearPending = false;
117
200
  model = null;
118
201
  activity = null;
202
+ followup;
203
+ subagent = null;
204
+ subagentStarted = 0;
205
+ activityStarted = 0;
206
+ progressTimer;
119
207
  usage = null;
208
+ /** Running language servers, refreshed by the owner; null means nothing is running. */
209
+ servers = [];
210
+ /** True while a browse call is driving the browser. Display only. */
211
+ browse = false;
120
212
  closed = false;
121
213
  paste = false;
122
214
  pasteBuffer = '';
123
215
  pasteBytes = 0;
216
+ previousInput = '';
124
217
  editorScroll = 0;
125
218
  images = [];
126
219
  clipboardTask;
@@ -135,9 +228,11 @@ export class TerminalUI {
135
228
  output;
136
229
  cwd;
137
230
  colorizer = new TranscriptColorizer();
138
- colorizerState = { mode: 'text', inDiff: false };
231
+ colorizerState = { mode: 'text', inDiff: false, inToolOutput: false };
139
232
  palette = paletteFor('dark');
140
233
  panelStyle = '48;5;235';
234
+ /** Foreground for text drawn on `panelStyle`; keeps the status line readable on both themes. */
235
+ panelAccent = PANEL_ACCENT.dark;
141
236
  backgroundProbe = false;
142
237
  /** 背景プローブ中(返信待ち)。時間による入力抑制には使わない。 */
143
238
  backgroundWaiting = false;
@@ -148,6 +243,7 @@ export class TerminalUI {
148
243
  replyDone = false;
149
244
  constructor(cwd, input = process.stdin, output = process.stdout, options = {}) {
150
245
  this.clipboardReader = options.readClipboardImage ?? readClipboardImage;
246
+ this.copyText = options.writeClipboardText ?? writeClipboardText;
151
247
  this.cwd = cwd;
152
248
  this.input = input;
153
249
  this.output = output;
@@ -157,14 +253,23 @@ export class TerminalUI {
157
253
  // キー入力を落とし、ユーザーの打鍵はいつでも通常通り処理する。
158
254
  if (this.color && input.isTTY === true)
159
255
  this.probeBackground();
160
- emitKeypressEvents(input);
256
+ if (options.writeClipboardText || (process.platform === 'darwin' && input.isTTY && output.isTTY)) {
257
+ const keyInput = this.keyInput = new PassThrough();
258
+ this.mouseInput = new TerminalMouseInput(text => { if (text)
259
+ keyInput.write(text); }, this.mouseReport, () => this.paste || this.replySilenced);
260
+ emitKeypressEvents(keyInput);
261
+ keyInput.on('keypress', this.keypress);
262
+ input.on('data', this.mouseInput.write);
263
+ }
264
+ else
265
+ emitKeypressEvents(input);
161
266
  input.setRawMode(true);
162
267
  input.on('keypress', this.keypress);
163
268
  input.on('end', this.onEnd);
164
269
  output.on('resize', this.onResize);
165
270
  process.on('exit', this.close);
166
271
  input.resume();
167
- output.write('\x1b[?2004h');
272
+ output.write('\x1b[?2004h' + (this.mouseInput ? '\x1b[?1002h\x1b[?1006h' : ''));
168
273
  // 起動時は一度だけ画面を消す(前回実行の残りを見せない)。
169
274
  this.clearPending = true;
170
275
  if (this.backgroundProbe)
@@ -197,6 +302,7 @@ export class TerminalUI {
197
302
  if (classified !== null) {
198
303
  this.palette = paletteFor(classified);
199
304
  this.panelStyle = classified === 'light' ? '48;5;255' : '48;5;235';
305
+ this.panelAccent = PANEL_ACCENT[classified];
200
306
  this.render();
201
307
  }
202
308
  };
@@ -227,26 +333,139 @@ export class TerminalUI {
227
333
  onResize = () => {
228
334
  if (this.closed)
229
335
  return;
336
+ this.cancelDrag();
230
337
  this.clearPending = true;
231
338
  this.streamRow = 1;
232
339
  this.cursorRow = 1;
233
- this.render();
340
+ if (this.page)
341
+ this.renderPage();
342
+ else if (this.history)
343
+ this.renderHistory();
344
+ else
345
+ this.render();
234
346
  };
235
347
  columns() { return Math.max(12, this.output.columns || 80); }
236
348
  rows() { return Math.max(6, this.output.rows || 24); }
237
- /** 起動直後は80、会話が始まると端末幅に応じて広げる(旧設計と同じ判断)。 */
349
+ /** 会話中は左ペイン、起動時は中央寄せ用に80列まで。 */
238
350
  width() {
239
351
  const columns = this.columns();
240
- return this.started ? Math.max(8, Math.min(columns - 2, Math.max(80, Math.floor(columns * 0.85))))
241
- : Math.max(8, Math.min(columns - 2, 80));
352
+ if (!this.started)
353
+ return Math.max(8, Math.min(columns - 2, 80));
354
+ return this.hasUsagePane() ? columns - SIDEBAR_WIDTH - 2 : columns;
242
355
  }
243
- write(text) { this.appendTranscript(text); this.render(); }
356
+ write(text, kind = 'system') { this.appendTranscript(text, kind); this.render(); }
244
357
  setModel(model) { this.model = model; this.render(); }
245
- setActivity(activity) { if (this.activity !== activity) {
358
+ setActivity(activity) {
359
+ if (this.closed || this.activity === activity)
360
+ return;
246
361
  this.activity = activity;
362
+ this.activityStarted = performance.now();
363
+ this.updateProgressTimer();
364
+ this.render();
365
+ }
366
+ turnToolCount;
367
+ setTurnToolCount(count) {
368
+ if (this.closed || this.turnToolCount === count)
369
+ return;
370
+ this.turnToolCount = count;
371
+ this.render();
372
+ }
373
+ activityLabel() {
374
+ if (!this.activity)
375
+ return null;
376
+ const seconds = Math.floor((performance.now() - this.activityStarted) / 1000);
377
+ return `${this.activity} · ${seconds}秒`;
378
+ }
379
+ animationEnabled = process.env.MODKH_NO_ANIMATION !== '1';
380
+ setAnimation(enabled) {
381
+ if (this.closed || this.animationEnabled === enabled)
382
+ return;
383
+ this.animationEnabled = enabled;
384
+ this.updateProgressTimer();
385
+ this.render();
386
+ }
387
+ canAnimate() {
388
+ return this.color && this.animationEnabled;
389
+ }
390
+ updateProgressTimer() {
391
+ clearInterval(this.progressTimer);
392
+ const interval = this.activity && this.canAnimate() ? WHALE_FRAME_MS : 1000;
393
+ this.progressTimer = this.activity || this.subagent ? setInterval(() => {
394
+ // Keep the ordinary seconds refresh while a prompt or draft occupies the composer.
395
+ if (interval === 1000 || (!this.pending && !this.text) ||
396
+ Math.floor((performance.now() - this.activityStarted) / 1000) !==
397
+ Math.floor((performance.now() - this.activityStarted - interval) / 1000))
398
+ this.render();
399
+ }, interval).unref() : undefined;
400
+ }
401
+ beginFollowups(submit) {
402
+ this.followup = submit;
403
+ this.render();
404
+ return unsent => {
405
+ if (this.followup !== submit)
406
+ return;
407
+ this.followup = undefined;
408
+ if (unsent.length) {
409
+ this.text = [...unsent, this.text].filter(Boolean).join('\n\n');
410
+ this.cursor = chars(this.text).length;
411
+ this.write('\n(送信待ちだった追加の依頼を入力欄に戻しました)\n');
412
+ }
413
+ this.render();
414
+ };
415
+ }
416
+ sendFollowup() {
417
+ if (!this.text.trim() || !this.followup)
418
+ return;
419
+ const error = isChatCommand(this.text) ? 'スラッシュコマンドは応答完了後に使えます' : this.followup(this.text);
420
+ this.inputNotice = error ?? '追加の依頼を受け付けました';
421
+ if (error === null) {
422
+ this.previousInput = this.text;
423
+ this.text = '';
424
+ this.cursor = 0;
425
+ this.editorScroll = 0;
426
+ }
427
+ }
428
+ hasUsagePane() {
429
+ return this.usageVisible && this.columns() >= 80 && this.rows() >= 9;
430
+ }
431
+ controlMargin() {
432
+ return this.started ? 0 : Math.floor((this.columns() - this.width()) / 2);
433
+ }
434
+ controlWidth() {
435
+ return this.width();
436
+ }
437
+ editorWidth() {
438
+ return Math.max(5, this.controlWidth() - 3);
439
+ }
440
+ setSubagent(activity, delegationCount) {
441
+ if (this.closed || (this.delegationCount === delegationCount && this.subagent?.phase === activity?.phase &&
442
+ this.subagent?.pluginId === activity?.pluginId && this.subagent?.task === activity?.task))
443
+ return;
444
+ this.delegationCount = delegationCount;
445
+ if (activity && !this.subagent) {
446
+ this.subagentStarted = performance.now();
447
+ }
448
+ this.subagent = activity;
449
+ this.updateProgressTimer();
247
450
  this.render();
248
- } }
451
+ }
249
452
  setUsage(usage) { this.usage = usage; this.render(); }
453
+ /** Browse activity is display state; the browser itself is never started from here. */
454
+ setBrowse(active) {
455
+ if (this.closed || this.browse === active)
456
+ return;
457
+ this.browse = active;
458
+ this.render();
459
+ }
460
+ /** Re-render only when the list actually changed; the owner polls this during analysis. */
461
+ setServers(servers) {
462
+ const same = this.servers.length === servers.length &&
463
+ this.servers.every((server, index) => server.id === servers[index]?.id && server.root === servers[index]?.root);
464
+ if (same)
465
+ return;
466
+ this.servers = servers;
467
+ this.render();
468
+ }
250
469
  /** Accumulate one reasoning delta, or flush the finished block into the transcript with `null`. */
251
470
  setReasoning(delta) {
252
471
  if (delta !== null) {
@@ -257,24 +476,47 @@ export class TerminalUI {
257
476
  const text = this.reasoning.trimEnd();
258
477
  this.reasoning = '';
259
478
  if (text)
260
- this.appendTranscript(`\n(推論)\n${text}\n`);
479
+ this.appendTranscript(`\n(推論)\n${text}\n`, 'reasoning');
261
480
  this.render();
262
481
  }
263
482
  unread(line) { this.queued.unshift(line); }
483
+ restoreDraft(text) {
484
+ this.text = text;
485
+ this.cursor = chars(text).length;
486
+ this.render();
487
+ }
264
488
  get imageCount() { return this.images.length; }
265
489
  takeImages() { const images = this.images; this.images = []; this.render(); return images; }
266
490
  next(signal) { return this.wait('何を調べますか? / でコマンド', undefined, '', signal, false, true); }
267
491
  ask(title, signal, secret = false) { return this.wait(title, undefined, '', signal, secret); }
492
+ confirm(title, signal) { return this.wait(title, APPROVAL_CHOICES, '', signal); }
268
493
  choose(title, choices, query = '') { return this.wait(title, choices, query); }
494
+ showPage(title, text) {
495
+ if (this.closed)
496
+ return Promise.resolve();
497
+ if (this.page || this.pending || this.followup)
498
+ throw new Error('端末の入力待ちは同時に1件だけです');
499
+ this.leaveHistory(false);
500
+ this.cancelDrag();
501
+ return new Promise(resolve => {
502
+ this.page = { title, text, top: 0, width: 0, lines: [], pasting: false, resolve };
503
+ this.output.write('\x1b[?1049h\x1b[?25l');
504
+ this.renderPage();
505
+ });
506
+ }
269
507
  wait(title, choices, query = '', signal, secret = false, composer = false) {
270
508
  if (signal?.aborted || this.closed)
271
509
  return Promise.resolve(null);
272
- if (this.queued.length)
273
- return Promise.resolve(this.queued.shift());
274
- if (this.pending)
510
+ if (this.page || this.pending)
275
511
  throw new Error('端末の入力待ちは同時に1件だけです');
276
- this.text = query;
277
- this.cursor = chars(query).length;
512
+ if (choices !== APPROVAL_CHOICES && this.queued.length)
513
+ return Promise.resolve(this.queued.shift());
514
+ if (!composer)
515
+ this.leaveHistory();
516
+ const draft = !composer && this.text
517
+ ? { text: this.text, cursor: this.cursor, scroll: this.editorScroll, notice: this.inputNotice } : undefined;
518
+ this.text = composer ? this.text : query;
519
+ this.cursor = composer ? this.cursor : chars(query).length;
278
520
  this.selection = 0;
279
521
  this.hiddenCompletion = false;
280
522
  this.editorScroll = 0;
@@ -288,11 +530,15 @@ export class TerminalUI {
288
530
  this.paste = false;
289
531
  this.pasteBuffer = '';
290
532
  this.pasteBytes = 0;
533
+ if (composer && value?.trim() && !isChatCommand(value))
534
+ this.previousInput = value;
291
535
  if (value === null && composer)
292
536
  this.images = [];
293
537
  this.pending = undefined;
294
- this.text = '';
295
- this.cursor = 0;
538
+ this.text = draft?.text ?? '';
539
+ this.cursor = draft?.cursor ?? 0;
540
+ this.editorScroll = draft?.scroll ?? 0;
541
+ this.inputNotice = draft?.notice ?? '';
296
542
  this.render();
297
543
  resolve(value);
298
544
  };
@@ -309,15 +555,44 @@ export class TerminalUI {
309
555
  // Pinned rows are actions: they stay on top so a bare Enter cannot pick an arbitrary model.
310
556
  return [...visible.filter(c => c.pinned), ...visible.filter(c => !c.pinned)];
311
557
  }
312
- if (!this.hiddenCompletion && this.text.startsWith('/') && !(/\s/.test(this.text)))
558
+ if (this.pending && !this.hiddenCompletion && this.text.startsWith('/') && !(/\s/.test(this.text)))
313
559
  return matching(COMMANDS, this.text);
314
560
  return undefined;
315
561
  }
562
+ fileMenu;
563
+ fileOptions() {
564
+ if (!(this.pending ? this.pending.composer && !this.pending.secret : this.followup)) {
565
+ this.fileMenu = undefined;
566
+ return undefined;
567
+ }
568
+ if (this.fileMenu?.text !== this.text || this.fileMenu.cursor !== this.cursor) {
569
+ const mention = activeFileMention(this.text, chars(this.text).slice(0, this.cursor).join('').length);
570
+ const pdfPath = mention && !this.text.includes('\n') && isPdfPathPrefix(this.text.slice(0, mention.start));
571
+ this.fileMenu = mention ? { text: this.text, cursor: this.cursor, mention,
572
+ candidates: fileCandidates(this.cwd, mention.query, pdfPath ? name => /\.pdf$/i.test(name) : undefined),
573
+ selected: 0, dismissed: false } : undefined;
574
+ }
575
+ return this.fileMenu?.dismissed ? undefined : this.fileMenu;
576
+ }
577
+ completeFile(mention, candidate) {
578
+ const reference = formatFileMention(candidate.path);
579
+ const rest = this.text.slice(mention.end);
580
+ const separator = !candidate.directory && !/^\s/u.test(rest) ? ' ' : '';
581
+ const prefix = this.text.slice(0, mention.start) + reference + separator;
582
+ if (Buffer.byteLength(prefix + rest) > MAX_INPUT_BYTES) {
583
+ this.inputNotice = '入力は128 KiB以内にしてください';
584
+ return;
585
+ }
586
+ this.text = prefix + rest;
587
+ this.cursor = chars(prefix).length - (candidate.directory && reference.startsWith('@"') ? 1 : 0);
588
+ this.fileMenu = undefined;
589
+ this.inputNotice = '';
590
+ }
316
591
  insertText(value) {
317
- if (this.replySilenced)
592
+ if (this.pending?.choices === APPROVAL_CHOICES || this.replySilenced)
318
593
  return; // OSC 返信の取り込みを入力にしない
319
594
  const normalized = clean(value.replace(/\r\n?/g, '\n').replace(/\t/g, ' '));
320
- const added = chars(this.pending?.composer ? normalized : normalized.replace(/\n/g, ' '));
595
+ const added = chars((this.pending?.composer || (!this.pending && this.followup)) ? normalized : normalized.replace(/\n/g, ' '));
321
596
  const parts = chars(this.text);
322
597
  const next = parts.slice(0, this.cursor).concat(added, parts.slice(this.cursor)).join('');
323
598
  if (Buffer.byteLength(next) > MAX_INPUT_BYTES) {
@@ -360,8 +635,242 @@ export class TerminalUI {
360
635
  this.render();
361
636
  }
362
637
  }
638
+ mouseReport = ({ button, released, ...point }) => {
639
+ if (this.pending?.secret)
640
+ return;
641
+ if (!released && (button === 64 || button === 65)) {
642
+ const delta = button === 64 ? -3 : 3;
643
+ if (this.page)
644
+ this.renderPage(delta);
645
+ else
646
+ this.scrollHistory(-delta);
647
+ return;
648
+ }
649
+ if (this.page)
650
+ return;
651
+ if (point.row < 1 || point.row > this.rows() || point.column < 1)
652
+ return;
653
+ const rows = this.visibleTranscript();
654
+ if (!released && button === 0) {
655
+ // Some terminals repeat the press immediately before the release.
656
+ if (!this.drag && rows.has(point.row) && point.column <= this.width()) {
657
+ this.drag = { anchor: point, end: point };
658
+ }
659
+ return;
660
+ }
661
+ const drag = this.drag;
662
+ if (!drag || (released ? button !== 0 : button !== 32))
663
+ return;
664
+ drag.end = point;
665
+ if (!released) {
666
+ this.output.write(this.clearDragHighlight() + this.drawDragHighlight());
667
+ return;
668
+ }
669
+ const moved = drag.anchor.row !== point.row || drag.anchor.column !== point.column;
670
+ const text = moved ? selectedTranscript(rows, drag).map(line => line.text + (line.newline ? '\n' : '')).join('') : '';
671
+ this.cancelDrag();
672
+ this.render();
673
+ if (text.trim())
674
+ this.copyQueue = this.copyQueue.then(() => this.copySelection(text));
675
+ };
676
+ visibleTranscript() {
677
+ return this.history?.rows ?? new Map([...this.transcriptRows, ...this.liveTranscriptRows]);
678
+ }
679
+ drawDragHighlight() {
680
+ if (!this.drag)
681
+ return '';
682
+ const lines = selectedTranscript(this.visibleTranscript(), this.drag).filter(line => line.text);
683
+ this.selectionRows = lines.map(line => line.row);
684
+ return lines.length ? '\x1b7' + lines.map(line => `\x1b[${line.row};${line.column}H\x1b[7m${line.text}\x1b[0m`).join('') + '\x1b8' : '';
685
+ }
686
+ clearDragHighlight() {
687
+ if (!this.selectionRows.length)
688
+ return '';
689
+ const rows = this.visibleTranscript();
690
+ const restore = this.selectionRows.map(row => `\x1b[${row};1H${rows.get(row)?.painted ?? ''}`).join('');
691
+ this.selectionRows = [];
692
+ return '\x1b7' + restore + '\x1b8';
693
+ }
694
+ cancelDrag() {
695
+ const restore = this.clearDragHighlight();
696
+ if (restore)
697
+ this.output.write(restore);
698
+ this.drag = undefined;
699
+ }
700
+ async copySelection(text) {
701
+ if (this.closed)
702
+ return;
703
+ try {
704
+ await this.copyText(text);
705
+ this.inputNotice = '選択範囲をコピーしました';
706
+ }
707
+ catch {
708
+ this.inputNotice = '選択範囲をコピーできませんでした';
709
+ }
710
+ finally {
711
+ if (this.history)
712
+ this.renderHistory();
713
+ else
714
+ this.render();
715
+ }
716
+ }
717
+ scrollTranscriptRows(count) {
718
+ this.drag = undefined;
719
+ const visible = new Map();
720
+ for (const [row, line] of this.transcriptRows) {
721
+ if (row > count)
722
+ visible.set(row - count, line);
723
+ else if (this.mouseInput)
724
+ this.historyRows.push(line);
725
+ }
726
+ this.transcriptRows = visible;
727
+ if (this.historyRows.length > TRANSCRIPT_HISTORY_ROWS) {
728
+ this.historyRows.splice(0, this.historyRows.length - TRANSCRIPT_HISTORY_ROWS);
729
+ }
730
+ }
731
+ scrollHistory(delta) {
732
+ if (!this.started)
733
+ return;
734
+ this.cancelDrag();
735
+ if (!this.history) {
736
+ if (delta < 0 || !this.historyRows.length)
737
+ return;
738
+ const source = [...this.historyRows, ...this.visibleTranscript().values()];
739
+ this.history = { source, width: 0, lines: [], offset: 0, rows: new Map() };
740
+ this.inputNotice = '';
741
+ this.output.write('\x1b[?1049h\x1b[?25l');
742
+ }
743
+ this.history.offset = Math.max(0, this.history.offset + delta);
744
+ if (this.history.offset)
745
+ this.renderHistory();
746
+ else
747
+ this.leaveHistory();
748
+ }
749
+ renderHistory() {
750
+ const history = this.history;
751
+ if (!history)
752
+ return;
753
+ const rows = this.rows();
754
+ const width = this.width();
755
+ if (history.width !== width) {
756
+ history.width = width;
757
+ history.lines = reflowTranscript(history.source, width);
758
+ }
759
+ const transcript = history.lines;
760
+ const bodyRows = rows - 1;
761
+ history.offset = Math.min(history.offset, Math.max(1, transcript.length - bodyRows));
762
+ const end = Math.max(0, transcript.length - history.offset);
763
+ const visible = transcript.slice(Math.max(0, end - bodyRows), end);
764
+ let out = this.clearDragHighlight() + '\x1b[H\x1b[J';
765
+ history.rows.clear();
766
+ visible.forEach((line, index) => {
767
+ history.rows.set(index + 1, line);
768
+ out += `\x1b[${index + 1};1H${line.painted}`;
769
+ });
770
+ const hint = 'MoDKH · 会話履歴 · Esc 戻る';
771
+ const details = this.inputNotice || this.activityLabel() || 'ホイール / PgUp / PgDn';
772
+ const footer = fitText(`${hint} · ${details}`, width);
773
+ out += `\x1b[${rows};1H${this.paint(footer, `${this.panelStyle};${this.panelAccent}`)}`;
774
+ if (this.hasUsagePane()) {
775
+ const usage = usageBreakdownLines(this.usage ?? EMPTY_USAGE, SIDEBAR_WIDTH - 4);
776
+ out += this.drawSidebar(rows, this.columns(), this.sidebarLines(rows, usage));
777
+ }
778
+ this.output.write(out + this.drawDragHighlight());
779
+ }
780
+ leaveHistory(redraw = true) {
781
+ if (!this.history)
782
+ return;
783
+ this.cancelDrag();
784
+ this.history = undefined;
785
+ this.output.write('\x1b[?1049l');
786
+ if (redraw)
787
+ this.render();
788
+ }
789
+ renderPage(delta = 0) {
790
+ const page = this.page;
791
+ if (!page)
792
+ return;
793
+ const rows = this.rows();
794
+ const width = this.columns() - 1; // Avoid autowrap at the right margin.
795
+ if (page.width !== width) {
796
+ page.width = width;
797
+ page.lines = wrapText(page.text, width);
798
+ }
799
+ const bodyRows = rows - 3;
800
+ page.top = Math.max(0, Math.min(page.top + delta, page.lines.length - bodyRows));
801
+ const visible = page.lines.slice(page.top, page.top + bodyRows);
802
+ const heading = this.paint(fitText(page.title, width), '1');
803
+ const hints = fitText('Esc/q 戻る ↑↓ 行 PgUp/PgDn ページ', width);
804
+ const position = fitText(`${page.top + 1}–${page.top + visible.length} / ${page.lines.length}`, width);
805
+ this.output.write(`\x1b[H\x1b[J${heading}` +
806
+ visible.map((line, i) => `\x1b[${i + 2};1H${line}`).join('') +
807
+ `\x1b[${rows - 1};1H${position}\x1b[${rows};1H${hints}`);
808
+ }
809
+ dismissPage() {
810
+ const page = this.page;
811
+ if (!page)
812
+ return;
813
+ this.page = undefined;
814
+ this.output.write('\x1b[?1049l\x1b[?25h');
815
+ page.resolve();
816
+ }
817
+ pageKey(key) {
818
+ const page = this.page;
819
+ if (!page || this.replySilenced)
820
+ return;
821
+ if (key.name === 'paste-start' || key.name === 'paste-end') {
822
+ page.pasting = key.name === 'paste-start';
823
+ return;
824
+ }
825
+ if (page.pasting)
826
+ return;
827
+ if (key.name === 'escape' || (key.name === 'q' && !key.ctrl && !key.meta) || (key.ctrl && key.name === 'c')) {
828
+ this.dismissPage();
829
+ return;
830
+ }
831
+ const step = this.rows() - 4; // Leave one line of context between pages.
832
+ switch (key.name) {
833
+ case 'up':
834
+ this.renderPage(-1);
835
+ break;
836
+ case 'down':
837
+ this.renderPage(1);
838
+ break;
839
+ case 'pageup':
840
+ this.renderPage(-step);
841
+ break;
842
+ case 'pagedown':
843
+ case 'space':
844
+ this.renderPage(step);
845
+ break;
846
+ case 'home':
847
+ this.renderPage(-page.top);
848
+ break;
849
+ case 'end':
850
+ this.renderPage(page.lines.length);
851
+ break;
852
+ }
853
+ }
363
854
  onEnd = () => { this.pending?.finish(null); this.close(); };
364
855
  keypress = (value, key) => {
856
+ if (this.page) {
857
+ this.pageKey(key);
858
+ return;
859
+ }
860
+ if (this.drag) {
861
+ this.cancelDrag();
862
+ this.render();
863
+ }
864
+ if (this.mouseInput && !this.paste && !this.replySilenced && !this.pending?.secret &&
865
+ (key.name === 'pageup' || key.name === 'pagedown')) {
866
+ this.scrollHistory((this.rows() - 2) * (key.name === 'pageup' ? 1 : -1));
867
+ return;
868
+ }
869
+ if (this.history) {
870
+ this.leaveHistory();
871
+ if (key.name === 'escape')
872
+ return;
873
+ }
365
874
  if (key.name === 'paste-start') {
366
875
  this.paste = true;
367
876
  this.pasteBuffer = '';
@@ -370,7 +879,7 @@ export class TerminalUI {
370
879
  }
371
880
  if (key.name === 'paste-end') {
372
881
  this.paste = false;
373
- if (this.pending && this.pasteBytes <= MAX_INPUT_BYTES)
882
+ if ((this.pending || this.followup) && this.pasteBytes <= MAX_INPUT_BYTES)
374
883
  this.insertText(this.pasteBuffer);
375
884
  else if (this.pasteBytes > MAX_INPUT_BYTES)
376
885
  this.inputNotice = '貼り付けるテキストは128 KiB以内にしてください';
@@ -408,14 +917,15 @@ export class TerminalUI {
408
917
  // 返信チャンク(OSC 応答)から生じたキー入力だけを握りつぶす。Ctrl+C は通す。
409
918
  if (this.replySilenced && !(key.ctrl && key.name === 'c'))
410
919
  return;
411
- // PageUp/PgDn は端末本来のスクロールに任せる(代替スクリーンを使わないため)。
412
- if (!this.pending)
920
+ const pending = this.pending;
921
+ if (!pending && !this.followup)
413
922
  return;
923
+ const composer = pending ? pending.composer : true;
414
924
  if (key.ctrl && key.name === 'v') {
415
925
  void this.pasteImage();
416
926
  return;
417
927
  }
418
- if (key.ctrl && key.name === 'x' && this.pending.composer) {
928
+ if (key.ctrl && key.name === 'x' && pending?.composer) {
419
929
  this.clipboardTask?.abort();
420
930
  this.clipboardTask = undefined;
421
931
  this.images.pop();
@@ -424,26 +934,40 @@ export class TerminalUI {
424
934
  return;
425
935
  }
426
936
  const options = this.options();
937
+ const files = this.fileOptions();
427
938
  if (key.name === 'escape' || key.ctrl && key.name === 'd') {
428
- if (this.pending.choices)
429
- this.pending.finish(null);
939
+ if (pending?.choices)
940
+ pending.finish(null);
941
+ else if (files && key.name === 'escape') {
942
+ files.dismissed = true;
943
+ this.render();
944
+ }
430
945
  else if (options?.length && key.name === 'escape') {
431
946
  this.hiddenCompletion = true;
432
947
  this.render();
433
948
  }
434
949
  else if (!this.text && key.ctrl)
435
- this.pending.finish(null);
950
+ pending?.finish(null);
436
951
  return;
437
952
  }
438
- const newline = this.pending.composer && (value === '\n' || key.ctrl && key.name === 'j' || (key.name === 'return' || key.name === 'enter') && (key.shift || key.meta));
953
+ const newline = composer && (value === '\n' || key.ctrl && key.name === 'j' || (key.name === 'return' || key.name === 'enter') && (key.shift || key.meta));
439
954
  if (newline)
440
955
  this.insertText('\n');
441
956
  else if (options && (key.name === 'up' || key.name === 'down')) {
442
957
  this.selection = options.length ? (this.selection + (key.name === 'down' ? 1 : -1) + options.length) % options.length : 0;
443
958
  }
444
- else if (this.pending.composer && (key.name === 'up' || key.name === 'down')) {
445
- const width = Math.max(5, Math.min(this.width() - 4, 80) - 3);
446
- this.cursor = verticalCursor(this.text, this.cursor, width, key.name === 'up' ? -1 : 1);
959
+ else if (files?.candidates.length && (key.name === 'up' || key.name === 'down')) {
960
+ const count = files.candidates.length;
961
+ files.selected = (files.selected + (key.name === 'down' ? 1 : -1) + count) % count;
962
+ }
963
+ else if (composer && key.name === 'up' && !this.text && this.previousInput) {
964
+ this.text = this.previousInput;
965
+ this.cursor = chars(this.text).length;
966
+ this.hiddenCompletion = true;
967
+ this.inputNotice = '';
968
+ }
969
+ else if (composer && (key.name === 'up' || key.name === 'down')) {
970
+ this.cursor = verticalCursor(this.text, this.cursor, this.editorWidth(), key.name === 'up' ? -1 : 1);
447
971
  }
448
972
  else if (key.name === 'return' || key.name === 'enter' || key.name === 'tab') {
449
973
  if (this.clipboardTask) {
@@ -453,17 +977,22 @@ export class TerminalUI {
453
977
  }
454
978
  const selected = options?.[this.selection];
455
979
  if (key.name === 'tab') {
456
- if (selected && !this.pending.choices) {
980
+ const candidate = files?.candidates[files.selected];
981
+ if (files && candidate)
982
+ this.completeFile(files.mention, candidate);
983
+ else if (selected && !pending?.choices) {
457
984
  this.text = selected.value;
458
985
  this.cursor = chars(this.text).length;
459
986
  }
460
987
  }
461
- else if (this.pending.choices) {
988
+ else if (pending?.choices) {
462
989
  if (selected)
463
- this.pending.finish(selected.value);
990
+ pending.finish(selected.value);
464
991
  }
992
+ else if (pending)
993
+ pending.finish(selected?.value ?? this.text);
465
994
  else
466
- this.pending.finish(selected?.value ?? this.text);
995
+ this.sendFollowup();
467
996
  }
468
997
  else if (key.name === 'left')
469
998
  this.cursor = Math.max(0, this.cursor - 1);
@@ -493,32 +1022,48 @@ export class TerminalUI {
493
1022
  this.render();
494
1023
  };
495
1024
  /**
496
- * トランスクリプトへ追記する。完成行は直ちに折り返して出力待ちキューへ。
1025
+ * トランスクリプトへ追記する。完成行を出力待ちキューへ。装飾と折り返しは描画時に行う。
497
1026
  * 会話の始まり(`▶`)を検出したら、それ以降の行を広めの幅で折り返す。
498
1027
  */
499
- appendTranscript(text) {
1028
+ appendTranscript(text, kind) {
500
1029
  let source = (this.partial + text).replace(/\r\n?/g, '\n');
501
- if (/(^|\n)▶/.test(text) || /https:\/\//.test(text))
1030
+ let lineKind = this.partial ? this.partialKind : kind;
1031
+ if (kind === 'user')
1032
+ this.usageVisible = true;
1033
+ if (kind === 'user' || /(^|\n)▶/.test(text) || /https:\/\//.test(text))
502
1034
  this.started = true;
503
- const width = this.width();
504
1035
  for (;;) {
505
1036
  const at = source.indexOf('\n');
506
1037
  if (at < 0) {
507
1038
  this.partial = source;
1039
+ this.partialKind = lineKind;
508
1040
  break;
509
1041
  }
510
1042
  const logicalLine = source.slice(0, at);
511
1043
  source = source.slice(at + 1);
512
1044
  // 会話が始まる前の案内行はウェルカムブロックへ(会話開始時に一括で出力する)。
513
- if (!this.started) {
1045
+ if (!this.started)
514
1046
  this.bootLines.push(logicalLine);
515
- continue;
516
- }
517
- for (const wrapped of wrap(logicalLine, width))
518
- this.queue.push(wrapped);
519
- this.partial = '';
1047
+ else
1048
+ this.queue.push({ text: logicalLine, kind: lineKind });
1049
+ lineKind = kind;
520
1050
  }
521
1051
  }
1052
+ renderTranscriptLine(raw, kind, width, newline, colorizer) {
1053
+ const source = clean(raw);
1054
+ const colored = colorizer.line(source, this.palette, kind);
1055
+ const text = clean(colored);
1056
+ if (kind === 'answer' && source && !text)
1057
+ return [];
1058
+ if (kind === 'user') {
1059
+ return transcriptLine(text, width, newline).map(line => {
1060
+ const padded = line.text.padEnd(line.text.length + width - textWidth(line.text));
1061
+ const painted = this.color && line.text ? this.paint(padded, `${this.panelStyle};${this.palette.user}`) : line.text;
1062
+ return { ...line, painted };
1063
+ });
1064
+ }
1065
+ return reflowTranscript([{ text, painted: this.color ? colored : text, newline }], width);
1066
+ }
522
1067
  paint(text, code) { return this.color ? `\x1b[${code}m${text}\x1b[0m` : text; }
523
1068
  /**
524
1069
  * 1フレームの描画。
@@ -528,45 +1073,65 @@ export class TerminalUI {
528
1073
  * 再描画は最下部ブロックに限るため、過去の履歴が端末のスクロールバックに蓄積する。
529
1074
  */
530
1075
  render = () => {
531
- if (this.closed)
1076
+ // Keep mouse coordinates stable while a response is still streaming under the drag.
1077
+ if (this.closed || this.page || this.history || this.drag)
532
1078
  return;
533
1079
  const rows = this.rows();
534
- const width = this.width();
535
- // 画面全体に対してコンテンツを中央に寄せる(ウェルカムも会話中も同じ中央寄せ)。
536
- const paintMargin = Math.max(0, Math.floor((this.columns() - width) / 2));
537
- const marginPrefix = ' '.repeat(Math.min(paintMargin, Math.max(0, this.columns() - 6)));
538
- const stream = this.queue.splice(0, this.queue.length)
539
- .map(line => this.color ? this.colorizer.line(line, this.palette) : line);
1080
+ const columns = this.columns();
1081
+ const width = this.started ? this.width() : Math.max(8, Math.min(columns - 4, 80));
1082
+ // 会話開始前だけ中央寄せを残す。会話中は余白を付けず、画面上の位置とコピー結果を一致させる。
1083
+ const marginPrefix = this.started ? '' : ' '.repeat(Math.max(0, Math.floor((columns - width) / 2)));
1084
+ const stream = this.queue.splice(0).flatMap(line => this.renderTranscriptLine(line.text, line.kind, width, true, this.colorizer));
540
1085
  this.colorizerState = this.colorizer.state();
541
- // 会話が始まった瞬間、ウェルカム(ロゴ+案内)を一度だけ本文へ流し込む。
1086
+ // 起動時の案内だけを履歴に残す。ロゴはウェルカム画面の一部。
542
1087
  if (this.started && !this.bootFlushed) {
543
1088
  this.bootFlushed = true;
544
- const banner = ['MoDKH · Coding Harness', ...logoForWidth(width)];
545
- stream.unshift(...banner.map(l => this.paint(l, l.startsWith('MoDKH') ? '1' : ACCENT)), ...this.bootLines.flatMap(l => wrap(l, width)));
1089
+ stream.unshift(...this.bootLines.flatMap(line => {
1090
+ const wrapped = wrap(line, width);
1091
+ return wrapped.map((text, index) => ({ text, painted: text, newline: index === wrapped.length - 1 }));
1092
+ }));
546
1093
  this.bootLines = [];
547
1094
  }
548
1095
  // --- ライブブロック(最下部)を構成する ---
549
1096
  const displayText = this.pending?.secret ? '•'.repeat(chars(this.text).length) : this.text;
550
1097
  const composer = !this.pending || this.pending.composer;
551
- const editor = editorLayout(displayText, Math.max(5, width - 3));
1098
+ const editor = editorLayout(displayText, this.editorWidth());
552
1099
  const cursor = editor.positions[Math.min(this.cursor, editor.positions.length - 1)];
553
- const inputRows = Math.min(Math.max(1, rows - 8), Math.max(composer ? 3 : 1, editor.lines.length));
1100
+ const showUsage = this.hasUsagePane();
1101
+ const stackUsage = this.usageVisible && !showUsage && columns >= SIDEBAR_WIDTH && rows >= 14;
1102
+ const usageRows = showUsage || stackUsage
1103
+ ? usageBreakdownLines(this.usage ?? EMPTY_USAGE, SIDEBAR_WIDTH - 4) : [];
1104
+ const stackedHeight = stackUsage ? usageRows.length : 0;
1105
+ const files = this.fileOptions();
1106
+ const fileRows = files ? Math.max(1, Math.min(files.candidates.length, 4, Math.floor(rows / 6))) : 0;
1107
+ const inputRows = Math.min(Math.max(1, rows - 8 - stackedHeight - fileRows), Math.max(composer ? 3 : 1, editor.lines.length));
554
1108
  const options = this.options();
555
- const partialLines = wrap(this.partial, width);
556
- const partialCount = this.partial ? partialLines.length : 0;
1109
+ const childPhase = this.subagent
1110
+ ? `${this.subagent.phase} · ${Math.floor((performance.now() - this.subagentStarted) / 1000)}秒` : '';
1111
+ const childTask = this.subagent?.task.split(/\r?\n/, 1)[0];
1112
+ const pane = showUsage ? this.sidebarSubagent(rows, usageRows.length) : null;
1113
+ const editingFollowup = !this.pending && !!this.followup;
1114
+ const compactChild = !!this.subagent && !pane;
1115
+ const controlWidth = this.controlWidth();
1116
+ const controlMargin = this.controlMargin();
1117
+ const partialRows = this.partial
1118
+ ? this.renderTranscriptLine(this.partial, this.partialKind, width, false, this.fork()) : [];
1119
+ const partialLines = partialRows.map(line => line.painted);
1120
+ const partialCount = partialLines.length;
557
1121
  // ライブの推論は見出し含めて表示。はみ出すときは古い行(先頭)から落とす。
558
1122
  const reasoningText = this.reasoning.trimEnd() === '' ? [] :
559
- wrap(`(推論)\n${this.reasoning.trimEnd()}`, width);
560
- const reservedForBody = 1 /* divider */ + inputRows + 4 /* status/hints/cwd+footer */ + (options ? 2 : 0) + partialCount;
1123
+ transcriptLines(`(推論)\n${this.reasoning.trimEnd()}`, width);
1124
+ const reservedForBody = 1 /* divider */ + inputRows + fileRows + 4 /* status/hints/cwd+footer */ + (options ? 2 : 0) + partialCount + stackedHeight;
561
1125
  const maxReasoning = Math.max(0, Math.min(rows - reservedForBody - 1, 24));
562
1126
  const liveReasoning = reasoningText.length === 0 ? [] :
563
1127
  reasoningText.slice(Math.max(0, reasoningText.length - maxReasoning))
564
- .map(line => ({ text: line, style: this.palette.reasoning }));
1128
+ .map(line => ({ ...line, painted: this.paint(fitText(line.text, width), this.palette.reasoning) }));
565
1129
  const optionsLines = [];
566
1130
  if (options) {
567
- const height = Math.max(1, Math.min(options.length || 1, Math.max(2, rows - (partialCount + liveReasoning.length) - 6), 8));
1131
+ const maxOptions = this.pending?.choices ? 8 : COMMANDS.length;
1132
+ const height = Math.max(1, Math.min(options.length || 1, Math.max(2, rows - (partialCount + liveReasoning.length) - 6 - stackedHeight), maxOptions));
568
1133
  const start = Math.max(0, Math.min(this.selection - height + 1, options.length - height));
569
- optionsLines.push({ text: this.pending?.choices ? this.pending.title : 'Commands', style: '1' });
1134
+ optionsLines.push({ text: this.pending?.choices ? this.pending.title : 'Commands', style: READABLE_TEXT_STYLE });
570
1135
  if (!options.length)
571
1136
  optionsLines.push({ text: '該当なし — 検索語を変える / Esc で戻る', style: '2' });
572
1137
  const matched = options.filter(choice => !choice.pinned).length;
@@ -578,8 +1143,13 @@ export class TerminalUI {
578
1143
  optionsLines.push({ text: label, style: active ? '97;44' : choice.pinned ? '2' : '' });
579
1144
  });
580
1145
  }
581
- const lines = [...optionsLines,
582
- { text: this.started ? '─'.repeat(width) : '', style: ACCENT }];
1146
+ // Reuse the divider row so the animation never moves or covers the editor.
1147
+ const water = this.activity && !this.pending && !this.text && this.canAnimate()
1148
+ ? whaleRow(Math.floor((performance.now() - this.activityStarted) / WHALE_FRAME_MS), controlWidth) : '';
1149
+ const lines = [...optionsLines, {
1150
+ text: water || (this.started && !showUsage ? '─'.repeat(width) : ''),
1151
+ style: water ? this.panelAccent : ACCENT,
1152
+ }];
583
1153
  const editorStart = partialCount + liveReasoning.length + lines.length;
584
1154
  // 入力欄が表示行数を超えたら、カーソルが常に窓内に来るようにスクロールする。
585
1155
  if (cursor.row < this.editorScroll)
@@ -589,33 +1159,62 @@ export class TerminalUI {
589
1159
  this.editorScroll = Math.max(0, Math.min(this.editorScroll, Math.max(0, editor.lines.length - inputRows)));
590
1160
  for (let i = 0; i < inputRows; i++) {
591
1161
  const line = editor.lines[this.editorScroll + i] ?? '';
592
- const placeholder = i === 0 && !this.text ? (this.pending?.choices ? 'Search…' : this.pending?.title ?? this.activity ?? '処理中… Ctrl+C で中止') : '';
593
- lines.push({ text: `│ ${line || placeholder}`, style: '' });
1162
+ const placeholder = i === 0 && !this.text ? (this.pending?.choices === APPROVAL_CHOICES ? '' : this.pending?.choices ? 'Search…' : this.pending?.title ?? this.activityLabel() ?? '処理中… Ctrl+C で中止') : '';
1163
+ let text = `│ ${line || placeholder}`;
1164
+ if (compactChild && !this.pending && this.subagent && (!editingFollowup || (!this.text && i > 0))) {
1165
+ text = `│ ${[childPhase, this.subagent.pluginId, childTask][i] ?? ''}`;
1166
+ }
1167
+ lines.push({ text, style: placeholder && this.pending ? READABLE_TEXT_STYLE : '' });
1168
+ }
1169
+ if (files) {
1170
+ const start = Math.max(0, Math.min(files.selected - fileRows + 1, files.candidates.length - fileRows));
1171
+ if (!files.candidates.length)
1172
+ lines.push({ text: 'ファイル候補なし', style: '2' });
1173
+ files.candidates.slice(start, start + fileRows).forEach((candidate, i) => {
1174
+ const active = start + i === files.selected;
1175
+ lines.push({ text: `${active ? '›' : ' '} ${candidate.path}`, style: active ? '97;44' : '' });
1176
+ });
594
1177
  }
595
1178
  const attachments = composer && this.images.length ? ` · 画像${this.images.length}枚 (Ctrl+Xで削除)` : '';
596
- const status = this.inputNotice && !this.pending?.secret ? this.inputNotice : `MoDKH · ${this.model ?? '未接続 — /connect'}${attachments}`;
597
- lines.push({ text: `│ ${status}`, style: ACCENT });
598
- const hints = !this.pending ? 'Ctrl+C 中止(入力は応答完了後)' : this.pending.choices ? '↑↓ 選択 Enter 決定 Esc 戻る'
599
- : composer ? 'Enter 送信 Ctrl+J 改行 Ctrl+V 画像 Cmd+V テキスト' : 'Enter 決定 Ctrl+C 中止';
600
- lines.push({ text: hints, style: '2' });
601
- // 最下段: 作業ルート(左)とトークン使用量のステータス(右)。狭い時はルートだけ。
602
- const usageStatus = this.usage ? usageBadgeLine(this.usage, Math.max(0, width - textWidth(this.cwd) - 3)) : '';
1179
+ // 右欄を置けない端末では、状態行に同じ表示を残す。
1180
+ const browseBadge = this.browse && !showUsage ? ` · ${BROWSE_ACTIVE_LABEL}` : '';
1181
+ const status = this.inputNotice && !this.pending?.secret ? this.inputNotice : `MoDKH · ${this.model ?? '未接続 — /connect'}${attachments}${browseBadge}`;
1182
+ const baseStatus = compactChild && (this.pending || editingFollowup) ? childPhase : status;
1183
+ const count = this.turnToolCount === undefined ? '' : `今回のツール実行: ${this.turnToolCount}件`;
1184
+ const badge = count && textWidth(baseStatus + ' · ' + count) <= controlWidth - 2 ? ` · ${count}` : '';
1185
+ const modelStatus = `│ ${baseStatus}${badge}`;
1186
+ // A notice is transient feedback, so it is emphasized beyond the standing status line.
1187
+ lines.push({ text: modelStatus, style: this.inputNotice && !this.pending?.secret ? `${this.panelAccent};1` : this.panelAccent });
1188
+ const hints = editingFollowup ? `${compactChild && this.inputNotice ? this.inputNotice + ' ' : ''}Enter 追加の依頼を送信 Ctrl+C 中止`
1189
+ : !this.pending ? 'Ctrl+C 中止(入力は応答完了後)' : this.pending.choices ? '↑↓ 選択 Enter 決定 Esc 戻る'
1190
+ : composer ? 'Enter 送信 Ctrl+J 改行 Ctrl+V 画像 Cmd+V テキスト' + (this.mouseInput ? ' ドラッグでコピー' : '') : 'Enter 決定 Ctrl+C 中止';
1191
+ const recallHint = (this.pending?.composer || editingFollowup) && !this.text && this.previousInput ? '↑ 前回の入力 ' : '';
1192
+ const fileHint = files ? '↑↓ ファイル選択 Tab 補完 Esc 閉じる' : '';
1193
+ lines.push({ text: fileHint || recallHint + hints, style: '2' });
1194
+ // 右側の内訳を置けない端末では、最下段に使用量の要約を残す。
1195
+ const badgeRoom = controlWidth - textWidth(this.cwd) - 2;
1196
+ const usageStatus = !this.usageVisible || usageRows.length ? '' : this.usage?.responses
1197
+ ? usageBadgeLine(this.usage, controlWidth) : '計 — tok';
603
1198
  const usageWidth = textWidth(usageStatus);
604
1199
  const cwdWidth = textWidth(this.cwd);
605
- const bottom = usageStatus.length > 0 && width - cwdWidth - usageWidth >= 2
606
- ? `${this.cwd}${' '.repeat(width - cwdWidth - usageWidth)}${usageStatus}`
607
- : this.cwd;
1200
+ const bottom = usageStatus && badgeRoom >= usageWidth
1201
+ ? `${this.cwd}${' '.repeat(controlWidth - cwdWidth - usageWidth)}${usageStatus}`
1202
+ : usageStatus ? usageStatus.padStart(controlWidth - usageWidth + usageStatus.length) : this.cwd;
608
1203
  lines.push({ text: bottom, style: '2' });
609
- const styled = (row) => {
610
- const fitted = fitText(row.text, width);
1204
+ const styled = (row, maxWidth = width) => {
1205
+ const fitted = fitText(row.text, maxWidth);
611
1206
  if (row.text.startsWith('│ ')) {
612
- const padded = fitted + ' '.repeat(Math.max(0, width - textWidth(fitted)));
613
- return this.paint('│', ACCENT) + this.paint(padded.slice(1), `${this.panelStyle}${row.style ? `;${row.style}` : ''}`);
1207
+ const padded = fitted + ' '.repeat(Math.max(0, maxWidth - textWidth(fitted)));
1208
+ return this.paint('│', this.panelAccent) + this.paint(padded.slice(1), `${this.panelStyle}${row.style ? `;${row.style}` : ''}`);
614
1209
  }
615
1210
  return this.paint(fitted, row.style);
616
1211
  };
617
- // 会話が始まる前のウェルカム: ロゴ+案内を縦中央に整える。
618
- // paintMargin は両フェーズ共通(画面全体に対する中央寄せ)。
1212
+ const rightStart = columns - SIDEBAR_WIDTH;
1213
+ const controls = lines.map(row => ' '.repeat(controlMargin) + styled(row, controlWidth));
1214
+ if (stackUsage) {
1215
+ controls.splice(controls.length - 2, 0, ...usageRows.map(row => ' '.repeat(rightStart) + this.paintSidebarRow(row)));
1216
+ }
1217
+ // 会話が始まる前のウェルカム: ロゴ+案内を中央に整える。
619
1218
  const marginStyled = (row) => marginPrefix + styled(row);
620
1219
  let body = [];
621
1220
  let editorStartIdx = editorStart;
@@ -635,19 +1234,20 @@ export class TerminalUI {
635
1234
  body = [
636
1235
  ...welcome.map(row => marginStyled(row)),
637
1236
  ...Array.from({ length: midPad }, () => marginPrefix),
638
- ...(this.partial ? partialLines.map(line => marginPrefix + (this.color ? this.fork().line(line, this.palette) : line)) : []),
639
- ...liveReasoning.map(row => marginPrefix + this.paint(fitText(row.text, width), row.style)),
1237
+ ...partialLines,
1238
+ ...liveReasoning.map(row => marginPrefix + row.painted),
640
1239
  // lines にはコマンドメニュー(optionsLines)が含まれる。二重に展開しない。
641
- ...lines.map(marginStyled),
1240
+ ...controls,
642
1241
  ];
643
1242
  editorStartIdx = welcome.length + midPad + partialCount + liveReasoning.length + optionsLines.length + 1;
644
1243
  }
645
1244
  else {
1245
+ // 会話中は余白を付けない: 画面上の位置とコピーした文字列を一致させる。
646
1246
  body = [
647
- ...(this.partial ? partialLines.map(line => marginPrefix + (this.color ? this.fork().line(line, this.palette) : line)) : []),
648
- ...liveReasoning.map(row => marginPrefix + this.paint(fitText(row.text, width), row.style)),
1247
+ ...partialLines,
1248
+ ...liveReasoning.map(row => row.painted),
649
1249
  // lines にはコマンドメニュー(optionsLines)が含まれる。二重に展開しない。
650
- ...lines.map(marginStyled),
1250
+ ...controls,
651
1251
  ];
652
1252
  }
653
1253
  // 最下部ブロックは1行以上の余白を残して画面に収める。はみ出すときは上侧から落とす。
@@ -664,17 +1264,17 @@ export class TerminalUI {
664
1264
  // サイズ変更や起動直後は画面を一度消して制御範囲を作り直す(残りを見せない)。
665
1265
  if (this.clearPending) {
666
1266
  this.clearPending = false;
1267
+ this.scrollTranscriptRows(rows);
667
1268
  this.streamRow = 1;
668
1269
  this.cursorRow = 1;
669
1270
  out += '\x1b[2J\x1b[1;1H';
670
1271
  }
1272
+ else if (this.sidebarPainted) {
1273
+ // 右欄を履歴に巻き込む前に消し、左側を描いた後で元の位置へ戻す。
1274
+ out += this.eraseSidebar(rows, rightStart + 1);
1275
+ }
671
1276
  const streamRow = this.streamRow >= 1 ? Math.max(1, Math.min(rows, this.streamRow)) : rows;
672
- // 消去: カーソルは前回フレームの入力位置にある。そこから streamRow まで上がって消す。
673
- const cursorBase = Math.max(1, Math.min(rows, this.cursorRow >= 1 ? this.cursorRow : rows));
674
- const eraseUp = Math.max(0, cursorBase - streamRow);
675
- if (eraseUp > 0)
676
- out += `\x1b[${eraseUp}A`;
677
- out += `\r\x1b[J`;
1277
+ out += `\x1b[${streamRow};1H\x1b[J`;
678
1278
  // 確定行の出力。ライブブロックの上端を越えそうなら先にスクロールして確定させる。
679
1279
  const streamBottom = Math.max(1, rows - liveCount);
680
1280
  let r = streamRow;
@@ -683,8 +1283,10 @@ export class TerminalUI {
683
1283
  const scrolls = Math.min(r - streamBottom, rows);
684
1284
  out += `\x1b[${rows};1H` + '\n'.repeat(scrolls);
685
1285
  r -= scrolls;
1286
+ this.scrollTranscriptRows(scrolls);
686
1287
  }
687
- out += `\x1b[${r};1H\x1b[K${marginPrefix}${line}\r\n`;
1288
+ out += `\x1b[${r};1H\x1b[K${line.painted}\r\n`;
1289
+ this.transcriptRows.set(r, line);
688
1290
  r++;
689
1291
  }
690
1292
  this.streamRow = Math.max(1, Math.min(rows, r));
@@ -695,16 +1297,76 @@ export class TerminalUI {
695
1297
  const scrolls = Math.min(rows, this.streamRow - liveStart);
696
1298
  out += `\x1b[${rows};1H` + '\n'.repeat(scrolls);
697
1299
  this.streamRow -= scrolls;
1300
+ this.scrollTranscriptRows(scrolls);
1301
+ }
1302
+ this.liveTranscriptRows.clear();
1303
+ if (this.started) {
1304
+ const liveTranscript = [...partialRows, ...liveReasoning];
1305
+ for (let i = overflow; i < liveTranscript.length; i++) {
1306
+ this.liveTranscriptRows.set(liveStart + i - overflow, liveTranscript[i]);
1307
+ }
698
1308
  }
699
1309
  for (let i = 0; i < liveCount; i++) {
700
1310
  out += `\x1b[${liveStart + i};1H\x1b[K${body[i]}` + (i === liveCount - 1 ? '' : '\r\n');
701
1311
  }
1312
+ if (showUsage)
1313
+ out += this.drawSidebar(rows, columns, this.sidebarLines(rows, usageRows));
1314
+ this.sidebarPainted = showUsage;
702
1315
  const cursorLiveRow = Math.min(rows, liveStart + editorStartIdx + (cursor.row - this.editorScroll));
703
- const cursorCol = Math.min(this.columns(), paintMargin + 3 + cursor.column);
704
- out += `\x1b[${cursorLiveRow};${cursorCol}H` + (this.pending ? '\x1b[?25h' : '\x1b[?25l');
1316
+ const cursorCol = Math.min(columns, controlMargin + 3 + cursor.column);
1317
+ out += `\x1b[${cursorLiveRow};${cursorCol}H` + (this.pending || editingFollowup ? '\x1b[?25h' : '\x1b[?25l');
705
1318
  this.cursorRow = cursorLiveRow;
706
1319
  this.output.write(out);
707
1320
  };
1321
+ sidebarSubagent(rows, usageHeight) {
1322
+ // A browse row takes one line before the subagent block, so it must be reserved here too.
1323
+ const browseHeight = this.browse ? 1 : 0;
1324
+ return this.started && !this.pending && rows - usageHeight - 3 - browseHeight >= 3 + Number(this.servers.length > 0)
1325
+ ? this.subagent : null;
1326
+ }
1327
+ sidebarLines(rows, usageRows) {
1328
+ const pane = this.sidebarSubagent(rows, usageRows.length);
1329
+ const browseRow = this.browse ? BROWSE_ACTIVE_LABEL : null;
1330
+ const serverRoom = rows - usageRows.length - 3 - (browseRow ? 1 : 0) - (pane ? 3 : 0);
1331
+ const servers = this.servers.slice(0, Math.min(SIDEBAR_SERVER_ROWS, serverRoom));
1332
+ const serverRows = servers.map(server => serverRow(server, this.cwd));
1333
+ const rest = this.servers.length - servers.length;
1334
+ if (rest > 0 && serverRoom > servers.length)
1335
+ serverRows.push(`ほか${rest}件`);
1336
+ const separatorRoom = serverRoom - serverRows.length;
1337
+ const rule = '─'.repeat(SIDEBAR_WIDTH - 4);
1338
+ const divider = separatorRoom >= 6 ? [' ', rule, ' '] : separatorRoom >= 2 ? [rule] : [];
1339
+ const sidebar = ['', ...usageRows, ...(browseRow ? [browseRow] : []), ...divider,
1340
+ `${SUBAGENTS_HEADING} ${this.subagent?.runningCount ?? (this.subagent ? 1 : 0)}稼働 / 累計${this.delegationCount}`];
1341
+ if (pane)
1342
+ sidebar.push(`${pane.phase} · ${Math.floor((performance.now() - this.subagentStarted) / 1000)}秒`, pane.task.split(/\r?\n/, 1)[0], pane.pluginId);
1343
+ sidebar.push(...divider, `${SERVERS_HEADING} ${this.servers.length}稼働`, ...serverRows);
1344
+ return sidebar;
1345
+ }
1346
+ paintSidebarRow(content) {
1347
+ const right = fitText(content, SIDEBAR_WIDTH - 4);
1348
+ const border = this.paint('│', ACCENT);
1349
+ const heading = content.startsWith(USAGE_HEADING) || content.startsWith(SUBAGENTS_HEADING)
1350
+ || content.startsWith(SERVERS_HEADING) || content === BROWSE_ACTIVE_LABEL;
1351
+ const style = heading ? `${this.panelStyle};1` : this.panelStyle;
1352
+ const padding = ' '.repeat(SIDEBAR_WIDTH - 3 - textWidth(right));
1353
+ const panel = this.paint(` ${right}${padding}`, style);
1354
+ return border + panel + border;
1355
+ }
1356
+ drawSidebar(rows, columns, sidebar) {
1357
+ const empty = this.paint(' '.repeat(SIDEBAR_WIDTH), this.panelStyle);
1358
+ let out = '';
1359
+ for (let i = 0; i < rows; i++) {
1360
+ const content = sidebar[i];
1361
+ const panel = content ? this.paintSidebarRow(content) : this.color ? empty : '';
1362
+ if (panel)
1363
+ out += `\x1b[${i + 1};${columns - SIDEBAR_WIDTH + 1}H${panel}`;
1364
+ }
1365
+ return out;
1366
+ }
1367
+ eraseSidebar(rows, column) {
1368
+ return Array.from({ length: rows }, (_, i) => `\x1b[${i + 1};${column}H\x1b[K`).join('');
1369
+ }
708
1370
  /** 未完了行の色分け用に、完成行までの状態を複製する。 */
709
1371
  fork() {
710
1372
  const clone = new TranscriptColorizer();
@@ -714,7 +1376,17 @@ export class TerminalUI {
714
1376
  close = () => {
715
1377
  if (this.closed)
716
1378
  return;
1379
+ this.dismissPage();
1380
+ this.leaveHistory(false);
1381
+ this.cancelDrag();
717
1382
  this.closed = true;
1383
+ if (this.mouseInput) {
1384
+ this.input.off('data', this.mouseInput.write);
1385
+ this.mouseInput.close();
1386
+ this.keyInput?.destroy();
1387
+ this.output.write('\x1b[?1006l\x1b[?1002l');
1388
+ }
1389
+ clearInterval(this.progressTimer);
718
1390
  this.clipboardTask?.abort();
719
1391
  this.clipboardTask = undefined;
720
1392
  this.images = [];
@@ -729,6 +1401,9 @@ export class TerminalUI {
729
1401
  const rows = this.rows();
730
1402
  const eraseRow = Math.min(rows, this.streamRow >= 1 ? this.streamRow : rows);
731
1403
  const base = Math.max(1, Math.min(rows, this.cursorRow >= 1 ? this.cursorRow : rows));
1404
+ if (this.sidebarPainted) {
1405
+ this.output.write(this.eraseSidebar(rows, this.columns() - SIDEBAR_WIDTH + 1) + `\x1b[${base};1H`);
1406
+ }
732
1407
  const up = base - eraseRow;
733
1408
  if (up > 0)
734
1409
  this.output.write(`\x1b[${up}A`);