billion-context 0.1.59 → 0.1.60-pr.306.165
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 +302 -62
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -30021,9 +30021,9 @@ var require_sha256 = __commonJS({
|
|
|
30021
30021
|
var forge2 = require_forge();
|
|
30022
30022
|
require_md();
|
|
30023
30023
|
require_util7();
|
|
30024
|
-
var
|
|
30025
|
-
forge2.md.sha256 = forge2.md.algorithms.sha256 =
|
|
30026
|
-
|
|
30024
|
+
var sha2562 = module.exports = forge2.sha256 = forge2.sha256 || {};
|
|
30025
|
+
forge2.md.sha256 = forge2.md.algorithms.sha256 = sha2562;
|
|
30026
|
+
sha2562.create = function() {
|
|
30027
30027
|
if (!_initialized) {
|
|
30028
30028
|
_init();
|
|
30029
30029
|
}
|
|
@@ -47852,6 +47852,7 @@ function rejectLegacyRoute(key, value) {
|
|
|
47852
47852
|
// src/server.ts
|
|
47853
47853
|
import http from "http";
|
|
47854
47854
|
import fs6 from "fs";
|
|
47855
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
47855
47856
|
|
|
47856
47857
|
// src/compress-settings.ts
|
|
47857
47858
|
function resolveContextLimitValue(raw, nativeLimit) {
|
|
@@ -49830,15 +49831,17 @@ function normalizeSseLineEndings(buf) {
|
|
|
49830
49831
|
}
|
|
49831
49832
|
|
|
49832
49833
|
// src/loop/tag-echo-filter.ts
|
|
49833
|
-
var PAIRED = /\x3cacp\s[^<>]
|
|
49834
|
-
var
|
|
49834
|
+
var PAIRED = /\x3cacp\s[^<>]{0,256}>([^<>]{0,64})<\/acp>/;
|
|
49835
|
+
var LONE_OPEN = /\x3cacp(?:\s[^<>]{0,256})?>/;
|
|
49836
|
+
var LONE_CLOSE = /<\/acp(?=[\s>])[^<>]{0,32}>/;
|
|
49835
49837
|
var PARTIAL_TAIL = /(\x3cacp\s[^<>]*|<\/?a?c?p?)$/;
|
|
49836
|
-
var
|
|
49838
|
+
var TRUNC_OPEN = /\x3cacp\s[^<>]*$/;
|
|
49837
49839
|
var CLOSE_TAG = "</acp";
|
|
49838
49840
|
var HOLD_LIMIT = 128;
|
|
49841
|
+
var TAG_OPEN_CAP = 4096;
|
|
49839
49842
|
var SWALLOW_CAP = 80;
|
|
49840
49843
|
function stripAcpTags(text) {
|
|
49841
|
-
return text.replace(new RegExp(PAIRED.source, "g"), "").replace(new RegExp(
|
|
49844
|
+
return text.replace(new RegExp(PAIRED.source, "g"), "").replace(new RegExp(LONE_OPEN.source, "g"), "").replace(new RegExp(LONE_CLOSE.source, "g"), "").replace(new RegExp(TRUNC_OPEN.source), "");
|
|
49842
49845
|
}
|
|
49843
49846
|
function containsRenderTagText(s3) {
|
|
49844
49847
|
return /\x3c\/?acp(?=[\s>])/.test(s3) || /\\u003c\/?acp(?=[\s>\\])/.test(s3);
|
|
@@ -49881,15 +49884,26 @@ function createTagEchoFilter(onDrop) {
|
|
|
49881
49884
|
return out;
|
|
49882
49885
|
}
|
|
49883
49886
|
const p2 = PAIRED.exec(buf);
|
|
49884
|
-
const
|
|
49885
|
-
|
|
49886
|
-
|
|
49887
|
-
|
|
49887
|
+
const o = LONE_OPEN.exec(buf);
|
|
49888
|
+
const c = LONE_CLOSE.exec(buf);
|
|
49889
|
+
let m2 = null;
|
|
49890
|
+
for (const cand of [p2, o, c]) {
|
|
49891
|
+
if (cand && (m2 === null || cand.index < m2.index)) m2 = cand;
|
|
49892
|
+
}
|
|
49888
49893
|
if (!m2) {
|
|
49889
49894
|
const t = PARTIAL_TAIL.exec(buf);
|
|
49890
|
-
if (t
|
|
49891
|
-
|
|
49892
|
-
|
|
49895
|
+
if (t) {
|
|
49896
|
+
const definite = /^\x3cacp\s/.test(t[0]);
|
|
49897
|
+
const cap = definite ? TAG_OPEN_CAP : HOLD_LIMIT;
|
|
49898
|
+
if (t[0].length <= cap) {
|
|
49899
|
+
held = t[0];
|
|
49900
|
+
out += buf.slice(0, buf.length - t[0].length);
|
|
49901
|
+
} else if (definite) {
|
|
49902
|
+
drop(t[0]);
|
|
49903
|
+
out += buf.slice(0, buf.length - t[0].length);
|
|
49904
|
+
} else {
|
|
49905
|
+
out += buf;
|
|
49906
|
+
}
|
|
49893
49907
|
} else {
|
|
49894
49908
|
out += buf;
|
|
49895
49909
|
}
|
|
@@ -49898,8 +49912,7 @@ function createTagEchoFilter(onDrop) {
|
|
|
49898
49912
|
drop(m2[0]);
|
|
49899
49913
|
out += buf.slice(0, m2.index);
|
|
49900
49914
|
buf = buf.slice(m2.index + m2[0].length);
|
|
49901
|
-
|
|
49902
|
-
if (!wasPaired && /^\x3cacp\s/.test(m2[0])) {
|
|
49915
|
+
if (m2 === o && /^\x3cacp\s/.test(m2[0])) {
|
|
49903
49916
|
swallowUntilClose = true;
|
|
49904
49917
|
swallowed = "";
|
|
49905
49918
|
}
|
|
@@ -49913,14 +49926,19 @@ function createTagEchoFilter(onDrop) {
|
|
|
49913
49926
|
return process2(chunk);
|
|
49914
49927
|
},
|
|
49915
49928
|
flush() {
|
|
49916
|
-
|
|
49929
|
+
const rest = swallowed + held;
|
|
49930
|
+
const wasSwallowing = swallowUntilClose;
|
|
49917
49931
|
swallowed = "";
|
|
49918
49932
|
held = "";
|
|
49919
49933
|
swallowUntilClose = false;
|
|
49920
|
-
|
|
49934
|
+
if (wasSwallowing) {
|
|
49935
|
+
if (rest.length > 0) drop(rest);
|
|
49936
|
+
return "";
|
|
49937
|
+
}
|
|
49938
|
+
const t = new RegExp(TRUNC_OPEN.source).exec(rest);
|
|
49921
49939
|
if (t) {
|
|
49922
49940
|
drop(t[0]);
|
|
49923
|
-
|
|
49941
|
+
return rest.slice(0, t.index);
|
|
49924
49942
|
}
|
|
49925
49943
|
return rest;
|
|
49926
49944
|
},
|
|
@@ -50210,16 +50228,21 @@ TASK: The conversation segment below (messages ${startRef}\u2013${endRef}) must
|
|
|
50210
50228
|
clearTimer();
|
|
50211
50229
|
}
|
|
50212
50230
|
}
|
|
50231
|
+
var ABORTED_FAILURE = { kind: "aborted", detail: "the client disconnected during preflight compression" };
|
|
50213
50232
|
async function preflightCompress(deps, messages) {
|
|
50214
50233
|
const limit = deps.config.modelContextLimit;
|
|
50215
|
-
const result = { compressedRanges: 0, savedTokens: 0 };
|
|
50234
|
+
const result = { compressedRanges: 0, savedTokens: 0, payloadEstimate: estimateCoreMessages(messages) };
|
|
50216
50235
|
if (limit <= 0) return result;
|
|
50217
50236
|
const budget = Math.max(MIN_CHUNK_TOKENS, Math.floor(limit * CHUNK_FRACTION));
|
|
50218
50237
|
const minChars = deps.config.compress.minCompressRange;
|
|
50219
50238
|
let currentTokens = deps.session.stats.lastInputTokens;
|
|
50220
50239
|
let startTokens = -1;
|
|
50240
|
+
let failure;
|
|
50221
50241
|
for (let round = 0; round < MAX_PREFLIGHT_ROUNDS; round++) {
|
|
50222
|
-
if (deps.signal?.aborted)
|
|
50242
|
+
if (deps.signal?.aborted) {
|
|
50243
|
+
failure = ABORTED_FAILURE;
|
|
50244
|
+
break;
|
|
50245
|
+
}
|
|
50223
50246
|
const turn = deps.core.processTurn({
|
|
50224
50247
|
messages,
|
|
50225
50248
|
state: deps.session.state,
|
|
@@ -50229,19 +50252,29 @@ async function preflightCompress(deps, messages) {
|
|
|
50229
50252
|
});
|
|
50230
50253
|
deps.session.state = turn.state;
|
|
50231
50254
|
currentTokens = Math.max(deps.session.stats.lastInputTokens, estimateCoreMessages(turn.messages));
|
|
50255
|
+
result.payloadEstimate = estimateCoreMessages(turn.messages);
|
|
50232
50256
|
if (startTokens < 0) startTokens = currentTokens;
|
|
50233
50257
|
if (currentTokens < limit) break;
|
|
50234
50258
|
const ranges = viableRanges(turn.nudge?.compressibleRanges ?? []);
|
|
50235
|
-
if (ranges.length === 0)
|
|
50259
|
+
if (ranges.length === 0) {
|
|
50260
|
+
failure = { kind: "exhausted", detail: "no compressible ranges remain in the conversation" };
|
|
50261
|
+
break;
|
|
50262
|
+
}
|
|
50236
50263
|
const range = [...ranges].sort((a, b2) => refNum2(a.startRef) - refNum2(b2.startRef))[0];
|
|
50237
50264
|
const { refToIdx } = refMaps(messages, deps.session.state);
|
|
50238
50265
|
const startIdx = refToIdx.get(range.startRef);
|
|
50239
50266
|
const endIdx = refToIdx.get(range.endRef);
|
|
50240
|
-
if (startIdx === void 0 || endIdx === void 0 || startIdx > endIdx)
|
|
50267
|
+
if (startIdx === void 0 || endIdx === void 0 || startIdx > endIdx) {
|
|
50268
|
+
failure = { kind: "exhausted", detail: "the compressible range no longer resolves to payload messages" };
|
|
50269
|
+
break;
|
|
50270
|
+
}
|
|
50241
50271
|
let appliedThisRound = 0;
|
|
50242
50272
|
for (const [cs2, ce2] of splitChunks(messages, startIdx, endIdx, budget)) {
|
|
50243
50273
|
if (currentTokens < limit) break;
|
|
50244
|
-
if (deps.signal?.aborted)
|
|
50274
|
+
if (deps.signal?.aborted) {
|
|
50275
|
+
failure = ABORTED_FAILURE;
|
|
50276
|
+
break;
|
|
50277
|
+
}
|
|
50245
50278
|
const maps = refMaps(messages, deps.session.state);
|
|
50246
50279
|
const startRef = maps.idxToRef.get(cs2);
|
|
50247
50280
|
const endRef = maps.idxToRef.get(ce2);
|
|
@@ -50254,8 +50287,17 @@ async function preflightCompress(deps, messages) {
|
|
|
50254
50287
|
summary = await summarizeRange(deps, content, startRef, endRef);
|
|
50255
50288
|
} catch (err2) {
|
|
50256
50289
|
if (err2 instanceof UpstreamHttpError) {
|
|
50290
|
+
failure = {
|
|
50291
|
+
kind: "upstream",
|
|
50292
|
+
status: err2.status,
|
|
50293
|
+
detail: err2.status === 429 ? `the summarization call was rate-limited by the upstream (HTTP 429)` : `the summarization call was rejected by the upstream (HTTP ${err2.status})`
|
|
50294
|
+
};
|
|
50257
50295
|
deps.log("warn", `[preflight] summarization failed: HTTP ${err2.status} ${err2.body.slice(0, 200)}`);
|
|
50296
|
+
} else if (deps.signal?.aborted) {
|
|
50297
|
+
failure = ABORTED_FAILURE;
|
|
50298
|
+
deps.log("warn", `[preflight] summarization aborted: client disconnected`);
|
|
50258
50299
|
} else {
|
|
50300
|
+
failure = { kind: "upstream", detail: `the summarization call failed: ${String(err2)}` };
|
|
50259
50301
|
deps.log("warn", `[preflight] summarization failed: ${String(err2)}`);
|
|
50260
50302
|
}
|
|
50261
50303
|
break;
|
|
@@ -50280,10 +50322,19 @@ async function preflightCompress(deps, messages) {
|
|
|
50280
50322
|
appliedThisRound += 1;
|
|
50281
50323
|
result.compressedRanges += 1;
|
|
50282
50324
|
}
|
|
50283
|
-
if (appliedThisRound === 0)
|
|
50325
|
+
if (appliedThisRound === 0) {
|
|
50326
|
+
if (!failure) {
|
|
50327
|
+
failure = { kind: "exhausted", detail: "no range could be compressed (chunks below minCompressRange or the summarization responses were unusable)" };
|
|
50328
|
+
}
|
|
50329
|
+
break;
|
|
50330
|
+
}
|
|
50331
|
+
}
|
|
50332
|
+
if (!failure && currentTokens >= limit) {
|
|
50333
|
+
failure = { kind: "exhausted", detail: `the compress budget was exhausted after ${MAX_PREFLIGHT_ROUNDS} rounds` };
|
|
50284
50334
|
}
|
|
50285
50335
|
if (result.compressedRanges > 0) deps.session.stats.lastInputTokens = currentTokens;
|
|
50286
50336
|
result.savedTokens = Math.max(0, startTokens - currentTokens);
|
|
50337
|
+
if (currentTokens >= limit) result.failure = failure;
|
|
50287
50338
|
return result;
|
|
50288
50339
|
}
|
|
50289
50340
|
|
|
@@ -52129,8 +52180,15 @@ ${systemPrompt}` : systemPrompt;
|
|
|
52129
52180
|
} else if (type === "message_delta") {
|
|
52130
52181
|
const u2 = data.usage ?? {};
|
|
52131
52182
|
if (typeof u2.output_tokens === "number") roundOutput = u2.output_tokens;
|
|
52132
|
-
|
|
52133
|
-
|
|
52183
|
+
const input = typeof u2.input_tokens === "number" ? u2.input_tokens : void 0;
|
|
52184
|
+
const cached = typeof u2.cache_read_input_tokens === "number" ? u2.cache_read_input_tokens : void 0;
|
|
52185
|
+
if (input !== void 0 && input > 0 && cached !== void 0) {
|
|
52186
|
+
roundInput = input;
|
|
52187
|
+
roundCached = cached;
|
|
52188
|
+
} else {
|
|
52189
|
+
if (input !== void 0 && input > 0) roundInput = input;
|
|
52190
|
+
if (cached !== void 0 && cached > 0) roundCached = cached;
|
|
52191
|
+
}
|
|
52134
52192
|
const d = data.delta ?? {};
|
|
52135
52193
|
if (typeof d.stop_reason === "string") stopReason = d.stop_reason;
|
|
52136
52194
|
if (!usageYielded) {
|
|
@@ -52566,6 +52624,102 @@ function preferPromptCacheKeyIdentity(identity, body) {
|
|
|
52566
52624
|
return { ...identity, value: pck, source: "prompt-cache-key", clientProvided: true };
|
|
52567
52625
|
}
|
|
52568
52626
|
|
|
52627
|
+
// src/prefix-affinity.ts
|
|
52628
|
+
import { createHash as createHash5 } from "crypto";
|
|
52629
|
+
var MIN_CANONICAL_BYTES = 24;
|
|
52630
|
+
var MAX_TRACKED_SESSIONS = 256;
|
|
52631
|
+
var TTL_MS2 = 7 * 24 * 60 * 60 * 1e3;
|
|
52632
|
+
function stableStringify(value) {
|
|
52633
|
+
return JSON.stringify(sortKeys(value));
|
|
52634
|
+
}
|
|
52635
|
+
function sortKeys(value) {
|
|
52636
|
+
if (Array.isArray(value)) return value.map(sortKeys);
|
|
52637
|
+
if (value && typeof value === "object") {
|
|
52638
|
+
const record = value;
|
|
52639
|
+
const out = {};
|
|
52640
|
+
for (const key of Object.keys(record).sort()) out[key] = sortKeys(record[key]);
|
|
52641
|
+
return out;
|
|
52642
|
+
}
|
|
52643
|
+
return value;
|
|
52644
|
+
}
|
|
52645
|
+
function sha256(text) {
|
|
52646
|
+
return createHash5("sha256").update(text, "utf8").digest("hex");
|
|
52647
|
+
}
|
|
52648
|
+
function hasUserMessage(messages) {
|
|
52649
|
+
return messages.some((m2) => !!m2 && typeof m2 === "object" && m2.role === "user");
|
|
52650
|
+
}
|
|
52651
|
+
function chainHashes(messages) {
|
|
52652
|
+
const hashes = [];
|
|
52653
|
+
let prev = "";
|
|
52654
|
+
let bytes = 0;
|
|
52655
|
+
for (const message of messages) {
|
|
52656
|
+
const canonical = stableStringify(message);
|
|
52657
|
+
bytes += canonical.length;
|
|
52658
|
+
prev = sha256(`${prev}\0${canonical}`);
|
|
52659
|
+
hashes.push(prev);
|
|
52660
|
+
}
|
|
52661
|
+
return bytes >= MIN_CANONICAL_BYTES ? hashes : [];
|
|
52662
|
+
}
|
|
52663
|
+
var PrefixAffinityResolver = class {
|
|
52664
|
+
trackedChains = /* @__PURE__ */ new Map();
|
|
52665
|
+
/**
|
|
52666
|
+
* Resolve an anonymous request to a session id.
|
|
52667
|
+
* Returns null when the request carries no usable conversation signal
|
|
52668
|
+
* (caller keeps the #286 explicit 400).
|
|
52669
|
+
*/
|
|
52670
|
+
resolve(messages) {
|
|
52671
|
+
const hashes = chainHashes(messages);
|
|
52672
|
+
if (hashes.length === 0 || !hasUserMessage(messages)) return null;
|
|
52673
|
+
const tailHash = hashes[hashes.length - 1];
|
|
52674
|
+
const tracked = this.trackedChains;
|
|
52675
|
+
this.expire(tracked);
|
|
52676
|
+
let best;
|
|
52677
|
+
for (const entry of tracked.values()) {
|
|
52678
|
+
if (entry.depth > hashes.length) continue;
|
|
52679
|
+
if (hashes[entry.depth - 1] !== entry.tailHash) continue;
|
|
52680
|
+
if (!best || entry.depth > best.depth || entry.depth === best.depth && entry.lastSeen > best.lastSeen) best = entry;
|
|
52681
|
+
}
|
|
52682
|
+
if (best) {
|
|
52683
|
+
return {
|
|
52684
|
+
sessionId: best.sessionId,
|
|
52685
|
+
matchedDepth: best.depth,
|
|
52686
|
+
storedDepth: best.depth,
|
|
52687
|
+
incomingDepth: hashes.length,
|
|
52688
|
+
tailHash
|
|
52689
|
+
};
|
|
52690
|
+
}
|
|
52691
|
+
const sessionId = `pfa-${sha256(`${tailHash}\0${hashes.length}`).slice(0, 16)}`;
|
|
52692
|
+
return { sessionId, matchedDepth: 0, storedDepth: 0, incomingDepth: hashes.length, tailHash };
|
|
52693
|
+
}
|
|
52694
|
+
/** Record the chain of a session (on creation and after every anonymous
|
|
52695
|
+
* request — the incoming history is the truth, appends extend it). */
|
|
52696
|
+
note(sessionId, depth, tailHash) {
|
|
52697
|
+
const tracked = this.trackedChains;
|
|
52698
|
+
tracked.delete(sessionId);
|
|
52699
|
+
tracked.set(sessionId, { sessionId, depth, tailHash, lastSeen: Date.now() });
|
|
52700
|
+
while (tracked.size > MAX_TRACKED_SESSIONS) {
|
|
52701
|
+
const oldest = [...tracked.values()].sort((a, b2) => a.lastSeen - b2.lastSeen)[0];
|
|
52702
|
+
if (!oldest) break;
|
|
52703
|
+
tracked.delete(oldest.sessionId);
|
|
52704
|
+
}
|
|
52705
|
+
}
|
|
52706
|
+
/** Drop tracking for a removed session. */
|
|
52707
|
+
forget(sessionId) {
|
|
52708
|
+
this.trackedChains.delete(sessionId);
|
|
52709
|
+
}
|
|
52710
|
+
trackedSessionIds() {
|
|
52711
|
+
return [...this.trackedChains.keys()];
|
|
52712
|
+
}
|
|
52713
|
+
expire(tracked) {
|
|
52714
|
+
if (tracked.size === 0) return;
|
|
52715
|
+
const now = Date.now();
|
|
52716
|
+
for (const [id, entry] of tracked) {
|
|
52717
|
+
if (now - entry.lastSeen > TTL_MS2) tracked.delete(id);
|
|
52718
|
+
}
|
|
52719
|
+
}
|
|
52720
|
+
};
|
|
52721
|
+
var prefixAffinity = new PrefixAffinityResolver();
|
|
52722
|
+
|
|
52569
52723
|
// node_modules/acp-kernel/dist/panel/index.js
|
|
52570
52724
|
function topicFallback(summary) {
|
|
52571
52725
|
const first = summary.split(/[.\n]/)[0] ?? "";
|
|
@@ -53791,7 +53945,7 @@ function collectModelWindows(config) {
|
|
|
53791
53945
|
}
|
|
53792
53946
|
|
|
53793
53947
|
// src/discover.ts
|
|
53794
|
-
var
|
|
53948
|
+
var TTL_MS3 = 2e3;
|
|
53795
53949
|
function unwrapUpstream(url) {
|
|
53796
53950
|
const idx = url.indexOf("/bili/");
|
|
53797
53951
|
return idx >= 0 ? url.slice(idx + "/bili/".length) : url;
|
|
@@ -53859,7 +54013,7 @@ function mtimesEqual(a, b2) {
|
|
|
53859
54013
|
var cache3 = null;
|
|
53860
54014
|
function discoverMitmDomains(env = process.env) {
|
|
53861
54015
|
const now = Date.now();
|
|
53862
|
-
if (cache3 && now - cache3.checkedAt <
|
|
54016
|
+
if (cache3 && now - cache3.checkedAt < TTL_MS3) {
|
|
53863
54017
|
return cache3.domains;
|
|
53864
54018
|
}
|
|
53865
54019
|
const paths = configFilePaths(env);
|
|
@@ -54721,6 +54875,7 @@ async function decodeRequestBody(contentEncoding, input, maxOutputBytes) {
|
|
|
54721
54875
|
function bodyDumpEnabled() {
|
|
54722
54876
|
return process.env.ACP_DUMP_BODY === "1";
|
|
54723
54877
|
}
|
|
54878
|
+
var BILI_HOP_HEADER = "x-bili-hop";
|
|
54724
54879
|
function parseLauncherModelWindows(raw) {
|
|
54725
54880
|
if (!raw) return {};
|
|
54726
54881
|
try {
|
|
@@ -54739,10 +54894,25 @@ var LAUNCHER_MODEL_WINDOWS = parseLauncherModelWindows(process.env.BILI_LAUNCHER
|
|
|
54739
54894
|
function launcherContextWindow(model) {
|
|
54740
54895
|
return LAUNCHER_MODEL_WINDOWS[model];
|
|
54741
54896
|
}
|
|
54897
|
+
function anthropicBetaContextWindow(headers) {
|
|
54898
|
+
const raw = headers["anthropic-beta"];
|
|
54899
|
+
if (raw === void 0) return void 0;
|
|
54900
|
+
const list = Array.isArray(raw) ? raw.join(",") : raw;
|
|
54901
|
+
let best;
|
|
54902
|
+
for (const part of list.split(",")) {
|
|
54903
|
+
const m2 = /^context-(\d+)m\b/.exec(part.trim().toLowerCase());
|
|
54904
|
+
if (!m2) continue;
|
|
54905
|
+
const n = Number.parseInt(m2[1], 10);
|
|
54906
|
+
if (!Number.isFinite(n) || n <= 0) continue;
|
|
54907
|
+
const w2 = n * 1e6;
|
|
54908
|
+
if (best === void 0 || w2 > best) best = w2;
|
|
54909
|
+
}
|
|
54910
|
+
return best;
|
|
54911
|
+
}
|
|
54742
54912
|
function safeSessionId(id) {
|
|
54743
54913
|
return (id ?? "unknown").replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
54744
54914
|
}
|
|
54745
|
-
var NO_IDENTITY_MESSAGE = "Missing stable conversation identity. Send one of the headers: x-session-id, x-session-affinity, x-acp-session, x-opencode-session, x-claude-code-session-id, session-id \u2014 or body session_id / prompt_cache_key (responses/openai).
|
|
54915
|
+
var NO_IDENTITY_MESSAGE = "Missing stable conversation identity. Send one of the headers: x-session-id, x-session-affinity, x-acp-session, x-opencode-session, x-claude-code-session-id, session-id \u2014 or body session_id / prompt_cache_key (responses/openai). Requests replaying a conversation history are matched by content prefix affinity (#309); this one carries no usable history signal.";
|
|
54746
54916
|
var UPSTREAM_HOP_HEADERS = /* @__PURE__ */ new Set([
|
|
54747
54917
|
"host",
|
|
54748
54918
|
"content-length",
|
|
@@ -54816,6 +54986,7 @@ async function startServer(opts) {
|
|
|
54816
54986
|
const core = createCore();
|
|
54817
54987
|
const config = opts.kernelConfig;
|
|
54818
54988
|
const log2 = (level, msg) => logMsg(opts, level, msg);
|
|
54989
|
+
const instanceId = randomUUID2();
|
|
54819
54990
|
await initSessions();
|
|
54820
54991
|
loadConversations();
|
|
54821
54992
|
log2("info", `[persist] ${getStore().enabled ? "enabled" : "disabled"}`);
|
|
@@ -54825,7 +54996,7 @@ async function startServer(opts) {
|
|
|
54825
54996
|
void loadRegistry();
|
|
54826
54997
|
const server = http.createServer(async (req, res) => {
|
|
54827
54998
|
try {
|
|
54828
|
-
await handle(req, res, opts, core, config, log2);
|
|
54999
|
+
await handle(req, res, opts, core, config, log2, instanceId);
|
|
54829
55000
|
} catch (err2) {
|
|
54830
55001
|
const msg = String(err2);
|
|
54831
55002
|
log2("error", msg);
|
|
@@ -54950,7 +55121,7 @@ function adminTrustedHosts(bindHost, port) {
|
|
|
54950
55121
|
}
|
|
54951
55122
|
return set;
|
|
54952
55123
|
}
|
|
54953
|
-
async function handle(req, res, opts, core, config, log2) {
|
|
55124
|
+
async function handle(req, res, opts, core, config, log2, instanceId) {
|
|
54954
55125
|
const isAdminPath = req.url === "/__bili/" || req.url?.startsWith("/__bili/") || req.url === "/__acp/" || req.url?.startsWith("/__acp/");
|
|
54955
55126
|
if (isAdminPath && !isLoopbackAddress(req.socket.remoteAddress)) {
|
|
54956
55127
|
res.writeHead(403, { "content-type": "application/json" });
|
|
@@ -55111,6 +55282,11 @@ async function handle(req, res, opts, core, config, log2) {
|
|
|
55111
55282
|
res.end(JSON.stringify({ error: { type: "invalid_request", message: String(err2) } }));
|
|
55112
55283
|
return;
|
|
55113
55284
|
}
|
|
55285
|
+
const hopMarker = headerValue2(req, BILI_HOP_HEADER);
|
|
55286
|
+
if (hopMarker !== void 0) {
|
|
55287
|
+
const selfLoop = hopMarker === instanceId;
|
|
55288
|
+
log2("warn", selfLoop ? `[chain] inbound request carries THIS instance's ${BILI_HOP_HEADER} marker (${hopMarker}) \u2014 self-loop detected. Passing through without processing; check your upstream config (it may point back to this instance).` : `[chain] inbound request carries ${BILI_HOP_HEADER} from another bili instance (${hopMarker}) \u2014 bili\u2192bili chain detected. Passing through without processing to avoid double compression; keep only one bili instance in the chain.`);
|
|
55289
|
+
}
|
|
55114
55290
|
const countTokens = isCountTokensRequest(req.method ?? "GET", urlPath, bodyBuffer.length > 0);
|
|
55115
55291
|
let parsed = null;
|
|
55116
55292
|
if (protocol && bodyBuffer.length > 0) {
|
|
@@ -55158,13 +55334,14 @@ ${bodyBuffer.toString("utf8")}`);
|
|
|
55158
55334
|
return void 0;
|
|
55159
55335
|
}
|
|
55160
55336
|
})();
|
|
55337
|
+
const betaWindow = anthropicBetaContextWindow(req.headers);
|
|
55161
55338
|
const pluginWindow = pluginReportedContextWindow(req.headers);
|
|
55162
55339
|
const launcherWindow = launcherContextWindow(model);
|
|
55163
55340
|
const peekWindow = host ? peekRegistryContext(model, host) : void 0;
|
|
55164
55341
|
const configuredWindow = resolveConfiguredContextLimit(opts.routes, embeddedUrl, model);
|
|
55165
|
-
let native = pluginWindow ?? launcherWindow ?? peekWindow ?? configuredWindow ?? lookupContextLimit(model);
|
|
55342
|
+
let native = betaWindow ?? pluginWindow ?? launcherWindow ?? peekWindow ?? configuredWindow ?? lookupContextLimit(model);
|
|
55166
55343
|
const operatorWindowTuned = resolveCompress(opts.routes, embeddedUrl, model, opts.compress).modelContextLimit !== void 0;
|
|
55167
|
-
nativeFromFallback = !pluginWindow && !launcherWindow && !peekWindow && !configuredWindow && !operatorWindowTuned;
|
|
55344
|
+
nativeFromFallback = !betaWindow && !pluginWindow && !launcherWindow && !peekWindow && !configuredWindow && !operatorWindowTuned;
|
|
55168
55345
|
if (!native && host) {
|
|
55169
55346
|
native = await contextFromRegistry(model, host);
|
|
55170
55347
|
if (native) nativeFromFallback = false;
|
|
@@ -55174,7 +55351,7 @@ ${bodyBuffer.toString("utf8")}`);
|
|
|
55174
55351
|
}
|
|
55175
55352
|
}
|
|
55176
55353
|
let prepared = null;
|
|
55177
|
-
if (!opts.passthrough && protocol && parsed && typeof parsed === "object") {
|
|
55354
|
+
if (!opts.passthrough && hopMarker === void 0 && protocol && parsed && typeof parsed === "object") {
|
|
55178
55355
|
const sessionHeader = headerValue2(req, opts.sessionHeader);
|
|
55179
55356
|
let pluginAgent = pluginAgentHeader(req.headers);
|
|
55180
55357
|
let pluginConversation = pluginConversationHeader(req.headers);
|
|
@@ -55194,13 +55371,25 @@ ${bodyBuffer.toString("utf8")}`);
|
|
|
55194
55371
|
parsed.instructions
|
|
55195
55372
|
);
|
|
55196
55373
|
const clientProvided = protocol === "responses" ? responsesIdentity?.clientProvided ?? false : protocol === "openai" ? openaiIdentity?.clientProvided ?? false : !!convHeader;
|
|
55374
|
+
let anonAffinity = null;
|
|
55197
55375
|
if (!clientProvided) {
|
|
55198
|
-
|
|
55199
|
-
|
|
55200
|
-
|
|
55201
|
-
|
|
55376
|
+
const anonMessages = protocol === "responses" ? parsed.input ?? [] : parsed.messages ?? [];
|
|
55377
|
+
anonAffinity = prefixAffinity.resolve(Array.isArray(anonMessages) ? anonMessages : []);
|
|
55378
|
+
if (!anonAffinity) {
|
|
55379
|
+
log2("warn", `400: no stable conversation identity on ${protocol} request \u2192 ${upstreamOrigin}; refusing to create a content-fingerprint session (#286)`);
|
|
55380
|
+
res.writeHead(400, { "content-type": "application/json" });
|
|
55381
|
+
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 } }));
|
|
55382
|
+
return;
|
|
55383
|
+
}
|
|
55384
|
+
if (anonAffinity.matchedDepth > 0) {
|
|
55385
|
+
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)`);
|
|
55386
|
+
log("info", `[prefix-affinity] session ${anonAffinity.sessionId} matched at depth ${anonAffinity.matchedDepth}/${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)})`);
|
|
55387
|
+
} else {
|
|
55388
|
+
log2("info", `[prefix-affinity] new anonymous session ${anonAffinity.sessionId} (depth=${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)})`);
|
|
55389
|
+
log("info", `[prefix-affinity] new session ${anonAffinity.sessionId} at depth ${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)})`);
|
|
55390
|
+
}
|
|
55202
55391
|
}
|
|
55203
|
-
const sessionId = conversation;
|
|
55392
|
+
const sessionId = anonAffinity ? anonAffinity.sessionId : conversation;
|
|
55204
55393
|
const bodyIdentity = responsesIdentity ?? openaiIdentity;
|
|
55205
55394
|
const affinity = affinityToken(bodyIdentity ?? {
|
|
55206
55395
|
value: clientConv ?? conversation,
|
|
@@ -55208,8 +55397,15 @@ ${bodyBuffer.toString("utf8")}`);
|
|
|
55208
55397
|
clientProvided: !!clientConv
|
|
55209
55398
|
});
|
|
55210
55399
|
const clientLabel = bodyIdentity?.clientProvided ? bodyIdentity.value : clientConversationHeader(req.headers);
|
|
55211
|
-
const session = getSession(sessionId, { protocol, upstreamOrigin, label: clientLabel ?? void 0 });
|
|
55212
|
-
if (
|
|
55400
|
+
const session = getSession(sessionId, { protocol, upstreamOrigin, label: clientLabel ?? (anonAffinity ? "prefix-affinity" : void 0) });
|
|
55401
|
+
if (anonAffinity) {
|
|
55402
|
+
prefixAffinity.note(sessionId, anonAffinity.incomingDepth, anonAffinity.tailHash);
|
|
55403
|
+
session.metadata.anonymousPrefixAffinity = {
|
|
55404
|
+
depth: anonAffinity.incomingDepth,
|
|
55405
|
+
tailHash: anonAffinity.tailHash
|
|
55406
|
+
};
|
|
55407
|
+
}
|
|
55408
|
+
if (!pluginAgent && !anonAffinity) {
|
|
55213
55409
|
const identityAgent = consumePluginRegisterFor(clientConv ?? conversation);
|
|
55214
55410
|
if (identityAgent) {
|
|
55215
55411
|
pluginAgent = identityAgent;
|
|
@@ -55263,7 +55459,7 @@ ${bodyBuffer.toString("utf8")}`);
|
|
|
55263
55459
|
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);
|
|
55264
55460
|
prepared = runPrepare();
|
|
55265
55461
|
if (!countTokens && !responsesCompact) {
|
|
55266
|
-
|
|
55462
|
+
const outcome = await preflightCompressIfNeeded(
|
|
55267
55463
|
prepared,
|
|
55268
55464
|
runPrepare,
|
|
55269
55465
|
req,
|
|
@@ -55274,10 +55470,29 @@ ${bodyBuffer.toString("utf8")}`);
|
|
|
55274
55470
|
parsed.model,
|
|
55275
55471
|
route,
|
|
55276
55472
|
affinity,
|
|
55277
|
-
log2
|
|
55473
|
+
log2,
|
|
55474
|
+
instanceId
|
|
55278
55475
|
);
|
|
55476
|
+
if (isPreflightFailFast(outcome)) {
|
|
55477
|
+
if (outcome.respond && !res.headersSent && !res.destroyed) {
|
|
55478
|
+
res.writeHead(outcome.status, {
|
|
55479
|
+
"content-type": "application/json",
|
|
55480
|
+
...outcome.status === 503 ? { "retry-after": "30" } : {}
|
|
55481
|
+
});
|
|
55482
|
+
res.end(JSON.stringify({
|
|
55483
|
+
error: {
|
|
55484
|
+
type: "server_error",
|
|
55485
|
+
code: "preflight_compress_failed",
|
|
55486
|
+
message: outcome.message,
|
|
55487
|
+
retryable: outcome.retryable
|
|
55488
|
+
}
|
|
55489
|
+
}));
|
|
55490
|
+
}
|
|
55491
|
+
return;
|
|
55492
|
+
}
|
|
55493
|
+
prepared = outcome;
|
|
55279
55494
|
}
|
|
55280
|
-
await forward(req, res, opts, prepared.body, prepared, core, reqConfig, log2, route, affinity);
|
|
55495
|
+
await forward(req, res, opts, prepared.body, prepared, core, reqConfig, log2, route, instanceId, affinity);
|
|
55281
55496
|
if (prepared) {
|
|
55282
55497
|
rememberPluginMessages(sessionId, prepared.processedMessages, prepared.originalMessages, prepared.nudge);
|
|
55283
55498
|
}
|
|
@@ -55290,7 +55505,7 @@ ${bodyBuffer.toString("utf8")}`);
|
|
|
55290
55505
|
if (protocol === null && !opts.passthrough) {
|
|
55291
55506
|
log2("warn", `unrecognized path ${maskUrlsInText(req.url ?? "")} \u2014 not a known protocol (/chat/completions, /v1/messages, /responses, /responses/compact); forwarding unchanged`);
|
|
55292
55507
|
}
|
|
55293
|
-
await forward(req, res, opts, bodyBuffer, null, core, reqConfig, log2, route, void 0);
|
|
55508
|
+
await forward(req, res, opts, bodyBuffer, null, core, reqConfig, log2, route, instanceId, void 0);
|
|
55294
55509
|
}
|
|
55295
55510
|
}
|
|
55296
55511
|
var ACP_TAG_MARK = "<acp ";
|
|
@@ -55651,7 +55866,7 @@ function injectResponsesTool(tools, toolsToAdd = ACP_TOOLS_RESPONSES) {
|
|
|
55651
55866
|
const additions = toolsToAdd.filter((t) => !present.has(t.name));
|
|
55652
55867
|
return [...tools, ...additions];
|
|
55653
55868
|
}
|
|
55654
|
-
function buildForwardTarget(req, opts, route, affinity) {
|
|
55869
|
+
function buildForwardTarget(req, opts, route, affinity, hopMarker) {
|
|
55655
55870
|
const reqUrl = req.url ?? "";
|
|
55656
55871
|
const isAbsoluteUrl = /^https?:\/\//i.test(reqUrl);
|
|
55657
55872
|
const rewritten = route ? route.rewrittenUrl : isAbsoluteUrl ? reqUrl : opts.upstream + reqUrl;
|
|
@@ -55663,6 +55878,7 @@ function buildForwardTarget(req, opts, route, affinity) {
|
|
|
55663
55878
|
if (UPSTREAM_HOP_HEADERS.has(lower) || reqConnNamed.has(lower) || v2 === void 0) continue;
|
|
55664
55879
|
headers[k2] = Array.isArray(v2) ? v2.join(", ") : v2;
|
|
55665
55880
|
}
|
|
55881
|
+
if (hopMarker !== void 0) headers[BILI_HOP_HEADER] = hopMarker;
|
|
55666
55882
|
headers["host"] = new URL(upstreamUrl).host;
|
|
55667
55883
|
const betaKey = Object.keys(headers).find((h) => h.toLowerCase() === "x-codex-beta-features");
|
|
55668
55884
|
if (betaKey) {
|
|
@@ -55676,14 +55892,29 @@ function buildForwardTarget(req, opts, route, affinity) {
|
|
|
55676
55892
|
const proxyUrl = resolveProxy(opts.routes, opts.proxy, route?.rewrittenUrl ?? upstreamUrl, opts.proxyFallback);
|
|
55677
55893
|
return { upstreamUrl, headers, proxyUrl };
|
|
55678
55894
|
}
|
|
55679
|
-
|
|
55895
|
+
function isPreflightFailFast(outcome) {
|
|
55896
|
+
return "failFast" in outcome;
|
|
55897
|
+
}
|
|
55898
|
+
async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, core, config, model, route, affinity, log2, instanceId) {
|
|
55680
55899
|
const session = prepared.session;
|
|
55681
55900
|
const limit = config.modelContextLimit;
|
|
55682
|
-
const
|
|
55901
|
+
const payloadEstimate = estimateCoreMessages(prepared.processedMessages);
|
|
55902
|
+
const tokenCount = Math.max(session.stats.lastInputTokens, payloadEstimate);
|
|
55683
55903
|
if (limit <= 0 || !model || tokenCount < limit) return prepared;
|
|
55684
|
-
|
|
55904
|
+
const failFast = (status2, detail, retryable) => {
|
|
55905
|
+
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.`;
|
|
55906
|
+
log2("error", `[${session.id}] preflight fail-fast ${status2} (retryable=${retryable}): ${message}`);
|
|
55907
|
+
return { failFast: true, status: status2, message, retryable, respond: !res.writableEnded };
|
|
55908
|
+
};
|
|
55909
|
+
if ((prepared.nudge?.compressibleRanges ?? []).length === 0) {
|
|
55910
|
+
if (payloadEstimate < limit) {
|
|
55911
|
+
log2("warn", `[${session.id}] preflight trigger fired on a stale baseline (~${tokenCount}) but the payload fits (~${payloadEstimate}/${limit}); forwarding as-is`);
|
|
55912
|
+
return prepared;
|
|
55913
|
+
}
|
|
55914
|
+
return failFast(502, "no part of the conversation is compressible (nothing left to fold)", false);
|
|
55915
|
+
}
|
|
55685
55916
|
log2("warn", `[${session.id}] context ${tokenCount} tokens exceeds model window ${limit} (model=${model}); preflight compressing before forward`);
|
|
55686
|
-
const { upstreamUrl, headers, proxyUrl } = buildForwardTarget(req, opts, route, affinity);
|
|
55917
|
+
const { upstreamUrl, headers, proxyUrl } = buildForwardTarget(req, opts, route, affinity, instanceId);
|
|
55687
55918
|
const clientAbort = new AbortController();
|
|
55688
55919
|
res.on("close", () => {
|
|
55689
55920
|
if (!res.writableEnded) clientAbort.abort();
|
|
@@ -55705,17 +55936,26 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
|
|
|
55705
55936
|
},
|
|
55706
55937
|
prepared.originalMessages
|
|
55707
55938
|
);
|
|
55708
|
-
if (result.
|
|
55709
|
-
|
|
55710
|
-
|
|
55711
|
-
|
|
55712
|
-
|
|
55939
|
+
if (result.payloadEstimate < limit) {
|
|
55940
|
+
if (result.compressedRanges > 0) {
|
|
55941
|
+
log2("info", `[${session.id}] preflight compressed ${result.compressedRanges} range(s), ~${result.savedTokens} tokens saved (${tokenCount} \u2192 ${session.stats.lastInputTokens}) in ${Date.now() - started}ms; rebuilding payload`);
|
|
55942
|
+
const rebuilt = runPrepare();
|
|
55943
|
+
session.stats.requests -= 1;
|
|
55944
|
+
return rebuilt;
|
|
55945
|
+
}
|
|
55946
|
+
log2("warn", `[${session.id}] preflight made no progress but the payload fits (~${result.payloadEstimate}/${limit}); forwarding as-is`);
|
|
55947
|
+
return prepared;
|
|
55713
55948
|
}
|
|
55714
|
-
|
|
55715
|
-
|
|
55949
|
+
const f2 = result.failure;
|
|
55950
|
+
if (f2?.kind === "aborted") {
|
|
55951
|
+
log2("warn", `[${session.id}] preflight aborted (${f2.detail}); not forwarding`);
|
|
55952
|
+
return { failFast: true, status: 0, message: f2.detail, retryable: false, respond: false };
|
|
55953
|
+
}
|
|
55954
|
+
const status = f2?.kind === "upstream" && f2.status === 429 ? 503 : 502;
|
|
55955
|
+
return failFast(status, f2?.detail ?? "unknown reason", status === 503);
|
|
55716
55956
|
}
|
|
55717
|
-
async function forward(req, res, opts, body, prepared, core, config, log2, route, affinity) {
|
|
55718
|
-
const { upstreamUrl, headers, proxyUrl } = buildForwardTarget(req, opts, route, affinity);
|
|
55957
|
+
async function forward(req, res, opts, body, prepared, core, config, log2, route, instanceId, affinity) {
|
|
55958
|
+
const { upstreamUrl, headers, proxyUrl } = buildForwardTarget(req, opts, route, affinity, prepared !== null ? instanceId : void 0);
|
|
55719
55959
|
log2("info", `forward ${req.method} \u2192 ${maskUrlForLog(upstreamUrl)}`);
|
|
55720
55960
|
if (process.env.ACP_DEBUG && prepared) {
|
|
55721
55961
|
const sid = prepared.session.id;
|
|
@@ -60055,7 +60295,7 @@ function pluginStatusAll() {
|
|
|
60055
60295
|
}
|
|
60056
60296
|
|
|
60057
60297
|
// src/launcher.ts
|
|
60058
|
-
import { randomUUID as
|
|
60298
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
60059
60299
|
import fs10 from "fs";
|
|
60060
60300
|
import net2 from "net";
|
|
60061
60301
|
import os5 from "os";
|
|
@@ -61035,7 +61275,7 @@ async function runLaunch(params, deps = {}) {
|
|
|
61035
61275
|
const dshAcpPatch = writeDshAcpPatch(dshHomeDir);
|
|
61036
61276
|
if (dshAcpPatch) clientArgs = dshArgsWithPatch(clientArgs, dshAcpPatch);
|
|
61037
61277
|
} else if (base === "codex") {
|
|
61038
|
-
const codexConversationId = injectMcp ?
|
|
61278
|
+
const codexConversationId = injectMcp ? randomUUID3() : void 0;
|
|
61039
61279
|
if (directUrl) {
|
|
61040
61280
|
env = { ...process.env, BILLION_CONTEXT_PROXY: origin };
|
|
61041
61281
|
if (codexConversationId) clientArgs = [...buildCodexMcpArgs(origin, codexConversationId), ...clientArgs];
|