@uncarved/jade 0.1.2 → 0.1.3

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 (151) hide show
  1. package/README.md +204 -198
  2. package/bin/jade.js +23 -0
  3. package/dist/commands.d.ts +20 -0
  4. package/dist/commands.js +20 -0
  5. package/dist/commands.js.map +1 -1
  6. package/dist/distro.d.ts +43 -6
  7. package/dist/distro.js +198 -48
  8. package/dist/distro.js.map +1 -1
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +2 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/main.js +436 -300
  13. package/dist/main.js.map +1 -1
  14. package/dist/plugin-cli.d.ts +1 -1
  15. package/dist/plugin-cli.js +79 -36
  16. package/dist/plugin-cli.js.map +1 -1
  17. package/dist/plugins/budget.d.ts +2 -2
  18. package/dist/plugins/budget.js +2 -2
  19. package/dist/plugins/budget.js.map +1 -1
  20. package/dist/plugins/builtins.js +6 -3
  21. package/dist/plugins/builtins.js.map +1 -1
  22. package/dist/plugins/checks.d.ts +2 -1
  23. package/dist/plugins/checks.js +25 -5
  24. package/dist/plugins/checks.js.map +1 -1
  25. package/dist/plugins/compact.js +45 -1
  26. package/dist/plugins/compact.js.map +1 -1
  27. package/dist/plugins/core.d.ts +5 -0
  28. package/dist/plugins/core.js +39 -0
  29. package/dist/plugins/core.js.map +1 -1
  30. package/dist/plugins/host.d.ts +52 -0
  31. package/dist/plugins/host.js +115 -0
  32. package/dist/plugins/host.js.map +1 -0
  33. package/dist/plugins/install.d.ts +1 -1
  34. package/dist/plugins/loader.d.ts +238 -10
  35. package/dist/plugins/loader.js +175 -21
  36. package/dist/plugins/loader.js.map +1 -1
  37. package/dist/plugins/policy.d.ts +2 -0
  38. package/dist/plugins/policy.js +17 -1
  39. package/dist/plugins/policy.js.map +1 -1
  40. package/dist/plugins/prompts.d.ts +6 -1
  41. package/dist/plugins/prompts.js +103 -15
  42. package/dist/plugins/prompts.js.map +1 -1
  43. package/dist/plugins/repeats.d.ts +7 -0
  44. package/dist/plugins/repeats.js +74 -13
  45. package/dist/plugins/repeats.js.map +1 -1
  46. package/dist/plugins/review.d.ts +2 -0
  47. package/dist/plugins/review.js +41 -3
  48. package/dist/plugins/review.js.map +1 -1
  49. package/dist/plugins/sessions.d.ts +7 -0
  50. package/dist/plugins/sessions.js +110 -0
  51. package/dist/plugins/sessions.js.map +1 -0
  52. package/dist/provider.d.ts +56 -2
  53. package/dist/provider.js +73 -7
  54. package/dist/provider.js.map +1 -1
  55. package/dist/session-lifecycle.d.ts +61 -0
  56. package/dist/session-lifecycle.js +167 -0
  57. package/dist/session-lifecycle.js.map +1 -0
  58. package/dist/session-scope.d.ts +53 -0
  59. package/dist/session-scope.js +116 -0
  60. package/dist/session-scope.js.map +1 -0
  61. package/dist/sessions.d.ts +6 -0
  62. package/dist/sessions.js +20 -0
  63. package/dist/sessions.js.map +1 -1
  64. package/dist/sys.d.ts +4 -1
  65. package/dist/sys.js +18 -1
  66. package/dist/sys.js.map +1 -1
  67. package/dist/tools/ask.d.ts +11 -0
  68. package/dist/tools/ask.js +62 -0
  69. package/dist/tools/ask.js.map +1 -0
  70. package/dist/tools/fs.d.ts +4 -0
  71. package/dist/tools/fs.js +53 -12
  72. package/dist/tools/fs.js.map +1 -1
  73. package/dist/tools/grep.js +3 -2
  74. package/dist/tools/grep.js.map +1 -1
  75. package/dist/tools/shell.js +5 -1
  76. package/dist/tools/shell.js.map +1 -1
  77. package/dist/tools/task.d.ts +6 -2
  78. package/dist/tools/task.js +36 -8
  79. package/dist/tools/task.js.map +1 -1
  80. package/dist/tools/web.d.ts +33 -3
  81. package/dist/tools/web.js +351 -143
  82. package/dist/tools/web.js.map +1 -1
  83. package/dist/ui/configure.js +91 -22
  84. package/dist/ui/configure.js.map +1 -1
  85. package/dist/ui/diff.d.ts +1 -1
  86. package/dist/ui/diff.js +1 -2
  87. package/dist/ui/diff.js.map +1 -1
  88. package/dist/ui/editor.d.ts +8 -0
  89. package/dist/ui/editor.js +50 -1
  90. package/dist/ui/editor.js.map +1 -1
  91. package/dist/ui/markdown.d.ts +6 -1
  92. package/dist/ui/markdown.js +57 -19
  93. package/dist/ui/markdown.js.map +1 -1
  94. package/dist/ui/render.d.ts +9 -10
  95. package/dist/ui/render.js +35 -72
  96. package/dist/ui/render.js.map +1 -1
  97. package/dist/ui/renderers.d.ts +8 -0
  98. package/dist/ui/renderers.js +169 -0
  99. package/dist/ui/renderers.js.map +1 -0
  100. package/dist/ui/screen.d.ts +22 -2
  101. package/dist/ui/screen.js +104 -15
  102. package/dist/ui/screen.js.map +1 -1
  103. package/dist/ui/transcript.d.ts +13 -0
  104. package/dist/ui/transcript.js +105 -15
  105. package/dist/ui/transcript.js.map +1 -1
  106. package/dist/ui/tui.d.ts +2 -0
  107. package/dist/ui/tui.js +309 -58
  108. package/dist/ui/tui.js.map +1 -1
  109. package/dist/update.d.ts +53 -0
  110. package/dist/update.js +255 -0
  111. package/dist/update.js.map +1 -0
  112. package/package.json +6 -5
  113. package/src/commands.ts +24 -0
  114. package/src/distro.ts +228 -51
  115. package/src/index.ts +2 -0
  116. package/src/main.ts +413 -292
  117. package/src/plugin-cli.ts +73 -34
  118. package/src/plugins/budget.ts +4 -4
  119. package/src/plugins/builtins.ts +6 -3
  120. package/src/plugins/checks.ts +25 -6
  121. package/src/plugins/compact.ts +40 -1
  122. package/src/plugins/core.ts +40 -0
  123. package/src/plugins/host.ts +146 -0
  124. package/src/plugins/install.ts +1 -1
  125. package/src/plugins/loader.ts +379 -23
  126. package/src/plugins/policy.ts +17 -1
  127. package/src/plugins/prompts.ts +108 -15
  128. package/src/plugins/repeats.ts +75 -14
  129. package/src/plugins/review.ts +40 -3
  130. package/src/plugins/sessions.ts +109 -0
  131. package/src/provider.ts +109 -10
  132. package/src/session-lifecycle.ts +194 -0
  133. package/src/session-scope.ts +135 -0
  134. package/src/sessions.ts +17 -0
  135. package/src/sys.ts +18 -1
  136. package/src/tools/ask.ts +72 -0
  137. package/src/tools/fs.ts +53 -12
  138. package/src/tools/grep.ts +3 -2
  139. package/src/tools/shell.ts +5 -1
  140. package/src/tools/task.ts +51 -11
  141. package/src/tools/web.ts +370 -140
  142. package/src/ui/configure.ts +90 -27
  143. package/src/ui/diff.ts +1 -2
  144. package/src/ui/editor.ts +50 -1
  145. package/src/ui/markdown.ts +258 -219
  146. package/src/ui/render.ts +35 -57
  147. package/src/ui/renderers.ts +183 -0
  148. package/src/ui/screen.ts +113 -19
  149. package/src/ui/transcript.ts +109 -16
  150. package/src/ui/tui.tsx +353 -58
  151. package/src/update.ts +262 -0
@@ -1,219 +1,258 @@
1
- // 终端里显示模型回复的 Markdown:标题、粗体、斜体、行内代码、链接、列表、引用、分隔线、代码块和表格。
2
- // 回复是流式到达的,按完整的行逐行处理:代码块要记住是否在块里,表格要攒齐所有行才能算列宽,
3
- // 所以做成有状态的 markdownStream。表格和分隔线跟终端宽度有关,交出去的是按宽度现排的函数。
4
-
5
- import stringWidth from "string-width";
6
- import wrapAnsi from "wrap-ansi";
7
- import { bold, cyan, dim, italic, strike, underline } from "./screen.ts";
8
-
9
- /** 排好版的一行,或者按显示宽度现排的若干行(表格、分隔线) */
10
- export type MdLine = string | { render(width: number): string[] };
11
-
12
- export interface MarkdownStream {
13
- /** 送进一个完整的行,返回可以显示的行;表格的行先攒着,等表格结束 */
14
- push(line: string): MdLine[];
15
- /** 回复结束:交出攒着的内容,恢复初始状态 */
16
- flush(): MdLine[];
17
- /** 攒着还没交出的内容,流式输出时先显示在底部 */
18
- pending(): MdLine[];
19
- }
20
-
21
- type Align = "left" | "center" | "right";
22
-
23
- const FENCE = /^\s*(`{3,}|~{3,})\s*([^`\s]*)/;
24
- const RULE = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/;
25
- const DELIMITER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
26
-
27
- export function markdownStream(): MarkdownStream {
28
- /** 所在代码块的开头标记(``` 或 ~~~),不在代码块里时为 undefined */
29
- let fence: string | undefined;
30
- /** 带 | 的一行:下一行是分隔行时它是表头,否则是普通的一行 */
31
- let candidate: string | undefined;
32
- let table: { align: Align[]; rows: string[][] } | undefined;
33
-
34
- const endTable = (): MdLine[] => {
35
- const out: MdLine[] = [];
36
- if (table) out.push(tableLine(table.rows, table.align));
37
- else if (candidate !== undefined) out.push(renderLine(candidate));
38
- table = undefined;
39
- candidate = undefined;
40
- return out;
41
- };
42
-
43
- function push(line: string): MdLine[] {
44
- if (fence) {
45
- const m = line.match(FENCE);
46
- if (m && m[1]![0] === fence[0] && m[1]!.length >= fence.length && !m[2]) {
47
- fence = undefined;
48
- return [];
49
- }
50
- return [` ${line}`];
51
- }
52
- if (table) {
53
- if (line.includes("|") && line.trim()) {
54
- table.rows.push(cells(line));
55
- return [];
56
- }
57
- return [...endTable(), ...push(line)];
58
- }
59
- if (candidate !== undefined) {
60
- if (DELIMITER.test(line) && line.includes("-")) {
61
- const header = cells(candidate);
62
- const align = cells(line).map((c): Align => (c.startsWith(":") && c.endsWith(":") ? "center" : c.endsWith(":") ? "right" : "left"));
63
- while (align.length < header.length) align.push("left");
64
- table = { align, rows: [header] };
65
- candidate = undefined;
66
- return [];
67
- }
68
- return [...endTable(), ...push(line)];
69
- }
70
- const m = line.match(FENCE);
71
- if (m) {
72
- fence = m[1]!;
73
- return m[2] ? [dim(` ${m[2]}`)] : [];
74
- }
75
- if (splitCells(line).length > 1) {
76
- candidate = line;
77
- return [];
78
- }
79
- return [renderLine(line)];
80
- }
81
-
82
- return {
83
- push,
84
- flush() {
85
- const out = endTable();
86
- fence = undefined;
87
- return out;
88
- },
89
- pending: () => (table ? [tableLine(table.rows, table.align)] : candidate !== undefined ? [renderLine(candidate)] : []),
90
- };
91
- }
92
-
93
- /** 整段 Markdown 排好版(测试和一次性显示用) */
94
- export function renderMarkdown(text: string, width: number): string[] {
95
- const md = markdownStream();
96
- const out = [...text.split("\n").flatMap((l) => md.push(l)), ...md.flush()];
97
- return out.flatMap((l) => (typeof l === "string" ? [l] : l.render(width)));
98
- }
99
-
100
- /** 代码块和表格以外的一行 */
101
- function renderLine(line: string): MdLine {
102
- if (RULE.test(line)) return { render: (width) => [dim("─".repeat(Math.max(1, Math.min(width, 80))))] };
103
- const heading = line.match(/^\s{0,3}(#{1,6})\s+(.*?)(\s+#+)?\s*$/);
104
- if (heading) {
105
- const text = inline(heading[2]!);
106
- return heading[1]!.length === 1 ? bold(underline(text)) : bold(text);
107
- }
108
- const quote = line.match(/^\s*>\s?(.*)$/);
109
- if (quote) return dim("│ ") + inline(quote[1]!);
110
- const item = line.match(/^(\s*)([-*+])\s+(\[[ xX]\]\s+)?(.*)$/);
111
- if (item) {
112
- const box = item[3] ? (item[3][1] === " " ? "☐ " : "☑ ") : "";
113
- return `${item[1]}${box ? "" : cyan("• ")}${box}${inline(item[4]!)}`;
114
- }
115
- const ordered = line.match(/^(\s*)(\d+[.)])\s+(.*)$/);
116
- if (ordered) return `${ordered[1]}${cyan(ordered[2]!)} ${inline(ordered[3]!)}`;
117
- return inline(line);
118
- }
119
-
120
- /** 行内格式:`代码`、**粗体**、*斜体*、~~删除线~~、[链接](url)、反斜杠转义。代码里的内容原样显示 */
121
- export function inline(text: string): string {
122
- return text
123
- .split(/(`+[^`]*?`+)/)
124
- .map((part, i) => {
125
- if (i % 2 === 1) return cyan(part.replace(/^`+ ?|`+$/g, "").replace(/ $/, ""));
126
- return part
127
- .replace(/\\([\\`*_{}[\]()#+\-.!|~<>])/g, (_, c: string) => `\0${c.charCodeAt(0)}\0`)
128
- .replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_, label: string, url: string) =>
129
- label === url ? underline(url) : `${underline(label)}${dim(` (${url})`)}`,
130
- )
131
- .replace(/<(https?:\/\/[^>\s]+)>/g, (_, url: string) => underline(url))
132
- .replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*|(?<![\w])__(?=\S)(.+?)(?<=\S)__(?![\w])/g, (_, a?: string, b?: string) => bold(a ?? b!))
133
- .replace(/(?<![*\w])\*(?=[^\s*])(.+?)(?<=[^\s*])\*(?![*\w])|(?<![_\w])_(?=[^\s_])(.+?)(?<=[^\s_])_(?![_\w])/g, (_, a?: string, b?: string) => italic(a ?? b!))
134
- .replace(/~~(?=\S)(.+?)(?<=\S)~~/g, (_, s: string) => strike(s))
135
- .replace(/\0(\d+)\0/g, (_, c: string) => String.fromCharCode(Number(c)));
136
- })
137
- .join("");
138
- }
139
-
140
- /** 按没转义、不在行内代码里的 | 拆开一行 */
141
- function splitCells(line: string): string[] {
142
- const out: string[] = [];
143
- let cell = "";
144
- let code = false;
145
- for (let i = 0; i < line.length; i++) {
146
- const c = line[i]!;
147
- if (c === "\\" && line[i + 1] === "|") {
148
- cell += "|";
149
- i++;
150
- } else if (c === "`") {
151
- code = !code;
152
- cell += c;
153
- } else if (c === "|" && !code) {
154
- out.push(cell);
155
- cell = "";
156
- } else cell += c;
157
- }
158
- out.push(cell);
159
- return out;
160
- }
161
-
162
- /** 表格一行的各个单元格,去掉两端的 | */
163
- function cells(line: string): string[] {
164
- const parts = splitCells(line.trim());
165
- if (parts.length > 1 && parts[0]!.trim() === "") parts.shift();
166
- if (parts.length > 1 && parts.at(-1)!.trim() === "") parts.pop();
167
- return parts.map((c) => c.trim());
168
- }
169
-
170
- function tableLine(rows: string[][], align: Align[]): MdLine {
171
- const shown = rows.map((r, i) => r.map((c) => (i === 0 ? bold(inline(c)) : inline(c))));
172
- return { render: (width) => renderTable(shown, align, width) };
173
- }
174
-
175
- /**
176
- * 画带边框的表格。放不下时按比例收窄较宽的列、单元格内折行;
177
- * 窄到每列连 3 列都分不到时,改成每行一段「表头: 值」
178
- */
179
- function renderTable(rows: string[][], align: Align[], width: number): string[] {
180
- const n = Math.max(...rows.map((r) => r.length));
181
- const grid = rows.map((r) => Array.from({ length: n }, (_, i) => r[i] ?? ""));
182
- const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => stringWidth(r[i]!))));
183
- const room = width - (3 * n + 1);
184
- if (room < 3 * n) {
185
- const [head, ...body] = grid;
186
- return body.flatMap((r, k) => [
187
- ...(k ? [""] : []),
188
- ...r.flatMap((c, i) => wrapAnsi(`${head![i]}${dim(":")} ${c}`, Math.max(1, width), { hard: true }).split("\n")),
189
- ]);
190
- }
191
- // 从最窄的列开始,能放下的列按原宽,放不下的平分剩下的宽度
192
- const widths = [...natural];
193
- if (natural.reduce((a, b) => a + b, 0) > room) {
194
- let left = room;
195
- let open = n;
196
- for (const i of [...natural.keys()].sort((a, b) => natural[a]! - natural[b]!)) {
197
- const share = Math.floor(left / open);
198
- widths[i] = Math.min(natural[i]!, share);
199
- left -= widths[i]!;
200
- open--;
201
- }
202
- }
203
- const pad = (s: string, w: number, a: Align) => {
204
- const gap = w - stringWidth(s);
205
- if (a === "right") return " ".repeat(gap) + s;
206
- if (a === "center") return " ".repeat(Math.floor(gap / 2)) + s + " ".repeat(Math.ceil(gap / 2));
207
- return s + " ".repeat(gap);
208
- };
209
- const border = (l: string, m: string, r: string) => dim(l + widths.map((w) => "─".repeat(w + 2)).join(m) + r);
210
- const row = (r: string[]) => {
211
- const parts = r.map((c, i) => wrapAnsi(c, widths[i]!, { hard: true, trim: true }).split("\n"));
212
- const height = Math.max(...parts.map((p) => p.length));
213
- return Array.from({ length: height }, (_, k) =>
214
- dim("│ ") + parts.map((p, i) => pad(p[k] ?? "", widths[i]!, align[i] ?? "left")).join(dim(" │ ")) + dim(" │"),
215
- );
216
- };
217
- const [head, ...body] = grid;
218
- return [border("┌", "┬", "┐"), ...row(head!), border("├", "┼", "┤"), ...body.flatMap(row), border("└", "┴", "┘")];
219
- }
1
+ // 终端里显示模型回复的 Markdown:标题、粗体、斜体、行内代码、链接、列表、引用、分隔线、代码块和表格。
2
+ // 回复是流式到达的,按完整的行逐行处理:代码块要记住是否在块里,表格要攒齐所有行才能算列宽,
3
+ // 所以做成有状态的 markdownStream。表格和分隔线跟终端宽度有关,交出去的是按宽度现排的函数。
4
+
5
+ import stringWidth from "string-width";
6
+ import wrapAnsi from "wrap-ansi";
7
+ import { bold, cyan, dim, italic, strike, underline } from "./screen.ts";
8
+
9
+ /** 排好版的一行,或者按显示宽度现排的若干行(表格、分隔线) */
10
+ export type MdLine = string | { render(width: number): string[] };
11
+
12
+ export interface MarkdownStream {
13
+ /** 送进一个完整的行,返回可以显示的行;表格的行先攒着,等表格结束 */
14
+ push(line: string): MdLine[];
15
+ /** 回复结束:交出攒着的内容,恢复初始状态 */
16
+ flush(): MdLine[];
17
+ /** 攒着还没交出的内容,流式输出时先显示在底部 */
18
+ pending(): MdLine[];
19
+ }
20
+
21
+ type Align = "left" | "center" | "right";
22
+
23
+ const FENCE = /^\s*(`{3,}|~{3,})\s*([^`\s]*)/;
24
+ const RULE = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/;
25
+ const DELIMITER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
26
+
27
+ export function markdownStream(): MarkdownStream {
28
+ /** 所在代码块的开头标记(``` 或 ~~~),不在代码块里时为 undefined */
29
+ let fence: string | undefined;
30
+ /** 带 | 的一行:下一行是分隔行时它是表头,否则是普通的一行 */
31
+ let candidate: string | undefined;
32
+ let table: { align: Align[]; rows: string[][] } | undefined;
33
+
34
+ const endTable = (): MdLine[] => {
35
+ const out: MdLine[] = [];
36
+ if (table) out.push(tableLine(table.rows, table.align));
37
+ else if (candidate !== undefined) out.push(renderLine(candidate));
38
+ table = undefined;
39
+ candidate = undefined;
40
+ return out;
41
+ };
42
+
43
+ function push(line: string): MdLine[] {
44
+ if (fence) {
45
+ const m = line.match(FENCE);
46
+ if (m && m[1]![0] === fence[0] && m[1]!.length >= fence.length && !m[2]) {
47
+ fence = undefined;
48
+ return [];
49
+ }
50
+ // 左边一条竖线和正文分开;长行折行后续行也带竖线
51
+ return [hanging(dim("┃ "), line, dim("┃ "))];
52
+ }
53
+ if (table) {
54
+ if (line.includes("|") && line.trim()) {
55
+ table.rows.push(cells(line));
56
+ return [];
57
+ }
58
+ return [...endTable(), ...push(line)];
59
+ }
60
+ if (candidate !== undefined) {
61
+ if (DELIMITER.test(line) && line.includes("-")) {
62
+ const header = cells(candidate);
63
+ const align = cells(line).map((c): Align => (c.startsWith(":") && c.endsWith(":") ? "center" : c.endsWith(":") ? "right" : "left"));
64
+ while (align.length < header.length) align.push("left");
65
+ table = { align, rows: [header] };
66
+ candidate = undefined;
67
+ return [];
68
+ }
69
+ return [...endTable(), ...push(line)];
70
+ }
71
+ const m = line.match(FENCE);
72
+ if (m) {
73
+ fence = m[1]!;
74
+ return m[2] ? [dim(`┃ ${m[2]}`)] : [];
75
+ }
76
+ if (splitCells(line).length > 1) {
77
+ candidate = line;
78
+ return [];
79
+ }
80
+ return [renderLine(line)];
81
+ }
82
+
83
+ return {
84
+ push,
85
+ flush() {
86
+ const out = endTable();
87
+ fence = undefined;
88
+ return out;
89
+ },
90
+ pending: () => (table ? [tableLine(table.rows, table.align)] : candidate !== undefined ? [renderLine(candidate)] : []),
91
+ };
92
+ }
93
+
94
+ /** 整段 Markdown 排好版(测试和一次性显示用) */
95
+ export function renderMarkdown(text: string, width: number): string[] {
96
+ const md = markdownStream();
97
+ const out = [...text.split("\n").flatMap((l) => md.push(l)), ...md.flush()];
98
+ return out.flatMap((l) => (typeof l === "string" ? [l] : l.render(width)));
99
+ }
100
+
101
+ /** 代码块和表格以外的一行 */
102
+ function renderLine(line: string): MdLine {
103
+ if (RULE.test(line)) return { render: (width) => [dim("─".repeat(Math.max(1, Math.min(width, 80))))] };
104
+ const heading = line.match(/^\s{0,3}(#{1,6})\s+(.*?)(\s+#+)?\s*$/);
105
+ if (heading) {
106
+ const text = inline(heading[2]!);
107
+ return heading[1]!.length === 1 ? bold(underline(text)) : bold(text);
108
+ }
109
+ const quote = line.match(/^\s*>\s?(.*)$/);
110
+ if (quote) return hanging(dim("│ "), inline(quote[1]!), dim("│ "));
111
+ const item = line.match(/^(\s*)([-*+])\s+(\[[ xX]\]\s+)?(.*)$/);
112
+ // 列表项折行时续行和正文对齐
113
+ if (item) {
114
+ const box = item[3] ? (item[3][1] === " " ? "☐ " : "☑ ") : "";
115
+ return hanging(`${item[1]}${box ? "" : cyan("• ")}${box}`, inline(item[4]!));
116
+ }
117
+ const ordered = line.match(/^(\s*)(\d+[.)])\s+(.*)$/);
118
+ if (ordered) return hanging(`${ordered[1]}${cyan(ordered[2]!)} `, inline(ordered[3]!));
119
+ return inline(line);
120
+ }
121
+
122
+ /**
123
+ * 行内格式:`代码`、**粗体**、*斜体*、~~删除线~~、[链接](url)、反斜杠转义。代码里的内容原样显示。
124
+ * 行内代码先换成占位符,粗体、斜体处理完再换回来,"**用 `foo()` 实现**" 这样跨过代码的粗体才认得出
125
+ */
126
+ export function inline(text: string): string {
127
+ const codes: string[] = [];
128
+ return text
129
+ .replace(/`+[^`]*?`+/g, (code) => `\x01${codes.push(cyan(code.replace(/^`+ ?|`+$/g, "").replace(/ $/, ""))) - 1}\x01`)
130
+ .replace(/\\([\\`*_{}[\]()#+\-.!|~<>])/g, (_, c: string) => `\0${c.charCodeAt(0)}\0`)
131
+ .replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_, label: string, url: string) =>
132
+ label === url ? underline(url) : `${underline(label)}${dim(` (${url})`)}`,
133
+ )
134
+ .replace(/<(https?:\/\/[^>\s]+)>/g, (_, url: string) => underline(url))
135
+ .replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*|(?<![\w])__(?=\S)(.+?)(?<=\S)__(?![\w])/g, (_, a?: string, b?: string) => bold(a ?? b!))
136
+ .replace(/(?<![*\w])\*(?=[^\s*])(.+?)(?<=[^\s*])\*(?![*\w])|(?<![_\w])_(?=[^\s_])(.+?)(?<=[^\s_])_(?![_\w])/g, (_, a?: string, b?: string) => italic(a ?? b!))
137
+ .replace(/~~(?=\S)(.+?)(?<=\S)~~/g, (_, s: string) => strike(s))
138
+ .replace(/\0(\d+)\0/g, (_, c: string) => String.fromCharCode(Number(c)))
139
+ .replace(/\x01(\d+)\x01/g, (_, i: string) => codes[Number(i)]!);
140
+ }
141
+
142
+ /** 制表符换成空格,按 stop 列一个制表位对齐(按显示宽度算,忽略颜色)。终端按 8 列显示 tab,按 0 列算宽度会对不齐、超宽 */
143
+ export function expandTabs(text: string, stop = 4): string {
144
+ if (!text.includes("\t")) return text;
145
+ return text
146
+ .split("\n")
147
+ .map((line) => {
148
+ if (!line.includes("\t")) return line;
149
+ let out = "";
150
+ let col = 0;
151
+ const parts = line.split("\t");
152
+ parts.forEach((p, i) => {
153
+ out += p;
154
+ col += stringWidth(p);
155
+ if (i < parts.length - 1) {
156
+ const n = stop - (col % stop);
157
+ out += " ".repeat(n);
158
+ col += n;
159
+ }
160
+ });
161
+ return out;
162
+ })
163
+ .join("\n");
164
+ }
165
+
166
+ /** 折行时续行缩进到 head 之后(列表项的正文、代码块的竖线);rest 是续行开头显示的内容,宽度和 head 相同 */
167
+ function hanging(head: string, body: string, rest = " ".repeat(stringWidth(head))): MdLine {
168
+ return {
169
+ render: (width) => {
170
+ const room = Math.max(1, width - stringWidth(head));
171
+ return wrapAnsi(expandTabs(body), room, { hard: true, trim: false })
172
+ .split("\n")
173
+ // 折行处留下的行尾空格看不见,去掉免得多占一列
174
+ .map((r, i) => (i === 0 ? head : rest) + r.trimEnd());
175
+ },
176
+ };
177
+ }
178
+
179
+ /** 按没转义、不在行内代码里的 | 拆开一行 */
180
+ function splitCells(line: string): string[] {
181
+ const out: string[] = [];
182
+ let cell = "";
183
+ let code = false;
184
+ for (let i = 0; i < line.length; i++) {
185
+ const c = line[i]!;
186
+ if (c === "\\" && line[i + 1] === "|") {
187
+ cell += "|";
188
+ i++;
189
+ } else if (c === "`") {
190
+ code = !code;
191
+ cell += c;
192
+ } else if (c === "|" && !code) {
193
+ out.push(cell);
194
+ cell = "";
195
+ } else cell += c;
196
+ }
197
+ out.push(cell);
198
+ return out;
199
+ }
200
+
201
+ /** 表格一行的各个单元格,去掉两端的 | */
202
+ function cells(line: string): string[] {
203
+ const parts = splitCells(line.trim());
204
+ if (parts.length > 1 && parts[0]!.trim() === "") parts.shift();
205
+ if (parts.length > 1 && parts.at(-1)!.trim() === "") parts.pop();
206
+ return parts.map((c) => c.trim());
207
+ }
208
+
209
+ function tableLine(rows: string[][], align: Align[]): MdLine {
210
+ const shown = rows.map((r, i) => r.map((c) => (i === 0 ? bold(inline(c)) : inline(c))));
211
+ return { render: (width) => renderTable(shown, align, width) };
212
+ }
213
+
214
+ /**
215
+ * 画带边框的表格。放不下时按比例收窄较宽的列、单元格内折行;
216
+ * 窄到每列连 3 列都分不到时,改成每行一段「表头: 值」
217
+ */
218
+ function renderTable(rows: string[][], align: Align[], width: number): string[] {
219
+ const n = Math.max(...rows.map((r) => r.length));
220
+ const grid = rows.map((r) => Array.from({ length: n }, (_, i) => r[i] ?? ""));
221
+ const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => stringWidth(r[i]!))));
222
+ const room = width - (3 * n + 1);
223
+ if (room < 3 * n) {
224
+ const [head, ...body] = grid;
225
+ return body.flatMap((r, k) => [
226
+ ...(k ? [""] : []),
227
+ ...r.flatMap((c, i) => wrapAnsi(`${head![i]}${dim(":")} ${c}`, Math.max(1, width), { hard: true }).split("\n")),
228
+ ]);
229
+ }
230
+ // 从最窄的列开始,能放下的列按原宽,放不下的平分剩下的宽度
231
+ const widths = [...natural];
232
+ if (natural.reduce((a, b) => a + b, 0) > room) {
233
+ let left = room;
234
+ let open = n;
235
+ for (const i of [...natural.keys()].sort((a, b) => natural[a]! - natural[b]!)) {
236
+ const share = Math.floor(left / open);
237
+ widths[i] = Math.min(natural[i]!, share);
238
+ left -= widths[i]!;
239
+ open--;
240
+ }
241
+ }
242
+ const pad = (s: string, w: number, a: Align) => {
243
+ const gap = w - stringWidth(s);
244
+ if (a === "right") return " ".repeat(gap) + s;
245
+ if (a === "center") return " ".repeat(Math.floor(gap / 2)) + s + " ".repeat(Math.ceil(gap / 2));
246
+ return s + " ".repeat(gap);
247
+ };
248
+ const border = (l: string, m: string, r: string) => dim(l + widths.map((w) => "─".repeat(w + 2)).join(m) + r);
249
+ const row = (r: string[]) => {
250
+ const parts = r.map((c, i) => wrapAnsi(c, widths[i]!, { hard: true, trim: true }).split("\n"));
251
+ const height = Math.max(...parts.map((p) => p.length));
252
+ return Array.from({ length: height }, (_, k) =>
253
+ dim("│ ") + parts.map((p, i) => pad(p[k] ?? "", widths[i]!, align[i] ?? "left")).join(dim(" │ ")) + dim(" │"),
254
+ );
255
+ };
256
+ const [head, ...body] = grid;
257
+ return [border("┌", "┬", "┐"), ...row(head!), border("├", "┼", "┤"), ...body.flatMap(row), border("└", "┴", "┘")];
258
+ }
package/src/ui/render.ts CHANGED
@@ -1,15 +1,39 @@
1
- // 宿主显示用的纯函数:工具调用的一行摘要、审批时的预览、折叠的工具结果。不依赖运行时和界面状态。
1
+ // 宿主显示用的纯函数:工具调用的默认摘要和预览、折叠的工具结果。不依赖运行时和界面状态。
2
+ // 各个工具自己的显示见 renderers.ts(jade 的工具)和插件的 renderers。
2
3
 
3
- import { readFile } from "node:fs/promises";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
- import type { PendingCall } from "uncarved";
7
- import { applyEditsToText, display, type Edit } from "../tools/fs.ts";
8
- import { renderDiff } from "./diff.ts";
9
- import { dim, green, red, yellow } from "./screen.ts";
6
+ import { display } from "../tools/fs.ts";
7
+ import { dim } from "./screen.ts";
10
8
 
11
9
  export const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
12
10
 
11
+ /**
12
+ * 带颜色(SGR 序列)的文字截到 n 个可见字符:序列不算长度、不会被切开;截断时在最后复位颜色,
13
+ * 不让没关上的颜色渗到后面的行
14
+ */
15
+ export function clipStyled(s: string, n: number): string {
16
+ const sgr = /\x1b\[[0-9;:]*m/y;
17
+ let out = "";
18
+ let visible = 0;
19
+ let styled = false;
20
+ for (let i = 0; i < s.length; ) {
21
+ sgr.lastIndex = i;
22
+ const m = sgr.exec(s);
23
+ if (m) {
24
+ out += m[0];
25
+ styled = true;
26
+ i += m[0].length;
27
+ continue;
28
+ }
29
+ if (visible === n) return out + "…" + (styled ? "\x1b[0m" : "");
30
+ out += s[i];
31
+ visible++;
32
+ i++;
33
+ }
34
+ return out;
35
+ }
36
+
13
37
  /** 家目录下的路径显示成 ~/… */
14
38
  export function shortPath(p: string): string {
15
39
  const rel = path.relative(os.homedir(), p);
@@ -17,62 +41,16 @@ export function shortPath(p: string): string {
17
41
  return shown.split(path.sep).join("/");
18
42
  }
19
43
 
20
- /** 工具调用的一行摘要,显示在工具名后面的括号里 */
21
- export function summarize(cwd: string, name: string, input: unknown): string {
44
+ /** 工具调用默认的一行摘要,显示在工具名后面的括号里:path 参数,没有时是参数的 JSON */
45
+ export function summarize(cwd: string, input: unknown): string {
22
46
  const i = (input ?? {}) as Record<string, unknown>;
23
- if (name === "bash") return clip(String(i.command ?? "").split("\n")[0]!, 120);
24
- if (name === "task") return String(i.description ?? "");
25
- if (name === "bash_output" || name === "kill_shell") return String(i.id ?? "");
26
- if (name === "todo_write") return `${Array.isArray(i.todos) ? i.todos.length : 0} items`;
27
- if (name === "web_fetch") return clip(String(i.url ?? ""), 120);
28
- if (name === "web_search") return clip(String(i.query ?? ""), 120);
29
- if (name === "memory") return `${i.action} ${i.scope}: ${clip(String(i.text ?? ""), 120)}`;
30
47
  const where = typeof i.path === "string" ? display(cwd, i.path) : "";
31
- if (name === "multi_edit") return `${where}, ${Array.isArray(i.edits) ? i.edits.length : 0} edits`;
32
- if (name === "grep" || name === "glob") return `${i.pattern}${where && where !== "." ? ` in ${where}` : ""}`;
33
48
  return where || clip(JSON.stringify(input), 120);
34
49
  }
35
50
 
36
- /** summarize 省略了内容时(目前只有多行或很长的 bash 命令),调用行展开后先显示完整的参数 */
37
- export function callDetails(name: string, input: unknown): string | undefined {
38
- if (name !== "bash") return undefined;
39
- const command = String(((input ?? {}) as Record<string, unknown>).command ?? "");
40
- const lines = command.split("\n");
41
- if (lines.length === 1 && lines[0]!.length <= 120) return undefined;
42
- return detailsOf(lines.map((l, i) => `${i === 0 ? "$" : " "} ${l}`), dim, 200);
43
- }
44
-
45
- /**
46
- * 审批时显示的内容:修改显示成带行号和上下文的 diff(读出文件、按工具的规则算出修改后的内容),
47
- * 命令显示命令本身。文件读不了、替换不成立时退回到只显示参数里的新旧文本
48
- */
49
- export async function preview(c: PendingCall, cwd: string): Promise<string> {
50
- const i = (c.input ?? {}) as Record<string, unknown>;
51
- const lines = (s: string, mark: string, color: (s: string) => string, max = 30) => {
52
- const all = s.split("\n");
53
- const shown = all.slice(0, max).map((l) => color(`${mark} ${l}`));
54
- if (all.length > max) shown.push(dim(` … ${all.length - max} more lines`));
55
- return shown.join("\n");
56
- };
57
- const raw = (e: Record<string, unknown>) => `${lines(String(e.old_string ?? ""), "-", red)}\n${lines(String(e.new_string ?? ""), "+", green)}`;
58
- const file = typeof i.path === "string" ? path.resolve(cwd, i.path) : undefined;
59
- const current = file ? await readFile(file, "utf8").catch(() => undefined) : undefined;
60
- if (c.name === "edit_file" || (c.name === "multi_edit" && Array.isArray(i.edits))) {
61
- const edits = (c.name === "edit_file" ? [i] : i.edits) as unknown as Edit[];
62
- const fallback = () => edits.map((e) => raw(e as unknown as Record<string, unknown>)).join(dim("\n ⋯\n"));
63
- if (current === undefined) return fallback();
64
- const r = applyEditsToText(current, edits, display(cwd, file!));
65
- if (typeof r === "string") return `${fallback()}\n${yellow(` (this edit will fail: ${clip(r, 200)})`)}`;
66
- return renderDiff(current, r.text);
67
- }
68
- if (c.name === "write_file") {
69
- const content = String(i.content ?? "");
70
- if (current !== undefined) return `${dim(" overwrites the existing file:")}\n${renderDiff(current, content)}`;
71
- return lines(content, "+", green, 20);
72
- }
73
- if (c.name === "bash") return lines(String(i.command ?? ""), "$", (s) => s);
74
- if (c.name === "memory") return `${i.action === "remove" ? red("- ") : green("+ ")}${String(i.text ?? "")}`;
75
- return dim(clip(JSON.stringify(c.input, null, 2), 2000));
51
+ /** 审批时默认的预览:参数的 JSON */
52
+ export function preview(input: unknown): string {
53
+ return dim(clip(JSON.stringify(input, null, 2), 2000));
76
54
  }
77
55
 
78
56
  /** 工具结果展开后的内容:缩进的全部行,超过 max 行时截断 */