skyloom 1.14.8 → 1.15.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 (156) hide show
  1. package/.github/workflows/ci.yml +2 -2
  2. package/.github/workflows/publish.yml +51 -4
  3. package/CONVERSION_PLAN.md +191 -191
  4. package/config/default.yaml +46 -43
  5. package/config/models.yaml +928 -155
  6. package/config/providers.yaml +109 -6
  7. package/dist/agents/snow.d.ts +2 -0
  8. package/dist/agents/snow.d.ts.map +1 -1
  9. package/dist/agents/snow.js +36 -5
  10. package/dist/agents/snow.js.map +1 -1
  11. package/dist/cli/loom_chat.d.ts.map +1 -1
  12. package/dist/cli/loom_chat.js +207 -1
  13. package/dist/cli/loom_chat.js.map +1 -1
  14. package/dist/cli/main.js +190 -40
  15. package/dist/cli/main.js.map +1 -1
  16. package/dist/cli/tui.d.ts.map +1 -1
  17. package/dist/cli/tui.js +6 -31
  18. package/dist/cli/tui.js.map +1 -1
  19. package/dist/core/agent.d.ts +6 -4
  20. package/dist/core/agent.d.ts.map +1 -1
  21. package/dist/core/agent.js +61 -20
  22. package/dist/core/agent.js.map +1 -1
  23. package/dist/core/catalog.d.ts.map +1 -1
  24. package/dist/core/catalog.js +30 -9
  25. package/dist/core/catalog.js.map +1 -1
  26. package/dist/core/commands.d.ts +110 -0
  27. package/dist/core/commands.d.ts.map +1 -0
  28. package/dist/core/commands.js +633 -0
  29. package/dist/core/commands.js.map +1 -0
  30. package/dist/core/concurrency.d.ts +38 -0
  31. package/dist/core/concurrency.d.ts.map +1 -0
  32. package/dist/core/concurrency.js +65 -0
  33. package/dist/core/concurrency.js.map +1 -0
  34. package/dist/core/factory.js +16 -16
  35. package/dist/core/file_checkpoint.d.ts +9 -0
  36. package/dist/core/file_checkpoint.d.ts.map +1 -1
  37. package/dist/core/file_checkpoint.js +33 -1
  38. package/dist/core/file_checkpoint.js.map +1 -1
  39. package/dist/core/llm.d.ts.map +1 -1
  40. package/dist/core/llm.js +66 -13
  41. package/dist/core/llm.js.map +1 -1
  42. package/dist/core/memory.js +51 -51
  43. package/dist/core/schemas.d.ts +16 -0
  44. package/dist/core/schemas.d.ts.map +1 -1
  45. package/dist/core/schemas.js +32 -0
  46. package/dist/core/schemas.js.map +1 -1
  47. package/dist/core/security.d.ts.map +1 -1
  48. package/dist/core/security.js +27 -0
  49. package/dist/core/security.js.map +1 -1
  50. package/dist/core/skymd.js +14 -14
  51. package/dist/core/trace.d.ts +105 -0
  52. package/dist/core/trace.d.ts.map +1 -0
  53. package/dist/core/trace.js +213 -0
  54. package/dist/core/trace.js.map +1 -0
  55. package/dist/tools/builtin.d.ts +2 -6
  56. package/dist/tools/builtin.d.ts.map +1 -1
  57. package/dist/tools/builtin.js +18 -111
  58. package/dist/tools/builtin.js.map +1 -1
  59. package/dist/tools/extra.d.ts +13 -0
  60. package/dist/tools/extra.d.ts.map +1 -0
  61. package/dist/tools/extra.js +827 -0
  62. package/dist/tools/extra.js.map +1 -0
  63. package/dist/tools/guards.d.ts +12 -0
  64. package/dist/tools/guards.d.ts.map +1 -0
  65. package/dist/tools/guards.js +143 -0
  66. package/dist/tools/guards.js.map +1 -0
  67. package/dist/tools/model_tool.d.ts.map +1 -1
  68. package/dist/tools/model_tool.js +24 -4
  69. package/dist/tools/model_tool.js.map +1 -1
  70. package/dist/web/markdown.d.ts +32 -0
  71. package/dist/web/markdown.d.ts.map +1 -0
  72. package/dist/web/markdown.js +202 -0
  73. package/dist/web/markdown.js.map +1 -0
  74. package/dist/web/server.d.ts +4 -0
  75. package/dist/web/server.d.ts.map +1 -1
  76. package/dist/web/server.js +14 -582
  77. package/dist/web/server.js.map +1 -1
  78. package/dist/web/ui.d.ts +31 -0
  79. package/dist/web/ui.d.ts.map +1 -0
  80. package/dist/web/ui.js +1009 -0
  81. package/dist/web/ui.js.map +1 -0
  82. package/docs/AESTHETIC_DESIGN.md +152 -152
  83. package/docs/OPTIMIZATION_PLAN.md +178 -178
  84. package/package.json +1 -1
  85. package/src/agents/snow.ts +38 -5
  86. package/src/cli/commands_md.ts +112 -112
  87. package/src/cli/input_macros.ts +83 -83
  88. package/src/cli/loom.ts +1041 -1041
  89. package/src/cli/loom_chat.ts +772 -603
  90. package/src/cli/main.ts +853 -723
  91. package/src/cli/tui.ts +264 -289
  92. package/src/core/agent/guard.ts +133 -133
  93. package/src/core/agent/task.ts +100 -100
  94. package/src/core/agent.ts +1630 -1590
  95. package/src/core/agent_helpers.ts +500 -500
  96. package/src/core/bus.ts +221 -221
  97. package/src/core/cache.ts +153 -153
  98. package/src/core/catalog.ts +199 -178
  99. package/src/core/circuit_breaker.ts +119 -119
  100. package/src/core/commands.ts +704 -0
  101. package/src/core/concurrency.ts +73 -0
  102. package/src/core/config.ts +365 -365
  103. package/src/core/constants.ts +95 -95
  104. package/src/core/factory.ts +656 -656
  105. package/src/core/file_checkpoint.ts +163 -136
  106. package/src/core/hooks.ts +126 -126
  107. package/src/core/llm.ts +972 -915
  108. package/src/core/logger.ts +143 -143
  109. package/src/core/mcp.ts +1001 -1001
  110. package/src/core/memory.ts +1201 -1201
  111. package/src/core/middleware.ts +350 -350
  112. package/src/core/model_config.ts +159 -159
  113. package/src/core/pipelines.ts +424 -424
  114. package/src/core/schemas.ts +319 -282
  115. package/src/core/security.ts +27 -0
  116. package/src/core/semantic.ts +211 -211
  117. package/src/core/skill.ts +384 -384
  118. package/src/core/skymd.ts +143 -143
  119. package/src/core/theme.ts +65 -65
  120. package/src/core/tool.ts +457 -457
  121. package/src/core/trace.ts +236 -0
  122. package/src/core/verify.ts +71 -71
  123. package/src/plugins/loader.ts +91 -91
  124. package/src/skills/loader.ts +75 -75
  125. package/src/tools/builtin.ts +571 -642
  126. package/src/tools/computer.ts +279 -279
  127. package/src/tools/extra.ts +662 -0
  128. package/src/tools/guards.ts +82 -0
  129. package/src/tools/model_tool.ts +93 -74
  130. package/src/tools/todo.ts +76 -76
  131. package/src/web/markdown.ts +193 -0
  132. package/src/web/server.ts +117 -693
  133. package/src/web/ui.ts +949 -0
  134. package/tests/agent.test.ts +211 -159
  135. package/tests/agent_helpers.test.ts +48 -48
  136. package/tests/catalog.test.ts +86 -86
  137. package/tests/checkpoint_commands.test.ts +124 -124
  138. package/tests/claude_compat.test.ts +110 -110
  139. package/tests/commands.test.ts +103 -0
  140. package/tests/concurrency.test.ts +102 -0
  141. package/tests/config.test.ts +41 -41
  142. package/tests/extra_tools.test.ts +212 -0
  143. package/tests/fence_plugin.test.ts +52 -52
  144. package/tests/guard.test.ts +75 -75
  145. package/tests/loom.test.ts +337 -337
  146. package/tests/memory.test.ts +170 -170
  147. package/tests/model_config.test.ts +109 -109
  148. package/tests/skymd.test.ts +146 -146
  149. package/tests/ssrf.test.ts +38 -38
  150. package/tests/structured_retry.test.ts +87 -0
  151. package/tests/task.test.ts +60 -60
  152. package/tests/todo_toolstats.test.ts +94 -94
  153. package/tests/trace.test.ts +128 -0
  154. package/tests/tui.test.ts +67 -67
  155. package/tests/web.test.ts +169 -0
  156. package/tsconfig.json +38 -38
package/src/cli/tui.ts CHANGED
@@ -1,289 +1,264 @@
1
- /**
2
- * 天空织机 TUI — a polished *linear* terminal interface.
3
- *
4
- * Design note: the previous version tried to be a full-screen app, redrawing
5
- * the whole screen on every keystroke while the reply streamed linearly below
6
- * it — the two fought, the conversation never persisted, and hand-rolled
7
- * raw-mode editing mangled CJK width. This rewrite is linear (like Claude Code
8
- * / opencode): real readline line-editing + a CJK-aware wrapping stream
9
- * renderer. Robust, flicker-free, and it actually reads like a conversation.
10
- */
11
-
12
- import * as readline from "readline";
13
- import chalk from "chalk";
14
- import { agentTheme, PALETTE } from "../core/theme";
15
-
16
- const TUI_VERSION = (() => { try { return require("../../package.json").version; } catch { return ""; } })();
17
-
18
- export interface TUIContext {
19
- agent: any;
20
- agents: Map<string, any>;
21
- model: string;
22
- cost: string;
23
- width: number;
24
- height: number;
25
- }
26
-
27
- /* ── Slash commands (for tab-completion + the inline palette) ── */
28
- export const SLASH_COMMANDS: [string, string][] = [
29
- ["/fog", "≋ · 探索洞察"],
30
- ["/rain", "⸽ · 创造产出"],
31
- ["/frost", "✱ · 精炼品质"],
32
- ["/snow", "❉ · 架构规划"],
33
- ["/dew", "∘ 露 · 可靠守护"],
34
- ["/fair", "☼ 晴 · 情感陪伴"],
35
- ["/help", "查看所有命令"],
36
- ["/setup", "配置向导"],
37
- ["/init", "扫描项目生成 SKY.md"],
38
- ["/plan", "切换计划模式(只读出方案)"],
39
- ["/verify", "运行项目验证命令"],
40
- ["/context", "上下文占用明细"],
41
- ["/rewind", "回退本轮文件改动"],
42
- ["/tools", "工具调用统计"],
43
- ["/model", "查看/切换模型(独立/统一)"],
44
- ["/cost", "费用统计"],
45
- ["/status", "状态总览"],
46
- ["/memory", "记忆状态"],
47
- ["/sessions", "会话列表"],
48
- ["/resume ", "恢复会话(序号/id)"],
49
- ["/new", "开始新会话"],
50
- ["/workspace", "工作空间"],
51
- ["/compact", "压缩上下文"],
52
- ["/clear", "清屏"],
53
- ["/task ", "多 Agent 编排"],
54
- ["/mcp", "MCP 服务器"],
55
- ["/version", "版本信息"],
56
- ["/quit", "退出"],
57
- ];
58
-
59
- /* ════════════════════════════════════════
60
- Markdown stripping — clean raw md for terminal display
61
- ════════════════════════════════════════ */
62
- /** Strip common markdown formatting for clean terminal output. */
63
- export function stripMarkdown(s: string): string {
64
- return s
65
- .replace(/^#{1,4}\s+/gm, '') // headings
66
- .replace(/\*\*(.+?)\*\*/g, '$1') // bold
67
- .replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, '$1') // italic
68
- .replace(/__([^_]+)__/g, '$1') // alt bold
69
- .replace(/_([^_]+)_/g, '$1') // alt italic
70
- .replace(/`([^`]+)`/g, '$1') // inline code
71
- .replace(/~~(.+?)~~/g, '$1') // strikethrough
72
- .replace(/^\s*[-*+]\s+/gm, '• ') // bullets
73
- .replace(/^\s*\d+[.)]\s+/gm, ' ') // numbered lists
74
- .replace(/^\|.*\|$/gm, (line) => { // tables → spaced columns
75
- return line.replace(/\|/g, ' ').replace(/-{2,}/g, '──');
76
- })
77
- .replace(/\n{3,}/g, '\n\n'); // collapse excess newlines
78
- }
79
-
80
- /** Page output through a simple pager (Enter to continue, q to quit) */
81
- export async function pageOutput(out: NodeJS.WriteStream, text: string): Promise<void> {
82
- const lines = text.split('\n');
83
- const h = (out.rows || 24) - 2;
84
- if (lines.length <= h) { out.write(text + '\n'); return; }
85
-
86
- const readline = require('readline');
87
- const rl = readline.createInterface({ input: process.stdin, output: out });
88
-
89
- for (let i = 0; i < lines.length; i += h) {
90
- const chunk = lines.slice(i, i + h).join('\n');
91
- out.write(chunk + '\n');
92
- if (i + h < lines.length) {
93
- const remaining = lines.length - i - h;
94
- out.write(`\x1b[7m ── ${remaining} more lines · Enter=next · q=quit ── \x1b[0m\n`);
95
- const key: string = await new Promise(r => {
96
- process.stdin.setRawMode?.(true);
97
- process.stdin.resume();
98
- process.stdin.once('data', (d: Buffer) => { process.stdin.setRawMode?.(false); process.stdin.pause(); r(d.toString()); });
99
- });
100
- if (key === 'q' || key === '\x03') { rl.close(); return; }
101
- }
102
- }
103
- rl.close();
104
- }
105
-
106
- /* ════════════════════════════════════════
107
- CJK-aware display width
108
- ════════════════════════════════════════ */
109
- /** Visual columns occupied by a single code point (CJK / fullwidth = 2). */
110
- export function charWidth(cp: number): number {
111
- if (cp === 0) return 0;
112
- if (cp < 32 || (cp >= 0x7f && cp < 0xa0)) return 0; // control
113
- // East-Asian wide / fullwidth ranges
114
- if (
115
- (cp >= 0x1100 && cp <= 0x115f) || // Hangul Jamo
116
- (cp >= 0x2e80 && cp <= 0x303e) || // CJK radicals, Kangxi, punctuation
117
- (cp >= 0x3041 && cp <= 0x33ff) || // Hiragana…CJK symbols
118
- (cp >= 0x3400 && cp <= 0x4dbf) || // CJK Ext A
119
- (cp >= 0x4e00 && cp <= 0x9fff) || // CJK Unified
120
- (cp >= 0xa000 && cp <= 0xa4cf) || // Yi
121
- (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul syllables
122
- (cp >= 0xf900 && cp <= 0xfaff) || // CJK compat
123
- (cp >= 0xfe10 && cp <= 0xfe19) ||
124
- (cp >= 0xfe30 && cp <= 0xfe6f) || // CJK compat forms
125
- (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth forms
126
- (cp >= 0xffe0 && cp <= 0xffe6) ||
127
- (cp >= 0x1f300 && cp <= 0x1faff) // emoji / pictographs
128
- ) return 2;
129
- return 1;
130
- }
131
-
132
- const ANSI_RE = /\x1b\[[0-9;]*m/g;
133
-
134
- /** Visual width of a string, ignoring ANSI color codes. */
135
- export function visualWidth(s: string): number {
136
- let w = 0;
137
- for (const ch of s.replace(ANSI_RE, "")) w += charWidth(ch.codePointAt(0) || 0);
138
- return w;
139
- }
140
-
141
- /** Pad a string (containing ANSI) to a visual width. */
142
- export function padVisual(s: string, width: number): string {
143
- const diff = width - visualWidth(s);
144
- return diff > 0 ? s + " ".repeat(diff) : s;
145
- }
146
-
147
- /* ════════════════════════════════════════
148
- Streaming renderer word-wrap aware, CJK aware
149
- ════════════════════════════════════════ */
150
- /**
151
- * Writes streamed text with a fixed left gutter, wrapping at the terminal
152
- * width. English wraps on word boundaries; CJK wraps per glyph. Color is
153
- * applied per flushed chunk so styling survives wrapping.
154
- */
155
- export class StreamRenderer {
156
- private col = 0;
157
- private word = "";
158
- private atLineStart = true;
159
- private out: NodeJS.WriteStream;
160
- private gutter: string;
161
- private maxCols: number;
162
- private color: (s: string) => string;
163
-
164
- constructor(out: NodeJS.WriteStream, opts?: { gutter?: string; color?: (s: string) => string }) {
165
- this.out = out;
166
- this.gutter = opts?.gutter ?? " ";
167
- this.color = opts?.color ?? ((s) => s);
168
- const cols = out.columns || 80;
169
- // content width excludes the gutter; clamp for readability
170
- this.maxCols = Math.max(32, Math.min(cols - visualWidth(this.gutter) - 1, 96));
171
- }
172
-
173
- /** Lazily emit the left gutter at the start of each visual line. */
174
- private startLine() { if (this.atLineStart) { this.out.write(this.gutter); this.atLineStart = false; } }
175
- private newline() { this.out.write("\n"); this.atLineStart = true; this.col = 0; }
176
-
177
- /** Strip asterisk formatting: **text** text, *text* text, __text__ → text */
178
- private cleanWord(s: string): string {
179
- return s.replace(/\*\*(.+?)\*\*/g, (_, t) => t)
180
- .replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, (_, t) => t)
181
- .replace(/__([^_]+)__/g, (_, t) => t)
182
- .replace(/_([^_]+)_/g, (_, t) => t);
183
- }
184
-
185
- private flushWord() {
186
- if (!this.word) return;
187
- const cleaned = this.cleanWord(this.word);
188
- if (!cleaned) { this.word = ""; return; }
189
- const w = visualWidth(cleaned);
190
- if (this.col > 0 && this.col + w > this.maxCols) this.newline();
191
- this.startLine();
192
- this.out.write(this.color(cleaned));
193
- this.col += w;
194
- this.word = "";
195
- }
196
-
197
- /** Feed a chunk of streamed text. Filters out raw md formatting. */
198
- write(text: string) {
199
- for (const ch of text) {
200
- if (ch === "\r") continue;
201
- if (ch === "\n") { this.flushWord(); this.newline(); continue; }
202
- if (ch === " " || ch === "\t") {
203
- this.flushWord();
204
- if (this.col > 0 && this.col < this.maxCols) { this.startLine(); this.out.write(" "); this.col += 1; }
205
- continue;
206
- }
207
- // Strip heading markers (# ## ###) at line start
208
- if (ch === "#" && this.atLineStart) { continue; }
209
- // Strip inline code backticks
210
- if (ch === "`") { this.flushWord(); continue; }
211
- const cp = ch.codePointAt(0) || 0;
212
- if (charWidth(cp) === 2) {
213
- // CJK / wide: flush any pending latin word, then place this glyph
214
- this.flushWord();
215
- if (this.col > 0 && this.col + 2 > this.maxCols) this.newline();
216
- this.startLine();
217
- this.out.write(this.color(ch));
218
- this.col += 2;
219
- } else {
220
- this.word += ch;
221
- // very long unbroken token: hard-break to avoid overflow
222
- if (visualWidth(this.word) >= this.maxCols) this.flushWord();
223
- }
224
- }
225
- }
226
-
227
- /** Flush any buffered word (call before switching styles / ending). */
228
- flush() { this.flushWord(); }
229
- }
230
-
231
- /* ════════════════════════════════════════
232
- Input — readline-based, robust line editing
233
- ════════════════════════════════════════ */
234
- /** Tab-completer for slash commands. */
235
- function slashCompleter(line: string): [string[], string] {
236
- if (!line.startsWith("/")) return [[], line];
237
- const names = SLASH_COMMANDS.map(([c]) => c.trimEnd());
238
- const hits = names.filter((c) => c.startsWith(line));
239
- return [hits.length ? hits : names, line];
240
- }
241
-
242
- /** The prompt string for an agent: a small mineral seal + chevron. */
243
- export function promptFor(agentName: string): string {
244
- const t = agentTheme(agentName);
245
- return chalk.hex(t.hex)(` ${t.symbol} ${t.kanji} `) + chalk.hex(PALETTE.inkLight)("❯ ");
246
- }
247
-
248
- /** Cross-turn input history (↑/↓), shared by every per-turn reader. */
249
- const inputHistory: string[] = [];
250
-
251
- /**
252
- * Read one line with the agent-themed prompt. A fresh readline interface is
253
- * created and closed per call this deliberately avoids clashing with the
254
- * separate readline prompts used by the setup wizard and tool-approval flow
255
- * (two live interfaces on one stdin corrupt input). History is preserved
256
- * manually across turns.
257
- */
258
- export function readLine(agentName: string, out: NodeJS.WriteStream = process.stdout): Promise<string> {
259
- return new Promise((resolve) => {
260
- const rl = readline.createInterface({
261
- input: process.stdin,
262
- output: out,
263
- completer: slashCompleter,
264
- terminal: process.stdin.isTTY ?? false,
265
- history: [...inputHistory],
266
- historySize: 200,
267
- } as any);
268
- rl.on("SIGINT", () => { out.write("\n" + chalk.dim(" 再会。\n")); rl.close(); process.exit(0); });
269
- rl.question(promptFor(agentName), (answer) => {
270
- const trimmed = answer.trim();
271
- if (trimmed) inputHistory.unshift(trimmed);
272
- rl.close();
273
- resolve(trimmed);
274
- });
275
- });
276
- }
277
-
278
- /** Render the inline slash-command palette (printed, not full-screen). */
279
- export function renderPalette(filter: string): string {
280
- const f = filter.toLowerCase();
281
- const matches = SLASH_COMMANDS.filter(([c]) => c.toLowerCase().startsWith(f));
282
- const list = matches.length ? matches : SLASH_COMMANDS;
283
- const lines = list.slice(0, 12).map(([cmd, desc]) => {
284
- const isAgent = ["/fog", "/rain", "/frost", "/snow", "/dew", "/fair"].includes(cmd.trim());
285
- const name = isAgent ? chalk.hex(agentTheme(cmd.trim().slice(1)).hex)(cmd.padEnd(12)) : chalk.hex(PALETTE.inkMid)(cmd.padEnd(12));
286
- return " " + name + chalk.hex(PALETTE.inkLight)(desc);
287
- });
288
- return chalk.dim(" 命令 · Tab 补全\n") + lines.join("\n") + "\n";
289
- }
1
+ /**
2
+ * 天空织机 TUI — a polished *linear* terminal interface.
3
+ *
4
+ * Design note: the previous version tried to be a full-screen app, redrawing
5
+ * the whole screen on every keystroke while the reply streamed linearly below
6
+ * it — the two fought, the conversation never persisted, and hand-rolled
7
+ * raw-mode editing mangled CJK width. This rewrite is linear (like Claude Code
8
+ * / opencode): real readline line-editing + a CJK-aware wrapping stream
9
+ * renderer. Robust, flicker-free, and it actually reads like a conversation.
10
+ */
11
+
12
+ import * as readline from "readline";
13
+ import chalk from "chalk";
14
+ import { agentTheme, PALETTE } from "../core/theme";
15
+ import { registry } from "../core/commands";
16
+
17
+ const TUI_VERSION = (() => { try { return require("../../package.json").version; } catch { return ""; } })();
18
+
19
+ export interface TUIContext {
20
+ agent: any;
21
+ agents: Map<string, any>;
22
+ model: string;
23
+ cost: string;
24
+ width: number;
25
+ height: number;
26
+ }
27
+
28
+ /* ── Slash commands (for tab-completion + the inline palette) ──
29
+ Derived from the central command registry (src/core/commands.ts) so the
30
+ palette, tab-completer, and /help all stay in sync with a single source of
31
+ truth no parallel hand-kept array to drift. */
32
+ export const SLASH_COMMANDS: [string, string][] = registry.slashItems("zh");
33
+
34
+ /* ════════════════════════════════════════
35
+ Markdown stripping — clean raw md for terminal display
36
+ ════════════════════════════════════════ */
37
+ /** Strip common markdown formatting for clean terminal output. */
38
+ export function stripMarkdown(s: string): string {
39
+ return s
40
+ .replace(/^#{1,4}\s+/gm, '') // headings
41
+ .replace(/\*\*(.+?)\*\*/g, '$1') // bold
42
+ .replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, '$1') // italic
43
+ .replace(/__([^_]+)__/g, '$1') // alt bold
44
+ .replace(/_([^_]+)_/g, '$1') // alt italic
45
+ .replace(/`([^`]+)`/g, '$1') // inline code
46
+ .replace(/~~(.+?)~~/g, '$1') // strikethrough
47
+ .replace(/^\s*[-*+]\s+/gm, '• ') // bullets
48
+ .replace(/^\s*\d+[.)]\s+/gm, ' ') // numbered lists
49
+ .replace(/^\|.*\|$/gm, (line) => { // tables → spaced columns
50
+ return line.replace(/\|/g, ' ').replace(/-{2,}/g, '──');
51
+ })
52
+ .replace(/\n{3,}/g, '\n\n'); // collapse excess newlines
53
+ }
54
+
55
+ /** Page output through a simple pager (Enter to continue, q to quit) */
56
+ export async function pageOutput(out: NodeJS.WriteStream, text: string): Promise<void> {
57
+ const lines = text.split('\n');
58
+ const h = (out.rows || 24) - 2;
59
+ if (lines.length <= h) { out.write(text + '\n'); return; }
60
+
61
+ const readline = require('readline');
62
+ const rl = readline.createInterface({ input: process.stdin, output: out });
63
+
64
+ for (let i = 0; i < lines.length; i += h) {
65
+ const chunk = lines.slice(i, i + h).join('\n');
66
+ out.write(chunk + '\n');
67
+ if (i + h < lines.length) {
68
+ const remaining = lines.length - i - h;
69
+ out.write(`\x1b[7m ── ${remaining} more lines · Enter=next · q=quit ── \x1b[0m\n`);
70
+ const key: string = await new Promise(r => {
71
+ process.stdin.setRawMode?.(true);
72
+ process.stdin.resume();
73
+ process.stdin.once('data', (d: Buffer) => { process.stdin.setRawMode?.(false); process.stdin.pause(); r(d.toString()); });
74
+ });
75
+ if (key === 'q' || key === '\x03') { rl.close(); return; }
76
+ }
77
+ }
78
+ rl.close();
79
+ }
80
+
81
+ /* ════════════════════════════════════════
82
+ CJK-aware display width
83
+ ════════════════════════════════════════ */
84
+ /** Visual columns occupied by a single code point (CJK / fullwidth = 2). */
85
+ export function charWidth(cp: number): number {
86
+ if (cp === 0) return 0;
87
+ if (cp < 32 || (cp >= 0x7f && cp < 0xa0)) return 0; // control
88
+ // East-Asian wide / fullwidth ranges
89
+ if (
90
+ (cp >= 0x1100 && cp <= 0x115f) || // Hangul Jamo
91
+ (cp >= 0x2e80 && cp <= 0x303e) || // CJK radicals, Kangxi, punctuation
92
+ (cp >= 0x3041 && cp <= 0x33ff) || // Hiragana…CJK symbols
93
+ (cp >= 0x3400 && cp <= 0x4dbf) || // CJK Ext A
94
+ (cp >= 0x4e00 && cp <= 0x9fff) || // CJK Unified
95
+ (cp >= 0xa000 && cp <= 0xa4cf) || // Yi
96
+ (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul syllables
97
+ (cp >= 0xf900 && cp <= 0xfaff) || // CJK compat
98
+ (cp >= 0xfe10 && cp <= 0xfe19) ||
99
+ (cp >= 0xfe30 && cp <= 0xfe6f) || // CJK compat forms
100
+ (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth forms
101
+ (cp >= 0xffe0 && cp <= 0xffe6) ||
102
+ (cp >= 0x1f300 && cp <= 0x1faff) // emoji / pictographs
103
+ ) return 2;
104
+ return 1;
105
+ }
106
+
107
+ const ANSI_RE = /\x1b\[[0-9;]*m/g;
108
+
109
+ /** Visual width of a string, ignoring ANSI color codes. */
110
+ export function visualWidth(s: string): number {
111
+ let w = 0;
112
+ for (const ch of s.replace(ANSI_RE, "")) w += charWidth(ch.codePointAt(0) || 0);
113
+ return w;
114
+ }
115
+
116
+ /** Pad a string (containing ANSI) to a visual width. */
117
+ export function padVisual(s: string, width: number): string {
118
+ const diff = width - visualWidth(s);
119
+ return diff > 0 ? s + " ".repeat(diff) : s;
120
+ }
121
+
122
+ /* ════════════════════════════════════════
123
+ Streaming renderer word-wrap aware, CJK aware
124
+ ════════════════════════════════════════ */
125
+ /**
126
+ * Writes streamed text with a fixed left gutter, wrapping at the terminal
127
+ * width. English wraps on word boundaries; CJK wraps per glyph. Color is
128
+ * applied per flushed chunk so styling survives wrapping.
129
+ */
130
+ export class StreamRenderer {
131
+ private col = 0;
132
+ private word = "";
133
+ private atLineStart = true;
134
+ private out: NodeJS.WriteStream;
135
+ private gutter: string;
136
+ private maxCols: number;
137
+ private color: (s: string) => string;
138
+
139
+ constructor(out: NodeJS.WriteStream, opts?: { gutter?: string; color?: (s: string) => string }) {
140
+ this.out = out;
141
+ this.gutter = opts?.gutter ?? " ";
142
+ this.color = opts?.color ?? ((s) => s);
143
+ const cols = out.columns || 80;
144
+ // content width excludes the gutter; clamp for readability
145
+ this.maxCols = Math.max(32, Math.min(cols - visualWidth(this.gutter) - 1, 96));
146
+ }
147
+
148
+ /** Lazily emit the left gutter at the start of each visual line. */
149
+ private startLine() { if (this.atLineStart) { this.out.write(this.gutter); this.atLineStart = false; } }
150
+ private newline() { this.out.write("\n"); this.atLineStart = true; this.col = 0; }
151
+
152
+ /** Strip asterisk formatting: **text** text, *text* text, __text__ text */
153
+ private cleanWord(s: string): string {
154
+ return s.replace(/\*\*(.+?)\*\*/g, (_, t) => t)
155
+ .replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g, (_, t) => t)
156
+ .replace(/__([^_]+)__/g, (_, t) => t)
157
+ .replace(/_([^_]+)_/g, (_, t) => t);
158
+ }
159
+
160
+ private flushWord() {
161
+ if (!this.word) return;
162
+ const cleaned = this.cleanWord(this.word);
163
+ if (!cleaned) { this.word = ""; return; }
164
+ const w = visualWidth(cleaned);
165
+ if (this.col > 0 && this.col + w > this.maxCols) this.newline();
166
+ this.startLine();
167
+ this.out.write(this.color(cleaned));
168
+ this.col += w;
169
+ this.word = "";
170
+ }
171
+
172
+ /** Feed a chunk of streamed text. Filters out raw md formatting. */
173
+ write(text: string) {
174
+ for (const ch of text) {
175
+ if (ch === "\r") continue;
176
+ if (ch === "\n") { this.flushWord(); this.newline(); continue; }
177
+ if (ch === " " || ch === "\t") {
178
+ this.flushWord();
179
+ if (this.col > 0 && this.col < this.maxCols) { this.startLine(); this.out.write(" "); this.col += 1; }
180
+ continue;
181
+ }
182
+ // Strip heading markers (# ## ###) at line start
183
+ if (ch === "#" && this.atLineStart) { continue; }
184
+ // Strip inline code backticks
185
+ if (ch === "`") { this.flushWord(); continue; }
186
+ const cp = ch.codePointAt(0) || 0;
187
+ if (charWidth(cp) === 2) {
188
+ // CJK / wide: flush any pending latin word, then place this glyph
189
+ this.flushWord();
190
+ if (this.col > 0 && this.col + 2 > this.maxCols) this.newline();
191
+ this.startLine();
192
+ this.out.write(this.color(ch));
193
+ this.col += 2;
194
+ } else {
195
+ this.word += ch;
196
+ // very long unbroken token: hard-break to avoid overflow
197
+ if (visualWidth(this.word) >= this.maxCols) this.flushWord();
198
+ }
199
+ }
200
+ }
201
+
202
+ /** Flush any buffered word (call before switching styles / ending). */
203
+ flush() { this.flushWord(); }
204
+ }
205
+
206
+ /* ════════════════════════════════════════
207
+ Input readline-based, robust line editing
208
+ ════════════════════════════════════════ */
209
+ /** Tab-completer for slash commands. */
210
+ function slashCompleter(line: string): [string[], string] {
211
+ if (!line.startsWith("/")) return [[], line];
212
+ const names = SLASH_COMMANDS.map(([c]) => c.trimEnd());
213
+ const hits = names.filter((c) => c.startsWith(line));
214
+ return [hits.length ? hits : names, line];
215
+ }
216
+
217
+ /** The prompt string for an agent: a small mineral seal + chevron. */
218
+ export function promptFor(agentName: string): string {
219
+ const t = agentTheme(agentName);
220
+ return chalk.hex(t.hex)(` ${t.symbol} ${t.kanji} `) + chalk.hex(PALETTE.inkLight)("❯ ");
221
+ }
222
+
223
+ /** Cross-turn input history (↑/↓), shared by every per-turn reader. */
224
+ const inputHistory: string[] = [];
225
+
226
+ /**
227
+ * Read one line with the agent-themed prompt. A fresh readline interface is
228
+ * created and closed per call — this deliberately avoids clashing with the
229
+ * separate readline prompts used by the setup wizard and tool-approval flow
230
+ * (two live interfaces on one stdin corrupt input). History is preserved
231
+ * manually across turns.
232
+ */
233
+ export function readLine(agentName: string, out: NodeJS.WriteStream = process.stdout): Promise<string> {
234
+ return new Promise((resolve) => {
235
+ const rl = readline.createInterface({
236
+ input: process.stdin,
237
+ output: out,
238
+ completer: slashCompleter,
239
+ terminal: process.stdin.isTTY ?? false,
240
+ history: [...inputHistory],
241
+ historySize: 200,
242
+ } as any);
243
+ rl.on("SIGINT", () => { out.write("\n" + chalk.dim(" 再会。\n")); rl.close(); process.exit(0); });
244
+ rl.question(promptFor(agentName), (answer) => {
245
+ const trimmed = answer.trim();
246
+ if (trimmed) inputHistory.unshift(trimmed);
247
+ rl.close();
248
+ resolve(trimmed);
249
+ });
250
+ });
251
+ }
252
+
253
+ /** Render the inline slash-command palette (printed, not full-screen). */
254
+ export function renderPalette(filter: string): string {
255
+ const f = filter.toLowerCase();
256
+ const matches = SLASH_COMMANDS.filter(([c]) => c.toLowerCase().startsWith(f));
257
+ const list = matches.length ? matches : SLASH_COMMANDS;
258
+ const lines = list.slice(0, 12).map(([cmd, desc]) => {
259
+ const isAgent = ["/fog", "/rain", "/frost", "/snow", "/dew", "/fair"].includes(cmd.trim());
260
+ const name = isAgent ? chalk.hex(agentTheme(cmd.trim().slice(1)).hex)(cmd.padEnd(12)) : chalk.hex(PALETTE.inkMid)(cmd.padEnd(12));
261
+ return " " + name + chalk.hex(PALETTE.inkLight)(desc);
262
+ });
263
+ return chalk.dim(" 命令 · Tab 补全\n") + lines.join("\n") + "\n";
264
+ }