billion-context 0.1.75-pr.484.303 → 0.1.75-pr.486.305
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 +235 -177
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -48008,12 +48008,22 @@ import path3 from "path";
|
|
|
48008
48008
|
// src/fetch-util.ts
|
|
48009
48009
|
var MAX_REQUEST_BYTES = 100 * 1024 * 1024;
|
|
48010
48010
|
var UPSTREAM_TIMEOUT_MS = 10 * 60 * 1e3;
|
|
48011
|
+
var liveUpstreamTimers = /* @__PURE__ */ new Set();
|
|
48011
48012
|
async function fetchWithTimeout(url, opts, timeoutMs = UPSTREAM_TIMEOUT_MS, externalSignal) {
|
|
48012
48013
|
const controller = new AbortController();
|
|
48013
|
-
|
|
48014
|
+
const armTimer = () => {
|
|
48015
|
+
const t = setTimeout(() => {
|
|
48016
|
+
liveUpstreamTimers.delete(t);
|
|
48017
|
+
controller.abort();
|
|
48018
|
+
}, timeoutMs);
|
|
48019
|
+
liveUpstreamTimers.add(t);
|
|
48020
|
+
return t;
|
|
48021
|
+
};
|
|
48022
|
+
let timer2 = armTimer();
|
|
48014
48023
|
const rearm = () => {
|
|
48015
48024
|
clearTimeout(timer2);
|
|
48016
|
-
|
|
48025
|
+
liveUpstreamTimers.delete(timer2);
|
|
48026
|
+
timer2 = armTimer();
|
|
48017
48027
|
};
|
|
48018
48028
|
let onExternalAbort = null;
|
|
48019
48029
|
if (externalSignal) {
|
|
@@ -48025,6 +48035,7 @@ async function fetchWithTimeout(url, opts, timeoutMs = UPSTREAM_TIMEOUT_MS, exte
|
|
|
48025
48035
|
}
|
|
48026
48036
|
const cleanup = () => {
|
|
48027
48037
|
clearTimeout(timer2);
|
|
48038
|
+
liveUpstreamTimers.delete(timer2);
|
|
48028
48039
|
if (onExternalAbort && externalSignal) externalSignal.removeEventListener("abort", onExternalAbort);
|
|
48029
48040
|
};
|
|
48030
48041
|
try {
|
|
@@ -54563,6 +54574,12 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
|
|
|
54563
54574
|
return new Promise((r) => res.once("drain", () => r()));
|
|
54564
54575
|
}
|
|
54565
54576
|
};
|
|
54577
|
+
const settleUsage = () => {
|
|
54578
|
+
if (session && (acc.inputTokens !== void 0 || acc.outputTokens !== void 0 || acc.cachedTokens !== void 0)) {
|
|
54579
|
+
applyUsageSample(session, acc, protocol);
|
|
54580
|
+
markDirty(session);
|
|
54581
|
+
}
|
|
54582
|
+
};
|
|
54566
54583
|
const pushField = (field, index, text) => {
|
|
54567
54584
|
const s3 = filterFor(field, index);
|
|
54568
54585
|
const clean = s3.filter.push(text);
|
|
@@ -54668,10 +54685,14 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
|
|
|
54668
54685
|
}
|
|
54669
54686
|
const rest = flushTails();
|
|
54670
54687
|
if (rest.length > 0 && !res.destroyed && !res.writableEnded) await write(rest);
|
|
54671
|
-
|
|
54672
|
-
|
|
54673
|
-
|
|
54688
|
+
settleUsage();
|
|
54689
|
+
} catch (e) {
|
|
54690
|
+
settleUsage();
|
|
54691
|
+
if (res.destroyed || res.writableEnded) {
|
|
54692
|
+
log2?.("client aborted mid-stream");
|
|
54693
|
+
return;
|
|
54674
54694
|
}
|
|
54695
|
+
throw e;
|
|
54675
54696
|
} finally {
|
|
54676
54697
|
reader.releaseLock();
|
|
54677
54698
|
res.end();
|
|
@@ -54705,6 +54726,12 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
|
|
|
54705
54726
|
return new Promise((r) => res.once("drain", () => r()));
|
|
54706
54727
|
}
|
|
54707
54728
|
};
|
|
54729
|
+
const settleUsage = () => {
|
|
54730
|
+
if (session && (acc.inputTokens !== void 0 || acc.outputTokens !== void 0 || acc.cachedTokens !== void 0)) {
|
|
54731
|
+
applyUsageSample(session, acc, "responses");
|
|
54732
|
+
markDirty(session);
|
|
54733
|
+
}
|
|
54734
|
+
};
|
|
54708
54735
|
let lastDeltaMeta = null;
|
|
54709
54736
|
const flushTail = (after) => {
|
|
54710
54737
|
const tail = tagFilter.flush();
|
|
@@ -54777,10 +54804,14 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
|
|
|
54777
54804
|
const rest = flushTail("");
|
|
54778
54805
|
if (rest.length > 0) await write(rest);
|
|
54779
54806
|
}
|
|
54780
|
-
|
|
54781
|
-
|
|
54782
|
-
|
|
54807
|
+
settleUsage();
|
|
54808
|
+
} catch (e) {
|
|
54809
|
+
settleUsage();
|
|
54810
|
+
if (res.destroyed || res.writableEnded) {
|
|
54811
|
+
log2?.("client aborted mid-stream");
|
|
54812
|
+
return;
|
|
54783
54813
|
}
|
|
54814
|
+
throw e;
|
|
54784
54815
|
} finally {
|
|
54785
54816
|
reader.releaseLock();
|
|
54786
54817
|
res.end();
|
|
@@ -54806,10 +54837,16 @@ function rebuildEvent(rawEvent, ev) {
|
|
|
54806
54837
|
async function pipePluginJson(stream2, res, session, protocol) {
|
|
54807
54838
|
const reader = stream2.getReader();
|
|
54808
54839
|
const chunks = [];
|
|
54809
|
-
|
|
54810
|
-
|
|
54811
|
-
|
|
54812
|
-
|
|
54840
|
+
try {
|
|
54841
|
+
for (; ; ) {
|
|
54842
|
+
const { done, value } = await reader.read();
|
|
54843
|
+
if (done) break;
|
|
54844
|
+
if (value && value.length > 0) chunks.push(Buffer.from(value));
|
|
54845
|
+
}
|
|
54846
|
+
} catch (e) {
|
|
54847
|
+
if (!res.writableEnded) res.end();
|
|
54848
|
+
if (res.destroyed || res.writableEnded) return;
|
|
54849
|
+
throw e;
|
|
54813
54850
|
}
|
|
54814
54851
|
reader.releaseLock();
|
|
54815
54852
|
const text = Buffer.concat(chunks).toString("utf8");
|
|
@@ -56460,7 +56497,10 @@ async function startServer(opts) {
|
|
|
56460
56497
|
await handle(req, res, opts, core, config, log2, instanceId, instanceStartedAt);
|
|
56461
56498
|
} catch (err2) {
|
|
56462
56499
|
const msg = String(err2);
|
|
56463
|
-
|
|
56500
|
+
const e = err2;
|
|
56501
|
+
const clientAbort = (e?.name === "AbortError" || /abort/i.test(String(e?.message ?? ""))) && (res.destroyed || res.writableEnded);
|
|
56502
|
+
if (clientAbort) log2("info", `client aborted mid-stream: ${msg}`);
|
|
56503
|
+
else log2("error", msg);
|
|
56464
56504
|
if (!res.headersSent) {
|
|
56465
56505
|
const status = msg.includes("exceeds") ? 413 : 502;
|
|
56466
56506
|
res.writeHead(status, { "content-type": "application/json" });
|
|
@@ -57849,187 +57889,205 @@ ${hdrText}
|
|
|
57849
57889
|
return;
|
|
57850
57890
|
}
|
|
57851
57891
|
if (prepared?.pluginMode) {
|
|
57852
|
-
|
|
57853
|
-
|
|
57854
|
-
|
|
57855
|
-
|
|
57856
|
-
|
|
57857
|
-
|
|
57858
|
-
|
|
57859
|
-
|
|
57860
|
-
|
|
57861
|
-
|
|
57862
|
-
|
|
57863
|
-
|
|
57864
|
-
|
|
57865
|
-
|
|
57866
|
-
const resolvedBuf = await resolveFakeCompletion(upstream.body, {
|
|
57867
|
-
protocol: prepared.protocol,
|
|
57868
|
-
body,
|
|
57869
|
-
upstreamUrl,
|
|
57870
|
-
reqHeaders: buildForwardHeaders(headers),
|
|
57871
|
-
proxyUrl,
|
|
57872
|
-
signal: clientAbort.signal,
|
|
57873
|
-
session: prepared.session,
|
|
57874
|
-
log: log2
|
|
57875
|
-
});
|
|
57876
|
-
responseBody = bufferToStream(resolvedBuf);
|
|
57877
|
-
}
|
|
57878
|
-
const useRewriter = prepared !== null && prepared.compressInjected && prepared.processedMessages.length > 0;
|
|
57879
|
-
if (!useRewriter || prepared === null) {
|
|
57880
|
-
if (prepared && prepared.resetAfterSuccess) {
|
|
57881
|
-
const [toClient, toObserve] = responseBody.tee();
|
|
57882
|
-
const observed = observeResponsesTerminalState(toObserve, prepared.stream);
|
|
57883
|
-
const tagLog = (msg) => log2("info", `[${prepared.session.id}] ${msg}`);
|
|
57884
|
-
if ((upstream.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
57885
|
-
await pipePluginResponsesWithStrip(toClient, res, void 0, tagLog);
|
|
57886
|
-
} else {
|
|
57887
|
-
await pipeThrough(toClient, res);
|
|
57888
|
-
}
|
|
57889
|
-
clearUpstreamTimer();
|
|
57890
|
-
const terminal = await observed;
|
|
57891
|
-
if (terminal === "completed") {
|
|
57892
|
-
markNativeCompactionBoundary(prepared.session);
|
|
57893
|
-
log2("info", `[${prepared.session.id}] native Responses compact completed; rebase scheduled for next Responses turn`);
|
|
57894
|
-
} else {
|
|
57895
|
-
log2("warn", `[${prepared.session.id}] native compact response terminal=${terminal}; rebase NOT scheduled`);
|
|
57892
|
+
try {
|
|
57893
|
+
let pluginBody = upstream.body;
|
|
57894
|
+
if (prepared.stream && maxFakeCompletionRetries() > 0) {
|
|
57895
|
+
const resolvedBuf = await resolveFakeCompletion(pluginBody, {
|
|
57896
|
+
protocol: prepared.protocol,
|
|
57897
|
+
body,
|
|
57898
|
+
upstreamUrl,
|
|
57899
|
+
reqHeaders: buildForwardHeaders(headers),
|
|
57900
|
+
proxyUrl,
|
|
57901
|
+
signal: clientAbort.signal,
|
|
57902
|
+
session: prepared.session,
|
|
57903
|
+
log: log2
|
|
57904
|
+
});
|
|
57905
|
+
pluginBody = bufferToStream(resolvedBuf);
|
|
57896
57906
|
}
|
|
57897
|
-
|
|
57898
|
-
|
|
57899
|
-
|
|
57900
|
-
|
|
57901
|
-
|
|
57907
|
+
if (prepared.stream) {
|
|
57908
|
+
if (prepared.protocol === "responses") {
|
|
57909
|
+
await pipePluginResponsesWithStrip(pluginBody, res, prepared.session, (msg) => log2("info", `[${prepared.session.id}] ${msg}`));
|
|
57910
|
+
} else {
|
|
57911
|
+
await pipePluginChatWithStrip(pluginBody, res, prepared.protocol, prepared.session, (msg) => log2("info", `[${prepared.session.id}] ${msg}`));
|
|
57912
|
+
}
|
|
57902
57913
|
} else {
|
|
57903
|
-
await
|
|
57914
|
+
await pipePluginJson(pluginBody, res, prepared.session, prepared.protocol);
|
|
57904
57915
|
}
|
|
57905
|
-
|
|
57906
|
-
} else if (prepared && (upstream.headers.get("content-type") ?? "").includes("application/json")) {
|
|
57907
|
-
await pipePluginJson(responseBody, res, void 0, prepared.protocol);
|
|
57908
|
-
clearUpstreamTimer();
|
|
57909
|
-
} else {
|
|
57910
|
-
await pipeThrough(responseBody, res);
|
|
57916
|
+
} finally {
|
|
57911
57917
|
clearUpstreamTimer();
|
|
57912
57918
|
}
|
|
57913
57919
|
return;
|
|
57914
57920
|
}
|
|
57915
|
-
|
|
57916
|
-
|
|
57917
|
-
|
|
57918
|
-
|
|
57919
|
-
|
|
57920
|
-
|
|
57921
|
-
|
|
57922
|
-
|
|
57923
|
-
|
|
57924
|
-
|
|
57925
|
-
|
|
57926
|
-
|
|
57927
|
-
|
|
57928
|
-
|
|
57929
|
-
|
|
57930
|
-
|
|
57931
|
-
|
|
57932
|
-
|
|
57933
|
-
|
|
57934
|
-
|
|
57935
|
-
|
|
57936
|
-
|
|
57937
|
-
|
|
57938
|
-
|
|
57939
|
-
|
|
57940
|
-
|
|
57941
|
-
|
|
57942
|
-
|
|
57943
|
-
|
|
57944
|
-
|
|
57945
|
-
|
|
57946
|
-
|
|
57947
|
-
|
|
57948
|
-
}
|
|
57949
|
-
|
|
57950
|
-
|
|
57951
|
-
|
|
57952
|
-
|
|
57953
|
-
|
|
57954
|
-
|
|
57955
|
-
systemPrompt,
|
|
57956
|
-
clientAbort.signal
|
|
57957
|
-
);
|
|
57958
|
-
let protocolFragmentWarned = false;
|
|
57959
|
-
for await (const chunk of loop) {
|
|
57960
|
-
if (res.destroyed || res.writableEnded) break;
|
|
57961
|
-
{
|
|
57962
|
-
const s3 = chunk.toString("utf8");
|
|
57963
|
-
if (s3.includes("<acp ") || s3.includes("</acp")) {
|
|
57964
|
-
log2("warn", `[${prepared.session.id}] tag echo: ${prepared.protocol} response stream contains <acp tag`);
|
|
57965
|
-
} else if (!protocolFragmentWarned && containsToolCallXmlFragment(s3)) {
|
|
57966
|
-
protocolFragmentWarned = true;
|
|
57967
|
-
log2("warn", `[${prepared.session.id}] tag echo: ${prepared.protocol} response stream contains tool-call XML fragment (possible tag echo; not stripped)`);
|
|
57968
|
-
}
|
|
57969
|
-
}
|
|
57970
|
-
res.write(chunk);
|
|
57971
|
-
if (res.writableNeedDrain) {
|
|
57972
|
-
await Promise.race([
|
|
57973
|
-
new Promise((r) => res.once("drain", () => r())),
|
|
57974
|
-
new Promise((r) => res.once("close", () => r()))
|
|
57975
|
-
]);
|
|
57921
|
+
let responseBody = upstream.body;
|
|
57922
|
+
try {
|
|
57923
|
+
if (prepared !== null && prepared.stream && maxFakeCompletionRetries() > 0) {
|
|
57924
|
+
const resolvedBuf = await resolveFakeCompletion(upstream.body, {
|
|
57925
|
+
protocol: prepared.protocol,
|
|
57926
|
+
body,
|
|
57927
|
+
upstreamUrl,
|
|
57928
|
+
reqHeaders: buildForwardHeaders(headers),
|
|
57929
|
+
proxyUrl,
|
|
57930
|
+
signal: clientAbort.signal,
|
|
57931
|
+
session: prepared.session,
|
|
57932
|
+
log: log2
|
|
57933
|
+
});
|
|
57934
|
+
responseBody = bufferToStream(resolvedBuf);
|
|
57935
|
+
}
|
|
57936
|
+
const useRewriter = prepared !== null && prepared.compressInjected && prepared.processedMessages.length > 0;
|
|
57937
|
+
if (!useRewriter || prepared === null) {
|
|
57938
|
+
if (prepared && prepared.resetAfterSuccess) {
|
|
57939
|
+
const [toClient, toObserve] = responseBody.tee();
|
|
57940
|
+
const observed = observeResponsesTerminalState(toObserve, prepared.stream);
|
|
57941
|
+
const tagLog = (msg) => log2("info", `[${prepared.session.id}] ${msg}`);
|
|
57942
|
+
if ((upstream.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
57943
|
+
await pipePluginResponsesWithStrip(toClient, res, void 0, tagLog);
|
|
57944
|
+
} else {
|
|
57945
|
+
await pipeThrough(toClient, res);
|
|
57946
|
+
}
|
|
57947
|
+
const terminal = await observed;
|
|
57948
|
+
if (terminal === "completed") {
|
|
57949
|
+
markNativeCompactionBoundary(prepared.session);
|
|
57950
|
+
log2("info", `[${prepared.session.id}] native Responses compact completed; rebase scheduled for next Responses turn`);
|
|
57951
|
+
} else {
|
|
57952
|
+
log2("warn", `[${prepared.session.id}] native compact response terminal=${terminal}; rebase NOT scheduled`);
|
|
57953
|
+
}
|
|
57954
|
+
} else if (prepared && prepared.stream && (upstream.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
57955
|
+
const p2 = prepared;
|
|
57956
|
+
const tagLog = (msg) => log2("info", `[${p2.session.id}] ${msg}`);
|
|
57957
|
+
if (p2.protocol === "responses") {
|
|
57958
|
+
await pipePluginResponsesWithStrip(responseBody, res, void 0, tagLog);
|
|
57959
|
+
} else {
|
|
57960
|
+
await pipePluginChatWithStrip(responseBody, res, p2.protocol, void 0, tagLog);
|
|
57976
57961
|
}
|
|
57977
|
-
|
|
57962
|
+
} else if (prepared && (upstream.headers.get("content-type") ?? "").includes("application/json")) {
|
|
57963
|
+
await pipePluginJson(responseBody, res, void 0, prepared.protocol);
|
|
57964
|
+
} else {
|
|
57965
|
+
await pipeThrough(responseBody, res);
|
|
57978
57966
|
}
|
|
57979
|
-
|
|
57980
|
-
} catch (e) {
|
|
57981
|
-
emitStreamError(res, prepared.protocol, e?.message ?? String(e), (m2) => log2("error", `[${prepared.session.id}] ${m2}`));
|
|
57982
|
-
} finally {
|
|
57983
|
-
clearUpstreamTimer();
|
|
57984
|
-
if (dumpRaw) await dumpRaw;
|
|
57967
|
+
return;
|
|
57985
57968
|
}
|
|
57986
|
-
|
|
57987
|
-
|
|
57988
|
-
|
|
57989
|
-
|
|
57969
|
+
const ctx = {
|
|
57970
|
+
core,
|
|
57971
|
+
config,
|
|
57972
|
+
messages: prepared.originalMessages,
|
|
57973
|
+
session: prepared.session,
|
|
57974
|
+
log: (msg) => log2("info", `[${prepared.session.id}] ${msg}`),
|
|
57975
|
+
debug: opts.debug
|
|
57976
|
+
};
|
|
57977
|
+
if (prepared.stream) {
|
|
57978
|
+
let streamToRead = responseBody;
|
|
57979
|
+
let dumpRaw;
|
|
57980
|
+
if (opts.dumpSse) {
|
|
57981
|
+
const [a, b2] = responseBody.tee();
|
|
57982
|
+
streamToRead = a;
|
|
57983
|
+
dumpRaw = dumpStreamToFile(b2, opts.dumpSse, `${Date.now()}-${safeSessionId(prepared.session.id)}-raw.sse`);
|
|
57984
|
+
}
|
|
57990
57985
|
try {
|
|
57991
|
-
|
|
57992
|
-
|
|
57993
|
-
|
|
57994
|
-
|
|
57995
|
-
|
|
57996
|
-
|
|
57997
|
-
|
|
57998
|
-
|
|
57999
|
-
|
|
58000
|
-
|
|
58001
|
-
|
|
58002
|
-
|
|
58003
|
-
|
|
58004
|
-
|
|
58005
|
-
|
|
58006
|
-
|
|
58007
|
-
|
|
58008
|
-
|
|
58009
|
-
|
|
58010
|
-
|
|
58011
|
-
|
|
58012
|
-
|
|
57986
|
+
const parsedReq = JSON.parse(typeof body === "string" ? body : body.toString("utf8"));
|
|
57987
|
+
const reqHeaders = buildForwardHeaders(headers);
|
|
57988
|
+
const textProtocol = prepared.protocol === "responses" && !!prepared.responsesTextProtocol;
|
|
57989
|
+
const systemPrompt = textProtocol ? buildCompressHybridSystemPrompt(prepared.prompts ?? defaultPrompts) : buildCompressSystemPrompt(prepared.prompts ?? defaultPrompts);
|
|
57990
|
+
const adapter = pickAdapter(prepared.protocol, parsedReq, textProtocol, prepared.responsesProjection, prepared.anthropicSystem, prepared.openaiSystemText);
|
|
57991
|
+
const refreshFolded = (current) => {
|
|
57992
|
+
const turn = core.processTurn({
|
|
57993
|
+
messages: prepared.originalMessages,
|
|
57994
|
+
state: prepared.session.state,
|
|
57995
|
+
config,
|
|
57996
|
+
tokenCount: prepared.session.stats.lastInputTokens,
|
|
57997
|
+
renderTags: prepared.renderTags ?? "text-only"
|
|
57998
|
+
});
|
|
57999
|
+
prepared.session.state = turn.state;
|
|
58000
|
+
const records = current.filter((m2) => typeof m2.id === "string" && m2.id.startsWith("acp_loop_"));
|
|
58001
|
+
return stripKernelSummaries([...turn.messages, ...records], turn.state);
|
|
58002
|
+
};
|
|
58003
|
+
const loop = runCompressLoop(
|
|
58004
|
+
streamToRead,
|
|
58005
|
+
{ core, config, messages: prepared.processedMessages.length > 0 ? prepared.processedMessages : prepared.originalMessages, compressMessages: prepared.originalMessages, session: prepared.session, log: ctx.log, proxyUrl, protocol: prepared.protocol, textProtocol, debug: opts.debug, nudge: prepared.nudge, refreshFolded },
|
|
58006
|
+
parsedReq,
|
|
58007
|
+
{ url: upstreamUrl, headers: reqHeaders },
|
|
58008
|
+
adapter,
|
|
58009
|
+
systemPrompt,
|
|
58010
|
+
clientAbort.signal
|
|
58011
|
+
);
|
|
58012
|
+
let protocolFragmentWarned = false;
|
|
58013
|
+
for await (const chunk of loop) {
|
|
58014
|
+
if (res.destroyed || res.writableEnded) break;
|
|
58015
|
+
{
|
|
58016
|
+
const s3 = chunk.toString("utf8");
|
|
58017
|
+
if (s3.includes("<acp ") || s3.includes("</acp")) {
|
|
58018
|
+
log2("warn", `[${prepared.session.id}] tag echo: ${prepared.protocol} response stream contains <acp tag`);
|
|
58019
|
+
} else if (!protocolFragmentWarned && containsToolCallXmlFragment(s3)) {
|
|
58020
|
+
protocolFragmentWarned = true;
|
|
58021
|
+
log2("warn", `[${prepared.session.id}] tag echo: ${prepared.protocol} response stream contains tool-call XML fragment (possible tag echo; not stripped)`);
|
|
58022
|
+
}
|
|
58023
|
+
}
|
|
58024
|
+
res.write(chunk);
|
|
58025
|
+
if (res.writableNeedDrain) {
|
|
58026
|
+
await Promise.race([
|
|
58027
|
+
new Promise((r) => res.once("drain", () => r())),
|
|
58028
|
+
new Promise((r) => res.once("close", () => r()))
|
|
58029
|
+
]);
|
|
58013
58030
|
}
|
|
58014
|
-
|
|
58015
|
-
if (typeof out === "number") prepared.session.stats.outputTokens += out;
|
|
58031
|
+
if (res.destroyed || res.writableEnded) break;
|
|
58016
58032
|
}
|
|
58017
|
-
|
|
58018
|
-
|
|
58019
|
-
|
|
58020
|
-
|
|
58021
|
-
|
|
58022
|
-
|
|
58033
|
+
res.end();
|
|
58034
|
+
} catch (e) {
|
|
58035
|
+
emitStreamError(res, prepared.protocol, e?.message ?? String(e), (m2) => log2("error", `[${prepared.session.id}] ${m2}`));
|
|
58036
|
+
} finally {
|
|
58037
|
+
clearUpstreamTimer();
|
|
58038
|
+
if (dumpRaw) await dumpRaw;
|
|
58039
|
+
markDirty(prepared.session);
|
|
58040
|
+
}
|
|
58041
|
+
} else {
|
|
58042
|
+
try {
|
|
58043
|
+
const buf = await upstream.arrayBuffer();
|
|
58044
|
+
const text = Buffer.from(buf).toString("utf8");
|
|
58045
|
+
try {
|
|
58046
|
+
let json = JSON.parse(text);
|
|
58047
|
+
if (prepared.protocol === "responses" && prepared.responsesTextProtocol) {
|
|
58048
|
+
const requestBody = JSON.parse(typeof body === "string" ? body : body.toString("utf8"));
|
|
58049
|
+
const requestHeaders = buildForwardHeaders(headers);
|
|
58050
|
+
json = await compressLoopResponsesJson(
|
|
58051
|
+
json,
|
|
58052
|
+
{ core, config, messages: prepared.originalMessages, session: prepared.session, log: ctx.log, proxyUrl, textProtocol: true },
|
|
58053
|
+
requestBody,
|
|
58054
|
+
{ url: upstreamUrl, headers: requestHeaders }
|
|
58055
|
+
);
|
|
58056
|
+
}
|
|
58057
|
+
const u2 = json.usage ?? {};
|
|
58058
|
+
const { total, cached } = usageTotals(prepared.protocol, u2);
|
|
58059
|
+
if (typeof total === "number") {
|
|
58060
|
+
prepared.session.stats.inputTokens += total;
|
|
58061
|
+
prepared.session.stats.lastInputTokens = Math.max(
|
|
58062
|
+
0,
|
|
58063
|
+
total - (prepared.session.stats.compressCreditTokens ?? 0)
|
|
58064
|
+
);
|
|
58065
|
+
if (typeof cached === "number") {
|
|
58066
|
+
prepared.session.stats.cachedTokens += cached;
|
|
58067
|
+
prepared.session.stats.cacheSamples += 1;
|
|
58068
|
+
}
|
|
58069
|
+
const out = u2.completion_tokens ?? u2.output_tokens;
|
|
58070
|
+
if (typeof out === "number") prepared.session.stats.outputTokens += out;
|
|
58071
|
+
}
|
|
58072
|
+
if (prepared.protocol === "openai") {
|
|
58073
|
+
rewriteOpenaiJsonResponse(json, ctx);
|
|
58074
|
+
} else if (prepared.protocol === "responses") {
|
|
58075
|
+
rewriteResponsesJsonResponse(json, ctx);
|
|
58076
|
+
} else {
|
|
58077
|
+
rewriteJsonResponse(json, ctx);
|
|
58078
|
+
}
|
|
58079
|
+
res.end(JSON.stringify(json));
|
|
58080
|
+
} catch {
|
|
58081
|
+
res.end(text);
|
|
58023
58082
|
}
|
|
58024
|
-
|
|
58025
|
-
|
|
58026
|
-
|
|
58083
|
+
} finally {
|
|
58084
|
+
clearUpstreamTimer();
|
|
58085
|
+
markDirty(prepared.session);
|
|
58027
58086
|
}
|
|
58028
|
-
} finally {
|
|
58029
|
-
clearUpstreamTimer();
|
|
58030
58087
|
}
|
|
58088
|
+
} finally {
|
|
58089
|
+
clearUpstreamTimer();
|
|
58031
58090
|
}
|
|
58032
|
-
markDirty(prepared.session);
|
|
58033
58091
|
}
|
|
58034
58092
|
async function readStreamToBuffer(stream2, maxBytes = 1 << 20) {
|
|
58035
58093
|
const reader = stream2.getReader();
|