billion-context 0.1.76 → 0.1.77-pr.493.322

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";
@@ -51945,6 +52017,7 @@ var CONTEXT_OVERFLOW_PATTERNS = [
51945
52017
  /maximum context length/i,
51946
52018
  /max context length/i,
51947
52019
  /maximum context size/i,
52020
+ /longer than the model'?s context length/i,
51948
52021
  /exceeds the context window/i,
51949
52022
  /out of room in the model/i,
51950
52023
  /exceeded model token limit/i,
@@ -51961,7 +52034,7 @@ function toTokenNumber(s3) {
51961
52034
  function parseOverflowWindow(text) {
51962
52035
  let m2 = text.match(/>\s*(\d[\d,]*)\s*maximum/i);
51963
52036
  if (m2) return toTokenNumber(m2[1]);
51964
- m2 = text.match(/maximum context length is (\d[\d,]*)/i) ?? text.match(/maximum context length of (\d[\d,]*)/i) ?? text.match(/maximum context size (?:is|of) (\d[\d,]*)/i) ?? text.match(/(?:maximum|max)\s+(?:context\s+)?length\s+(?:is\s+)?(\d[\d,]*)/i) ?? text.match(/limit of (\d[\d,]*)\s*token/i) ?? text.match(/(\d[\d,]*)\s*maximum\b/i);
52037
+ m2 = text.match(/maximum context length is (\d[\d,]*)/i) ?? text.match(/maximum context length of (\d[\d,]*)/i) ?? text.match(/maximum context size (?:is|of) (\d[\d,]*)/i) ?? text.match(/(?:maximum|max)\s+(?:context\s+)?length\s+(?:is\s+)?(\d[\d,]*)/i) ?? text.match(/context length\s*\((\d[\d,]*)\s*token/i) ?? text.match(/limit of (\d[\d,]*)\s*token/i) ?? text.match(/(\d[\d,]*)\s*maximum\b/i);
51965
52038
  if (m2) return toTokenNumber(m2[1]);
51966
52039
  return void 0;
51967
52040
  }
@@ -55344,13 +55417,20 @@ function loadClientConfig(env, cwd) {
55344
55417
  config.dsh = readDshConfig(resolveDshHome(env));
55345
55418
  return config;
55346
55419
  }
55347
- function collectModelWindows(config) {
55420
+ function collectModelWindows(config, scope) {
55348
55421
  const out = {};
55349
55422
  const add = (wins) => {
55350
55423
  for (const w2 of wins ?? []) {
55351
55424
  if (!out[w2.id] || w2.contextWindow > out[w2.id]) out[w2.id] = w2.contextWindow;
55352
55425
  }
55353
55426
  };
55427
+ if (scope) {
55428
+ if (scope === "codex") add(config.codex?.modelWindows);
55429
+ else if (scope === "pi") for (const p2 of Object.values(config.pi?.providers ?? {})) add(p2.models);
55430
+ else if (scope === "omp") for (const p2 of Object.values(config.omp?.providers ?? {})) add(p2.models);
55431
+ else if (scope === "opencode") for (const p2 of Object.values(config.opencode?.providers ?? {})) add(p2.models);
55432
+ return out;
55433
+ }
55354
55434
  for (const p2 of Object.values(config.pi?.providers ?? {})) add(p2.models);
55355
55435
  for (const p2 of Object.values(config.omp?.providers ?? {})) add(p2.models);
55356
55436
  for (const p2 of Object.values(config.opencode?.providers ?? {})) add(p2.models);
@@ -57290,7 +57370,7 @@ function emergencyNudge(nudge, escalationPct = EMERGENCY_NUDGE_ESCALATION_PCT) {
57290
57370
  function clampOutgoingOutput(rebuilt, field, ctx, sessionId, log2) {
57291
57371
  const raw = rebuilt[field];
57292
57372
  if (typeof raw !== "number") return;
57293
- const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens);
57373
+ const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens) + ctx.imageTokens;
57294
57374
  const capped = clampOutputBudget(raw, inputEstimate, ctx.nativeWindow);
57295
57375
  if (capped !== void 0) {
57296
57376
  rebuilt[field] = capped;
@@ -57355,7 +57435,7 @@ function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session,
57355
57435
  processedMessages = [];
57356
57436
  }
57357
57437
  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);
57438
+ 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
57439
  delete rebuilt.prompt_cache_retention;
57360
57440
  if (stream2 && rebuilt.stream_options === void 0) {
57361
57441
  rebuilt.stream_options = { include_usage: true };
@@ -57473,7 +57553,7 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
57473
57553
  }
57474
57554
  const rebuilt = { ...parsed, input: rebuiltInput, tools: toolsOut };
57475
57555
  if (!isCompactionTrigger) {
57476
- clampOutgoingOutput(rebuilt, "max_output_tokens", { systemText: (responsesProjection?.systemParts ?? []).join("\n"), tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, nativeWindow }, sessionId, log2);
57556
+ 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
57557
  }
57478
57558
  const promptCacheKey = resolvePromptCacheKey(
57479
57559
  rebuilt.prompt_cache_key,
@@ -57698,11 +57778,13 @@ function isPreflightFailFast(outcome) {
57698
57778
  async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, core, config, model, route, affinity, log2, instanceId) {
57699
57779
  const session = prepared.session;
57700
57780
  const limit = config.modelContextLimit;
57701
- const payloadEstimate = estimateCoreMessages(prepared.processedMessages);
57781
+ const imageTokens = imageTokensInRawBody(prepared.protocol, prepared.body);
57782
+ const payloadEstimate = estimateCoreMessages(prepared.processedMessages) + imageTokens;
57702
57783
  const tokenCount = Math.max(session.stats.lastInputTokens, payloadEstimate);
57703
57784
  if (limit <= 0 || !model || tokenCount < limit) return prepared;
57704
57785
  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.`;
57786
+ 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.` : "";
57787
+ 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
57788
  log2("error", `[${session.id}] preflight fail-fast ${status2} (retryable=${retryable}): ${message}`);
57707
57789
  return { failFast: true, status: status2, message, retryable, respond: !res.writableEnded };
57708
57790
  };
@@ -57732,7 +57814,8 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
57732
57814
  model,
57733
57815
  proxyUrl,
57734
57816
  signal: clientAbort.signal,
57735
- log: log2
57817
+ log: log2,
57818
+ imageFloor: imageTokens
57736
57819
  },
57737
57820
  prepared.originalMessages
57738
57821
  );
@@ -57901,9 +57984,12 @@ ${hdrText}
57901
57984
  const info = inspectContextOverflow(upstream.status, errBody.toString("utf8"));
57902
57985
  if (info.isOverflow) {
57903
57986
  let reqModel;
57987
+ let rejectedImageTokens = 0;
57904
57988
  try {
57905
57989
  const rawBody = typeof prepared.body === "string" ? prepared.body : prepared.body.toString("utf8");
57906
- reqModel = JSON.parse(rawBody).model;
57990
+ const parsedBody = JSON.parse(rawBody);
57991
+ reqModel = typeof parsedBody.model === "string" ? parsedBody.model : void 0;
57992
+ rejectedImageTokens = imageTokensInParsedBody(prepared.protocol, parsedBody);
57907
57993
  } catch {
57908
57994
  reqModel = void 0;
57909
57995
  }
@@ -57915,7 +58001,7 @@ ${hdrText}
57915
58001
  s3.metadata.learnedContextLimits = learnedMap;
57916
58002
  log2("warn", `[${s3.id}] upstream context overflow \u2014 learned real window ${info.window} for ${reqModel ?? "(unknown model)"} (was ${prev ?? "unset"}); arming emergency shrink`);
57917
58003
  } else {
57918
- const payloadEstimate = estimateCoreMessages(prepared.processedMessages);
58004
+ const payloadEstimate = estimateCoreMessages(prepared.processedMessages) + rejectedImageTokens;
57919
58005
  const prev = (reqModel ? learnedMap[reqModel] : void 0) ?? s3.metadata.learnedContextLimit;
57920
58006
  if (payloadEstimate >= 1e3 && (prev === void 0 || payloadEstimate < prev)) {
57921
58007
  if (reqModel) learnedMap[reqModel] = payloadEstimate;
@@ -63640,7 +63726,7 @@ async function runLaunch(params, deps = {}) {
63640
63726
  const routes = discoverRoutes(base, config);
63641
63727
  const biliRoutes = loadRoutes(process.env);
63642
63728
  const domains = dedupeInOrder([...routes.httpsDomains, ...params.mitmDomains ?? []]);
63643
- const handle2 = await ensureProxyRunning({ host, port, passthrough, debug, mitmDomains: domains, modelWindows: collectModelWindows(config) }, deps);
63729
+ const handle2 = await ensureProxyRunning({ host, port, passthrough, debug, mitmDomains: domains, modelWindows: collectModelWindows(config, base) }, deps);
63644
63730
  console.error(
63645
63731
  `bili: started proxy at ${handle2.origin} (MITM domains: ${domains.length ? domains.join(", ") : "defaults"})` + (routes.httpRewrites.length > 0 ? ` (HTTP /bili/ rewrites: ${routes.httpRewrites.length})` : "") + (routes.httpsRewrites.length > 0 ? ` (HTTPS cert rewrites: ${routes.httpsRewrites.length})` : "") + (params.client === "pi-test" ? " (no extensions)" : "")
63646
63732
  );
@@ -63815,7 +63901,7 @@ async function runTestPi(params, deps = {}) {
63815
63901
  ...discoverDomains("pi", config),
63816
63902
  ...params.mitmDomains ?? []
63817
63903
  ]);
63818
- const handle2 = await ensureProxyRunning({ host, port, passthrough, debug, mitmDomains: domains, modelWindows: collectModelWindows(config) }, deps);
63904
+ const handle2 = await ensureProxyRunning({ host, port, passthrough, debug, mitmDomains: domains, modelWindows: collectModelWindows(config, "pi") }, deps);
63819
63905
  console.error(
63820
63906
  `bili: started proxy at ${handle2.origin} (MITM domains: ${domains.length ? domains.join(", ") : "defaults"})`
63821
63907
  );