mocode-ai 1.8.4 → 1.8.6

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.
@@ -0,0 +1,143 @@
1
+ // 请求体字节预算:与 token 窗口并列的第二个预算。
2
+ //
3
+ // 为什么需要:上游网关(如本机 Kiro-Go,maxPayloadBytes = 900 KiB)限的是**整个请求体字节数**,
4
+ // 而 token 估算按像素算图、看不到字节;图片又随 history 每步重发。token 只用了 7% 却被 400 拒收,
5
+ // 就是这个维度没人管。
6
+ //
7
+ // 口径(只有一个系数):上限 L 的 80% 为触发线。L 的来源按优先级:
8
+ // 1. 显式配置 MOCODE_REQUEST_MAX_KB(网关硬上限,Kiro-Go 填 900);
9
+ // 2. 自动学习:上游以 context_length_exceeded 拒收、而本地 token 估算远低于窗口时,
10
+ // 把那次失败请求的估算字节数记为 L(取历史最小值,按 baseURL 持久化);
11
+ // 3. 都没有 → 0 = 不限制(直连官方 API 不会无谓丢图)。
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { createHash } from 'node:crypto';
16
+ /** 触发线 = 上限 × 0.8。整套机制唯一的系数。 */
17
+ export const REQUEST_BYTES_TRIGGER_RATIO = 0.8;
18
+ /** 低于它的失败请求不可能是「字节上限」问题,不学习,防止误学出极小上限。 */
19
+ const MIN_LEARNABLE_BYTES = 64 * 1024;
20
+ const toolBytesCache = new WeakMap();
21
+ function toolsBytes(tools) {
22
+ if (tools.length === 0)
23
+ return 0;
24
+ const key = tools;
25
+ const hit = toolBytesCache.get(key);
26
+ if (hit !== undefined)
27
+ return hit;
28
+ const n = Buffer.byteLength(JSON.stringify(tools), 'utf8');
29
+ toolBytesCache.set(key, n);
30
+ return n;
31
+ }
32
+ /**
33
+ * 估算一次请求体的字节数:文本按 UTF-8 字节、图片按 data URL 长度(ASCII)、工具 schema 按 JSON 长度,
34
+ * 每条消息加 32 字节结构开销。偏差在几个百分点内,够做 0.8 触发线的判断。纯函数、永不抛错。
35
+ */
36
+ export function estimateRequestBytes(messages, tools = []) {
37
+ let sum = 0;
38
+ try {
39
+ sum += toolsBytes(tools);
40
+ for (const m of messages) {
41
+ sum += 32;
42
+ const content = m.content;
43
+ if (typeof content === 'string') {
44
+ sum += Buffer.byteLength(content, 'utf8');
45
+ }
46
+ else if (Array.isArray(content)) {
47
+ for (const part of content) {
48
+ if (!part || typeof part !== 'object')
49
+ continue;
50
+ const p = part;
51
+ if (typeof p.text === 'string')
52
+ sum += Buffer.byteLength(p.text, 'utf8');
53
+ if (p.type === 'image_url') {
54
+ const iu = p.image_url;
55
+ const url = typeof iu === 'string' ? iu : iu && typeof iu === 'object' ? iu.url : undefined;
56
+ sum += 40 + (typeof url === 'string' ? url.length : 0);
57
+ }
58
+ }
59
+ }
60
+ const calls = m
61
+ .tool_calls;
62
+ if (Array.isArray(calls)) {
63
+ for (const c of calls) {
64
+ sum += 48 + (c?.id?.length ?? 0) + (c?.function?.name?.length ?? 0) + (c?.function?.arguments?.length ?? 0);
65
+ }
66
+ }
67
+ }
68
+ }
69
+ catch {
70
+ // 估算失败按已累计值返回;不能因度量阻断请求。
71
+ }
72
+ return sum;
73
+ }
74
+ /** 显式配置的网关硬上限(字节)。MOCODE_REQUEST_MAX_KB;未配置/空串/非法/0 → 0。 */
75
+ export function explicitRequestLimitBytes() {
76
+ const raw = process.env.MOCODE_REQUEST_MAX_KB;
77
+ if (raw === undefined || raw.trim() === '')
78
+ return 0;
79
+ const kb = Number(raw);
80
+ return Number.isFinite(kb) && kb > 0 ? Math.round(kb * 1024) : 0;
81
+ }
82
+ let cache;
83
+ function cachePath() {
84
+ return process.env.MOCODE_REQUEST_LIMIT_CACHE || path.join(os.homedir(), '.mocode', 'request-limits.json');
85
+ }
86
+ /** 只落 baseURL 的摘要,避免 URL 中偶然携带的凭据写盘。 */
87
+ function keyOf(baseURL) {
88
+ return createHash('sha256').update(baseURL).digest('hex');
89
+ }
90
+ function readCache() {
91
+ if (cache)
92
+ return cache;
93
+ try {
94
+ const parsed = JSON.parse(fs.readFileSync(cachePath(), 'utf8'));
95
+ if (parsed.version === 1 && parsed.entries && typeof parsed.entries === 'object') {
96
+ cache = parsed;
97
+ return cache;
98
+ }
99
+ }
100
+ catch {
101
+ // 不存在或损坏都从空缓存开始。
102
+ }
103
+ cache = { version: 1, entries: {} };
104
+ return cache;
105
+ }
106
+ /** 测试用:丢弃内存缓存,下次读取重新走磁盘。 */
107
+ export function resetRequestLimitCache() {
108
+ cache = undefined;
109
+ }
110
+ /** 当前 baseURL 的请求体上限(字节)。显式配置 > 学习值 > 0(不限制)。 */
111
+ export function requestByteLimit(baseURL) {
112
+ const explicit = explicitRequestLimitBytes();
113
+ if (explicit > 0)
114
+ return explicit;
115
+ const entry = readCache().entries[keyOf(baseURL)];
116
+ return entry && Number.isFinite(entry.bytes) && entry.bytes > 0 ? entry.bytes : 0;
117
+ }
118
+ /**
119
+ * 记录一次「字节拒收」:failingBytes 是被拒请求的估算字节数。取历史最小值(只会更保守)。
120
+ * 返回生效的学习值;样本过小(< 64 KiB)不学,返回当前值。
121
+ */
122
+ export function learnRequestByteLimit(baseURL, failingBytes) {
123
+ const store = readCache();
124
+ const key = keyOf(baseURL);
125
+ const previous = store.entries[key]?.bytes;
126
+ if (!Number.isFinite(failingBytes) || failingBytes < MIN_LEARNABLE_BYTES)
127
+ return previous ?? 0;
128
+ const bytes = previous && previous > 0 ? Math.min(previous, Math.round(failingBytes)) : Math.round(failingBytes);
129
+ if (bytes === previous)
130
+ return bytes;
131
+ store.entries[key] = { bytes, updatedAt: Date.now() };
132
+ try {
133
+ const target = cachePath();
134
+ fs.mkdirSync(path.dirname(target), { recursive: true });
135
+ const tmp = `${target}.tmp-${process.pid}`;
136
+ fs.writeFileSync(tmp, JSON.stringify(store), 'utf8');
137
+ fs.renameSync(tmp, target);
138
+ }
139
+ catch {
140
+ // 只影响跨进程复用;当前进程仍用内存值。
141
+ }
142
+ return bytes;
143
+ }
@@ -209,6 +209,228 @@ export function applyVisionWindow(messages, opts) {
209
209
  return noopResult(messages);
210
210
  }
211
211
  }
212
+ /**
213
+ * 上游拒收请求体时,被摘掉的大图所留下的占位行前缀。
214
+ * 兼作「已发生过几次」的无状态计数器(数 history 里有几条占位),用来掐断跨 step 的循环。
215
+ */
216
+ export const OVERSIZED_IMAGE_PLACEHOLDER_PREFIX = '[image removed: upstream rejected the request size';
217
+ /** 默认「大图」阈值:data URL 字符数。约 150 KB 原始字节;小图不动。 */
218
+ export const OVERSIZED_IMAGE_MIN_CHARS = 200_000;
219
+ function imageUrlChars(part) {
220
+ const iu = part.image_url;
221
+ const url = typeof iu === 'string' ? iu : iu && typeof iu === 'object' ? iu.url : undefined;
222
+ return typeof url === 'string' ? url.length : 0;
223
+ }
224
+ /** history 里 data URL 超过阈值的 image_url part 数(只读)。 */
225
+ export function countOversizedImages(messages, minChars = OVERSIZED_IMAGE_MIN_CHARS) {
226
+ let count = 0;
227
+ if (!Array.isArray(messages))
228
+ return 0;
229
+ for (const message of messages) {
230
+ const parts = userContentParts(message);
231
+ if (!parts)
232
+ continue;
233
+ for (const part of parts)
234
+ if (part.type === 'image_url' && imageUrlChars(part) >= minChars)
235
+ count++;
236
+ }
237
+ return count;
238
+ }
239
+ /** history 里已有多少条「大图被摘除」占位(无状态地得知本会话已经历过几次)。 */
240
+ export function countOversizedImagePlaceholders(messages) {
241
+ let count = 0;
242
+ if (!Array.isArray(messages))
243
+ return 0;
244
+ for (const message of messages) {
245
+ const parts = userContentParts(message);
246
+ if (!parts)
247
+ continue;
248
+ for (const part of parts) {
249
+ if (typeof part.text === 'string' && part.text.startsWith(OVERSIZED_IMAGE_PLACEHOLDER_PREFIX))
250
+ count++;
251
+ }
252
+ }
253
+ return count;
254
+ }
255
+ /**
256
+ * 上游因请求体过大拒收时的外科手术:只把**大** image_url part 换成文本占位,其余 part(含附件前言)原样保留。
257
+ * 与摘要压缩的区别:不丢任何对话信息,模型能看到「图被拒了、该降采样后重读」而不是被摘要悄悄吞掉。
258
+ * 纯函数、永不抛错;无改动时返回入参引用。
259
+ */
260
+ export function stripOversizedImages(messages, opts = {}) {
261
+ try {
262
+ if (!Array.isArray(messages))
263
+ return { changed: false, stripped: 0, messages: messages };
264
+ const minChars = opts.minChars ?? OVERSIZED_IMAGE_MIN_CHARS;
265
+ let stripped = 0;
266
+ const next = messages.map((message) => {
267
+ const parts = userContentParts(message);
268
+ if (!parts || !parts.some((p) => p.type === 'image_url' && imageUrlChars(p) >= minChars))
269
+ return message;
270
+ const content = parts.map((part) => {
271
+ if (part.type === 'image_url' && imageUrlChars(part) >= minChars) {
272
+ stripped++;
273
+ return {
274
+ type: 'text',
275
+ text: `${OVERSIZED_IMAGE_PLACEHOLDER_PREFIX} (~${Math.round(imageUrlChars(part) / 1024)} KB inline). ` +
276
+ 'The image was not seen. Shrink or downscale it (e.g. resize to <=1568px long edge) and read it again.]',
277
+ };
278
+ }
279
+ return part;
280
+ });
281
+ return { role: 'user', content };
282
+ });
283
+ if (stripped === 0)
284
+ return { changed: false, stripped: 0, messages: messages };
285
+ return { changed: true, stripped, messages: next };
286
+ }
287
+ catch {
288
+ return { changed: false, stripped: 0, messages: messages };
289
+ }
290
+ }
291
+ /** 总量预算淘汰留下的占位前缀;与 OVERSIZED_IMAGE_PLACEHOLDER_PREFIX 刻意不同,不计入「上游拒收」循环计数。 */
292
+ export const IMAGE_BUDGET_PLACEHOLDER_PREFIX = '[image removed: over the request image budget';
293
+ /**
294
+ * 图片总量预算:history 里**非屏幕帧**图片(read_file 文档图 / screenshot / 用户粘贴图)的 data URL
295
+ * 字符数之和超过 maxChars 时,从最旧的开始换成文本占位,**始终保留最新一张**。
296
+ *
297
+ * 为什么要有:上游代理限的是整个请求体字节数,而图片会随 history 每步重发、只增不减;
298
+ * 每张图单独都合规,攒几张就整体越线。屏幕帧(`computer-`)由 applyVisionWindow 管,这里不碰,
299
+ * 避免改变 Computer Use 既有行为。幂等:淘汰后总量 <= 预算或只剩一张,再调即 no-op。
300
+ * 纯函数、永不抛错;无改动返回入参引用。附件前言原样保留(rollback 靠它区分真实用户轮)。
301
+ */
302
+ export function applyImageBudget(messages, opts) {
303
+ const noop = () => ({ changed: false, evicted: 0, messages: messages });
304
+ try {
305
+ if (!Array.isArray(messages) || !Number.isFinite(opts?.maxChars) || opts.maxChars <= 0)
306
+ return noop();
307
+ const entries = [];
308
+ let total = 0;
309
+ for (let i = 0; i < messages.length; i++) {
310
+ const parts = userContentParts(messages[i]);
311
+ if (!parts || isFrameCarrier(messages[i]))
312
+ continue;
313
+ for (let j = 0; j < parts.length; j++) {
314
+ if (parts[j].type !== 'image_url')
315
+ continue;
316
+ const chars = imageUrlChars(parts[j]);
317
+ entries.push({ msg: i, part: j, chars });
318
+ total += chars;
319
+ }
320
+ }
321
+ if (total <= opts.maxChars || entries.length <= 1)
322
+ return noop();
323
+ const evict = new Set();
324
+ for (let k = 0; k < entries.length - 1 && total > opts.maxChars; k++) {
325
+ evict.add(`${entries[k].msg}:${entries[k].part}`);
326
+ total -= entries[k].chars;
327
+ }
328
+ const sizeOf = new Map(entries.map((e) => [`${e.msg}:${e.part}`, e.chars]));
329
+ const budgetKb = Math.round(opts.maxChars / 1024);
330
+ const next = messages.map((message, i) => {
331
+ const parts = userContentParts(message);
332
+ if (!parts || !parts.some((_, j) => evict.has(`${i}:${j}`)))
333
+ return message;
334
+ const content = parts.map((part, j) => evict.has(`${i}:${j}`)
335
+ ? {
336
+ type: 'text',
337
+ text: `${IMAGE_BUDGET_PLACEHOLDER_PREFIX} (~${Math.round((sizeOf.get(`${i}:${j}`) ?? 0) / 1024)} KB inline; ` +
338
+ (budgetKb >= 1
339
+ ? `older images are dropped to keep the total under ~${budgetKb} KB). `
340
+ : 'older images are dropped to relieve context pressure; only the latest is kept). ') +
341
+ 'Not visible now; read it again with read_file if you still need it.]',
342
+ }
343
+ : part);
344
+ return { role: 'user', content };
345
+ });
346
+ return { changed: true, evicted: evict.size, messages: next };
347
+ }
348
+ catch {
349
+ return noop();
350
+ }
351
+ }
352
+ /** 按轮次淘汰留下的文字卡前缀;与 OVERSIZED/BUDGET 前缀刻意不同,不计入「上游拒收」循环计数。 */
353
+ export const IMAGE_AGED_PLACEHOLDER_PREFIX = '[image aged out: ';
354
+ /**
355
+ * 是否为真实用户轮消息(beginTurn 记入 turns 的那条)。口径同 rollback/store.ts 的 isRealTurnUserMessage:
356
+ * 排除工具附件载体(带 ATTACHMENT_PREAMBLE)与 computer- 帧剪枝后的 `[screenshot omitted: …]` 占位。
357
+ * 不能 import rollback(循环依赖),故本地实现。
358
+ */
359
+ function isRealUserTurnMessage(message) {
360
+ if (!message || message.role !== 'user')
361
+ return false;
362
+ const content = message.content;
363
+ if (typeof content === 'string')
364
+ return !content.startsWith(PRUNED_FRAME_PREFIX);
365
+ if (!Array.isArray(content))
366
+ return false;
367
+ for (const raw of content) {
368
+ if (!raw || typeof raw !== 'object')
369
+ continue;
370
+ const text = raw.text;
371
+ if (typeof text === 'string' && (text.startsWith(ATTACHMENT_PREAMBLE) || text.startsWith(PRUNED_FRAME_PREFIX))) {
372
+ return false;
373
+ }
374
+ }
375
+ return true;
376
+ }
377
+ /**
378
+ * 图片按轮次淘汰:最后一条真实用户消息**之前**的工具附件图(read_file 文档图 / screenshot / browser 等,
379
+ * 即帧名不以 `computer-` 开头的)换成文字卡;当前轮内的图原样保留(模型常多步引用)。
380
+ * 用户自己粘贴的图不动(没有附件前言);屏幕帧由 applyVisionWindow 管。
381
+ * 文字卡写明帧名与体积,提示需要时 read_file 重读。附件前言 text part 原样保留(rollback 靠它区分轮次)。
382
+ * 幂等(淘汰后不再含 image_url);纯函数、永不抛错;无改动返回入参引用。
383
+ */
384
+ export function applyImageTurnAging(messages) {
385
+ const noop = () => ({ changed: false, aged: 0, messages: messages });
386
+ try {
387
+ if (!Array.isArray(messages))
388
+ return noop();
389
+ let lastUser = -1;
390
+ for (let i = messages.length - 1; i >= 0; i--) {
391
+ if (isRealUserTurnMessage(messages[i])) {
392
+ lastUser = i;
393
+ break;
394
+ }
395
+ }
396
+ if (lastUser <= 0)
397
+ return noop();
398
+ let aged = 0;
399
+ const next = messages.map((message, i) => {
400
+ if (i >= lastUser)
401
+ return message;
402
+ const parts = userContentParts(message);
403
+ if (!parts || imagePartCount(parts) === 0)
404
+ return message;
405
+ const names = frameNames(message);
406
+ if (!names)
407
+ return message; // 无附件前言 = 用户粘贴图,不动
408
+ let imageIndex = 0;
409
+ let changed = false;
410
+ const content = parts.map((part) => {
411
+ if (part.type !== 'image_url')
412
+ return part;
413
+ const name = names[imageIndex++];
414
+ if (name !== undefined && VISION_FRAME_NAME_PREFIXES.some((prefix) => name.startsWith(prefix)))
415
+ return part;
416
+ changed = true;
417
+ aged++;
418
+ return {
419
+ type: 'text',
420
+ text: `${IMAGE_AGED_PLACEHOLDER_PREFIX}${name ?? UNKNOWN_FRAME_NAME} (~${Math.round(imageUrlChars(part) / 1024)} KB inline). ` +
421
+ 'It was viewed in an earlier turn and is no longer attached; call read_file on the file again if you need to see it.]',
422
+ };
423
+ });
424
+ return changed ? { role: 'user', content } : message;
425
+ });
426
+ if (aged === 0)
427
+ return noop();
428
+ return { changed: true, aged, messages: next };
429
+ }
430
+ catch {
431
+ return noop();
432
+ }
433
+ }
212
434
  /** 累积一次剪枝结果(由 HistoryManager 调用)。 */
213
435
  export function recordVisionWindowPrune(droppedFrames) {
214
436
  if (!Number.isFinite(droppedFrames) || droppedFrames <= 0)
@@ -225,3 +447,122 @@ export function resetVisionWindowTelemetry() {
225
447
  telemetry.prunes = 0;
226
448
  telemetry.framesDropped = 0;
227
449
  }
450
+ // ───────────────────────── 请求体字节预算:图片 → 文字卡 ─────────────────────────
451
+ //
452
+ // 请求体超过字节线(request-limit.ts)而去掉图片即可达标时,由模型把图描述成文字,
453
+ // 再用「描述 + 文件路径」卡片替换原图;模型需要细节时按路径 read_file 重读。
454
+ /** 描述卡前缀;与 OVERSIZED/BUDGET/AGED 前缀刻意不同,不计入「上游拒收」循环计数。 */
455
+ export const IMAGE_CARD_PREFIX = '[image described: ';
456
+ /** 描述文字的长度上限(字符),防止一张图的描述反过来撑大请求。 */
457
+ export const IMAGE_CARD_MAX_DESCRIPTION_CHARS = 1500;
458
+ function imageUrlOf(part) {
459
+ const iu = part.image_url;
460
+ const url = typeof iu === 'string' ? iu : iu && typeof iu === 'object' ? iu.url : undefined;
461
+ return typeof url === 'string' ? url : '';
462
+ }
463
+ function basenameOf(p) {
464
+ const segs = p.split(/[\\/]/);
465
+ return segs[segs.length - 1] || p;
466
+ }
467
+ /** 在附件消息之前最近的一次 assistant tool_calls 里,按 path 参数的文件名反查原路径。 */
468
+ function findSourcePath(messages, msgIndex, name) {
469
+ for (let i = msgIndex - 1; i >= 0 && i >= msgIndex - 12; i--) {
470
+ const m = messages[i];
471
+ if (m?.role !== 'assistant' || !Array.isArray(m.tool_calls) || m.tool_calls.length === 0)
472
+ continue;
473
+ for (const call of m.tool_calls) {
474
+ try {
475
+ const args = JSON.parse(call?.function?.arguments ?? '');
476
+ if (typeof args?.path === 'string' && basenameOf(args.path) === name)
477
+ return args.path;
478
+ }
479
+ catch {
480
+ // 参数不是合法 JSON:跳过这一条。
481
+ }
482
+ }
483
+ return undefined; // 只看最近的一批
484
+ }
485
+ return undefined;
486
+ }
487
+ /**
488
+ * 列出 history 里可被换成文字卡的图片(按出现顺序,旧在前):非屏幕帧的工具图与用户粘贴图。
489
+ * `computer-` 屏幕帧由 applyVisionWindow 管,这里不碰。纯函数、永不抛错。
490
+ */
491
+ export function listReplaceableImages(messages) {
492
+ const out = [];
493
+ try {
494
+ if (!Array.isArray(messages))
495
+ return out;
496
+ for (let i = 0; i < messages.length; i++) {
497
+ const parts = userContentParts(messages[i]);
498
+ if (!parts || imagePartCount(parts) === 0 || isFrameCarrier(messages[i]))
499
+ continue;
500
+ const names = frameNames(messages[i]);
501
+ let imageIndex = 0;
502
+ for (let j = 0; j < parts.length; j++) {
503
+ if (parts[j].type !== 'image_url')
504
+ continue;
505
+ const name = names ? names[imageIndex] : undefined;
506
+ imageIndex++;
507
+ if (name !== undefined && VISION_FRAME_NAME_PREFIXES.some((prefix) => name.startsWith(prefix)))
508
+ continue;
509
+ const dataUrl = imageUrlOf(parts[j]);
510
+ out.push({
511
+ key: `${i}:${j}`,
512
+ msg: i,
513
+ part: j,
514
+ chars: dataUrl.length,
515
+ dataUrl,
516
+ name,
517
+ path: name !== undefined ? findSourcePath(messages, i, name) : undefined,
518
+ });
519
+ }
520
+ }
521
+ }
522
+ catch {
523
+ // 永不抛错:返回已收集到的部分。
524
+ }
525
+ return out;
526
+ }
527
+ /** 生成替换原图的文字卡。description 为 null 表示描述失败:只留名称与重读提示。 */
528
+ export function buildImageCard(img, description) {
529
+ const kb = Math.round(img.chars / 1024);
530
+ const label = img.name ?? 'pasted image';
531
+ const reread = img.path
532
+ ? `For details, call read_file on "${img.path}" again.`
533
+ : img.name
534
+ ? `For details, call read_file on the file "${img.name}" again.`
535
+ : 'It has no file path and cannot be re-read.';
536
+ const body = description
537
+ ? `Summary: ${description.trim().slice(0, IMAGE_CARD_MAX_DESCRIPTION_CHARS)}`
538
+ : 'No summary is available (the image was not seen).';
539
+ return `${IMAGE_CARD_PREFIX}${label} (~${kb} KB inline, removed to keep the request under the upstream size limit). ${body} ${reread}]`;
540
+ }
541
+ /** 把 cards(key → 卡片文本)对应的 image_url part 换成 text part。幂等;无改动返回入参引用。 */
542
+ export function applyImageCards(messages, cards) {
543
+ const noop = () => ({ changed: false, replaced: 0, messages: messages });
544
+ try {
545
+ if (!Array.isArray(messages) || cards.size === 0)
546
+ return noop();
547
+ let replaced = 0;
548
+ const next = messages.map((message, i) => {
549
+ const parts = userContentParts(message);
550
+ if (!parts || !parts.some((p, j) => p.type === 'image_url' && cards.has(`${i}:${j}`)))
551
+ return message;
552
+ const content = parts.map((part, j) => {
553
+ const card = part.type === 'image_url' ? cards.get(`${i}:${j}`) : undefined;
554
+ if (card === undefined)
555
+ return part;
556
+ replaced++;
557
+ return { type: 'text', text: card };
558
+ });
559
+ return { role: 'user', content };
560
+ });
561
+ if (replaced === 0)
562
+ return noop();
563
+ return { changed: true, replaced, messages: next };
564
+ }
565
+ catch {
566
+ return noop();
567
+ }
568
+ }
package/dist/headless.js CHANGED
@@ -246,6 +246,13 @@ export async function runHeadless(opts) {
246
246
  onModelRetry: (info) => {
247
247
  process.stderr.write(`[retry] model error (${info.code}), retry ${info.nextAttempt} in ${info.waitMs}ms\n`);
248
248
  },
249
+ onImageRelief: (info) => {
250
+ process.stderr.write(info.phase === 'start'
251
+ ? `[images] compressing ${info.images} image(s) to text cards (request ~${Math.round(info.bytes / 1024)} KB)\n`
252
+ : info.replaced > 0
253
+ ? `[images] ${info.replaced} image(s) replaced (${Math.round(info.bytesBefore / 1024)} KB -> ${Math.round(info.bytesAfter / 1024)} KB)\n`
254
+ : '');
255
+ },
249
256
  };
250
257
  const startedAt = Date.now();
251
258
  let exitCode = 0;
@@ -1,4 +1,8 @@
1
+ import { readFileSync } from 'node:fs';
1
2
  import { ui } from '../ui/theme.js';
3
+ import { renderFileChange, renderMultiFileChange } from '../ui/diff.js';
4
+ import { isToolErrorOutput } from '../tools/result.js';
5
+ import { jailResolve } from '../sandbox/index.js';
2
6
  import * as layout from '../ui/layout.js';
3
7
  import * as batch from '../ui/batch.js';
4
8
  import { displayWidth, padEndDisplay, summarizeToolCall, summarizeToolResult } from '../ui/render.js';
@@ -25,6 +29,84 @@ export function formatUserMessage(lines, trailingBlank = true) {
25
29
  })
26
30
  .join('\n') + (trailingBlank ? '\n\n' : '\n'));
27
31
  }
32
+ const toLf = (s) => s.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
33
+ /** 回放用的行号定位:在**当前**文件里找 text 的唯一命中行(edit 已落盘,找新文本);找不到/不唯一退回 1。 */
34
+ function locateLine(filePath, text) {
35
+ if (!text)
36
+ return 1;
37
+ try {
38
+ const data = toLf(readFileSync(jailResolve(filePath), 'utf8'));
39
+ const needle = toLf(text);
40
+ const first = data.indexOf(needle);
41
+ if (first < 0 || data.indexOf(needle, first + needle.length) !== -1)
42
+ return 1;
43
+ return data.slice(0, first).split('\n').length;
44
+ }
45
+ catch {
46
+ return 1;
47
+ }
48
+ }
49
+ /**
50
+ * 由历史里的工具参数重建 edit_file/write_file 的 diff 块(回放时自动展开用)。
51
+ * history 只存参数不存执行前快照,所以是尽力还原:
52
+ * - write_file 无旧内容 → 按 Create 展示全部为新增行;
53
+ * - edit_file 行号在当前文件里按新文本定位,定位不到退回相对行号 1;
54
+ * - 行号区间模式(无 old_string)、失败结果、参数非法 → 返回 null,退回单行摘要。
55
+ */
56
+ export function buildReplayDiff(name, rawArgs, output) {
57
+ if (isToolErrorOutput(output))
58
+ return null;
59
+ let parsed;
60
+ try {
61
+ const v = JSON.parse(rawArgs);
62
+ if (!v || typeof v !== 'object')
63
+ return null;
64
+ parsed = v;
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ const filePath = String(parsed.path ?? '');
70
+ if (!filePath)
71
+ return null;
72
+ if (name === 'write_file') {
73
+ if (typeof parsed.content !== 'string')
74
+ return null;
75
+ return renderFileChange({ path: filePath, kind: 'write', oldStr: null, newStr: parsed.content, startLine: 1 });
76
+ }
77
+ if (name !== 'edit_file')
78
+ return null;
79
+ if (Array.isArray(parsed.replacements) && parsed.replacements.length > 0) {
80
+ const hunks = [];
81
+ for (const item of parsed.replacements) {
82
+ const rec = item;
83
+ if (!rec || typeof rec.old_string !== 'string' || typeof rec.new_string !== 'string')
84
+ return null;
85
+ hunks.push({
86
+ oldStr: rec.old_string,
87
+ newStr: rec.new_string,
88
+ startLine: locateLine(filePath, rec.new_string),
89
+ });
90
+ }
91
+ return (renderMultiFileChange({ path: filePath, hunks }) ??
92
+ renderFileChange({
93
+ path: filePath,
94
+ kind: 'edit',
95
+ oldStr: hunks.map((h) => h.oldStr).join('\n'),
96
+ newStr: hunks.map((h) => h.newStr).join('\n'),
97
+ startLine: hunks[0].startLine,
98
+ }));
99
+ }
100
+ if (typeof parsed.old_string !== 'string' || typeof parsed.new_string !== 'string')
101
+ return null;
102
+ return renderFileChange({
103
+ path: filePath,
104
+ kind: 'edit',
105
+ oldStr: parsed.old_string,
106
+ newStr: parsed.new_string,
107
+ startLine: locateLine(filePath, parsed.new_string),
108
+ });
109
+ }
28
110
  /** 把任意消息 content 拍平成字符串(OpenAI 可能 string / null / 多模态数组)。 */
29
111
  export function textOf(c) {
30
112
  if (typeof c === 'string')
@@ -58,6 +140,7 @@ export function queryHistoryFromMessages(messages) {
58
140
  */
59
141
  export function renderHistory(history) {
60
142
  const idToEntry = new Map();
143
+ const idToArgs = new Map(); // tool_call id → 原始参数 JSON,供重建 mutation diff
61
144
  // 普通工具可跨 assistant 步聚合;mutation 各自占一个 group,并切断前后普通工具。
62
145
  let pendingBatches = [];
63
146
  let normalBatch = null;
@@ -95,6 +178,9 @@ export function renderHistory(history) {
95
178
  }
96
179
  if (m.role === 'user') {
97
180
  flushBatch(); // 上一轮 batch(若有)收尾
181
+ // 上一条 agent 正文 → 本条用户气泡:contentWriteMdOnce 会裁掉 markdown 尾部空行,
182
+ // 不归一的话气泡紧贴正文(实时对话由 REPL 循环顶部的 normalizeInputBoundary 保证恰好 1 条空行)。
183
+ layout.normalizeInputBoundary();
98
184
  const lines = textOf(m.content).split('\n');
99
185
  layout.contentWrite(formatUserMessage(lines));
100
186
  const atts = messageAttachments.get(idx);
@@ -151,8 +237,10 @@ export function renderHistory(history) {
151
237
  }
152
238
  normalBatch.push(entry);
153
239
  }
154
- if (tc?.id)
240
+ if (tc?.id) {
155
241
  idToEntry.set(tc.id, entry);
242
+ idToArgs.set(tc.id, args);
243
+ }
156
244
  }
157
245
  continue; // 跳过后续 tool 消息处理循环(由下一分支填 result)
158
246
  }
@@ -165,9 +253,11 @@ export function renderHistory(history) {
165
253
  const target = idToEntry.get(id);
166
254
  const name = target?.name ?? '';
167
255
  const output = textOf(m.content);
168
- const preview = summarizeToolResult(name, output);
169
256
  if (target) {
170
- target.resultSummary = preview;
257
+ // mutation 成功:重建 diff 块,回放时自动展开(与实时一致);否则退回单行摘要。
258
+ const diff = batch.isMutationToolName(name) ? buildReplayDiff(name, idToArgs.get(id) ?? '', output) : null;
259
+ target.diffBlock = diff;
260
+ target.resultSummary = diff ? '' : summarizeToolResult(name, output);
171
261
  target.fullOutput = output;
172
262
  }
173
263
  // 不直接写屏——等 flushBatch 时出单行摘要