billion-context 0.1.86 → 0.1.87-pr.397.392

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`);
@@ -50433,6 +50448,50 @@ function withStagedCompressGuidance(text) {
50433
50448
  return text + STAGED_COMPRESS_GUIDANCE;
50434
50449
  }
50435
50450
 
50451
+ // src/acp-status.ts
50452
+ function handleAcpStatus(args, ctx) {
50453
+ const scope = typeof args.scope === "string" ? args.scope : void 0;
50454
+ const view = typeof args.view === "string" ? args.view : void 0;
50455
+ const tool = typeof args.tool === "string" ? args.tool : void 0;
50456
+ const sort = typeof args.sort === "string" ? args.sort : void 0;
50457
+ const limit = typeof args.limit === "number" ? args.limit : void 0;
50458
+ const base = buildStatusReport(ctx.session.state, ctx.messages, defaultCountTokens, { scope, view, tool, sort, limit });
50459
+ if (scope) return base;
50460
+ const extra = [];
50461
+ try {
50462
+ const turn = ctx.core.processTurn({
50463
+ messages: ctx.messages,
50464
+ state: ctx.session.state,
50465
+ config: ctx.config,
50466
+ tokenCount: ctx.session.stats.lastInputTokens,
50467
+ renderTags: "none"
50468
+ });
50469
+ const nudge = turn.nudge;
50470
+ if (nudge) {
50471
+ extra.push("");
50472
+ extra.push(nudge.shouldInject ? `Nudge: ACTIVE \u2014 ${nudge.reason}` : `Nudge: idle \u2014 ${nudge.reason}`);
50473
+ const ranges = viableRanges(nudge.compressibleRanges);
50474
+ const protectedRanges = nudge.protectedRanges ?? [];
50475
+ if (ranges.length > 0 || protectedRanges.length > 0) {
50476
+ extra.push("");
50477
+ extra.push(formatRanges(ranges, protectedRanges));
50478
+ }
50479
+ }
50480
+ } catch {
50481
+ }
50482
+ const archive = preCompactionArchiveOf(ctx.session);
50483
+ const archivedIds = Object.keys(archive);
50484
+ if (archivedIds.length > 0) {
50485
+ extra.push("");
50486
+ extra.push(`PRE-COMPACTION ARCHIVE \u2014 ${archivedIds.length} block(s): content was replaced by the client's native compaction summary, so it is no longer in the session history and decompress is unavailable.`);
50487
+ for (const id of archivedIds) {
50488
+ extra.push(` ${id} \u2014 ${archive[id].reason}`);
50489
+ }
50490
+ }
50491
+ return extra.length > 0 ? `${base}
50492
+ ${extra.join("\n")}` : base;
50493
+ }
50494
+
50436
50495
  // src/decompress-shared.ts
50437
50496
  import { mkdirSync as mkdirSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync3 } from "fs";
50438
50497
  import { dirname as dirname2, join as join2 } from "path";
@@ -50754,7 +50813,7 @@ function executeAnthropicProxyTool(toolName, args, ctx) {
50754
50813
  ${lines.join("\n\n")}`;
50755
50814
  }
50756
50815
  if (toolName === "acp_status") {
50757
- return buildStatusReport(ctx.session.state, ctx.messages, estimateTokensFast);
50816
+ return handleAcpStatus(args, ctx);
50758
50817
  }
50759
50818
  return `[Unknown proxy tool: ${toolName}]`;
50760
50819
  }
@@ -50988,6 +51047,12 @@ TASK: The conversation segment below (messages ${startRef}\u2013${endRef}) must
50988
51047
  }
50989
51048
  }
50990
51049
  var ABORTED_FAILURE = { kind: "aborted", detail: "the client disconnected during preflight compression" };
51050
+ function relaxedConfig(config) {
51051
+ return { ...config, preserveRecentMessages: 0, preserveRecentTokens: 0 };
51052
+ }
51053
+ function noEmergencyTruncate(config) {
51054
+ return { ...config, modelContextLimit: config.modelContextLimit * 100 };
51055
+ }
50991
51056
  async function preflightCompress(deps, messages) {
50992
51057
  const limit = deps.config.modelContextLimit;
50993
51058
  const result = { compressedRanges: 0, savedTokens: 0, payloadEstimate: estimateCoreMessages(messages) + (deps.imageFloor ?? 0) };
@@ -50997,6 +51062,9 @@ async function preflightCompress(deps, messages) {
50997
51062
  let currentTokens = deps.session.stats.lastInputTokens;
50998
51063
  let startTokens = -1;
50999
51064
  let failure;
51065
+ let activeConfig = deps.config;
51066
+ let relaxed = false;
51067
+ 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
51068
  for (let round = 0; round < MAX_PREFLIGHT_ROUNDS; round++) {
51001
51069
  if (deps.signal?.aborted) {
51002
51070
  failure = ABORTED_FAILURE;
@@ -51005,7 +51073,7 @@ async function preflightCompress(deps, messages) {
51005
51073
  const turn = deps.core.processTurn({
51006
51074
  messages,
51007
51075
  state: deps.session.state,
51008
- config: deps.config,
51076
+ config: noEmergencyTruncate(activeConfig),
51009
51077
  tokenCount: currentTokens,
51010
51078
  renderTags: "text-only"
51011
51079
  });
@@ -51016,7 +51084,13 @@ async function preflightCompress(deps, messages) {
51016
51084
  if (currentTokens < limit) break;
51017
51085
  const ranges = viableRanges(turn.nudge?.compressibleRanges ?? []);
51018
51086
  if (ranges.length === 0) {
51019
- failure = { kind: "exhausted", detail: "no compressible ranges remain in the conversation" };
51087
+ if (!relaxed && result.payloadEstimate >= limit) {
51088
+ activeConfig = relaxedConfig(deps.config);
51089
+ relaxed = true;
51090
+ deps.log("warn", "[preflight] no compressible ranges outside the protected recent zone; relaxing soft protection (preserveRecentMessages/Tokens -> 0) and retrying");
51091
+ continue;
51092
+ }
51093
+ failure = { kind: "exhausted", detail: relaxed ? relaxedExhaustedDetail : "no compressible ranges remain in the conversation" };
51020
51094
  break;
51021
51095
  }
51022
51096
  const range = [...ranges].sort((a, b2) => refNum3(a.startRef) - refNum3(b2.startRef))[0];
@@ -51064,7 +51138,7 @@ async function preflightCompress(deps, messages) {
51064
51138
  if (!summary) continue;
51065
51139
  const ctx = {
51066
51140
  core: deps.core,
51067
- config: deps.config,
51141
+ config: activeConfig,
51068
51142
  messages,
51069
51143
  session: deps.session,
51070
51144
  log: (msg) => deps.log("info", msg)
@@ -51089,7 +51163,10 @@ async function preflightCompress(deps, messages) {
51089
51163
  }
51090
51164
  }
51091
51165
  if (!failure && currentTokens >= limit) {
51092
- failure = { kind: "exhausted", detail: `the compress budget was exhausted after ${MAX_PREFLIGHT_ROUNDS} rounds` };
51166
+ failure = {
51167
+ kind: "exhausted",
51168
+ detail: relaxed ? relaxedExhaustedDetail : `the compress budget was exhausted after ${MAX_PREFLIGHT_ROUNDS} rounds`
51169
+ };
51093
51170
  }
51094
51171
  if (result.compressedRanges > 0) deps.session.stats.lastInputTokens = currentTokens;
51095
51172
  result.savedTokens = Math.max(0, startTokens - currentTokens);
@@ -51872,6 +51949,23 @@ function isLoopThinking(m2) {
51872
51949
  function stripLoopThinking(messages) {
51873
51950
  return messages.filter((m2) => !isLoopThinking(m2));
51874
51951
  }
51952
+ function canonicalArgs(args) {
51953
+ try {
51954
+ return JSON.stringify(sortKeys(JSON.parse(args)));
51955
+ } catch {
51956
+ return args;
51957
+ }
51958
+ }
51959
+ function sortKeys(v2) {
51960
+ if (Array.isArray(v2)) return v2.map(sortKeys);
51961
+ if (v2 !== null && typeof v2 === "object") {
51962
+ const src = v2;
51963
+ const out = {};
51964
+ for (const k2 of Object.keys(src).sort()) out[k2] = sortKeys(src[k2]);
51965
+ return out;
51966
+ }
51967
+ return v2;
51968
+ }
51875
51969
  function executeProxyTool(toolName, args, ctx, callId) {
51876
51970
  if (toolName === "compress") {
51877
51971
  return applyRanges(parseCompressInput(args, callId), ctx);
@@ -51900,38 +51994,6 @@ ${lines.join("\n\n")}`;
51900
51994
  }
51901
51995
  return `[Unknown proxy tool: ${toolName}]`;
51902
51996
  }
51903
- function handleAcpStatus(args, ctx) {
51904
- const scope = typeof args.scope === "string" ? args.scope : void 0;
51905
- const view = typeof args.view === "string" ? args.view : void 0;
51906
- const tool = typeof args.tool === "string" ? args.tool : void 0;
51907
- const sort = typeof args.sort === "string" ? args.sort : void 0;
51908
- 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 });
51910
- if (scope) return base;
51911
- const nudge = ctx.nudge;
51912
- const ranges = nudge?.compressibleRanges ?? [];
51913
- const protectedRanges = nudge?.protectedRanges ?? [];
51914
- const archive = preCompactionArchiveOf(ctx.session);
51915
- const archivedIds = Object.keys(archive);
51916
- const extra = [];
51917
- if (nudge) {
51918
- extra.push("");
51919
- extra.push(nudge.shouldInject ? `Nudge: ACTIVE \u2014 ${nudge.reason}` : `Nudge: idle \u2014 ${nudge.reason}`);
51920
- }
51921
- if (ranges.length > 0 || protectedRanges.length > 0) {
51922
- extra.push("");
51923
- extra.push(formatRanges(ranges, protectedRanges));
51924
- }
51925
- if (archivedIds.length > 0) {
51926
- extra.push("");
51927
- extra.push(`PRE-COMPACTION ARCHIVE \u2014 ${archivedIds.length} block(s): content was replaced by the client's native compaction summary, so it is no longer in the session history and decompress is unavailable.`);
51928
- for (const id of archivedIds) {
51929
- extra.push(` ${id} \u2014 ${archive[id].reason}`);
51930
- }
51931
- }
51932
- return extra.length > 0 ? `${base}
51933
- ${extra.join("\n")}` : base;
51934
- }
51935
51997
  function recordUsage(ctx, usage, round) {
51936
51998
  const prompt = usage.inputTokens;
51937
51999
  const cached = usage.cachedTokens;
@@ -51974,6 +52036,7 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
51974
52036
  log("warn", `[acp-loop] upstream rejected replay (HTTP ${info.status}); retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})${lc}`);
51975
52037
  }
51976
52038
  );
52039
+ const failedSignatures = /* @__PURE__ */ new Set();
51977
52040
  try {
51978
52041
  for (let round = 1; round <= MAX_LOOP_ROUNDS; round++) {
51979
52042
  if (signal?.aborted) break;
@@ -52229,6 +52292,19 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
52229
52292
  yield adapter.emitCompletion({ finishReason: "length", usage });
52230
52293
  return;
52231
52294
  }
52295
+ const failedMutating = proxyResults.filter(
52296
+ (pr2) => (pr2.name === "compress" || pr2.name === "decompress") && pr2.result.includes("FAILED")
52297
+ );
52298
+ if (reRequest && failedMutating.length > 0 && failedMutating.length === proxyResults.length) {
52299
+ const repeated = failedMutating.some((pr2) => failedSignatures.has(`${pr2.name}\0${canonicalArgs(pr2.arguments)}`));
52300
+ if (repeated) {
52301
+ 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}`);
52302
+ log("warn", `[acp-loop] repeated identical compress failure at round ${round}; breaking early (#156)`);
52303
+ yield adapter.emitCompletion({ finishReason: "length", usage });
52304
+ return;
52305
+ }
52306
+ }
52307
+ for (const pr2 of failedMutating) failedSignatures.add(`${pr2.name}\0${canonicalArgs(pr2.arguments)}`);
52232
52308
  ctx.log(`[acp-loop] round ${round}: proxy tool executed; re-requesting so the model sees the result`);
52233
52309
  if (signal?.aborted) break;
52234
52310
  let newBody = adapter.buildRequest(coreMessages, systemPrompt, requestBody);
@@ -53755,7 +53831,7 @@ function executeProxyTool2(toolName, args, ctx) {
53755
53831
  ${lines.join("\n\n")}`;
53756
53832
  }
53757
53833
  if (toolName === "acp_status") {
53758
- return buildStatusReport(ctx.session.state, ctx.messages, estimateTokensFast);
53834
+ return handleAcpStatus(args, ctx);
53759
53835
  }
53760
53836
  return `[Unknown proxy tool: ${toolName}]`;
53761
53837
  }
@@ -54334,14 +54410,14 @@ var MIN_TAIL_MATCH = 3;
54334
54410
  var MAX_STORED_ITEMS = 128;
54335
54411
  var MIN_FORK_PREFIX = 3;
54336
54412
  function stableStringify(value) {
54337
- return JSON.stringify(sortKeys(value));
54413
+ return JSON.stringify(sortKeys2(value));
54338
54414
  }
54339
- function sortKeys(value) {
54340
- if (Array.isArray(value)) return value.map(sortKeys);
54415
+ function sortKeys2(value) {
54416
+ if (Array.isArray(value)) return value.map(sortKeys2);
54341
54417
  if (value && typeof value === "object") {
54342
54418
  const record = value;
54343
54419
  const out = {};
54344
- for (const key of Object.keys(record).sort()) out[key] = sortKeys(record[key]);
54420
+ for (const key of Object.keys(record).sort()) out[key] = sortKeys2(record[key]);
54345
54421
  return out;
54346
54422
  }
54347
54423
  return value;
@@ -55058,8 +55134,7 @@ async function handlePluginTool(payload, res, deps) {
55058
55134
  config: deps.config,
55059
55135
  messages,
55060
55136
  session,
55061
- log: (m2) => deps.log("info", `[${session.id}] [plugin] ${m2}`),
55062
- nudge: mem?.nudge
55137
+ log: (m2) => deps.log("info", `[${session.id}] [plugin] ${m2}`)
55063
55138
  }, callId);
55064
55139
  });
55065
55140
  } catch (err2) {
@@ -58421,12 +58496,9 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
58421
58496
  log2("error", `[${session.id}] preflight fail-fast ${status2} (retryable=${retryable}): ${message}`);
58422
58497
  return { failFast: true, status: status2, message, retryable, respond: !res.writableEnded };
58423
58498
  };
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);
58499
+ if ((prepared.nudge?.compressibleRanges ?? []).length === 0 && payloadEstimate < limit) {
58500
+ log2("warn", `[${session.id}] preflight trigger fired on a stale baseline (~${tokenCount}) but the payload fits (~${payloadEstimate}/${limit}); forwarding as-is`);
58501
+ return prepared;
58430
58502
  }
58431
58503
  log2("warn", `[${session.id}] context ${tokenCount} tokens exceeds model window ${limit} (model=${model}); preflight compressing before forward`);
58432
58504
  const { upstreamUrl, headers, proxyUrl } = buildForwardTarget(req, opts, route, affinity, instanceId);
@@ -58452,14 +58524,13 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
58452
58524
  },
58453
58525
  prepared.originalMessages
58454
58526
  );
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`);
58527
+ if (result.compressedRanges > 0) {
58528
+ 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`);
58529
+ const rebuilt = runPrepare();
58530
+ session.stats.requests -= 1;
58531
+ if (estimateCoreMessages(rebuilt.processedMessages) + imageTokens < limit) return rebuilt;
58532
+ } else if (estimateCoreMessages(prepared.processedMessages) + imageTokens < limit) {
58533
+ log2("warn", `[${session.id}] preflight made no progress but the payload fits; forwarding as-is`);
58463
58534
  return prepared;
58464
58535
  }
58465
58536
  const f2 = result.failure;
@@ -58468,7 +58539,7 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
58468
58539
  return { failFast: true, status: 0, message: f2.detail, retryable: false, respond: false };
58469
58540
  }
58470
58541
  const status = f2?.kind === "upstream" && f2.status === 429 ? 503 : 502;
58471
- return failFast(status, f2?.detail ?? "unknown reason", status === 503);
58542
+ return failFast(status, f2?.detail ?? "the payload still exceeds the window after preflight compression", status === 503);
58472
58543
  }
58473
58544
  async function forward(req, res, opts, body, prepared, core, config, log2, route, instanceId, affinity) {
58474
58545
  if (prepared?.codexForge) {
@@ -58789,7 +58860,7 @@ ${hdrText}
58789
58860
  };
58790
58861
  const loop = runCompressLoop(
58791
58862
  streamToRead,
58792
- { core, config, messages: prepared.processedMessages.length > 0 ? prepared.processedMessages : prepared.originalMessages, compressMessages: prepared.originalMessages, session: prepared.session, log: ctx.log, proxyUrl, protocol: prepared.protocol, textProtocol, debug: opts.debug, nudge: prepared.nudge, refreshFolded },
58863
+ { core, config, messages: prepared.processedMessages.length > 0 ? prepared.processedMessages : prepared.originalMessages, compressMessages: prepared.originalMessages, session: prepared.session, log: ctx.log, proxyUrl, protocol: prepared.protocol, textProtocol, debug: opts.debug, refreshFolded },
58793
58864
  parsedReq,
58794
58865
  { url: upstreamUrl, headers: reqHeaders },
58795
58866
  adapter,