modkh 0.0.0-stage → 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 (327) hide show
  1. package/README.md +66 -2
  2. package/dist/agent/bundled-skills.d.ts +13 -0
  3. package/dist/agent/bundled-skills.js +95 -0
  4. package/dist/agent/compaction.d.ts +53 -0
  5. package/dist/agent/compaction.js +191 -0
  6. package/dist/agent/images.d.ts +10 -0
  7. package/dist/agent/images.js +33 -0
  8. package/dist/agent/loop.d.ts +103 -0
  9. package/dist/agent/loop.js +267 -0
  10. package/dist/agent/skills.d.ts +26 -0
  11. package/dist/agent/skills.js +190 -0
  12. package/dist/agent/types.d.ts +137 -0
  13. package/dist/agent/types.js +12 -0
  14. package/dist/cli/agenticreplay.d.ts +1 -0
  15. package/dist/cli/agenticreplay.js +66 -0
  16. package/dist/cli/agents.d.ts +8 -0
  17. package/dist/cli/agents.js +12 -0
  18. package/dist/cli/answer-markdown.d.ts +3 -0
  19. package/dist/cli/answer-markdown.js +29 -0
  20. package/dist/cli/approval.d.ts +29 -0
  21. package/dist/cli/approval.js +92 -0
  22. package/dist/cli/catalog.d.ts +37 -0
  23. package/dist/cli/catalog.js +46 -0
  24. package/dist/cli/chat.d.ts +18 -0
  25. package/dist/cli/chat.js +1061 -0
  26. package/dist/cli/clipboard.d.ts +11 -0
  27. package/dist/cli/clipboard.js +82 -0
  28. package/dist/cli/color.d.ts +59 -0
  29. package/dist/cli/color.js +244 -0
  30. package/dist/cli/compaction-settings.d.ts +21 -0
  31. package/dist/cli/compaction-settings.js +54 -0
  32. package/dist/cli/completion-art.d.ts +2 -0
  33. package/dist/cli/completion-art.js +62 -0
  34. package/dist/cli/config.d.ts +50 -0
  35. package/dist/cli/config.js +192 -0
  36. package/dist/cli/editor.d.ts +23 -0
  37. package/dist/cli/editor.js +115 -0
  38. package/dist/cli/file-mentions.d.ts +14 -0
  39. package/dist/cli/file-mentions.js +141 -0
  40. package/dist/cli/head-checks.d.ts +41 -0
  41. package/dist/cli/head-checks.js +146 -0
  42. package/dist/cli/initial-connection.d.ts +7 -0
  43. package/dist/cli/initial-connection.js +20 -0
  44. package/dist/cli/keys.d.ts +29 -0
  45. package/dist/cli/keys.js +107 -0
  46. package/dist/cli/language.d.ts +1 -0
  47. package/dist/cli/language.js +105 -0
  48. package/dist/cli/limits.d.ts +13 -0
  49. package/dist/cli/limits.js +19 -0
  50. package/dist/cli/lines.d.ts +18 -0
  51. package/dist/cli/lines.js +80 -0
  52. package/dist/cli/model-catalog.d.ts +16 -0
  53. package/dist/cli/model-catalog.js +130 -0
  54. package/dist/cli/models.d.ts +4 -0
  55. package/dist/cli/models.js +101 -0
  56. package/dist/cli/official-models.d.ts +6 -0
  57. package/dist/cli/official-models.js +77 -0
  58. package/dist/cli/pdf.d.ts +8 -0
  59. package/dist/cli/pdf.js +71 -0
  60. package/dist/cli/permissions.d.ts +25 -0
  61. package/dist/cli/permissions.js +30 -0
  62. package/dist/cli/plugins.d.ts +1 -0
  63. package/dist/cli/plugins.js +53 -0
  64. package/dist/cli/providers.d.ts +10 -0
  65. package/dist/cli/providers.js +82 -0
  66. package/dist/cli/shell-display.d.ts +6 -0
  67. package/dist/cli/shell-display.js +35 -0
  68. package/dist/cli/stateright.d.ts +1 -0
  69. package/dist/cli/stateright.js +37 -0
  70. package/dist/cli/terminal-mouse.d.ts +21 -0
  71. package/dist/cli/terminal-mouse.js +51 -0
  72. package/dist/cli/terminal.d.ts +231 -0
  73. package/dist/cli/terminal.js +1417 -0
  74. package/dist/cli/tool-display.d.ts +9 -0
  75. package/dist/cli/tool-display.js +87 -0
  76. package/dist/cli/transcript-selection.d.ts +22 -0
  77. package/dist/cli/transcript-selection.js +75 -0
  78. package/dist/cli/usage.d.ts +22 -0
  79. package/dist/cli/usage.js +117 -0
  80. package/dist/cli/waiting-nyan.d.ts +3 -0
  81. package/dist/cli/waiting-nyan.js +17 -0
  82. package/dist/cli/waiting-whales.d.ts +3 -0
  83. package/dist/cli/waiting-whales.js +24 -0
  84. package/dist/index.d.ts +11 -0
  85. package/dist/index.js +186 -0
  86. package/dist/language/catalog.d.ts +44 -0
  87. package/dist/language/catalog.js +100 -0
  88. package/dist/language/commonlisp-bundled.d.ts +11 -0
  89. package/dist/language/commonlisp-bundled.js +22 -0
  90. package/dist/language/commonlisp-dependencies.d.ts +16 -0
  91. package/dist/language/commonlisp-dependencies.js +68 -0
  92. package/dist/language/commonlisp-install.d.ts +15 -0
  93. package/dist/language/commonlisp-install.js +214 -0
  94. package/dist/language/commonlisp-reader.d.ts +17 -0
  95. package/dist/language/commonlisp-reader.js +47 -0
  96. package/dist/language/commonlisp-systems.d.ts +3 -0
  97. package/dist/language/commonlisp-systems.js +32 -0
  98. package/dist/language/commonlisp-tls.d.ts +10 -0
  99. package/dist/language/commonlisp-tls.js +51 -0
  100. package/dist/language/detect.d.ts +29 -0
  101. package/dist/language/detect.js +103 -0
  102. package/dist/language/grammars/LICENSE +24 -0
  103. package/dist/language/grammars/manifest.json +76 -0
  104. package/dist/language/grammars/tree-sitter-c.wasm +0 -0
  105. package/dist/language/grammars/tree-sitter-cpp.wasm +0 -0
  106. package/dist/language/grammars/tree-sitter-css.wasm +0 -0
  107. package/dist/language/grammars/tree-sitter-html.wasm +0 -0
  108. package/dist/language/grammars/tree-sitter-javascript.wasm +0 -0
  109. package/dist/language/grammars/tree-sitter-php.wasm +0 -0
  110. package/dist/language/grammars/tree-sitter-python.wasm +0 -0
  111. package/dist/language/grammars/tree-sitter-ruby.wasm +0 -0
  112. package/dist/language/grammars/tree-sitter-rust.wasm +0 -0
  113. package/dist/language/grammars/tree-sitter-swift.wasm +0 -0
  114. package/dist/language/grammars/tree-sitter-tsx.wasm +0 -0
  115. package/dist/language/grammars/tree-sitter-typescript.wasm +0 -0
  116. package/dist/language/install.d.ts +50 -0
  117. package/dist/language/install.js +293 -0
  118. package/dist/language/lsp/client.d.ts +97 -0
  119. package/dist/language/lsp/client.js +340 -0
  120. package/dist/language/lsp/pool.d.ts +75 -0
  121. package/dist/language/lsp/pool.js +140 -0
  122. package/dist/language/lsp/service.d.ts +50 -0
  123. package/dist/language/lsp/service.js +174 -0
  124. package/dist/language/native.d.ts +8 -0
  125. package/dist/language/native.js +100 -0
  126. package/dist/language/platform.d.ts +14 -0
  127. package/dist/language/platform.js +20 -0
  128. package/dist/language/positions.d.ts +20 -0
  129. package/dist/language/positions.js +46 -0
  130. package/dist/language/syntax/assets.d.ts +9 -0
  131. package/dist/language/syntax/assets.js +73 -0
  132. package/dist/language/syntax/parser.d.ts +33 -0
  133. package/dist/language/syntax/parser.js +162 -0
  134. package/dist/language/typescript-capability.d.ts +6 -0
  135. package/dist/language/typescript-capability.js +42 -0
  136. package/dist/lisp/builtin-agents.d.ts +5 -0
  137. package/dist/lisp/builtin-agents.js +52 -0
  138. package/dist/lisp/config.d.ts +25 -0
  139. package/dist/lisp/config.js +202 -0
  140. package/dist/lisp/routing.d.ts +5 -0
  141. package/dist/lisp/routing.js +24 -0
  142. package/dist/lisp/runtime.d.ts +26 -0
  143. package/dist/lisp/runtime.js +107 -0
  144. package/dist/memory/kiokuko.d.ts +32 -0
  145. package/dist/memory/kiokuko.js +102 -0
  146. package/dist/memory/mcp.d.ts +38 -0
  147. package/dist/memory/mcp.js +211 -0
  148. package/dist/model/ai-sdk.d.ts +27 -0
  149. package/dist/model/ai-sdk.js +185 -0
  150. package/dist/model/chatgpt/login.d.ts +42 -0
  151. package/dist/model/chatgpt/login.js +180 -0
  152. package/dist/model/chatgpt/responses.d.ts +41 -0
  153. package/dist/model/chatgpt/responses.js +254 -0
  154. package/dist/model/chatgpt/tokens.d.ts +11 -0
  155. package/dist/model/chatgpt/tokens.js +50 -0
  156. package/dist/model/connection.d.ts +6 -0
  157. package/dist/model/connection.js +67 -0
  158. package/dist/model/context-window.d.ts +3 -0
  159. package/dist/model/context-window.js +64 -0
  160. package/dist/model/context.d.ts +11 -0
  161. package/dist/model/context.js +69 -0
  162. package/dist/model/factory.d.ts +27 -0
  163. package/dist/model/factory.js +89 -0
  164. package/dist/model/fixed.d.ts +17 -0
  165. package/dist/model/fixed.js +41 -0
  166. package/dist/model/harness-profile.d.ts +6 -0
  167. package/dist/model/harness-profile.js +23 -0
  168. package/dist/model/providers.d.ts +32 -0
  169. package/dist/model/providers.js +72 -0
  170. package/dist/model/reasoning.d.ts +16 -0
  171. package/dist/model/reasoning.js +84 -0
  172. package/dist/model/record-fetch.d.ts +2 -0
  173. package/dist/model/record-fetch.js +19 -0
  174. package/dist/plugins/api.d.ts +60 -0
  175. package/dist/plugins/api.js +1 -0
  176. package/dist/plugins/manager.d.ts +35 -0
  177. package/dist/plugins/manager.js +280 -0
  178. package/dist/plugins/package.d.ts +13 -0
  179. package/dist/plugins/package.js +99 -0
  180. package/dist/plugins/registry.d.ts +8 -0
  181. package/dist/plugins/registry.js +14 -0
  182. package/dist/session/store.d.ts +93 -0
  183. package/dist/session/store.js +311 -0
  184. package/dist/session/workspace.d.ts +19 -0
  185. package/dist/session/workspace.js +73 -0
  186. package/dist/subagents/head-assignment.d.ts +11 -0
  187. package/dist/subagents/head-assignment.js +47 -0
  188. package/dist/subagents/limits.d.ts +4 -0
  189. package/dist/subagents/limits.js +6 -0
  190. package/dist/subagents/processes.d.ts +18 -0
  191. package/dist/subagents/processes.js +73 -0
  192. package/dist/subagents/request.d.ts +4 -0
  193. package/dist/subagents/request.js +38 -0
  194. package/dist/subagents/service.d.ts +73 -0
  195. package/dist/subagents/service.js +645 -0
  196. package/dist/subagents/settings.d.ts +10 -0
  197. package/dist/subagents/settings.js +32 -0
  198. package/dist/subagents/types.d.ts +63 -0
  199. package/dist/subagents/types.js +1 -0
  200. package/dist/subagents/verification.d.ts +34 -0
  201. package/dist/subagents/verification.js +215 -0
  202. package/dist/tools/browse.d.ts +13 -0
  203. package/dist/tools/browse.js +117 -0
  204. package/dist/tools/browser-capability.d.ts +3 -0
  205. package/dist/tools/browser-capability.js +29 -0
  206. package/dist/tools/diff.d.ts +6 -0
  207. package/dist/tools/diff.js +82 -0
  208. package/dist/tools/edit.d.ts +3 -0
  209. package/dist/tools/edit.js +152 -0
  210. package/dist/tools/files.d.ts +6 -0
  211. package/dist/tools/files.js +96 -0
  212. package/dist/tools/formal-input.d.ts +6 -0
  213. package/dist/tools/formal-input.js +29 -0
  214. package/dist/tools/formal.d.ts +9 -0
  215. package/dist/tools/formal.js +79 -0
  216. package/dist/tools/guard.d.ts +7 -0
  217. package/dist/tools/guard.js +48 -0
  218. package/dist/tools/job-tools.d.ts +19 -0
  219. package/dist/tools/job-tools.js +148 -0
  220. package/dist/tools/jobs.d.ts +79 -0
  221. package/dist/tools/jobs.js +186 -0
  222. package/dist/tools/language.d.ts +6 -0
  223. package/dist/tools/language.js +172 -0
  224. package/dist/tools/lean-proof.d.ts +38 -0
  225. package/dist/tools/lean-proof.js +83 -0
  226. package/dist/tools/registry.d.ts +30 -0
  227. package/dist/tools/registry.js +113 -0
  228. package/dist/tools/run.d.ts +13 -0
  229. package/dist/tools/run.js +163 -0
  230. package/dist/tools/search.d.ts +2 -0
  231. package/dist/tools/search.js +156 -0
  232. package/dist/tools/shell-process.d.ts +115 -0
  233. package/dist/tools/shell-process.js +297 -0
  234. package/dist/tools/skills.d.ts +2 -0
  235. package/dist/tools/skills.js +46 -0
  236. package/dist/tools/stateright-runtime.d.ts +3 -0
  237. package/dist/tools/stateright-runtime.js +16 -0
  238. package/dist/tools/stateright.d.ts +3 -0
  239. package/dist/tools/stateright.js +78 -0
  240. package/dist/tools/web.d.ts +24 -0
  241. package/dist/tools/web.js +391 -0
  242. package/dist/version.d.ts +2 -0
  243. package/dist/version.js +2 -0
  244. package/docs/ci-repair-20261116.md +30 -0
  245. package/docs/commonlisp-build-output.md +14 -0
  246. package/docs/commonlisp-provider-migration.md +22 -0
  247. package/docs/commonlisp-qlot-recovery.md +28 -0
  248. package/docs/commonlisp-tls-recovery.md +28 -0
  249. package/docs/context-efficiency.md +122 -0
  250. package/docs/input.md +126 -0
  251. package/docs/languages.md +117 -0
  252. package/docs/models.md +109 -0
  253. package/docs/modkh-evidence.json +641 -0
  254. package/docs/modkh-failure-comparison.json +675 -0
  255. package/docs/modkh-namespace.md +39 -0
  256. package/docs/modkh-qlot-evidence.json +37 -0
  257. package/docs/modkh-verification.md +173 -0
  258. package/docs/modkh.md +128 -0
  259. package/docs/presets.md +64 -0
  260. package/docs/setup.md +99 -0
  261. package/docs/stateright.md +45 -0
  262. package/docs/subagents.md +152 -0
  263. package/docs/web.md +57 -0
  264. package/experiments/presets/common-lisp.lisp +38 -0
  265. package/experiments/presets/css.lisp +38 -0
  266. package/experiments/presets/formal.lisp +18 -0
  267. package/experiments/presets/html.lisp +38 -0
  268. package/experiments/presets/js.lisp +38 -0
  269. package/experiments/presets/language-microagents.lisp +29 -0
  270. package/experiments/presets/php.lisp +38 -0
  271. package/experiments/presets/svelte.lisp +38 -0
  272. package/experiments/presets/tailwindcss.lisp +24 -0
  273. package/experiments/presets/ts.lisp +38 -0
  274. package/native/stateright/Cargo.lock +478 -0
  275. package/native/stateright/Cargo.toml +11 -0
  276. package/native/stateright/src/lib.rs +163 -0
  277. package/native/stateright/src/main.rs +38 -0
  278. package/package.json +57 -4
  279. package/plugins/modkh-explorer/index.mjs +3 -0
  280. package/plugins/modkh-explorer/plugin.json +1 -0
  281. package/plugins/modkh-worker/index.mjs +3 -0
  282. package/plugins/modkh-worker/plugin.json +1 -0
  283. package/skills/kiokuko-dsh/LICENSE +21 -0
  284. package/skills/kiokuko-dsh/coding-ideal-routine-skill/SKILL.md +106 -0
  285. package/skills/kiokuko-dsh/japanese-translation-for-oss-models/SKILL.md +65 -0
  286. package/skills/kiokuko-dsh/kiokuko-architecture/SKILL.md +20 -0
  287. package/skills/kiokuko-dsh/kiokuko-architecture/references/cases.md +11 -0
  288. package/skills/kiokuko-dsh/kiokuko-benchmark/SKILL.md +20 -0
  289. package/skills/kiokuko-dsh/kiokuko-benchmark/references/cases.md +11 -0
  290. package/skills/kiokuko-dsh/kiokuko-investigate/SKILL.md +20 -0
  291. package/skills/kiokuko-dsh/kiokuko-investigate/references/cases.md +11 -0
  292. package/skills/kiokuko-dsh/kiokuko-lisp/SKILL.md +390 -0
  293. package/skills/kiokuko-dsh/kiokuko-review/SKILL.md +20 -0
  294. package/skills/kiokuko-dsh/kiokuko-review/references/cases.md +11 -0
  295. package/skills/kiokuko-dsh/kiokuko-simple-work/SKILL.md +70 -0
  296. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/SKILL.md +79 -0
  297. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/boundaries-and-ownership.md +52 -0
  298. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/domain-and-types.md +48 -0
  299. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/effects-and-data.md +43 -0
  300. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/kiokuko-patterns.md +314 -0
  301. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/problem-shaping-and-language.md +90 -0
  302. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/protocols-and-idempotency.md +42 -0
  303. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/review-checklist.md +92 -0
  304. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/verification.md +45 -0
  305. package/skills/kiokuko-dsh/kiokuko-skill-authoring/SKILL.md +20 -0
  306. package/skills/kiokuko-dsh/kiokuko-skill-authoring/references/cases.md +11 -0
  307. package/skills/kiokuko-dsh/kiokuko-soul/SKILL.md +25 -0
  308. package/skills/kiokuko-dsh/kiokuko-technical-writing/SKILL.md +20 -0
  309. package/skills/kiokuko-dsh/kiokuko-technical-writing/references/cases.md +11 -0
  310. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/SKILL.md +64 -0
  311. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/accessibility-and-navigation.md +31 -0
  312. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/async-recovery.md +49 -0
  313. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/forms-and-controls.md +35 -0
  314. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/interaction-feedback.md +34 -0
  315. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/responsive-and-platform.md +38 -0
  316. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/safety-and-review.md +43 -0
  317. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/ui-checklist.md +75 -0
  318. package/skills/kiokuko-dsh/kiokuko-verification/SKILL.md +20 -0
  319. package/skills/kiokuko-dsh/kiokuko-verification/references/cases.md +11 -0
  320. package/skills/kiokuko-dsh/manifest.json +168 -0
  321. package/skills/kiokuko-dsh/memory-reasoning/SKILL.md +44 -0
  322. package/skills/kiokuko-dsh/one-shot-software-completion/SKILL.md +113 -0
  323. package/skills/kiokuko-dsh/one-shot-software-completion/references/boundaries-and-lifecycle.md +70 -0
  324. package/skills/kiokuko-dsh/one-shot-software-completion/references/discovery-and-scope.md +71 -0
  325. package/skills/kiokuko-dsh/one-shot-software-completion/references/failure-recovery.md +43 -0
  326. package/skills/kiokuko-dsh/one-shot-software-completion/references/verification-and-completion.md +73 -0
  327. package/skills/kiokuko-dsh/veteran-programmer-skill/SKILL.md +66 -0
@@ -0,0 +1,1417 @@
1
+ import { emitKeypressEvents } from 'node:readline';
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";
10
+ export { textWidth, fitText } from "./editor.js";
11
+ import { readClipboardImage, writeClipboardText } from "./clipboard.js";
12
+ import { MAX_IMAGES, parseImage } from "../agent/images.js";
13
+ import { LineSource } from "./lines.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: '承認' }];
17
+ export const COMMANDS = [
18
+ { value: '/connect', label: '/connect', detail: 'プロバイダーに接続' },
19
+ { value: '/models', label: '/models', 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 <番号> で全文' },
26
+ { value: '/allow', label: '/allow', detail: '承認ポリシー (all / workspace / none)' },
27
+ { value: '/keys', label: '/keys', detail: '保存済みAPIキー' },
28
+ { value: '/help', label: '/help', detail: '操作ガイド' },
29
+ { value: '/exit', label: '/exit', detail: '終了' },
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
+ }
37
+ const LOGO = [
38
+ '███╗ ███╗ ██████╗ ██╗ ██╗ ██╗ ██╗',
39
+ '████╗ ████║ ██╔══██╗ ██║ ██╔╝ ██║ ██║',
40
+ '██╔████╔██║ ████╗ ██║ ██║ █████╔╝ ███████║',
41
+ '██║╚██╔╝██║██╔═██╗ ██║ ██║ ██╔═██╗ ██╔══██║',
42
+ '██║ ╚═╝ ██║╚████╔╝ ██████╔╝ ██║ ██╗ ██║ ██║',
43
+ '╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝',
44
+ ];
45
+ const logoForWidth = (width) => width >= Math.max(...LOGO.map(textWidth)) ? LOGO : ['MoDKH'];
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' };
49
+ /** Every term must appear in any order, so "seek deep" finds deepseek. Pinned rows always survive. */
50
+ function matching(choices, query) {
51
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
52
+ return choices.filter(c => c.pinned || terms.every(t => `${c.label} ${c.value} ${c.detail ?? ''}`.toLowerCase().includes(t)));
53
+ }
54
+ /** Non-TTY / screen-reader mode preserves the line protocol and never emits ANSI. */
55
+ class PlainTerminal {
56
+ interactive = false;
57
+ lines = new LineSource();
58
+ reasoning = '';
59
+ write(text) { process.stdout.write(text); }
60
+ showPage(title, text) {
61
+ this.write(`${title}\n\n${text}\n`);
62
+ return Promise.resolve();
63
+ }
64
+ next(signal) { return this.lines.next(signal); }
65
+ unread(line) { this.lines.unread(line); }
66
+ setModel(_model) { }
67
+ /** Line mode cannot update a status line, so reasoning is printed once when the step moves on. */
68
+ setReasoning(delta) {
69
+ if (delta !== null) {
70
+ this.reasoning = (this.reasoning + delta).slice(-8_000);
71
+ return;
72
+ }
73
+ const text = this.reasoning.trimEnd();
74
+ this.reasoning = '';
75
+ if (text)
76
+ this.write(`\n(推論)\n${text}\n`);
77
+ }
78
+ /** Line mode has no footer; report the same totals once so piped runs stay observable. */
79
+ setUsage(usage) {
80
+ const line = usageFooter(usage, 120);
81
+ if (line)
82
+ this.write(`\n(使用量: ${line})\n`);
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
+ }
102
+ close() { this.lines.close(); }
103
+ ask(title, signal) { this.write(`${title}\n`); return this.next(signal); }
104
+ confirm(title, signal) { return this.ask(title + ' [y/N]', signal); }
105
+ async choose(title, choices, query = '') {
106
+ for (;;) {
107
+ const matches = matching(choices, query);
108
+ this.write(`${title}\n`);
109
+ matches.forEach((c, i) => this.write(`${i + 1}. ${c.label}${c.detail ? ` ${c.detail}` : ''}\n`));
110
+ if (!matches.length)
111
+ this.write('該当するモデルはありません。検索語を変えてください。\n');
112
+ const answer = (await this.ask('番号で選択 / 文字列で検索 / * で全件 / 空行・/cancel で戻る'))?.trim();
113
+ if (!answer || answer === '/cancel')
114
+ return null;
115
+ if (answer.startsWith('/')) {
116
+ this.unread(answer);
117
+ return null;
118
+ }
119
+ const direct = choices.find(c => c.value === answer);
120
+ if (direct)
121
+ return direct.value;
122
+ if (/^\d+$/.test(answer)) {
123
+ if (matches[Number(answer) - 1])
124
+ return matches[Number(answer) - 1].value;
125
+ this.write('番号が範囲外です。\n');
126
+ }
127
+ else
128
+ query = answer === '*' ? '' : answer;
129
+ }
130
+ }
131
+ }
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;
158
+ /**
159
+ * メインスクリーンに流し込むストリーミングUI。
160
+ * - 完成したトランスクリプト行は一度だけ出力し、その後は端末のスクロールバックへ流れる
161
+ * - 起動時はロゴと入力欄を中央にまとめ、会話開始後は入力欄を最下部に描画する
162
+ * 通常はメインスクリーンを使う。マウス操作で履歴を開く間だけ別画面に切り替える。
163
+ */
164
+ export class TerminalUI {
165
+ interactive = true;
166
+ text = '';
167
+ cursor = 0;
168
+ selection = 0;
169
+ pending;
170
+ queued = [];
171
+ /** 描画を待っている、折り返し前の論理行。 */
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;
184
+ /** まだ改行が来ていない最終行。ライブブロックの一部として再描画する。 */
185
+ partial = '';
186
+ partialKind = 'system';
187
+ started = false;
188
+ usageVisible = false;
189
+ delegationCount = 0;
190
+ sidebarPainted = false;
191
+ /** 会話開始前の案内行(ウェルカムブロックに表示し、会話開始時に本文へ流す)。 */
192
+ bootLines = [];
193
+ bootFlushed = false;
194
+ /** 現在のコントロール範囲の先頭行(次の確定行を書き込む絶対行)。0 は未初期化(=最下段扱い)。 */
195
+ streamRow = 0;
196
+ /** 最後に出した絶対カーソルの物理行(消去の起点)。 */
197
+ cursorRow = 0;
198
+ /** リサイズ直後の1回だけ画面全体を消す。 */
199
+ clearPending = false;
200
+ model = null;
201
+ activity = null;
202
+ followup;
203
+ subagent = null;
204
+ subagentStarted = 0;
205
+ activityStarted = 0;
206
+ progressTimer;
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;
212
+ closed = false;
213
+ paste = false;
214
+ pasteBuffer = '';
215
+ pasteBytes = 0;
216
+ previousInput = '';
217
+ editorScroll = 0;
218
+ images = [];
219
+ clipboardTask;
220
+ inputNotice = '';
221
+ /** Current step's reasoning text, drawn above the composer while it streams. */
222
+ reasoning = '';
223
+ clipboardReader;
224
+ hiddenCompletion = false;
225
+ previousRaw;
226
+ color;
227
+ input;
228
+ output;
229
+ cwd;
230
+ colorizer = new TranscriptColorizer();
231
+ colorizerState = { mode: 'text', inDiff: false, inToolOutput: false };
232
+ palette = paletteFor('dark');
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;
236
+ backgroundProbe = false;
237
+ /** 背景プローブ中(返信待ち)。時間による入力抑制には使わない。 */
238
+ backgroundWaiting = false;
239
+ /** 返信チャンク由来のキー入力だけを一時的に握りつぶす。 */
240
+ replySilenced = false;
241
+ /** 返信の先頭(\x1b]11;)から返信完了まで、分割チャンクごとに抑制を続ける。 */
242
+ replyStarted = false;
243
+ replyDone = false;
244
+ constructor(cwd, input = process.stdin, output = process.stdout, options = {}) {
245
+ this.clipboardReader = options.readClipboardImage ?? readClipboardImage;
246
+ this.copyText = options.writeClipboardText ?? writeClipboardText;
247
+ this.cwd = cwd;
248
+ this.input = input;
249
+ this.output = output;
250
+ this.previousRaw = input.isRaw;
251
+ this.color = process.env.NO_COLOR === undefined;
252
+ // 背景プローブの data 購読を readline より先に付ける。返信チャンクからだけ
253
+ // キー入力を落とし、ユーザーの打鍵はいつでも通常通り処理する。
254
+ if (this.color && input.isTTY === true)
255
+ this.probeBackground();
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);
266
+ input.setRawMode(true);
267
+ input.on('keypress', this.keypress);
268
+ input.on('end', this.onEnd);
269
+ output.on('resize', this.onResize);
270
+ process.on('exit', this.close);
271
+ input.resume();
272
+ output.write('\x1b[?2004h' + (this.mouseInput ? '\x1b[?1002h\x1b[?1006h' : ''));
273
+ // 起動時は一度だけ画面を消す(前回実行の残りを見せない)。
274
+ this.clearPending = true;
275
+ if (this.backgroundProbe)
276
+ this.output.write('\x1b]11;?\x1b\\');
277
+ this.render();
278
+ }
279
+ /**
280
+ * OSC 11 で端末の背景色を問い合わせる。返信がなければダーク扱い(既定パレット)。
281
+ * 返信バイトを readline が文字入力として流し込むので、返信を含むチャンクから
282
+ * 生じるキー入力だけを握りつぶす。返信が来ない端末では何も握らない(CIでも安全)。
283
+ */
284
+ probeBackground() {
285
+ if (this.backgroundProbe)
286
+ return;
287
+ this.backgroundProbe = true;
288
+ this.backgroundWaiting = true;
289
+ let buffer = '';
290
+ let timer;
291
+ const onData = (chunk) => {
292
+ buffer += chunk;
293
+ if (this.backgroundWaiting && buffer.includes('\x1b]11;'))
294
+ this.replyStarted = true;
295
+ if (this.replyStarted && !this.replyDone)
296
+ this.silenceReplyKeys();
297
+ const osc = parseOscBackground(buffer);
298
+ if (osc === null)
299
+ return;
300
+ finishProbe();
301
+ const classified = classifyBackground(osc, process.env);
302
+ if (classified !== null) {
303
+ this.palette = paletteFor(classified);
304
+ this.panelStyle = classified === 'light' ? '48;5;255' : '48;5;235';
305
+ this.panelAccent = PANEL_ACCENT[classified];
306
+ this.render();
307
+ }
308
+ };
309
+ const finishProbe = () => {
310
+ clearTimeout(timer);
311
+ this.backgroundWaiting = false;
312
+ this.replyDone = true;
313
+ this.input.off('data', onData);
314
+ // 分割到着で入力欄に紛れた返信文字があれば取り除く(単一チャンクは握りつぶし済み)。
315
+ const tail = /\x1b\]11;([^\x07\x1b]*)/.exec(buffer)?.[1];
316
+ if (tail && this.text.includes(tail)) {
317
+ this.text = this.text.split(tail).join('');
318
+ this.cursor = Math.min(this.cursor, Math.max(0, this.text.length));
319
+ this.render();
320
+ }
321
+ };
322
+ this.input.on('data', onData);
323
+ timer = setTimeout(finishProbe, 250);
324
+ }
325
+ /** 返信チャンクから生じるキー入力を、現在の入力処理の終わりまで握りつぶす。 */
326
+ silenceReplyKeys() {
327
+ if (this.replySilenced)
328
+ return;
329
+ this.replySilenced = true;
330
+ queueMicrotask(() => { this.replySilenced = false; });
331
+ }
332
+ /** リサイズ: 画面を作り直す。トランスクリプトはスクロールバックに確定済み。 */
333
+ onResize = () => {
334
+ if (this.closed)
335
+ return;
336
+ this.cancelDrag();
337
+ this.clearPending = true;
338
+ this.streamRow = 1;
339
+ this.cursorRow = 1;
340
+ if (this.page)
341
+ this.renderPage();
342
+ else if (this.history)
343
+ this.renderHistory();
344
+ else
345
+ this.render();
346
+ };
347
+ columns() { return Math.max(12, this.output.columns || 80); }
348
+ rows() { return Math.max(6, this.output.rows || 24); }
349
+ /** 会話中は左ペイン、起動時は中央寄せ用に80列まで。 */
350
+ width() {
351
+ const columns = this.columns();
352
+ if (!this.started)
353
+ return Math.max(8, Math.min(columns - 2, 80));
354
+ return this.hasUsagePane() ? columns - SIDEBAR_WIDTH - 2 : columns;
355
+ }
356
+ write(text, kind = 'system') { this.appendTranscript(text, kind); this.render(); }
357
+ setModel(model) { this.model = model; this.render(); }
358
+ setActivity(activity) {
359
+ if (this.closed || this.activity === activity)
360
+ return;
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();
450
+ this.render();
451
+ }
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
+ }
469
+ /** Accumulate one reasoning delta, or flush the finished block into the transcript with `null`. */
470
+ setReasoning(delta) {
471
+ if (delta !== null) {
472
+ this.reasoning = (this.reasoning + delta).slice(-20_000);
473
+ this.render();
474
+ return;
475
+ }
476
+ const text = this.reasoning.trimEnd();
477
+ this.reasoning = '';
478
+ if (text)
479
+ this.appendTranscript(`\n(推論)\n${text}\n`, 'reasoning');
480
+ this.render();
481
+ }
482
+ unread(line) { this.queued.unshift(line); }
483
+ restoreDraft(text) {
484
+ this.text = text;
485
+ this.cursor = chars(text).length;
486
+ this.render();
487
+ }
488
+ get imageCount() { return this.images.length; }
489
+ takeImages() { const images = this.images; this.images = []; this.render(); return images; }
490
+ next(signal) { return this.wait('何を調べますか? / でコマンド', undefined, '', signal, false, true); }
491
+ ask(title, signal, secret = false) { return this.wait(title, undefined, '', signal, secret); }
492
+ confirm(title, signal) { return this.wait(title, APPROVAL_CHOICES, '', signal); }
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
+ }
507
+ wait(title, choices, query = '', signal, secret = false, composer = false) {
508
+ if (signal?.aborted || this.closed)
509
+ return Promise.resolve(null);
510
+ if (this.page || this.pending)
511
+ throw new Error('端末の入力待ちは同時に1件だけです');
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;
520
+ this.selection = 0;
521
+ this.hiddenCompletion = false;
522
+ this.editorScroll = 0;
523
+ this.inputNotice = '';
524
+ return new Promise(resolve => {
525
+ const abort = () => finish(null);
526
+ const finish = (value) => {
527
+ signal?.removeEventListener('abort', abort);
528
+ this.clipboardTask?.abort();
529
+ this.clipboardTask = undefined;
530
+ this.paste = false;
531
+ this.pasteBuffer = '';
532
+ this.pasteBytes = 0;
533
+ if (composer && value?.trim() && !isChatCommand(value))
534
+ this.previousInput = value;
535
+ if (value === null && composer)
536
+ this.images = [];
537
+ this.pending = undefined;
538
+ this.text = draft?.text ?? '';
539
+ this.cursor = draft?.cursor ?? 0;
540
+ this.editorScroll = draft?.scroll ?? 0;
541
+ this.inputNotice = draft?.notice ?? '';
542
+ this.render();
543
+ resolve(value);
544
+ };
545
+ this.pending = { title, choices, finish, secret, composer };
546
+ signal?.addEventListener('abort', abort, { once: true });
547
+ this.render();
548
+ });
549
+ }
550
+ options() {
551
+ if (this.pending?.secret)
552
+ return undefined;
553
+ if (this.pending?.choices) {
554
+ const visible = matching(this.pending.choices, this.text);
555
+ // Pinned rows are actions: they stay on top so a bare Enter cannot pick an arbitrary model.
556
+ return [...visible.filter(c => c.pinned), ...visible.filter(c => !c.pinned)];
557
+ }
558
+ if (this.pending && !this.hiddenCompletion && this.text.startsWith('/') && !(/\s/.test(this.text)))
559
+ return matching(COMMANDS, this.text);
560
+ return undefined;
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
+ }
591
+ insertText(value) {
592
+ if (this.pending?.choices === APPROVAL_CHOICES || this.replySilenced)
593
+ return; // OSC 返信の取り込みを入力にしない
594
+ const normalized = clean(value.replace(/\r\n?/g, '\n').replace(/\t/g, ' '));
595
+ const added = chars((this.pending?.composer || (!this.pending && this.followup)) ? normalized : normalized.replace(/\n/g, ' '));
596
+ const parts = chars(this.text);
597
+ const next = parts.slice(0, this.cursor).concat(added, parts.slice(this.cursor)).join('');
598
+ if (Buffer.byteLength(next) > MAX_INPUT_BYTES) {
599
+ this.inputNotice = '入力は128 KiB以内にしてください';
600
+ return;
601
+ }
602
+ this.text = next;
603
+ this.cursor += added.length;
604
+ this.selection = 0;
605
+ this.hiddenCompletion = false;
606
+ this.inputNotice = '';
607
+ }
608
+ async pasteImage() {
609
+ const pending = this.pending;
610
+ if (!pending?.composer || pending.secret || this.clipboardTask)
611
+ return;
612
+ if (this.images.length >= MAX_IMAGES) {
613
+ this.inputNotice = `添付画像は最大${MAX_IMAGES}枚です`;
614
+ this.render();
615
+ return;
616
+ }
617
+ const controller = new AbortController();
618
+ this.clipboardTask = controller;
619
+ this.inputNotice = '画像を読込中…';
620
+ this.render();
621
+ try {
622
+ const image = parseImage(await this.clipboardReader(controller.signal));
623
+ if (controller.signal.aborted || this.pending !== pending || this.closed)
624
+ return;
625
+ this.images.push(image);
626
+ this.inputNotice = '';
627
+ }
628
+ catch (e) {
629
+ if (!controller.signal.aborted && this.pending === pending)
630
+ this.inputNotice = e instanceof Error ? e.message : '画像の読み取りに失敗しました';
631
+ }
632
+ finally {
633
+ if (this.clipboardTask === controller)
634
+ this.clipboardTask = undefined;
635
+ this.render();
636
+ }
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
+ }
854
+ onEnd = () => { this.pending?.finish(null); this.close(); };
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
+ }
874
+ if (key.name === 'paste-start') {
875
+ this.paste = true;
876
+ this.pasteBuffer = '';
877
+ this.pasteBytes = 0;
878
+ return;
879
+ }
880
+ if (key.name === 'paste-end') {
881
+ this.paste = false;
882
+ if ((this.pending || this.followup) && this.pasteBytes <= MAX_INPUT_BYTES)
883
+ this.insertText(this.pasteBuffer);
884
+ else if (this.pasteBytes > MAX_INPUT_BYTES)
885
+ this.inputNotice = '貼り付けるテキストは128 KiB以内にしてください';
886
+ this.pasteBuffer = '';
887
+ this.pasteBytes = 0;
888
+ this.render();
889
+ return;
890
+ }
891
+ if (this.paste) {
892
+ this.pasteBytes += Buffer.byteLength(value ?? '');
893
+ if (this.pasteBytes <= MAX_INPUT_BYTES)
894
+ this.pasteBuffer += value ?? '';
895
+ return;
896
+ }
897
+ if (key.ctrl && key.name === 'c') {
898
+ this.clipboardTask?.abort();
899
+ this.clipboardTask = undefined;
900
+ this.inputNotice = '';
901
+ if (process.listenerCount('SIGINT') > 0)
902
+ process.emit('SIGINT');
903
+ else if (this.pending?.choices || this.text || this.images.length) {
904
+ if (this.pending?.choices)
905
+ this.pending.finish(null);
906
+ else {
907
+ this.text = '';
908
+ this.cursor = 0;
909
+ this.images = [];
910
+ this.render();
911
+ }
912
+ }
913
+ else
914
+ this.pending?.finish(null);
915
+ return;
916
+ }
917
+ // 返信チャンク(OSC 応答)から生じたキー入力だけを握りつぶす。Ctrl+C は通す。
918
+ if (this.replySilenced && !(key.ctrl && key.name === 'c'))
919
+ return;
920
+ const pending = this.pending;
921
+ if (!pending && !this.followup)
922
+ return;
923
+ const composer = pending ? pending.composer : true;
924
+ if (key.ctrl && key.name === 'v') {
925
+ void this.pasteImage();
926
+ return;
927
+ }
928
+ if (key.ctrl && key.name === 'x' && pending?.composer) {
929
+ this.clipboardTask?.abort();
930
+ this.clipboardTask = undefined;
931
+ this.images.pop();
932
+ this.inputNotice = '';
933
+ this.render();
934
+ return;
935
+ }
936
+ const options = this.options();
937
+ const files = this.fileOptions();
938
+ if (key.name === 'escape' || key.ctrl && key.name === 'd') {
939
+ if (pending?.choices)
940
+ pending.finish(null);
941
+ else if (files && key.name === 'escape') {
942
+ files.dismissed = true;
943
+ this.render();
944
+ }
945
+ else if (options?.length && key.name === 'escape') {
946
+ this.hiddenCompletion = true;
947
+ this.render();
948
+ }
949
+ else if (!this.text && key.ctrl)
950
+ pending?.finish(null);
951
+ return;
952
+ }
953
+ const newline = composer && (value === '\n' || key.ctrl && key.name === 'j' || (key.name === 'return' || key.name === 'enter') && (key.shift || key.meta));
954
+ if (newline)
955
+ this.insertText('\n');
956
+ else if (options && (key.name === 'up' || key.name === 'down')) {
957
+ this.selection = options.length ? (this.selection + (key.name === 'down' ? 1 : -1) + options.length) % options.length : 0;
958
+ }
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);
971
+ }
972
+ else if (key.name === 'return' || key.name === 'enter' || key.name === 'tab') {
973
+ if (this.clipboardTask) {
974
+ this.inputNotice = '画像の読込中です。完了後にEnterで送信';
975
+ this.render();
976
+ return;
977
+ }
978
+ const selected = options?.[this.selection];
979
+ if (key.name === 'tab') {
980
+ const candidate = files?.candidates[files.selected];
981
+ if (files && candidate)
982
+ this.completeFile(files.mention, candidate);
983
+ else if (selected && !pending?.choices) {
984
+ this.text = selected.value;
985
+ this.cursor = chars(this.text).length;
986
+ }
987
+ }
988
+ else if (pending?.choices) {
989
+ if (selected)
990
+ pending.finish(selected.value);
991
+ }
992
+ else if (pending)
993
+ pending.finish(selected?.value ?? this.text);
994
+ else
995
+ this.sendFollowup();
996
+ }
997
+ else if (key.name === 'left')
998
+ this.cursor = Math.max(0, this.cursor - 1);
999
+ else if (key.name === 'right')
1000
+ this.cursor = Math.min(chars(this.text).length, this.cursor + 1);
1001
+ else if (key.name === 'home' || key.ctrl && key.name === 'a')
1002
+ this.cursor = lineEdge(this.text, this.cursor, 'start');
1003
+ else if (key.name === 'end' || key.ctrl && key.name === 'e')
1004
+ this.cursor = lineEdge(this.text, this.cursor, 'end');
1005
+ else if (key.ctrl && key.name === 'u') {
1006
+ this.text = '';
1007
+ this.cursor = 0;
1008
+ this.inputNotice = '';
1009
+ }
1010
+ else if (key.name === 'backspace' || key.name === 'delete') {
1011
+ const parts = chars(this.text);
1012
+ if (key.name === 'backspace' && this.cursor > 0)
1013
+ parts.splice(--this.cursor, 1);
1014
+ else if (key.name === 'delete')
1015
+ parts.splice(this.cursor, 1);
1016
+ this.text = parts.join('');
1017
+ this.selection = 0;
1018
+ this.hiddenCompletion = false;
1019
+ }
1020
+ else if (value && !key.ctrl && !key.meta)
1021
+ this.insertText(value);
1022
+ this.render();
1023
+ };
1024
+ /**
1025
+ * トランスクリプトへ追記する。完成行を出力待ちキューへ。装飾と折り返しは描画時に行う。
1026
+ * 会話の始まり(`▶`)を検出したら、それ以降の行を広めの幅で折り返す。
1027
+ */
1028
+ appendTranscript(text, kind) {
1029
+ let source = (this.partial + text).replace(/\r\n?/g, '\n');
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))
1034
+ this.started = true;
1035
+ for (;;) {
1036
+ const at = source.indexOf('\n');
1037
+ if (at < 0) {
1038
+ this.partial = source;
1039
+ this.partialKind = lineKind;
1040
+ break;
1041
+ }
1042
+ const logicalLine = source.slice(0, at);
1043
+ source = source.slice(at + 1);
1044
+ // 会話が始まる前の案内行はウェルカムブロックへ(会話開始時に一括で出力する)。
1045
+ if (!this.started)
1046
+ this.bootLines.push(logicalLine);
1047
+ else
1048
+ this.queue.push({ text: logicalLine, kind: lineKind });
1049
+ lineKind = kind;
1050
+ }
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
+ }
1067
+ paint(text, code) { return this.color ? `\x1b[${code}m${text}\x1b[0m` : text; }
1068
+ /**
1069
+ * 1フレームの描画。
1070
+ * 1) 前回のライブブロック(最下部)を消去。伸びた分は先にスクロールして確定させる
1071
+ * 2) 確定したトランスクリプト行を出力(はみ出した行はスクロールバックへ確定)
1072
+ * 3) ライブブロックを、起動時は縦中央、会話中は最下段に再描画
1073
+ * 再描画は最下部ブロックに限るため、過去の履歴が端末のスクロールバックに蓄積する。
1074
+ */
1075
+ render = () => {
1076
+ // Keep mouse coordinates stable while a response is still streaming under the drag.
1077
+ if (this.closed || this.page || this.history || this.drag)
1078
+ return;
1079
+ const rows = this.rows();
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));
1085
+ this.colorizerState = this.colorizer.state();
1086
+ // 起動時の案内だけを履歴に残す。ロゴはウェルカム画面の一部。
1087
+ if (this.started && !this.bootFlushed) {
1088
+ this.bootFlushed = true;
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
+ }));
1093
+ this.bootLines = [];
1094
+ }
1095
+ // --- ライブブロック(最下部)を構成する ---
1096
+ const displayText = this.pending?.secret ? '•'.repeat(chars(this.text).length) : this.text;
1097
+ const composer = !this.pending || this.pending.composer;
1098
+ const editor = editorLayout(displayText, this.editorWidth());
1099
+ const cursor = editor.positions[Math.min(this.cursor, editor.positions.length - 1)];
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));
1108
+ const options = this.options();
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;
1121
+ // ライブの推論は見出し含めて表示。はみ出すときは古い行(先頭)から落とす。
1122
+ const reasoningText = this.reasoning.trimEnd() === '' ? [] :
1123
+ transcriptLines(`(推論)\n${this.reasoning.trimEnd()}`, width);
1124
+ const reservedForBody = 1 /* divider */ + inputRows + fileRows + 4 /* status/hints/cwd+footer */ + (options ? 2 : 0) + partialCount + stackedHeight;
1125
+ const maxReasoning = Math.max(0, Math.min(rows - reservedForBody - 1, 24));
1126
+ const liveReasoning = reasoningText.length === 0 ? [] :
1127
+ reasoningText.slice(Math.max(0, reasoningText.length - maxReasoning))
1128
+ .map(line => ({ ...line, painted: this.paint(fitText(line.text, width), this.palette.reasoning) }));
1129
+ const optionsLines = [];
1130
+ if (options) {
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));
1133
+ const start = Math.max(0, Math.min(this.selection - height + 1, options.length - height));
1134
+ optionsLines.push({ text: this.pending?.choices ? this.pending.title : 'Commands', style: READABLE_TEXT_STYLE });
1135
+ if (!options.length)
1136
+ optionsLines.push({ text: '該当なし — 検索語を変える / Esc で戻る', style: '2' });
1137
+ const matched = options.filter(choice => !choice.pinned).length;
1138
+ options.slice(start, start + height).forEach((choice, i) => {
1139
+ const active = start + i === this.selection;
1140
+ const detail = choice.pinned && this.pending?.choices
1141
+ ? `${this.text ? `${matched}件一致` : `${matched}件`} · 空白区切りは語順自由` : choice.detail ?? '';
1142
+ const label = `${active ? '›' : ' '} ${choice.label} ${detail}`;
1143
+ optionsLines.push({ text: label, style: active ? '97;44' : choice.pinned ? '2' : '' });
1144
+ });
1145
+ }
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
+ }];
1153
+ const editorStart = partialCount + liveReasoning.length + lines.length;
1154
+ // 入力欄が表示行数を超えたら、カーソルが常に窓内に来るようにスクロールする。
1155
+ if (cursor.row < this.editorScroll)
1156
+ this.editorScroll = cursor.row;
1157
+ if (cursor.row >= this.editorScroll + inputRows)
1158
+ this.editorScroll = cursor.row - inputRows + 1;
1159
+ this.editorScroll = Math.max(0, Math.min(this.editorScroll, Math.max(0, editor.lines.length - inputRows)));
1160
+ for (let i = 0; i < inputRows; i++) {
1161
+ const line = editor.lines[this.editorScroll + i] ?? '';
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
+ });
1177
+ }
1178
+ const attachments = composer && this.images.length ? ` · 画像${this.images.length}枚 (Ctrl+Xで削除)` : '';
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';
1198
+ const usageWidth = textWidth(usageStatus);
1199
+ const cwdWidth = textWidth(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;
1203
+ lines.push({ text: bottom, style: '2' });
1204
+ const styled = (row, maxWidth = width) => {
1205
+ const fitted = fitText(row.text, maxWidth);
1206
+ if (row.text.startsWith('│ ')) {
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}` : ''}`);
1209
+ }
1210
+ return this.paint(fitted, row.style);
1211
+ };
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
+ // 会話が始まる前のウェルカム: ロゴ+案内を中央に整える。
1218
+ const marginStyled = (row) => marginPrefix + styled(row);
1219
+ let body = [];
1220
+ let editorStartIdx = editorStart;
1221
+ if (!this.started) {
1222
+ // タイトルとロゴをコンテンツ幅の中央に揃える。
1223
+ const widthCenter = (line) => {
1224
+ const pad = Math.max(0, Math.floor((width - textWidth(line)) / 2));
1225
+ return ' '.repeat(pad) + line;
1226
+ };
1227
+ const welcome = [
1228
+ { text: widthCenter('MoDKH · Coding Harness'), style: '1' },
1229
+ ...logoForWidth(width).map(line => ({ text: widthCenter(line), style: ACCENT })),
1230
+ ...this.bootLines.slice(-8).flatMap(line => wrap(line, width).map(text => ({ text, style: '' }))),
1231
+ ];
1232
+ // ロゴと入力欄は一つのまとまり。余白を両者の間に入れない。
1233
+ const midPad = 1;
1234
+ body = [
1235
+ ...welcome.map(row => marginStyled(row)),
1236
+ ...Array.from({ length: midPad }, () => marginPrefix),
1237
+ ...partialLines,
1238
+ ...liveReasoning.map(row => marginPrefix + row.painted),
1239
+ // lines にはコマンドメニュー(optionsLines)が含まれる。二重に展開しない。
1240
+ ...controls,
1241
+ ];
1242
+ editorStartIdx = welcome.length + midPad + partialCount + liveReasoning.length + optionsLines.length + 1;
1243
+ }
1244
+ else {
1245
+ // 会話中は余白を付けない: 画面上の位置とコピーした文字列を一致させる。
1246
+ body = [
1247
+ ...partialLines,
1248
+ ...liveReasoning.map(row => row.painted),
1249
+ // lines にはコマンドメニュー(optionsLines)が含まれる。二重に展開しない。
1250
+ ...controls,
1251
+ ];
1252
+ }
1253
+ // 最下部ブロックは1行以上の余白を残して画面に収める。はみ出すときは上侧から落とす。
1254
+ const overflow = Math.max(0, body.length - (rows - 1));
1255
+ if (overflow > 0) {
1256
+ body = body.slice(overflow);
1257
+ editorStartIdx = Math.max(0, editorStartIdx - overflow);
1258
+ }
1259
+ const liveCount = body.length;
1260
+ // --- 描画。消去は「最終トランスクリプト行の下一行」から下端まで。
1261
+ // ライブブロックと空き行だけを消すので、過去の行はスクロールバックに確定したままである。
1262
+ // streamRow は未初期化のとき最下段(起動時のシェルプロンプト位置を想定)。
1263
+ let out = '';
1264
+ // サイズ変更や起動直後は画面を一度消して制御範囲を作り直す(残りを見せない)。
1265
+ if (this.clearPending) {
1266
+ this.clearPending = false;
1267
+ this.scrollTranscriptRows(rows);
1268
+ this.streamRow = 1;
1269
+ this.cursorRow = 1;
1270
+ out += '\x1b[2J\x1b[1;1H';
1271
+ }
1272
+ else if (this.sidebarPainted) {
1273
+ // 右欄を履歴に巻き込む前に消し、左側を描いた後で元の位置へ戻す。
1274
+ out += this.eraseSidebar(rows, rightStart + 1);
1275
+ }
1276
+ const streamRow = this.streamRow >= 1 ? Math.max(1, Math.min(rows, this.streamRow)) : rows;
1277
+ out += `\x1b[${streamRow};1H\x1b[J`;
1278
+ // 確定行の出力。ライブブロックの上端を越えそうなら先にスクロールして確定させる。
1279
+ const streamBottom = Math.max(1, rows - liveCount);
1280
+ let r = streamRow;
1281
+ for (const line of stream) {
1282
+ if (r > streamBottom) {
1283
+ const scrolls = Math.min(r - streamBottom, rows);
1284
+ out += `\x1b[${rows};1H` + '\n'.repeat(scrolls);
1285
+ r -= scrolls;
1286
+ this.scrollTranscriptRows(scrolls);
1287
+ }
1288
+ out += `\x1b[${r};1H\x1b[K${line.painted}\r\n`;
1289
+ this.transcriptRows.set(r, line);
1290
+ r++;
1291
+ }
1292
+ this.streamRow = Math.max(1, Math.min(rows, r));
1293
+ // 起動時はグループ全体を縦中央へ。会話中は最下段に必要な余白を空ける。
1294
+ const liveStart = this.started ? Math.max(1, rows - liveCount + 1)
1295
+ : Math.max(1, Math.floor((rows - liveCount) / 2) + 1);
1296
+ if (liveStart < this.streamRow) {
1297
+ const scrolls = Math.min(rows, this.streamRow - liveStart);
1298
+ out += `\x1b[${rows};1H` + '\n'.repeat(scrolls);
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
+ }
1308
+ }
1309
+ for (let i = 0; i < liveCount; i++) {
1310
+ out += `\x1b[${liveStart + i};1H\x1b[K${body[i]}` + (i === liveCount - 1 ? '' : '\r\n');
1311
+ }
1312
+ if (showUsage)
1313
+ out += this.drawSidebar(rows, columns, this.sidebarLines(rows, usageRows));
1314
+ this.sidebarPainted = showUsage;
1315
+ const cursorLiveRow = Math.min(rows, liveStart + editorStartIdx + (cursor.row - this.editorScroll));
1316
+ const cursorCol = Math.min(columns, controlMargin + 3 + cursor.column);
1317
+ out += `\x1b[${cursorLiveRow};${cursorCol}H` + (this.pending || editingFollowup ? '\x1b[?25h' : '\x1b[?25l');
1318
+ this.cursorRow = cursorLiveRow;
1319
+ this.output.write(out);
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
+ }
1370
+ /** 未完了行の色分け用に、完成行までの状態を複製する。 */
1371
+ fork() {
1372
+ const clone = new TranscriptColorizer();
1373
+ clone.restore(this.colorizerState);
1374
+ return clone;
1375
+ }
1376
+ close = () => {
1377
+ if (this.closed)
1378
+ return;
1379
+ this.dismissPage();
1380
+ this.leaveHistory(false);
1381
+ this.cancelDrag();
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);
1390
+ this.clipboardTask?.abort();
1391
+ this.clipboardTask = undefined;
1392
+ this.images = [];
1393
+ this.pending?.finish(null);
1394
+ this.input.removeListener('keypress', this.keypress);
1395
+ this.input.removeListener('end', this.onEnd);
1396
+ this.output.removeListener('resize', this.onResize);
1397
+ process.removeListener('exit', this.close);
1398
+ this.input.setRawMode(this.previousRaw);
1399
+ this.input.pause();
1400
+ // 入力欄(ライブブロック)を消して、シェルのプロンプトが新しい行に出るようにする。
1401
+ const rows = this.rows();
1402
+ const eraseRow = Math.min(rows, this.streamRow >= 1 ? this.streamRow : rows);
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
+ }
1407
+ const up = base - eraseRow;
1408
+ if (up > 0)
1409
+ this.output.write(`\x1b[${up}A`);
1410
+ this.output.write('\r\x1b[J');
1411
+ this.output.write('\x1b[0m\x1b[?25h\x1b[?2004l\r\n');
1412
+ };
1413
+ }
1414
+ export function createTerminal(cwd) {
1415
+ return process.stdin.isTTY && process.stdout.isTTY && process.env.TERM !== 'dumb' && process.env.MODKH_PLAIN !== '1'
1416
+ ? new TerminalUI(cwd) : new PlainTerminal();
1417
+ }