billion-context 0.1.75-pr.485.304 → 0.1.75

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