billion-context 0.1.87-pr.591.413 → 0.1.88-pr.558.418

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/index.js CHANGED
@@ -51107,6 +51107,7 @@ var CHUNK_FRACTION = 0.6;
51107
51107
  var MIN_CHUNK_TOKENS = 2e3;
51108
51108
  var MIN_SUMMARY_CHARS = 50;
51109
51109
  var MAX_SUMMARY_OUTPUT_TOKENS = 8192;
51110
+ var MAX_SUMMARY_CALLS_PER_PREFLIGHT = 8;
51110
51111
  function refMaps(messages, state) {
51111
51112
  const refToIdx = /* @__PURE__ */ new Map();
51112
51113
  const idxToRef = /* @__PURE__ */ new Map();
@@ -51146,6 +51147,11 @@ function estimateRawBodyTokens(parsed) {
51146
51147
  walk(parsed);
51147
51148
  return tokens;
51148
51149
  }
51150
+ function estimateCoreMessagesUpper(messages) {
51151
+ let chars = 0;
51152
+ for (const m2 of messages) chars += (m2.text ?? "").length;
51153
+ return chars;
51154
+ }
51149
51155
  function rangeChars2(messages, startIdx, endIdx) {
51150
51156
  let chars = 0;
51151
51157
  for (let i = startIdx; i <= endIdx && i < messages.length; i++) {
@@ -51165,16 +51171,16 @@ ${text}`);
51165
51171
  }
51166
51172
  return parts.join("\n\n");
51167
51173
  }
51168
- function splitChunks(messages, startIdx, endIdx, budgetTokens) {
51174
+ function splitChunks(messages, startIdx, endIdx, budget, minUnits, countText = defaultCountTokens) {
51169
51175
  const chunks = [];
51170
51176
  let cur = startIdx;
51171
51177
  while (cur <= endIdx) {
51172
- let tokens = 0;
51178
+ let total = 0;
51173
51179
  let last = cur;
51174
51180
  for (let i = cur; i <= endIdx; i++) {
51175
- const t = defaultCountTokens(messages[i].text ?? "");
51176
- if (tokens + t > budgetTokens && i > cur) break;
51177
- tokens += t;
51181
+ const t = countText(messages[i].text ?? "");
51182
+ if (total + t > budget && i > cur && (minUnits <= 0 || total >= minUnits)) break;
51183
+ total += t;
51178
51184
  last = i;
51179
51185
  }
51180
51186
  chunks.push([cur, last]);
@@ -51261,16 +51267,23 @@ function noEmergencyTruncate(config) {
51261
51267
  }
51262
51268
  async function preflightCompress(deps, messages) {
51263
51269
  const limit = deps.config.modelContextLimit;
51264
- const result = { compressedRanges: 0, savedTokens: 0, payloadEstimate: estimateCoreMessages(messages) + (deps.imageFloor ?? 0) + (deps.wireOverhead ?? 0) };
51270
+ const result = { compressedRanges: 0, savedTokens: 0, payloadEstimate: estimateCoreMessages(messages) + (deps.imageFloor ?? 0) + (deps.wireOverhead ?? 0), fitsWindow: true };
51265
51271
  if (limit <= 0) return result;
51266
51272
  const budget = Math.max(MIN_CHUNK_TOKENS, Math.floor(limit * CHUNK_FRACTION));
51267
51273
  const minChars = deps.config.compress.minCompressRange;
51268
- let currentTokens = deps.session.stats.lastInputTokens;
51274
+ const baselineKnown = deps.unknownBaseline !== true;
51275
+ const countText = baselineKnown ? defaultCountTokens : (text) => text.length;
51276
+ let currentTokens = baselineKnown ? deps.session.stats.lastInputTokens : estimateCoreMessagesUpper(messages);
51277
+ let finalUpper = baselineKnown ? 0 : estimateCoreMessagesUpper(messages);
51269
51278
  let startTokens = -1;
51270
51279
  let failure;
51271
51280
  let activeConfig = deps.config;
51272
51281
  let relaxed = false;
51273
51282
  const relaxedExhaustedDetail = `the payload still exceeds the window after folding everything compressible, including the soft-protected recent zone (last ${deps.config.preserveRecentMessages} messages + most recent user message), which was relaxed under overflow; hard protectedTools remain excluded. Raise the model context window or restart the session to recover.`;
51283
+ const skipSet = /* @__PURE__ */ new Set();
51284
+ let summaryCalls = 0;
51285
+ let budgetHit = false;
51286
+ let rangesTried = 0;
51274
51287
  for (let round = 0; round < MAX_PREFLIGHT_ROUNDS; round++) {
51275
51288
  if (deps.signal?.aborted) {
51276
51289
  failure = ABORTED_FAILURE;
@@ -51285,6 +51298,10 @@ async function preflightCompress(deps, messages) {
51285
51298
  });
51286
51299
  deps.session.state = turn.state;
51287
51300
  currentTokens = Math.max(deps.session.stats.lastInputTokens, estimateCoreMessages(turn.messages) + (deps.imageFloor ?? 0) + (deps.wireOverhead ?? 0));
51301
+ if (!baselineKnown) {
51302
+ finalUpper = estimateCoreMessagesUpper(turn.messages) + (deps.imageFloor ?? 0) + (deps.wireOverhead ?? 0);
51303
+ currentTokens = Math.max(currentTokens, finalUpper);
51304
+ }
51288
51305
  result.payloadEstimate = estimateCoreMessages(turn.messages) + (deps.imageFloor ?? 0) + (deps.wireOverhead ?? 0);
51289
51306
  if (startTokens < 0) startTokens = currentTokens;
51290
51307
  if (currentTokens < limit) break;
@@ -51293,90 +51310,119 @@ async function preflightCompress(deps, messages) {
51293
51310
  if (!relaxed && result.payloadEstimate >= limit) {
51294
51311
  activeConfig = relaxedConfig(deps.config);
51295
51312
  relaxed = true;
51313
+ summaryCalls = 0;
51314
+ budgetHit = false;
51296
51315
  deps.log("warn", "[preflight] no compressible ranges outside the protected recent zone; relaxing soft protection (preserveRecentMessages/Tokens -> 0) and retrying");
51297
51316
  continue;
51298
51317
  }
51299
51318
  failure = { kind: "exhausted", detail: relaxed ? relaxedExhaustedDetail : "no compressible ranges remain in the conversation" };
51300
51319
  break;
51301
51320
  }
51302
- const range = [...ranges].sort((a, b2) => refNum3(a.startRef) - refNum3(b2.startRef))[0];
51303
- const { refToIdx } = refMaps(messages, deps.session.state);
51304
- const startIdx = refToIdx.get(range.startRef);
51305
- const endIdx = refToIdx.get(range.endRef);
51306
- if (startIdx === void 0 || endIdx === void 0 || startIdx > endIdx) {
51307
- failure = { kind: "exhausted", detail: "the compressible range no longer resolves to payload messages" };
51308
- break;
51309
- }
51321
+ const ordered = [...ranges].sort((a, b2) => refNum3(a.startRef) - refNum3(b2.startRef));
51310
51322
  let appliedThisRound = 0;
51311
- for (const [cs2, ce2] of splitChunks(messages, startIdx, endIdx, budget)) {
51323
+ for (const range of ordered) {
51312
51324
  if (currentTokens < limit) break;
51313
51325
  if (deps.signal?.aborted) {
51314
51326
  failure = ABORTED_FAILURE;
51315
51327
  break;
51316
51328
  }
51317
- const maps = refMaps(messages, deps.session.state);
51318
- const startRef = maps.idxToRef.get(cs2);
51319
- const endRef = maps.idxToRef.get(ce2);
51320
- if (!startRef || !endRef) continue;
51321
- if (rangeChars2(messages, cs2, ce2) < minChars) continue;
51322
- const content = renderRange(messages, cs2, ce2);
51323
- if (content.length === 0) continue;
51324
- let summary;
51325
- try {
51326
- summary = await summarizeRange(deps, content, startRef, endRef);
51327
- } catch (err2) {
51328
- if (err2 instanceof UpstreamHttpError) {
51329
- failure = {
51330
- kind: "upstream",
51331
- status: err2.status,
51332
- detail: err2.status === 429 ? `the summarization call was rate-limited by the upstream (HTTP 429)` : `the summarization call was rejected by the upstream (HTTP ${err2.status})`
51333
- };
51334
- deps.log("warn", `[preflight] summarization failed: HTTP ${err2.status} ${err2.body.slice(0, 200)}`);
51335
- } else if (deps.signal?.aborted) {
51329
+ if (budgetHit) break;
51330
+ const skipKey = `${range.startRef}:${range.endRef}`;
51331
+ if (skipSet.has(skipKey)) continue;
51332
+ const { refToIdx } = refMaps(messages, deps.session.state);
51333
+ const startIdx = refToIdx.get(range.startRef);
51334
+ const endIdx = refToIdx.get(range.endRef);
51335
+ if (startIdx === void 0 || endIdx === void 0 || startIdx > endIdx) {
51336
+ skipSet.add(skipKey);
51337
+ continue;
51338
+ }
51339
+ rangesTried += 1;
51340
+ for (const [cs2, ce2] of splitChunks(messages, startIdx, endIdx, budget, baselineKnown ? 0 : minChars, countText)) {
51341
+ if (currentTokens < limit) break;
51342
+ if (deps.signal?.aborted) {
51336
51343
  failure = ABORTED_FAILURE;
51337
- deps.log("warn", `[preflight] summarization aborted: client disconnected`);
51338
- } else {
51339
- failure = { kind: "upstream", detail: `the summarization call failed: ${String(err2)}` };
51340
- deps.log("warn", `[preflight] summarization failed: ${String(err2)}`);
51344
+ break;
51345
+ }
51346
+ if (budgetHit) break;
51347
+ const maps = refMaps(messages, deps.session.state);
51348
+ const startRef = maps.idxToRef.get(cs2);
51349
+ const endRef = maps.idxToRef.get(ce2);
51350
+ if (!startRef || !endRef) continue;
51351
+ if (rangeChars2(messages, cs2, ce2) < minChars) continue;
51352
+ const content = renderRange(messages, cs2, ce2);
51353
+ if (content.length === 0) continue;
51354
+ if (summaryCalls >= MAX_SUMMARY_CALLS_PER_PREFLIGHT) {
51355
+ budgetHit = true;
51356
+ break;
51357
+ }
51358
+ summaryCalls += 1;
51359
+ let summary;
51360
+ try {
51361
+ summary = await summarizeRange(deps, content, startRef, endRef);
51362
+ } catch (err2) {
51363
+ if (err2 instanceof UpstreamHttpError) {
51364
+ failure = {
51365
+ kind: "upstream",
51366
+ status: err2.status,
51367
+ detail: err2.status === 429 ? `the summarization call was rate-limited by the upstream (HTTP 429)` : `the summarization call was rejected by the upstream (HTTP ${err2.status})`
51368
+ };
51369
+ deps.log("warn", `[preflight] summarization failed: HTTP ${err2.status} ${err2.body.slice(0, 200)}`);
51370
+ } else if (deps.signal?.aborted) {
51371
+ failure = ABORTED_FAILURE;
51372
+ deps.log("warn", `[preflight] summarization aborted: client disconnected`);
51373
+ } else {
51374
+ failure = { kind: "upstream", detail: `the summarization call failed: ${String(err2)}` };
51375
+ deps.log("warn", `[preflight] summarization failed: ${String(err2)}`);
51376
+ }
51377
+ break;
51378
+ }
51379
+ if (!summary) {
51380
+ deps.log("warn", `[preflight] range ${skipKey} produced no usable summary; skipping it`);
51381
+ skipSet.add(skipKey);
51382
+ break;
51383
+ }
51384
+ const ctx = {
51385
+ core: deps.core,
51386
+ config: activeConfig,
51387
+ messages,
51388
+ session: deps.session,
51389
+ log: (msg) => deps.log("info", msg)
51390
+ };
51391
+ const creditBefore = deps.session.stats.compressCreditTokens;
51392
+ const applied = applyRanges(parseCompressInput({ content: [{ startId: startRef, endId: endRef, summary, topic: "preflight overflow compress" }] }), ctx);
51393
+ if (applied.startsWith("[Compression FAILED")) {
51394
+ deps.log("warn", `[preflight] ${applied}`);
51395
+ skipSet.add(skipKey);
51396
+ break;
51341
51397
  }
51398
+ const compressed = deps.session.stats.compressCreditTokens - creditBefore;
51399
+ const folded = baselineKnown ? compressed : rangeChars2(messages, cs2, ce2);
51400
+ currentTokens = Math.max(0, currentTokens - folded + countText(summary));
51401
+ deps.session.stats.lastInputTokens += defaultCountTokens(summary);
51402
+ appliedThisRound += 1;
51403
+ result.compressedRanges += 1;
51342
51404
  break;
51343
51405
  }
51344
- if (!summary) continue;
51345
- const ctx = {
51346
- core: deps.core,
51347
- config: activeConfig,
51348
- messages,
51349
- session: deps.session,
51350
- log: (msg) => deps.log("info", msg)
51351
- };
51352
- const creditBefore = deps.session.stats.compressCreditTokens;
51353
- const applied = applyRanges(parseCompressInput({ content: [{ startId: startRef, endId: endRef, summary, topic: "preflight overflow compress" }] }), ctx);
51354
- if (applied.startsWith("[Compression FAILED")) {
51355
- deps.log("warn", `[preflight] ${applied}`);
51356
- continue;
51357
- }
51358
- const compressed = deps.session.stats.compressCreditTokens - creditBefore;
51359
- currentTokens = Math.max(0, currentTokens - compressed + defaultCountTokens(summary));
51360
- deps.session.stats.lastInputTokens += defaultCountTokens(summary);
51361
- appliedThisRound += 1;
51362
- result.compressedRanges += 1;
51363
- }
51364
- if (appliedThisRound === 0) {
51365
- if (!failure) {
51366
- failure = { kind: "exhausted", detail: "no range could be compressed (chunks below minCompressRange or the summarization responses were unusable)" };
51367
- }
51368
- break;
51406
+ if (appliedThisRound > 0) break;
51407
+ if (failure || budgetHit) break;
51369
51408
  }
51409
+ if (appliedThisRound === 0) break;
51370
51410
  }
51371
- if (!failure && currentTokens >= limit) {
51372
- failure = {
51373
- kind: "exhausted",
51374
- detail: relaxed ? relaxedExhaustedDetail : `the compress budget was exhausted after ${MAX_PREFLIGHT_ROUNDS} rounds`
51375
- };
51411
+ if (currentTokens >= limit && !failure) {
51412
+ if (budgetHit) {
51413
+ failure = { kind: "exhausted", detail: `the preflight summarization budget (${MAX_SUMMARY_CALLS_PER_PREFLIGHT} calls per protection regime) was exhausted before the payload fit the window` };
51414
+ } else if (relaxed && result.compressedRanges > 0) {
51415
+ failure = { kind: "exhausted", detail: relaxedExhaustedDetail };
51416
+ } else if (result.compressedRanges === 0) {
51417
+ failure = { kind: "exhausted", detail: `no range could be compressed across ${rangesTried} viable range${rangesTried === 1 ? "" : "s"} (each was below minCompressRange, had an unusable summary, or failed to apply)` };
51418
+ } else {
51419
+ failure = { kind: "exhausted", detail: `the compress budget was exhausted after ${MAX_PREFLIGHT_ROUNDS} rounds` };
51420
+ }
51376
51421
  }
51377
51422
  if (result.compressedRanges > 0) deps.session.stats.lastInputTokens = currentTokens;
51378
51423
  result.savedTokens = Math.max(0, startTokens - currentTokens);
51379
51424
  if (currentTokens >= limit) result.failure = failure;
51425
+ result.fitsWindow = baselineKnown ? result.payloadEstimate < limit : finalUpper < limit;
51380
51426
  return result;
51381
51427
  }
51382
51428
 
@@ -58310,6 +58356,7 @@ ${bodyBuffer.toString("utf8")}`);
58310
58356
  parsed.model,
58311
58357
  route,
58312
58358
  affinity,
58359
+ anonAffinity !== null,
58313
58360
  log2,
58314
58361
  instanceId
58315
58362
  );
@@ -58445,6 +58492,11 @@ function armHostUsageCredit(session, originalMessages, processedMessages, log2)
58445
58492
  log2("info", `[${session.id}] host usage backfill armed: +${session.hostCreditTokens} tok (forwarded view is folded); host usage will report the uncompressed baseline`);
58446
58493
  }
58447
58494
  }
58495
+ function effectiveTokenCount(session, msgs) {
58496
+ if (session.stats.lastInputTokens > 0) return session.stats.lastInputTokens;
58497
+ if (!session.metadata.anonymousPrefixAffinity) return 0;
58498
+ return estimateCoreMessagesUpper(msgs);
58499
+ }
58448
58500
  function prepareAnthropic(parsed, req, opts, core, config, prompts, log2, session, pluginMode) {
58449
58501
  const sessionId = session.id;
58450
58502
  const stream2 = parsed.stream === true;
@@ -58469,7 +58521,7 @@ function prepareAnthropic(parsed, req, opts, core, config, prompts, log2, sessio
58469
58521
  const { msgs, cacheControls } = anthropicToCore(parsed);
58470
58522
  originalMessages = msgs;
58471
58523
  extractSystem(parsed.system);
58472
- const tokenCount = session.stats.lastInputTokens;
58524
+ const tokenCount = effectiveTokenCount(session, msgs);
58473
58525
  const activeBefore = new Set(session.state.blocks.filter((b2) => b2.active).map((b2) => b2.blockId));
58474
58526
  const turn = core.processTurn({ messages: msgs, state: session.state, config, tokenCount, renderTags: "text-only" });
58475
58527
  session.state = turn.state;
@@ -58590,7 +58642,7 @@ function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session,
58590
58642
  const { msgs, systemText } = openaiToCore(parsed);
58591
58643
  openaiSystemText = systemText;
58592
58644
  originalMessages = msgs;
58593
- const tokenCount = session.stats.lastInputTokens;
58645
+ const tokenCount = effectiveTokenCount(session, msgs);
58594
58646
  const activeBefore = new Set(session.state.blocks.filter((b2) => b2.active).map((b2) => b2.blockId));
58595
58647
  const turn = core.processTurn({ messages: msgs, state: session.state, config, tokenCount, renderTags: "text-only" });
58596
58648
  session.state = turn.state;
@@ -58695,7 +58747,7 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
58695
58747
  if (process.env.ACP_DEBUG) {
58696
58748
  log2("info", `[${sessionId}] input items: ${Array.isArray(parsed.input) ? parsed.input.map((i) => i.type).join(",") : "(string)"}`);
58697
58749
  }
58698
- const tokenCount = session.stats.lastInputTokens;
58750
+ const tokenCount = effectiveTokenCount(session, msgs);
58699
58751
  const turn = core.processTurn({ messages: msgs, state: session.state, config, tokenCount, renderTags });
58700
58752
  session.state = turn.state;
58701
58753
  session.stats.compressCreditTokens = 0;
@@ -58993,14 +59045,15 @@ function buildForwardTarget(req, opts, route, affinity, hopMarker) {
58993
59045
  function isPreflightFailFast(outcome) {
58994
59046
  return "failFast" in outcome;
58995
59047
  }
58996
- async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, core, config, model, route, affinity, log2, instanceId) {
59048
+ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, core, config, model, route, affinity, anonymous, log2, instanceId) {
58997
59049
  const session = prepared.session;
58998
59050
  const limit = config.modelContextLimit;
58999
59051
  const imageTokens = imageTokensInRawBody(prepared.protocol, prepared.body);
59000
59052
  const textEstimate = estimateCoreMessages(prepared.processedMessages);
59001
59053
  const overheadEstimate = estimateWireOverhead(prepared.protocol, prepared.body);
59002
59054
  const payloadEstimate = textEstimate + overheadEstimate + imageTokens;
59003
- const tokenCount = Math.max(session.stats.lastInputTokens, payloadEstimate);
59055
+ const unknownBaseline = anonymous && session.stats.lastInputTokens <= 0;
59056
+ const tokenCount = unknownBaseline ? estimateCoreMessagesUpper(prepared.processedMessages) + overheadEstimate + imageTokens : Math.max(session.stats.lastInputTokens, payloadEstimate);
59004
59057
  if (limit <= 0 || !model || tokenCount < limit) return prepared;
59005
59058
  const learnedMap = session.metadata.learnedContextLimits;
59006
59059
  const learnedLimit = (model ? learnedMap?.[model] : void 0) ?? session.metadata.learnedContextLimit;
@@ -59015,9 +59068,14 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
59015
59068
  log2("error", `[${session.id}] preflight fail-fast ${status2} (retryable=${retryable}): ${message}`);
59016
59069
  return { failFast: true, status: status2, message, retryable, respond: !res.writableEnded };
59017
59070
  };
59018
- if ((prepared.nudge?.compressibleRanges ?? []).length === 0 && payloadEstimate < limit) {
59019
- log2("warn", `[${session.id}] preflight trigger fired on a stale baseline (~${tokenCount}) but the payload fits (~${payloadEstimate}/${limit}); forwarding as-is`);
59020
- return prepared;
59071
+ if ((prepared.nudge?.compressibleRanges ?? []).length === 0) {
59072
+ if (!unknownBaseline && payloadEstimate < limit) {
59073
+ log2("warn", `[${session.id}] preflight trigger fired on a stale baseline (~${tokenCount}) but the payload fits (~${payloadEstimate}/${limit}); forwarding as-is`);
59074
+ return prepared;
59075
+ }
59076
+ if (unknownBaseline) {
59077
+ return failFast(502, "no part of the conversation is compressible (nothing left to fold)", false);
59078
+ }
59021
59079
  }
59022
59080
  log2("warn", `[${session.id}] context ${tokenCount} tokens exceeds model window ${limit} (model=${model}); preflight compressing before forward`);
59023
59081
  const { upstreamUrl, headers, proxyUrl } = buildForwardTarget(req, opts, route, affinity, instanceId);
@@ -59040,7 +59098,8 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
59040
59098
  signal: clientAbort.signal,
59041
59099
  log: log2,
59042
59100
  imageFloor: imageTokens,
59043
- wireOverhead: overheadEstimate
59101
+ wireOverhead: overheadEstimate,
59102
+ unknownBaseline
59044
59103
  },
59045
59104
  prepared.originalMessages
59046
59105
  );
@@ -59048,8 +59107,9 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
59048
59107
  log2("info", `[${session.id}] preflight compressed ${result.compressedRanges} range(s), ~${result.savedTokens} tokens saved (${tokenCount} \u2192 ${session.stats.lastInputTokens}) in ${Date.now() - started}ms; rebuilding payload`);
59049
59108
  const rebuilt = runPrepare();
59050
59109
  session.stats.requests -= 1;
59051
- if (estimateCoreMessages(rebuilt.processedMessages) + overheadEstimate + imageTokens < limit) return rebuilt;
59052
- } else if (estimateCoreMessages(prepared.processedMessages) + overheadEstimate + imageTokens < limit) {
59110
+ const fits = unknownBaseline ? result.fitsWindow : estimateCoreMessages(rebuilt.processedMessages) + overheadEstimate + imageTokens < limit;
59111
+ if (fits) return rebuilt;
59112
+ } else if (unknownBaseline ? result.fitsWindow : estimateCoreMessages(prepared.processedMessages) + overheadEstimate + imageTokens < limit) {
59053
59113
  log2("warn", `[${session.id}] preflight made no progress but the payload fits; forwarding as-is`);
59054
59114
  return prepared;
59055
59115
  }