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