billion-context 0.1.111-pr.787.631 → 0.1.111

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
@@ -60869,7 +60869,7 @@ async function decodeRequestBody(contentEncoding, input, maxOutputBytes) {
60869
60869
  return { body, decoded: true };
60870
60870
  }
60871
60871
 
60872
- // src/server/observability.ts
60872
+ // src/server.ts
60873
60873
  function bodyDumpEnabled() {
60874
60874
  return process.env.ACP_DUMP_BODY === "1";
60875
60875
  }
@@ -60898,8 +60898,6 @@ function logUnrecognizedPath(log2, url) {
60898
60898
  function isModelDiscoveryPath(path20) {
60899
60899
  return path20.replace(/\/+$/, "").endsWith("/models");
60900
60900
  }
60901
-
60902
- // src/server/context-window.ts
60903
60901
  var BILI_HOP_HEADER = "x-bili-hop";
60904
60902
  function parseLauncherModelWindows(raw) {
60905
60903
  if (!raw) return {};
@@ -60935,8 +60933,6 @@ function anthropicBetaContextWindow(headers) {
60935
60933
  }
60936
60934
  return best;
60937
60935
  }
60938
-
60939
- // src/server/headers.ts
60940
60936
  function safeSessionId(id) {
60941
60937
  return (id ?? "unknown").replace(/[^a-zA-Z0-9._-]/g, "_");
60942
60938
  }
@@ -60978,175 +60974,6 @@ function buildForwardHeaders(headers) {
60978
60974
  out["content-type"] = "application/json";
60979
60975
  return out;
60980
60976
  }
60981
-
60982
- // src/server/side-request.ts
60983
- var SIDE_REQUEST_MAX_TOKENS = 200;
60984
- function isSideRequest(parsed) {
60985
- if (!parsed || typeof parsed !== "object") return false;
60986
- const p2 = parsed;
60987
- if (Array.isArray(p2.tools) && p2.tools.length > 0) return false;
60988
- const raw = p2.max_tokens ?? p2.max_completion_tokens ?? p2.max_output_tokens;
60989
- return typeof raw === "number" && raw > 0 && raw <= SIDE_REQUEST_MAX_TOKENS;
60990
- }
60991
- function outputBudgetField(parsed) {
60992
- if (!parsed || typeof parsed !== "object") return null;
60993
- const p2 = parsed;
60994
- for (const field of ["max_tokens", "max_completion_tokens", "max_output_tokens"]) {
60995
- if (typeof p2[field] === "number" && p2[field] > 0) return field;
60996
- }
60997
- return null;
60998
- }
60999
- function restoreOutputBudget(parsed, session, log2) {
61000
- const field = outputBudgetField(parsed);
61001
- if (!field) return;
61002
- const p2 = parsed;
61003
- const value = p2[field];
61004
- if (value > SIDE_REQUEST_MAX_TOKENS) {
61005
- session.metadata.outputBudgetHighWater = value;
61006
- return;
61007
- }
61008
- if (!Array.isArray(p2.tools) || p2.tools.length === 0) return;
61009
- const highWater = session.metadata.outputBudgetHighWater;
61010
- if (typeof highWater === "number" && highWater > SIDE_REQUEST_MAX_TOKENS) {
61011
- p2[field] = highWater;
61012
- log2("info", `[${session.id}] output budget restored ${value} -> ${highWater} (#546: client shrank it from its raw-history estimate)`);
61013
- }
61014
- }
61015
- var SIDE_REQUEST_GUARD_TOLERANCE = 1.15;
61016
- function sideRequestGuard(parsed, protocol, modelContextLimit, learnedLimit, imageBilling = "bytes") {
61017
- let limit = modelContextLimit;
61018
- if (typeof learnedLimit === "number" && learnedLimit > 0 && learnedLimit < limit) limit = learnedLimit;
61019
- const field = outputBudgetField(parsed);
61020
- const maxOut = field ? parsed[field] : 0;
61021
- if (limit > 0 && shouldReserveOutputHeadroom(protocol)) limit = reserveOutputHeadroom(limit, maxOut);
61022
- const estimate = estimateRawBodyTokens(parsed) + imageTokensInParsedBody(protocol, parsed, imageBilling);
61023
- return { blocked: limit > 0 && estimate >= limit * SIDE_REQUEST_GUARD_TOLERANCE, estimate, limit };
61024
- }
61025
-
61026
- // src/server/budget.ts
61027
- var OUTPUT_CLAMP_MARGIN_PCT = 0.05;
61028
- var OUTPUT_CLAMP_MIN_MARGIN = 2048;
61029
- var OUTPUT_CLAMP_FLOOR = 1024;
61030
- var EMERGENCY_NUDGE_ESCALATION_PCT = 0.7;
61031
- function countSystemAndToolsTokens(systemText, tools) {
61032
- return defaultCountTokens(systemText ?? "") + defaultCountTokens(JSON.stringify(tools ?? []));
61033
- }
61034
- function estimateInputTokens(processedMessages, systemText, tools, lastInputTokens) {
61035
- const est = estimateCoreMessages(processedMessages) + countSystemAndToolsTokens(systemText, tools);
61036
- return Math.max(lastInputTokens > 0 ? lastInputTokens : 0, est);
61037
- }
61038
- function estimateWireOverhead(protocol, body) {
61039
- let parsed;
61040
- try {
61041
- parsed = JSON.parse(typeof body === "string" ? body : body.toString("utf8"));
61042
- } catch {
61043
- return 0;
61044
- }
61045
- const sysRaw = protocol === "responses" ? parsed.instructions : parsed.system;
61046
- let sysText = "";
61047
- if (typeof sysRaw === "string") {
61048
- sysText = sysRaw;
61049
- } else if (Array.isArray(sysRaw)) {
61050
- sysText = sysRaw.map((part) => typeof part?.text === "string" ? part.text : "").join("\n");
61051
- }
61052
- if (protocol === "openai" && Array.isArray(parsed.messages)) {
61053
- const hoisted = parsed.messages.filter((m2) => m2.role === "system" || m2.role === "developer").map((m2) => typeof m2.content === "string" ? m2.content : "").join("\n");
61054
- sysText = sysText ? `${sysText}
61055
- ${hoisted}` : hoisted;
61056
- }
61057
- return defaultCountTokens(sysText) + defaultCountTokens(JSON.stringify(parsed.tools ?? []));
61058
- }
61059
- function clampOutputBudget(requested, inputEstimate, nativeWindow) {
61060
- const margin = Math.max(OUTPUT_CLAMP_MIN_MARGIN, Math.ceil(inputEstimate * OUTPUT_CLAMP_MARGIN_PCT));
61061
- const cap = nativeWindow - inputEstimate - margin;
61062
- if (cap < OUTPUT_CLAMP_FLOOR || cap >= requested) return void 0;
61063
- return cap;
61064
- }
61065
- function emergencyNudge(nudge, escalationPct = EMERGENCY_NUDGE_ESCALATION_PCT) {
61066
- if (!nudge || nudge.shouldInject) return false;
61067
- if (nudge.compressibleRanges.length === 0) return false;
61068
- return nudge.contextUsage >= escalationPct;
61069
- }
61070
- function clampOutgoingOutput(rebuilt, field, ctx, sessionId, log2) {
61071
- const raw = rebuilt[field];
61072
- if (typeof raw !== "number") return;
61073
- const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens) + ctx.imageTokens;
61074
- const capped = clampOutputBudget(raw, inputEstimate, ctx.nativeWindow);
61075
- if (capped !== void 0) {
61076
- rebuilt[field] = capped;
61077
- log2("info", `[${sessionId}] output budget clamped ${raw} -> ${capped} (input~${inputEstimate}, window=${ctx.nativeWindow}); prevents input+output overflow (#453)`);
61078
- }
61079
- }
61080
-
61081
- // src/server/stream-io.ts
61082
- async function readStreamToBuffer(stream2, maxBytes = 1 << 20) {
61083
- const reader = stream2.getReader();
61084
- const chunks = [];
61085
- let kept = 0;
61086
- try {
61087
- for (; ; ) {
61088
- const { done, value } = await reader.read();
61089
- if (done) break;
61090
- if (value && kept < maxBytes) {
61091
- const take = Math.min(value.length, maxBytes - kept);
61092
- chunks.push(Buffer.from(value.subarray(0, take)));
61093
- kept += take;
61094
- }
61095
- }
61096
- } finally {
61097
- reader.releaseLock();
61098
- }
61099
- return Buffer.concat(chunks);
61100
- }
61101
- function bufferToStream(buf) {
61102
- return new ReadableStream({
61103
- start(controller) {
61104
- controller.enqueue(new Uint8Array(buf));
61105
- controller.close();
61106
- }
61107
- });
61108
- }
61109
- async function pipeThrough(stream2, res) {
61110
- const reader = stream2.getReader();
61111
- try {
61112
- for (; ; ) {
61113
- const { done, value } = await reader.read();
61114
- if (done) break;
61115
- if (!res.write(Buffer.from(value))) {
61116
- await new Promise((r) => res.once("drain", () => r()));
61117
- }
61118
- }
61119
- } finally {
61120
- reader.releaseLock();
61121
- res.end();
61122
- }
61123
- }
61124
- async function dumpStreamToFile(stream2, dir, name) {
61125
- const { mkdirSync: mkdirSync7, createWriteStream: createWriteStream2 } = await import("fs");
61126
- const { join: join6 } = await import("path");
61127
- try {
61128
- mkdirSync7(dir, { recursive: true });
61129
- const ws2 = createWriteStream2(join6(dir, name));
61130
- ws2.on("error", (e) => {
61131
- logDumpFailure("SSE stream dump", e);
61132
- });
61133
- const reader = stream2.getReader();
61134
- try {
61135
- for (; ; ) {
61136
- const { done, value } = await reader.read();
61137
- if (done) break;
61138
- ws2.write(Buffer.from(value));
61139
- }
61140
- } finally {
61141
- reader.releaseLock();
61142
- ws2.end();
61143
- }
61144
- } catch (err2) {
61145
- logDumpFailure("SSE stream dump", err2);
61146
- }
61147
- }
61148
-
61149
- // src/server.ts
61150
60977
  function resolveUpstream(_opts, reqUrl, req) {
61151
60978
  const mitmUpstream = readMitmUpstream(req?.socket);
61152
60979
  if (mitmUpstream) {
@@ -61360,6 +61187,48 @@ Content-Length: ${Buffer.byteLength(body)}\r
61360
61187
  }
61361
61188
  return server;
61362
61189
  }
61190
+ var SIDE_REQUEST_MAX_TOKENS = 200;
61191
+ function isSideRequest(parsed) {
61192
+ if (!parsed || typeof parsed !== "object") return false;
61193
+ const p2 = parsed;
61194
+ if (Array.isArray(p2.tools) && p2.tools.length > 0) return false;
61195
+ const raw = p2.max_tokens ?? p2.max_completion_tokens ?? p2.max_output_tokens;
61196
+ return typeof raw === "number" && raw > 0 && raw <= SIDE_REQUEST_MAX_TOKENS;
61197
+ }
61198
+ function outputBudgetField(parsed) {
61199
+ if (!parsed || typeof parsed !== "object") return null;
61200
+ const p2 = parsed;
61201
+ for (const field of ["max_tokens", "max_completion_tokens", "max_output_tokens"]) {
61202
+ if (typeof p2[field] === "number" && p2[field] > 0) return field;
61203
+ }
61204
+ return null;
61205
+ }
61206
+ function restoreOutputBudget(parsed, session, log2) {
61207
+ const field = outputBudgetField(parsed);
61208
+ if (!field) return;
61209
+ const p2 = parsed;
61210
+ const value = p2[field];
61211
+ if (value > SIDE_REQUEST_MAX_TOKENS) {
61212
+ session.metadata.outputBudgetHighWater = value;
61213
+ return;
61214
+ }
61215
+ if (!Array.isArray(p2.tools) || p2.tools.length === 0) return;
61216
+ const highWater = session.metadata.outputBudgetHighWater;
61217
+ if (typeof highWater === "number" && highWater > SIDE_REQUEST_MAX_TOKENS) {
61218
+ p2[field] = highWater;
61219
+ log2("info", `[${session.id}] output budget restored ${value} -> ${highWater} (#546: client shrank it from its raw-history estimate)`);
61220
+ }
61221
+ }
61222
+ var SIDE_REQUEST_GUARD_TOLERANCE = 1.15;
61223
+ function sideRequestGuard(parsed, protocol, modelContextLimit, learnedLimit, imageBilling = "bytes") {
61224
+ let limit = modelContextLimit;
61225
+ if (typeof learnedLimit === "number" && learnedLimit > 0 && learnedLimit < limit) limit = learnedLimit;
61226
+ const field = outputBudgetField(parsed);
61227
+ const maxOut = field ? parsed[field] : 0;
61228
+ if (limit > 0 && shouldReserveOutputHeadroom(protocol)) limit = reserveOutputHeadroom(limit, maxOut);
61229
+ const estimate = estimateRawBodyTokens(parsed) + imageTokensInParsedBody(protocol, parsed, imageBilling);
61230
+ return { blocked: limit > 0 && estimate >= limit * SIDE_REQUEST_GUARD_TOLERANCE, estimate, limit };
61231
+ }
61363
61232
  function imageBillingFor(opts, upstreamUrl) {
61364
61233
  const env = process.env.BILI_IMAGE_BILLING;
61365
61234
  const configured = env === "pixels" || env === "bytes" ? env : findRoute(opts.routes, upstreamUrl)?.imageBilling ?? opts.imageBilling ?? "auto";
@@ -62186,6 +62055,59 @@ function prepareAnthropic(parsed, req, opts, core, config, prompts, surface, log
62186
62055
  delete rebuilt.prompt_cache_key;
62187
62056
  return { body: JSON.stringify(rebuilt), session, processedMessages, originalMessages, anthropicSystem: parsed.system, protocol: "anthropic", stream: stream2, compressInjected: injectTools, pluginMode, nudge, prompts, surface, renderTags: "text-only" };
62188
62057
  }
62058
+ var OUTPUT_CLAMP_MARGIN_PCT = 0.05;
62059
+ var OUTPUT_CLAMP_MIN_MARGIN = 2048;
62060
+ var OUTPUT_CLAMP_FLOOR = 1024;
62061
+ var EMERGENCY_NUDGE_ESCALATION_PCT = 0.7;
62062
+ function countSystemAndToolsTokens(systemText, tools) {
62063
+ return defaultCountTokens(systemText ?? "") + defaultCountTokens(JSON.stringify(tools ?? []));
62064
+ }
62065
+ function estimateInputTokens(processedMessages, systemText, tools, lastInputTokens) {
62066
+ const est = estimateCoreMessages(processedMessages) + countSystemAndToolsTokens(systemText, tools);
62067
+ return Math.max(lastInputTokens > 0 ? lastInputTokens : 0, est);
62068
+ }
62069
+ function estimateWireOverhead(protocol, body) {
62070
+ let parsed;
62071
+ try {
62072
+ parsed = JSON.parse(typeof body === "string" ? body : body.toString("utf8"));
62073
+ } catch {
62074
+ return 0;
62075
+ }
62076
+ const sysRaw = protocol === "responses" ? parsed.instructions : parsed.system;
62077
+ let sysText = "";
62078
+ if (typeof sysRaw === "string") {
62079
+ sysText = sysRaw;
62080
+ } else if (Array.isArray(sysRaw)) {
62081
+ sysText = sysRaw.map((part) => typeof part?.text === "string" ? part.text : "").join("\n");
62082
+ }
62083
+ if (protocol === "openai" && Array.isArray(parsed.messages)) {
62084
+ const hoisted = parsed.messages.filter((m2) => m2.role === "system" || m2.role === "developer").map((m2) => typeof m2.content === "string" ? m2.content : "").join("\n");
62085
+ sysText = sysText ? `${sysText}
62086
+ ${hoisted}` : hoisted;
62087
+ }
62088
+ return defaultCountTokens(sysText) + defaultCountTokens(JSON.stringify(parsed.tools ?? []));
62089
+ }
62090
+ function clampOutputBudget(requested, inputEstimate, nativeWindow) {
62091
+ const margin = Math.max(OUTPUT_CLAMP_MIN_MARGIN, Math.ceil(inputEstimate * OUTPUT_CLAMP_MARGIN_PCT));
62092
+ const cap = nativeWindow - inputEstimate - margin;
62093
+ if (cap < OUTPUT_CLAMP_FLOOR || cap >= requested) return void 0;
62094
+ return cap;
62095
+ }
62096
+ function emergencyNudge(nudge, escalationPct = EMERGENCY_NUDGE_ESCALATION_PCT) {
62097
+ if (!nudge || nudge.shouldInject) return false;
62098
+ if (nudge.compressibleRanges.length === 0) return false;
62099
+ return nudge.contextUsage >= escalationPct;
62100
+ }
62101
+ function clampOutgoingOutput(rebuilt, field, ctx, sessionId, log2) {
62102
+ const raw = rebuilt[field];
62103
+ if (typeof raw !== "number") return;
62104
+ const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens) + ctx.imageTokens;
62105
+ const capped = clampOutputBudget(raw, inputEstimate, ctx.nativeWindow);
62106
+ if (capped !== void 0) {
62107
+ rebuilt[field] = capped;
62108
+ log2("info", `[${sessionId}] output budget clamped ${raw} -> ${capped} (input~${inputEstimate}, window=${ctx.nativeWindow}); prevents input+output overflow (#453)`);
62109
+ }
62110
+ }
62189
62111
  function prepareOpenai(parsed, req, opts, core, config, prompts, surface, log2, session, pluginMode, upstreamOrigin, nativeWindow, reasoning, billingUpstream) {
62190
62112
  const sessionId = session.id;
62191
62113
  const stream2 = parsed.stream === true;
@@ -63367,6 +63289,33 @@ ${buildAbsorbSystemPrompt(absorbToolName(loopConfig))}` : "";
63367
63289
  clearUpstreamTimer();
63368
63290
  }
63369
63291
  }
63292
+ async function readStreamToBuffer(stream2, maxBytes = 1 << 20) {
63293
+ const reader = stream2.getReader();
63294
+ const chunks = [];
63295
+ let kept = 0;
63296
+ try {
63297
+ for (; ; ) {
63298
+ const { done, value } = await reader.read();
63299
+ if (done) break;
63300
+ if (value && kept < maxBytes) {
63301
+ const take = Math.min(value.length, maxBytes - kept);
63302
+ chunks.push(Buffer.from(value.subarray(0, take)));
63303
+ kept += take;
63304
+ }
63305
+ }
63306
+ } finally {
63307
+ reader.releaseLock();
63308
+ }
63309
+ return Buffer.concat(chunks);
63310
+ }
63311
+ function bufferToStream(buf) {
63312
+ return new ReadableStream({
63313
+ start(controller) {
63314
+ controller.enqueue(new Uint8Array(buf));
63315
+ controller.close();
63316
+ }
63317
+ });
63318
+ }
63370
63319
  async function resolveFakeCompletion(stream2, opts) {
63371
63320
  let buffer = await readStreamToBuffer(stream2, fakeBufCap());
63372
63321
  const max = maxFakeCompletionRetries();
@@ -63411,6 +63360,45 @@ async function resolveFakeCompletion(stream2, opts) {
63411
63360
  markDirty(opts.session);
63412
63361
  return buffer;
63413
63362
  }
63363
+ async function pipeThrough(stream2, res) {
63364
+ const reader = stream2.getReader();
63365
+ try {
63366
+ for (; ; ) {
63367
+ const { done, value } = await reader.read();
63368
+ if (done) break;
63369
+ if (!res.write(Buffer.from(value))) {
63370
+ await new Promise((r) => res.once("drain", () => r()));
63371
+ }
63372
+ }
63373
+ } finally {
63374
+ reader.releaseLock();
63375
+ res.end();
63376
+ }
63377
+ }
63378
+ async function dumpStreamToFile(stream2, dir, name) {
63379
+ const { mkdirSync: mkdirSync7, createWriteStream: createWriteStream2 } = await import("fs");
63380
+ const { join: join6 } = await import("path");
63381
+ try {
63382
+ mkdirSync7(dir, { recursive: true });
63383
+ const ws2 = createWriteStream2(join6(dir, name));
63384
+ ws2.on("error", (e) => {
63385
+ logDumpFailure("SSE stream dump", e);
63386
+ });
63387
+ const reader = stream2.getReader();
63388
+ try {
63389
+ for (; ; ) {
63390
+ const { done, value } = await reader.read();
63391
+ if (done) break;
63392
+ ws2.write(Buffer.from(value));
63393
+ }
63394
+ } finally {
63395
+ reader.releaseLock();
63396
+ ws2.end();
63397
+ }
63398
+ } catch (err2) {
63399
+ logDumpFailure("SSE stream dump", err2);
63400
+ }
63401
+ }
63414
63402
  function deriveTitle(messages) {
63415
63403
  for (const m2 of messages) {
63416
63404
  if (m2.role !== "user" || m2.contentType !== "text") continue;