modkh 0.0.0-stage → 0.1.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.
- package/README.md +24 -2
- package/dist/agent/bundled-skills.d.ts +13 -0
- package/dist/agent/bundled-skills.js +95 -0
- package/dist/agent/images.d.ts +10 -0
- package/dist/agent/images.js +33 -0
- package/dist/agent/loop.d.ts +56 -0
- package/dist/agent/loop.js +155 -0
- package/dist/agent/skills.d.ts +20 -0
- package/dist/agent/skills.js +169 -0
- package/dist/agent/types.d.ts +132 -0
- package/dist/agent/types.js +12 -0
- package/dist/cli/agents.d.ts +8 -0
- package/dist/cli/agents.js +12 -0
- package/dist/cli/approval.d.ts +27 -0
- package/dist/cli/approval.js +62 -0
- package/dist/cli/catalog.d.ts +39 -0
- package/dist/cli/catalog.js +76 -0
- package/dist/cli/chat.d.ts +18 -0
- package/dist/cli/chat.js +733 -0
- package/dist/cli/clipboard.d.ts +9 -0
- package/dist/cli/clipboard.js +54 -0
- package/dist/cli/color.d.ts +42 -0
- package/dist/cli/color.js +176 -0
- package/dist/cli/config.d.ts +41 -0
- package/dist/cli/config.js +188 -0
- package/dist/cli/editor.d.ts +16 -0
- package/dist/cli/editor.js +77 -0
- package/dist/cli/keys.d.ts +18 -0
- package/dist/cli/keys.js +82 -0
- package/dist/cli/language.d.ts +1 -0
- package/dist/cli/language.js +105 -0
- package/dist/cli/limits.d.ts +13 -0
- package/dist/cli/limits.js +19 -0
- package/dist/cli/lines.d.ts +18 -0
- package/dist/cli/lines.js +80 -0
- package/dist/cli/models.d.ts +4 -0
- package/dist/cli/models.js +69 -0
- package/dist/cli/permissions.d.ts +25 -0
- package/dist/cli/permissions.js +30 -0
- package/dist/cli/plugins.d.ts +1 -0
- package/dist/cli/plugins.js +53 -0
- package/dist/cli/providers.d.ts +46 -0
- package/dist/cli/providers.js +76 -0
- package/dist/cli/terminal.d.ts +143 -0
- package/dist/cli/terminal.js +742 -0
- package/dist/cli/usage.d.ts +29 -0
- package/dist/cli/usage.js +75 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +164 -0
- package/dist/language/catalog.d.ts +44 -0
- package/dist/language/catalog.js +100 -0
- package/dist/language/commonlisp-bundled.d.ts +11 -0
- package/dist/language/commonlisp-bundled.js +22 -0
- package/dist/language/commonlisp-dependencies.d.ts +16 -0
- package/dist/language/commonlisp-dependencies.js +68 -0
- package/dist/language/commonlisp-install.d.ts +14 -0
- package/dist/language/commonlisp-install.js +213 -0
- package/dist/language/commonlisp-reader.d.ts +17 -0
- package/dist/language/commonlisp-reader.js +47 -0
- package/dist/language/commonlisp-systems.d.ts +3 -0
- package/dist/language/commonlisp-systems.js +32 -0
- package/dist/language/commonlisp-tls.d.ts +10 -0
- package/dist/language/commonlisp-tls.js +51 -0
- package/dist/language/detect.d.ts +29 -0
- package/dist/language/detect.js +103 -0
- package/dist/language/grammars/LICENSE +24 -0
- package/dist/language/grammars/manifest.json +76 -0
- package/dist/language/grammars/tree-sitter-c.wasm +0 -0
- package/dist/language/grammars/tree-sitter-cpp.wasm +0 -0
- package/dist/language/grammars/tree-sitter-css.wasm +0 -0
- package/dist/language/grammars/tree-sitter-html.wasm +0 -0
- package/dist/language/grammars/tree-sitter-javascript.wasm +0 -0
- package/dist/language/grammars/tree-sitter-php.wasm +0 -0
- package/dist/language/grammars/tree-sitter-python.wasm +0 -0
- package/dist/language/grammars/tree-sitter-ruby.wasm +0 -0
- package/dist/language/grammars/tree-sitter-rust.wasm +0 -0
- package/dist/language/grammars/tree-sitter-swift.wasm +0 -0
- package/dist/language/grammars/tree-sitter-tsx.wasm +0 -0
- package/dist/language/grammars/tree-sitter-typescript.wasm +0 -0
- package/dist/language/install.d.ts +50 -0
- package/dist/language/install.js +293 -0
- package/dist/language/lsp/client.d.ts +97 -0
- package/dist/language/lsp/client.js +337 -0
- package/dist/language/lsp/pool.d.ts +67 -0
- package/dist/language/lsp/pool.js +122 -0
- package/dist/language/lsp/service.d.ts +46 -0
- package/dist/language/lsp/service.js +138 -0
- package/dist/language/native.d.ts +8 -0
- package/dist/language/native.js +100 -0
- package/dist/language/platform.d.ts +14 -0
- package/dist/language/platform.js +20 -0
- package/dist/language/positions.d.ts +20 -0
- package/dist/language/positions.js +46 -0
- package/dist/language/syntax/assets.d.ts +9 -0
- package/dist/language/syntax/assets.js +73 -0
- package/dist/language/syntax/parser.d.ts +24 -0
- package/dist/language/syntax/parser.js +144 -0
- package/dist/language/typescript-capability.d.ts +6 -0
- package/dist/language/typescript-capability.js +42 -0
- package/dist/lisp/config.d.ts +16 -0
- package/dist/lisp/config.js +159 -0
- package/dist/lisp/routing.d.ts +5 -0
- package/dist/lisp/routing.js +24 -0
- package/dist/lisp/runtime.d.ts +21 -0
- package/dist/lisp/runtime.js +83 -0
- package/dist/memory/kiokuko.d.ts +32 -0
- package/dist/memory/kiokuko.js +102 -0
- package/dist/memory/mcp.d.ts +38 -0
- package/dist/memory/mcp.js +211 -0
- package/dist/model/ai-sdk.d.ts +27 -0
- package/dist/model/ai-sdk.js +180 -0
- package/dist/model/chatgpt/login.d.ts +42 -0
- package/dist/model/chatgpt/login.js +180 -0
- package/dist/model/chatgpt/responses.d.ts +41 -0
- package/dist/model/chatgpt/responses.js +202 -0
- package/dist/model/chatgpt/tokens.d.ts +11 -0
- package/dist/model/chatgpt/tokens.js +50 -0
- package/dist/model/connection.d.ts +6 -0
- package/dist/model/connection.js +65 -0
- package/dist/model/context.d.ts +9 -0
- package/dist/model/context.js +69 -0
- package/dist/model/factory.d.ts +25 -0
- package/dist/model/factory.js +88 -0
- package/dist/model/fixed.d.ts +17 -0
- package/dist/model/fixed.js +41 -0
- package/dist/model/reasoning.d.ts +16 -0
- package/dist/model/reasoning.js +62 -0
- package/dist/plugins/api.d.ts +60 -0
- package/dist/plugins/api.js +1 -0
- package/dist/plugins/manager.d.ts +34 -0
- package/dist/plugins/manager.js +261 -0
- package/dist/plugins/package.d.ts +13 -0
- package/dist/plugins/package.js +99 -0
- package/dist/plugins/registry.d.ts +8 -0
- package/dist/plugins/registry.js +14 -0
- package/dist/session/store.d.ts +82 -0
- package/dist/session/store.js +285 -0
- package/dist/session/workspace.d.ts +19 -0
- package/dist/session/workspace.js +73 -0
- package/dist/subagents/processes.d.ts +18 -0
- package/dist/subagents/processes.js +73 -0
- package/dist/subagents/request.d.ts +4 -0
- package/dist/subagents/request.js +21 -0
- package/dist/subagents/service.d.ts +39 -0
- package/dist/subagents/service.js +352 -0
- package/dist/subagents/settings.d.ts +10 -0
- package/dist/subagents/settings.js +32 -0
- package/dist/subagents/types.d.ts +43 -0
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/verification.d.ts +31 -0
- package/dist/subagents/verification.js +178 -0
- package/dist/tools/diff.d.ts +6 -0
- package/dist/tools/diff.js +82 -0
- package/dist/tools/edit.d.ts +3 -0
- package/dist/tools/edit.js +152 -0
- package/dist/tools/files.d.ts +6 -0
- package/dist/tools/files.js +96 -0
- package/dist/tools/formal.d.ts +8 -0
- package/dist/tools/formal.js +77 -0
- package/dist/tools/guard.d.ts +7 -0
- package/dist/tools/guard.js +48 -0
- package/dist/tools/job-tools.d.ts +19 -0
- package/dist/tools/job-tools.js +148 -0
- package/dist/tools/jobs.d.ts +77 -0
- package/dist/tools/jobs.js +181 -0
- package/dist/tools/language.d.ts +6 -0
- package/dist/tools/language.js +174 -0
- package/dist/tools/registry.d.ts +28 -0
- package/dist/tools/registry.js +105 -0
- package/dist/tools/run.d.ts +13 -0
- package/dist/tools/run.js +159 -0
- package/dist/tools/search.d.ts +2 -0
- package/dist/tools/search.js +156 -0
- package/dist/tools/shell-process.d.ts +115 -0
- package/dist/tools/shell-process.js +286 -0
- package/dist/tools/skills.d.ts +2 -0
- package/dist/tools/skills.js +46 -0
- package/dist/tools/web.d.ts +24 -0
- package/dist/tools/web.js +386 -0
- package/docs/ci-repair-20261116.md +30 -0
- package/docs/commonlisp-provider-migration.md +22 -0
- package/docs/commonlisp-qlot-recovery.md +28 -0
- package/docs/commonlisp-tls-recovery.md +28 -0
- package/docs/context-efficiency.md +100 -0
- package/docs/input.md +66 -0
- package/docs/languages.md +117 -0
- package/docs/models.md +85 -0
- package/docs/modkh-evidence.json +641 -0
- package/docs/modkh-failure-comparison.json +675 -0
- package/docs/modkh-namespace.md +39 -0
- package/docs/modkh-qlot-evidence.json +37 -0
- package/docs/modkh-verification.md +173 -0
- package/docs/modkh.md +124 -0
- package/docs/presets.md +19 -0
- package/docs/setup.md +112 -0
- package/docs/subagents.md +134 -0
- package/docs/web.md +57 -0
- package/experiments/presets/common-lisp.lisp +38 -0
- package/experiments/presets/css.lisp +38 -0
- package/experiments/presets/formal.lisp +7 -0
- package/experiments/presets/html.lisp +38 -0
- package/experiments/presets/js.lisp +38 -0
- package/experiments/presets/php.lisp +38 -0
- package/experiments/presets/svelte.lisp +38 -0
- package/experiments/presets/tailwindcss.lisp +24 -0
- package/experiments/presets/ts.lisp +38 -0
- package/package.json +49 -4
- package/plugins/modkh-explorer/index.mjs +3 -0
- package/plugins/modkh-explorer/plugin.json +1 -0
- package/plugins/modkh-worker/index.mjs +3 -0
- package/plugins/modkh-worker/plugin.json +1 -0
- package/skills/kiokuko-dsh/LICENSE +21 -0
- package/skills/kiokuko-dsh/coding-ideal-routine-skill/SKILL.md +106 -0
- package/skills/kiokuko-dsh/japanese-translation-for-oss-models/SKILL.md +65 -0
- package/skills/kiokuko-dsh/kiokuko-architecture/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-architecture/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-benchmark/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-benchmark/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-investigate/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-investigate/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-lisp/SKILL.md +390 -0
- package/skills/kiokuko-dsh/kiokuko-review/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-review/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-simple-work/SKILL.md +70 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/SKILL.md +79 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/boundaries-and-ownership.md +52 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/domain-and-types.md +48 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/effects-and-data.md +43 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/kiokuko-patterns.md +314 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/problem-shaping-and-language.md +90 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/protocols-and-idempotency.md +42 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/review-checklist.md +92 -0
- package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/verification.md +45 -0
- package/skills/kiokuko-dsh/kiokuko-skill-authoring/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-skill-authoring/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-soul/SKILL.md +25 -0
- package/skills/kiokuko-dsh/kiokuko-technical-writing/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-technical-writing/references/cases.md +11 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/SKILL.md +64 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/accessibility-and-navigation.md +31 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/async-recovery.md +49 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/forms-and-controls.md +35 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/interaction-feedback.md +34 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/responsive-and-platform.md +38 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/safety-and-review.md +43 -0
- package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/ui-checklist.md +75 -0
- package/skills/kiokuko-dsh/kiokuko-verification/SKILL.md +20 -0
- package/skills/kiokuko-dsh/kiokuko-verification/references/cases.md +11 -0
- package/skills/kiokuko-dsh/manifest.json +168 -0
- package/skills/kiokuko-dsh/memory-reasoning/SKILL.md +44 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/SKILL.md +113 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/references/boundaries-and-lifecycle.md +70 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/references/discovery-and-scope.md +71 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/references/failure-recovery.md +43 -0
- package/skills/kiokuko-dsh/one-shot-software-completion/references/verification-and-completion.md +73 -0
- package/skills/kiokuko-dsh/veteran-programmer-skill/SKILL.md +66 -0
|
@@ -0,0 +1,742 @@
|
|
|
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";
|
|
4
|
+
export { textWidth, fitText } from "./editor.js";
|
|
5
|
+
import { readClipboardImage } from "./clipboard.js";
|
|
6
|
+
import { MAX_IMAGES, parseImage } from "../agent/images.js";
|
|
7
|
+
import { LineSource } from "./lines.js";
|
|
8
|
+
import { TranscriptColorizer, classifyBackground, parseOscBackground, paletteFor, } from "./color.js";
|
|
9
|
+
export const COMMANDS = [
|
|
10
|
+
{ value: '/connect', label: '/connect', detail: 'プロバイダーに接続' },
|
|
11
|
+
{ value: '/models', label: '/models', detail: 'モデルを選択' },
|
|
12
|
+
{ value: '/reasoning', label: '/reasoning', detail: '推論レベル (off/minimal/low/medium/high)' },
|
|
13
|
+
{ value: '/agents', label: '/agents', detail: '子エージェントの一覧・委譲' },
|
|
14
|
+
{ value: '/allow', label: '/allow', detail: '承認ポリシー (all / workspace / none)' },
|
|
15
|
+
{ value: '/keys', label: '/keys', detail: '保存済みAPIキー' },
|
|
16
|
+
{ value: '/help', label: '/help', detail: '操作ガイド' },
|
|
17
|
+
{ value: '/exit', label: '/exit', detail: '終了' },
|
|
18
|
+
];
|
|
19
|
+
const LOGO = [
|
|
20
|
+
'███╗ ███╗ ██████╗ ██╗ ██╗ ██╗ ██╗',
|
|
21
|
+
'████╗ ████║ ██╔══██╗ ██║ ██╔╝ ██║ ██║',
|
|
22
|
+
'██╔████╔██║ ████╗ ██║ ██║ █████╔╝ ███████║',
|
|
23
|
+
'██║╚██╔╝██║██╔═██╗ ██║ ██║ ██╔═██╗ ██╔══██║',
|
|
24
|
+
'██║ ╚═╝ ██║╚████╔╝ ██████╔╝ ██║ ██╗ ██║ ██║',
|
|
25
|
+
'╚═╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝',
|
|
26
|
+
];
|
|
27
|
+
const logoForWidth = (width) => width >= Math.max(...LOGO.map(textWidth)) ? LOGO : ['MoDKH'];
|
|
28
|
+
const ACCENT = '34'; // Use the terminal theme's blue; NO_COLOR is respected by paint().
|
|
29
|
+
/** Every term must appear in any order, so "seek deep" finds deepseek. Pinned rows always survive. */
|
|
30
|
+
function matching(choices, query) {
|
|
31
|
+
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
|
|
32
|
+
return choices.filter(c => c.pinned || terms.every(t => `${c.label} ${c.value} ${c.detail ?? ''}`.toLowerCase().includes(t)));
|
|
33
|
+
}
|
|
34
|
+
/** Non-TTY / screen-reader mode preserves the line protocol and never emits ANSI. */
|
|
35
|
+
class PlainTerminal {
|
|
36
|
+
interactive = false;
|
|
37
|
+
lines = new LineSource();
|
|
38
|
+
reasoning = '';
|
|
39
|
+
write(text) { process.stdout.write(text); }
|
|
40
|
+
next(signal) { return this.lines.next(signal); }
|
|
41
|
+
unread(line) { this.lines.unread(line); }
|
|
42
|
+
setModel(_model) { }
|
|
43
|
+
/** Line mode cannot update a status line, so reasoning is printed once when the step moves on. */
|
|
44
|
+
setReasoning(delta) {
|
|
45
|
+
if (delta !== null) {
|
|
46
|
+
this.reasoning = (this.reasoning + delta).slice(-8_000);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const text = this.reasoning.trimEnd();
|
|
50
|
+
this.reasoning = '';
|
|
51
|
+
if (text)
|
|
52
|
+
this.write(`\n(推論)\n${text}\n`);
|
|
53
|
+
}
|
|
54
|
+
/** Line mode has no footer; report the same totals once so piped runs stay observable. */
|
|
55
|
+
setUsage(usage) {
|
|
56
|
+
const line = usageFooter(usage, 120);
|
|
57
|
+
if (line)
|
|
58
|
+
this.write(`\n(使用量: ${line})\n`);
|
|
59
|
+
}
|
|
60
|
+
close() { this.lines.close(); }
|
|
61
|
+
ask(title, signal) { this.write(`${title}\n`); return this.next(signal); }
|
|
62
|
+
async choose(title, choices, query = '') {
|
|
63
|
+
for (;;) {
|
|
64
|
+
const matches = matching(choices, query);
|
|
65
|
+
this.write(`${title}\n`);
|
|
66
|
+
matches.forEach((c, i) => this.write(`${i + 1}. ${c.label}${c.detail ? ` ${c.detail}` : ''}\n`));
|
|
67
|
+
if (!matches.length)
|
|
68
|
+
this.write('該当するモデルはありません。検索語を変えてください。\n');
|
|
69
|
+
const answer = (await this.ask('番号で選択 / 文字列で検索 / * で全件 / 空行・/cancel で戻る'))?.trim();
|
|
70
|
+
if (!answer || answer === '/cancel')
|
|
71
|
+
return null;
|
|
72
|
+
if (answer.startsWith('/')) {
|
|
73
|
+
this.unread(answer);
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
const direct = choices.find(c => c.value === answer);
|
|
77
|
+
if (direct)
|
|
78
|
+
return direct.value;
|
|
79
|
+
if (/^\d+$/.test(answer)) {
|
|
80
|
+
if (matches[Number(answer) - 1])
|
|
81
|
+
return matches[Number(answer) - 1].value;
|
|
82
|
+
this.write('番号が範囲外です。\n');
|
|
83
|
+
}
|
|
84
|
+
else
|
|
85
|
+
query = answer === '*' ? '' : answer;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const MAX_INPUT_BYTES = 128 * 1024;
|
|
90
|
+
/**
|
|
91
|
+
* メインスクリーンに流し込むストリーミングUI。
|
|
92
|
+
* - 完成したトランスクリプト行は一度だけ出力し、その後は端末のスクロールバックへ流れる
|
|
93
|
+
* - 起動時はロゴと入力欄を中央にまとめ、会話開始後は入力欄を最下部に描画する
|
|
94
|
+
* 代替スクリーン(?1049)は使わない。これが「起動前バッファしか辿れない」問題の原因だった。
|
|
95
|
+
*/
|
|
96
|
+
export class TerminalUI {
|
|
97
|
+
interactive = true;
|
|
98
|
+
text = '';
|
|
99
|
+
cursor = 0;
|
|
100
|
+
selection = 0;
|
|
101
|
+
pending;
|
|
102
|
+
queued = [];
|
|
103
|
+
/** スクロールバックへ確定待ちの完成行(折り返し済み)。 */
|
|
104
|
+
queue = [];
|
|
105
|
+
/** まだ改行が来ていない最終行。ライブブロックの一部として再描画する。 */
|
|
106
|
+
partial = '';
|
|
107
|
+
started = false;
|
|
108
|
+
/** 会話開始前の案内行(ウェルカムブロックに表示し、会話開始時に本文へ流す)。 */
|
|
109
|
+
bootLines = [];
|
|
110
|
+
bootFlushed = false;
|
|
111
|
+
/** 現在のコントロール範囲の先頭行(次の確定行を書き込む絶対行)。0 は未初期化(=最下段扱い)。 */
|
|
112
|
+
streamRow = 0;
|
|
113
|
+
/** 最後に出した絶対カーソルの物理行(消去の起点)。 */
|
|
114
|
+
cursorRow = 0;
|
|
115
|
+
/** リサイズ直後の1回だけ画面全体を消す。 */
|
|
116
|
+
clearPending = false;
|
|
117
|
+
model = null;
|
|
118
|
+
activity = null;
|
|
119
|
+
usage = null;
|
|
120
|
+
closed = false;
|
|
121
|
+
paste = false;
|
|
122
|
+
pasteBuffer = '';
|
|
123
|
+
pasteBytes = 0;
|
|
124
|
+
editorScroll = 0;
|
|
125
|
+
images = [];
|
|
126
|
+
clipboardTask;
|
|
127
|
+
inputNotice = '';
|
|
128
|
+
/** Current step's reasoning text, drawn above the composer while it streams. */
|
|
129
|
+
reasoning = '';
|
|
130
|
+
clipboardReader;
|
|
131
|
+
hiddenCompletion = false;
|
|
132
|
+
previousRaw;
|
|
133
|
+
color;
|
|
134
|
+
input;
|
|
135
|
+
output;
|
|
136
|
+
cwd;
|
|
137
|
+
colorizer = new TranscriptColorizer();
|
|
138
|
+
colorizerState = { mode: 'text', inDiff: false };
|
|
139
|
+
palette = paletteFor('dark');
|
|
140
|
+
panelStyle = '48;5;235';
|
|
141
|
+
backgroundProbe = false;
|
|
142
|
+
/** 背景プローブ中(返信待ち)。時間による入力抑制には使わない。 */
|
|
143
|
+
backgroundWaiting = false;
|
|
144
|
+
/** 返信チャンク由来のキー入力だけを一時的に握りつぶす。 */
|
|
145
|
+
replySilenced = false;
|
|
146
|
+
/** 返信の先頭(\x1b]11;)から返信完了まで、分割チャンクごとに抑制を続ける。 */
|
|
147
|
+
replyStarted = false;
|
|
148
|
+
replyDone = false;
|
|
149
|
+
constructor(cwd, input = process.stdin, output = process.stdout, options = {}) {
|
|
150
|
+
this.clipboardReader = options.readClipboardImage ?? readClipboardImage;
|
|
151
|
+
this.cwd = cwd;
|
|
152
|
+
this.input = input;
|
|
153
|
+
this.output = output;
|
|
154
|
+
this.previousRaw = input.isRaw;
|
|
155
|
+
this.color = process.env.NO_COLOR === undefined;
|
|
156
|
+
// 背景プローブの data 購読を readline より先に付ける。返信チャンクからだけ
|
|
157
|
+
// キー入力を落とし、ユーザーの打鍵はいつでも通常通り処理する。
|
|
158
|
+
if (this.color && input.isTTY === true)
|
|
159
|
+
this.probeBackground();
|
|
160
|
+
emitKeypressEvents(input);
|
|
161
|
+
input.setRawMode(true);
|
|
162
|
+
input.on('keypress', this.keypress);
|
|
163
|
+
input.on('end', this.onEnd);
|
|
164
|
+
output.on('resize', this.onResize);
|
|
165
|
+
process.on('exit', this.close);
|
|
166
|
+
input.resume();
|
|
167
|
+
output.write('\x1b[?2004h');
|
|
168
|
+
// 起動時は一度だけ画面を消す(前回実行の残りを見せない)。
|
|
169
|
+
this.clearPending = true;
|
|
170
|
+
if (this.backgroundProbe)
|
|
171
|
+
this.output.write('\x1b]11;?\x1b\\');
|
|
172
|
+
this.render();
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* OSC 11 で端末の背景色を問い合わせる。返信がなければダーク扱い(既定パレット)。
|
|
176
|
+
* 返信バイトを readline が文字入力として流し込むので、返信を含むチャンクから
|
|
177
|
+
* 生じるキー入力だけを握りつぶす。返信が来ない端末では何も握らない(CIでも安全)。
|
|
178
|
+
*/
|
|
179
|
+
probeBackground() {
|
|
180
|
+
if (this.backgroundProbe)
|
|
181
|
+
return;
|
|
182
|
+
this.backgroundProbe = true;
|
|
183
|
+
this.backgroundWaiting = true;
|
|
184
|
+
let buffer = '';
|
|
185
|
+
let timer;
|
|
186
|
+
const onData = (chunk) => {
|
|
187
|
+
buffer += chunk;
|
|
188
|
+
if (this.backgroundWaiting && buffer.includes('\x1b]11;'))
|
|
189
|
+
this.replyStarted = true;
|
|
190
|
+
if (this.replyStarted && !this.replyDone)
|
|
191
|
+
this.silenceReplyKeys();
|
|
192
|
+
const osc = parseOscBackground(buffer);
|
|
193
|
+
if (osc === null)
|
|
194
|
+
return;
|
|
195
|
+
finishProbe();
|
|
196
|
+
const classified = classifyBackground(osc, process.env);
|
|
197
|
+
if (classified !== null) {
|
|
198
|
+
this.palette = paletteFor(classified);
|
|
199
|
+
this.panelStyle = classified === 'light' ? '48;5;255' : '48;5;235';
|
|
200
|
+
this.render();
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
const finishProbe = () => {
|
|
204
|
+
clearTimeout(timer);
|
|
205
|
+
this.backgroundWaiting = false;
|
|
206
|
+
this.replyDone = true;
|
|
207
|
+
this.input.off('data', onData);
|
|
208
|
+
// 分割到着で入力欄に紛れた返信文字があれば取り除く(単一チャンクは握りつぶし済み)。
|
|
209
|
+
const tail = /\x1b\]11;([^\x07\x1b]*)/.exec(buffer)?.[1];
|
|
210
|
+
if (tail && this.text.includes(tail)) {
|
|
211
|
+
this.text = this.text.split(tail).join('');
|
|
212
|
+
this.cursor = Math.min(this.cursor, Math.max(0, this.text.length));
|
|
213
|
+
this.render();
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
this.input.on('data', onData);
|
|
217
|
+
timer = setTimeout(finishProbe, 250);
|
|
218
|
+
}
|
|
219
|
+
/** 返信チャンクから生じるキー入力を、現在の入力処理の終わりまで握りつぶす。 */
|
|
220
|
+
silenceReplyKeys() {
|
|
221
|
+
if (this.replySilenced)
|
|
222
|
+
return;
|
|
223
|
+
this.replySilenced = true;
|
|
224
|
+
queueMicrotask(() => { this.replySilenced = false; });
|
|
225
|
+
}
|
|
226
|
+
/** リサイズ: 画面を作り直す。トランスクリプトはスクロールバックに確定済み。 */
|
|
227
|
+
onResize = () => {
|
|
228
|
+
if (this.closed)
|
|
229
|
+
return;
|
|
230
|
+
this.clearPending = true;
|
|
231
|
+
this.streamRow = 1;
|
|
232
|
+
this.cursorRow = 1;
|
|
233
|
+
this.render();
|
|
234
|
+
};
|
|
235
|
+
columns() { return Math.max(12, this.output.columns || 80); }
|
|
236
|
+
rows() { return Math.max(6, this.output.rows || 24); }
|
|
237
|
+
/** 起動直後は80、会話が始まると端末幅に応じて広げる(旧設計と同じ判断)。 */
|
|
238
|
+
width() {
|
|
239
|
+
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));
|
|
242
|
+
}
|
|
243
|
+
write(text) { this.appendTranscript(text); this.render(); }
|
|
244
|
+
setModel(model) { this.model = model; this.render(); }
|
|
245
|
+
setActivity(activity) { if (this.activity !== activity) {
|
|
246
|
+
this.activity = activity;
|
|
247
|
+
this.render();
|
|
248
|
+
} }
|
|
249
|
+
setUsage(usage) { this.usage = usage; this.render(); }
|
|
250
|
+
/** Accumulate one reasoning delta, or flush the finished block into the transcript with `null`. */
|
|
251
|
+
setReasoning(delta) {
|
|
252
|
+
if (delta !== null) {
|
|
253
|
+
this.reasoning = (this.reasoning + delta).slice(-20_000);
|
|
254
|
+
this.render();
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
const text = this.reasoning.trimEnd();
|
|
258
|
+
this.reasoning = '';
|
|
259
|
+
if (text)
|
|
260
|
+
this.appendTranscript(`\n(推論)\n${text}\n`);
|
|
261
|
+
this.render();
|
|
262
|
+
}
|
|
263
|
+
unread(line) { this.queued.unshift(line); }
|
|
264
|
+
get imageCount() { return this.images.length; }
|
|
265
|
+
takeImages() { const images = this.images; this.images = []; this.render(); return images; }
|
|
266
|
+
next(signal) { return this.wait('何を調べますか? / でコマンド', undefined, '', signal, false, true); }
|
|
267
|
+
ask(title, signal, secret = false) { return this.wait(title, undefined, '', signal, secret); }
|
|
268
|
+
choose(title, choices, query = '') { return this.wait(title, choices, query); }
|
|
269
|
+
wait(title, choices, query = '', signal, secret = false, composer = false) {
|
|
270
|
+
if (signal?.aborted || this.closed)
|
|
271
|
+
return Promise.resolve(null);
|
|
272
|
+
if (this.queued.length)
|
|
273
|
+
return Promise.resolve(this.queued.shift());
|
|
274
|
+
if (this.pending)
|
|
275
|
+
throw new Error('端末の入力待ちは同時に1件だけです');
|
|
276
|
+
this.text = query;
|
|
277
|
+
this.cursor = chars(query).length;
|
|
278
|
+
this.selection = 0;
|
|
279
|
+
this.hiddenCompletion = false;
|
|
280
|
+
this.editorScroll = 0;
|
|
281
|
+
this.inputNotice = '';
|
|
282
|
+
return new Promise(resolve => {
|
|
283
|
+
const abort = () => finish(null);
|
|
284
|
+
const finish = (value) => {
|
|
285
|
+
signal?.removeEventListener('abort', abort);
|
|
286
|
+
this.clipboardTask?.abort();
|
|
287
|
+
this.clipboardTask = undefined;
|
|
288
|
+
this.paste = false;
|
|
289
|
+
this.pasteBuffer = '';
|
|
290
|
+
this.pasteBytes = 0;
|
|
291
|
+
if (value === null && composer)
|
|
292
|
+
this.images = [];
|
|
293
|
+
this.pending = undefined;
|
|
294
|
+
this.text = '';
|
|
295
|
+
this.cursor = 0;
|
|
296
|
+
this.render();
|
|
297
|
+
resolve(value);
|
|
298
|
+
};
|
|
299
|
+
this.pending = { title, choices, finish, secret, composer };
|
|
300
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
301
|
+
this.render();
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
options() {
|
|
305
|
+
if (this.pending?.secret)
|
|
306
|
+
return undefined;
|
|
307
|
+
if (this.pending?.choices) {
|
|
308
|
+
const visible = matching(this.pending.choices, this.text);
|
|
309
|
+
// Pinned rows are actions: they stay on top so a bare Enter cannot pick an arbitrary model.
|
|
310
|
+
return [...visible.filter(c => c.pinned), ...visible.filter(c => !c.pinned)];
|
|
311
|
+
}
|
|
312
|
+
if (!this.hiddenCompletion && this.text.startsWith('/') && !(/\s/.test(this.text)))
|
|
313
|
+
return matching(COMMANDS, this.text);
|
|
314
|
+
return undefined;
|
|
315
|
+
}
|
|
316
|
+
insertText(value) {
|
|
317
|
+
if (this.replySilenced)
|
|
318
|
+
return; // OSC 返信の取り込みを入力にしない
|
|
319
|
+
const normalized = clean(value.replace(/\r\n?/g, '\n').replace(/\t/g, ' '));
|
|
320
|
+
const added = chars(this.pending?.composer ? normalized : normalized.replace(/\n/g, ' '));
|
|
321
|
+
const parts = chars(this.text);
|
|
322
|
+
const next = parts.slice(0, this.cursor).concat(added, parts.slice(this.cursor)).join('');
|
|
323
|
+
if (Buffer.byteLength(next) > MAX_INPUT_BYTES) {
|
|
324
|
+
this.inputNotice = '入力は128 KiB以内にしてください';
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
this.text = next;
|
|
328
|
+
this.cursor += added.length;
|
|
329
|
+
this.selection = 0;
|
|
330
|
+
this.hiddenCompletion = false;
|
|
331
|
+
this.inputNotice = '';
|
|
332
|
+
}
|
|
333
|
+
async pasteImage() {
|
|
334
|
+
const pending = this.pending;
|
|
335
|
+
if (!pending?.composer || pending.secret || this.clipboardTask)
|
|
336
|
+
return;
|
|
337
|
+
if (this.images.length >= MAX_IMAGES) {
|
|
338
|
+
this.inputNotice = `添付画像は最大${MAX_IMAGES}枚です`;
|
|
339
|
+
this.render();
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
const controller = new AbortController();
|
|
343
|
+
this.clipboardTask = controller;
|
|
344
|
+
this.inputNotice = '画像を読込中…';
|
|
345
|
+
this.render();
|
|
346
|
+
try {
|
|
347
|
+
const image = parseImage(await this.clipboardReader(controller.signal));
|
|
348
|
+
if (controller.signal.aborted || this.pending !== pending || this.closed)
|
|
349
|
+
return;
|
|
350
|
+
this.images.push(image);
|
|
351
|
+
this.inputNotice = '';
|
|
352
|
+
}
|
|
353
|
+
catch (e) {
|
|
354
|
+
if (!controller.signal.aborted && this.pending === pending)
|
|
355
|
+
this.inputNotice = e instanceof Error ? e.message : '画像の読み取りに失敗しました';
|
|
356
|
+
}
|
|
357
|
+
finally {
|
|
358
|
+
if (this.clipboardTask === controller)
|
|
359
|
+
this.clipboardTask = undefined;
|
|
360
|
+
this.render();
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
onEnd = () => { this.pending?.finish(null); this.close(); };
|
|
364
|
+
keypress = (value, key) => {
|
|
365
|
+
if (key.name === 'paste-start') {
|
|
366
|
+
this.paste = true;
|
|
367
|
+
this.pasteBuffer = '';
|
|
368
|
+
this.pasteBytes = 0;
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (key.name === 'paste-end') {
|
|
372
|
+
this.paste = false;
|
|
373
|
+
if (this.pending && this.pasteBytes <= MAX_INPUT_BYTES)
|
|
374
|
+
this.insertText(this.pasteBuffer);
|
|
375
|
+
else if (this.pasteBytes > MAX_INPUT_BYTES)
|
|
376
|
+
this.inputNotice = '貼り付けるテキストは128 KiB以内にしてください';
|
|
377
|
+
this.pasteBuffer = '';
|
|
378
|
+
this.pasteBytes = 0;
|
|
379
|
+
this.render();
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
if (this.paste) {
|
|
383
|
+
this.pasteBytes += Buffer.byteLength(value ?? '');
|
|
384
|
+
if (this.pasteBytes <= MAX_INPUT_BYTES)
|
|
385
|
+
this.pasteBuffer += value ?? '';
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
if (key.ctrl && key.name === 'c') {
|
|
389
|
+
this.clipboardTask?.abort();
|
|
390
|
+
this.clipboardTask = undefined;
|
|
391
|
+
this.inputNotice = '';
|
|
392
|
+
if (process.listenerCount('SIGINT') > 0)
|
|
393
|
+
process.emit('SIGINT');
|
|
394
|
+
else if (this.pending?.choices || this.text || this.images.length) {
|
|
395
|
+
if (this.pending?.choices)
|
|
396
|
+
this.pending.finish(null);
|
|
397
|
+
else {
|
|
398
|
+
this.text = '';
|
|
399
|
+
this.cursor = 0;
|
|
400
|
+
this.images = [];
|
|
401
|
+
this.render();
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
else
|
|
405
|
+
this.pending?.finish(null);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
// 返信チャンク(OSC 応答)から生じたキー入力だけを握りつぶす。Ctrl+C は通す。
|
|
409
|
+
if (this.replySilenced && !(key.ctrl && key.name === 'c'))
|
|
410
|
+
return;
|
|
411
|
+
// PageUp/PgDn は端末本来のスクロールに任せる(代替スクリーンを使わないため)。
|
|
412
|
+
if (!this.pending)
|
|
413
|
+
return;
|
|
414
|
+
if (key.ctrl && key.name === 'v') {
|
|
415
|
+
void this.pasteImage();
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
if (key.ctrl && key.name === 'x' && this.pending.composer) {
|
|
419
|
+
this.clipboardTask?.abort();
|
|
420
|
+
this.clipboardTask = undefined;
|
|
421
|
+
this.images.pop();
|
|
422
|
+
this.inputNotice = '';
|
|
423
|
+
this.render();
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
const options = this.options();
|
|
427
|
+
if (key.name === 'escape' || key.ctrl && key.name === 'd') {
|
|
428
|
+
if (this.pending.choices)
|
|
429
|
+
this.pending.finish(null);
|
|
430
|
+
else if (options?.length && key.name === 'escape') {
|
|
431
|
+
this.hiddenCompletion = true;
|
|
432
|
+
this.render();
|
|
433
|
+
}
|
|
434
|
+
else if (!this.text && key.ctrl)
|
|
435
|
+
this.pending.finish(null);
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
const newline = this.pending.composer && (value === '\n' || key.ctrl && key.name === 'j' || (key.name === 'return' || key.name === 'enter') && (key.shift || key.meta));
|
|
439
|
+
if (newline)
|
|
440
|
+
this.insertText('\n');
|
|
441
|
+
else if (options && (key.name === 'up' || key.name === 'down')) {
|
|
442
|
+
this.selection = options.length ? (this.selection + (key.name === 'down' ? 1 : -1) + options.length) % options.length : 0;
|
|
443
|
+
}
|
|
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);
|
|
447
|
+
}
|
|
448
|
+
else if (key.name === 'return' || key.name === 'enter' || key.name === 'tab') {
|
|
449
|
+
if (this.clipboardTask) {
|
|
450
|
+
this.inputNotice = '画像の読込中です。完了後にEnterで送信';
|
|
451
|
+
this.render();
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
const selected = options?.[this.selection];
|
|
455
|
+
if (key.name === 'tab') {
|
|
456
|
+
if (selected && !this.pending.choices) {
|
|
457
|
+
this.text = selected.value;
|
|
458
|
+
this.cursor = chars(this.text).length;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
else if (this.pending.choices) {
|
|
462
|
+
if (selected)
|
|
463
|
+
this.pending.finish(selected.value);
|
|
464
|
+
}
|
|
465
|
+
else
|
|
466
|
+
this.pending.finish(selected?.value ?? this.text);
|
|
467
|
+
}
|
|
468
|
+
else if (key.name === 'left')
|
|
469
|
+
this.cursor = Math.max(0, this.cursor - 1);
|
|
470
|
+
else if (key.name === 'right')
|
|
471
|
+
this.cursor = Math.min(chars(this.text).length, this.cursor + 1);
|
|
472
|
+
else if (key.name === 'home' || key.ctrl && key.name === 'a')
|
|
473
|
+
this.cursor = lineEdge(this.text, this.cursor, 'start');
|
|
474
|
+
else if (key.name === 'end' || key.ctrl && key.name === 'e')
|
|
475
|
+
this.cursor = lineEdge(this.text, this.cursor, 'end');
|
|
476
|
+
else if (key.ctrl && key.name === 'u') {
|
|
477
|
+
this.text = '';
|
|
478
|
+
this.cursor = 0;
|
|
479
|
+
this.inputNotice = '';
|
|
480
|
+
}
|
|
481
|
+
else if (key.name === 'backspace' || key.name === 'delete') {
|
|
482
|
+
const parts = chars(this.text);
|
|
483
|
+
if (key.name === 'backspace' && this.cursor > 0)
|
|
484
|
+
parts.splice(--this.cursor, 1);
|
|
485
|
+
else if (key.name === 'delete')
|
|
486
|
+
parts.splice(this.cursor, 1);
|
|
487
|
+
this.text = parts.join('');
|
|
488
|
+
this.selection = 0;
|
|
489
|
+
this.hiddenCompletion = false;
|
|
490
|
+
}
|
|
491
|
+
else if (value && !key.ctrl && !key.meta)
|
|
492
|
+
this.insertText(value);
|
|
493
|
+
this.render();
|
|
494
|
+
};
|
|
495
|
+
/**
|
|
496
|
+
* トランスクリプトへ追記する。完成行は直ちに折り返して出力待ちキューへ。
|
|
497
|
+
* 会話の始まり(`▶`)を検出したら、それ以降の行を広めの幅で折り返す。
|
|
498
|
+
*/
|
|
499
|
+
appendTranscript(text) {
|
|
500
|
+
let source = (this.partial + text).replace(/\r\n?/g, '\n');
|
|
501
|
+
if (/(^|\n)▶/.test(text) || /https:\/\//.test(text))
|
|
502
|
+
this.started = true;
|
|
503
|
+
const width = this.width();
|
|
504
|
+
for (;;) {
|
|
505
|
+
const at = source.indexOf('\n');
|
|
506
|
+
if (at < 0) {
|
|
507
|
+
this.partial = source;
|
|
508
|
+
break;
|
|
509
|
+
}
|
|
510
|
+
const logicalLine = source.slice(0, at);
|
|
511
|
+
source = source.slice(at + 1);
|
|
512
|
+
// 会話が始まる前の案内行はウェルカムブロックへ(会話開始時に一括で出力する)。
|
|
513
|
+
if (!this.started) {
|
|
514
|
+
this.bootLines.push(logicalLine);
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
for (const wrapped of wrap(logicalLine, width))
|
|
518
|
+
this.queue.push(wrapped);
|
|
519
|
+
this.partial = '';
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
paint(text, code) { return this.color ? `\x1b[${code}m${text}\x1b[0m` : text; }
|
|
523
|
+
/**
|
|
524
|
+
* 1フレームの描画。
|
|
525
|
+
* 1) 前回のライブブロック(最下部)を消去。伸びた分は先にスクロールして確定させる
|
|
526
|
+
* 2) 確定したトランスクリプト行を出力(はみ出した行はスクロールバックへ確定)
|
|
527
|
+
* 3) ライブブロックを、起動時は縦中央、会話中は最下段に再描画
|
|
528
|
+
* 再描画は最下部ブロックに限るため、過去の履歴が端末のスクロールバックに蓄積する。
|
|
529
|
+
*/
|
|
530
|
+
render = () => {
|
|
531
|
+
if (this.closed)
|
|
532
|
+
return;
|
|
533
|
+
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);
|
|
540
|
+
this.colorizerState = this.colorizer.state();
|
|
541
|
+
// 会話が始まった瞬間、ウェルカム(ロゴ+案内)を一度だけ本文へ流し込む。
|
|
542
|
+
if (this.started && !this.bootFlushed) {
|
|
543
|
+
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)));
|
|
546
|
+
this.bootLines = [];
|
|
547
|
+
}
|
|
548
|
+
// --- ライブブロック(最下部)を構成する ---
|
|
549
|
+
const displayText = this.pending?.secret ? '•'.repeat(chars(this.text).length) : this.text;
|
|
550
|
+
const composer = !this.pending || this.pending.composer;
|
|
551
|
+
const editor = editorLayout(displayText, Math.max(5, width - 3));
|
|
552
|
+
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));
|
|
554
|
+
const options = this.options();
|
|
555
|
+
const partialLines = wrap(this.partial, width);
|
|
556
|
+
const partialCount = this.partial ? partialLines.length : 0;
|
|
557
|
+
// ライブの推論は見出し含めて表示。はみ出すときは古い行(先頭)から落とす。
|
|
558
|
+
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;
|
|
561
|
+
const maxReasoning = Math.max(0, Math.min(rows - reservedForBody - 1, 24));
|
|
562
|
+
const liveReasoning = reasoningText.length === 0 ? [] :
|
|
563
|
+
reasoningText.slice(Math.max(0, reasoningText.length - maxReasoning))
|
|
564
|
+
.map(line => ({ text: line, style: this.palette.reasoning }));
|
|
565
|
+
const optionsLines = [];
|
|
566
|
+
if (options) {
|
|
567
|
+
const height = Math.max(1, Math.min(options.length || 1, Math.max(2, rows - (partialCount + liveReasoning.length) - 6), 8));
|
|
568
|
+
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' });
|
|
570
|
+
if (!options.length)
|
|
571
|
+
optionsLines.push({ text: '該当なし — 検索語を変える / Esc で戻る', style: '2' });
|
|
572
|
+
const matched = options.filter(choice => !choice.pinned).length;
|
|
573
|
+
options.slice(start, start + height).forEach((choice, i) => {
|
|
574
|
+
const active = start + i === this.selection;
|
|
575
|
+
const detail = choice.pinned && this.pending?.choices
|
|
576
|
+
? `${this.text ? `${matched}件一致` : `${matched}件`} · 空白区切りは語順自由` : choice.detail ?? '';
|
|
577
|
+
const label = `${active ? '›' : ' '} ${choice.label} ${detail}`;
|
|
578
|
+
optionsLines.push({ text: label, style: active ? '97;44' : choice.pinned ? '2' : '' });
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
const lines = [...optionsLines,
|
|
582
|
+
{ text: this.started ? '─'.repeat(width) : '', style: ACCENT }];
|
|
583
|
+
const editorStart = partialCount + liveReasoning.length + lines.length;
|
|
584
|
+
// 入力欄が表示行数を超えたら、カーソルが常に窓内に来るようにスクロールする。
|
|
585
|
+
if (cursor.row < this.editorScroll)
|
|
586
|
+
this.editorScroll = cursor.row;
|
|
587
|
+
if (cursor.row >= this.editorScroll + inputRows)
|
|
588
|
+
this.editorScroll = cursor.row - inputRows + 1;
|
|
589
|
+
this.editorScroll = Math.max(0, Math.min(this.editorScroll, Math.max(0, editor.lines.length - inputRows)));
|
|
590
|
+
for (let i = 0; i < inputRows; i++) {
|
|
591
|
+
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: '' });
|
|
594
|
+
}
|
|
595
|
+
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)) : '';
|
|
603
|
+
const usageWidth = textWidth(usageStatus);
|
|
604
|
+
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;
|
|
608
|
+
lines.push({ text: bottom, style: '2' });
|
|
609
|
+
const styled = (row) => {
|
|
610
|
+
const fitted = fitText(row.text, width);
|
|
611
|
+
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}` : ''}`);
|
|
614
|
+
}
|
|
615
|
+
return this.paint(fitted, row.style);
|
|
616
|
+
};
|
|
617
|
+
// 会話が始まる前のウェルカム: ロゴ+案内を縦中央に整える。
|
|
618
|
+
// paintMargin は両フェーズ共通(画面全体に対する中央寄せ)。
|
|
619
|
+
const marginStyled = (row) => marginPrefix + styled(row);
|
|
620
|
+
let body = [];
|
|
621
|
+
let editorStartIdx = editorStart;
|
|
622
|
+
if (!this.started) {
|
|
623
|
+
// タイトルとロゴをコンテンツ幅の中央に揃える。
|
|
624
|
+
const widthCenter = (line) => {
|
|
625
|
+
const pad = Math.max(0, Math.floor((width - textWidth(line)) / 2));
|
|
626
|
+
return ' '.repeat(pad) + line;
|
|
627
|
+
};
|
|
628
|
+
const welcome = [
|
|
629
|
+
{ text: widthCenter('MoDKH · Coding Harness'), style: '1' },
|
|
630
|
+
...logoForWidth(width).map(line => ({ text: widthCenter(line), style: ACCENT })),
|
|
631
|
+
...this.bootLines.slice(-8).flatMap(line => wrap(line, width).map(text => ({ text, style: '' }))),
|
|
632
|
+
];
|
|
633
|
+
// ロゴと入力欄は一つのまとまり。余白を両者の間に入れない。
|
|
634
|
+
const midPad = 1;
|
|
635
|
+
body = [
|
|
636
|
+
...welcome.map(row => marginStyled(row)),
|
|
637
|
+
...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)),
|
|
640
|
+
// lines にはコマンドメニュー(optionsLines)が含まれる。二重に展開しない。
|
|
641
|
+
...lines.map(marginStyled),
|
|
642
|
+
];
|
|
643
|
+
editorStartIdx = welcome.length + midPad + partialCount + liveReasoning.length + optionsLines.length + 1;
|
|
644
|
+
}
|
|
645
|
+
else {
|
|
646
|
+
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)),
|
|
649
|
+
// lines にはコマンドメニュー(optionsLines)が含まれる。二重に展開しない。
|
|
650
|
+
...lines.map(marginStyled),
|
|
651
|
+
];
|
|
652
|
+
}
|
|
653
|
+
// 最下部ブロックは1行以上の余白を残して画面に収める。はみ出すときは上侧から落とす。
|
|
654
|
+
const overflow = Math.max(0, body.length - (rows - 1));
|
|
655
|
+
if (overflow > 0) {
|
|
656
|
+
body = body.slice(overflow);
|
|
657
|
+
editorStartIdx = Math.max(0, editorStartIdx - overflow);
|
|
658
|
+
}
|
|
659
|
+
const liveCount = body.length;
|
|
660
|
+
// --- 描画。消去は「最終トランスクリプト行の下一行」から下端まで。
|
|
661
|
+
// ライブブロックと空き行だけを消すので、過去の行はスクロールバックに確定したままである。
|
|
662
|
+
// streamRow は未初期化のとき最下段(起動時のシェルプロンプト位置を想定)。
|
|
663
|
+
let out = '';
|
|
664
|
+
// サイズ変更や起動直後は画面を一度消して制御範囲を作り直す(残りを見せない)。
|
|
665
|
+
if (this.clearPending) {
|
|
666
|
+
this.clearPending = false;
|
|
667
|
+
this.streamRow = 1;
|
|
668
|
+
this.cursorRow = 1;
|
|
669
|
+
out += '\x1b[2J\x1b[1;1H';
|
|
670
|
+
}
|
|
671
|
+
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`;
|
|
678
|
+
// 確定行の出力。ライブブロックの上端を越えそうなら先にスクロールして確定させる。
|
|
679
|
+
const streamBottom = Math.max(1, rows - liveCount);
|
|
680
|
+
let r = streamRow;
|
|
681
|
+
for (const line of stream) {
|
|
682
|
+
if (r > streamBottom) {
|
|
683
|
+
const scrolls = Math.min(r - streamBottom, rows);
|
|
684
|
+
out += `\x1b[${rows};1H` + '\n'.repeat(scrolls);
|
|
685
|
+
r -= scrolls;
|
|
686
|
+
}
|
|
687
|
+
out += `\x1b[${r};1H\x1b[K${marginPrefix}${line}\r\n`;
|
|
688
|
+
r++;
|
|
689
|
+
}
|
|
690
|
+
this.streamRow = Math.max(1, Math.min(rows, r));
|
|
691
|
+
// 起動時はグループ全体を縦中央へ。会話中は最下段に必要な余白を空ける。
|
|
692
|
+
const liveStart = this.started ? Math.max(1, rows - liveCount + 1)
|
|
693
|
+
: Math.max(1, Math.floor((rows - liveCount) / 2) + 1);
|
|
694
|
+
if (liveStart < this.streamRow) {
|
|
695
|
+
const scrolls = Math.min(rows, this.streamRow - liveStart);
|
|
696
|
+
out += `\x1b[${rows};1H` + '\n'.repeat(scrolls);
|
|
697
|
+
this.streamRow -= scrolls;
|
|
698
|
+
}
|
|
699
|
+
for (let i = 0; i < liveCount; i++) {
|
|
700
|
+
out += `\x1b[${liveStart + i};1H\x1b[K${body[i]}` + (i === liveCount - 1 ? '' : '\r\n');
|
|
701
|
+
}
|
|
702
|
+
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');
|
|
705
|
+
this.cursorRow = cursorLiveRow;
|
|
706
|
+
this.output.write(out);
|
|
707
|
+
};
|
|
708
|
+
/** 未完了行の色分け用に、完成行までの状態を複製する。 */
|
|
709
|
+
fork() {
|
|
710
|
+
const clone = new TranscriptColorizer();
|
|
711
|
+
clone.restore(this.colorizerState);
|
|
712
|
+
return clone;
|
|
713
|
+
}
|
|
714
|
+
close = () => {
|
|
715
|
+
if (this.closed)
|
|
716
|
+
return;
|
|
717
|
+
this.closed = true;
|
|
718
|
+
this.clipboardTask?.abort();
|
|
719
|
+
this.clipboardTask = undefined;
|
|
720
|
+
this.images = [];
|
|
721
|
+
this.pending?.finish(null);
|
|
722
|
+
this.input.removeListener('keypress', this.keypress);
|
|
723
|
+
this.input.removeListener('end', this.onEnd);
|
|
724
|
+
this.output.removeListener('resize', this.onResize);
|
|
725
|
+
process.removeListener('exit', this.close);
|
|
726
|
+
this.input.setRawMode(this.previousRaw);
|
|
727
|
+
this.input.pause();
|
|
728
|
+
// 入力欄(ライブブロック)を消して、シェルのプロンプトが新しい行に出るようにする。
|
|
729
|
+
const rows = this.rows();
|
|
730
|
+
const eraseRow = Math.min(rows, this.streamRow >= 1 ? this.streamRow : rows);
|
|
731
|
+
const base = Math.max(1, Math.min(rows, this.cursorRow >= 1 ? this.cursorRow : rows));
|
|
732
|
+
const up = base - eraseRow;
|
|
733
|
+
if (up > 0)
|
|
734
|
+
this.output.write(`\x1b[${up}A`);
|
|
735
|
+
this.output.write('\r\x1b[J');
|
|
736
|
+
this.output.write('\x1b[0m\x1b[?25h\x1b[?2004l\r\n');
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
export function createTerminal(cwd) {
|
|
740
|
+
return process.stdin.isTTY && process.stdout.isTTY && process.env.TERM !== 'dumb' && process.env.MODKH_PLAIN !== '1'
|
|
741
|
+
? new TerminalUI(cwd) : new PlainTerminal();
|
|
742
|
+
}
|