@uncarved/jade 0.3.0 → 0.4.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 (207) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +482 -27
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +49 -24
  14. package/plugins/approval/policy.ts +48 -25
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +55 -12
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +10 -9
  50. package/plugins/models/index.ts +31 -4
  51. package/plugins/models/provider.ts +12 -1
  52. package/plugins/modes/index.ts +13 -2
  53. package/plugins/print/index.ts +7 -4
  54. package/plugins/prompts/index.ts +0 -0
  55. package/plugins/renderers/index.ts +10 -5
  56. package/plugins/repeats/index.ts +39 -9
  57. package/plugins/schedule/index.ts +2 -0
  58. package/plugins/screenshot/browser.ts +231 -0
  59. package/plugins/screenshot/index.ts +3 -2
  60. package/plugins/screenshot/tool.ts +27 -51
  61. package/plugins/sessions/index.ts +48 -2
  62. package/plugins/shell/index.ts +75 -22
  63. package/plugins/shell/plugin.json +1 -2
  64. package/plugins/shell/renderers.ts +9 -7
  65. package/plugins/shell/shell.ts +93 -34
  66. package/plugins/skills/index.ts +28 -19
  67. package/plugins/skills/project.ts +12 -7
  68. package/plugins/steer/index.ts +5 -4
  69. package/plugins/task/index.ts +81 -81
  70. package/plugins/task/plugin.json +5 -2
  71. package/plugins/task/style.ts +13 -14
  72. package/plugins/task/subagent.ts +67 -184
  73. package/plugins/todo/index.ts +39 -9
  74. package/plugins/tools/index.ts +57 -0
  75. package/plugins/tools/plugin.json +7 -0
  76. package/plugins/tui/frontend.ts +161 -87
  77. package/plugins/tui/index.ts +2 -3
  78. package/plugins/tui/mascot.ts +8 -7
  79. package/plugins/tui/mentions.ts +11 -80
  80. package/plugins/tui/plugin.json +1 -1
  81. package/plugins/tui/screen.ts +55 -5
  82. package/plugins/tui/transcript.ts +17 -7
  83. package/plugins/tui/tui.ts +356 -104
  84. package/plugins/tui/vendor.ts +1 -1
  85. package/plugins/undo/checkpoint.ts +5 -3
  86. package/plugins/undo/index.ts +43 -14
  87. package/plugins/undo/style.ts +13 -14
  88. package/plugins/web/index.ts +7 -18
  89. package/plugins/web/plugin.json +1 -1
  90. package/plugins-dist/approval/index.js +363 -414
  91. package/plugins-dist/approval/policy.js +395 -497
  92. package/plugins-dist/approval/review.js +132 -158
  93. package/plugins-dist/approval/schema.js +50 -55
  94. package/plugins-dist/ask/index.js +115 -129
  95. package/plugins-dist/budget/index.js +27 -31
  96. package/plugins-dist/checks/checks.js +293 -329
  97. package/plugins-dist/checks/index.js +119 -139
  98. package/plugins-dist/checks/plugin.json +2 -1
  99. package/plugins-dist/checks/project.js +57 -65
  100. package/plugins-dist/commands/index.js +47 -29
  101. package/plugins-dist/compact/compact.js +233 -249
  102. package/plugins-dist/compact/index.js +98 -95
  103. package/plugins-dist/compact/style.js +9 -14
  104. package/plugins-dist/completions/index.js +30 -0
  105. package/plugins-dist/completions/plugin.json +9 -0
  106. package/plugins-dist/continue/index.js +40 -52
  107. package/plugins-dist/copy/index.js +40 -0
  108. package/plugins-dist/copy/plugin.json +9 -0
  109. package/plugins-dist/cost/index.js +98 -115
  110. package/plugins-dist/custom-commands/index.js +55 -72
  111. package/plugins-dist/editor/index.js +64 -72
  112. package/plugins-dist/fs/diff.js +111 -124
  113. package/plugins-dist/fs/fs.js +426 -469
  114. package/plugins-dist/fs/grep.js +262 -244
  115. package/plugins-dist/fs/index.js +20 -34
  116. package/plugins-dist/fs/plugin.json +1 -2
  117. package/plugins-dist/fs/renderers.js +100 -112
  118. package/plugins-dist/fs/style.js +11 -15
  119. package/plugins-dist/fs/sys.js +31 -43
  120. package/plugins-dist/hooks/index.js +107 -127
  121. package/plugins-dist/keys/index.js +27 -31
  122. package/plugins-dist/mcp/index.js +271 -199
  123. package/plugins-dist/mcp/install.js +123 -137
  124. package/plugins-dist/mcp/mcp.js +638 -577
  125. package/plugins-dist/mcp/plugin.json +3 -1
  126. package/plugins-dist/mcp/project.js +98 -115
  127. package/plugins-dist/memory/index.js +83 -88
  128. package/plugins-dist/memory/memory.js +111 -128
  129. package/plugins-dist/memory/style.js +9 -14
  130. package/plugins-dist/mentions/attach.js +91 -99
  131. package/plugins-dist/mentions/candidates.js +49 -0
  132. package/plugins-dist/mentions/index.js +71 -81
  133. package/plugins-dist/mentions/plugin.json +2 -1
  134. package/plugins-dist/mentions/style.js +9 -14
  135. package/plugins-dist/models/config.js +29 -43
  136. package/plugins-dist/models/configure.js +392 -473
  137. package/plugins-dist/models/context.js +14 -22
  138. package/plugins-dist/models/index.js +182 -188
  139. package/plugins-dist/models/provider.js +243 -295
  140. package/plugins-dist/models/saved.js +59 -71
  141. package/plugins-dist/modes/index.js +138 -165
  142. package/plugins-dist/plugins/index.js +34 -34
  143. package/plugins-dist/print/index.js +192 -175
  144. package/plugins-dist/prompts/index.js +81 -89
  145. package/plugins-dist/prompts/notes.js +31 -37
  146. package/plugins-dist/prompts/prompts.js +155 -193
  147. package/plugins-dist/prompts/results.js +40 -53
  148. package/plugins-dist/prompts/sys.js +39 -50
  149. package/plugins-dist/renderers/index.js +32 -32
  150. package/plugins-dist/repeats/index.js +134 -151
  151. package/plugins-dist/schedule/cron.js +49 -56
  152. package/plugins-dist/schedule/index.js +229 -247
  153. package/plugins-dist/schedule/store.js +93 -109
  154. package/plugins-dist/scratch/index.js +12 -18
  155. package/plugins-dist/screenshot/browser.js +169 -0
  156. package/plugins-dist/screenshot/index.js +37 -45
  157. package/plugins-dist/screenshot/sys.js +53 -65
  158. package/plugins-dist/screenshot/tool.js +101 -151
  159. package/plugins-dist/sessions/index.js +149 -117
  160. package/plugins-dist/shell/index.js +117 -74
  161. package/plugins-dist/shell/plugin.json +1 -2
  162. package/plugins-dist/shell/renderers.js +28 -33
  163. package/plugins-dist/shell/service.js +17 -23
  164. package/plugins-dist/shell/shell.js +317 -320
  165. package/plugins-dist/shell/sys.js +64 -79
  166. package/plugins-dist/skills/index.js +193 -211
  167. package/plugins-dist/skills/install.js +122 -149
  168. package/plugins-dist/skills/project.js +65 -73
  169. package/plugins-dist/skills/skills.js +135 -171
  170. package/plugins-dist/steer/index.js +108 -125
  171. package/plugins-dist/suggest/index.js +235 -259
  172. package/plugins-dist/task/index.js +130 -148
  173. package/plugins-dist/task/plugin.json +5 -4
  174. package/plugins-dist/task/style.js +9 -14
  175. package/plugins-dist/task/subagent.js +156 -279
  176. package/plugins-dist/todo/index.js +79 -63
  177. package/plugins-dist/tools/index.js +43 -0
  178. package/plugins-dist/tools/plugin.json +9 -0
  179. package/plugins-dist/tui/editor.js +145 -160
  180. package/plugins-dist/tui/frontend.js +641 -655
  181. package/plugins-dist/tui/history.js +34 -37
  182. package/plugins-dist/tui/index.js +16 -18
  183. package/plugins-dist/tui/markdown.js +203 -247
  184. package/plugins-dist/tui/mascot.js +266 -353
  185. package/plugins-dist/tui/mentions.js +67 -144
  186. package/plugins-dist/tui/plugin.json +1 -2
  187. package/plugins-dist/tui/render.js +35 -45
  188. package/plugins-dist/tui/screen.js +197 -180
  189. package/plugins-dist/tui/transcript.js +436 -468
  190. package/plugins-dist/tui/tui.js +1554 -1645
  191. package/plugins-dist/tui/vendor.js +1388 -1088
  192. package/plugins-dist/undo/checkpoint.js +95 -118
  193. package/plugins-dist/undo/index.js +185 -192
  194. package/plugins-dist/undo/snapshot.js +83 -99
  195. package/plugins-dist/undo/style.js +9 -14
  196. package/plugins-dist/update/index.js +26 -28
  197. package/plugins-dist/web/env.js +55 -68
  198. package/plugins-dist/web/index.js +80 -110
  199. package/plugins-dist/web/plugin.json +1 -2
  200. package/plugins-dist/web/renderers.js +4 -5
  201. package/plugins-dist/web/web.js +514 -593
  202. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  203. package/sdk/python/jade_plugin.py +9 -2
  204. package/src/api.ts +1 -1
  205. package/src/host.ts +39 -4
  206. package/src/remote.ts +6 -1
  207. package/src/session.ts +489 -34
@@ -1,493 +1,461 @@
1
- // 把运行时的通知和日志事件显示成对话:模型的流式输出、工具调用和结果、轮次结束的原因,
2
- // 以及恢复会话时重新显示历史。顺带统计本会话的 token 用量、更新状态栏的上下文用量。
3
- //
4
- // 只负责显示和统计,不驱动运行时;前端(frontend.ts)用 lastEnd、turnFailed 决定接下来做什么。
5
1
  import { clip, clipStyled, detailsOf, preview, summarize } from "./render.js";
6
2
  import { bold, cyan, dim, green, red, yellow } from "./screen.js";
7
- /** 工具结果折叠起来的完整内容最多这么多行 */
8
3
  const MAX_DETAIL_LINES = 2000;
9
- /** 插件事件里的用量:只取数字字段 */
4
+ const MAX_ECHO_LINES = 12;
5
+ const ECHO_HEAD_LINES = 6;
10
6
  function usageOf(u) {
11
- if (typeof u !== "object" || u === null)
12
- return undefined;
13
- const out = {};
14
- for (const k of ["inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens"]) {
15
- const v = u[k];
16
- if (typeof v === "number" && Number.isFinite(v))
17
- out[k] = v;
18
- }
19
- return Object.keys(out).length ? out : undefined;
7
+ if (typeof u !== "object" || u === null)
8
+ return;
9
+ const out = {};
10
+ for (const k of ["inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens"]) {
11
+ const v = u[k];
12
+ if (typeof v === "number" && Number.isFinite(v))
13
+ out[k] = v;
14
+ }
15
+ return Object.keys(out).length ? out : undefined;
20
16
  }
21
- const textOf = (blocks) => blocks.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n");
22
- const errorText = (err) => (err instanceof Error ? err.message : String(err));
17
+ const textOf = (blocks) => blocks.flatMap((b) => b.kind === "text" ? [b.text] : []).join(`
18
+ `);
19
+ const errorText = (err) => err instanceof Error ? err.message : String(err);
23
20
  export function transcript(opts) {
24
- const { screen, cwd } = opts;
25
- const usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
26
- const addUsage = (u) => {
27
- for (const k of Object.keys(usage))
28
- usage[k] += u?.[k] ?? 0;
29
- if (u)
30
- screen.status({ spent: { input: usage.inputTokens, output: usage.outputTokens } });
31
- };
32
- /**
33
- * 一个事件带来的用量:模型回复;插件事件 data 里的 usage(压缩时的总结调用、auto 模式的审查这类插件自己发的请求);
34
- * 子 Agent 的用量在它自己的日志里(读不到时不算,不让一个读失败变成没人处理的 rejection)
35
- */
36
- async function countUsage(e) {
37
- if (e.type === "model.responded")
38
- addUsage(e.data.usage);
39
- else if (e.origin.by === "plugin")
40
- addUsage(usageOf(e.data?.usage));
41
- else if (e.type === "tool.completed") {
42
- const child = e.data.child;
43
- if (child && opts.readLog)
44
- for (const c of await opts.readLog(child.sessionId).catch(() => []))
45
- await countUsage(c);
46
- }
21
+ const { screen, cwd } = opts;
22
+ const usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
23
+ const addUsage = (u) => {
24
+ for (const k of Object.keys(usage))
25
+ usage[k] += u?.[k] ?? 0;
26
+ if (u)
27
+ screen.status({ spent: { input: usage.inputTokens, output: usage.outputTokens } });
28
+ };
29
+ async function countUsage(e) {
30
+ if (e.type === "model.responded")
31
+ addUsage(e.data.usage);
32
+ else if (e.origin.by === "plugin")
33
+ addUsage(usageOf(e.data?.usage));
34
+ else if (e.type === "tool.completed") {
35
+ const child = e.data.child;
36
+ if (child && opts.readLog)
37
+ for (const c of await opts.readLog(child.sessionId).catch(() => []))
38
+ await countUsage(c);
47
39
  }
48
- /**
49
- * 报过缓存命中数的 provider/模型。有的服务只在命中时才带这个字段,报过一次之后没带就是没命中;
50
- * 换了服务或模型要重新看,否则从报缓存的服务换到不报的,会一直显示 0%
51
- */
52
- let reportsCache;
53
- /** 上下文用量:最近一次回复的输入加输出,就是下一次请求的大致起点;以及这次输入的缓存命中率 */
54
- function showContext(e) {
55
- const u = e.data.usage;
56
- if (u?.inputTokens === undefined)
57
- return;
58
- const by = e.origin.by === "model" ? `${e.origin.provider}/${e.origin.model}` : "";
59
- if (u.cacheReadTokens !== undefined)
60
- reportsCache = by;
61
- screen.status({
62
- context: { used: u.inputTokens + (u.outputTokens ?? 0), limit: opts.contextWindow(), compactAt: opts.compactAt?.() },
63
- cache: reportsCache === by && u.inputTokens > 0 ? (u.cacheReadTokens ?? 0) / u.inputTokens : undefined,
64
- });
40
+ }
41
+ let reportsCache;
42
+ function showContext(e) {
43
+ const u = e.data.usage;
44
+ if (u?.inputTokens === undefined)
45
+ return;
46
+ const by = e.origin.by === "model" ? `${e.origin.provider}/${e.origin.model}` : "";
47
+ if (u.cacheReadTokens !== undefined)
48
+ reportsCache = by;
49
+ screen.status({
50
+ context: { used: u.inputTokens + (u.outputTokens ?? 0), limit: opts.contextWindow() },
51
+ cache: reportsCache === by && u.inputTokens > 0 ? (u.cacheReadTokens ?? 0) / u.inputTokens : undefined
52
+ });
53
+ }
54
+ const speed = { first: 0, estimate: 0, shown: 0 };
55
+ const startSpeed = () => {
56
+ speed.first = 0;
57
+ speed.estimate = 0;
58
+ toolChars = 0;
59
+ };
60
+ let toolChars = 0;
61
+ const toolLabel = () => toolChars < 1000 ? "Writing" : `Writing (${Math.floor(toolChars / 1000)}k chars)`;
62
+ const trackSpeed = (text) => {
63
+ const now = Date.now();
64
+ if (!speed.first)
65
+ speed.first = now;
66
+ const wide = text.match(/[^\x00-\x7f]/g)?.length ?? 0;
67
+ speed.estimate += (text.length - wide) / 4 + wide;
68
+ if (now - speed.shown < 500 || now - speed.first < 1000)
69
+ return;
70
+ speed.shown = now;
71
+ screen.status({ speed: { tps: speed.estimate / ((now - speed.first) / 1000), live: true } });
72
+ };
73
+ const finishSpeed = (u) => {
74
+ const seconds = (Date.now() - speed.first) / 1000;
75
+ const tokens = u?.outputTokens ?? Math.round(speed.estimate);
76
+ if (speed.first && tokens > 0 && seconds >= 0.2)
77
+ screen.status({ speed: { tps: tokens / seconds } });
78
+ speed.first = 0;
79
+ speed.estimate = 0;
80
+ };
81
+ const toolNames = new Map;
82
+ let replaying = false;
83
+ const activity = (label) => {
84
+ if (!replaying)
85
+ screen.busy(label);
86
+ };
87
+ let streamed = false;
88
+ const running = new Set;
89
+ const calls = new Map;
90
+ const befores = new Map;
91
+ const progress = (id, line, o) => {
92
+ running.add(id);
93
+ screen.progress(id, line, o);
94
+ };
95
+ const doneProgress = (id) => {
96
+ if (running.delete(id))
97
+ screen.progress(id, undefined);
98
+ };
99
+ const inputs = new Map;
100
+ const asks = new Map;
101
+ const failed = new Set;
102
+ async function custom(name, use) {
103
+ const found = opts.renderer?.(name);
104
+ if (!found)
105
+ return;
106
+ try {
107
+ return await use(found.renderer);
108
+ } catch (err) {
109
+ renderFailed(found.plugin, name, err);
110
+ return;
65
111
  }
66
- /**
67
- * 输出速度:从第一个增量开始计时(不算等待首个 token 的时间),输出中按字数估 token 数,每半秒更新一次状态栏;
68
- * 回复结束后用服务端报的输出 token 数算准确值。工具参数的增量也算输出,只调用工具的回复同样从第一个增量开始计时。
69
- * 一个增量都没收到的回复(不支持流式的服务)不更新速度:从发出请求开始算会把等待首个 token 的时间也算进去,数字偏低
70
- */
71
- const speed = { first: 0, estimate: 0, shown: 0 };
72
- const startSpeed = () => {
73
- speed.first = 0;
74
- speed.estimate = 0;
75
- toolChars = 0;
76
- };
77
- /** 这次回复里工具参数已经生成的字数:写大文件时一写几分钟,显示出来才看得出不是卡住了 */
78
- let toolChars = 0;
79
- const toolLabel = () => (toolChars < 1000 ? "Writing" : `Writing (${Math.floor(toolChars / 1000)}k chars)`);
80
- const trackSpeed = (text) => {
81
- const now = Date.now();
82
- if (!speed.first)
83
- speed.first = now;
84
- const wide = text.match(/[^\x00-\x7f]/g)?.length ?? 0;
85
- speed.estimate += (text.length - wide) / 4 + wide;
86
- if (now - speed.shown < 500 || now - speed.first < 1000)
87
- return;
88
- speed.shown = now;
89
- screen.status({ speed: { tps: speed.estimate / ((now - speed.first) / 1000), live: true } });
90
- };
91
- const finishSpeed = (u) => {
92
- const seconds = (Date.now() - speed.first) / 1000;
93
- const tokens = u?.outputTokens ?? Math.round(speed.estimate);
94
- if (speed.first && tokens > 0 && seconds >= 0.2)
95
- screen.status({ speed: { tps: tokens / seconds } });
96
- speed.first = 0;
97
- speed.estimate = 0;
98
- };
99
- const toolNames = new Map();
100
- /** 正在重新显示恢复的会话里已有的内容:只输出,不显示进行中的状态 */
101
- let replaying = false;
102
- const activity = (label) => {
103
- if (!replaying)
104
- screen.busy(label);
105
- };
106
- let streamed = false;
107
- /** 正在运行、显示着进度的工具 */
108
- const running = new Set();
109
- /** 调用行省略了的参数(例如很长的命令),结果出来后放在折叠内容的最前面 */
110
- const calls = new Map();
111
- /** renderer 的 before 在执行前记下的东西,结果出来时交给它的 result */
112
- const befores = new Map();
113
- const progress = (id, line, o) => {
114
- running.add(id);
115
- screen.progress(id, line, o);
116
- };
117
- const doneProgress = (id) => {
118
- if (running.delete(id))
119
- screen.progress(id, undefined);
120
- };
121
- /** 有 result renderer 的调用的参数,结果出来时交给它 */
122
- const inputs = new Map();
123
- /** 等人工审批的调用的参数,回答(input.received)来了按它显示 */
124
- const asks = new Map();
125
- /** 出过错的 renderer(插件 + 工具),只提示一次 */
126
- const failed = new Set();
127
- /** 调用插件的 renderer;没有、出错时返回 undefined(用默认的显示) */
128
- async function custom(name, use) {
129
- const found = opts.renderer?.(name);
130
- if (!found)
131
- return undefined;
132
- try {
133
- return await use(found.renderer);
134
- }
135
- catch (err) {
136
- renderFailed(found.plugin, name, err);
137
- return undefined;
138
- }
112
+ }
113
+ function customSync(name, use) {
114
+ const found = opts.renderer?.(name);
115
+ if (!found)
116
+ return;
117
+ try {
118
+ return use(found.renderer);
119
+ } catch (err) {
120
+ renderFailed(found.plugin, name, err);
121
+ return;
139
122
  }
140
- /** 同步的版本:摘要和结果在事件通知里同步显示 */
141
- function customSync(name, use) {
142
- const found = opts.renderer?.(name);
143
- if (!found)
144
- return undefined;
145
- try {
146
- return use(found.renderer);
123
+ }
124
+ function renderFailed(plugin, name, err) {
125
+ if (failed.has(`${plugin}:${name}`))
126
+ return;
127
+ failed.add(`${plugin}:${name}`);
128
+ screen.log(yellow(`[warning] plugin ${plugin}: showing ${name} failed, using the default display: ${errorText(err)}`));
129
+ }
130
+ const summary = (name, input) => {
131
+ const s = customSync(name, (r) => r.summary?.(input));
132
+ return typeof s === "string" ? clip(s.split(`
133
+ `)[0], 120) : summarize(cwd, input);
134
+ };
135
+ const details = (name, input) => {
136
+ const d = customSync(name, (r) => r.details?.(input));
137
+ return typeof d === "string" && d ? d.replace(/^/gm, " ") : undefined;
138
+ };
139
+ const self = {
140
+ usage,
141
+ lastEnd: undefined,
142
+ lastError: undefined,
143
+ turnFailed: false,
144
+ onNotice,
145
+ replay,
146
+ summary,
147
+ details,
148
+ async preview(c) {
149
+ const p = await custom(c.name, (r) => r.preview?.(c.input));
150
+ return typeof p === "string" ? p : preview(c.input);
151
+ },
152
+ echo: (text) => {
153
+ const shown = (t) => t.startsWith("/") ? cyan(`› ${t}`) : `
154
+ ${bold(`› ${t.replace(/\n/g, `
155
+ `)}`)}`;
156
+ const lines = text.split(`
157
+ `);
158
+ if (lines.length <= MAX_ECHO_LINES)
159
+ return screen.log(shown(text));
160
+ const rest = lines.slice(ECHO_HEAD_LINES);
161
+ screen.log(`${shown(lines.slice(0, ECHO_HEAD_LINES).join(`
162
+ `))}
163
+ ${dim(`… +${rest.length} lines`)}`, { details: rest.map((l) => ` ${l}`).join(`
164
+ `) });
165
+ },
166
+ reset() {
167
+ for (const k of Object.keys(usage))
168
+ usage[k] = 0;
169
+ reportsCache = undefined;
170
+ toolNames.clear();
171
+ for (const id of running)
172
+ screen.progress(id, undefined);
173
+ running.clear();
174
+ calls.clear();
175
+ befores.clear();
176
+ inputs.clear();
177
+ asks.clear();
178
+ self.lastEnd = undefined;
179
+ }
180
+ };
181
+ function onNotice(n) {
182
+ switch (n.type) {
183
+ case "delta":
184
+ if (n.delta.kind === "reset") {
185
+ if (streamed) {
186
+ screen.endStream();
187
+ screen.log(yellow("[output above discarded; retrying]"));
188
+ }
189
+ streamed = false;
190
+ startSpeed();
191
+ return;
192
+ }
193
+ trackSpeed(n.delta.text);
194
+ if (n.delta.kind === "tool_input") {
195
+ const before = toolLabel();
196
+ toolChars += n.delta.text.length;
197
+ const label = toolLabel();
198
+ if (label !== before || toolChars === n.delta.text.length)
199
+ screen.busy(label);
200
+ return;
147
201
  }
148
- catch (err) {
149
- renderFailed(found.plugin, name, err);
150
- return undefined;
202
+ streamed = true;
203
+ if (n.delta.kind === "thinking") {
204
+ screen.busy("Thinking");
205
+ screen.stream("thinking", n.delta.text);
206
+ } else {
207
+ screen.busy("Writing");
208
+ screen.stream("text", n.delta.text);
151
209
  }
210
+ return;
211
+ case "hook-error":
212
+ screen.log(yellow(`[hook error] ${n.info.plugin} at ${n.info.point}: ${errorText(n.info.error)}`));
213
+ return;
214
+ case "warning":
215
+ screen.log(yellow(`[warning] ${n.code}`));
216
+ return;
217
+ case "awaiting":
218
+ return;
219
+ case "tool-progress":
220
+ return renderProgress(n.toolUseId, n.update);
221
+ case "event":
222
+ return renderEvent(n.event);
152
223
  }
153
- function renderFailed(plugin, name, err) {
154
- if (failed.has(`${plugin}:${name}`))
155
- return;
156
- failed.add(`${plugin}:${name}`);
157
- screen.log(yellow(`[warning] plugin ${plugin}: showing ${name} failed, using the default display: ${errorText(err)}`));
224
+ }
225
+ function renderProgress(toolUseId, update) {
226
+ const name = toolNames.get(toolUseId) ?? "?";
227
+ if (opts.renderer?.(name)?.renderer.progress) {
228
+ const line = customSync(name, (r) => r.progress?.(update, { toolUseId, summary }));
229
+ if (typeof line === "string" && line)
230
+ progress(toolUseId, clipStyled(line.split(`
231
+ `)[0], 200));
232
+ return;
158
233
  }
159
- const summary = (name, input) => {
160
- const s = customSync(name, (r) => r.summary?.(input));
161
- return typeof s === "string" ? clip(s.split("\n")[0], 120) : summarize(cwd, input);
162
- };
163
- const details = (name, input) => {
164
- const d = customSync(name, (r) => r.details?.(input));
165
- return typeof d === "string" && d ? d.replace(/^/gm, " ") : undefined;
166
- };
167
- const self = {
168
- usage,
169
- lastEnd: undefined,
170
- lastError: undefined,
171
- turnFailed: false,
172
- onNotice,
173
- replay,
174
- summary,
175
- details,
176
- async preview(c) {
177
- const p = await custom(c.name, (r) => r.preview?.(c.input));
178
- return typeof p === "string" ? p : preview(c.input);
179
- },
180
- echo: (text) => screen.log(text.startsWith("/") ? cyan(`› ${text}`) : `\n${bold(`› ${text.replace(/\n/g, "\n ")}`)}`),
181
- reset() {
182
- for (const k of Object.keys(usage))
183
- usage[k] = 0;
184
- reportsCache = undefined;
185
- toolNames.clear();
186
- for (const id of running)
187
- screen.progress(id, undefined);
188
- running.clear();
189
- calls.clear();
190
- befores.clear();
191
- inputs.clear();
192
- asks.clear();
193
- self.lastEnd = undefined;
194
- },
195
- };
196
- function onNotice(n) {
197
- switch (n.type) {
198
- case "delta":
199
- if (n.delta.kind === "reset") {
200
- // 已经输出的内容收不回来,标记一下
201
- if (streamed) {
202
- screen.endStream();
203
- screen.log(yellow("[output above discarded; retrying]"));
204
- }
205
- streamed = false;
206
- startSpeed();
207
- return;
208
- }
209
- trackSpeed(n.delta.text);
210
- // 工具参数只用来计时,不显示;也不算已经输出了内容(重试时不用标记作废,回复结束时照常打印没流式输出的正文)
211
- if (n.delta.kind === "tool_input") {
212
- // 只在千位变了时更新,不让每个增量都重画
213
- const before = toolLabel();
214
- toolChars += n.delta.text.length;
215
- const label = toolLabel();
216
- if (label !== before || toolChars === n.delta.text.length)
217
- screen.busy(label);
218
- return;
219
- }
220
- streamed = true;
221
- if (n.delta.kind === "thinking") {
222
- screen.busy("Thinking");
223
- screen.stream("thinking", n.delta.text);
224
- }
225
- else {
226
- screen.busy("Writing");
227
- screen.stream("text", n.delta.text);
228
- }
229
- return;
230
- case "hook-error":
231
- screen.log(yellow(`[hook error] ${n.info.plugin} at ${n.info.point}: ${errorText(n.info.error)}`));
232
- return;
233
- case "warning":
234
- screen.log(yellow(`[warning] ${n.code}`));
235
- return;
236
- case "awaiting":
237
- return;
238
- case "tool-progress":
239
- return renderProgress(n.toolUseId, n.update);
240
- case "event":
241
- return renderEvent(n.event);
234
+ const text = update?.text;
235
+ if (typeof text !== "string")
236
+ return;
237
+ for (const l of text.replace(/\n$/, "").split(`
238
+ `))
239
+ progress(toolUseId, dim(` │ ${clip(l, 200)}`), { output: true });
240
+ }
241
+ function renderEvent(e) {
242
+ switch (e.type) {
243
+ case "model.requested":
244
+ activity("Waiting for the model");
245
+ if (!replaying)
246
+ startSpeed();
247
+ return;
248
+ case "model.responded": {
249
+ const d = e.data;
250
+ countUsage(e);
251
+ showContext(e);
252
+ if (!replaying)
253
+ finishSpeed(d.usage);
254
+ for (const b of d.content)
255
+ if (b.kind === "tool_use")
256
+ toolNames.set(b.id, b.name);
257
+ if (!streamed) {
258
+ const text = textOf(d.content).trim();
259
+ if (text)
260
+ screen.stream("text", text);
242
261
  }
243
- }
244
- /** 工具的进度:有 renderer 的 progress 时由它换成一行;否则 { text } 形式的按输出逐行显示(例如 bash),其他的不显示 */
245
- function renderProgress(toolUseId, update) {
246
- const name = toolNames.get(toolUseId) ?? "?";
247
- if (opts.renderer?.(name)?.renderer.progress) {
248
- const line = customSync(name, (r) => r.progress?.(update, { toolUseId, summary }));
249
- if (typeof line === "string" && line)
250
- progress(toolUseId, clipStyled(line.split("\n")[0], 200));
251
- return;
262
+ streamed = false;
263
+ screen.endStream();
264
+ return;
265
+ }
266
+ case "tool.decided": {
267
+ const d = e.data;
268
+ const name = toolNames.get(d.toolUseId) ?? "?";
269
+ const full = details(name, d.input);
270
+ if (full)
271
+ calls.set(d.toolUseId, full);
272
+ if (opts.renderer?.(name)?.renderer.result)
273
+ inputs.set(d.toolUseId, d.input);
274
+ if (d.decision === "ask") {
275
+ asks.set(d.toolUseId, d.input);
276
+ return;
252
277
  }
253
- const text = update?.text;
254
- if (typeof text !== "string")
255
- return;
256
- for (const l of text.replace(/\n$/, "").split("\n"))
257
- progress(toolUseId, dim(` │ ${clip(l, 200)}`), { output: true });
258
- }
259
- function renderEvent(e) {
260
- switch (e.type) {
261
- case "model.requested":
262
- activity("Waiting for the model");
263
- if (!replaying)
264
- startSpeed();
265
- return;
266
- case "model.responded": {
267
- const d = e.data;
268
- void countUsage(e);
269
- showContext(e);
270
- if (!replaying)
271
- finishSpeed(d.usage);
272
- for (const b of d.content)
273
- if (b.kind === "tool_use")
274
- toolNames.set(b.id, b.name);
275
- // 不支持流式的 provider、重新显示历史:一次送出最终文本,和流式输出一样排版
276
- if (!streamed) {
277
- const text = textOf(d.content).trim();
278
- if (text)
279
- screen.stream("text", text);
280
- }
281
- streamed = false;
282
- screen.endStream();
283
- return;
284
- }
285
- case "tool.decided": {
286
- const d = e.data;
287
- const name = toolNames.get(d.toolUseId) ?? "?";
288
- const full = details(name, d.input);
289
- if (full)
290
- calls.set(d.toolUseId, full);
291
- if (opts.renderer?.(name)?.renderer.result)
292
- inputs.set(d.toolUseId, d.input);
293
- if (d.decision === "ask") {
294
- asks.set(d.toolUseId, d.input);
295
- return;
296
- }
297
- // 执行前交给 renderer 的 before(例如按文件当时的内容算 diff);重新显示历史时文件已经变了,不调用
298
- if (d.decision === "allow" && !replaying) {
299
- const before = customSync(name, (r) => r.before?.(d.input));
300
- if (before !== undefined)
301
- befores.set(d.toolUseId, before);
302
- }
303
- const head = `${bold(name)}(${summary(name, d.input)})`;
304
- if (d.decision === "deny")
305
- screen.log(red(`✗ ${head}`) + dim(d.reason ? ` — ${clip(d.reason, 200)}` : ""), { id: d.toolUseId, details: full });
306
- else {
307
- activity(`Running ${name}`);
308
- // 用户批准的调用在审批时已经显示过;重新显示历史时没有审批这一步
309
- if (d.decidedBy !== "user" || replaying) {
310
- const own = customSync(name, (r) => r.call?.(d.input));
311
- if (typeof own === "string" && own) {
312
- // renderer 给的内容:第一行是调用行(结果接在它后面),其余的行不折叠
313
- const [first, ...rest] = own.split("\n");
314
- screen.log(cyan("● ") + first, { id: d.toolUseId, details: full });
315
- if (rest.length)
316
- screen.log(rest.join("\n"));
317
- }
318
- else {
319
- // auto 模式下审查放行的带着理由
320
- screen.log(cyan("● ") + head + (d.reason ? dim(` — ${clip(d.reason, 160)}`) : ""), { id: d.toolUseId, details: full });
321
- }
322
- }
323
- }
324
- return;
325
- }
326
- case "input.received": {
327
- // 对等待审批的调用的回答:和关卡直接决定的一样显示
328
- const d = e.data;
329
- if (d.kind !== "approval")
330
- return;
331
- const input = asks.get(d.toolUseId);
332
- asks.delete(d.toolUseId);
333
- const decided = { toolUseId: d.toolUseId, decision: d.approved ? "allow" : "deny", input, ...(d.approved ? {} : { reason: d.reason }) };
334
- return renderEvent({ ...e, type: "tool.decided", data: decided });
335
- }
336
- case "tool.completed": {
337
- const d = e.data;
338
- void countUsage(e);
339
- activity("Working");
340
- doneProgress(d.toolUseId);
341
- const call = calls.get(d.toolUseId);
342
- calls.delete(d.toolUseId);
343
- const before = befores.get(d.toolUseId);
344
- befores.delete(d.toolUseId);
345
- const input = inputs.get(d.toolUseId);
346
- inputs.delete(d.toolUseId);
347
- const text = textOf(d.content).trim();
348
- const name = toolNames.get(d.toolUseId) ?? "?";
349
- const mine = customSync(name, (r) => r.result?.({ toolUseId: d.toolUseId, input, text, isError: d.isError === true, before }));
350
- // null:renderer 不要显示结果
351
- if (mine === null)
352
- return;
353
- if (mine && typeof mine.line === "string") {
354
- const own = typeof mine.details === "string" && mine.details ? [mine.details.replace(/^/gm, " ")] : [];
355
- const folded = [...(call ? [call] : []), ...own].join("\n") || undefined;
356
- screen.amend(d.toolUseId, (d.isError ? red : dim)("⎿ ") + clipStyled(mine.line.split("\n")[0], 200), { details: folded });
357
- return;
358
- }
359
- const lines = text.split("\n");
360
- // 结果接在调用的那一行后面;摘要省略了内容时,把完整结果(和子 Agent 调用过的工具)折叠起来,点击展开
361
- const shown = d.isError ? 4 : 1;
362
- const width = d.isError ? 200 : 160;
363
- const hidden = lines.length > shown || lines.some((l) => l.length > width);
364
- const details = hidden || call
365
- ? [...(call ? [call] : []), ...(hidden ? [detailsOf(lines, d.isError ? red : (s) => s, MAX_DETAIL_LINES)] : [])].join("\n")
366
- : undefined;
367
- if (d.isError)
368
- screen.amend(d.toolUseId, red(`⎿ ${lines.slice(0, shown).map((l) => clip(l, width)).join("\n ")}`), { details });
369
- else
370
- screen.amend(d.toolUseId, dim(`⎿ ${clip(lines[0] ?? "", width)}${lines.length > 1 ? ` (+${lines.length - 1} lines)` : ""}`), { details });
371
- return;
372
- }
373
- case "tool.interrupted": {
374
- const d = e.data;
375
- doneProgress(d.toolUseId);
376
- calls.delete(d.toolUseId);
377
- befores.delete(d.toolUseId);
378
- inputs.delete(d.toolUseId);
379
- screen.amend(d.toolUseId, yellow("⎿ interrupted before finishing; not retried"));
380
- return;
381
- }
382
- case "turn.ended": {
383
- const d = e.data;
384
- self.lastEnd = d.reason;
385
- for (const id of [...running])
386
- doneProgress(id);
387
- self.lastError = d.error;
388
- self.turnFailed = d.reason === "error" || d.reason === "aborted";
389
- if (d.reason === "stopped")
390
- screen.log(yellow("[stopped: step budget for this turn used up; send a message to continue]"));
391
- else if (d.reason === "aborted")
392
- screen.log(yellow("[interrupted]"));
393
- else if (d.reason === "max_tokens") {
394
- // 不读 process.env:写在 $JADE_HOME/.env 里的只有 models 插件知道
395
- const max = opts.maxTokens?.();
396
- const limit = max ? `${max} tokens` : "the provider's default";
397
- screen.log(yellow(`[reply cut off at the output limit (${limit}); raise it with /model if this keeps happening]`));
398
- }
399
- else if (d.reason !== "end")
400
- screen.log(yellow(`[turn ended: ${d.reason}${d.error ? ` — ${d.error}` : ""}]`));
401
- if (self.turnFailed && !replaying && opts.canRetry())
402
- screen.log(dim("[send /retry to request again without adding a message]"));
403
- return;
404
- }
405
- default:
406
- return renderPluginEvent(e);
278
+ if (d.decision === "allow" && !replaying) {
279
+ const before = customSync(name, (r) => r.before?.(d.input));
280
+ if (before !== undefined)
281
+ befores.set(d.toolUseId, before);
407
282
  }
408
- }
409
- /**
410
- * 插件的事件:用量照常统计;插件为它注册了渲染器时由渲染器显示,
411
- * 否则只有 ctx.emit("notice", { text, level? }) 写入的提示显示成 [插件 id] 文本
412
- */
413
- function renderPluginEvent(e) {
414
- if (e.origin.by !== "plugin")
415
- return;
416
- void countUsage(e);
417
- const found = opts.eventRenderer?.(e.type);
418
- if (!found)
419
- return renderPluginNotice(e);
420
- let shown;
421
- try {
422
- shown = found.renderer.render(e.data);
283
+ const head = `${bold(name)}(${summary(name, d.input)})`;
284
+ if (d.decision === "deny")
285
+ screen.log(red(`✗ ${head}`) + dim(d.reason ? ` — ${clip(d.reason, 200)}` : ""), { id: d.toolUseId, details: full });
286
+ else {
287
+ activity(`Running ${name}`);
288
+ if (d.decidedBy !== "user" || replaying) {
289
+ const own = customSync(name, (r) => r.call?.(d.input));
290
+ if (typeof own === "string" && own) {
291
+ const [first, ...rest] = own.split(`
292
+ `);
293
+ screen.log(cyan("● ") + first, { id: d.toolUseId, details: full });
294
+ if (rest.length)
295
+ screen.log(rest.join(`
296
+ `));
297
+ } else {
298
+ screen.log(cyan("● ") + head + (d.reason ? dim(` — ${clip(d.reason, 160)}`) : ""), { id: d.toolUseId, details: full });
299
+ }
300
+ }
423
301
  }
424
- catch (err) {
425
- return renderFailed(found.plugin, e.type, err);
302
+ return;
303
+ }
304
+ case "input.received": {
305
+ const d = e.data;
306
+ if (d.kind !== "approval")
307
+ return;
308
+ const input = asks.get(d.toolUseId);
309
+ asks.delete(d.toolUseId);
310
+ const decided = { toolUseId: d.toolUseId, decision: d.approved ? "allow" : "deny", input, ...d.approved ? {} : { reason: d.reason } };
311
+ return renderEvent({ ...e, type: "tool.decided", data: decided });
312
+ }
313
+ case "tool.completed": {
314
+ const d = e.data;
315
+ countUsage(e);
316
+ activity("Working");
317
+ doneProgress(d.toolUseId);
318
+ const call = calls.get(d.toolUseId);
319
+ calls.delete(d.toolUseId);
320
+ const before = befores.get(d.toolUseId);
321
+ befores.delete(d.toolUseId);
322
+ const input = inputs.get(d.toolUseId);
323
+ inputs.delete(d.toolUseId);
324
+ const text = textOf(d.content).trim();
325
+ const name = toolNames.get(d.toolUseId) ?? "?";
326
+ const mine = customSync(name, (r) => r.result?.({ toolUseId: d.toolUseId, input, text, isError: d.isError === true, before }));
327
+ if (mine === null)
328
+ return;
329
+ if (mine && typeof mine.line === "string") {
330
+ const own = typeof mine.details === "string" && mine.details ? [mine.details.replace(/^/gm, " ")] : [];
331
+ const folded = [...call ? [call] : [], ...own].join(`
332
+ `) || undefined;
333
+ screen.amend(d.toolUseId, (d.isError ? red : dim)("⎿ ") + clipStyled(mine.line.split(`
334
+ `)[0], 200), { details: folded });
335
+ return;
426
336
  }
427
- if (!shown || typeof shown.line !== "string")
428
- return;
429
- const details = typeof shown.details === "string" && shown.details ? shown.details.replace(/^/gm, " ") : undefined;
430
- screen.log(shown.line, { details });
431
- }
432
- /** 插件用 ctx.emit("notice", { text, level? }) 写入的提示,显示成 [插件 id] 文本 */
433
- function renderPluginNotice(e) {
434
- if (e.origin.by !== "plugin" || !e.type.endsWith("/notice"))
435
- return;
337
+ const lines = text.split(`
338
+ `);
339
+ const shown = d.isError ? 4 : 1;
340
+ const width = d.isError ? 200 : 160;
341
+ const hidden = lines.length > shown || lines.some((l) => l.length > width);
342
+ const details = hidden || call ? [...call ? [call] : [], ...hidden ? [detailsOf(lines, d.isError ? red : (s) => s, MAX_DETAIL_LINES)] : []].join(`
343
+ `) : undefined;
344
+ if (d.isError)
345
+ screen.amend(d.toolUseId, red(`⎿ ${lines.slice(0, shown).map((l) => clip(l, width)).join(`
346
+ `)}`), { details });
347
+ else
348
+ screen.amend(d.toolUseId, dim(`⎿ ${clip(lines[0] ?? "", width)}${lines.length > 1 ? ` (+${lines.length - 1} lines)` : ""}`), { details });
349
+ return;
350
+ }
351
+ case "tool.interrupted": {
436
352
  const d = e.data;
437
- if (typeof d?.text !== "string" || !d.text)
438
- return;
439
- const line = `[${e.origin.id}] ${clip(d.text, 2000)}`;
440
- screen.log(d.level === "warning" ? yellow(line) : dim(line));
353
+ doneProgress(d.toolUseId);
354
+ calls.delete(d.toolUseId);
355
+ befores.delete(d.toolUseId);
356
+ inputs.delete(d.toolUseId);
357
+ screen.amend(d.toolUseId, yellow("⎿ interrupted before finishing; not retried"));
358
+ return;
359
+ }
360
+ case "turn.ended": {
361
+ const d = e.data;
362
+ self.lastEnd = d.reason;
363
+ for (const id of [...running])
364
+ doneProgress(id);
365
+ self.lastError = d.error;
366
+ self.turnFailed = d.reason === "error" || d.reason === "aborted";
367
+ if (d.reason === "stopped")
368
+ screen.log(yellow("[stopped before the turn finished; send a message to continue]"));
369
+ else if (d.reason === "aborted")
370
+ screen.log(yellow("[interrupted]"));
371
+ else if (d.reason === "max_tokens") {
372
+ const max = opts.maxTokens?.();
373
+ const limit = max ? `${max} tokens` : "the provider's default";
374
+ screen.log(yellow(`[reply cut off at the output limit (${limit})]`));
375
+ } else if (d.reason !== "end")
376
+ screen.log(yellow(`[turn ended: ${d.reason}${d.error ? ` — ${d.error}` : ""}]`));
377
+ if (self.turnFailed && !replaying && opts.canRetry())
378
+ screen.log(dim("[send /retry to request again without adding a message]"));
379
+ return;
380
+ }
381
+ default:
382
+ return renderPluginEvent(e);
441
383
  }
442
- async function replay(events, show) {
443
- if (!show) {
444
- for (const e of events) {
445
- await countUsage(e);
446
- if (e.type === "model.responded")
447
- showContext(e);
448
- }
449
- return;
384
+ }
385
+ function renderPluginEvent(e) {
386
+ if (e.origin.by !== "plugin")
387
+ return;
388
+ countUsage(e);
389
+ const found = opts.eventRenderer?.(e.type);
390
+ if (!found)
391
+ return renderPluginNotice(e);
392
+ let shown;
393
+ try {
394
+ shown = found.renderer.render(e.data);
395
+ } catch (err) {
396
+ return renderFailed(found.plugin, e.type, err);
397
+ }
398
+ if (!shown || typeof shown.line !== "string")
399
+ return;
400
+ const details = typeof shown.details === "string" && shown.details ? shown.details.replace(/^/gm, " ") : undefined;
401
+ screen.log(shown.line, { details });
402
+ }
403
+ function renderPluginNotice(e) {
404
+ if (e.origin.by !== "plugin" || !e.type.endsWith("/notice"))
405
+ return;
406
+ const d = e.data;
407
+ if (typeof d?.text !== "string" || !d.text)
408
+ return;
409
+ const line = `[${e.origin.id}] ${clip(d.text, 2000)}`;
410
+ screen.log(d.level === "warning" ? yellow(line) : dim(line));
411
+ }
412
+ async function replay(events, show) {
413
+ if (!show) {
414
+ for (const e of events) {
415
+ await countUsage(e);
416
+ if (e.type === "model.responded")
417
+ showContext(e);
418
+ }
419
+ return;
420
+ }
421
+ replaying = true;
422
+ const asked = new Map;
423
+ try {
424
+ for (const e of events) {
425
+ if (e.type === "tool.decided") {
426
+ const d = e.data;
427
+ if (d.decision === "ask")
428
+ asked.set(d.toolUseId, d.input);
450
429
  }
451
- replaying = true;
452
- /** 等待用户审批的调用的参数,用户的决定记在之后的 input.received 里 */
453
- const asked = new Map();
454
- try {
455
- for (const e of events) {
456
- if (e.type === "tool.decided") {
457
- const d = e.data;
458
- if (d.decision === "ask")
459
- asked.set(d.toolUseId, d.input);
460
- }
461
- if (e.type !== "input.received") {
462
- renderEvent(e);
463
- continue;
464
- }
465
- const d = e.data;
466
- if (d.kind === "approval") {
467
- const name = toolNames.get(d.toolUseId) ?? "?";
468
- const head = `${bold(name)}(${summary(name, asked.get(d.toolUseId))})`;
469
- screen.log(d.approved ? green(`✓ ${head}`) : red(`✗ ${head}`) + dim(d.reason ? ` — ${clip(d.reason, 200)}` : ""), {
470
- id: d.toolUseId,
471
- details: details(name, asked.get(d.toolUseId)),
472
- });
473
- continue;
474
- }
475
- if (d.kind === "retry") {
476
- screen.log(dim("[retried]"));
477
- continue;
478
- }
479
- if (d.kind !== "message")
480
- continue;
481
- // 宿主附带的说明(例如自动续写)不是用户说的话
482
- const text = d.content.flatMap((b) => (b.kind === "text" && b.origin.by === "user" ? [b.text] : [])).join("\n");
483
- if (text)
484
- self.echo(text);
485
- }
430
+ if (e.type !== "input.received") {
431
+ renderEvent(e);
432
+ continue;
433
+ }
434
+ const d = e.data;
435
+ if (d.kind === "approval") {
436
+ const name = toolNames.get(d.toolUseId) ?? "?";
437
+ const head = `${bold(name)}(${summary(name, asked.get(d.toolUseId))})`;
438
+ screen.log(d.approved ? green(`✓ ${head}`) : red(`✗ ${head}`) + dim(d.reason ? ` — ${clip(d.reason, 200)}` : ""), {
439
+ id: d.toolUseId,
440
+ details: details(name, asked.get(d.toolUseId))
441
+ });
442
+ continue;
486
443
  }
487
- finally {
488
- replaying = false;
444
+ if (d.kind === "retry") {
445
+ screen.log(dim("[retried]"));
446
+ continue;
489
447
  }
490
- screen.log(dim("─".repeat(20) + " resumed " + "─".repeat(20)));
448
+ if (d.kind !== "message")
449
+ continue;
450
+ const text = d.content.flatMap((b) => b.kind === "text" && b.origin.by === "user" ? [b.text] : []).join(`
451
+ `);
452
+ if (text)
453
+ self.echo(text);
454
+ }
455
+ } finally {
456
+ replaying = false;
491
457
  }
492
- return self;
458
+ screen.log(dim("─".repeat(20) + " resumed " + "─".repeat(20)));
459
+ }
460
+ return self;
493
461
  }