billion-context 0.1.86 → 0.1.87-pr.337.390

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
@@ -43476,10 +43476,6 @@ function defaultCountTokens(text) {
43476
43476
  const cjkCount = cjk?.length ?? 0;
43477
43477
  return cjkCount + Math.ceil((text.length - cjkCount) / 4);
43478
43478
  }
43479
- function estimateTokensFast(text) {
43480
- if (!text) return 0;
43481
- return Math.ceil(text.length / 4);
43482
- }
43483
43479
  var COMPRESS_PHILOSOPHY = `Compression Philosophy:
43484
43480
  - All compression serves the primary task, but be frugal.
43485
43481
  - Context capacity is precious. Save context by compressing consumed outputs, not by avoiding tools.
@@ -46339,7 +46335,7 @@ function formatTokens2(n) {
46339
46335
  }
46340
46336
  function pct(n, total) {
46341
46337
  if (n <= 0 || total <= 0) return 0;
46342
- return Math.max(1, Math.round(n / total * 100));
46338
+ return Math.round(n / total * 100);
46343
46339
  }
46344
46340
  function numericPart2(blockId) {
46345
46341
  const match = /^b(\d+)$/.exec(blockId);
@@ -46378,12 +46374,18 @@ function collectVisible(messages, state, countTokens) {
46378
46374
  if (block.active) summaryTokens += summaryTokensOf(block, countTokens);
46379
46375
  }
46380
46376
  const visible = [];
46377
+ const toolCallNames = /* @__PURE__ */ new Map();
46378
+ for (const message of messages) {
46379
+ if (message.contentType === "tool-call" && message.toolCallId && message.toolName) {
46380
+ toolCallNames.set(message.toolCallId, message.toolName);
46381
+ }
46382
+ }
46381
46383
  messages.forEach((message, index) => {
46382
46384
  if (coveredIds.has(message.id)) return;
46383
46385
  const ref = refForRaw(state.messageRefs, message.id);
46384
46386
  if (!ref) return;
46385
46387
  const tokens = countTokens(message.text ?? "");
46386
- const tool = message.toolName ?? "text";
46388
+ const tool = isToolMessage(message) ? message.toolName ?? (message.toolCallId ? toolCallNames.get(message.toolCallId) : void 0) ?? "tool" : "text";
46387
46389
  if (tokens > 0) visible.push({ ref, tokens, tool, index });
46388
46390
  });
46389
46391
  return { visible, summaryTokens };
@@ -46471,6 +46473,17 @@ function renderUncompressedRanges(visible) {
46471
46473
  const m2 = ref.match(/\d+/);
46472
46474
  return m2 ? parseInt(m2[0], 10) : 0;
46473
46475
  };
46476
+ const dominantTool = (toolTokens) => {
46477
+ let best = "text";
46478
+ let bestN = -1;
46479
+ for (const [tool, n] of toolTokens) {
46480
+ if (n > bestN) {
46481
+ best = tool;
46482
+ bestN = n;
46483
+ }
46484
+ }
46485
+ return best;
46486
+ };
46474
46487
  const merged = [];
46475
46488
  for (const m2 of visible) {
46476
46489
  const num3 = refNum22(m2.ref);
@@ -46479,13 +46492,15 @@ function renderUncompressedRanges(visible) {
46479
46492
  last.endRef = m2.ref;
46480
46493
  last.count += 1;
46481
46494
  last.tokens += m2.tokens;
46495
+ last.toolTokens.set(m2.tool, (last.toolTokens.get(m2.tool) ?? 0) + m2.tokens);
46482
46496
  } else {
46483
- merged.push({ startRef: m2.ref, endRef: m2.ref, startNum: num3, count: 1, tokens: m2.tokens, tool: m2.tool });
46497
+ const toolTokens = /* @__PURE__ */ new Map([[m2.tool, m2.tokens]]);
46498
+ merged.push({ startRef: m2.ref, endRef: m2.ref, startNum: num3, count: 1, tokens: m2.tokens, toolTokens });
46484
46499
  }
46485
46500
  }
46486
46501
  for (const r of merged.slice(0, 30)) {
46487
46502
  const range = r.count === 1 ? r.startRef : `${r.startRef}\u2013${r.endRef}`;
46488
- lines.push(` ${range} (${r.count} msgs, ${formatTokens2(r.tokens)}${r.count > 1 ? ` (${Math.round(r.tokens / r.count)}/msg)` : ""}) ${r.tool}`);
46503
+ lines.push(` ${range} (${r.count} msgs, ${formatTokens2(r.tokens)}${r.count > 1 ? ` (${Math.round(r.tokens / r.count)}/msg)` : ""}) ${dominantTool(r.toolTokens)}`);
46489
46504
  }
46490
46505
  if (merged.length > 30) {
46491
46506
  lines.push(` ... and ${merged.length - 30} more ranges`);
@@ -50754,7 +50769,7 @@ function executeAnthropicProxyTool(toolName, args, ctx) {
50754
50769
  ${lines.join("\n\n")}`;
50755
50770
  }
50756
50771
  if (toolName === "acp_status") {
50757
- return buildStatusReport(ctx.session.state, ctx.messages, estimateTokensFast);
50772
+ return buildStatusReport(ctx.session.state, ctx.messages, defaultCountTokens);
50758
50773
  }
50759
50774
  return `[Unknown proxy tool: ${toolName}]`;
50760
50775
  }
@@ -50988,6 +51003,12 @@ TASK: The conversation segment below (messages ${startRef}\u2013${endRef}) must
50988
51003
  }
50989
51004
  }
50990
51005
  var ABORTED_FAILURE = { kind: "aborted", detail: "the client disconnected during preflight compression" };
51006
+ function relaxedConfig(config) {
51007
+ return { ...config, preserveRecentMessages: 0, preserveRecentTokens: 0 };
51008
+ }
51009
+ function noEmergencyTruncate(config) {
51010
+ return { ...config, modelContextLimit: config.modelContextLimit * 100 };
51011
+ }
50991
51012
  async function preflightCompress(deps, messages) {
50992
51013
  const limit = deps.config.modelContextLimit;
50993
51014
  const result = { compressedRanges: 0, savedTokens: 0, payloadEstimate: estimateCoreMessages(messages) + (deps.imageFloor ?? 0) };
@@ -50997,6 +51018,9 @@ async function preflightCompress(deps, messages) {
50997
51018
  let currentTokens = deps.session.stats.lastInputTokens;
50998
51019
  let startTokens = -1;
50999
51020
  let failure;
51021
+ let activeConfig = deps.config;
51022
+ let relaxed = false;
51023
+ 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.`;
51000
51024
  for (let round = 0; round < MAX_PREFLIGHT_ROUNDS; round++) {
51001
51025
  if (deps.signal?.aborted) {
51002
51026
  failure = ABORTED_FAILURE;
@@ -51005,7 +51029,7 @@ async function preflightCompress(deps, messages) {
51005
51029
  const turn = deps.core.processTurn({
51006
51030
  messages,
51007
51031
  state: deps.session.state,
51008
- config: deps.config,
51032
+ config: noEmergencyTruncate(activeConfig),
51009
51033
  tokenCount: currentTokens,
51010
51034
  renderTags: "text-only"
51011
51035
  });
@@ -51016,7 +51040,13 @@ async function preflightCompress(deps, messages) {
51016
51040
  if (currentTokens < limit) break;
51017
51041
  const ranges = viableRanges(turn.nudge?.compressibleRanges ?? []);
51018
51042
  if (ranges.length === 0) {
51019
- failure = { kind: "exhausted", detail: "no compressible ranges remain in the conversation" };
51043
+ if (!relaxed && result.payloadEstimate >= limit) {
51044
+ activeConfig = relaxedConfig(deps.config);
51045
+ relaxed = true;
51046
+ deps.log("warn", "[preflight] no compressible ranges outside the protected recent zone; relaxing soft protection (preserveRecentMessages/Tokens -> 0) and retrying");
51047
+ continue;
51048
+ }
51049
+ failure = { kind: "exhausted", detail: relaxed ? relaxedExhaustedDetail : "no compressible ranges remain in the conversation" };
51020
51050
  break;
51021
51051
  }
51022
51052
  const range = [...ranges].sort((a, b2) => refNum3(a.startRef) - refNum3(b2.startRef))[0];
@@ -51064,7 +51094,7 @@ async function preflightCompress(deps, messages) {
51064
51094
  if (!summary) continue;
51065
51095
  const ctx = {
51066
51096
  core: deps.core,
51067
- config: deps.config,
51097
+ config: activeConfig,
51068
51098
  messages,
51069
51099
  session: deps.session,
51070
51100
  log: (msg) => deps.log("info", msg)
@@ -51089,7 +51119,10 @@ async function preflightCompress(deps, messages) {
51089
51119
  }
51090
51120
  }
51091
51121
  if (!failure && currentTokens >= limit) {
51092
- failure = { kind: "exhausted", detail: `the compress budget was exhausted after ${MAX_PREFLIGHT_ROUNDS} rounds` };
51122
+ failure = {
51123
+ kind: "exhausted",
51124
+ detail: relaxed ? relaxedExhaustedDetail : `the compress budget was exhausted after ${MAX_PREFLIGHT_ROUNDS} rounds`
51125
+ };
51093
51126
  }
51094
51127
  if (result.compressedRanges > 0) deps.session.stats.lastInputTokens = currentTokens;
51095
51128
  result.savedTokens = Math.max(0, startTokens - currentTokens);
@@ -51872,6 +51905,23 @@ function isLoopThinking(m2) {
51872
51905
  function stripLoopThinking(messages) {
51873
51906
  return messages.filter((m2) => !isLoopThinking(m2));
51874
51907
  }
51908
+ function canonicalArgs(args) {
51909
+ try {
51910
+ return JSON.stringify(sortKeys(JSON.parse(args)));
51911
+ } catch {
51912
+ return args;
51913
+ }
51914
+ }
51915
+ function sortKeys(v2) {
51916
+ if (Array.isArray(v2)) return v2.map(sortKeys);
51917
+ if (v2 !== null && typeof v2 === "object") {
51918
+ const src = v2;
51919
+ const out = {};
51920
+ for (const k2 of Object.keys(src).sort()) out[k2] = sortKeys(src[k2]);
51921
+ return out;
51922
+ }
51923
+ return v2;
51924
+ }
51875
51925
  function executeProxyTool(toolName, args, ctx, callId) {
51876
51926
  if (toolName === "compress") {
51877
51927
  return applyRanges(parseCompressInput(args, callId), ctx);
@@ -51906,7 +51956,7 @@ function handleAcpStatus(args, ctx) {
51906
51956
  const tool = typeof args.tool === "string" ? args.tool : void 0;
51907
51957
  const sort = typeof args.sort === "string" ? args.sort : void 0;
51908
51958
  const limit = typeof args.limit === "number" ? args.limit : void 0;
51909
- const base = buildStatusReport(ctx.session.state, ctx.messages, estimateTokensFast, { scope, view, tool, sort, limit });
51959
+ const base = buildStatusReport(ctx.session.state, ctx.messages, defaultCountTokens, { scope, view, tool, sort, limit });
51910
51960
  if (scope) return base;
51911
51961
  const nudge = ctx.nudge;
51912
51962
  const ranges = nudge?.compressibleRanges ?? [];
@@ -51974,6 +52024,7 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
51974
52024
  log("warn", `[acp-loop] upstream rejected replay (HTTP ${info.status}); retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})${lc}`);
51975
52025
  }
51976
52026
  );
52027
+ const failedSignatures = /* @__PURE__ */ new Set();
51977
52028
  try {
51978
52029
  for (let round = 1; round <= MAX_LOOP_ROUNDS; round++) {
51979
52030
  if (signal?.aborted) break;
@@ -52229,6 +52280,19 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
52229
52280
  yield adapter.emitCompletion({ finishReason: "length", usage });
52230
52281
  return;
52231
52282
  }
52283
+ const failedMutating = proxyResults.filter(
52284
+ (pr2) => (pr2.name === "compress" || pr2.name === "decompress") && pr2.result.includes("FAILED")
52285
+ );
52286
+ if (reRequest && failedMutating.length > 0 && failedMutating.length === proxyResults.length) {
52287
+ const repeated = failedMutating.some((pr2) => failedSignatures.has(`${pr2.name}\0${canonicalArgs(pr2.arguments)}`));
52288
+ if (repeated) {
52289
+ ctx.log(`[acp-loop] round ${round}: model re-submitted an already-failed compress with identical arguments; stopping after ${round} round(s) instead of ${MAX_LOOP_ROUNDS}`);
52290
+ log("warn", `[acp-loop] repeated identical compress failure at round ${round}; breaking early (#156)`);
52291
+ yield adapter.emitCompletion({ finishReason: "length", usage });
52292
+ return;
52293
+ }
52294
+ }
52295
+ for (const pr2 of failedMutating) failedSignatures.add(`${pr2.name}\0${canonicalArgs(pr2.arguments)}`);
52232
52296
  ctx.log(`[acp-loop] round ${round}: proxy tool executed; re-requesting so the model sees the result`);
52233
52297
  if (signal?.aborted) break;
52234
52298
  let newBody = adapter.buildRequest(coreMessages, systemPrompt, requestBody);
@@ -53755,7 +53819,7 @@ function executeProxyTool2(toolName, args, ctx) {
53755
53819
  ${lines.join("\n\n")}`;
53756
53820
  }
53757
53821
  if (toolName === "acp_status") {
53758
- return buildStatusReport(ctx.session.state, ctx.messages, estimateTokensFast);
53822
+ return buildStatusReport(ctx.session.state, ctx.messages, defaultCountTokens);
53759
53823
  }
53760
53824
  return `[Unknown proxy tool: ${toolName}]`;
53761
53825
  }
@@ -54334,14 +54398,14 @@ var MIN_TAIL_MATCH = 3;
54334
54398
  var MAX_STORED_ITEMS = 128;
54335
54399
  var MIN_FORK_PREFIX = 3;
54336
54400
  function stableStringify(value) {
54337
- return JSON.stringify(sortKeys(value));
54401
+ return JSON.stringify(sortKeys2(value));
54338
54402
  }
54339
- function sortKeys(value) {
54340
- if (Array.isArray(value)) return value.map(sortKeys);
54403
+ function sortKeys2(value) {
54404
+ if (Array.isArray(value)) return value.map(sortKeys2);
54341
54405
  if (value && typeof value === "object") {
54342
54406
  const record = value;
54343
54407
  const out = {};
54344
- for (const key of Object.keys(record).sort()) out[key] = sortKeys(record[key]);
54408
+ for (const key of Object.keys(record).sort()) out[key] = sortKeys2(record[key]);
54345
54409
  return out;
54346
54410
  }
54347
54411
  return value;
@@ -58421,12 +58485,9 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
58421
58485
  log2("error", `[${session.id}] preflight fail-fast ${status2} (retryable=${retryable}): ${message}`);
58422
58486
  return { failFast: true, status: status2, message, retryable, respond: !res.writableEnded };
58423
58487
  };
58424
- if ((prepared.nudge?.compressibleRanges ?? []).length === 0) {
58425
- if (payloadEstimate < limit) {
58426
- log2("warn", `[${session.id}] preflight trigger fired on a stale baseline (~${tokenCount}) but the payload fits (~${payloadEstimate}/${limit}); forwarding as-is`);
58427
- return prepared;
58428
- }
58429
- return failFast(502, "no part of the conversation is compressible (nothing left to fold)", false);
58488
+ if ((prepared.nudge?.compressibleRanges ?? []).length === 0 && payloadEstimate < limit) {
58489
+ log2("warn", `[${session.id}] preflight trigger fired on a stale baseline (~${tokenCount}) but the payload fits (~${payloadEstimate}/${limit}); forwarding as-is`);
58490
+ return prepared;
58430
58491
  }
58431
58492
  log2("warn", `[${session.id}] context ${tokenCount} tokens exceeds model window ${limit} (model=${model}); preflight compressing before forward`);
58432
58493
  const { upstreamUrl, headers, proxyUrl } = buildForwardTarget(req, opts, route, affinity, instanceId);
@@ -58452,14 +58513,13 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
58452
58513
  },
58453
58514
  prepared.originalMessages
58454
58515
  );
58455
- if (result.payloadEstimate < limit) {
58456
- if (result.compressedRanges > 0) {
58457
- 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`);
58458
- const rebuilt = runPrepare();
58459
- session.stats.requests -= 1;
58460
- return rebuilt;
58461
- }
58462
- log2("warn", `[${session.id}] preflight made no progress but the payload fits (~${result.payloadEstimate}/${limit}); forwarding as-is`);
58516
+ if (result.compressedRanges > 0) {
58517
+ 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`);
58518
+ const rebuilt = runPrepare();
58519
+ session.stats.requests -= 1;
58520
+ if (estimateCoreMessages(rebuilt.processedMessages) + imageTokens < limit) return rebuilt;
58521
+ } else if (estimateCoreMessages(prepared.processedMessages) + imageTokens < limit) {
58522
+ log2("warn", `[${session.id}] preflight made no progress but the payload fits; forwarding as-is`);
58463
58523
  return prepared;
58464
58524
  }
58465
58525
  const f2 = result.failure;
@@ -58468,7 +58528,7 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
58468
58528
  return { failFast: true, status: 0, message: f2.detail, retryable: false, respond: false };
58469
58529
  }
58470
58530
  const status = f2?.kind === "upstream" && f2.status === 429 ? 503 : 502;
58471
- return failFast(status, f2?.detail ?? "unknown reason", status === 503);
58531
+ return failFast(status, f2?.detail ?? "the payload still exceeds the window after preflight compression", status === 503);
58472
58532
  }
58473
58533
  async function forward(req, res, opts, body, prepared, core, config, log2, route, instanceId, affinity) {
58474
58534
  if (prepared?.codexForge) {