billion-context 0.1.62 → 0.1.63-pr.338.192

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
@@ -47900,7 +47900,7 @@ function rejectLegacyRoute(key, value) {
47900
47900
  // src/server.ts
47901
47901
  import http from "http";
47902
47902
  import fs6 from "fs";
47903
- import { randomUUID as randomUUID2 } from "crypto";
47903
+ import { randomUUID as randomUUID3 } from "crypto";
47904
47904
 
47905
47905
  // src/compress-settings.ts
47906
47906
  function resolveContextLimitValue(raw, nativeLimit) {
@@ -48297,6 +48297,213 @@ function registryLookup(reg, model, host) {
48297
48297
  return void 0;
48298
48298
  }
48299
48299
 
48300
+ // src/codex-models-snapshot.json
48301
+ var codex_models_snapshot_default = {
48302
+ source: "openai/codex main (commit 868c9ed) \u2014 codex-rs/models-manager/models.json",
48303
+ fetchedAt: "2026-08-28T17:09:46Z",
48304
+ count: 10,
48305
+ models: [
48306
+ {
48307
+ slug: "gpt-5.6-sol",
48308
+ contextWindow: 272e3,
48309
+ maxContextWindow: 872e3
48310
+ },
48311
+ {
48312
+ slug: "gpt-5.6-terra",
48313
+ contextWindow: 272e3,
48314
+ maxContextWindow: 872e3
48315
+ },
48316
+ {
48317
+ slug: "gpt-5.6-luna",
48318
+ contextWindow: 272e3,
48319
+ maxContextWindow: 872e3
48320
+ },
48321
+ {
48322
+ slug: "gpt-daybreak-blue-latest",
48323
+ contextWindow: 272e3,
48324
+ maxContextWindow: 872e3
48325
+ },
48326
+ {
48327
+ slug: "gpt-daybreak-red-latest",
48328
+ contextWindow: 372e3,
48329
+ maxContextWindow: 372e3
48330
+ },
48331
+ {
48332
+ slug: "gpt-5.5",
48333
+ contextWindow: 272e3,
48334
+ maxContextWindow: 272e3
48335
+ },
48336
+ {
48337
+ slug: "gpt-5.4",
48338
+ contextWindow: 272e3,
48339
+ maxContextWindow: 1e6
48340
+ },
48341
+ {
48342
+ slug: "gpt-5.4-mini",
48343
+ contextWindow: 272e3,
48344
+ maxContextWindow: 272e3
48345
+ },
48346
+ {
48347
+ slug: "gpt-5.2",
48348
+ contextWindow: 272e3,
48349
+ maxContextWindow: 272e3
48350
+ },
48351
+ {
48352
+ slug: "codex-auto-review",
48353
+ contextWindow: 272e3,
48354
+ maxContextWindow: 872e3
48355
+ }
48356
+ ]
48357
+ };
48358
+
48359
+ // src/codex-compact.ts
48360
+ import { randomUUID } from "crypto";
48361
+ var CODEX_COMPACT_ID_PREFIX = "fc_bili_";
48362
+ var CODEX_COMPACT_SENTINEL = "bili:acp:";
48363
+ var CODEX_UA_PREFIXES = ["codex_cli_rs/", "codex_exec/"];
48364
+ function codexCompactMode() {
48365
+ const v2 = process.env.BILI_CODEX_COMPACT?.trim().toLowerCase();
48366
+ return v2 === "pass" ? "pass" : "intercept";
48367
+ }
48368
+ function isCodexClient(headers) {
48369
+ const ua = headers["user-agent"];
48370
+ if (!ua) return false;
48371
+ const s3 = Array.isArray(ua) ? ua[0] : ua;
48372
+ return typeof s3 === "string" && CODEX_UA_PREFIXES.some((p2) => s3.startsWith(p2));
48373
+ }
48374
+ function hasCompactionTrigger(input) {
48375
+ if (!Array.isArray(input)) return false;
48376
+ const last = input[input.length - 1];
48377
+ return last?.type === "compaction_trigger";
48378
+ }
48379
+ function isBiliCompactionItem(item) {
48380
+ const it2 = item;
48381
+ if (!it2 || it2.type !== "compaction") return false;
48382
+ if (typeof it2.id === "string" && it2.id.startsWith(CODEX_COMPACT_ID_PREFIX)) return true;
48383
+ if (typeof it2.encrypted_content === "string" && it2.encrypted_content.startsWith(CODEX_COMPACT_SENTINEL)) return true;
48384
+ return false;
48385
+ }
48386
+ function stripBiliCompactionItems(input) {
48387
+ return input.filter((item) => !isBiliCompactionItem(item));
48388
+ }
48389
+ function extractBiliSummary(item) {
48390
+ const it2 = item;
48391
+ if (!it2 || typeof it2.encrypted_content !== "string") return void 0;
48392
+ if (!it2.encrypted_content.startsWith(CODEX_COMPACT_SENTINEL)) return void 0;
48393
+ const text = it2.encrypted_content.slice(CODEX_COMPACT_SENTINEL.length);
48394
+ return text.length > 0 ? text : void 0;
48395
+ }
48396
+ function replaceBiliCompactionItems(input) {
48397
+ const items = [];
48398
+ let replaced = 0;
48399
+ let dropped = 0;
48400
+ for (const item of input) {
48401
+ if (!isBiliCompactionItem(item)) {
48402
+ items.push(item);
48403
+ continue;
48404
+ }
48405
+ const summary = extractBiliSummary(item);
48406
+ if (summary === void 0) {
48407
+ dropped++;
48408
+ continue;
48409
+ }
48410
+ items.push({
48411
+ type: "message",
48412
+ role: "user",
48413
+ content: [{ type: "input_text", text: `[bili] context summary after compaction:
48414
+ ${summary}` }]
48415
+ });
48416
+ replaced++;
48417
+ }
48418
+ return { items, replaced, dropped };
48419
+ }
48420
+ function codexCompactGate(session, effectiveLimit, transformOk) {
48421
+ if (!transformOk || effectiveLimit <= 0) return false;
48422
+ if (session.stats.lastInputTokens >= effectiveLimit * 0.9) return false;
48423
+ return session.state.blocks.some((b2) => b2.active);
48424
+ }
48425
+ function buildTriggerForgeBody(summaryText, usage, stream2) {
48426
+ const compactionItem = {
48427
+ type: "compaction",
48428
+ id: `${CODEX_COMPACT_ID_PREFIX}${randomUUID()}`,
48429
+ encrypted_content: `${CODEX_COMPACT_SENTINEL}${summaryText}`
48430
+ };
48431
+ const usageJson = {
48432
+ input_tokens: usage.inputTokens,
48433
+ output_tokens: usage.outputTokens,
48434
+ total_tokens: usage.totalTokens
48435
+ };
48436
+ const id = `resp_bili_${randomUUID()}`;
48437
+ if (!stream2) {
48438
+ return {
48439
+ body: JSON.stringify({ id, output: [compactionItem], usage: usageJson }),
48440
+ contentType: "application/json"
48441
+ };
48442
+ }
48443
+ const frame1 = `data: ${JSON.stringify({ type: "response.output_item.done", item: compactionItem })}
48444
+
48445
+ `;
48446
+ const frame2 = `data: ${JSON.stringify({ type: "response.completed", response: { id, usage: usageJson } })}
48447
+
48448
+ `;
48449
+ return { body: frame1 + frame2, contentType: "text/event-stream" };
48450
+ }
48451
+ var FORGED_SUMMARY_HEADER = "[Compressed conversation section]";
48452
+ function renderForgedSummary(block) {
48453
+ const body = block.summary.trim();
48454
+ const topicLine = block.topic ? `${FORGED_SUMMARY_HEADER} \u2014 ${block.topic}` : FORGED_SUMMARY_HEADER;
48455
+ return body.length === 0 ? topicLine : `${topicLine}
48456
+ ${body}`;
48457
+ }
48458
+ function mergeForgedSummaries(existing, blocks) {
48459
+ const merged = existing ? [...existing] : [];
48460
+ for (const block of blocks) {
48461
+ if (!block.active) continue;
48462
+ const rendered = renderForgedSummary(block);
48463
+ if (!merged.includes(rendered)) merged.push(rendered);
48464
+ }
48465
+ return merged;
48466
+ }
48467
+
48468
+ // src/codex-models.ts
48469
+ var SNAPSHOT = codex_models_snapshot_default;
48470
+ var TABLE = SNAPSHOT.models;
48471
+ var CODEX_FALLBACK_CONTEXT_WINDOW = 272e3;
48472
+ function resolvedWindow(m2) {
48473
+ return m2.contextWindow ?? m2.maxContextWindow ?? CODEX_FALLBACK_CONTEXT_WINDOW;
48474
+ }
48475
+ function lookupWindow(model) {
48476
+ const direct = longestPrefixMatch(model);
48477
+ if (direct) return resolvedWindow(direct);
48478
+ const slash = model.indexOf("/");
48479
+ if (slash > 0) {
48480
+ const namespace = model.slice(0, slash);
48481
+ const suffix = model.slice(slash + 1);
48482
+ if (!suffix.includes("/") && /^[A-Za-z0-9_-]+$/.test(namespace)) {
48483
+ const m2 = longestPrefixMatch(suffix);
48484
+ if (m2) return resolvedWindow(m2);
48485
+ }
48486
+ }
48487
+ return CODEX_FALLBACK_CONTEXT_WINDOW;
48488
+ }
48489
+ function longestPrefixMatch(model) {
48490
+ let best;
48491
+ for (const m2 of TABLE) {
48492
+ if (!model.startsWith(m2.slug)) continue;
48493
+ if (!best || m2.slug.length > best.slug.length) best = m2;
48494
+ }
48495
+ return best;
48496
+ }
48497
+ function codexWindowForModel(model) {
48498
+ return lookupWindow(model);
48499
+ }
48500
+ function codexAlignedWindow(limit, model, headers) {
48501
+ if (!isCodexClient(headers)) return { limit, clamped: false };
48502
+ const w2 = codexWindowForModel(model);
48503
+ if (limit > w2) return { limit: w2, clamped: true };
48504
+ return { limit, clamped: false };
48505
+ }
48506
+
48300
48507
  // node_modules/acp-kernel/dist/wire/index.js
48301
48508
  import { createHash } from "crypto";
48302
48509
  function hashId(s3) {
@@ -50474,7 +50681,7 @@ function renderPage(origin, version2) {
50474
50681
  // src/web/api.ts
50475
50682
  import { closeSync, existsSync as existsSync3, fsyncSync, mkdirSync as mkdirSync4, openSync, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync3 } from "fs";
50476
50683
  import { dirname as dirname3 } from "path";
50477
- import { randomUUID } from "crypto";
50684
+ import { randomUUID as randomUUID2 } from "crypto";
50478
50685
  function readConfig() {
50479
50686
  const parsed = safeReadJson(configFile());
50480
50687
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
@@ -50499,7 +50706,7 @@ function readUpstreamSettings() {
50499
50706
  function atomicWriteConfig(config) {
50500
50707
  const filePath = configFile();
50501
50708
  mkdirSync4(dirname3(filePath), { recursive: true });
50502
- const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
50709
+ const tempPath = `${filePath}.${process.pid}.${randomUUID2()}.tmp`;
50503
50710
  let descriptor;
50504
50711
  try {
50505
50712
  descriptor = openSync(tempPath, "wx", 384);
@@ -52605,6 +52812,105 @@ function rewriteResponsesJsonResponse(body, ctx) {
52605
52812
  return body;
52606
52813
  }
52607
52814
 
52815
+ // src/stream-terminal.ts
52816
+ var SUCCEEDED = "response.completed";
52817
+ var FAILED_EVENTS = /* @__PURE__ */ new Set(["response.failed", "response.incomplete"]);
52818
+ var MAX_JSON_BYTES = 16 << 20;
52819
+ async function observeResponsesTerminalState(stream2, isStream) {
52820
+ return isStream ? observeSseTerminalState(stream2) : observeJsonTerminalState(stream2);
52821
+ }
52822
+ function terminalFromSseLine(line) {
52823
+ if (line.startsWith("event:")) {
52824
+ const name = line.slice(6).trim();
52825
+ if (name === SUCCEEDED) return "completed";
52826
+ if (FAILED_EVENTS.has(name)) return "failed";
52827
+ return null;
52828
+ }
52829
+ if (line.startsWith("data:")) {
52830
+ const data = line.slice(5).trim();
52831
+ if (!data.startsWith("{")) return null;
52832
+ try {
52833
+ const type = JSON.parse(data).type;
52834
+ if (type === SUCCEEDED) return "completed";
52835
+ if (type === "response.failed" || type === "response.incomplete") return "failed";
52836
+ } catch {
52837
+ return null;
52838
+ }
52839
+ }
52840
+ return null;
52841
+ }
52842
+ async function observeSseTerminalState(stream2) {
52843
+ const reader = stream2.getReader();
52844
+ const decoder = new TextDecoder();
52845
+ let buf = "";
52846
+ let state = "unknown";
52847
+ try {
52848
+ for (; ; ) {
52849
+ const { done, value } = await reader.read();
52850
+ if (done) break;
52851
+ buf += decoder.decode(value, { stream: true });
52852
+ let nl;
52853
+ while ((nl = buf.indexOf("\n")) >= 0) {
52854
+ const line = buf.slice(0, nl).replace(/\r$/, "");
52855
+ buf = buf.slice(nl + 1);
52856
+ const next = terminalFromSseLine(line);
52857
+ if (next !== null) {
52858
+ state = next;
52859
+ break;
52860
+ }
52861
+ }
52862
+ if (state !== "unknown") {
52863
+ await reader.cancel().catch(() => {
52864
+ });
52865
+ break;
52866
+ }
52867
+ }
52868
+ } catch {
52869
+ return "unknown";
52870
+ } finally {
52871
+ reader.releaseLock();
52872
+ }
52873
+ return state;
52874
+ }
52875
+ async function observeJsonTerminalState(stream2) {
52876
+ const reader = stream2.getReader();
52877
+ const chunks = [];
52878
+ let size = 0;
52879
+ let overflow = false;
52880
+ try {
52881
+ for (; ; ) {
52882
+ const { done, value } = await reader.read();
52883
+ if (done) break;
52884
+ if (!overflow) {
52885
+ size += value.length;
52886
+ if (size <= MAX_JSON_BYTES) {
52887
+ chunks.push(Buffer.from(value));
52888
+ } else {
52889
+ overflow = true;
52890
+ }
52891
+ }
52892
+ }
52893
+ } catch {
52894
+ return "unknown";
52895
+ } finally {
52896
+ reader.releaseLock();
52897
+ }
52898
+ if (overflow) return "unknown";
52899
+ const text = Buffer.concat(chunks).toString("utf8").trim();
52900
+ if (!text) return "unknown";
52901
+ let body;
52902
+ try {
52903
+ body = JSON.parse(text);
52904
+ } catch {
52905
+ return "unknown";
52906
+ }
52907
+ if (typeof body !== "object" || body === null) return "unknown";
52908
+ const rec = body;
52909
+ if (rec.error !== void 0) return "failed";
52910
+ if (Array.isArray(rec.output)) return "completed";
52911
+ return "unknown";
52912
+ }
52913
+
52608
52914
  // src/stream-error.ts
52609
52915
  function safeWrite(res, chunk) {
52610
52916
  try {
@@ -52700,12 +53006,38 @@ function preferPromptCacheKeyIdentity(identity, body) {
52700
53006
  if (pck.length === 0) return identity;
52701
53007
  return { ...identity, value: pck, source: "prompt-cache-key", clientProvided: true };
52702
53008
  }
53009
+ function codexTurnIdentity(headers) {
53010
+ const raw = headers["x-codex-turn-metadata"];
53011
+ if (typeof raw !== "string" || raw.trim().length === 0) return void 0;
53012
+ let parsed;
53013
+ try {
53014
+ parsed = JSON.parse(raw);
53015
+ } catch {
53016
+ return void 0;
53017
+ }
53018
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
53019
+ const record = parsed;
53020
+ const threadSource = record["thread_source"];
53021
+ if (typeof threadSource !== "string" || threadSource.trim().length === 0) return void 0;
53022
+ const metaThreadId = record["thread_id"];
53023
+ if (typeof metaThreadId !== "string" || metaThreadId.trim().length === 0) return void 0;
53024
+ const threadHeader = headers["thread-id"];
53025
+ if (typeof threadHeader !== "string" || threadHeader.trim() !== metaThreadId.trim()) return void 0;
53026
+ if (threadSource.trim() === "user") {
53027
+ return void 0;
53028
+ }
53029
+ return { value: threadHeader.trim(), threadSource };
53030
+ }
52703
53031
 
52704
53032
  // src/prefix-affinity.ts
52705
53033
  import { createHash as createHash5 } from "crypto";
52706
53034
  var MIN_CANONICAL_BYTES = 24;
52707
53035
  var MAX_TRACKED_SESSIONS = 256;
52708
53036
  var TTL_MS2 = 7 * 24 * 60 * 60 * 1e3;
53037
+ var TAIL_WINDOW = 8;
53038
+ var MIN_TAIL_MATCH = 3;
53039
+ var MAX_STORED_ITEMS = 128;
53040
+ var MIN_FORK_PREFIX = 3;
52709
53041
  function stableStringify(value) {
52710
53042
  return JSON.stringify(sortKeys(value));
52711
53043
  }
@@ -52737,6 +53069,15 @@ function chainHashes(messages) {
52737
53069
  }
52738
53070
  return bytes >= MIN_CANONICAL_BYTES ? hashes : [];
52739
53071
  }
53072
+ function perItemHashes(messages) {
53073
+ return messages.map((m2) => sha256(stableStringify(m2)));
53074
+ }
53075
+ function lcpLength(a, b2) {
53076
+ const n = Math.min(a.length, b2.length);
53077
+ let i = 0;
53078
+ while (i < n && a[i] === b2[i]) i++;
53079
+ return i;
53080
+ }
52740
53081
  var PrefixAffinityResolver = class {
52741
53082
  trackedChains = /* @__PURE__ */ new Map();
52742
53083
  /**
@@ -52747,12 +53088,15 @@ var PrefixAffinityResolver = class {
52747
53088
  resolve(messages) {
52748
53089
  const hashes = chainHashes(messages);
52749
53090
  if (hashes.length === 0 || !hasUserMessage(messages)) return null;
52750
- const tailHash = hashes[hashes.length - 1];
53091
+ const incomingDepth = hashes.length;
53092
+ const tailHash = hashes[incomingDepth - 1];
53093
+ const incItemHashes = perItemHashes(messages);
53094
+ const storedItemHashes = incItemHashes.slice(-MAX_STORED_ITEMS);
52751
53095
  const tracked = this.trackedChains;
52752
53096
  this.expire(tracked);
52753
53097
  let best;
52754
53098
  for (const entry of tracked.values()) {
52755
- if (entry.depth > hashes.length) continue;
53099
+ if (entry.depth > incomingDepth) continue;
52756
53100
  if (hashes[entry.depth - 1] !== entry.tailHash) continue;
52757
53101
  if (!best || entry.depth > best.depth || entry.depth === best.depth && entry.lastSeen > best.lastSeen) best = entry;
52758
53102
  }
@@ -52761,19 +53105,79 @@ var PrefixAffinityResolver = class {
52761
53105
  sessionId: best.sessionId,
52762
53106
  matchedDepth: best.depth,
52763
53107
  storedDepth: best.depth,
52764
- incomingDepth: hashes.length,
52765
- tailHash
53108
+ incomingDepth,
53109
+ tailHash,
53110
+ via: "prefix",
53111
+ itemHashes: storedItemHashes
52766
53112
  };
52767
53113
  }
52768
- const sessionId = `pfa-${sha256(`${tailHash}\0${hashes.length}`).slice(0, 16)}`;
52769
- return { sessionId, matchedDepth: 0, storedDepth: 0, incomingDepth: hashes.length, tailHash };
53114
+ const w2 = Math.min(TAIL_WINDOW, incomingDepth);
53115
+ const candidates = [];
53116
+ if (w2 >= MIN_TAIL_MATCH) {
53117
+ for (const entry of tracked.values()) {
53118
+ const stored = entry.itemHashes;
53119
+ for (let j2 = 1; j2 + w2 <= stored.length; j2++) {
53120
+ let match = true;
53121
+ for (let i = 0; i < w2; i++) {
53122
+ if (incItemHashes[i] !== stored[j2 + i]) {
53123
+ match = false;
53124
+ break;
53125
+ }
53126
+ }
53127
+ if (match) {
53128
+ candidates.push(entry);
53129
+ break;
53130
+ }
53131
+ }
53132
+ }
53133
+ }
53134
+ if (candidates.length === 1) {
53135
+ const entry = candidates[0];
53136
+ const w3 = Math.min(TAIL_WINDOW, incomingDepth, entry.depth);
53137
+ return {
53138
+ sessionId: entry.sessionId,
53139
+ matchedDepth: w3,
53140
+ storedDepth: entry.depth,
53141
+ incomingDepth,
53142
+ tailHash,
53143
+ via: "tail-window",
53144
+ itemHashes: storedItemHashes
53145
+ };
53146
+ }
53147
+ let lineage;
53148
+ if (candidates.length > 1) {
53149
+ lineage = { parents: candidates.map((c) => c.sessionId), reason: "truncated" };
53150
+ } else {
53151
+ let forkParent;
53152
+ let forkLcp = 0;
53153
+ for (const entry of tracked.values()) {
53154
+ if (entry.depth > MAX_STORED_ITEMS) continue;
53155
+ const lcp = lcpLength(incItemHashes, entry.itemHashes);
53156
+ if (lcp >= MIN_FORK_PREFIX && lcp > forkLcp) {
53157
+ forkLcp = lcp;
53158
+ forkParent = entry;
53159
+ }
53160
+ }
53161
+ if (forkParent) lineage = { parents: [forkParent.sessionId], reason: "forked", sharedPrefix: forkLcp };
53162
+ }
53163
+ const sessionId = `pfa-${sha256(`${tailHash}\0${incomingDepth}`).slice(0, 16)}`;
53164
+ return {
53165
+ sessionId,
53166
+ matchedDepth: 0,
53167
+ storedDepth: 0,
53168
+ incomingDepth,
53169
+ tailHash,
53170
+ via: "new",
53171
+ itemHashes: storedItemHashes,
53172
+ ...lineage ? { lineage } : {}
53173
+ };
52770
53174
  }
52771
53175
  /** Record the chain of a session (on creation and after every anonymous
52772
53176
  * request — the incoming history is the truth, appends extend it). */
52773
- note(sessionId, depth, tailHash) {
53177
+ note(sessionId, depth, tailHash, itemHashes) {
52774
53178
  const tracked = this.trackedChains;
52775
53179
  tracked.delete(sessionId);
52776
- tracked.set(sessionId, { sessionId, depth, tailHash, lastSeen: Date.now() });
53180
+ tracked.set(sessionId, { sessionId, depth, tailHash, itemHashes, lastSeen: Date.now() });
52777
53181
  while (tracked.size > MAX_TRACKED_SESSIONS) {
52778
53182
  const oldest = [...tracked.values()].sort((a, b2) => a.lastSeen - b2.lastSeen)[0];
52779
53183
  if (!oldest) break;
@@ -53686,16 +54090,31 @@ function readClaudeSettings(homeDir, cwd, env = process.env) {
53686
54090
  path8.join(cwd, ".claude", "settings.json")
53687
54091
  ];
53688
54092
  let anthropicBaseUrl;
54093
+ let model;
54094
+ let autoCompactWindow;
53689
54095
  for (const f2 of files) {
53690
54096
  const obj = readJsonObject(f2);
53691
54097
  const settingsEnv = obj?.env;
53692
54098
  if (settingsEnv && typeof settingsEnv === "object" && !Array.isArray(settingsEnv)) {
53693
- const v2 = settingsEnv.ANTHROPIC_BASE_URL;
54099
+ const e = settingsEnv;
54100
+ const v2 = e.ANTHROPIC_BASE_URL;
53694
54101
  if (nonEmpty2(v2)) anthropicBaseUrl = v2;
54102
+ const m2 = e.ANTHROPIC_MODEL;
54103
+ if (nonEmpty2(m2)) model = String(m2);
54104
+ const acw = Number(e.CLAUDE_CODE_AUTO_COMPACT_WINDOW);
54105
+ if (Number.isFinite(acw) && acw > 0) autoCompactWindow = acw;
53695
54106
  }
54107
+ const tm = obj?.model;
54108
+ if (nonEmpty2(tm) && model === void 0) model = String(tm);
54109
+ const tacw = Number(obj?.autoCompactWindow);
54110
+ if (Number.isFinite(tacw) && tacw > 0 && autoCompactWindow === void 0) autoCompactWindow = tacw;
53696
54111
  }
53697
54112
  if (!anthropicBaseUrl && nonEmpty2(env.ANTHROPIC_BASE_URL)) anthropicBaseUrl = env.ANTHROPIC_BASE_URL;
53698
- return anthropicBaseUrl ? { anthropicBaseUrl } : {};
54113
+ return {
54114
+ ...anthropicBaseUrl ? { anthropicBaseUrl } : {},
54115
+ ...model ? { model } : {},
54116
+ ...autoCompactWindow ? { autoCompactWindow } : {}
54117
+ };
53699
54118
  }
53700
54119
  function parseCodexToml(text) {
53701
54120
  const result = { providers: {} };
@@ -53703,6 +54122,7 @@ function parseCodexToml(text) {
53703
54122
  let curProvider = null;
53704
54123
  let codexModel;
53705
54124
  let codexContextWindow;
54125
+ let codexAutoCompactLimit;
53706
54126
  for (const rawLine of text.split(/\r?\n/)) {
53707
54127
  const line = rawLine.trim();
53708
54128
  if (!line || line.startsWith("#")) continue;
@@ -53727,10 +54147,14 @@ function parseCodexToml(text) {
53727
54147
  } else if (curProvider && key === "base_url") {
53728
54148
  result.providers[curProvider].baseUrl = val;
53729
54149
  }
53730
- } else if (numMatch && table === "" && numMatch[1] === "model_context_window") {
53731
- codexContextWindow = Number(numMatch[2]);
54150
+ } else if (numMatch && table === "") {
54151
+ if (numMatch[1] === "model_context_window") codexContextWindow = Number(numMatch[2]);
54152
+ else if (numMatch[1] === "model_auto_compact_token_limit") codexAutoCompactLimit = Number(numMatch[2]);
53732
54153
  }
53733
54154
  }
54155
+ if (codexModel) result.model = codexModel;
54156
+ if (codexContextWindow) result.contextWindow = codexContextWindow;
54157
+ if (codexAutoCompactLimit) result.autoCompactLimit = codexAutoCompactLimit;
53734
54158
  const win = toModelWindow(codexModel, codexContextWindow);
53735
54159
  if (win) result.modelWindows = [win];
53736
54160
  return result;
@@ -55063,7 +55487,7 @@ async function startServer(opts) {
55063
55487
  const core = createCore();
55064
55488
  const config = opts.kernelConfig;
55065
55489
  const log2 = (level, msg) => logMsg(opts, level, msg);
55066
- const instanceId = randomUUID2();
55490
+ const instanceId = randomUUID3();
55067
55491
  await initSessions();
55068
55492
  loadConversations();
55069
55493
  log2("info", `[persist] ${getStore().enabled ? "enabled" : "disabled"}`);
@@ -55424,6 +55848,13 @@ ${bodyBuffer.toString("utf8")}`);
55424
55848
  if (native) nativeFromFallback = false;
55425
55849
  }
55426
55850
  reqConfig = resolveRequestConfig(config, opts.routes, embeddedUrl, model, native, opts.compress);
55851
+ const aligned = operatorWindowTuned ? { limit: reqConfig.modelContextLimit, clamped: false } : codexAlignedWindow(reqConfig.modelContextLimit, model, req.headers);
55852
+ if (aligned.clamped) {
55853
+ const before = reqConfig.modelContextLimit;
55854
+ reqConfig = { ...reqConfig, modelContextLimit: aligned.limit };
55855
+ nativeFromFallback = false;
55856
+ log2("info", `[codex] effective window clamped ${before} \u2192 ${aligned.limit} (codex's own perception for model=${model}; ACP now compresses before codex's native auto-compact)`);
55857
+ }
55427
55858
  reqPrompts = resolveCompressPrompts(resolveCompress(opts.routes, embeddedUrl, model, opts.compress));
55428
55859
  }
55429
55860
  }
@@ -55434,7 +55865,8 @@ ${bodyBuffer.toString("utf8")}`);
55434
55865
  let pluginConversation = pluginConversationHeader(req.headers);
55435
55866
  const clientConv = clientConversationHeader(req.headers);
55436
55867
  const convHeader = clientConv ?? sessionHeader;
55437
- const responsesIdentity = protocol === "responses" ? preferPromptCacheKeyIdentity(
55868
+ const codexTurn = protocol === "responses" ? codexTurnIdentity(req.headers) : void 0;
55869
+ const responsesIdentity = protocol === "responses" ? codexTurn ? { value: codexTurn.value, source: "header", clientProvided: true } : preferPromptCacheKeyIdentity(
55438
55870
  conversationIdentityResponses(parsed, convHeader),
55439
55871
  parsed
55440
55872
  ) : void 0;
@@ -55443,7 +55875,7 @@ ${bodyBuffer.toString("utf8")}`);
55443
55875
  convHeader ? { value: openaiSignal, source: "header", clientProvided: true } : { value: openaiSignal, source: "content-fingerprint", clientProvided: false },
55444
55876
  parsed
55445
55877
  ) : void 0;
55446
- const conversation = protocol === "anthropic" ? conversationSignalAnthropic(parsed, convHeader) : protocol === "openai" ? openaiIdentity?.value ?? openaiSignal : subagentNamespace(
55878
+ const conversation = protocol === "anthropic" ? conversationSignalAnthropic(parsed, convHeader) : protocol === "openai" ? openaiIdentity?.value ?? openaiSignal : codexTurn ? codexTurn.value : subagentNamespace(
55447
55879
  responsesIdentity?.value ?? conversationSignalResponses(parsed, convHeader),
55448
55880
  parsed.instructions
55449
55881
  );
@@ -55458,12 +55890,16 @@ ${bodyBuffer.toString("utf8")}`);
55458
55890
  res.end(JSON.stringify(protocol === "anthropic" ? { type: "error", error: { type: "invalid_request_error", message: NO_IDENTITY_MESSAGE } } : { error: { type: "invalid_request_error", message: NO_IDENTITY_MESSAGE } }));
55459
55891
  return;
55460
55892
  }
55461
- if (anonAffinity.matchedDepth > 0) {
55893
+ if (anonAffinity.via === "tail-window") {
55894
+ log2("info", `[prefix-affinity] anonymous ${protocol} request \u2192 session ${anonAffinity.sessionId} (tail-window reattach window=${anonAffinity.matchedDepth}/${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)}; truncated replay reattached, kernel reconciles by message id)`);
55895
+ log("info", `[prefix-affinity] session ${anonAffinity.sessionId} reattached via tail-window (window ${anonAffinity.matchedDepth}/${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)})`);
55896
+ } else if (anonAffinity.matchedDepth > 0) {
55462
55897
  log2("info", `[prefix-affinity] anonymous ${protocol} request \u2192 session ${anonAffinity.sessionId} (prefix match depth=${anonAffinity.matchedDepth}/${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)}; fork semantics: diverged histories split on their next request)`);
55463
55898
  log("info", `[prefix-affinity] session ${anonAffinity.sessionId} matched at depth ${anonAffinity.matchedDepth}/${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)})`);
55464
55899
  } else {
55465
- log2("info", `[prefix-affinity] new anonymous session ${anonAffinity.sessionId} (depth=${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)})`);
55466
- log("info", `[prefix-affinity] new session ${anonAffinity.sessionId} at depth ${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)})`);
55900
+ const lineage = anonAffinity.lineage ? `; lineage=${anonAffinity.lineage.reason} of ${anonAffinity.lineage.parents.join(",")}` : "";
55901
+ log2("info", `[prefix-affinity] new anonymous session ${anonAffinity.sessionId} (depth=${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)}${lineage})`);
55902
+ log("info", `[prefix-affinity] new session ${anonAffinity.sessionId} at depth ${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)}${lineage})`);
55467
55903
  }
55468
55904
  }
55469
55905
  const sessionId = anonAffinity ? anonAffinity.sessionId : conversation;
@@ -55476,10 +55912,12 @@ ${bodyBuffer.toString("utf8")}`);
55476
55912
  const clientLabel = bodyIdentity?.clientProvided ? bodyIdentity.value : clientConversationHeader(req.headers);
55477
55913
  const session = getSession(sessionId, { protocol, upstreamOrigin, label: clientLabel ?? (anonAffinity ? "prefix-affinity" : void 0) });
55478
55914
  if (anonAffinity) {
55479
- prefixAffinity.note(sessionId, anonAffinity.incomingDepth, anonAffinity.tailHash);
55915
+ prefixAffinity.note(sessionId, anonAffinity.incomingDepth, anonAffinity.tailHash, anonAffinity.itemHashes);
55480
55916
  session.metadata.anonymousPrefixAffinity = {
55481
55917
  depth: anonAffinity.incomingDepth,
55482
- tailHash: anonAffinity.tailHash
55918
+ tailHash: anonAffinity.tailHash,
55919
+ via: anonAffinity.via,
55920
+ ...anonAffinity.lineage ? { lineage: anonAffinity.lineage } : {}
55483
55921
  };
55484
55922
  }
55485
55923
  if (!pluginAgent && !anonAffinity) {
@@ -55489,7 +55927,7 @@ ${bodyBuffer.toString("utf8")}`);
55489
55927
  pluginConversation = clientConv ?? conversation;
55490
55928
  }
55491
55929
  }
55492
- if (!pluginAgent && session.stats.requests === 0) {
55930
+ if (!pluginAgent && session.stats.requests === 0 && codexTurnIdentity(req.headers) === void 0) {
55493
55931
  const pending = takePendingPluginRegister();
55494
55932
  if (pending) {
55495
55933
  pluginAgent = pending.agent;
@@ -55533,7 +55971,7 @@ ${bodyBuffer.toString("utf8")}`);
55533
55971
  acquireInFlight(session);
55534
55972
  try {
55535
55973
  await withSessionLock(session, async () => {
55536
- const runPrepare = () => countTokens ? prepareCountTokens(parsed, core, reqConfig, log2, session) : protocol === "anthropic" ? prepareAnthropic(parsed, req, opts, core, reqConfig, reqPrompts, log2, session, pluginMode) : protocol === "openai" ? prepareOpenai(parsed, req, opts, core, reqConfig, reqPrompts, log2, session, pluginMode) : responsesCompact ? prepareResponsesCompact(bodyBuffer, parsed, session) : prepareResponses(parsed, req, opts, core, reqConfig, reqPrompts, log2, session, responsesIdentity, pluginMode, upstreamOrigin);
55974
+ const runPrepare = () => countTokens ? prepareCountTokens(parsed, core, reqConfig, log2, session) : protocol === "anthropic" ? prepareAnthropic(parsed, req, opts, core, reqConfig, reqPrompts, log2, session, pluginMode) : protocol === "openai" ? prepareOpenai(parsed, req, opts, core, reqConfig, reqPrompts, log2, session, pluginMode) : responsesCompact ? prepareResponsesCompact(bodyBuffer, parsed, session, req, core, reqConfig, log2) : prepareResponses(parsed, req, opts, core, reqConfig, reqPrompts, log2, session, responsesIdentity, pluginMode, upstreamOrigin);
55537
55975
  prepared = runPrepare();
55538
55976
  if (!countTokens && !responsesCompact) {
55539
55977
  const outcome = await preflightCompressIfNeeded(
@@ -55744,12 +56182,22 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
55744
56182
  if (reconcileNativeCompactionBoundary(session)) {
55745
56183
  log2("info", `[${sessionId}] reconciled ACP state after native Responses compact boundary`);
55746
56184
  }
56185
+ let echoReplaced = false;
56186
+ if (Array.isArray(parsed.input)) {
56187
+ const { items, replaced, dropped } = replaceBiliCompactionItems(parsed.input);
56188
+ if (replaced > 0 || dropped > 0) {
56189
+ echoReplaced = true;
56190
+ log2("info", `[${sessionId}] replaced ${replaced} echoed bili compaction item(s) with summary handoff message(s)${dropped > 0 ? `, dropped ${dropped} legacy marker item(s)` : ""}`);
56191
+ parsed.input = items;
56192
+ }
56193
+ }
55747
56194
  let processedMessages = [];
55748
56195
  let originalMessages = [];
55749
56196
  let nudge;
55750
56197
  let responsesProjection;
55751
56198
  let rebuiltInput = parsed.input;
55752
56199
  let toolsOut = parsed.tools;
56200
+ let transformOk = false;
55753
56201
  const typedItems = normalizeResponsesMessageItems(parsed.input);
55754
56202
  if (typedItems > 0) {
55755
56203
  log2("info", `[${sessionId}] stamped type:"message" on ${typedItems} type-less input item(s) before projection (omp wire form)`);
@@ -55761,6 +56209,7 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
55761
56209
  }
55762
56210
  const shouldInject = opts.compress.injectTool;
55763
56211
  const injectTools = shouldInject && !pluginMode;
56212
+ const isCompactionTrigger = hasCompactionTrigger(parsed.input);
55764
56213
  const responsesTextProtocol = FORCE_TEXT_PROTOCOL || resolveCompressProtocol(opts.routes, upstreamOrigin) === "marker";
55765
56214
  try {
55766
56215
  const projection = responsesToCore(parsed);
@@ -55771,7 +56220,7 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
55771
56220
  log2("info", `[${sessionId}] input items: ${Array.isArray(parsed.input) ? parsed.input.map((i) => i.type).join(",") : "(string)"}`);
55772
56221
  }
55773
56222
  const tokenCount = session.stats.lastInputTokens;
55774
- const turn = core.processTurn({ messages: msgs, state: session.state, config, tokenCount, renderTags: process.env.ACP_RENDER_NONE ? "none" : "text-only" });
56223
+ const turn = core.processTurn({ messages: msgs, state: session.state, config, tokenCount, renderTags: process.env.ACP_RENDER_NONE || isCompactionTrigger ? "none" : "text-only" });
55775
56224
  session.state = turn.state;
55776
56225
  session.stats.compressCreditTokens = 0;
55777
56226
  if (turn.nudge) turn.nudge.compressibleRanges = viableRanges(turn.nudge.compressibleRanges);
@@ -55786,18 +56235,19 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
55786
56235
  processedMessages = stripKernelSummaries(turn.messages, turn.state);
55787
56236
  reapOrphanBlocks(session, msgs, deactivateBlock);
55788
56237
  rebuiltInput = patchResponsesInput(projection, processedMessages);
55789
- if (shouldInject && !process.env.ACP_NO_COMPRESS_PROMPT) {
56238
+ const forgedSummaries = echoReplaced ? [] : session.metadata.codexForgedSummaries ?? [];
56239
+ if (shouldInject && !isCompactionTrigger && !process.env.ACP_NO_COMPRESS_PROMPT) {
55790
56240
  const prompt = responsesTextProtocol ? buildCompressHybridSystemPrompt(prompts) : buildCompressSystemPrompt(prompts);
55791
- const devContent = [...projection.systemParts, prompt].join("\n\n---\n\n");
56241
+ const devContent = [...projection.systemParts, ...forgedSummaries, prompt].join("\n\n---\n\n");
55792
56242
  rebuiltInput = injectResponsesDeveloperMessage(rebuiltInput, devContent);
55793
56243
  if (!process.env.ACP_NO_INJECT_TOOL && injectTools) {
55794
56244
  toolsOut = responsesTextProtocol ? injectResponsesTool(parsed.tools, ACP_READONLY_TOOLS_RESPONSES) : injectResponsesTool(parsed.tools);
55795
56245
  }
55796
- } else if (projection.systemParts.length > 0) {
55797
- rebuiltInput = injectResponsesDeveloperMessage(rebuiltInput, projection.systemParts.join("\n\n---\n\n"));
56246
+ } else if (projection.systemParts.length > 0 || forgedSummaries.length > 0) {
56247
+ const devContent = [...projection.systemParts, ...forgedSummaries].join("\n\n---\n\n");
56248
+ rebuiltInput = injectResponsesDeveloperMessage(rebuiltInput, devContent);
55798
56249
  }
55799
- const triggerFinal = Array.isArray(rebuiltInput) && rebuiltInput.length > 0 && rebuiltInput[rebuiltInput.length - 1].type === "compaction_trigger";
55800
- if (opts.compress.injectNudge && turn.nudge?.shouldInject && shouldInject && !triggerFinal) {
56250
+ if (opts.compress.injectNudge && turn.nudge?.shouldInject && shouldInject && !isCompactionTrigger) {
55801
56251
  try {
55802
56252
  const rendered = renderNudgeText(turn.nudge, prompts);
55803
56253
  if (rendered.text) {
@@ -55808,10 +56258,28 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
55808
56258
  } catch {
55809
56259
  }
55810
56260
  }
56261
+ transformOk = true;
55811
56262
  } catch (err2) {
55812
56263
  log2("warn", `[${sessionId}] kernel transform failed, forwarding unchanged: ${String(err2)}`);
55813
56264
  processedMessages = [];
55814
56265
  }
56266
+ let codexForge;
56267
+ if (transformOk && codexCompactMode() === "intercept" && isCodexClient(req.headers) && hasCompactionTrigger(parsed.input) && codexCompactGate(session, config.modelContextLimit, transformOk)) {
56268
+ const summaries = session.state.blocks.filter((b2) => b2.active).map((b2) => b2.summary);
56269
+ const prevForged = session.metadata.codexForgedSummaries;
56270
+ const captured = mergeForgedSummaries(prevForged, session.state.blocks);
56271
+ if (captured.length !== (prevForged?.length ?? 0)) {
56272
+ session.metadata.codexForgedSummaries = captured;
56273
+ markDirty(session);
56274
+ }
56275
+ const est = defaultCountTokens(typeof parsed.input === "string" ? parsed.input : JSON.stringify(parsed.input ?? ""));
56276
+ const total = Math.max(session.stats.lastInputTokens, est, 1);
56277
+ codexForge = {
56278
+ kind: "trigger",
56279
+ ...buildTriggerForgeBody(summaries.join("\n\n"), { inputTokens: total, outputTokens: 0, totalTokens: total }, stream2)
56280
+ };
56281
+ log2("info", `[${sessionId}] codex compact intercepted (trigger); forged SSE with ${summaries.length} block summary(s), upstream not contacted`);
56282
+ }
55815
56283
  const rebuilt = { ...parsed, input: rebuiltInput, tools: toolsOut };
55816
56284
  const promptCacheKey = resolvePromptCacheKey(
55817
56285
  rebuilt.prompt_cache_key,
@@ -55841,11 +56309,13 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
55841
56309
  responsesProjection,
55842
56310
  protocol: "responses",
55843
56311
  stream: stream2,
55844
- compressInjected: injectTools,
56312
+ compressInjected: injectTools && !isCompactionTrigger,
55845
56313
  pluginMode,
55846
56314
  responsesTextProtocol,
55847
56315
  nudge,
55848
- prompts
56316
+ prompts,
56317
+ resetAfterSuccess: isCompactionTrigger,
56318
+ codexForge
55849
56319
  };
55850
56320
  }
55851
56321
  function isCountTokensRequest(method, urlPath, hasBody) {
@@ -55881,10 +56351,13 @@ function prepareCountTokens(parsed, core, config, log2, session) {
55881
56351
  };
55882
56352
  }
55883
56353
  }
55884
- function prepareResponsesCompact(body, parsed, session) {
56354
+ function prepareResponsesCompact(body, parsed, session, req, core, config, log2) {
55885
56355
  ++session.stats.requests;
55886
- return {
55887
- body,
56356
+ const cleaned = Array.isArray(parsed.input) ? stripBiliCompactionItems(parsed.input) : parsed.input;
56357
+ const stripped = Array.isArray(parsed.input) && cleaned.length !== parsed.input.length;
56358
+ const forgeBody = { ...parsed, input: cleaned };
56359
+ const base = {
56360
+ body: stripped ? Buffer.from(JSON.stringify(forgeBody)) : body,
55888
56361
  session,
55889
56362
  processedMessages: [],
55890
56363
  originalMessages: [],
@@ -55893,6 +56366,35 @@ function prepareResponsesCompact(body, parsed, session) {
55893
56366
  compressInjected: false,
55894
56367
  resetAfterSuccess: true
55895
56368
  };
56369
+ if (codexCompactMode() !== "intercept" || !isCodexClient(req.headers) || !Array.isArray(parsed.input)) {
56370
+ return base;
56371
+ }
56372
+ const prevState = session.state;
56373
+ let transformOk = false;
56374
+ try {
56375
+ const projection = responsesToCore(forgeBody);
56376
+ const turn = core.processTurn({ messages: projection.msgs, state: session.state, config, tokenCount: session.stats.lastInputTokens, renderTags: process.env.ACP_RENDER_NONE ? "none" : "text-only" });
56377
+ session.state = turn.state;
56378
+ transformOk = true;
56379
+ if (!codexCompactGate(session, config.modelContextLimit, transformOk)) {
56380
+ session.state = prevState;
56381
+ return base;
56382
+ }
56383
+ const processed = stripKernelSummaries(turn.messages, turn.state);
56384
+ const output = patchResponsesInput(projection, processed);
56385
+ if (typeof output === "string") {
56386
+ session.state = prevState;
56387
+ return base;
56388
+ }
56389
+ snapshotMessages(session, projection.msgs);
56390
+ markDirty(session);
56391
+ log2("info", `[${session.id}] codex compact intercepted (endpoint); forged history with ${output.length} item(s), upstream not contacted`);
56392
+ return { ...base, codexForge: { kind: "endpoint", body: JSON.stringify({ output }), contentType: "application/json" } };
56393
+ } catch (err2) {
56394
+ session.state = prevState;
56395
+ log2("warn", `[${session.id}] codex compact forge failed (${String(err2)}); passing through to upstream`);
56396
+ return base;
56397
+ }
55896
56398
  }
55897
56399
  function shouldInjectPromptCacheKey(routing, upstream) {
55898
56400
  if (routing === "enabled") return true;
@@ -56032,6 +56534,12 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
56032
56534
  return failFast(status, f2?.detail ?? "unknown reason", status === 503);
56033
56535
  }
56034
56536
  async function forward(req, res, opts, body, prepared, core, config, log2, route, instanceId, affinity) {
56537
+ if (prepared?.codexForge) {
56538
+ log2("info", `[${prepared.session.id}] codex compact served locally (${prepared.codexForge.kind}); upstream not contacted`);
56539
+ res.writeHead(200, { "content-type": prepared.codexForge.contentType });
56540
+ res.end(prepared.codexForge.body);
56541
+ return;
56542
+ }
56035
56543
  const { upstreamUrl, headers, proxyUrl } = buildForwardTarget(req, opts, route, affinity, prepared !== null ? instanceId : void 0);
56036
56544
  log2("info", `forward ${req.method} \u2192 ${maskUrlForLog(upstreamUrl)}`);
56037
56545
  if (process.env.ACP_DEBUG && prepared) {
@@ -56221,8 +56729,7 @@ ${hdrText}
56221
56729
  res.end();
56222
56730
  clearUpstreamTimer();
56223
56731
  if (prepared?.resetAfterSuccess) {
56224
- markNativeCompactionBoundary(prepared.session);
56225
- log2("info", `[${prepared.session.id}] native Responses compact completed; rebase scheduled for next Responses turn`);
56732
+ log2("warn", `[${prepared.session.id}] native compact response had no body; rebase NOT scheduled`);
56226
56733
  }
56227
56734
  return;
56228
56735
  }
@@ -56241,11 +56748,21 @@ ${hdrText}
56241
56748
  }
56242
56749
  const useRewriter = prepared !== null && prepared.compressInjected && prepared.processedMessages.length > 0;
56243
56750
  if (!useRewriter || prepared === null) {
56244
- await pipeThrough(upstream.body, res);
56245
- clearUpstreamTimer();
56246
- if (prepared?.resetAfterSuccess) {
56247
- markNativeCompactionBoundary(prepared.session);
56248
- log2("info", `[${prepared.session.id}] native Responses compact completed; rebase scheduled for next Responses turn`);
56751
+ if (prepared && prepared.resetAfterSuccess) {
56752
+ const [toClient, toObserve] = upstream.body.tee();
56753
+ const observed = observeResponsesTerminalState(toObserve, prepared.stream);
56754
+ await pipeThrough(toClient, res);
56755
+ clearUpstreamTimer();
56756
+ const terminal = await observed;
56757
+ if (terminal === "completed") {
56758
+ markNativeCompactionBoundary(prepared.session);
56759
+ log2("info", `[${prepared.session.id}] native Responses compact completed; rebase scheduled for next Responses turn`);
56760
+ } else {
56761
+ log2("warn", `[${prepared.session.id}] native compact response terminal=${terminal}; rebase NOT scheduled`);
56762
+ }
56763
+ } else {
56764
+ await pipeThrough(upstream.body, res);
56765
+ clearUpstreamTimer();
56249
56766
  }
56250
56767
  return;
56251
56768
  }
@@ -59493,6 +60010,9 @@ function isNewer(latest, current) {
59493
60010
  }
59494
60011
  return false;
59495
60012
  }
60013
+ function staleInstallStatus(diskVersion, runningVersion) {
60014
+ return diskVersion !== void 0 && isNewer(diskVersion, runningVersion) ? "restart" : "current";
60015
+ }
59496
60016
  async function readLastCheck() {
59497
60017
  try {
59498
60018
  const data = await readFile2(THROTTLE_FILE, "utf-8");
@@ -59697,7 +60217,11 @@ async function checkForUpdate(opts, force = false) {
59697
60217
  const diskVersion = installDir ? await readDiskVersion(installDir) : void 0;
59698
60218
  const currentVersion = diskVersion ?? opts.currentVersion;
59699
60219
  if (!isNewer(latest, currentVersion)) {
59700
- log("info", `[update] current=${currentVersion} latest=${latest} (up to date)`);
60220
+ if (staleInstallStatus(diskVersion, opts.currentVersion) === "restart") {
60221
+ log("warn", `[update] running v${opts.currentVersion} but v${diskVersion} is installed \u2014 restart bili to activate (auto-update replaced the on-disk install; this process is still on the old code)`);
60222
+ } else {
60223
+ log("info", `[update] current=${currentVersion} latest=${latest} (up to date)`);
60224
+ }
59701
60225
  return;
59702
60226
  }
59703
60227
  const tarballUrl = data.dist?.tarball;
@@ -60372,7 +60896,7 @@ function pluginStatusAll() {
60372
60896
  }
60373
60897
 
60374
60898
  // src/launcher.ts
60375
- import { randomUUID as randomUUID3 } from "crypto";
60899
+ import { randomUUID as randomUUID4 } from "crypto";
60376
60900
  import fs10 from "fs";
60377
60901
  import net2 from "net";
60378
60902
  import os5 from "os";
@@ -60537,6 +61061,37 @@ function buildCodexArgs(origin, httpRewrites, httpsRewrites, extra) {
60537
61061
  args.push(...extra);
60538
61062
  return args;
60539
61063
  }
61064
+ async function resolveLauncherWindow(model, routes, upstreamUrl) {
61065
+ if (!model) return void 0;
61066
+ let host;
61067
+ if (upstreamUrl) {
61068
+ try {
61069
+ host = new URL(upstreamUrl).hostname;
61070
+ } catch {
61071
+ host = void 0;
61072
+ }
61073
+ }
61074
+ return resolveConfiguredContextLimit(routes, upstreamUrl, model) ?? lookupContextLimit(model) ?? await contextFromRegistry(model, host);
61075
+ }
61076
+ function codexUpstreamUrl(codex) {
61077
+ const provider = codex?.modelProvider ? codex?.providers?.[codex.modelProvider]?.baseUrl : void 0;
61078
+ return provider ?? codex?.openaiBaseUrl ?? "https://api.openai.com/v1";
61079
+ }
61080
+ async function resolveCodexBudgetArgs(opts) {
61081
+ const { model, clientWindow, clientAutoCompactLimit, routes, upstreamUrl } = opts;
61082
+ if (!model || clientWindow) return [];
61083
+ const window2 = await resolveLauncherWindow(model, routes, upstreamUrl);
61084
+ if (!window2) return [];
61085
+ const limit = clientAutoCompactLimit ?? window2;
61086
+ return ["-c", `model_context_window=${window2}`, "-c", `model_auto_compact_token_limit=${limit}`];
61087
+ }
61088
+ async function resolveClaudeBudgetEnv(opts) {
61089
+ const { model, userAutoCompactWindow, shellAutoCompactWindow, routes, upstreamUrl } = opts;
61090
+ if (!model || userAutoCompactWindow !== void 0 || nonEmpty2(shellAutoCompactWindow)) return {};
61091
+ const window2 = await resolveLauncherWindow(model, routes, upstreamUrl);
61092
+ if (!window2) return {};
61093
+ return { CLAUDE_CODE_AUTO_COMPACT_WINDOW: String(window2) };
61094
+ }
60540
61095
  function buildClaudeEnv(origin, caPath, httpRewrites, httpsRewrites, baseEnv) {
60541
61096
  const env = { ...baseEnv, HTTPS_PROXY: origin, NODE_EXTRA_CA_CERTS: caPath, BILLION_CONTEXT_PROXY: origin };
60542
61097
  const r = httpRewrites.find((rw) => rw.key === "ANTHROPIC_BASE_URL");
@@ -60548,8 +61103,49 @@ function buildClaudeEnv(origin, caPath, httpRewrites, httpsRewrites, baseEnv) {
60548
61103
  function launcherDirectUrl(env) {
60549
61104
  return env.BILI_LAUNCHER_DIRECT === "1";
60550
61105
  }
60551
- function launcherInjectMcp(env, base) {
60552
- return base !== "pi" && base !== "omp" && base !== "opencode" && base !== "hermes" && base !== "dsh" && env.BILI_LAUNCHER_PLUGIN !== "0";
61106
+ function isPrivateUpstreamHost(raw) {
61107
+ let host;
61108
+ try {
61109
+ host = new URL(raw).hostname.toLowerCase();
61110
+ } catch {
61111
+ return false;
61112
+ }
61113
+ if (host === "localhost" || host.endsWith(".local") || host.endsWith(".lan") || host.endsWith(".internal")) return true;
61114
+ if (host.startsWith("[")) host = host.slice(1, -1);
61115
+ if (host.includes(":")) {
61116
+ if (host === "::1" || host === "::") return true;
61117
+ const first = host.split(":")[0] ?? "";
61118
+ if (/^f[cd]/.test(first)) return true;
61119
+ if (/^fe[89ab]/.test(first)) return true;
61120
+ const dotted = /::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(host);
61121
+ if (dotted && isPrivateIPv4(dotted[1])) return true;
61122
+ const hex = /::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host);
61123
+ if (hex) {
61124
+ const w1 = Number.parseInt(hex[1], 16);
61125
+ const w2 = Number.parseInt(hex[2], 16);
61126
+ if (isPrivateIPv4(`${w1 >> 8}.${w1 & 255}.${w2 >> 8}.${w2 & 255}`)) return true;
61127
+ }
61128
+ return false;
61129
+ }
61130
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) return isPrivateIPv4(host);
61131
+ return false;
61132
+ }
61133
+ function isPrivateIPv4(host) {
61134
+ const a = Number.parseInt(host.split(".")[0] ?? "", 10);
61135
+ const b2 = Number.parseInt(host.split(".")[1] ?? "", 10);
61136
+ if (a === 127 || a === 10 || a === 0) return true;
61137
+ if (a === 172 && b2 >= 16 && b2 <= 31) return true;
61138
+ if (a === 192 && b2 === 168) return true;
61139
+ if (a === 169 && b2 === 254) return true;
61140
+ return false;
61141
+ }
61142
+ function launcherInjectMcp(env, base, codexUpstream) {
61143
+ if (base === "pi" || base === "omp" || base === "opencode" || base === "hermes" || base === "dsh") return false;
61144
+ if (env.BILI_LAUNCHER_PLUGIN === "0") return false;
61145
+ if (base === "codex" && env.BILI_LAUNCHER_PLUGIN === void 0 && codexUpstream !== void 0 && isPrivateUpstreamHost(codexUpstream)) {
61146
+ return false;
61147
+ }
61148
+ return true;
60553
61149
  }
60554
61150
  function buildMcpConfig(origin) {
60555
61151
  const script = selfDistFile("mcp.js");
@@ -61259,6 +61855,7 @@ async function runLaunch(params, deps = {}) {
61259
61855
  const config = loadClientConfig(process.env, process.cwd());
61260
61856
  const base = baseClientName(params.client);
61261
61857
  const routes = discoverRoutes(base, config);
61858
+ const biliRoutes = loadRoutes(process.env);
61262
61859
  const domains = dedupeInOrder([...routes.httpsDomains, ...params.mitmDomains ?? []]);
61263
61860
  const handle2 = await ensureProxyRunning({ host, port, passthrough, debug, mitmDomains: domains, modelWindows: collectModelWindows(config) }, deps);
61264
61861
  console.error(
@@ -61288,11 +61885,16 @@ async function runLaunch(params, deps = {}) {
61288
61885
  );
61289
61886
  }
61290
61887
  }
61291
- const injectMcp = launcherInjectMcp(process.env, base);
61888
+ const codexUpstream = base === "codex" ? codexUpstreamUrl(config.codex) : void 0;
61889
+ const injectMcp = launcherInjectMcp(process.env, base, codexUpstream);
61292
61890
  if (injectMcp) {
61293
61891
  console.error(`bili: injecting native bili MCP tools for ${base} (disable with BILI_LAUNCHER_PLUGIN=0).`);
61294
61892
  } else if (base === "claude" || base === "codex") {
61295
- console.error("bili: native MCP tools disabled (BILI_LAUNCHER_PLUGIN=0) \u2014 running in pure wire mode.");
61893
+ if (process.env.BILI_LAUNCHER_PLUGIN === "0") {
61894
+ console.error("bili: native MCP tools disabled (BILI_LAUNCHER_PLUGIN=0) \u2014 running in pure wire mode.");
61895
+ } else {
61896
+ console.error(`bili: codex upstream ${codexUpstream} is local/private \u2014 self-hosted models cannot see codex namespace MCP tools; using wire-injected flat tools instead (force MCP with BILI_LAUNCHER_PLUGIN=1).`);
61897
+ }
61296
61898
  }
61297
61899
  const origin = handle2.origin;
61298
61900
  if (base === "pi") {
@@ -61352,18 +61954,40 @@ async function runLaunch(params, deps = {}) {
61352
61954
  const dshAcpPatch = writeDshAcpPatch(dshHomeDir);
61353
61955
  if (dshAcpPatch) clientArgs = dshArgsWithPatch(clientArgs, dshAcpPatch);
61354
61956
  } else if (base === "codex") {
61355
- const codexConversationId = injectMcp ? randomUUID3() : void 0;
61957
+ const codexConversationId = injectMcp ? randomUUID4() : void 0;
61356
61958
  if (directUrl) {
61357
61959
  env = { ...process.env, BILLION_CONTEXT_PROXY: origin };
61358
61960
  if (codexConversationId) clientArgs = [...buildCodexMcpArgs(origin, codexConversationId), ...clientArgs];
61359
61961
  } else {
61360
61962
  env = buildCodexEnv(origin, resolveCombinedCaPath(process.env), process.env);
61361
61963
  clientArgs = buildCodexArgs(origin, routes.httpRewrites, routes.httpsRewrites, clientArgs);
61964
+ const budgetArgs = await resolveCodexBudgetArgs({
61965
+ model: config.codex?.model,
61966
+ clientWindow: config.codex?.contextWindow,
61967
+ clientAutoCompactLimit: config.codex?.autoCompactLimit,
61968
+ routes: biliRoutes,
61969
+ upstreamUrl: codexUpstreamUrl(config.codex)
61970
+ });
61971
+ if (budgetArgs.length > 0) {
61972
+ clientArgs = [...budgetArgs, ...clientArgs];
61973
+ console.error(`bili: codex budget aligned \u2014 ${budgetArgs.slice(2).join(", ")} (model: ${config.codex?.model})`);
61974
+ }
61362
61975
  if (injectMcp && codexConversationId) clientArgs = [...buildCodexMcpArgs(origin, codexConversationId), ...clientArgs];
61363
61976
  }
61364
61977
  } else {
61365
61978
  env = directUrl ? buildClaudePluginEnv(origin, true, process.env) : buildClaudeEnv(origin, ca, routes.httpRewrites, routes.httpsRewrites, process.env);
61366
61979
  if (directUrl) env.BILLION_CONTEXT_PROXY = origin;
61980
+ const claudeBudget = await resolveClaudeBudgetEnv({
61981
+ model: nonEmpty2(process.env.ANTHROPIC_MODEL) ? process.env.ANTHROPIC_MODEL : config.claude?.model,
61982
+ userAutoCompactWindow: config.claude?.autoCompactWindow,
61983
+ shellAutoCompactWindow: process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW,
61984
+ routes: biliRoutes,
61985
+ upstreamUrl: config.claude?.anthropicBaseUrl ?? "https://api.anthropic.com"
61986
+ });
61987
+ Object.assign(env, claudeBudget);
61988
+ if (claudeBudget.CLAUDE_CODE_AUTO_COMPACT_WINDOW !== void 0) {
61989
+ console.error(`bili: claude budget aligned \u2014 CLAUDE_CODE_AUTO_COMPACT_WINDOW=${claudeBudget.CLAUDE_CODE_AUTO_COMPACT_WINDOW}`);
61990
+ }
61367
61991
  if (injectMcp) {
61368
61992
  const mcpFile = path13.join(os5.tmpdir(), `bili-mcp-${Date.now()}.json`);
61369
61993
  fs10.writeFileSync(mcpFile, JSON.stringify(buildMcpConfig(origin)));