@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
@@ -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,17 +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");
84
- export const italic = paint("3");
85
- export const underline = paint("4");
86
- export const strike = paint("9");
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
+ }
87
171
 
88
172
  // ---------- 纯文本实现 ----------
89
173
 
@@ -105,9 +189,16 @@ export function plainScreen(opts: { interactive: boolean }): Screen {
105
189
  if (!atLineStart) write("\n");
106
190
  write(s + "\n");
107
191
  };
108
- const ask = async (q: string) => {
192
+ /** 中止时返回 undefined */
193
+ const ask = async (q: string, signal?: AbortSignal) => {
109
194
  rl ??= createInterface({ input: process.stdin, output: process.stdout, terminal: true });
110
- 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
+ }
111
202
  };
112
203
 
113
204
  return {
@@ -154,12 +245,15 @@ export function plainScreen(opts: { interactive: boolean }): Screen {
154
245
  line(yellow(title));
155
246
  if (o?.body) line(o.body);
156
247
  choices.forEach((c, i) => line(` ${i + 1}. ${c.label}${c.hint ? dim(` ${c.hint}`) : ""}`));
157
- 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));
158
250
  return Number.isInteger(n) && n >= 1 && n <= choices.length ? choices[n - 1]!.value : undefined;
159
251
  },
160
252
  async input(title, o) {
161
253
  if (!opts.interactive) return undefined;
162
- 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 || "";
163
257
  },
164
258
  clear: () => {},
165
259
  async close() {
@@ -7,7 +7,9 @@ import { readAll, type Block, type EventDataMap, type LogEvent, type LogStore, t
7
7
  import type { ShellProgress } from "../tools/shell.ts";
8
8
  import type { TaskProgress } from "../tools/task.ts";
9
9
  import { renderTodos, type Todo } from "../tools/todo.ts";
10
- import { callDetails, clip, detailsOf, summarize } from "./render.ts";
10
+ import type { ToolRenderer } from "../plugins/loader.ts";
11
+ import type { PendingCall } from "uncarved";
12
+ import { clip, clipStyled, detailsOf, preview, summarize } from "./render.ts";
11
13
  import { bold, cyan, dim, green, red, yellow, type Screen } from "./screen.ts";
12
14
 
13
15
  export type Notice = Parameters<Parameters<Runtime["subscribe"]>[0]>[0];
@@ -23,6 +25,8 @@ export interface TranscriptOptions {
23
25
  compactAt?(): number;
24
26
  /** 上一轮失败后能否用 /retry 重新请求 */
25
27
  canRetry(): boolean;
28
+ /** 插件为自己的工具注册的显示方式(随会话的插件实例变) */
29
+ renderer?(tool: string): { plugin: string; renderer: ToolRenderer } | undefined;
26
30
  }
27
31
 
28
32
  export interface Transcript {
@@ -41,6 +45,12 @@ export interface Transcript {
41
45
  turnFailed: boolean;
42
46
  /** 开始新会话时清空 */
43
47
  reset(): void;
48
+ /** 工具调用括号里的一行摘要:插件的 renderer 优先 */
49
+ summary(name: string, input: unknown): string;
50
+ /** 摘要省略了的参数,调用行展开后显示在最前面(已经缩进);没有时是 undefined */
51
+ details(name: string, input: unknown): string | undefined;
52
+ /** 审批时的预览:工具的 renderer 给的,没有时是参数的 JSON */
53
+ preview(c: PendingCall): Promise<string>;
44
54
  }
45
55
 
46
56
  /** 工具结果折叠起来的完整内容最多这么多行 */
@@ -67,15 +77,20 @@ export function transcript(opts: TranscriptOptions): Transcript {
67
77
  }
68
78
  }
69
79
 
70
- /** 服务端报过缓存命中数。有的服务只在命中时才带这个字段,报过一次之后没带就是没命中 */
71
- let reportsCache = false;
80
+ /**
81
+ * 报过缓存命中数的 provider/模型。有的服务只在命中时才带这个字段,报过一次之后没带就是没命中;
82
+ * 换了服务或模型要重新看,否则从报缓存的服务换到不报的,会一直显示 0%
83
+ */
84
+ let reportsCache: string | undefined;
72
85
  /** 上下文用量:最近一次回复的输入加输出,就是下一次请求的大致起点;以及这次输入的缓存命中率 */
73
- function showContext(u: Usage | undefined) {
86
+ function showContext(e: LogEvent<"model.responded">) {
87
+ const u = e.data.usage;
74
88
  if (u?.inputTokens === undefined) return;
75
- if (u.cacheReadTokens !== undefined) reportsCache = true;
89
+ const by = e.origin.by === "model" ? `${e.origin.provider}/${e.origin.model}` : "";
90
+ if (u.cacheReadTokens !== undefined) reportsCache = by;
76
91
  screen.status({
77
92
  context: { used: u.inputTokens + (u.outputTokens ?? 0), limit: opts.contextWindow(), compactAt: opts.compactAt?.() },
78
- cache: reportsCache && u.inputTokens > 0 ? (u.cacheReadTokens ?? 0) / u.inputTokens : undefined,
93
+ cache: reportsCache === by && u.inputTokens > 0 ? (u.cacheReadTokens ?? 0) / u.inputTokens : undefined,
79
94
  });
80
95
  }
81
96
 
@@ -88,7 +103,11 @@ export function transcript(opts: TranscriptOptions): Transcript {
88
103
  const startSpeed = () => {
89
104
  speed.first = 0;
90
105
  speed.estimate = 0;
106
+ toolChars = 0;
91
107
  };
108
+ /** 这次回复里工具参数已经生成的字数:写大文件时一写几分钟,显示出来才看得出不是卡住了 */
109
+ let toolChars = 0;
110
+ const toolLabel = () => (toolChars < 1000 ? "Writing" : `Writing (${Math.floor(toolChars / 1000)}k chars)`);
92
111
  const trackSpeed = (text: string) => {
93
112
  const now = Date.now();
94
113
  if (!speed.first) speed.first = now;
@@ -123,13 +142,55 @@ export function transcript(opts: TranscriptOptions): Transcript {
123
142
  const tasks = new Map<string, string>();
124
143
  /** 调用行省略了的参数(例如很长的命令),结果出来后放在折叠内容的最前面 */
125
144
  const calls = new Map<string, string>();
126
- const progress = (id: string, line: string, o?: { output?: boolean }) => {
145
+ /** renderer 的 before 在执行前记下的东西,结果出来时交给它的 result */
146
+ const befores = new Map<string, unknown>();
147
+ const progress =(id: string, line: string, o?: { output?: boolean }) => {
127
148
  running.add(id);
128
149
  screen.progress(id, line, o);
129
150
  };
130
151
  const doneProgress = (id: string) => {
131
152
  if (running.delete(id)) screen.progress(id, undefined);
132
153
  };
154
+ /** 有 result renderer 的调用的参数,结果出来时交给它 */
155
+ const inputs = new Map<string, unknown>();
156
+
157
+ /** 出过错的 renderer(插件 + 工具),只提示一次 */
158
+ const failed = new Set<string>();
159
+ /** 调用插件的 renderer;没有、出错时返回 undefined(用默认的显示) */
160
+ async function custom<T>(name: string, use: (r: ToolRenderer) => T | undefined | Promise<T | undefined>): Promise<T | undefined> {
161
+ const found = opts.renderer?.(name);
162
+ if (!found) return undefined;
163
+ try {
164
+ return await use(found.renderer);
165
+ } catch (err) {
166
+ renderFailed(found.plugin, name, err);
167
+ return undefined;
168
+ }
169
+ }
170
+ /** 同步的版本:摘要和结果在事件通知里同步显示 */
171
+ function customSync<T>(name: string, use: (r: ToolRenderer) => T | undefined): T | undefined {
172
+ const found = opts.renderer?.(name);
173
+ if (!found) return undefined;
174
+ try {
175
+ return use(found.renderer);
176
+ } catch (err) {
177
+ renderFailed(found.plugin, name, err);
178
+ return undefined;
179
+ }
180
+ }
181
+ function renderFailed(plugin: string, name: string, err: unknown) {
182
+ if (failed.has(`${plugin}:${name}`)) return;
183
+ failed.add(`${plugin}:${name}`);
184
+ screen.log(yellow(`[warning] plugin ${plugin}: showing ${name} failed, using the default display: ${errorText(err)}`));
185
+ }
186
+ const summary = (name: string, input: unknown): string => {
187
+ const s = customSync(name, (r) => r.summary?.(input));
188
+ return typeof s === "string" ? clip(s.split("\n")[0]!, 120) : summarize(cwd, input);
189
+ };
190
+ const details = (name: string, input: unknown): string | undefined => {
191
+ const d = customSync(name, (r) => r.details?.(input));
192
+ return typeof d === "string" && d ? d.replace(/^/gm, " ") : undefined;
193
+ };
133
194
 
134
195
  const self: Transcript = {
135
196
  usage,
@@ -138,10 +199,16 @@ export function transcript(opts: TranscriptOptions): Transcript {
138
199
  turnFailed: false,
139
200
  onNotice,
140
201
  replay,
202
+ summary,
203
+ details,
204
+ async preview(c) {
205
+ const p = await custom(c.name, (r) => r.preview?.(c.input));
206
+ return typeof p === "string" ? p : preview(c.input);
207
+ },
141
208
  echo: (text) => screen.log(text.startsWith("/") ? cyan(`› ${text}`) : `\n${bold(`› ${text.replace(/\n/g, "\n ")}`)}`),
142
209
  reset() {
143
210
  for (const k of Object.keys(usage) as (keyof Usage)[]) usage[k] = 0;
144
- reportsCache = false;
211
+ reportsCache = undefined;
145
212
  toolNames.clear();
146
213
  quiet.clear();
147
214
  for (const id of running) screen.progress(id, undefined);
@@ -149,6 +216,8 @@ export function transcript(opts: TranscriptOptions): Transcript {
149
216
  steps.clear();
150
217
  tasks.clear();
151
218
  calls.clear();
219
+ befores.clear();
220
+ inputs.clear();
152
221
  self.lastEnd = undefined;
153
222
  },
154
223
  };
@@ -169,7 +238,11 @@ export function transcript(opts: TranscriptOptions): Transcript {
169
238
  trackSpeed(n.delta.text);
170
239
  // 工具参数只用来计时,不显示;也不算已经输出了内容(重试时不用标记作废,回复结束时照常打印没流式输出的正文)
171
240
  if (n.delta.kind === "tool_input") {
172
- screen.busy("Writing");
241
+ // 只在千位变了时更新,不让每个增量都重画
242
+ const before = toolLabel();
243
+ toolChars += n.delta.text.length;
244
+ const label = toolLabel();
245
+ if (label !== before || toolChars === n.delta.text.length) screen.busy(label);
173
246
  return;
174
247
  }
175
248
  streamed = true;
@@ -211,7 +284,7 @@ export function transcript(opts: TranscriptOptions): Transcript {
211
284
  if (p.kind === "task-tool") {
212
285
  // 要用户批准的调用在审批时显示
213
286
  if (p.decision === "ask") return;
214
- const step = `${p.decision === "deny" ? "✗" : "·"} ${p.name}(${summarize(cwd, p.name, p.input)})`;
287
+ const step = `${p.decision === "deny" ? "✗" : "·"} ${p.name}(${summary(p.name, p.input)})`;
215
288
  steps.set(toolUseId, [...(steps.get(toolUseId) ?? []), step]);
216
289
  return taskLine(step);
217
290
  }
@@ -229,7 +302,7 @@ export function transcript(opts: TranscriptOptions): Transcript {
229
302
  case "model.responded": {
230
303
  const d = e.data as EventDataMap["model.responded"];
231
304
  void countUsage(e);
232
- showContext(d.usage);
305
+ showContext(e as LogEvent<"model.responded">);
233
306
  if (!replaying) finishSpeed(d.usage);
234
307
  for (const b of d.content) if (b.kind === "tool_use") toolNames.set(b.id, b.name);
235
308
  // 不支持流式的 provider、重新显示历史:一次送出最终文本,和流式输出一样排版
@@ -244,10 +317,16 @@ export function transcript(opts: TranscriptOptions): Transcript {
244
317
  case "tool.decided": {
245
318
  const d = e.data as EventDataMap["tool.decided"];
246
319
  const name = toolNames.get(d.toolUseId) ?? "?";
247
- const full = callDetails(name, d.input);
320
+ const full = details(name, d.input);
248
321
  if (full) calls.set(d.toolUseId, full);
322
+ if (opts.renderer?.(name)?.renderer.result) inputs.set(d.toolUseId, d.input);
249
323
  if (d.decision === "ask") return;
250
- const head = `${bold(name)}(${summarize(cwd, name, d.input)})`;
324
+ // 执行前交给 renderer 的 before(例如按文件当时的内容算 diff);重新显示历史时文件已经变了,不调用
325
+ if (d.decision === "allow" && !replaying) {
326
+ const before = customSync(name, (r) => r.before?.(d.input));
327
+ if (before !== undefined) befores.set(d.toolUseId, before);
328
+ }
329
+ const head = `${bold(name)}(${summary(name, d.input)})`;
251
330
  if (d.decision === "deny") screen.log(red(`✗ ${head}`) + dim(d.reason ? ` — ${clip(d.reason, 200)}` : ""), { id: d.toolUseId, details: full });
252
331
  else {
253
332
  activity(`Running ${name}`);
@@ -274,8 +353,20 @@ export function transcript(opts: TranscriptOptions): Transcript {
274
353
  tasks.delete(d.toolUseId);
275
354
  const call = calls.get(d.toolUseId);
276
355
  calls.delete(d.toolUseId);
356
+ const before = befores.get(d.toolUseId);
357
+ befores.delete(d.toolUseId);
358
+ const input = inputs.get(d.toolUseId);
359
+ inputs.delete(d.toolUseId);
277
360
  if (quiet.delete(d.toolUseId) && !d.isError) return;
278
361
  const text = textOf(d.content).trim();
362
+ const name = toolNames.get(d.toolUseId) ?? "?";
363
+ const mine = customSync(name, (r) => r.result?.({ input, text, isError: d.isError === true, before }));
364
+ if (mine && typeof mine.line === "string") {
365
+ const own = typeof mine.details === "string" && mine.details ? [mine.details.replace(/^/gm, " ")] : [];
366
+ const folded = [...(call ? [call] : []), ...own].join("\n") || undefined;
367
+ screen.amend(d.toolUseId, (d.isError ? red : dim)("⎿ ") + clipStyled(mine.line.split("\n")[0]!, 200), { details: folded });
368
+ return;
369
+ }
279
370
  const lines = text.split("\n");
280
371
  // 结果接在调用的那一行后面;摘要省略了内容时,把完整结果(和子 Agent 调用过的工具)折叠起来,点击展开
281
372
  const shown = d.isError ? 4 : 1;
@@ -298,6 +389,8 @@ export function transcript(opts: TranscriptOptions): Transcript {
298
389
  doneProgress(d.toolUseId);
299
390
  tasks.delete(d.toolUseId);
300
391
  calls.delete(d.toolUseId);
392
+ befores.delete(d.toolUseId);
393
+ inputs.delete(d.toolUseId);
301
394
  screen.amend(d.toolUseId, yellow("⎿ interrupted before finishing; not retried"));
302
395
  return;
303
396
  }
@@ -367,7 +460,7 @@ export function transcript(opts: TranscriptOptions): Transcript {
367
460
  if (!show) {
368
461
  for (const e of events) {
369
462
  await countUsage(e);
370
- if (e.type === "model.responded") showContext((e as LogEvent<"model.responded">).data.usage);
463
+ if (e.type === "model.responded") showContext(e as LogEvent<"model.responded">);
371
464
  }
372
465
  return;
373
466
  }
@@ -387,10 +480,10 @@ export function transcript(opts: TranscriptOptions): Transcript {
387
480
  const d = e.data as EventDataMap["input.received"];
388
481
  if (d.kind === "approval") {
389
482
  const name = toolNames.get(d.toolUseId) ?? "?";
390
- const head = `${bold(name)}(${summarize(cwd, name, asked.get(d.toolUseId))})`;
483
+ const head = `${bold(name)}(${summary(name, asked.get(d.toolUseId))})`;
391
484
  screen.log(d.approved ? green(`✓ ${head}`) : red(`✗ ${head}`) + dim(d.reason ? ` — ${clip(d.reason, 200)}` : ""), {
392
485
  id: d.toolUseId,
393
- details: callDetails(name, asked.get(d.toolUseId)),
486
+ details: details(name, asked.get(d.toolUseId)),
394
487
  });
395
488
  continue;
396
489
  }