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.
@@ -422,6 +422,21 @@ runtimeOrContext = defaultRuntime) {
422
422
  onModelRetry: (r) => spinner.start(t('agent.retrying', { seconds: Math.max(1, Math.round(r.waitMs / 1000)), attempt: r.attempt })),
423
423
  // 流式实时用量 → 底栏 context 进度条左侧 chip;轮末由 repl 清空。
424
424
  onLiveUsage: (u) => layout.setLiveUsage(u),
425
+ // 请求体字节预算触发的「图片 → 文字卡」:描述请求发出前先亮状态行,否则几十秒静止像卡死;
426
+ // 完成后打一行结果(与「压缩上下文」摘要行区分,不写 tokens)。
427
+ onImageRelief: (info) => {
428
+ const fmt = (n) => n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 1024)} KB`;
429
+ if (info.phase === 'start') {
430
+ spinner.start(`正在压缩图片(${info.images} 张,请求体约 ${fmt(info.bytes)})…`);
431
+ return;
432
+ }
433
+ spinner.stop();
434
+ if (info.replaced <= 0)
435
+ return;
436
+ if (!isLastContentRowBlank())
437
+ layout.contentWrite('\n');
438
+ layout.contentWrite(` ${ui.accent}●${ui.reset} 压缩图片 ${info.replaced} 张转为文字卡(${info.described} 张含描述) 请求体 ${fmt(info.bytesBefore)} → ${fmt(info.bytesAfter)}\n`);
439
+ },
425
440
  onTextEnd: () => {
426
441
  if (lastChar && lastChar !== '\n') {
427
442
  layout.contentWrite('\n');
@@ -1,5 +1,8 @@
1
1
  import { estimatePromptTokens, estimateTokens, isContextLengthError, } from '../llm/index.js';
2
- import { visionBatch, visionKeep } from '../config/index.js';
2
+ import { imageTurnAgingEnabled, visionBatch, visionKeep } from '../config/index.js';
3
+ import { estimateRequestBytes, learnRequestByteLimit, requestByteLimit } from '../context/request-limit.js';
4
+ import { createImageDescriber, relieveRequestBytes } from './request-governor.js';
5
+ import { countOversizedImagePlaceholders, countOversizedImages } from '../context/vision-window.js';
3
6
  import { getActiveSessionStore } from '../session/store.js';
4
7
  import { getCurrentSessionId } from '../session/state.js';
5
8
  import { toUsageRecord } from '../session/usage-stats.js';
@@ -47,6 +50,55 @@ export async function runModelTurn(input) {
47
50
  rebuildHistoryIndexes();
48
51
  onContextUpdate?.();
49
52
  }
53
+ // 图片按轮次淘汰:上一个真实用户轮及更早的工具图换成文字卡,当前轮内保留原图。
54
+ // 先于总量预算跑(预算只兜底「当前轮内」仍然过多的图)。同样要通知 readDedup。
55
+ if (imageTurnAgingEnabled() && historyManager.ageToolImages() > 0) {
56
+ rebuildHistoryIndexes();
57
+ readDedup.markContextChanged();
58
+ onContextUpdate?.();
59
+ }
60
+ // 请求体字节预算(上限来源见 context/request-limit.ts,触发线 = 上限 × 0.8):超线且去图即可达标时,
61
+ // 让模型把图描述成文字卡替换原图(卡片带路径,可 read_file 重读)。同样必须在 trim 之前;
62
+ // 被换掉的图要通知 readDedup,否则模型重读同一路径会被去重提示挡回。
63
+ const byteLimit = requestByteLimit(requestBaseURL);
64
+ if (byteLimit > 0) {
65
+ let reliefAnnounced = false;
66
+ const relief = await relieveRequestBytes({
67
+ historyManager,
68
+ tools: activeTools,
69
+ limitBytes: byteLimit,
70
+ extraBytes: sessionStateText ? Buffer.byteLength(sessionStateText, 'utf8') : 0,
71
+ signal,
72
+ describe: createImageDescriber(modelRunner),
73
+ onStart: (info) => {
74
+ reliefAnnounced = true;
75
+ hooks.onImageRelief?.({ phase: 'start', ...info });
76
+ },
77
+ });
78
+ if (reliefAnnounced) {
79
+ hooks.onImageRelief?.({
80
+ phase: 'done',
81
+ replaced: relief.replaced,
82
+ described: relief.described,
83
+ bytesBefore: relief.bytesBefore,
84
+ bytesAfter: relief.bytesAfter,
85
+ });
86
+ }
87
+ if (relief.replaced > 0) {
88
+ emitTrace('compact', {
89
+ source: 'request_bytes',
90
+ reason: 'describe_images',
91
+ compacted: false,
92
+ replaced: relief.replaced,
93
+ described: relief.described,
94
+ estimateBefore: relief.bytesBefore,
95
+ estimateAfter: relief.bytesAfter,
96
+ });
97
+ rebuildHistoryIndexes();
98
+ readDedup.markContextChanged();
99
+ onContextUpdate?.();
100
+ }
101
+ }
50
102
  const compactStartedAt = Date.now();
51
103
  const trimResult = await contextTrimmer.trim({
52
104
  mode: scheduler ? 'scheduled' : 'fallback',
@@ -204,41 +256,178 @@ export async function runModelTurn(input) {
204
256
  turnLifecycle.markAborted();
205
257
  return { kind: 'aborted', result: turnLifecycle.buildAbortedResult() };
206
258
  }
259
+ // 字节拒收的学习 + 描述重试:token 估算远低于窗口却被判超长 → 上游限的是请求体字节数。
260
+ // 记下这次失败请求的字节数作为上限(取历史最小值),再按 0.8 线把图描述成文字卡后重试一次。
261
+ let byteResult;
207
262
  if (!overflowRetried && isContextLengthError(error)) {
208
- overflowRetried = true;
209
- const rawEstimate = estimatePromptTokens(requestHistory, activeTools);
210
- if (rawEstimate > 1_000) {
211
- const calibration = ctx.updateTokenCalibration(requestBaseURL, requestModel, activeTools, rawEstimate, ctx.config.contextWindowTokens);
212
- runtimeContextState.correction = calibration.correction;
213
- runtimeContextState.calibrationSamples = calibration.samples;
263
+ const winTokens = ctx.config.contextWindowTokens;
264
+ const tokenEst = estimatePromptTokens(requestHistory, activeTools);
265
+ if (!(winTokens > 0 && tokenEst >= winTokens * 0.5)) {
266
+ const failingBytes = estimateRequestBytes(requestHistory, activeTools);
267
+ const learned = learnRequestByteLimit(requestBaseURL, failingBytes);
268
+ let reliefAnnounced = false;
269
+ const relief = await relieveRequestBytes({
270
+ historyManager,
271
+ tools: activeTools,
272
+ limitBytes: learned,
273
+ extraBytes: requestHistory.length > history.length ? failingBytes - estimateRequestBytes(history, activeTools) : 0,
274
+ signal,
275
+ describe: createImageDescriber(modelRunner),
276
+ onStart: (info) => {
277
+ reliefAnnounced = true;
278
+ hooks.onImageRelief?.({ phase: 'start', ...info });
279
+ },
280
+ });
281
+ if (reliefAnnounced) {
282
+ hooks.onImageRelief?.({
283
+ phase: 'done',
284
+ replaced: relief.replaced,
285
+ described: relief.described,
286
+ bytesBefore: relief.bytesBefore,
287
+ bytesAfter: relief.bytesAfter,
288
+ });
289
+ }
290
+ emitTrace('compact', {
291
+ source: 'overflow_retry',
292
+ reason: 'request_bytes',
293
+ compacted: false,
294
+ limit: learned,
295
+ relief: relief.reason,
296
+ replaced: relief.replaced,
297
+ described: relief.described,
298
+ estimateBefore: failingBytes,
299
+ durationMs: Date.now() - modelStartedAt,
300
+ });
301
+ if (relief.replaced > 0) {
302
+ rebuildHistoryIndexes();
303
+ readDedup.markContextChanged();
304
+ requestHistory = buildRequestHistory();
305
+ stepPromptEst = estimatePromptTokens(requestHistory, activeTools, runtimeContextState.correction);
306
+ try {
307
+ byteResult = await runChatOnce();
308
+ }
309
+ catch (retryError) {
310
+ // 去图后仍被判超长:说明还有文本压力,回落到下面的摘要路径(图已换成卡片)。
311
+ if (signal?.aborted || !isContextLengthError(retryError))
312
+ throw retryError;
313
+ }
314
+ }
214
315
  }
215
- const overflowResult = await contextTrimmer.trim({
216
- mode: 'overflow',
217
- history: historyManager.snapshot(),
218
- step,
219
- tools: activeTools,
220
- ephemeralTokens: sessionStateText ? estimateTokens(sessionStateText) : 0,
221
- signal,
222
- });
223
- const overflowStats = overflowResult.kind === 'aborted' ? {} : overflowResult.stats;
316
+ }
317
+ // 上游按请求体字节数拒收(而非 token):本地估算远低于窗口、history 里却有大图 → 病因是图,
318
+ // 摘要压缩救不了(摘要只会把图剥掉,模型没看过图又会重读,形成「读图→400→压缩」死循环)。
319
+ // 已经摘过 >=2 次仍被拒,直接抛错,不再循环。
320
+ const oversizedImages = !byteResult && !overflowRetried && isContextLengthError(error) ? countOversizedImages(history) : 0;
321
+ if (oversizedImages > 0 && countOversizedImagePlaceholders(history) >= 2)
322
+ throw error;
323
+ const overflowLocalEstimate = oversizedImages > 0 ? estimatePromptTokens(requestHistory, activeTools) : 0;
324
+ const overflowWindow = ctx.config.contextWindowTokens;
325
+ if (byteResult) {
326
+ // 已由上面的字节预算路径重试成功。
327
+ overflowRetried = true;
328
+ result = byteResult;
329
+ }
330
+ else if (oversizedImages > 0 && !(overflowWindow > 0 && overflowLocalEstimate >= overflowWindow * 0.5)) {
331
+ overflowRetried = true;
332
+ const stripped = historyManager.stripOversizedImages();
224
333
  emitTrace('compact', {
225
334
  source: 'overflow_retry',
226
- reason: overflowStats.reason ?? 'noop',
227
- compacted: overflowStats.compacted === true,
228
- estimateBefore: overflowStats.estimateBefore,
229
- estimateAfter: overflowStats.estimateAfter,
335
+ reason: 'strip_oversized_images',
336
+ compacted: false,
337
+ stripped,
338
+ estimateBefore: overflowLocalEstimate,
230
339
  durationMs: Date.now() - modelStartedAt,
231
340
  });
232
- if (overflowResult.kind === 'none' || overflowResult.kind === 'aborted')
341
+ if (stripped === 0)
233
342
  throw error;
234
- if (overflowResult.kind === 'rebuild') {
235
- historyRebuilt = true;
236
- rebuildHistoryIndexes();
237
- }
343
+ rebuildHistoryIndexes();
344
+ readDedup.markContextChanged();
238
345
  requestHistory = buildRequestHistory();
239
346
  stepPromptEst = estimatePromptTokens(requestHistory, activeTools, runtimeContextState.correction);
240
347
  result = await runChatOnce();
241
348
  }
349
+ else if (!overflowRetried && isContextLengthError(error)) {
350
+ overflowRetried = true;
351
+ // 第一道:摘要既压不掉保留区里的图,又白花一次 LLM 调用。先把除最新一张外的非屏幕帧图
352
+ // 换成文字卡,直接重试;只有「去图后仍被判超长」才说明是文本本身的问题,再走摘要。
353
+ let reliefResult;
354
+ const relieved = historyManager.enforceImageBudget({ maxChars: 1 });
355
+ if (relieved > 0) {
356
+ emitTrace('compact', {
357
+ source: 'overflow_retry',
358
+ reason: 'relieve_images',
359
+ compacted: false,
360
+ stripped: relieved,
361
+ durationMs: Date.now() - modelStartedAt,
362
+ });
363
+ rebuildHistoryIndexes();
364
+ readDedup.markContextChanged();
365
+ requestHistory = buildRequestHistory();
366
+ stepPromptEst = estimatePromptTokens(requestHistory, activeTools, runtimeContextState.correction);
367
+ try {
368
+ reliefResult = await runChatOnce();
369
+ }
370
+ catch (retryError) {
371
+ if (signal?.aborted || !isContextLengthError(retryError))
372
+ throw retryError;
373
+ }
374
+ }
375
+ if (reliefResult) {
376
+ result = reliefResult;
377
+ }
378
+ else {
379
+ // 跨 step 断路器:runModelTurn 的 overflowRetried 每 step 重置,挡不住「每步 400 → 每步摘要」。
380
+ // 同一用户轮(turnId)内摘要过一次仍被拒,说明摘要救不了,直接抛错,不再循环。
381
+ const breakerTurnId = turnLifecycle.traceTurnId;
382
+ if (breakerTurnId !== undefined) {
383
+ const prior = runtimeContextState.overflowCompaction;
384
+ const count = prior && prior.turnId === breakerTurnId ? prior.count : 0;
385
+ if (count >= 1) {
386
+ emitTrace('compact', {
387
+ source: 'overflow_retry',
388
+ reason: 'breaker_open',
389
+ compacted: false,
390
+ priorCompactions: count,
391
+ durationMs: Date.now() - modelStartedAt,
392
+ });
393
+ throw error;
394
+ }
395
+ runtimeContextState.overflowCompaction = { turnId: breakerTurnId, count: count + 1 };
396
+ }
397
+ const rawEstimate = estimatePromptTokens(requestHistory, activeTools);
398
+ if (rawEstimate > 1_000) {
399
+ const calibration = ctx.updateTokenCalibration(requestBaseURL, requestModel, activeTools, rawEstimate, ctx.config.contextWindowTokens);
400
+ runtimeContextState.correction = calibration.correction;
401
+ runtimeContextState.calibrationSamples = calibration.samples;
402
+ }
403
+ const overflowResult = await contextTrimmer.trim({
404
+ mode: 'overflow',
405
+ history: historyManager.snapshot(),
406
+ step,
407
+ tools: activeTools,
408
+ ephemeralTokens: sessionStateText ? estimateTokens(sessionStateText) : 0,
409
+ signal,
410
+ });
411
+ const overflowStats = overflowResult.kind === 'aborted' ? {} : overflowResult.stats;
412
+ emitTrace('compact', {
413
+ source: 'overflow_retry',
414
+ reason: overflowStats.reason ?? 'noop',
415
+ compacted: overflowStats.compacted === true,
416
+ estimateBefore: overflowStats.estimateBefore,
417
+ estimateAfter: overflowStats.estimateAfter,
418
+ durationMs: Date.now() - modelStartedAt,
419
+ });
420
+ if (overflowResult.kind === 'none' || overflowResult.kind === 'aborted')
421
+ throw error;
422
+ if (overflowResult.kind === 'rebuild') {
423
+ historyRebuilt = true;
424
+ rebuildHistoryIndexes();
425
+ }
426
+ requestHistory = buildRequestHistory();
427
+ stepPromptEst = estimatePromptTokens(requestHistory, activeTools, runtimeContextState.correction);
428
+ result = await runChatOnce();
429
+ }
430
+ }
242
431
  else {
243
432
  throw error;
244
433
  }
@@ -0,0 +1,128 @@
1
+ // 请求体字节预算的执行层(口径与上限来源见 context/request-limit.ts)。
2
+ //
3
+ // 请求体估算字节数超过「上限 × 0.8」时:
4
+ // 1. 若把图片去掉仍超线 → 病因是文本,本层不动,交给原有的摘要压缩;
5
+ // 2. 否则从最旧的图开始挑,挑到剩余字节落回线下为止;
6
+ // 3. 逐张让模型把图描述成文字(只带这一张图的小请求),描述 + 文件路径写成文字卡替换原图;
7
+ // 模型需要细节时按卡片里的路径 read_file 重读。描述失败降级为「未看过 + 重读提示」。
8
+ import { buildImageCard, listReplaceableImages } from '../context/vision-window.js';
9
+ import { estimateRequestBytes, REQUEST_BYTES_TRIGGER_RATIO } from '../context/request-limit.js';
10
+ /** 一次最多让模型描述几张;其余的只留名称 + 重读提示,防止描述调用本身拖慢一步。 */
11
+ export const MAX_DESCRIBED_IMAGES = 4;
12
+ /** 单张图描述请求的超时。 */
13
+ const DESCRIBE_TIMEOUT_MS = 60_000;
14
+ /** 文字卡替换后每张图大约占的字节数(用于规划时的余量估算)。 */
15
+ const CARD_BYTES_ESTIMATE = 700;
16
+ /** 每个 image_url part 在请求体里除 data URL 之外的结构开销(与 estimateRequestBytes 一致)。 */
17
+ const IMAGE_PART_OVERHEAD = 40;
18
+ /**
19
+ * 纯函数:决定要不要动图、动哪几张。
20
+ * 先判「去掉全部可换的图是否能达标」—— 不能就是文本问题(text_dominant),一张都不动;
21
+ * 能就从最旧的开始挑,挑到够为止(尽量少丢图,保留最新的)。
22
+ */
23
+ export function planImageRelief(images, totalBytes, limitBytes) {
24
+ const target = limitBytes * REQUEST_BYTES_TRIGGER_RATIO;
25
+ if (!(limitBytes > 0) || totalBytes <= target)
26
+ return { kind: 'under_limit' };
27
+ if (images.length === 0)
28
+ return { kind: 'no_images' };
29
+ const cost = (img) => img.chars + IMAGE_PART_OVERHEAD - CARD_BYTES_ESTIMATE;
30
+ const all = images.reduce((sum, img) => sum + cost(img), 0);
31
+ if (totalBytes - all > target)
32
+ return { kind: 'text_dominant' };
33
+ const picked = [];
34
+ let remaining = totalBytes;
35
+ for (const img of images) {
36
+ if (remaining <= target)
37
+ break;
38
+ picked.push(img);
39
+ remaining -= cost(img);
40
+ }
41
+ return { kind: 'replace', images: picked, bytesAfter: Math.max(0, Math.round(remaining)) };
42
+ }
43
+ const DESCRIBE_PROMPT = 'You are helping a coding agent that will NOT see this image again. Describe it so the agent can keep working without it: ' +
44
+ 'transcribe all visible text verbatim (error messages, code, numbers, labels), then summarize layout, UI state and anything ' +
45
+ 'notable for debugging. Be factual and concise (under 250 words). Do not add advice.';
46
+ /** 用当前模型描述一张图(独立小请求,不带工具、不写回 history)。任何失败返回 null。 */
47
+ export function createImageDescriber(modelRunner) {
48
+ return async (img, signal) => {
49
+ const controller = new AbortController();
50
+ const onAbort = () => controller.abort();
51
+ if (signal?.aborted)
52
+ return null;
53
+ signal?.addEventListener('abort', onAbort, { once: true });
54
+ const timer = setTimeout(() => controller.abort(), DESCRIBE_TIMEOUT_MS);
55
+ try {
56
+ const result = await modelRunner.run({
57
+ history: [
58
+ {
59
+ role: 'user',
60
+ content: [
61
+ { type: 'text', text: DESCRIBE_PROMPT },
62
+ { type: 'image_url', image_url: { url: img.dataUrl } },
63
+ ],
64
+ },
65
+ ],
66
+ tools: [],
67
+ handlers: {},
68
+ reasoningEffort: 'low',
69
+ }, controller.signal);
70
+ const text = result.content?.trim();
71
+ return text ? text : null;
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ finally {
77
+ clearTimeout(timer);
78
+ signal?.removeEventListener('abort', onAbort);
79
+ }
80
+ };
81
+ }
82
+ /** 请求体超线且去图可达标时,把图描述成文字卡替换。返回换掉的张数(0 = 未改动)。 */
83
+ export async function relieveRequestBytes(input) {
84
+ const { historyManager, tools, limitBytes, signal, describe } = input;
85
+ const messages = historyManager.snapshot().messages;
86
+ const bytesBefore = estimateRequestBytes(messages, tools) + (input.extraBytes ?? 0);
87
+ const idle = (reason) => ({
88
+ reason,
89
+ replaced: 0,
90
+ described: 0,
91
+ bytesBefore,
92
+ bytesAfter: bytesBefore,
93
+ });
94
+ if (!(limitBytes > 0))
95
+ return idle('no_limit');
96
+ const plan = planImageRelief(listReplaceableImages(messages), bytesBefore, limitBytes);
97
+ if (plan.kind !== 'replace')
98
+ return idle(plan.kind);
99
+ try {
100
+ input.onStart?.({ images: plan.images.length, bytes: bytesBefore });
101
+ }
102
+ catch {
103
+ // 展示回调不能影响主流程。
104
+ }
105
+ // 逐张描述(串行:并发会瞬间多打几个带大图的请求,上游反而更容易拒)。
106
+ const cards = new Map();
107
+ let described = 0;
108
+ for (let i = 0; i < plan.images.length; i++) {
109
+ const img = plan.images[i];
110
+ let description = null;
111
+ if (i < MAX_DESCRIBED_IMAGES && !signal?.aborted) {
112
+ description = await describe(img, signal);
113
+ if (description)
114
+ described++;
115
+ }
116
+ cards.set(img.key, buildImageCard(img, description));
117
+ }
118
+ if (signal?.aborted)
119
+ return idle('replaced');
120
+ const replaced = historyManager.replaceImagesWithCards(cards);
121
+ return {
122
+ reason: 'replaced',
123
+ replaced,
124
+ described,
125
+ bytesBefore,
126
+ bytesAfter: plan.bytesAfter,
127
+ };
128
+ }
@@ -1,4 +1,4 @@
1
- import { applyVisionWindow, recordVisionWindowPrune } from '../../context/vision-window.js';
1
+ import { applyImageBudget, applyImageCards, applyImageTurnAging, applyVisionWindow, recordVisionWindowPrune, stripOversizedImages, } from '../../context/vision-window.js';
2
2
  function replaceMessages(backing, messages) {
3
3
  const replacement = messages.slice();
4
4
  backing.length = 0;
@@ -171,6 +171,42 @@ class DefaultHistoryManager {
171
171
  this.revision++;
172
172
  return true;
173
173
  }
174
+ stripOversizedImages() {
175
+ this.assertNoActiveBatch('strip oversized images');
176
+ const result = stripOversizedImages(this.backing);
177
+ if (!result.changed)
178
+ return 0;
179
+ replaceMessages(this.backing, result.messages);
180
+ this.revision++;
181
+ return result.stripped;
182
+ }
183
+ ageToolImages() {
184
+ this.assertNoActiveBatch('age tool images');
185
+ const result = applyImageTurnAging(this.backing);
186
+ if (!result.changed)
187
+ return 0;
188
+ replaceMessages(this.backing, result.messages);
189
+ this.revision++;
190
+ return result.aged;
191
+ }
192
+ replaceImagesWithCards(cards) {
193
+ this.assertNoActiveBatch('replace images with cards');
194
+ const result = applyImageCards(this.backing, cards);
195
+ if (!result.changed)
196
+ return 0;
197
+ replaceMessages(this.backing, result.messages);
198
+ this.revision++;
199
+ return result.replaced;
200
+ }
201
+ enforceImageBudget(opts) {
202
+ this.assertNoActiveBatch('enforce image budget');
203
+ const result = applyImageBudget(this.backing, opts);
204
+ if (!result.changed)
205
+ return 0;
206
+ replaceMessages(this.backing, result.messages);
207
+ this.revision++;
208
+ return result.evicted;
209
+ }
174
210
  createCheckpoint() {
175
211
  return { revision: this.revision, messages: this.backing.slice() };
176
212
  }
@@ -72,36 +72,40 @@ export const DOWNSCALE_MAX_EDGE = 1568;
72
72
  * **8-bit RGB/RGBA PNG**(项目刻意零原生图像依赖)。所以兜底只覆盖 PNG;
73
73
  * JPEG/WebP/GIF 超限仍然拒绝,reason 会写明这一点。
74
74
  */
75
- export async function loadImageAttachmentWithDownscale(input, opts) {
76
- const loaded = await loadImageAttachment(input, opts);
77
- if (loaded.ok)
78
- return loaded;
79
- // 只有「体积超限」这一种失败值得兜底:路径为空/扩展名不支持/沙箱越界/不是普通文件
80
- // 都是真错误,缩图解决不了,原样透出让调用方给出准确提示。
81
- if (!loaded.reason.startsWith('too large'))
82
- return loaded;
83
- const mime = detectMime(input) ?? opts.sniffedMime ?? null;
84
- if (mime !== 'image/png') {
85
- return {
86
- ok: false,
87
- reason: `${loaded.reason} — 自动降采样仅支持 PNG(零原生图像依赖);${extname(input)} 请先转成 PNG 或自行压缩后重试`,
88
- };
89
- }
90
- let abs;
91
- try {
92
- abs = jailResolve(input.trim());
93
- }
94
- catch (e) {
95
- return { ok: false, reason: `outside sandbox: ${e instanceof Error ? e.message : String(e)}` };
96
- }
75
+ /**
76
+ * PNG 内联体积软预算(原始字节;base64 后约 ×1.33)。
77
+ *
78
+ * 为什么不只看 4 MiB 硬上限:上游代理对**整个请求体字节数**另有上限(本机 Kiro-Go 的
79
+ * maxPayloadBytes = 900 KiB,见其 proxy/translator.go;超限先丢旧历史,丢超 2 轮就回
80
+ * 400 "Request history exceeds the upstream payload limit"),而本地 token 估算按像素面积算,
81
+ * 看不出请求体已超 —— 结果是被误判成上下文超长,反复摘要压缩、模型始终看不到图。
82
+ *
83
+ * 360 KiB 原始字节 ≈ 480 KiB base64,给文本历史/工具 schema 留出约 400 KiB。
84
+ * 超预算的 PNG 先降到 DOWNSCALE_MAX_EDGE,仍超预算就沿 DOWNSCALE_FALLBACK_EDGES 逐级再缩
85
+ * (噪声多的截图在 1568 边长下仍可能 >1 MiB),直到装进预算或缩到最小一档。
86
+ * history 里所有非屏幕帧图片的总量另由 vision-window.applyImageBudget 兜底。
87
+ */
88
+ export const INLINE_PNG_BUDGET_BYTES = 360 * 1024;
89
+ /** 1568 仍超预算时依次尝试的更小长边。 */
90
+ const DOWNSCALE_FALLBACK_EDGES = [1280, 1024, 768, 512];
91
+ /** 读 PNG → 长边缩到 DOWNSCALE_MAX_EDGE → 重编码为内联附件。`failPrefix` 拼在失败原因前。 */
92
+ async function downscalePngFile(abs, maxBytes, failPrefix, budgetBytes) {
97
93
  try {
98
94
  const png = decodePng(await readFile(abs));
99
- const { img } = downscale(png, DOWNSCALE_MAX_EDGE);
100
- const buf = encodePng(img);
101
- if (buf.length > opts.maxBytes) {
95
+ let img = downscale(png, DOWNSCALE_MAX_EDGE).img;
96
+ let buf = encodePng(img);
97
+ for (const edge of DOWNSCALE_FALLBACK_EDGES) {
98
+ if (buf.length <= budgetBytes)
99
+ break;
100
+ if (edge >= Math.max(img.width, img.height))
101
+ continue;
102
+ img = downscale(png, edge).img;
103
+ buf = encodePng(img);
104
+ }
105
+ if (buf.length > maxBytes) {
102
106
  return {
103
107
  ok: false,
104
- reason: `${loaded.reason} — 降采样到 ${img.width}×${img.height} 后仍有 ${formatBytes(buf.length)},超过 ${formatBytes(opts.maxBytes)}`,
108
+ reason: `${failPrefix} — 降采样到 ${img.width}×${img.height} 后仍有 ${formatBytes(buf.length)},超过 ${formatBytes(maxBytes)}`,
105
109
  };
106
110
  }
107
111
  let st;
@@ -135,8 +139,40 @@ export async function loadImageAttachmentWithDownscale(input, opts) {
135
139
  }
136
140
  catch (error) {
137
141
  const message = error instanceof Error ? error.message : String(error);
138
- return { ok: false, reason: `${loaded.reason}(降采样兜底失败: ${message})` };
142
+ return { ok: false, reason: `${failPrefix}(降采样兜底失败: ${message})` };
143
+ }
144
+ }
145
+ export async function loadImageAttachmentWithDownscale(input, opts) {
146
+ const loaded = await loadImageAttachment(input, opts);
147
+ if (loaded.ok) {
148
+ // 软预算:未超限但体积偏大的 PNG 也缩一次;缩失败 / 缩了反而更大(已 ≤ 1568 的图)就原样发。
149
+ const budget = opts.budgetBytes ?? INLINE_PNG_BUDGET_BYTES;
150
+ if (loaded.att.mime !== 'image/png' || loaded.att.bytes <= budget)
151
+ return loaded;
152
+ const shrunk = await downscalePngFile(loaded.att.path, opts.maxBytes, '', budget);
153
+ if (shrunk.ok && shrunk.att.bytes < loaded.att.bytes)
154
+ return shrunk;
155
+ return loaded;
156
+ }
157
+ // 只有「体积超限」这一种失败值得兜底:路径为空/扩展名不支持/沙箱越界/不是普通文件
158
+ // 都是真错误,缩图解决不了,原样透出让调用方给出准确提示。
159
+ if (!loaded.reason.startsWith('too large'))
160
+ return loaded;
161
+ const mime = detectMime(input) ?? opts.sniffedMime ?? null;
162
+ if (mime !== 'image/png') {
163
+ return {
164
+ ok: false,
165
+ reason: `${loaded.reason} — 自动降采样仅支持 PNG(零原生图像依赖);${extname(input)} 请先转成 PNG 或自行压缩后重试`,
166
+ };
167
+ }
168
+ let abs;
169
+ try {
170
+ abs = jailResolve(input.trim());
171
+ }
172
+ catch (e) {
173
+ return { ok: false, reason: `outside sandbox: ${e instanceof Error ? e.message : String(e)}` };
139
174
  }
175
+ return downscalePngFile(abs, opts.maxBytes, loaded.reason, opts.budgetBytes ?? INLINE_PNG_BUDGET_BYTES);
140
176
  }
141
177
  export async function loadImageAttachment(input, opts) {
142
178
  const trimmed = input.trim();
@@ -860,6 +860,16 @@ export function visionBatch() {
860
860
  return DEFAULT_VISION_BATCH;
861
861
  return Math.round(parsed);
862
862
  }
863
+ /**
864
+ * 图片按轮次淘汰开关:下一个真实用户轮开始时,上一轮工具图(非 computer- 帧)换成文字卡。
865
+ * **默认开**;显式 0 / false / off 关闭。env: MOCODE_IMAGE_AGE_TURNS。
866
+ */
867
+ export function imageTurnAgingEnabled() {
868
+ const raw = process.env.MOCODE_IMAGE_AGE_TURNS?.trim().toLowerCase();
869
+ if (raw === undefined || raw === '')
870
+ return true;
871
+ return !(raw === '0' || raw === 'false' || raw === 'off' || raw === 'no');
872
+ }
863
873
  /** MCP 总开关;关闭时下次启动跳过 MCP 配置读取与服务连接。 */
864
874
  export function isMcpEnabled() {
865
875
  return config.mcpEnabled;