@uncarved/jade 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +187 -2
  3. package/bin/jade.js +20 -0
  4. package/dist/commands.d.ts +30 -0
  5. package/dist/commands.js +106 -0
  6. package/dist/commands.js.map +1 -0
  7. package/dist/config.d.ts +34 -0
  8. package/dist/config.js +130 -0
  9. package/dist/config.js.map +1 -0
  10. package/dist/context.d.ts +17 -0
  11. package/dist/context.js +53 -0
  12. package/dist/context.js.map +1 -0
  13. package/dist/distro.d.ts +93 -0
  14. package/dist/distro.js +277 -0
  15. package/dist/distro.js.map +1 -0
  16. package/dist/history.d.ts +10 -0
  17. package/dist/history.js +47 -0
  18. package/dist/history.js.map +1 -0
  19. package/dist/index.d.ts +26 -0
  20. package/dist/index.js +27 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/main.d.ts +2 -0
  23. package/dist/main.js +1124 -0
  24. package/dist/main.js.map +1 -0
  25. package/dist/mcp.d.ts +114 -0
  26. package/dist/mcp.js +640 -0
  27. package/dist/mcp.js.map +1 -0
  28. package/dist/memory.d.ts +19 -0
  29. package/dist/memory.js +129 -0
  30. package/dist/memory.js.map +1 -0
  31. package/dist/mentions.d.ts +35 -0
  32. package/dist/mentions.js +130 -0
  33. package/dist/mentions.js.map +1 -0
  34. package/dist/plugin-cli.d.ts +16 -0
  35. package/dist/plugin-cli.js +251 -0
  36. package/dist/plugin-cli.js.map +1 -0
  37. package/dist/plugins/budget.d.ts +9 -0
  38. package/dist/plugins/budget.js +30 -0
  39. package/dist/plugins/budget.js.map +1 -0
  40. package/dist/plugins/builtins.d.ts +10 -0
  41. package/dist/plugins/builtins.js +22 -0
  42. package/dist/plugins/builtins.js.map +1 -0
  43. package/dist/plugins/checks.d.ts +70 -0
  44. package/dist/plugins/checks.js +335 -0
  45. package/dist/plugins/checks.js.map +1 -0
  46. package/dist/plugins/compact.d.ts +26 -0
  47. package/dist/plugins/compact.js +216 -0
  48. package/dist/plugins/compact.js.map +1 -0
  49. package/dist/plugins/core.d.ts +42 -0
  50. package/dist/plugins/core.js +190 -0
  51. package/dist/plugins/core.js.map +1 -0
  52. package/dist/plugins/install.d.ts +68 -0
  53. package/dist/plugins/install.js +377 -0
  54. package/dist/plugins/install.js.map +1 -0
  55. package/dist/plugins/loader.d.ts +182 -0
  56. package/dist/plugins/loader.js +253 -0
  57. package/dist/plugins/loader.js.map +1 -0
  58. package/dist/plugins/policy.d.ts +64 -0
  59. package/dist/plugins/policy.js +269 -0
  60. package/dist/plugins/policy.js.map +1 -0
  61. package/dist/plugins/prompts.d.ts +28 -0
  62. package/dist/plugins/prompts.js +169 -0
  63. package/dist/plugins/prompts.js.map +1 -0
  64. package/dist/plugins/repeats.d.ts +9 -0
  65. package/dist/plugins/repeats.js +55 -0
  66. package/dist/plugins/repeats.js.map +1 -0
  67. package/dist/plugins/schema.d.ts +2 -0
  68. package/dist/plugins/schema.js +64 -0
  69. package/dist/plugins/schema.js.map +1 -0
  70. package/dist/provider.d.ts +52 -0
  71. package/dist/provider.js +187 -0
  72. package/dist/provider.js.map +1 -0
  73. package/dist/sessions.d.ts +13 -0
  74. package/dist/sessions.js +40 -0
  75. package/dist/sessions.js.map +1 -0
  76. package/dist/skills.d.ts +37 -0
  77. package/dist/skills.js +179 -0
  78. package/dist/skills.js.map +1 -0
  79. package/dist/sys.d.ts +44 -0
  80. package/dist/sys.js +115 -0
  81. package/dist/sys.js.map +1 -0
  82. package/dist/tools/checkpoint.d.ts +43 -0
  83. package/dist/tools/checkpoint.js +144 -0
  84. package/dist/tools/checkpoint.js.map +1 -0
  85. package/dist/tools/fs.d.ts +35 -0
  86. package/dist/tools/fs.js +417 -0
  87. package/dist/tools/fs.js.map +1 -0
  88. package/dist/tools/grep.d.ts +6 -0
  89. package/dist/tools/grep.js +243 -0
  90. package/dist/tools/grep.js.map +1 -0
  91. package/dist/tools/shell.d.ts +49 -0
  92. package/dist/tools/shell.js +295 -0
  93. package/dist/tools/shell.js.map +1 -0
  94. package/dist/tools/task.d.ts +31 -0
  95. package/dist/tools/task.js +86 -0
  96. package/dist/tools/task.js.map +1 -0
  97. package/dist/tools/todo.d.ts +10 -0
  98. package/dist/tools/todo.js +55 -0
  99. package/dist/tools/todo.js.map +1 -0
  100. package/dist/tools/web.d.ts +23 -0
  101. package/dist/tools/web.js +426 -0
  102. package/dist/tools/web.js.map +1 -0
  103. package/dist/ui/configure.d.ts +20 -0
  104. package/dist/ui/configure.js +285 -0
  105. package/dist/ui/configure.js.map +1 -0
  106. package/dist/ui/diff.d.ts +20 -0
  107. package/dist/ui/diff.js +142 -0
  108. package/dist/ui/diff.js.map +1 -0
  109. package/dist/ui/editor.d.ts +33 -0
  110. package/dist/ui/editor.js +128 -0
  111. package/dist/ui/editor.js.map +1 -0
  112. package/dist/ui/render.d.ts +13 -0
  113. package/dist/ui/render.js +84 -0
  114. package/dist/ui/render.js.map +1 -0
  115. package/dist/ui/screen.d.ts +90 -0
  116. package/dist/ui/screen.js +105 -0
  117. package/dist/ui/screen.js.map +1 -0
  118. package/dist/ui/transcript.d.ts +33 -0
  119. package/dist/ui/transcript.js +336 -0
  120. package/dist/ui/transcript.js.map +1 -0
  121. package/dist/ui/tui.d.ts +28 -0
  122. package/dist/ui/tui.js +884 -0
  123. package/dist/ui/tui.js.map +1 -0
  124. package/package.json +59 -4
  125. package/src/commands.ts +120 -0
  126. package/src/config.ts +146 -0
  127. package/src/context.ts +64 -0
  128. package/src/distro.ts +358 -0
  129. package/src/history.ts +55 -0
  130. package/src/index.ts +26 -0
  131. package/src/main.ts +1180 -0
  132. package/src/mcp.ts +693 -0
  133. package/src/memory.ts +135 -0
  134. package/src/mentions.ts +135 -0
  135. package/src/plugin-cli.ts +239 -0
  136. package/src/plugins/budget.ts +37 -0
  137. package/src/plugins/builtins.ts +31 -0
  138. package/src/plugins/checks.ts +390 -0
  139. package/src/plugins/compact.ts +257 -0
  140. package/src/plugins/core.ts +217 -0
  141. package/src/plugins/install.ts +429 -0
  142. package/src/plugins/loader.ts +386 -0
  143. package/src/plugins/policy.ts +304 -0
  144. package/src/plugins/prompts.ts +200 -0
  145. package/src/plugins/repeats.ts +62 -0
  146. package/src/plugins/schema.ts +67 -0
  147. package/src/provider.ts +208 -0
  148. package/src/sessions.ts +48 -0
  149. package/src/skills.ts +197 -0
  150. package/src/sys.ts +133 -0
  151. package/src/tools/checkpoint.ts +164 -0
  152. package/src/tools/fs.ts +432 -0
  153. package/src/tools/grep.ts +268 -0
  154. package/src/tools/shell.ts +339 -0
  155. package/src/tools/task.ts +105 -0
  156. package/src/tools/todo.ts +67 -0
  157. package/src/tools/web.ts +451 -0
  158. package/src/ui/configure.ts +310 -0
  159. package/src/ui/diff.ts +136 -0
  160. package/src/ui/editor.ts +136 -0
  161. package/src/ui/render.ts +74 -0
  162. package/src/ui/screen.ts +164 -0
  163. package/src/ui/transcript.ts +345 -0
  164. package/src/ui/tui.tsx +1374 -0
@@ -0,0 +1,164 @@
1
+ // 宿主的输出与交互接口。两种实现:
2
+ // - 终端界面(tui.tsx):全屏,标题在顶部,对话在中间自己滚动,输入框、状态栏固定在底部,运行中也能输入
3
+ // - 纯文本(这里):-p 和非交互运行时使用,逐行输出,提问用 readline
4
+
5
+ import { createInterface, type Interface } from "node:readline/promises";
6
+
7
+ export interface Choice<T> {
8
+ label: string;
9
+ value: T;
10
+ /** 选项后面的灰色说明 */
11
+ hint?: string;
12
+ }
13
+
14
+ export interface StatusInfo {
15
+ cwd: string;
16
+ branch?: string;
17
+ model: string;
18
+ mode: string;
19
+ session?: string;
20
+ /** 上一次请求的上下文用量,limit 是模型的上下文窗口 */
21
+ context?: { used: number; limit: number; /** 超过这个 token 数会自动压缩 */ compactAt?: number };
22
+ /** 本会话累计的用量(含子 Agent 和压缩) */
23
+ spent?: { input: number; output: number };
24
+ /** 上一次请求的输入中命中缓存的比例(0–1);服务不报告缓存用量时为 undefined */
25
+ cache?: number;
26
+ }
27
+
28
+ export interface CommandInfo {
29
+ name: string;
30
+ args?: string;
31
+ about: string;
32
+ }
33
+
34
+ export interface Screen {
35
+ /** 能向用户提问;为 false 时 select / input 直接返回 undefined */
36
+ readonly interactive: boolean;
37
+ /**
38
+ * 追加已经完成的输出,可以带 ANSI 颜色。
39
+ * details:折叠起来的完整内容,终端界面里点击 text 展开;纯文本输出不显示。
40
+ * id:之后用 amend 给这一项补充内容(工具调用的结果);终端界面里这一项收起时只占一行
41
+ */
42
+ log(text: string, opts?: { details?: string; id?: string }): void;
43
+ /**
44
+ * 给之前用 id 记下的一项补充内容:终端界面里接在那一项后面合成一项(details 替换原来的),
45
+ * 纯文本输出另起一行缩进显示。找不到那一项时也是另起一行
46
+ */
47
+ amend(id: string, text: string, opts?: { details?: string }): void;
48
+ /**
49
+ * 正在运行的工具 id 的一行进度(已经排好版);undefined 表示工具结束了。
50
+ * 终端界面只在对话最后显示每个工具最新的一行,结束时去掉;纯文本输出逐行打印。
51
+ * output 表示是工具自己的输出,纯文本输出里每个工具最多打印 20 行
52
+ */
53
+ progress(id: string, line: string | undefined, opts?: { output?: boolean }): void;
54
+ /** 流式输出模型的正文或思考 */
55
+ stream(kind: "text" | "thinking", text: string): void;
56
+ /** 结束当前的流式块 */
57
+ endStream(): void;
58
+ /** 正在进行的活动;undefined 表示空闲 */
59
+ busy(label: string | undefined): void;
60
+ status(info: Partial<StatusInfo>): void;
61
+ /** 排队等待发送的输入 */
62
+ queued(items: string[]): void;
63
+ /** 让用户从几项里选一项;取消时返回 undefined */
64
+ select<T>(title: string, choices: Choice<T>[], opts?: { body?: string }): Promise<T | undefined>;
65
+ /** 让用户输入一行;取消时返回 undefined */
66
+ input(title: string, opts?: { initial?: string; mask?: boolean; placeholder?: string }): Promise<string | undefined>;
67
+ /** 清空已经显示的对话(开始新会话时) */
68
+ clear(): void;
69
+ close(): Promise<void>;
70
+ }
71
+
72
+ // ---------- 颜色 ----------
73
+
74
+ const colors = Boolean(process.stdout.isTTY);
75
+ const paint = (code: string) => (s: string) => (colors ? `\x1b[${code}m${s}\x1b[0m` : s);
76
+ export const dim = paint("2");
77
+ export const red = paint("31");
78
+ export const green = paint("32");
79
+ export const yellow = paint("33");
80
+ export const cyan = paint("36");
81
+ export const bold = paint("1");
82
+
83
+ // ---------- 纯文本实现 ----------
84
+
85
+ const MAX_OUTPUT_LINES = 20;
86
+
87
+ export function plainScreen(opts: { interactive: boolean }): Screen {
88
+ let atLineStart = true;
89
+ let streaming: "text" | "thinking" | undefined;
90
+ let rl: Interface | undefined;
91
+ /** 每个工具已经打印了多少行输出 */
92
+ const outputLines = new Map<string, number>();
93
+
94
+ const write = (s: string) => {
95
+ if (!s) return;
96
+ process.stdout.write(s);
97
+ atLineStart = s.endsWith("\n");
98
+ };
99
+ const line = (s: string) => {
100
+ if (!atLineStart) write("\n");
101
+ write(s + "\n");
102
+ };
103
+ const ask = async (q: string) => {
104
+ rl ??= createInterface({ input: process.stdin, output: process.stdout, terminal: true });
105
+ return (await rl.question(q)).trim();
106
+ };
107
+
108
+ return {
109
+ interactive: opts.interactive,
110
+ log: (text) => {
111
+ streaming = undefined;
112
+ line(text);
113
+ },
114
+ amend: (_id, text) => {
115
+ streaming = undefined;
116
+ line(` ${text}`);
117
+ },
118
+ progress: (id, text, o) => {
119
+ if (text === undefined) return void outputLines.delete(id);
120
+ streaming = undefined;
121
+ if (o?.output) {
122
+ const shown = outputLines.get(id) ?? 0;
123
+ if (shown > MAX_OUTPUT_LINES) return;
124
+ outputLines.set(id, shown + 1);
125
+ if (shown === MAX_OUTPUT_LINES) return line(dim(" │ …"));
126
+ }
127
+ line(text);
128
+ },
129
+ stream: (kind, text) => {
130
+ if (kind !== streaming) {
131
+ // 不少模型的正文以空行开头;整块都是换行时等下一块
132
+ if (kind === "text") text = text.replace(/^\n+/, "");
133
+ if (!text) return;
134
+ if (kind === "thinking") line(dim("thinking…"));
135
+ else if (!atLineStart) write("\n");
136
+ streaming = kind;
137
+ }
138
+ write(kind === "thinking" ? dim(text) : text);
139
+ },
140
+ endStream: () => {
141
+ streaming = undefined;
142
+ if (!atLineStart) write("\n");
143
+ },
144
+ busy: () => {},
145
+ status: () => {},
146
+ queued: () => {},
147
+ async select(title, choices, o) {
148
+ if (!opts.interactive) return undefined;
149
+ line(yellow(title));
150
+ if (o?.body) line(o.body);
151
+ choices.forEach((c, i) => line(` ${i + 1}. ${c.label}${c.hint ? dim(` ${c.hint}`) : ""}`));
152
+ const n = Number(await ask(`Choose 1-${choices.length} (empty to cancel): `));
153
+ return Number.isInteger(n) && n >= 1 && n <= choices.length ? choices[n - 1]!.value : undefined;
154
+ },
155
+ async input(title, o) {
156
+ if (!opts.interactive) return undefined;
157
+ return (await ask(`${title}${o?.initial ? ` [${o.initial}]` : ""}: `)) || o?.initial || "";
158
+ },
159
+ clear: () => {},
160
+ async close() {
161
+ rl?.close();
162
+ },
163
+ };
164
+ }
@@ -0,0 +1,345 @@
1
+ // 把运行时的通知和日志事件显示成对话:模型的流式输出、工具调用和结果、轮次结束的原因,
2
+ // 以及恢复会话时重新显示历史。顺带统计本会话的 token 用量、更新状态栏的上下文用量。
3
+ //
4
+ // 只负责显示和统计,不驱动运行时;宿主(main.ts)用 lastEnd、turnFailed 决定接下来做什么。
5
+
6
+ import { readAll, type Block, type EventDataMap, type LogEvent, type LogStore, type Runtime, type TurnEndReason, type Usage } from "uncarved";
7
+ import type { ShellProgress } from "../tools/shell.ts";
8
+ import type { TaskProgress } from "../tools/task.ts";
9
+ import { renderTodos, type Todo } from "../tools/todo.ts";
10
+ import { clip, detailsOf, summarize } from "./render.ts";
11
+ import { bold, cyan, dim, green, red, yellow, type Screen } from "./screen.ts";
12
+
13
+ export type Notice = Parameters<Parameters<Runtime["subscribe"]>[0]>[0];
14
+
15
+ export interface TranscriptOptions {
16
+ screen: Screen;
17
+ cwd: string;
18
+ /** 子 Agent 的用量在它自己的日志里,从这里读 */
19
+ store: LogStore;
20
+ /** 模型的上下文窗口(状态栏显示用) */
21
+ contextWindow(): number;
22
+ /** 自动压缩的阈值(状态栏显示用) */
23
+ compactAt?(): number;
24
+ /** 上一轮失败后能否用 /retry 重新请求 */
25
+ canRetry(): boolean;
26
+ }
27
+
28
+ export interface Transcript {
29
+ onNotice(n: Notice): void;
30
+ /** 恢复的会话里已有的内容:show 为 true 时重新显示对话,否则只统计用量 */
31
+ replay(events: LogEvent[], show: boolean): Promise<void>;
32
+ /** 把用户的输入回显到输出里 */
33
+ echo(text: string): void;
34
+ /** 本会话的用量,包括子 Agent 和压缩 */
35
+ readonly usage: Readonly<Required<Usage>>;
36
+ /** 最近一轮的结束原因;宿主开始新一轮前清掉 */
37
+ lastEnd: TurnEndReason | undefined;
38
+ /** 最近一轮以错误结束时的错误信息 */
39
+ lastError: string | undefined;
40
+ /** 本轮已经以 turn.ended(error/aborted)结束并显示过原因,随后抛出的同一个错误不再重复显示 */
41
+ turnFailed: boolean;
42
+ /** 开始新会话时清空 */
43
+ reset(): void;
44
+ }
45
+
46
+ /** 工具结果折叠起来的完整内容最多这么多行 */
47
+ const MAX_DETAIL_LINES = 2000;
48
+
49
+ const textOf = (blocks: Block[]) => blocks.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n");
50
+ const errorText = (err: unknown) => (err instanceof Error ? err.message : String(err));
51
+
52
+ export function transcript(opts: TranscriptOptions): Transcript {
53
+ const { screen, cwd, store } = opts;
54
+
55
+ const usage: Required<Usage> = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
56
+ const addUsage = (u?: Usage) => {
57
+ for (const k of Object.keys(usage) as (keyof Usage)[]) usage[k] += u?.[k] ?? 0;
58
+ if (u) screen.status({ spent: { input: usage.inputTokens, output: usage.outputTokens } });
59
+ };
60
+ /** 一个事件带来的用量:模型回复、压缩时的总结调用;子 Agent 的用量在它自己的日志里 */
61
+ async function countUsage(e: LogEvent) {
62
+ if (e.type === "model.responded") addUsage((e as LogEvent<"model.responded">).data.usage);
63
+ else if (e.type === "jade/compact/compacted") addUsage((e.data as { usage?: Usage }).usage);
64
+ else if (e.type === "tool.completed") {
65
+ const child = (e as LogEvent<"tool.completed">).data.child;
66
+ if (child) for (const c of await readAll(store, child.sessionId)) await countUsage(c);
67
+ }
68
+ }
69
+
70
+ /** 服务端报过缓存命中数。有的服务只在命中时才带这个字段,报过一次之后没带就是没命中 */
71
+ let reportsCache = false;
72
+ /** 上下文用量:最近一次回复的输入加输出,就是下一次请求的大致起点;以及这次输入的缓存命中率 */
73
+ function showContext(u: Usage | undefined) {
74
+ if (u?.inputTokens === undefined) return;
75
+ if (u.cacheReadTokens !== undefined) reportsCache = true;
76
+ screen.status({
77
+ 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,
79
+ });
80
+ }
81
+
82
+ const toolNames = new Map<string, string>();
83
+ /** 正在重新显示恢复的会话里已有的内容:只输出,不显示进行中的状态 */
84
+ let replaying = false;
85
+ const activity = (label: string) => {
86
+ if (!replaying) screen.busy(label);
87
+ };
88
+ /** 结果不用再显示的工具调用 */
89
+ const quiet = new Set<string>();
90
+ let streamed = false;
91
+ /** 正在运行、显示着进度的工具 */
92
+ const running = new Set<string>();
93
+ /** 子 Agent 调用过的工具,结束时放进 task 结果的折叠内容里 */
94
+ const steps = new Map<string, string[]>();
95
+ const progress = (id: string, line: string, o?: { output?: boolean }) => {
96
+ running.add(id);
97
+ screen.progress(id, line, o);
98
+ };
99
+ const doneProgress = (id: string) => {
100
+ if (running.delete(id)) screen.progress(id, undefined);
101
+ };
102
+
103
+ const self: Transcript = {
104
+ usage,
105
+ lastEnd: undefined,
106
+ lastError: undefined,
107
+ turnFailed: false,
108
+ onNotice,
109
+ replay,
110
+ echo: (text) => screen.log(text.startsWith("/") ? cyan(`› ${text}`) : `\n${bold(`› ${text.replace(/\n/g, "\n ")}`)}`),
111
+ reset() {
112
+ for (const k of Object.keys(usage) as (keyof Usage)[]) usage[k] = 0;
113
+ reportsCache = false;
114
+ toolNames.clear();
115
+ quiet.clear();
116
+ for (const id of running) screen.progress(id, undefined);
117
+ running.clear();
118
+ steps.clear();
119
+ self.lastEnd = undefined;
120
+ },
121
+ };
122
+
123
+ function onNotice(n: Notice) {
124
+ switch (n.type) {
125
+ case "delta":
126
+ if (n.delta.kind === "reset") {
127
+ // 已经输出的内容收不回来,标记一下
128
+ if (streamed) {
129
+ screen.endStream();
130
+ screen.log(yellow("[output above discarded; retrying]"));
131
+ }
132
+ streamed = false;
133
+ return;
134
+ }
135
+ streamed = true;
136
+ if (n.delta.kind === "thinking") {
137
+ screen.busy("Thinking");
138
+ screen.stream("thinking", n.delta.text);
139
+ } else {
140
+ screen.busy("Writing");
141
+ screen.stream("text", n.delta.text);
142
+ }
143
+ return;
144
+ case "hook-error":
145
+ screen.log(yellow(`[hook error] ${n.info.plugin} at ${n.info.point}: ${errorText(n.info.error)}`));
146
+ return;
147
+ case "warning":
148
+ screen.log(yellow(`[warning] ${n.code}`));
149
+ return;
150
+ case "awaiting":
151
+ return;
152
+ case "tool-progress":
153
+ return renderProgress(n.toolUseId, n.update as ShellProgress | TaskProgress);
154
+ case "event":
155
+ return renderEvent(n.event);
156
+ }
157
+ }
158
+
159
+ function renderProgress(toolUseId: string, p: ShellProgress | TaskProgress) {
160
+ if (typeof p !== "object" || p === null) return;
161
+ if (p.kind === "task-start") return progress(toolUseId, dim(` ↳ sub-agent: ${p.description}`));
162
+ if (p.kind === "task-tool") {
163
+ // 要用户批准的调用在审批时显示
164
+ if (p.decision === "ask") return;
165
+ const step = `${p.decision === "deny" ? "✗" : "·"} ${p.name}(${summarize(cwd, p.name, p.input)})`;
166
+ steps.set(toolUseId, [...(steps.get(toolUseId) ?? []), step]);
167
+ return progress(toolUseId, dim(` ${step}`));
168
+ }
169
+ // 第三方工具的进度格式 jade 不认识,不显示
170
+ if (typeof (p as { text?: unknown }).text !== "string") return;
171
+ for (const l of p.text.replace(/\n$/, "").split("\n")) progress(toolUseId, dim(` │ ${clip(l, 200)}`), { output: true });
172
+ }
173
+
174
+ function renderEvent(e: LogEvent) {
175
+ switch (e.type) {
176
+ case "model.requested":
177
+ activity("Waiting for the model");
178
+ return;
179
+ case "model.responded": {
180
+ const d = e.data as EventDataMap["model.responded"];
181
+ void countUsage(e);
182
+ showContext(d.usage);
183
+ for (const b of d.content) if (b.kind === "tool_use") toolNames.set(b.id, b.name);
184
+ // 不支持流式的 provider:直接打印最终文本
185
+ if (!streamed) {
186
+ const text = textOf(d.content).trim();
187
+ if (text) screen.log(text);
188
+ }
189
+ streamed = false;
190
+ screen.endStream();
191
+ return;
192
+ }
193
+ case "tool.decided": {
194
+ const d = e.data as EventDataMap["tool.decided"];
195
+ const name = toolNames.get(d.toolUseId) ?? "?";
196
+ if (d.decision === "ask") return;
197
+ const head = `${bold(name)}(${summarize(cwd, name, d.input)})`;
198
+ if (d.decision === "deny") screen.log(red(`✗ ${head}`) + dim(d.reason ? ` — ${clip(d.reason, 200)}` : ""), { id: d.toolUseId });
199
+ else {
200
+ activity(`Running ${name}`);
201
+ if (name === "todo_write") {
202
+ // 清单本身就是参数:直接显示,结果不再显示
203
+ quiet.add(d.toolUseId);
204
+ screen.log(cyan("● ") + bold("Todos"));
205
+ screen.log(renderTodos((d.input as { todos?: Todo[] }).todos ?? []).replace(/^/gm, " "));
206
+ } else if (d.decidedBy !== "user" || replaying) {
207
+ // 用户批准的调用在审批时已经显示过;重新显示历史时没有审批这一步
208
+ screen.log(cyan("● ") + head, { id: d.toolUseId });
209
+ }
210
+ }
211
+ return;
212
+ }
213
+ case "tool.completed": {
214
+ const d = e.data as EventDataMap["tool.completed"];
215
+ void countUsage(e);
216
+ activity("Working");
217
+ doneProgress(d.toolUseId);
218
+ const sub = steps.get(d.toolUseId) ?? [];
219
+ steps.delete(d.toolUseId);
220
+ if (quiet.delete(d.toolUseId) && !d.isError) return;
221
+ const text = textOf(d.content).trim();
222
+ const lines = text.split("\n");
223
+ // 结果接在调用的那一行后面;摘要省略了内容时,把完整结果(和子 Agent 调用过的工具)折叠起来,点击展开
224
+ const shown = d.isError ? 4 : 1;
225
+ const width = d.isError ? 200 : 160;
226
+ const hidden = sub.length > 0 || lines.length > shown || lines.some((l) => l.length > width);
227
+ const details = hidden
228
+ ? [
229
+ ...(sub.length ? [dim(` sub-agent ran ${sub.length} tool call${sub.length > 1 ? "s" : ""}:`), ...sub.map((l) => dim(` ${l}`))] : []),
230
+ detailsOf(lines, d.isError ? red : (s) => s, MAX_DETAIL_LINES),
231
+ ].join("\n")
232
+ : undefined;
233
+ if (d.isError) screen.amend(d.toolUseId, red(`⎿ ${lines.slice(0, shown).map((l) => clip(l, width)).join("\n ")}`), { details });
234
+ else screen.amend(d.toolUseId, dim(`⎿ ${clip(lines[0] ?? "", width)}${lines.length > 1 ? ` (+${lines.length - 1} lines)` : ""}`), { details });
235
+ return;
236
+ }
237
+ case "tool.interrupted": {
238
+ const d = e.data as EventDataMap["tool.interrupted"];
239
+ doneProgress(d.toolUseId);
240
+ screen.amend(d.toolUseId, yellow("⎿ interrupted before finishing; not retried"));
241
+ return;
242
+ }
243
+ case "turn.ended": {
244
+ const d = e.data as EventDataMap["turn.ended"];
245
+ self.lastEnd = d.reason;
246
+ for (const id of [...running]) doneProgress(id);
247
+ self.lastError = d.error;
248
+ self.turnFailed = d.reason === "error" || d.reason === "aborted";
249
+ if (d.reason === "stopped") screen.log(yellow("[stopped: step budget for this turn used up; send a message to continue]"));
250
+ else if (d.reason === "aborted") screen.log(yellow("[interrupted]"));
251
+ else if (d.reason === "max_tokens") {
252
+ const limit = process.env.JADE_MAX_TOKENS ? `${process.env.JADE_MAX_TOKENS} tokens` : "the provider's default";
253
+ screen.log(yellow(`[reply cut off at the output limit (${limit}); raise it with /model if this keeps happening]`));
254
+ } else if (d.reason !== "end") screen.log(yellow(`[turn ended: ${d.reason}${d.error ? ` — ${d.error}` : ""}]`));
255
+ if (self.turnFailed && !replaying && opts.canRetry()) screen.log(dim("[send /retry to request again without adding a message]"));
256
+ return;
257
+ }
258
+ case "jade/compact/compacted": {
259
+ const d = e.data as { from: number; upTo: number; before: number };
260
+ void countUsage(e);
261
+ screen.log(dim(`[compacted ${d.upTo - d.from} messages, ~${d.before} tokens before]`));
262
+ return;
263
+ }
264
+ case "jade/checks/checked": {
265
+ const d = e.data as { summary: { name: string; problems: number; others?: number; failed?: string }[]; report: string };
266
+ const bad = d.summary.filter((s) => s.problems > 0 || s.others || s.failed);
267
+ const details = d.report ? detailsOf(d.report.split("\n").slice(1), (s) => s, MAX_DETAIL_LINES) : undefined;
268
+ if (bad.length === 0) {
269
+ screen.log(dim(` ✓ checks passed: ${d.summary.map((s) => s.name).join(", ")}`), { details });
270
+ } else {
271
+ const what = bad.map((s) =>
272
+ s.failed
273
+ ? `${s.name} ${s.failed}`
274
+ : `${s.name}: ${[s.problems > 0 ? `${s.problems} problem${s.problems > 1 ? "s" : ""} in changed files` : "", s.others ? `${s.others} new elsewhere` : ""]
275
+ .filter(Boolean)
276
+ .join(", ")}`,
277
+ );
278
+ screen.log(yellow(` ⚠ checks: ${what.join("; ")}`), { details });
279
+ }
280
+ return;
281
+ }
282
+ case "jade/compact/trimmed": {
283
+ const d = e.data as { saved: number };
284
+ screen.log(dim(`[cleared old tool output, ~${d.saved} tokens]`));
285
+ return;
286
+ }
287
+ default:
288
+ return renderPluginNotice(e);
289
+ }
290
+ }
291
+
292
+ /** 插件用 ctx.emit("notice", { text, level? }) 写入的提示,显示成 [插件 id] 文本 */
293
+ function renderPluginNotice(e: LogEvent) {
294
+ if (e.origin.by !== "plugin" || !e.type.endsWith("/notice")) return;
295
+ const d = e.data as { text?: unknown; level?: unknown } | null;
296
+ if (typeof d?.text !== "string" || !d.text) return;
297
+ const line = `[${e.origin.id}] ${clip(d.text, 2000)}`;
298
+ screen.log(d.level === "warning" ? yellow(line) : dim(line));
299
+ }
300
+
301
+ async function replay(events: LogEvent[], show: boolean) {
302
+ if (!show) {
303
+ for (const e of events) {
304
+ await countUsage(e);
305
+ if (e.type === "model.responded") showContext((e as LogEvent<"model.responded">).data.usage);
306
+ }
307
+ return;
308
+ }
309
+ replaying = true;
310
+ /** 等待用户审批的调用的参数,用户的决定记在之后的 input.received 里 */
311
+ const asked = new Map<string, unknown>();
312
+ try {
313
+ for (const e of events) {
314
+ if (e.type === "tool.decided") {
315
+ const d = e.data as EventDataMap["tool.decided"];
316
+ if (d.decision === "ask") asked.set(d.toolUseId, d.input);
317
+ }
318
+ if (e.type !== "input.received") {
319
+ renderEvent(e);
320
+ continue;
321
+ }
322
+ const d = e.data as EventDataMap["input.received"];
323
+ if (d.kind === "approval") {
324
+ const name = toolNames.get(d.toolUseId) ?? "?";
325
+ const head = `${bold(name)}(${summarize(cwd, name, asked.get(d.toolUseId))})`;
326
+ screen.log(d.approved ? green(`✓ ${head}`) : red(`✗ ${head}`) + dim(d.reason ? ` — ${clip(d.reason, 200)}` : ""), { id: d.toolUseId });
327
+ continue;
328
+ }
329
+ if (d.kind === "retry") {
330
+ screen.log(dim("[retried]"));
331
+ continue;
332
+ }
333
+ if (d.kind !== "message") continue;
334
+ // 宿主附带的说明(例如自动续写)不是用户说的话
335
+ const text = d.content.flatMap((b) => (b.kind === "text" && b.origin.by === "user" ? [b.text] : [])).join("\n");
336
+ if (text) self.echo(text);
337
+ }
338
+ } finally {
339
+ replaying = false;
340
+ }
341
+ screen.log(dim("─".repeat(20) + " resumed " + "─".repeat(20)));
342
+ }
343
+
344
+ return self;
345
+ }