billion-context 0.1.61 → 0.1.62

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
@@ -43649,7 +43649,7 @@ function formatRanges(compressible, protectedRanges) {
43649
43649
  if (compressible.length === 0 && protectedRanges.length === 0) {
43650
43650
  return "[No specific ranges detected \u2014 compress any consumed content.]";
43651
43651
  }
43652
- const refNum3 = (ref) => {
43652
+ const refNum4 = (ref) => {
43653
43653
  const m2 = ref.match(/\d+/);
43654
43654
  return m2 ? parseInt(m2[0], 10) : 0;
43655
43655
  };
@@ -43658,8 +43658,8 @@ function formatRanges(compressible, protectedRanges) {
43658
43658
  entries.push({
43659
43659
  startRef: r.startRef,
43660
43660
  endRef: r.endRef,
43661
- startNum: refNum3(r.startRef),
43662
- endNum: refNum3(r.endRef),
43661
+ startNum: refNum4(r.startRef),
43662
+ endNum: refNum4(r.endRef),
43663
43663
  count: r.count,
43664
43664
  tokens: r.tokens,
43665
43665
  toolPct: r.toolPct,
@@ -43676,8 +43676,8 @@ function formatRanges(compressible, protectedRanges) {
43676
43676
  entries.push({
43677
43677
  startRef: r.startRef,
43678
43678
  endRef: r.endRef,
43679
- startNum: refNum3(r.startRef),
43680
- endNum: refNum3(r.endRef),
43679
+ startNum: refNum4(r.startRef),
43680
+ endNum: refNum4(r.endRef),
43681
43681
  count: r.count,
43682
43682
  tokens: r.tokens,
43683
43683
  toolPct: 0,
@@ -47033,12 +47033,15 @@ function caDir() {
47033
47033
  }
47034
47034
 
47035
47035
  // src/logger.ts
47036
- import { createWriteStream, mkdirSync, statSync, renameSync } from "fs";
47036
+ import { createWriteStream, fstatSync, mkdirSync, statSync, renameSync } from "fs";
47037
47037
  import path2 from "path";
47038
47038
  var MAX_BYTES = 10 * 1024 * 1024;
47039
47039
  var stream;
47040
+ var streamFd;
47040
47041
  var logPath;
47041
47042
  var bytesWritten = 0;
47043
+ var reopenWarned = false;
47044
+ var capture = null;
47042
47045
  function openStream(file) {
47043
47046
  mkdirSync(path2.dirname(file), { recursive: true });
47044
47047
  let existingSize = 0;
@@ -47054,23 +47057,69 @@ function openStream(file) {
47054
47057
  } catch {
47055
47058
  }
47056
47059
  const s3 = createWriteStream(file, { flags: "a" });
47060
+ s3.on("open", (fd) => {
47061
+ if (stream === s3) streamFd = fd;
47062
+ });
47057
47063
  s3.on("error", () => {
47058
47064
  try {
47059
47065
  s3.destroy();
47060
47066
  } catch {
47061
47067
  }
47062
- if (stream === s3) stream = void 0;
47068
+ if (stream === s3) {
47069
+ stream = void 0;
47070
+ streamFd = void 0;
47071
+ }
47063
47072
  });
47064
47073
  bytesWritten = existingSize;
47065
47074
  return s3;
47066
47075
  }
47076
+ function isOrphaned(s3) {
47077
+ if (stream === s3 && streamFd === void 0) return false;
47078
+ try {
47079
+ const fdStat = fstatSync(streamFd);
47080
+ const pathStat = statSync(logPath);
47081
+ return fdStat.ino !== pathStat.ino || fdStat.dev !== pathStat.dev;
47082
+ } catch {
47083
+ return true;
47084
+ }
47085
+ }
47086
+ function closeQuietly(s3) {
47087
+ try {
47088
+ s3.end();
47089
+ } catch {
47090
+ }
47091
+ }
47092
+ function warnReopenFailed(err2) {
47093
+ if (reopenWarned) return;
47094
+ reopenWarned = true;
47095
+ const reason = err2 instanceof Error ? err2.message : String(err2);
47096
+ const msg = `log file ${logPath ?? "?"} unavailable (${reason}); continuing with stderr-only logging`;
47097
+ if (capture) {
47098
+ try {
47099
+ capture("warn", msg);
47100
+ } catch {
47101
+ }
47102
+ }
47103
+ try {
47104
+ process.stderr.write(`${(/* @__PURE__ */ new Date()).toISOString()} [warn] ${msg}
47105
+ `);
47106
+ } catch {
47107
+ }
47108
+ }
47067
47109
  function getStream() {
47068
47110
  if (!logPath) return void 0;
47069
- if (stream && stream.writable) return stream;
47111
+ if (stream && stream.writable && !isOrphaned(stream)) return stream;
47112
+ if (stream) closeQuietly(stream);
47113
+ stream = void 0;
47114
+ streamFd = void 0;
47070
47115
  try {
47071
47116
  stream = openStream(logPath);
47117
+ reopenWarned = false;
47072
47118
  return stream;
47073
- } catch {
47119
+ } catch (err2) {
47120
+ stream = void 0;
47121
+ streamFd = void 0;
47122
+ warnReopenFailed(err2);
47074
47123
  return void 0;
47075
47124
  }
47076
47125
  }
@@ -47081,10 +47130,9 @@ function configureLogger(file) {
47081
47130
  return void 0;
47082
47131
  }
47083
47132
  logPath = file;
47084
- stream = openStream(file);
47133
+ stream = getStream();
47085
47134
  return file;
47086
47135
  }
47087
- var capture = null;
47088
47136
  var log = (level, msg) => {
47089
47137
  if (capture) {
47090
47138
  try {
@@ -47102,22 +47150,21 @@ var log = (level, msg) => {
47102
47150
  let s3 = getStream();
47103
47151
  if (s3) {
47104
47152
  if (bytesWritten >= MAX_BYTES) {
47105
- try {
47106
- s3.end();
47107
- } catch {
47108
- }
47109
- stream = openStream(logPath);
47110
- s3 = stream;
47153
+ closeQuietly(s3);
47154
+ stream = void 0;
47155
+ s3 = getStream();
47111
47156
  }
47112
- try {
47113
- s3.write(line);
47114
- bytesWritten += Buffer.byteLength(line);
47115
- } catch {
47157
+ if (s3) {
47116
47158
  try {
47117
- s3.destroy();
47159
+ s3.write(line);
47160
+ bytesWritten += Buffer.byteLength(line);
47118
47161
  } catch {
47162
+ try {
47163
+ s3.destroy();
47164
+ } catch {
47165
+ }
47166
+ stream = void 0;
47119
47167
  }
47120
- stream = void 0;
47121
47168
  }
47122
47169
  }
47123
47170
  };
@@ -47129,6 +47176,7 @@ function closeLogger() {
47129
47176
  }
47130
47177
  }
47131
47178
  stream = void 0;
47179
+ streamFd = void 0;
47132
47180
  bytesWritten = 0;
47133
47181
  }
47134
47182
 
@@ -48017,6 +48065,10 @@ function replayBaseDelayMs() {
48017
48065
  const raw = Number(process.env.BILI_REPLAY_RETRY_BASE_MS);
48018
48066
  return Number.isFinite(raw) && raw >= 0 ? raw : 1500;
48019
48067
  }
48068
+ function maxShrinkPerCompress() {
48069
+ const raw = Number(process.env.BILI_MAX_SHRINK_PER_COMPRESS);
48070
+ return Number.isFinite(raw) && raw > 0 && raw <= 1 ? raw : void 0;
48071
+ }
48020
48072
  function replayBackoffMs(attempt) {
48021
48073
  return replayBaseDelayMs() * 2 ** (attempt - 1);
48022
48074
  }
@@ -49592,6 +49644,10 @@ function getStore() {
49592
49644
  }
49593
49645
 
49594
49646
  // src/session.ts
49647
+ function lastCompressSuffix(info) {
49648
+ if (!info) return "";
49649
+ return ` [after compress: shrink ${Math.round(info.shrinkRatio * 100)}% foldPoint=${info.foldPoint} blocks=${info.blocks} ~${info.tokensCompressed}tok]`;
49650
+ }
49595
49651
  var sessions = /* @__PURE__ */ new Map();
49596
49652
  var MAX_SESSIONS = Math.max(1, Number.parseInt(process.env.BILI_MAX_SESSIONS ?? "256", 10) || 256);
49597
49653
  var initialized = false;
@@ -49745,6 +49801,11 @@ function parseCompressInput(input, callId) {
49745
49801
  }
49746
49802
  return ranges;
49747
49803
  }
49804
+ var STAGED_COMPRESS_GUIDANCE = "\n\n[Smooth-transition guidance: when you compress, prefer a SMALLER, TAIL-biased range \u2014 compress the most recent large content and keep the stable prefix (the earliest messages) intact. A large single rewrite changes the request shape sharply and can trip provider risk-control; smaller tail-biased folds keep the prefix cache alive and the transition gentle.]";
49805
+ function withStagedCompressGuidance(text) {
49806
+ if (maxShrinkPerCompress() === void 0) return text;
49807
+ return text + STAGED_COMPRESS_GUIDANCE;
49808
+ }
49748
49809
 
49749
49810
  // src/decompress-shared.ts
49750
49811
  import { mkdirSync as mkdirSync3, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
@@ -50019,6 +50080,9 @@ ${lines.join("\n\n")}`;
50019
50080
  }
50020
50081
  return `[Unknown proxy tool: ${toolName}]`;
50021
50082
  }
50083
+ function refNum2(ref) {
50084
+ return Number(ref.replace(/\D/g, "")) || 0;
50085
+ }
50022
50086
  function applyRanges(ranges, ctx) {
50023
50087
  if (ranges.length === 0) {
50024
50088
  ctx.log("[acp-proxy: compress call had no valid ranges; nothing compressed.]");
@@ -50057,8 +50121,17 @@ function applyRanges(ranges, ctx) {
50057
50121
  ctx.log(`[acp-proxy: compress FAILED ${detail} \u2192 0 blocks. ${errs}]`);
50058
50122
  return `[Compression FAILED: ${errs}]`;
50059
50123
  }
50124
+ const preContext = ctx.session.stats.lastInputTokens;
50125
+ const shrinkRatio = preContext > 0 ? r.tokensCompressed / preContext : 0;
50126
+ const foldPoint = [...ranges].sort((a, b2) => refNum2(a.startRef) - refNum2(b2.startRef))[0]?.startRef ?? "unknown";
50127
+ ctx.session.lastCompress = { at: Date.now(), shrinkRatio, foldPoint, blocks: r.blocksCreated, tokensCompressed: r.tokensCompressed };
50128
+ ctx.log(`[acp-compress-obs] shrink ${Math.round(shrinkRatio * 100)}% (~${r.tokensCompressed}/${preContext} tok) foldPoint=${foldPoint} blocks=${r.blocksCreated}`);
50060
50129
  const warn = r.warnings.length > 0 ? ` ${r.warnings.join("; ")}` : "";
50061
- const msg = `[Compressed ${detail} \u2192 ${r.blocksCreated} block(s), ~${r.tokensCompressed} tokens saved.${warn}]`;
50130
+ let msg = `[Compressed ${detail} \u2192 ${r.blocksCreated} block(s), ~${r.tokensCompressed} tokens saved.${warn}]`;
50131
+ const maxShrink = maxShrinkPerCompress();
50132
+ if (maxShrink !== void 0 && shrinkRatio > maxShrink) {
50133
+ msg += ` [Staged-compress: this rewrite shrank context ${Math.round(shrinkRatio * 100)}%, above your ${Math.round(maxShrink * 100)}% per-compress target \u2014 the shape that trips provider risk-control (3007). Next time compress a SMALLER, TAIL-biased range (the most recent large content) and keep the stable prefix intact.]`;
50134
+ }
50062
50135
  ctx.log(`[acp-proxy: ${msg}]`);
50063
50136
  ctx.session.stats.compressCreditTokens = (ctx.session.stats.compressCreditTokens ?? 0) + r.tokensCompressed;
50064
50137
  ctx.session.stats.lastInputTokens = Math.max(0, ctx.session.stats.lastInputTokens - r.tokensCompressed);
@@ -50116,7 +50189,7 @@ function refMaps(messages, state) {
50116
50189
  });
50117
50190
  return { refToIdx, idxToRef };
50118
50191
  }
50119
- function refNum2(ref) {
50192
+ function refNum3(ref) {
50120
50193
  return Number(ref.replace(/\D/g, "")) || 0;
50121
50194
  }
50122
50195
  function estimateCoreMessages(messages) {
@@ -50206,7 +50279,9 @@ TASK: The conversation segment below (messages ${startRef}\u2013${endRef}) must
50206
50279
  },
50207
50280
  void 0,
50208
50281
  deps.signal,
50209
- (info) => deps.log("warn", `[preflight] summary attempt ${info.attempt} got HTTP ${info.status}; retrying in ${info.delayMs}ms`)
50282
+ (info) => {
50283
+ deps.log("warn", `[preflight] summary attempt ${info.attempt} got HTTP ${info.status}; retrying in ${info.delayMs}ms${lastCompressSuffix(deps.session.lastCompress)}`);
50284
+ }
50210
50285
  );
50211
50286
  try {
50212
50287
  const text = await response.text();
@@ -50260,7 +50335,7 @@ async function preflightCompress(deps, messages) {
50260
50335
  failure = { kind: "exhausted", detail: "no compressible ranges remain in the conversation" };
50261
50336
  break;
50262
50337
  }
50263
- const range = [...ranges].sort((a, b2) => refNum2(a.startRef) - refNum2(b2.startRef))[0];
50338
+ const range = [...ranges].sort((a, b2) => refNum3(a.startRef) - refNum3(b2.startRef))[0];
50264
50339
  const { refToIdx } = refMaps(messages, deps.session.state);
50265
50340
  const startIdx = refToIdx.get(range.startRef);
50266
50341
  const endIdx = refToIdx.get(range.endRef);
@@ -50914,8 +50989,9 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
50914
50989
  void 0,
50915
50990
  signal,
50916
50991
  (info) => {
50917
- ctx.log(`[acp-proxy: upstream rejected replay (HTTP ${info.status}: ${info.detail.slice(0, 120)}); likely provider risk-control \u2014 retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})]`);
50918
- log("warn", `[acp-loop] upstream rejected replay (HTTP ${info.status}); retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})`);
50992
+ const lc = lastCompressSuffix(ctx.session.lastCompress);
50993
+ ctx.log(`[acp-proxy: upstream rejected replay (HTTP ${info.status}: ${info.detail.slice(0, 120)}); likely provider risk-control \u2014 retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})${lc}]`);
50994
+ log("warn", `[acp-loop] upstream rejected replay (HTTP ${info.status}); retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})${lc}`);
50919
50995
  }
50920
50996
  );
50921
50997
  let newBody = adapter.buildRequest(coreMessages, systemPrompt, requestBody);
@@ -52432,8 +52508,9 @@ async function compressLoopResponsesJson(initialResponse, ctx, requestBody, requ
52432
52508
  body: JSON.stringify(requestBody),
52433
52509
  ...ctx.proxyUrl ? { dispatcher: proxyDispatcher(ctx.proxyUrl) } : {}
52434
52510
  }, void 0, void 0, (info) => {
52435
- ctx.log(`[acp-proxy: responses upstream rejected replay (HTTP ${info.status}: ${info.detail.slice(0, 120)}); likely provider risk-control \u2014 retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})]`);
52436
- log("warn", `[acp-compress-responses] upstream rejected replay (HTTP ${info.status}); retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})`);
52511
+ const lc = lastCompressSuffix(ctx.session.lastCompress);
52512
+ ctx.log(`[acp-proxy: responses upstream rejected replay (HTTP ${info.status}: ${info.detail.slice(0, 120)}); likely provider risk-control \u2014 retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})${lc}]`);
52513
+ log("warn", `[acp-compress-responses] upstream rejected replay (HTTP ${info.status}); retrying in ${info.delayMs}ms (attempt ${info.attempt}/${info.maxAttempts})${lc}`);
52437
52514
  }).catch((e) => {
52438
52515
  if (e instanceof UpstreamHttpError) {
52439
52516
  const suffix = e.attempts > 1 ? ` after ${e.attempts} attempt(s)` : "";
@@ -55583,7 +55660,7 @@ function prepareAnthropic(parsed, req, opts, core, config, prompts, log2, sessio
55583
55660
  try {
55584
55661
  const rendered = renderNudgeText(turn.nudge, prompts);
55585
55662
  if (rendered.text) {
55586
- rebuiltMessages = [...rebuiltMessages, { role: "user", content: rendered.text }];
55663
+ rebuiltMessages = [...rebuiltMessages, { role: "user", content: withStagedCompressGuidance(rendered.text) }];
55587
55664
  }
55588
55665
  } catch {
55589
55666
  }
@@ -55642,7 +55719,7 @@ function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session,
55642
55719
  try {
55643
55720
  const rendered = renderNudgeText(turn.nudge, prompts);
55644
55721
  if (rendered.text) {
55645
- rebuiltMessages = [...rebuiltMessages, { role: "user", content: rendered.text }];
55722
+ rebuiltMessages = [...rebuiltMessages, { role: "user", content: withStagedCompressGuidance(rendered.text) }];
55646
55723
  }
55647
55724
  } catch {
55648
55725
  }
@@ -55725,7 +55802,7 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
55725
55802
  const rendered = renderNudgeText(turn.nudge, prompts);
55726
55803
  if (rendered.text) {
55727
55804
  const inputItems = typeof rebuiltInput === "string" ? [{ type: "message", role: "user", content: rebuiltInput }] : rebuiltInput;
55728
- inputItems.push({ type: "message", role: "user", content: rendered.text });
55805
+ inputItems.push({ type: "message", role: "user", content: withStagedCompressGuidance(rendered.text) });
55729
55806
  rebuiltInput = inputItems;
55730
55807
  }
55731
55808
  } catch {