mocode-ai 1.8.5 → 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.
- package/dist/agent/index.js +15 -0
- package/dist/agent/model-turn.js +214 -25
- package/dist/agent/request-governor.js +128 -0
- package/dist/agent/stages/history-manager.js +37 -1
- package/dist/attachments/image.js +63 -27
- package/dist/config/index.js +10 -0
- package/dist/context/request-limit.js +143 -0
- package/dist/context/vision-window.js +341 -0
- package/dist/headless.js +7 -0
- package/dist/session/scheduler.js +20 -3
- package/package.json +1 -1
package/dist/agent/index.js
CHANGED
|
@@ -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');
|
package/dist/agent/model-turn.js
CHANGED
|
@@ -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
|
-
|
|
209
|
-
const
|
|
210
|
-
if (
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
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
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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:
|
|
227
|
-
compacted:
|
|
228
|
-
|
|
229
|
-
|
|
335
|
+
reason: 'strip_oversized_images',
|
|
336
|
+
compacted: false,
|
|
337
|
+
stripped,
|
|
338
|
+
estimateBefore: overflowLocalEstimate,
|
|
230
339
|
durationMs: Date.now() - modelStartedAt,
|
|
231
340
|
});
|
|
232
|
-
if (
|
|
341
|
+
if (stripped === 0)
|
|
233
342
|
throw error;
|
|
234
|
-
|
|
235
|
-
|
|
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
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
100
|
-
|
|
101
|
-
|
|
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: `${
|
|
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: `${
|
|
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();
|
package/dist/config/index.js
CHANGED
|
@@ -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;
|
|
@@ -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;
|
|
@@ -7,6 +7,7 @@ import { pruneStaleArtifacts, refreshArtifactFreshness } from '../context/artifa
|
|
|
7
7
|
import { pruneSuperseded } from '../context/relevance.js';
|
|
8
8
|
import { clearRetrievableResults } from '../context/clearing.js';
|
|
9
9
|
import { createAgeAwareEncodingState } from '../context/age-aware.js';
|
|
10
|
+
import { applyImageBudget } from '../context/vision-window.js';
|
|
10
11
|
function emptyPressure(report) {
|
|
11
12
|
return {
|
|
12
13
|
triggered: false,
|
|
@@ -27,10 +28,25 @@ export function createBudgetScheduler(state = contextState, runtime = defaultCom
|
|
|
27
28
|
async runStep(history, step, activeTools = chatTools, ephemeralTokens = 0, signal) {
|
|
28
29
|
// External file changes and mutations only update artifact metadata here.
|
|
29
30
|
refreshArtifactFreshness(state, history);
|
|
30
|
-
|
|
31
|
+
let report = evaluate(history, step, activeTools, ephemeralTokens);
|
|
32
|
+
const pressureLine = report.window * DEFAULT_BUDGET_POLICY.pressureTriggerRatio;
|
|
33
|
+
// 图片先行:压力线触发时先剥图(只留最新一张非屏幕帧图)再重估。图按像素计 token、又会随
|
|
34
|
+
// history 每步重发,但摘要只对旧区剥图、保留区的图原样留着 —— 为图压缩既压不掉图又白花一次
|
|
35
|
+
// LLM 调用。剥完低于线就根本不摘要;仍高于线说明文本本身超了,此时摘要才有意义。
|
|
36
|
+
// 屏幕帧(computer-)由 vision-window 管,这里不碰。
|
|
37
|
+
let imagesRelieved = 0;
|
|
38
|
+
if (Math.max(report.rawTotal, report.total) >= pressureLine) {
|
|
39
|
+
const relief = applyImageBudget(history, { maxChars: 1 });
|
|
40
|
+
if (relief.changed) {
|
|
41
|
+
history.splice(0, history.length, ...relief.messages);
|
|
42
|
+
imagesRelieved = relief.evicted;
|
|
43
|
+
report = evaluate(history, step, activeTools, ephemeralTokens);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
31
46
|
const pressure = emptyPressure(report);
|
|
47
|
+
pressure.imagesRelieved = imagesRelieved;
|
|
32
48
|
const occupancy = Math.max(report.rawTotal, report.total);
|
|
33
|
-
pressure.triggered = occupancy >=
|
|
49
|
+
pressure.triggered = occupancy >= pressureLine;
|
|
34
50
|
pressure.lowTriggered = !pressure.triggered && occupancy >= report.window * runtime.config.lowPressureRatio;
|
|
35
51
|
if (pressure.triggered) {
|
|
36
52
|
// A single 80% pressure event owns every history rewrite. Run all enabled
|
|
@@ -70,7 +86,8 @@ export function createBudgetScheduler(state = contextState, runtime = defaultCom
|
|
|
70
86
|
const actions = pressure.triggered ? scheduleActions(report) : [];
|
|
71
87
|
let compactHistoryCalled = false;
|
|
72
88
|
let historyRebuilt = false;
|
|
73
|
-
let contentMutated =
|
|
89
|
+
let contentMutated = imagesRelieved > 0 ||
|
|
90
|
+
pressure.superseded > 0 ||
|
|
74
91
|
pressure.staleArtifacts > 0 ||
|
|
75
92
|
pressure.encodedLogsAndSearches > 0 ||
|
|
76
93
|
pressure.cleared > 0;
|