billion-context 0.1.76 → 0.1.77-pr.497.318

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
@@ -50745,7 +50745,7 @@ function summaryPayload(protocol, model, system, content) {
50745
50745
  if (protocol === "openai") {
50746
50746
  return { model, max_tokens: MAX_SUMMARY_OUTPUT_TOKENS, messages: [{ role: "system", content: system }, { role: "user", content }], stream: false };
50747
50747
  }
50748
- return { model, max_output_tokens: MAX_SUMMARY_OUTPUT_TOKENS, instructions: system, input: [{ role: "user", content }], stream: false };
50748
+ return { model, max_output_tokens: MAX_SUMMARY_OUTPUT_TOKENS, instructions: system, input: [{ role: "user", content }], stream: false, store: false };
50749
50749
  }
50750
50750
  function extractSummaryText(protocol, json) {
50751
50751
  if (protocol === "anthropic") {
@@ -50811,7 +50811,7 @@ TASK: The conversation segment below (messages ${startRef}\u2013${endRef}) must
50811
50811
  var ABORTED_FAILURE = { kind: "aborted", detail: "the client disconnected during preflight compression" };
50812
50812
  async function preflightCompress(deps, messages) {
50813
50813
  const limit = deps.config.modelContextLimit;
50814
- const result = { compressedRanges: 0, savedTokens: 0, payloadEstimate: estimateCoreMessages(messages) };
50814
+ const result = { compressedRanges: 0, savedTokens: 0, payloadEstimate: estimateCoreMessages(messages) + (deps.imageFloor ?? 0) };
50815
50815
  if (limit <= 0) return result;
50816
50816
  const budget = Math.max(MIN_CHUNK_TOKENS, Math.floor(limit * CHUNK_FRACTION));
50817
50817
  const minChars = deps.config.compress.minCompressRange;
@@ -50831,8 +50831,8 @@ async function preflightCompress(deps, messages) {
50831
50831
  renderTags: "text-only"
50832
50832
  });
50833
50833
  deps.session.state = turn.state;
50834
- currentTokens = Math.max(deps.session.stats.lastInputTokens, estimateCoreMessages(turn.messages));
50835
- result.payloadEstimate = estimateCoreMessages(turn.messages);
50834
+ currentTokens = Math.max(deps.session.stats.lastInputTokens, estimateCoreMessages(turn.messages) + (deps.imageFloor ?? 0));
50835
+ result.payloadEstimate = estimateCoreMessages(turn.messages) + (deps.imageFloor ?? 0);
50836
50836
  if (startTokens < 0) startTokens = currentTokens;
50837
50837
  if (currentTokens < limit) break;
50838
50838
  const ranges = viableRanges(turn.nudge?.compressibleRanges ?? []);
@@ -50918,6 +50918,78 @@ async function preflightCompress(deps, messages) {
50918
50918
  return result;
50919
50919
  }
50920
50920
 
50921
+ // src/image-tokens.ts
50922
+ var REMOTE_IMAGE_TOKENS = 4096;
50923
+ function imageTokenCap() {
50924
+ const v2 = Number(process.env.BILI_IMAGE_TOKEN_CAP ?? "");
50925
+ return Number.isInteger(v2) && v2 > 0 ? v2 : 0;
50926
+ }
50927
+ function applyCap(cost) {
50928
+ const cap = imageTokenCap();
50929
+ return cap > 0 ? Math.min(cost, cap) : cost;
50930
+ }
50931
+ function costForUrl(url) {
50932
+ if (url.startsWith("data:")) {
50933
+ const i = url.indexOf("base64,");
50934
+ if (i >= 0) return applyCap(Math.ceil((url.length - i - "base64,".length) / 4));
50935
+ }
50936
+ return applyCap(REMOTE_IMAGE_TOKENS);
50937
+ }
50938
+ function isObj(v2) {
50939
+ return typeof v2 === "object" && v2 !== null;
50940
+ }
50941
+ function urlOf(v2) {
50942
+ if (typeof v2 === "string") return v2;
50943
+ if (isObj(v2) && typeof v2.url === "string") return v2.url;
50944
+ return void 0;
50945
+ }
50946
+ function imageTokensInParsedBody(protocol, body) {
50947
+ if (!isObj(body)) return 0;
50948
+ let total = 0;
50949
+ if (protocol === "responses") {
50950
+ const input = body.input;
50951
+ if (!Array.isArray(input)) return 0;
50952
+ for (const item of input) {
50953
+ if (!isObj(item) || !Array.isArray(item.content)) continue;
50954
+ for (const part of item.content) {
50955
+ if (!isObj(part) || part.type !== "input_image") continue;
50956
+ const url = urlOf(part.image_url);
50957
+ if (url) total += costForUrl(url);
50958
+ }
50959
+ }
50960
+ return total;
50961
+ }
50962
+ const messages = body.messages;
50963
+ if (!Array.isArray(messages)) return 0;
50964
+ for (const m2 of messages) {
50965
+ if (!isObj(m2) || !Array.isArray(m2.content)) continue;
50966
+ for (const part of m2.content) {
50967
+ if (!isObj(part)) continue;
50968
+ if (protocol === "openai") {
50969
+ if (part.type !== "image_url") continue;
50970
+ const url = urlOf(part.image_url);
50971
+ if (url) total += costForUrl(url);
50972
+ } else {
50973
+ if (part.type !== "image") continue;
50974
+ const src = part.source;
50975
+ if (isObj(src) && src.type === "base64" && typeof src.data === "string") total += applyCap(Math.ceil(src.data.length / 4));
50976
+ else if (isObj(src) && src.type === "url" && typeof src.url === "string") total += costForUrl(src.url);
50977
+ }
50978
+ }
50979
+ }
50980
+ return total;
50981
+ }
50982
+ function imageTokensInRawBody(protocol, raw) {
50983
+ const s3 = typeof raw === "string" ? raw : raw.toString("utf8");
50984
+ const probe = protocol === "responses" ? s3.includes("input_image") : protocol === "openai" ? s3.includes("image_url") : s3.includes('"type":"image"') || s3.includes('"type": "image"');
50985
+ if (!probe) return 0;
50986
+ try {
50987
+ return imageTokensInParsedBody(protocol, JSON.parse(s3));
50988
+ } catch {
50989
+ return 0;
50990
+ }
50991
+ }
50992
+
50921
50993
  // src/web/index.ts
50922
50994
  import { readFileSync as readFileSync3 } from "fs";
50923
50995
  import { dirname as dirname4, join as join3 } from "path";
@@ -57290,7 +57362,7 @@ function emergencyNudge(nudge, escalationPct = EMERGENCY_NUDGE_ESCALATION_PCT) {
57290
57362
  function clampOutgoingOutput(rebuilt, field, ctx, sessionId, log2) {
57291
57363
  const raw = rebuilt[field];
57292
57364
  if (typeof raw !== "number") return;
57293
- const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens);
57365
+ const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens) + ctx.imageTokens;
57294
57366
  const capped = clampOutputBudget(raw, inputEstimate, ctx.nativeWindow);
57295
57367
  if (capped !== void 0) {
57296
57368
  rebuilt[field] = capped;
@@ -57355,7 +57427,7 @@ function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session,
57355
57427
  processedMessages = [];
57356
57428
  }
57357
57429
  const rebuilt = { ...parsed, messages: rebuiltMessages, tools: toolsOut };
57358
- clampOutgoingOutput(rebuilt, typeof parsed.max_completion_tokens === "number" ? "max_completion_tokens" : "max_tokens", { systemText: openaiSystemText, tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, nativeWindow }, sessionId, log2);
57430
+ clampOutgoingOutput(rebuilt, typeof parsed.max_completion_tokens === "number" ? "max_completion_tokens" : "max_tokens", { systemText: openaiSystemText, tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, nativeWindow, imageTokens: imageTokensInParsedBody("openai", rebuilt) }, sessionId, log2);
57359
57431
  delete rebuilt.prompt_cache_retention;
57360
57432
  if (stream2 && rebuilt.stream_options === void 0) {
57361
57433
  rebuilt.stream_options = { include_usage: true };
@@ -57473,7 +57545,7 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
57473
57545
  }
57474
57546
  const rebuilt = { ...parsed, input: rebuiltInput, tools: toolsOut };
57475
57547
  if (!isCompactionTrigger) {
57476
- clampOutgoingOutput(rebuilt, "max_output_tokens", { systemText: (responsesProjection?.systemParts ?? []).join("\n"), tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, nativeWindow }, sessionId, log2);
57548
+ clampOutgoingOutput(rebuilt, "max_output_tokens", { systemText: (responsesProjection?.systemParts ?? []).join("\n"), tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, nativeWindow, imageTokens: imageTokensInParsedBody("responses", rebuilt) }, sessionId, log2);
57477
57549
  }
57478
57550
  const promptCacheKey = resolvePromptCacheKey(
57479
57551
  rebuilt.prompt_cache_key,
@@ -57698,11 +57770,13 @@ function isPreflightFailFast(outcome) {
57698
57770
  async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, core, config, model, route, affinity, log2, instanceId) {
57699
57771
  const session = prepared.session;
57700
57772
  const limit = config.modelContextLimit;
57701
- const payloadEstimate = estimateCoreMessages(prepared.processedMessages);
57773
+ const imageTokens = imageTokensInRawBody(prepared.protocol, prepared.body);
57774
+ const payloadEstimate = estimateCoreMessages(prepared.processedMessages) + imageTokens;
57702
57775
  const tokenCount = Math.max(session.stats.lastInputTokens, payloadEstimate);
57703
57776
  if (limit <= 0 || !model || tokenCount < limit) return prepared;
57704
57777
  const failFast = (status2, detail, retryable) => {
57705
- const message = `context ~${tokenCount} tokens exceeds the model window ${limit} (model=${model}) and preflight compression could not bring it under: ${detail}. The over-window payload was NOT forwarded.`;
57778
+ const imageNote = imageTokens >= limit ? ` Images alone account for ~${imageTokens} tokens (\u2265 window ${limit}); compression cannot remove them \u2014 shrink or remove the images, or raise the window.` : "";
57779
+ const message = `context ~${tokenCount} tokens exceeds the model window ${limit} (model=${model}) and preflight compression could not bring it under: ${detail}.` + imageNote + ` The over-window payload was NOT forwarded.`;
57706
57780
  log2("error", `[${session.id}] preflight fail-fast ${status2} (retryable=${retryable}): ${message}`);
57707
57781
  return { failFast: true, status: status2, message, retryable, respond: !res.writableEnded };
57708
57782
  };
@@ -57732,7 +57806,8 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
57732
57806
  model,
57733
57807
  proxyUrl,
57734
57808
  signal: clientAbort.signal,
57735
- log: log2
57809
+ log: log2,
57810
+ imageFloor: imageTokens
57736
57811
  },
57737
57812
  prepared.originalMessages
57738
57813
  );
@@ -57901,9 +57976,12 @@ ${hdrText}
57901
57976
  const info = inspectContextOverflow(upstream.status, errBody.toString("utf8"));
57902
57977
  if (info.isOverflow) {
57903
57978
  let reqModel;
57979
+ let rejectedImageTokens = 0;
57904
57980
  try {
57905
57981
  const rawBody = typeof prepared.body === "string" ? prepared.body : prepared.body.toString("utf8");
57906
- reqModel = JSON.parse(rawBody).model;
57982
+ const parsedBody = JSON.parse(rawBody);
57983
+ reqModel = typeof parsedBody.model === "string" ? parsedBody.model : void 0;
57984
+ rejectedImageTokens = imageTokensInParsedBody(prepared.protocol, parsedBody);
57907
57985
  } catch {
57908
57986
  reqModel = void 0;
57909
57987
  }
@@ -57915,7 +57993,7 @@ ${hdrText}
57915
57993
  s3.metadata.learnedContextLimits = learnedMap;
57916
57994
  log2("warn", `[${s3.id}] upstream context overflow \u2014 learned real window ${info.window} for ${reqModel ?? "(unknown model)"} (was ${prev ?? "unset"}); arming emergency shrink`);
57917
57995
  } else {
57918
- const payloadEstimate = estimateCoreMessages(prepared.processedMessages);
57996
+ const payloadEstimate = estimateCoreMessages(prepared.processedMessages) + rejectedImageTokens;
57919
57997
  const prev = (reqModel ? learnedMap[reqModel] : void 0) ?? s3.metadata.learnedContextLimit;
57920
57998
  if (payloadEstimate >= 1e3 && (prev === void 0 || payloadEstimate < prev)) {
57921
57999
  if (reqModel) learnedMap[reqModel] = payloadEstimate;