@uncarved/jade 0.1.1 → 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 (154) hide show
  1. package/README.md +18 -6
  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 +51 -7
  7. package/dist/distro.js +199 -48
  8. package/dist/distro.js.map +1 -1
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.js +3 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/main.js +479 -303
  13. package/dist/main.js.map +1 -1
  14. package/dist/mcp.js +1 -1
  15. package/dist/mcp.js.map +1 -1
  16. package/dist/plugin-cli.d.ts +1 -1
  17. package/dist/plugin-cli.js +79 -36
  18. package/dist/plugin-cli.js.map +1 -1
  19. package/dist/plugins/budget.d.ts +2 -2
  20. package/dist/plugins/budget.js +2 -2
  21. package/dist/plugins/budget.js.map +1 -1
  22. package/dist/plugins/builtins.js +6 -3
  23. package/dist/plugins/builtins.js.map +1 -1
  24. package/dist/plugins/checks.d.ts +2 -1
  25. package/dist/plugins/checks.js +25 -5
  26. package/dist/plugins/checks.js.map +1 -1
  27. package/dist/plugins/compact.js +45 -1
  28. package/dist/plugins/compact.js.map +1 -1
  29. package/dist/plugins/core.d.ts +5 -0
  30. package/dist/plugins/core.js +39 -0
  31. package/dist/plugins/core.js.map +1 -1
  32. package/dist/plugins/host.d.ts +52 -0
  33. package/dist/plugins/host.js +115 -0
  34. package/dist/plugins/host.js.map +1 -0
  35. package/dist/plugins/install.d.ts +1 -1
  36. package/dist/plugins/loader.d.ts +238 -10
  37. package/dist/plugins/loader.js +175 -21
  38. package/dist/plugins/loader.js.map +1 -1
  39. package/dist/plugins/policy.d.ts +23 -5
  40. package/dist/plugins/policy.js +63 -10
  41. package/dist/plugins/policy.js.map +1 -1
  42. package/dist/plugins/prompts.d.ts +14 -1
  43. package/dist/plugins/prompts.js +118 -16
  44. package/dist/plugins/prompts.js.map +1 -1
  45. package/dist/plugins/repeats.d.ts +7 -0
  46. package/dist/plugins/repeats.js +74 -13
  47. package/dist/plugins/repeats.js.map +1 -1
  48. package/dist/plugins/review.d.ts +18 -0
  49. package/dist/plugins/review.js +130 -0
  50. package/dist/plugins/review.js.map +1 -0
  51. package/dist/plugins/sessions.d.ts +7 -0
  52. package/dist/plugins/sessions.js +110 -0
  53. package/dist/plugins/sessions.js.map +1 -0
  54. package/dist/provider.d.ts +57 -3
  55. package/dist/provider.js +80 -10
  56. package/dist/provider.js.map +1 -1
  57. package/dist/session-lifecycle.d.ts +61 -0
  58. package/dist/session-lifecycle.js +167 -0
  59. package/dist/session-lifecycle.js.map +1 -0
  60. package/dist/session-scope.d.ts +53 -0
  61. package/dist/session-scope.js +116 -0
  62. package/dist/session-scope.js.map +1 -0
  63. package/dist/sessions.d.ts +6 -0
  64. package/dist/sessions.js +20 -0
  65. package/dist/sessions.js.map +1 -1
  66. package/dist/sys.d.ts +4 -1
  67. package/dist/sys.js +18 -1
  68. package/dist/sys.js.map +1 -1
  69. package/dist/tools/ask.d.ts +11 -0
  70. package/dist/tools/ask.js +62 -0
  71. package/dist/tools/ask.js.map +1 -0
  72. package/dist/tools/fs.d.ts +4 -0
  73. package/dist/tools/fs.js +53 -12
  74. package/dist/tools/fs.js.map +1 -1
  75. package/dist/tools/grep.js +3 -2
  76. package/dist/tools/grep.js.map +1 -1
  77. package/dist/tools/shell.js +5 -1
  78. package/dist/tools/shell.js.map +1 -1
  79. package/dist/tools/task.d.ts +10 -2
  80. package/dist/tools/task.js +40 -9
  81. package/dist/tools/task.js.map +1 -1
  82. package/dist/tools/web.d.ts +33 -3
  83. package/dist/tools/web.js +351 -143
  84. package/dist/tools/web.js.map +1 -1
  85. package/dist/ui/configure.js +144 -66
  86. package/dist/ui/configure.js.map +1 -1
  87. package/dist/ui/diff.d.ts +1 -1
  88. package/dist/ui/diff.js +1 -2
  89. package/dist/ui/diff.js.map +1 -1
  90. package/dist/ui/editor.d.ts +8 -0
  91. package/dist/ui/editor.js +50 -1
  92. package/dist/ui/editor.js.map +1 -1
  93. package/dist/ui/markdown.d.ts +22 -0
  94. package/dist/ui/markdown.js +242 -0
  95. package/dist/ui/markdown.js.map +1 -0
  96. package/dist/ui/render.d.ts +9 -8
  97. package/dist/ui/render.js +35 -62
  98. package/dist/ui/render.js.map +1 -1
  99. package/dist/ui/renderers.d.ts +8 -0
  100. package/dist/ui/renderers.js +169 -0
  101. package/dist/ui/renderers.js.map +1 -0
  102. package/dist/ui/screen.d.ts +25 -2
  103. package/dist/ui/screen.js +104 -12
  104. package/dist/ui/screen.js.map +1 -1
  105. package/dist/ui/transcript.d.ts +13 -0
  106. package/dist/ui/transcript.js +157 -31
  107. package/dist/ui/transcript.js.map +1 -1
  108. package/dist/ui/tui.d.ts +2 -0
  109. package/dist/ui/tui.js +383 -81
  110. package/dist/ui/tui.js.map +1 -1
  111. package/dist/update.d.ts +53 -0
  112. package/dist/update.js +255 -0
  113. package/dist/update.js.map +1 -0
  114. package/package.json +7 -6
  115. package/src/commands.ts +24 -0
  116. package/src/distro.ts +234 -52
  117. package/src/index.ts +3 -0
  118. package/src/main.ts +459 -300
  119. package/src/mcp.ts +1 -1
  120. package/src/plugin-cli.ts +73 -34
  121. package/src/plugins/budget.ts +4 -4
  122. package/src/plugins/builtins.ts +6 -3
  123. package/src/plugins/checks.ts +25 -6
  124. package/src/plugins/compact.ts +40 -1
  125. package/src/plugins/core.ts +40 -0
  126. package/src/plugins/host.ts +146 -0
  127. package/src/plugins/install.ts +1 -1
  128. package/src/plugins/loader.ts +379 -23
  129. package/src/plugins/policy.ts +70 -13
  130. package/src/plugins/prompts.ts +128 -16
  131. package/src/plugins/repeats.ts +75 -14
  132. package/src/plugins/review.ts +146 -0
  133. package/src/plugins/sessions.ts +109 -0
  134. package/src/provider.ts +117 -14
  135. package/src/session-lifecycle.ts +194 -0
  136. package/src/session-scope.ts +135 -0
  137. package/src/sessions.ts +17 -0
  138. package/src/sys.ts +18 -1
  139. package/src/tools/ask.ts +72 -0
  140. package/src/tools/fs.ts +53 -12
  141. package/src/tools/grep.ts +3 -2
  142. package/src/tools/shell.ts +5 -1
  143. package/src/tools/task.ts +56 -12
  144. package/src/tools/web.ts +370 -140
  145. package/src/ui/configure.ts +141 -67
  146. package/src/ui/diff.ts +1 -2
  147. package/src/ui/editor.ts +50 -1
  148. package/src/ui/markdown.ts +258 -0
  149. package/src/ui/render.ts +35 -48
  150. package/src/ui/renderers.ts +183 -0
  151. package/src/ui/screen.ts +113 -16
  152. package/src/ui/transcript.ts +164 -35
  153. package/src/ui/tui.tsx +424 -79
  154. package/src/update.ts +262 -0
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,53 +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
- /**
37
- * 审批时显示的内容:修改显示成带行号和上下文的 diff(读出文件、按工具的规则算出修改后的内容),
38
- * 命令显示命令本身。文件读不了、替换不成立时退回到只显示参数里的新旧文本
39
- */
40
- export async function preview(c: PendingCall, cwd: string): Promise<string> {
41
- const i = (c.input ?? {}) as Record<string, unknown>;
42
- const lines = (s: string, mark: string, color: (s: string) => string, max = 30) => {
43
- const all = s.split("\n");
44
- const shown = all.slice(0, max).map((l) => color(`${mark} ${l}`));
45
- if (all.length > max) shown.push(dim(` … ${all.length - max} more lines`));
46
- return shown.join("\n");
47
- };
48
- const raw = (e: Record<string, unknown>) => `${lines(String(e.old_string ?? ""), "-", red)}\n${lines(String(e.new_string ?? ""), "+", green)}`;
49
- const file = typeof i.path === "string" ? path.resolve(cwd, i.path) : undefined;
50
- const current = file ? await readFile(file, "utf8").catch(() => undefined) : undefined;
51
- if (c.name === "edit_file" || (c.name === "multi_edit" && Array.isArray(i.edits))) {
52
- const edits = (c.name === "edit_file" ? [i] : i.edits) as unknown as Edit[];
53
- const fallback = () => edits.map((e) => raw(e as unknown as Record<string, unknown>)).join(dim("\n ⋯\n"));
54
- if (current === undefined) return fallback();
55
- const r = applyEditsToText(current, edits, display(cwd, file!));
56
- if (typeof r === "string") return `${fallback()}\n${yellow(` (this edit will fail: ${clip(r, 200)})`)}`;
57
- return renderDiff(current, r.text);
58
- }
59
- if (c.name === "write_file") {
60
- const content = String(i.content ?? "");
61
- if (current !== undefined) return `${dim(" overwrites the existing file:")}\n${renderDiff(current, content)}`;
62
- return lines(content, "+", green, 20);
63
- }
64
- if (c.name === "bash") return lines(String(i.command ?? ""), "$", (s) => s);
65
- if (c.name === "memory") return `${i.action === "remove" ? red("- ") : green("+ ")}${String(i.text ?? "")}`;
66
- 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));
67
54
  }
68
55
 
69
56
  /** 工具结果展开后的内容:缩进的全部行,超过 max 行时截断 */
@@ -0,0 +1,183 @@
1
+ // jade 自己的工具怎么显示:和插件一样用 ToolRenderer(见 plugins/loader.ts),由提供这些工具的内置插件带上。
2
+ // 没有 renderer 的工具、renderer 没给的部分用 transcript 的默认显示。
3
+
4
+ import { readFileSync } from "node:fs";
5
+ import { readFile } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import type { ToolRenderer } from "../plugins/loader.ts";
8
+ import { applyEditsToText, display, type Edit } from "../tools/fs.ts";
9
+ import { diffLines, diffStats, renderDiff } from "./diff.ts";
10
+ import { clip } from "./render.ts";
11
+ import { dim, green, red, yellow } from "./screen.ts";
12
+
13
+ type Args = Record<string, unknown>;
14
+ const args = (input: unknown) => (input ?? {}) as Args;
15
+ const pathOf = (cwd: string, i: Args) => (typeof i.path === "string" ? display(cwd, i.path) : "");
16
+
17
+ /** 预览里的多行文字:每行前面加上标记,最多 max 行 */
18
+ function marked(s: string, mark: string, color: (s: string) => string, max = 30): string {
19
+ const all = s.split("\n");
20
+ const shown = all.slice(0, max).map((l) => color(`${mark} ${l}`));
21
+ if (all.length > max) shown.push(dim(` … ${all.length - max} more lines`));
22
+ return shown.join("\n");
23
+ }
24
+
25
+ /** 折叠内容里的多行文字(缩进由 transcript 加),最多 max 行 */
26
+ function capped(lines: string[], color: (s: string) => string, max: number): string {
27
+ const shown = lines.slice(0, max).map(color);
28
+ if (lines.length > max) shown.push(dim(`… ${lines.length - max} more lines`));
29
+ return shown.join("\n");
30
+ }
31
+
32
+ // ---------- 文件 ----------
33
+
34
+ type FileTool = "edit_file" | "multi_edit" | "write_file";
35
+ const editsOf = (tool: FileTool, i: Args) => (tool === "edit_file" ? [i] : Array.isArray(i.edits) ? i.edits : []) as unknown as Edit[];
36
+
37
+ /**
38
+ * 审批时的预览:带行号和上下文的 diff(读出文件、按工具的规则算出修改后的内容)。
39
+ * 文件读不了、替换不成立时退回到只显示参数里的新旧文本
40
+ */
41
+ async function filePreview(cwd: string, tool: FileTool, input: unknown): Promise<string> {
42
+ const i = args(input);
43
+ const file = typeof i.path === "string" ? path.resolve(cwd, i.path) : undefined;
44
+ const current = file ? await readFile(file, "utf8").catch(() => undefined) : undefined;
45
+ if (tool === "write_file") {
46
+ const content = String(i.content ?? "");
47
+ if (current !== undefined) return `${dim(" overwrites the existing file:")}\n${renderDiff(current, content)}`;
48
+ return marked(content, "+", green, 20);
49
+ }
50
+ if (tool === "multi_edit" && !Array.isArray(i.edits)) return dim(clip(JSON.stringify(input, null, 2), 2000));
51
+ const edits = editsOf(tool, i);
52
+ const raw = (e: Args) => `${marked(String(e.old_string ?? ""), "-", red)}\n${marked(String(e.new_string ?? ""), "+", green)}`;
53
+ const fallback = () => edits.map((e) => raw(e as unknown as Args)).join(dim("\n ⋯\n"));
54
+ if (current === undefined) return fallback();
55
+ const r = applyEditsToText(current, edits, display(cwd, file!));
56
+ if (typeof r === "string") return `${fallback()}\n${yellow(` (this edit will fail: ${clip(r, 200)})`)}`;
57
+ return renderDiff(current, r.text);
58
+ }
59
+
60
+ interface FileDiff {
61
+ added: number;
62
+ removed: number;
63
+ text: string;
64
+ }
65
+
66
+ /** 对话里折叠的 diff 最多显示这么多行 */
67
+ const MAX_DIFF_LINES = 400;
68
+ /** 结果文字(例如编辑后检查的输出)折叠起来最多这么多行 */
69
+ const MAX_RESULT_LINES = 2000;
70
+
71
+ /**
72
+ * 执行前后的差异。在工具执行之前调用(读的是修改前的文件),同步读文件:
73
+ * 执行前的事件通知是同步的,等异步读完文件可能已经改了。替换不成立时返回 undefined
74
+ */
75
+ function fileDiff(cwd: string, tool: FileTool, input: unknown): FileDiff | undefined {
76
+ const i = args(input);
77
+ if (typeof i.path !== "string") return undefined;
78
+ const file = path.resolve(cwd, i.path);
79
+ let before: string | undefined;
80
+ try {
81
+ before = readFileSync(file, "utf8");
82
+ } catch {}
83
+ let after: string;
84
+ if (tool === "write_file") {
85
+ after = String(i.content ?? "");
86
+ } else {
87
+ if (before === undefined) return undefined;
88
+ const r = applyEditsToText(before, editsOf(tool, i), display(cwd, file));
89
+ if (typeof r === "string") return undefined;
90
+ after = r.text;
91
+ }
92
+ const lines = diffLines(before ?? "", after);
93
+ const { added, removed } = diffStats(lines);
94
+ return { added, removed, text: renderDiff(before ?? "", after, MAX_DIFF_LINES, lines) };
95
+ }
96
+
97
+ /** 修改文件的工具:预览是 diff;结果行后面是增删的行数,展开看完整的 diff */
98
+ function fileRenderer(cwd: string, tool: FileTool, summary?: (input: unknown) => string): ToolRenderer {
99
+ return {
100
+ tool,
101
+ summary,
102
+ preview: (input) => filePreview(cwd, tool, input),
103
+ before: (input) => fileDiff(cwd, tool, input),
104
+ result: ({ text, isError, before }) => {
105
+ const diff = before as FileDiff | undefined;
106
+ if (!diff || isError) return undefined;
107
+ const [first = "", ...rest] = text.split("\n");
108
+ const extra = rest.length ? [capped(rest, (s) => s, MAX_RESULT_LINES)] : [];
109
+ return { line: dim(`${clip(first, 150)} `) + `${green(`+${diff.added}`)} ${red(`-${diff.removed}`)}`, details: [...extra, diff.text].join("\n") };
110
+ },
111
+ };
112
+ }
113
+
114
+ export function fsRenderers(cwd: string): ToolRenderer[] {
115
+ const search = (input: unknown) => {
116
+ const i = args(input);
117
+ const where = pathOf(cwd, i);
118
+ return `${i.pattern}${where && where !== "." ? ` in ${where}` : ""}`;
119
+ };
120
+ return [
121
+ fileRenderer(cwd, "edit_file"),
122
+ fileRenderer(cwd, "multi_edit", (input) => {
123
+ const i = args(input);
124
+ return `${pathOf(cwd, i)}, ${Array.isArray(i.edits) ? i.edits.length : 0} edits`;
125
+ }),
126
+ fileRenderer(cwd, "write_file"),
127
+ { tool: "grep", summary: search },
128
+ { tool: "glob", summary: search },
129
+ ];
130
+ }
131
+
132
+ // ---------- 其他内置工具 ----------
133
+
134
+ export const shellRenderers: ToolRenderer[] = [
135
+ {
136
+ tool: "bash",
137
+ summary: (input) => clip(String(args(input).command ?? "").split("\n")[0]!, 120),
138
+ // 摘要省略了内容时(多行或很长的命令),展开后先显示完整的命令
139
+ details: (input) => {
140
+ const lines = String(args(input).command ?? "").split("\n");
141
+ if (lines.length === 1 && lines[0]!.length <= 120) return undefined;
142
+ return capped(lines.map((l, i) => `${i === 0 ? "$" : " "} ${l}`), dim, 200);
143
+ },
144
+ preview: (input) => marked(String(args(input).command ?? ""), "$", (s) => s),
145
+ },
146
+ { tool: "bash_output", summary: (input) => String(args(input).id ?? "") },
147
+ { tool: "kill_shell", summary: (input) => String(args(input).id ?? "") },
148
+ ];
149
+
150
+ export const webRenderers: ToolRenderer[] = [
151
+ { tool: "web_fetch", summary: (input) => clip(String(args(input).url ?? ""), 120) },
152
+ { tool: "web_search", summary: (input) => clip(String(args(input).query ?? ""), 120) },
153
+ ];
154
+
155
+ export const todoRenderers: ToolRenderer[] = [
156
+ { tool: "todo_write", summary: (input) => `${Array.isArray(args(input).todos) ? (args(input).todos as unknown[]).length : 0} items` },
157
+ ];
158
+
159
+ export const askRenderers: ToolRenderer[] = [
160
+ {
161
+ tool: "ask_user",
162
+ summary: (input) => {
163
+ const q = args(input).questions;
164
+ return Array.isArray(q) && q.length === 1 ? clip(String(q[0]?.question ?? ""), 120) : `${Array.isArray(q) ? q.length : 0} questions`;
165
+ },
166
+ },
167
+ ];
168
+
169
+ export const memoryRenderers: ToolRenderer[] = [
170
+ {
171
+ tool: "memory",
172
+ summary: (input) => {
173
+ const i = args(input);
174
+ return `${i.action} ${i.scope}: ${clip(String(i.text ?? ""), 120)}`;
175
+ },
176
+ preview: (input) => {
177
+ const i = args(input);
178
+ return `${i.action === "remove" ? red("- ") : green("+ ")}${String(i.text ?? "")}`;
179
+ },
180
+ },
181
+ ];
182
+
183
+ export const taskRenderers: ToolRenderer[] = [{ tool: "task", summary: (input) => String(args(input).description ?? "") }];
package/src/ui/screen.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // - 纯文本(这里):-p 和非交互运行时使用,逐行输出,提问用 readline
4
4
 
5
5
  import { createInterface, type Interface } from "node:readline/promises";
6
+ import { stripVTControlCharacters } from "node:util";
6
7
 
7
8
  export interface Choice<T> {
8
9
  label: string;
@@ -12,6 +13,8 @@ export interface Choice<T> {
12
13
  }
13
14
 
14
15
  export interface StatusInfo {
16
+ /** 插件用 ctx.status 设置的段落(已经是一行、截断过) */
17
+ plugins?: { plugin: string; text: string }[];
15
18
  cwd: string;
16
19
  branch?: string;
17
20
  model: string;
@@ -62,10 +65,12 @@ export interface Screen {
62
65
  status(info: Partial<StatusInfo>): void;
63
66
  /** 排队等待发送的输入 */
64
67
  queued(items: string[]): void;
65
- /** 让用户从几项里选一项;取消时返回 undefined */
66
- select<T>(title: string, choices: Choice<T>[], opts?: { body?: string }): Promise<T | undefined>;
67
- /** 让用户输入一行;取消时返回 undefined */
68
- input(title: string, opts?: { initial?: string; mask?: boolean; placeholder?: string }): Promise<string | undefined>;
68
+ /** 让用户从几项里选一项;取消时返回 undefined。signal 中止时关掉对话框,也返回 undefined */
69
+ select<T>(title: string, choices: Choice<T>[], opts?: { body?: string; signal?: AbortSignal }): Promise<T | undefined>;
70
+ /** 让用户输入一行;取消时返回 undefined。signal 同 select */
71
+ input(title: string, opts?: { initial?: string; mask?: boolean; placeholder?: string; signal?: AbortSignal }): Promise<string | undefined>;
72
+ /** 输入框里还没提交的文字(插件的 ctx.input 用);只有终端界面有 */
73
+ readonly draft?: { text(): string; insert(text: string): void; set(text: string): void };
69
74
  /** 清空已经显示的对话(开始新会话时) */
70
75
  clear(): void;
71
76
  close(): Promise<void>;
@@ -73,14 +78,96 @@ export interface Screen {
73
78
 
74
79
  // ---------- 颜色 ----------
75
80
 
76
- const colors = Boolean(process.stdout.isTTY);
77
- const paint = (code: string) => (s: string) => (colors ? `\x1b[${code}m${s}\x1b[0m` : s);
78
- export const dim = paint("2");
79
- export const red = paint("31");
80
- export const green = paint("32");
81
- export const yellow = paint("33");
82
- export const cyan = paint("36");
83
- export const bold = paint("1");
81
+ // 设了 NO_COLOR(非空)时不输出颜色,见 https://no-color.org
82
+ const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
83
+ /**
84
+ * 每种样式用自己的关闭码,不用 \x1b[0m 全部重置:粗体里套着行内代码、链接时,后面的文字仍是粗体。
85
+ * 里面出现同一个关闭码(例如 dim 里套 bold,两者都用 22 关闭)时紧接着重新打开外层的样式
86
+ */
87
+ const paint = (open: string, close: string) => (s: string) =>
88
+ colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
89
+ export const dim = paint("2", "22");
90
+ export const red = paint("31", "39");
91
+ export const green = paint("32", "39");
92
+ export const yellow = paint("33", "39");
93
+ export const cyan = paint("36", "39");
94
+ export const bold = paint("1", "22");
95
+ export const italic = paint("3", "23");
96
+ export const underline = paint("4", "24");
97
+ export const strike = paint("9", "29");
98
+
99
+ // ---------- 过滤控制字符 ----------
100
+
101
+ /** 转义序列(CSI、OSC、DCS 这类字符串、其余 ESC 开头的)和换行、制表符之外的控制字符(含 C1) */
102
+ const CONTROL = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b[\]P^_X][^\x07\x1b]*(?:\x07|\x1b\\)?|\x1b[^[\]P^_X]?|[\x00-\x08\x0b-\x1f\x7f-\x9f]/g;
103
+ const SGR = /^\x1b\[[0-9;:]*m$/;
104
+ /** 文字末尾还没写完的转义序列:单独的 ESC、没有结束字节的 CSI、没有结束符的 OSC/DCS 这类字符串 */
105
+ const UNFINISHED = /\x1b(?:\[[0-?]*[ -/]*|[\]P^_X][^\x07\x1b]*)?$/;
106
+ /** 最多为一个没写完的序列留这么多字符 */
107
+ const MAX_HELD = 256;
108
+
109
+ /**
110
+ * 去掉可能搅乱终端的东西,只留颜色(SGR)、换行和制表符:插件、工具输出和模型的文字里可能有移动光标、清屏、
111
+ * 改窗口标题、写剪贴板之类的序列。单独的 \r(进度条)按终端的效果处理:每行只留最后一段
112
+ */
113
+ export function terminalSafe(text: string): string {
114
+ const lines = text.replaceAll("\r\n", "\n").split("\n");
115
+ return lines
116
+ .map((l) => (l.includes("\r") ? (l.split("\r").filter(Boolean).at(-1) ?? "") : l).replace(CONTROL, (m) => (SGR.test(m) ? m : "")))
117
+ .join("\n");
118
+ }
119
+
120
+ /** 让显示到屏幕上的每一段文字都经过 terminalSafe */
121
+ export function safeScreen(screen: Screen): Screen {
122
+ const s = terminalSafe;
123
+ const opt = (v: string | undefined) => (v === undefined ? undefined : s(v));
124
+ const lf = (t: string) => t.replace(/\r\n?/g, "\n");
125
+ const plain = (t: string) => stripVTControlCharacters(s(t));
126
+ /** 流式文字末尾还没写完的转义序列,等下一段 */
127
+ let held: { kind: "text" | "thinking"; text: string } | undefined;
128
+ return {
129
+ interactive: screen.interactive,
130
+ log: (text, o) => screen.log(s(text), o && { ...o, details: opt(o.details) }),
131
+ amend: (id, text, o) => screen.amend(id, s(text), o && { ...o, details: opt(o.details) }),
132
+ progress: (id, line, o) => screen.progress(id, opt(line), o),
133
+ stream: (kind, text) => {
134
+ // 上一段末尾没完的转义序列接到这一段前面再过滤,不然它被拆成两半,后一半当成文字显示出来
135
+ if (held && held.kind !== kind) held = undefined;
136
+ const whole = (held?.text ?? "") + text;
137
+ // 很长还没结束的(OSC 之类的字符串一直不给结束符)不再等,按现在的样子过滤
138
+ const found = whole.search(UNFINISHED);
139
+ const cut = found >= 0 && whole.length - found <= MAX_HELD ? found : -1;
140
+ held = cut >= 0 ? { kind, text: whole.slice(cut) } : undefined;
141
+ const shown = s(cut >= 0 ? whole.slice(0, cut) : whole);
142
+ if (shown) screen.stream(kind, shown);
143
+ },
144
+ endStream: () => {
145
+ // 到结束都没写完的序列不完整,丢掉
146
+ held = undefined;
147
+ screen.endStream();
148
+ },
149
+ busy: (label) => screen.busy(opt(label)),
150
+ status: (info) => {
151
+ const out: Partial<StatusInfo> = { ...info };
152
+ for (const k of ["cwd", "branch", "model", "mode", "session"] as const) if (typeof info[k] === "string") out[k] = s(info[k]);
153
+ if (info.plugins) out.plugins = info.plugins.map((p) => ({ plugin: p.plugin, text: s(p.text) }));
154
+ screen.status(out);
155
+ },
156
+ queued: (items) => screen.queued(items.map(s)),
157
+ select: (title, choices, o) =>
158
+ screen.select(
159
+ s(title),
160
+ choices.map((c) => ({ ...c, label: s(c.label), hint: opt(c.hint) })),
161
+ o && { ...o, body: opt(o.body) },
162
+ ),
163
+ input: (title, o) => screen.input(s(title), o && { ...o, initial: opt(o.initial), placeholder: opt(o.placeholder) }),
164
+ // 输入框里的 \r 是换行(旧 Mac 的换行符),不是进度条:先换成 \n,terminalSafe 才不会只留最后一段。
165
+ // 输入框里是要发给模型的纯文字,颜色也去掉
166
+ draft: screen.draft && { text: () => screen.draft!.text(), insert: (t) => screen.draft!.insert(plain(lf(t))), set: (t) => screen.draft!.set(plain(lf(t))) },
167
+ clear: () => screen.clear(),
168
+ close: () => screen.close(),
169
+ };
170
+ }
84
171
 
85
172
  // ---------- 纯文本实现 ----------
86
173
 
@@ -102,9 +189,16 @@ export function plainScreen(opts: { interactive: boolean }): Screen {
102
189
  if (!atLineStart) write("\n");
103
190
  write(s + "\n");
104
191
  };
105
- const ask = async (q: string) => {
192
+ /** 中止时返回 undefined */
193
+ const ask = async (q: string, signal?: AbortSignal) => {
106
194
  rl ??= createInterface({ input: process.stdin, output: process.stdout, terminal: true });
107
- return (await rl.question(q)).trim();
195
+ try {
196
+ return (await rl.question(q, { signal })).trim();
197
+ } catch (err) {
198
+ if (!signal?.aborted) throw err;
199
+ write("\n");
200
+ return undefined;
201
+ }
108
202
  };
109
203
 
110
204
  return {
@@ -151,12 +245,15 @@ export function plainScreen(opts: { interactive: boolean }): Screen {
151
245
  line(yellow(title));
152
246
  if (o?.body) line(o.body);
153
247
  choices.forEach((c, i) => line(` ${i + 1}. ${c.label}${c.hint ? dim(` ${c.hint}`) : ""}`));
154
- const n = Number(await ask(`Choose 1-${choices.length} (empty to cancel): `));
248
+ if (o?.signal?.aborted) return undefined;
249
+ const n = Number(await ask(`Choose 1-${choices.length} (empty to cancel): `, o?.signal));
155
250
  return Number.isInteger(n) && n >= 1 && n <= choices.length ? choices[n - 1]!.value : undefined;
156
251
  },
157
252
  async input(title, o) {
158
253
  if (!opts.interactive) return undefined;
159
- return (await ask(`${title}${o?.initial ? ` [${o.initial}]` : ""}: `)) || o?.initial || "";
254
+ if (o?.signal?.aborted) return undefined;
255
+ const answer = await ask(`${title}${o?.initial ? ` [${o.initial}]` : ""}: `, o?.signal);
256
+ return answer === undefined ? undefined : answer || o?.initial || "";
160
257
  },
161
258
  clear: () => {},
162
259
  async close() {