billion-context 0.1.100-pr.685.510 → 0.1.100

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
@@ -47777,14 +47777,7 @@ async function fetchWithTimeout(url, opts, timeoutMs, externalSignal) {
47777
47777
  const finalOpts = {
47778
47778
  ...opts,
47779
47779
  signal: controller.signal,
47780
- dispatcher: opts.dispatcher ?? directDispatcher(effective),
47781
- // Forward-proxy correctness: never silently follow a redirect.
47782
- // undici's default (follow) downgrades POST→GET and drops the body
47783
- // on 301/302/303, so a redirecting upstream (CDN/WAF) turns a valid
47784
- // POST into a 405 at the redirect target. Pass the 3xx through to
47785
- // the client, which follows it with its own policy. Internal bili
47786
- // fetches that want to follow (registry, upstream test) opt in.
47787
- redirect: opts.redirect ?? "manual"
47780
+ dispatcher: opts.dispatcher ?? directDispatcher(effective)
47788
47781
  };
47789
47782
  const raw = await fetch(url, finalOpts);
47790
47783
  if (raw.body) {
@@ -48587,7 +48580,6 @@ function parseRouteEntry(v2) {
48587
48580
  if (obj.compress) route.compress = obj.compress;
48588
48581
  const compatRoles = parseCompatRoles(obj.compat?.roles);
48589
48582
  if (compatRoles) route.compat = { roles: compatRoles };
48590
- if (typeof obj.passthrough === "boolean") route.passthrough = obj.passthrough;
48591
48583
  return route;
48592
48584
  }
48593
48585
  if (v2 === null) return {};
@@ -49017,8 +49009,7 @@ async function fetchFresh() {
49017
49009
  try {
49018
49010
  const { response, clearTimer } = await fetchWithTimeout(REGISTRY_URL, {
49019
49011
  ...opts,
49020
- headers: { Accept: "application/json" },
49021
- redirect: "follow"
49012
+ headers: { Accept: "application/json" }
49022
49013
  }, 15e3);
49023
49014
  const text = await response.text();
49024
49015
  clearTimer();
@@ -51511,44 +51502,20 @@ ${body}`;
51511
51502
  }
51512
51503
 
51513
51504
  // src/loop/tag-echo-filter.ts
51514
- function buildAcplikeName() {
51515
- const cores = ["acp", "apc", "cap", "cpa", "pac", "pca"];
51516
- const names = new Set(cores);
51517
- for (const c of cores) {
51518
- for (const ch of ["a", "c", "p", "i"]) {
51519
- for (let pos = 0; pos <= c.length; pos++) names.add(c.slice(0, pos) + ch + c.slice(pos));
51520
- }
51521
- }
51522
- return [...names].sort((a, b2) => b2.length - a.length).join("|");
51523
- }
51524
- var ACP_NAME_ALT = `(?:${buildAcplikeName()})`;
51525
- var NAME = ACP_NAME_ALT;
51526
- var PAIRED = new RegExp("<" + NAME + "\\s[^<>]{0,256}>([^<>]{0,64})<\\/" + NAME + ">");
51527
- var LONE_OPEN = new RegExp("<" + NAME + "(?:\\s[^<>]{0,256})?>");
51528
- var LONE_CLOSE = new RegExp("<\\/" + NAME + "(?=[\\s>])[^<>]{0,32}>");
51529
- var PARTIAL_TAIL = new RegExp("(<" + NAME + "\\s[^<>]*|<\\/" + NAME + "(?:\\s[^<>]{0,32})?|<\\/?[acip]*)$");
51530
- var TRUNC_OPEN = new RegExp("<" + NAME + "\\s[^<>]*$");
51531
- var TRUNC_CLOSE = new RegExp("<\\/" + NAME + "(?:\\s[^<>]{0,32})?$");
51532
- var DEFINITE_TAIL = new RegExp("^<" + NAME + "\\s|^<\\/" + NAME);
51533
- var OPEN_WITH_ATTRS = new RegExp("^<" + NAME + "\\s");
51534
- var CLOSE_HEAD = "</";
51535
- var CLOSE_NAME_ANCHORED = new RegExp("^" + NAME);
51505
+ var PAIRED = /\x3cacp\s[^<>]{0,256}>([^<>]{0,64})<\/acp>/;
51506
+ var LONE_OPEN = /\x3cacp(?:\s[^<>]{0,256})?>/;
51507
+ var LONE_CLOSE = /<\/acp(?=[\s>])[^<>]{0,32}>/;
51508
+ var PARTIAL_TAIL = /(\x3cacp\s[^<>]*|\x3c\/acp(?:\s[^<>]{0,32})?|<\/?a?c?p?)$/;
51509
+ var TRUNC_OPEN = /\x3cacp\s[^<>]*$/;
51510
+ var TRUNC_CLOSE = /\x3c\/acp(?:\s[^<>]{0,32})?$/;
51511
+ var CLOSE_TAG = "</acp";
51536
51512
  var HOLD_LIMIT = 128;
51537
51513
  var TAG_OPEN_CAP = 4096;
51538
51514
  var SWALLOW_CAP = 80;
51539
- function looseCloseEnd(s3) {
51540
- let idx = s3.indexOf(CLOSE_HEAD);
51541
- while (idx >= 0) {
51542
- const m2 = CLOSE_NAME_ANCHORED.exec(s3.slice(idx + 2));
51543
- if (m2 && s3[idx + 2 + m2[0].length] === ">") return idx + 2 + m2[0].length + 1;
51544
- idx = s3.indexOf(CLOSE_HEAD, idx + 1);
51545
- }
51546
- return -1;
51547
- }
51548
51515
  function stripAcpTags(text) {
51549
51516
  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), "").replace(new RegExp(TRUNC_CLOSE.source), "");
51550
51517
  }
51551
- var RENDER_TAG_DETECT = new RegExp("<\\/?" + NAME + "(?=[\\s>])|\\\\u003c\\/?" + NAME + "(?=[\\s>\\\\])");
51518
+ var RENDER_TAG_DETECT = /\x3c\/?acp(?=[\s>])|\\u003c\/?acp(?=[\s>\\])/;
51552
51519
  function containsRenderTagText(s3) {
51553
51520
  return RENDER_TAG_DETECT.test(s3);
51554
51521
  }
@@ -51565,8 +51532,6 @@ function createTagEchoFilter(onDrop) {
51565
51532
  let swallowed = "";
51566
51533
  let droppedAny = false;
51567
51534
  let notified = false;
51568
- let inputChars = 0;
51569
- let outputChars = 0;
51570
51535
  const drop = (snippet) => {
51571
51536
  droppedAny = true;
51572
51537
  if (onDrop && !notified) {
@@ -51580,9 +51545,10 @@ function createTagEchoFilter(onDrop) {
51580
51545
  for (; ; ) {
51581
51546
  if (swallowUntilClose) {
51582
51547
  const combined = swallowed + buf;
51583
- const end = looseCloseEnd(combined);
51584
- if (end >= 0) {
51585
- drop(combined.slice(0, end));
51548
+ const closeIdx = combined.indexOf(CLOSE_TAG);
51549
+ if (closeIdx >= 0 && combined[closeIdx + CLOSE_TAG.length] === ">") {
51550
+ const end = closeIdx + CLOSE_TAG.length + 1;
51551
+ drop(swallowed + combined.slice(0, end));
51586
51552
  swallowed = "";
51587
51553
  swallowUntilClose = false;
51588
51554
  buf = combined.slice(end);
@@ -51607,7 +51573,7 @@ function createTagEchoFilter(onDrop) {
51607
51573
  if (!m2) {
51608
51574
  const t = PARTIAL_TAIL.exec(buf);
51609
51575
  if (t) {
51610
- const definite = DEFINITE_TAIL.test(t[0]);
51576
+ const definite = /^\x3cacp\s/.test(t[0]) || /^\x3c\/acp/.test(t[0]);
51611
51577
  const cap = definite ? TAG_OPEN_CAP : HOLD_LIMIT;
51612
51578
  if (t[0].length <= cap) {
51613
51579
  held = t[0];
@@ -51626,7 +51592,7 @@ function createTagEchoFilter(onDrop) {
51626
51592
  drop(m2[0]);
51627
51593
  out += buf.slice(0, m2.index);
51628
51594
  buf = buf.slice(m2.index + m2[0].length);
51629
- if (m2 === o && OPEN_WITH_ATTRS.test(m2[0])) {
51595
+ if (m2 === o && /^\x3cacp\s/.test(m2[0])) {
51630
51596
  swallowUntilClose = true;
51631
51597
  swallowed = "";
51632
51598
  }
@@ -51635,12 +51601,9 @@ function createTagEchoFilter(onDrop) {
51635
51601
  };
51636
51602
  return {
51637
51603
  push(delta) {
51638
- inputChars += delta.length;
51639
51604
  const chunk = held + delta;
51640
51605
  held = "";
51641
- const r = process2(chunk);
51642
- outputChars += r.length;
51643
- return r;
51606
+ return process2(chunk);
51644
51607
  },
51645
51608
  flush() {
51646
51609
  const rest = swallowed + held;
@@ -51648,36 +51611,27 @@ function createTagEchoFilter(onDrop) {
51648
51611
  swallowed = "";
51649
51612
  held = "";
51650
51613
  swallowUntilClose = false;
51651
- let result;
51652
51614
  if (wasSwallowing) {
51653
51615
  if (rest.length > 0) drop(rest);
51654
- result = "";
51655
- } else {
51656
- const t = new RegExp(TRUNC_OPEN.source).exec(rest);
51657
- if (t) {
51658
- drop(t[0]);
51659
- result = rest.slice(0, t.index);
51660
- } else {
51661
- const tc = new RegExp(TRUNC_CLOSE.source).exec(rest);
51662
- if (tc) {
51663
- drop(tc[0]);
51664
- result = rest.slice(0, tc.index);
51665
- } else {
51666
- result = rest;
51667
- }
51668
- }
51616
+ return "";
51669
51617
  }
51670
- outputChars += result.length;
51671
- return result;
51618
+ const t = new RegExp(TRUNC_OPEN.source).exec(rest);
51619
+ if (t) {
51620
+ drop(t[0]);
51621
+ return rest.slice(0, t.index);
51622
+ }
51623
+ const tc = new RegExp(TRUNC_CLOSE.source).exec(rest);
51624
+ if (tc) {
51625
+ drop(tc[0]);
51626
+ return rest.slice(0, tc.index);
51627
+ }
51628
+ return rest;
51672
51629
  },
51673
51630
  dropped() {
51674
51631
  return droppedAny;
51675
51632
  },
51676
51633
  pending() {
51677
51634
  return held.length > 0 || swallowUntilClose;
51678
- },
51679
- stats() {
51680
- return { inputChars, outputChars, dropped: droppedAny };
51681
51635
  }
51682
51636
  };
51683
51637
  }
@@ -51982,41 +51936,16 @@ function splitChunks(messages, startIdx, endIdx, budget, minUnits, countText = d
51982
51936
  }
51983
51937
  return chunks;
51984
51938
  }
51985
- function summaryPayload(protocol, model, system, content, stream2, includeMaxOutputTokens) {
51939
+ function summaryPayload(protocol, model, system, content, stream2) {
51986
51940
  if (protocol === "anthropic") {
51987
51941
  return { model, max_tokens: MAX_SUMMARY_OUTPUT_TOKENS, system, messages: [{ role: "user", content }], stream: stream2 };
51988
51942
  }
51989
51943
  if (protocol === "openai") {
51990
51944
  return { model, max_tokens: MAX_SUMMARY_OUTPUT_TOKENS, messages: [{ role: "system", content: system }, { role: "user", content }], stream: stream2 };
51991
51945
  }
51992
- const payload = { model, instructions: system, input: [{ role: "user", content }], stream: stream2, store: false };
51993
- if (includeMaxOutputTokens) payload.max_output_tokens = MAX_SUMMARY_OUTPUT_TOKENS;
51994
- return payload;
51946
+ return { model, max_output_tokens: MAX_SUMMARY_OUTPUT_TOKENS, instructions: system, input: [{ role: "user", content }], stream: stream2, store: false };
51995
51947
  }
51996
51948
  var STREAM_REQUIRED_RE = /\bstream\b[^\n]{0,60}\btrue\b/i;
51997
- var MAX_OUTPUT_TOKENS_REJECTED_RE = /\bmax_output_tokens\b/i;
51998
- function noMaxOutputTokensKey(deps) {
51999
- return `${deps.url}\0${deps.model}`;
52000
- }
52001
- function hasLearnedNoMaxOutputTokens(deps) {
52002
- const learned = deps.session.metadata.preflightNoMaxOutputTokens;
52003
- return typeof learned === "object" && learned !== null && learned[noMaxOutputTokensKey(deps)] === true;
52004
- }
52005
- function rememberNoMaxOutputTokens(deps) {
52006
- const learned = deps.session.metadata.preflightNoMaxOutputTokens;
52007
- const map = typeof learned === "object" && learned !== null ? learned : {};
52008
- map[noMaxOutputTokensKey(deps)] = true;
52009
- deps.session.metadata.preflightNoMaxOutputTokens = map;
52010
- }
52011
- var SUMMARY_STRIP_HEADERS = /* @__PURE__ */ new Set(["x-openai-internal-codex-responses-lite"]);
52012
- function summaryHeaders(deps) {
52013
- const headers = {};
52014
- for (const [k2, v2] of Object.entries(deps.headers)) {
52015
- if (SUMMARY_STRIP_HEADERS.has(k2.toLowerCase())) continue;
52016
- headers[k2] = v2;
52017
- }
52018
- return headers;
52019
- }
52020
51949
  function extractSummaryFromSse(protocol, text) {
52021
51950
  let out = "";
52022
51951
  for (const line of text.split("\n")) {
@@ -52080,39 +52009,25 @@ async function summarizeRange(deps, content, startRef, endRef) {
52080
52009
  const system = buildCompressSystemPrompt(deps.prompts) + `
52081
52010
 
52082
52011
  TASK: The conversation segment below (messages ${startRef}\u2013${endRef}) must be compressed because the session context exceeds the current model's window. Write a tier-1 compression summary of the segment following every rule above. Output ONLY the summary text \u2014 no preamble, no closing remarks, no tool calls.`;
52083
- let stream2 = deps.session.metadata.preflightStreamSummary === true;
52084
- let includeMaxOutputTokens = !(deps.protocol === "responses" && hasLearnedNoMaxOutputTokens(deps));
52085
- for (; ; ) {
52086
- try {
52087
- return await requestSummary(deps, system, content, stream2, includeMaxOutputTokens);
52088
- } catch (err2) {
52089
- if (err2 instanceof UpstreamHttpError && err2.status === 400) {
52090
- let adapted = false;
52091
- if (!stream2 && STREAM_REQUIRED_RE.test(err2.body)) {
52092
- deps.session.metadata.preflightStreamSummary = true;
52093
- stream2 = true;
52094
- adapted = true;
52095
- deps.log("info", "[preflight] upstream requires stream for summaries; retrying with SSE (learned for this session)");
52096
- }
52097
- if (deps.protocol === "responses" && includeMaxOutputTokens && MAX_OUTPUT_TOKENS_REJECTED_RE.test(err2.body)) {
52098
- rememberNoMaxOutputTokens(deps);
52099
- includeMaxOutputTokens = false;
52100
- adapted = true;
52101
- deps.log("info", `[preflight] upstream rejects max_output_tokens for summaries (model=${deps.model}); retrying without it (learned for this session+upstream+model)`);
52102
- }
52103
- if (adapted) continue;
52104
- }
52105
- throw err2;
52012
+ const learned = deps.session.metadata.preflightStreamSummary === true;
52013
+ try {
52014
+ return await requestSummary(deps, system, content, learned);
52015
+ } catch (err2) {
52016
+ if (err2 instanceof UpstreamHttpError && err2.status === 400 && !learned && STREAM_REQUIRED_RE.test(err2.body)) {
52017
+ deps.session.metadata.preflightStreamSummary = true;
52018
+ deps.log("info", "[preflight] upstream requires stream for summaries; retrying with SSE (learned for this session)");
52019
+ return await requestSummary(deps, system, content, true);
52106
52020
  }
52021
+ throw err2;
52107
52022
  }
52108
52023
  }
52109
- async function requestSummary(deps, system, content, stream2, includeMaxOutputTokens) {
52024
+ async function requestSummary(deps, system, content, stream2) {
52110
52025
  const { response, clearTimer } = await fetchWithRetry(
52111
52026
  deps.url,
52112
52027
  {
52113
52028
  method: "POST",
52114
- headers: { "content-type": "application/json", ...summaryHeaders(deps) },
52115
- body: JSON.stringify(summaryPayload(deps.protocol, deps.model, system, content, stream2, includeMaxOutputTokens)),
52029
+ headers: { "content-type": "application/json", ...deps.headers },
52030
+ body: JSON.stringify(summaryPayload(deps.protocol, deps.model, system, content, stream2)),
52116
52031
  dispatcher: proxyDispatcher(deps.proxyUrl)
52117
52032
  },
52118
52033
  void 0,
@@ -53749,18 +53664,6 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
53749
53664
  }
53750
53665
  }
53751
53666
 
53752
- // src/degenerate-turn.ts
53753
- function degenerateTurnWarning(o) {
53754
- if ((o.reason ?? o.terminalReason) !== o.terminalReason) return null;
53755
- if (o.toolCalls > 0) return null;
53756
- if (o.text.outputChars > 0) return null;
53757
- const bits = [];
53758
- if (o.sawThinking) bits.push("thinking present");
53759
- if (o.text.dropped && o.text.inputChars > 0) bits.push(`${o.text.inputChars} chars of emitted text stripped as render-tag echo`);
53760
- else bits.push("no visible text emitted");
53761
- return `[degenerate-turn] ${o.wire}: turn ended ${o.terminalReason} with zero visible text and zero tool calls (${bits.join("; ")}) \u2014 the agent receives an empty turn and may stall until nudged (#673)`;
53762
- }
53763
-
53764
53667
  // src/loop/adapter-responses.ts
53765
53668
  var RESPONSES_ITEM_ID_MAX = 64;
53766
53669
  function normalizeResponsesMessageItems(input) {
@@ -53824,7 +53727,7 @@ function dropWhitespaceResponsesMessages(input) {
53824
53727
  }
53825
53728
  return dropped;
53826
53729
  }
53827
- var RENDER_TAG_RE = new RegExp("<" + ACP_NAME_ALT + "\\s[^>]*>[^<]*<\\/" + ACP_NAME_ALT + ">|<" + ACP_NAME_ALT + "\\s[^>]*\\/>", "g");
53730
+ var RENDER_TAG_RE = /\x3cacp\s[^>]*\x3e[^<]*\x3c\/acp\x3e|\x3cacp\s[^>]*\/\x3e/g;
53828
53731
  function stripRenderTags(text) {
53829
53732
  return text.replace(RENDER_TAG_RE, "");
53830
53733
  }
@@ -54039,17 +53942,6 @@ data: ${JSON.stringify({ type: "response.created", response: { id: createdRespId
54039
53942
  yield { kind: "text", delta: tail, ...raw ? { raw } : {} };
54040
53943
  }
54041
53944
  };
54042
- let sawReasoning = false;
54043
- let toolCallsEmitted = 0;
54044
- let degenerateWarned = false;
54045
- const maybeWarnDegenerate = (reason) => {
54046
- if (degenerateWarned) return;
54047
- const msg = degenerateTurnWarning({ reason, terminalReason: "completed", toolCalls: toolCallsEmitted, text: tagFilter.stats(), sawThinking: sawReasoning, wire: "responses" });
54048
- if (msg) {
54049
- degenerateWarned = true;
54050
- log("warn", msg);
54051
- }
54052
- };
54053
53945
  for await (const eventStr of iterSseEvents(upstream)) {
54054
53946
  const explicitType = extractEventType(eventStr);
54055
53947
  const dataLine = extractDataLine(eventStr);
@@ -54062,7 +53954,6 @@ data: ${JSON.stringify({ type: "response.created", response: { id: createdRespId
54062
53954
  }
54063
53955
  const type = explicitType ?? (typeof obj.type === "string" ? obj.type : null);
54064
53956
  if (!type) continue;
54065
- if (type.startsWith("response.reasoning")) sawReasoning = true;
54066
53957
  const rawBuf = Buffer.from(eventStr + "\n\n", "utf8");
54067
53958
  if (round === 1 && typeof obj.output_index === "number") {
54068
53959
  outputIndex = Math.max(outputIndex, obj.output_index + 1);
@@ -54146,7 +54037,6 @@ data: ${JSON.stringify({ type: "response.created", response: { id: createdRespId
54146
54037
  if (fc) {
54147
54038
  if (typeof item.arguments === "string" && item.arguments) fc.arguments = item.arguments;
54148
54039
  pending.delete(itemId);
54149
- toolCallsEmitted++;
54150
54040
  yield {
54151
54041
  kind: "tool_call",
54152
54042
  name: fc.name,
@@ -54155,7 +54045,6 @@ data: ${JSON.stringify({ type: "response.created", response: { id: createdRespId
54155
54045
  };
54156
54046
  } else {
54157
54047
  yield { kind: "meta", chunk: rawBuf, firstRoundOnly: false };
54158
- toolCallsEmitted++;
54159
54048
  yield {
54160
54049
  kind: "tool_call",
54161
54050
  name: typeof item.name === "string" ? item.name : "",
@@ -54192,7 +54081,6 @@ data: ${JSON.stringify({ type: "response.created", response: { id: createdRespId
54192
54081
  outputTokens: typeof respUsage?.output_tokens === "number" ? respUsage.output_tokens : void 0,
54193
54082
  cachedTokens: typeof pd?.cached_tokens === "number" ? pd.cached_tokens : void 0
54194
54083
  };
54195
- maybeWarnDegenerate("completed");
54196
54084
  yield { kind: "done", finishReason: "completed" };
54197
54085
  } else if (type === "response.incomplete") {
54198
54086
  yield* flushFilter();
@@ -54510,23 +54398,11 @@ function createOpenaiAdapter(requestBody, clientSystem, hostCredit = 0, absorbNa
54510
54398
  yield { kind: "text", delta: tail, raw: buildContent(tail) };
54511
54399
  }
54512
54400
  };
54513
- let sawReasoning = false;
54514
- let toolCallsEmitted = 0;
54515
- let degenerateWarned = false;
54516
- const maybeWarnDegenerate = (reason) => {
54517
- if (degenerateWarned) return;
54518
- const msg = degenerateTurnWarning({ reason, terminalReason: "stop", toolCalls: toolCallsEmitted, text: tagFilter.stats(), sawThinking: sawReasoning, wire: "openai" });
54519
- if (msg) {
54520
- degenerateWarned = true;
54521
- log("warn", msg);
54522
- }
54523
- };
54524
54401
  const rawToolChunks = [];
54525
54402
  let sawRealToolCall = false;
54526
54403
  const flushPendingAsStructured = function* () {
54527
54404
  for (const [, tc] of pending) {
54528
54405
  if (tc.name.length > 0 || tc.id.length > 0) {
54529
- toolCallsEmitted++;
54530
54406
  yield {
54531
54407
  kind: "tool_call",
54532
54408
  name: tc.name,
@@ -54549,7 +54425,6 @@ function createOpenaiAdapter(requestBody, clientSystem, hostCredit = 0, absorbNa
54549
54425
  }
54550
54426
  for (const [idx, tc] of pending) {
54551
54427
  if (realIndexes.has(idx) && (tc.name.length > 0 || tc.id.length > 0)) {
54552
- toolCallsEmitted++;
54553
54428
  yield {
54554
54429
  kind: "tool_call",
54555
54430
  name: tc.name,
@@ -54569,7 +54444,6 @@ function createOpenaiAdapter(requestBody, clientSystem, hostCredit = 0, absorbNa
54569
54444
  }
54570
54445
  for (const [idx, tc] of pending) {
54571
54446
  if (!realIndexes.has(idx) && tc.name.length > 0) {
54572
- toolCallsEmitted++;
54573
54447
  yield {
54574
54448
  kind: "tool_call",
54575
54449
  name: tc.name,
@@ -54594,7 +54468,6 @@ function createOpenaiAdapter(requestBody, clientSystem, hostCredit = 0, absorbNa
54594
54468
  if (sawRealToolCall) {
54595
54469
  yield { kind: "meta", chunk: Buffer.from(eventStr + "\n\n", "utf8") };
54596
54470
  }
54597
- maybeWarnDegenerate("stop");
54598
54471
  yield { kind: "done", finishReason: "stop", ...sawRealToolCall ? { suppressCompletion: true } : {} };
54599
54472
  continue;
54600
54473
  }
@@ -54640,11 +54513,9 @@ function createOpenaiAdapter(requestBody, clientSystem, hostCredit = 0, absorbNa
54640
54513
  if (sawRealToolCall) {
54641
54514
  const chunk = patchUsageChunk(eventStr, parsed, u2 ?? {}, hostCredit);
54642
54515
  yield { kind: "meta", chunk };
54643
- maybeWarnDegenerate(finishReason);
54644
54516
  yield { kind: "done", finishReason, suppressCompletion: true };
54645
54517
  continue;
54646
54518
  } else {
54647
- maybeWarnDegenerate(finishReason);
54648
54519
  yield {
54649
54520
  kind: "done",
54650
54521
  finishReason: hadToolCalls && finishReason === "stop" ? "tool_calls" : finishReason
@@ -54653,7 +54524,6 @@ function createOpenaiAdapter(requestBody, clientSystem, hostCredit = 0, absorbNa
54653
54524
  }
54654
54525
  if (!delta) continue;
54655
54526
  if (typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0) {
54656
- sawReasoning = true;
54657
54527
  yield { kind: "reasoning", delta: delta.reasoning_content, raw: finishReason ? stripFinishReasonChunk(rawBuf) : rawBuf };
54658
54528
  }
54659
54529
  if (delta.tool_calls) {
@@ -54931,17 +54801,6 @@ ${systemPrompt}` : systemPrompt;
54931
54801
  log("warn", `[tag-echo] stripped model-emitted render tag: ${snippet.slice(0, 80).replace(/\n/g, " ")}`);
54932
54802
  });
54933
54803
  let lastTextIndex = null;
54934
- let sawThinking = false;
54935
- let toolCallsEmitted = 0;
54936
- let degenerateWarned = false;
54937
- const maybeWarnDegenerate = (reason) => {
54938
- if (degenerateWarned) return;
54939
- const msg = degenerateTurnWarning({ reason, terminalReason: "end_turn", toolCalls: toolCallsEmitted, text: tagFilter.stats(), sawThinking, wire: "anthropic" });
54940
- if (msg) {
54941
- degenerateWarned = true;
54942
- log("warn", msg);
54943
- }
54944
- };
54945
54804
  for await (const eventStr of iterSseEvents2(upstream)) {
54946
54805
  const parsed = parseAnthropicSse(eventStr);
54947
54806
  if (!parsed) continue;
@@ -54978,10 +54837,7 @@ ${systemPrompt}` : systemPrompt;
54978
54837
  const id = typeof block.id === "string" ? block.id : `toolu_${upstreamIndex}`;
54979
54838
  pending.set(upstreamIndex, { id, name, json: "" });
54980
54839
  } else {
54981
- if (block.type === "thinking" || block.type === "redacted_thinking") {
54982
- thinkingIndexes.add(upstreamIndex);
54983
- sawThinking = true;
54984
- }
54840
+ if (block.type === "thinking" || block.type === "redacted_thinking") thinkingIndexes.add(upstreamIndex);
54985
54841
  const ci2 = clientIndex++;
54986
54842
  indexMap.set(upstreamIndex, ci2);
54987
54843
  openBlocks.push(ci2);
@@ -55026,7 +54882,6 @@ ${systemPrompt}` : systemPrompt;
55026
54882
  const tb = pending.get(upstreamIndex);
55027
54883
  if (tb) {
55028
54884
  pending.delete(upstreamIndex);
55029
- toolCallsEmitted++;
55030
54885
  yield {
55031
54886
  kind: "tool_call",
55032
54887
  name: tb.name,
@@ -55073,7 +54928,6 @@ ${systemPrompt}` : systemPrompt;
55073
54928
  cachedTokens: roundCached
55074
54929
  };
55075
54930
  }
55076
- maybeWarnDegenerate(stopReason);
55077
54931
  yield { kind: "done", finishReason: stopReason };
55078
54932
  } else if (type === "message_stop") {
55079
54933
  if (lastTextIndex !== null) {
@@ -55092,7 +54946,6 @@ ${systemPrompt}` : systemPrompt;
55092
54946
  cachedTokens: roundCached
55093
54947
  };
55094
54948
  }
55095
- maybeWarnDegenerate(stopReason);
55096
54949
  yield { kind: "done", finishReason: stopReason ?? "end_turn" };
55097
54950
  } else if (round === 1) {
55098
54951
  yield { kind: "meta", chunk: rawBuf, firstRoundOnly: true };
@@ -56703,18 +56556,11 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
56703
56556
 
56704
56557
  `;
56705
56558
  };
56706
- let sawToolUse = false;
56707
- let sawThinking = false;
56708
- let visibleTextChars = 0;
56709
- let finalFinishReason;
56710
56559
  const flushTails = () => {
56711
56560
  let out = "";
56712
56561
  for (const s3 of streams.values()) {
56713
56562
  const tail = s3.filter.flush();
56714
- if (tail.length > 0) {
56715
- out += syntheticTail(s3.field, s3.index, tail);
56716
- if (s3.field === "content" || s3.field === "text") visibleTextChars += tail.length;
56717
- }
56563
+ if (tail.length > 0) out += syntheticTail(s3.field, s3.index, tail);
56718
56564
  }
56719
56565
  return out;
56720
56566
  };
@@ -56737,28 +56583,6 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
56737
56583
  reason: "plugin chat passthrough stream ended without a completion event"
56738
56584
  });
56739
56585
  };
56740
- const maybeWarnDegenerate = () => {
56741
- if (!sawTerminal || res.destroyed || res.writableEnded) return;
56742
- let inputChars = 0;
56743
- let dropped = false;
56744
- for (const s3 of streams.values()) {
56745
- const st2 = s3.filter.stats();
56746
- inputChars += st2.inputChars;
56747
- dropped = dropped || st2.dropped;
56748
- }
56749
- const msg = degenerateTurnWarning({
56750
- reason: finalFinishReason,
56751
- terminalReason: protocol === "anthropic" ? "end_turn" : "stop",
56752
- toolCalls: sawToolUse ? 1 : 0,
56753
- text: { inputChars, outputChars: visibleTextChars, dropped },
56754
- sawThinking,
56755
- wire: `plugin-passthrough-${protocol}`
56756
- });
56757
- if (msg) {
56758
- log("warn", msg);
56759
- log2?.(msg);
56760
- }
56761
- };
56762
56586
  const pushField = (field, index, text) => {
56763
56587
  const s3 = filterFor(field, index);
56764
56588
  const clean = s3.filter.push(text);
@@ -56778,28 +56602,21 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
56778
56602
  let hadText = false;
56779
56603
  for (let ci2 = 0; ci2 < choices.length; ci2++) {
56780
56604
  const ch = choices[ci2];
56781
- if (ch && typeof ch["finish_reason"] === "string") finalFinishReason = ch["finish_reason"];
56782
56605
  const d = ch?.["delta"];
56783
56606
  if (!d || typeof d !== "object") continue;
56784
56607
  const dd = d;
56785
- if (dd["tool_calls"] !== void 0) sawToolUse = true;
56786
56608
  for (const field of ["content", "reasoning_content", "reasoning"]) {
56787
56609
  const v2 = dd[field];
56788
56610
  if (typeof v2 !== "string") continue;
56789
56611
  hadText = true;
56790
- if (field !== "content" && v2.length > 0) sawThinking = true;
56791
56612
  if (!mayStartRenderTag(v2) && !anyPending()) {
56792
56613
  if (v2.length > 0) keptText = true;
56793
- if (field === "content") visibleTextChars += v2.length;
56794
56614
  continue;
56795
56615
  }
56796
56616
  const index = typeof ch?.["index"] === "number" ? ch["index"] : ci2;
56797
56617
  const [clean, changed] = pushField(field, index, v2);
56798
56618
  if (clean.length === 0) droppedText = true;
56799
- else {
56800
- keptText = true;
56801
- if (field === "content") visibleTextChars += clean.length;
56802
- }
56619
+ else keptText = true;
56803
56620
  if (changed) {
56804
56621
  if (!rebuilt) {
56805
56622
  rebuilt = { ...ev, choices: choices.map((c) => ({ ...c, delta: { ...c["delta"] } })) };
@@ -56818,13 +56635,6 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
56818
56635
  return rawEvent + "\n\n";
56819
56636
  };
56820
56637
  const processAnthropic = (ev, rawEvent) => {
56821
- if (ev["type"] === "content_block_start") {
56822
- const cb = ev["content_block"];
56823
- const bt2 = cb && typeof cb === "object" ? cb["type"] : void 0;
56824
- if (bt2 === "tool_use") sawToolUse = true;
56825
- else if (bt2 === "thinking" || bt2 === "redacted_thinking") sawThinking = true;
56826
- return anyPending() ? flushTails() + rawEvent + "\n\n" : rawEvent + "\n\n";
56827
- }
56828
56638
  if (ev["type"] !== "content_block_delta") {
56829
56639
  return anyPending() ? flushTails() + rawEvent + "\n\n" : rawEvent + "\n\n";
56830
56640
  }
@@ -56835,17 +56645,11 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
56835
56645
  return rawEvent + "\n\n";
56836
56646
  }
56837
56647
  const raw = d[field];
56838
- if (field === "thinking" && raw.length > 0) sawThinking = true;
56839
56648
  if (!mayStartRenderTag(raw) && !anyPending()) {
56840
- if (field === "text" && raw.length > 0) visibleTextChars += raw.length;
56841
56649
  return rawEvent + "\n\n";
56842
56650
  }
56843
56651
  const [clean, changed] = pushField(field, index, raw);
56844
- if (!changed) {
56845
- if (field === "text" && raw.length > 0) visibleTextChars += raw.length;
56846
- return rawEvent + "\n\n";
56847
- }
56848
- if (field === "text" && clean.length > 0) visibleTextChars += clean.length;
56652
+ if (!changed) return rawEvent + "\n\n";
56849
56653
  if (clean.length === 0 && Object.keys(d ?? {}).length <= 2) return "";
56850
56654
  return rebuildEvent(rawEvent, { ...ev, delta: { ...d, [field]: clean } });
56851
56655
  };
@@ -56876,10 +56680,6 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
56876
56680
  continue;
56877
56681
  }
56878
56682
  if (ev["type"] === "message_stop") sawTerminal = true;
56879
- if (ev["type"] === "message_delta") {
56880
- const d = ev["delta"];
56881
- if (d && typeof d["stop_reason"] === "string") finalFinishReason = d["stop_reason"];
56882
- }
56883
56683
  const sample = usageFromSseEvent(ev);
56884
56684
  if (sample) mergeUsageSample(acc, sample);
56885
56685
  let backfilled = false;
@@ -56903,7 +56703,6 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
56903
56703
  if (rest.length > 0 && !res.destroyed && !res.writableEnded) await write(rest);
56904
56704
  settleUsage();
56905
56705
  maybeNoteTruncated();
56906
- maybeWarnDegenerate();
56907
56706
  } catch (e) {
56908
56707
  settleUsage();
56909
56708
  maybeNoteTruncated();
@@ -56940,9 +56739,6 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
56940
56739
  log("warn", `[tag-echo] stripped model-emitted render tag (plugin passthrough): ${snippet.slice(0, 80).replace(/\n/g, " ")}`);
56941
56740
  log2?.(`[tag-echo] stripped model-emitted render tag from plugin passthrough text`);
56942
56741
  });
56943
- let sawFunctionCall = false;
56944
- let sawReasoning = false;
56945
- let responseStatus;
56946
56742
  const write = (s3) => {
56947
56743
  if (!res.write(Buffer.from(s3, "utf8"))) {
56948
56744
  return new Promise((r) => res.once("drain", () => r()));
@@ -56963,22 +56759,6 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
56963
56759
  reason: "plugin responses passthrough stream ended without a completion event"
56964
56760
  });
56965
56761
  };
56966
- const maybeWarnDegenerate = () => {
56967
- if (!sawTerminal || res.destroyed || res.writableEnded) return;
56968
- const st2 = tagFilter.stats();
56969
- const msg = degenerateTurnWarning({
56970
- reason: responseStatus,
56971
- terminalReason: "completed",
56972
- toolCalls: sawFunctionCall ? 1 : 0,
56973
- text: st2,
56974
- sawThinking: sawReasoning,
56975
- wire: "plugin-passthrough-responses"
56976
- });
56977
- if (msg) {
56978
- log("warn", msg);
56979
- log2?.(msg);
56980
- }
56981
- };
56982
56762
  let lastDeltaMeta = null;
56983
56763
  const flushTail = (after) => {
56984
56764
  const tail = tagFilter.flush();
@@ -57018,16 +56798,6 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
57018
56798
  const sample = usageFromSseEvent(ev);
57019
56799
  if (sample) mergeUsageSample(acc, sample);
57020
56800
  const type = ev["type"];
57021
- if (typeof type === "string") {
57022
- if (type.startsWith("response.reasoning")) sawReasoning = true;
57023
- if (type === "response.output_item.added" || type === "response.output_item.done") {
57024
- const item = ev["item"];
57025
- const it2 = item?.["type"];
57026
- if (it2 === "function_call" || it2 === "custom_tool_call") sawFunctionCall = true;
57027
- }
57028
- const resp = ev["response"];
57029
- if (resp && typeof resp["status"] === "string") responseStatus = resp["status"];
57030
- }
57031
56801
  if (type === "response.output_text.done" || type === "response.content_part.done" || type === "response.output_item.done" || type === "response.completed" || type === "response.failed" || type === "response.incomplete") {
57032
56802
  if (type === "response.completed" || type === "response.failed" || type === "response.incomplete") sawTerminal = true;
57033
56803
  let evOut = ev;
@@ -57073,7 +56843,6 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
57073
56843
  const rest = flushTail("");
57074
56844
  if (rest.length > 0) await write(rest);
57075
56845
  }
57076
- maybeWarnDegenerate();
57077
56846
  settleUsage();
57078
56847
  maybeNoteTruncated();
57079
56848
  } catch (e) {
@@ -59149,7 +58918,6 @@ async function handle(req, res, opts, core, config, log2, instanceId, instanceSt
59149
58918
  try {
59150
58919
  const result = await fetchWithTimeout(targetUrl2, {
59151
58920
  method: "HEAD",
59152
- redirect: "follow",
59153
58921
  ...proxyUrl ? { dispatcher: proxyDispatcher(proxyUrl, 15e3) } : {}
59154
58922
  }, 15e3);
59155
58923
  result.clearTimer();
@@ -59346,11 +59114,7 @@ ${bodyBuffer.toString("utf8")}`);
59346
59114
  }
59347
59115
  }
59348
59116
  let prepared = null;
59349
- const routePassthrough = !opts.passthrough && findRoute(opts.routes, route?.rewrittenUrl)?.passthrough === true;
59350
- if (routePassthrough && hopMarker === void 0 && protocol && parsed) {
59351
- log2("info", `[route-passthrough] ${maskUrlsInText(route?.rewrittenUrl ?? "")} matches a passthrough route \u2014 forwarding verbatim, kernel bypassed`);
59352
- }
59353
- if (!opts.passthrough && !routePassthrough && hopMarker === void 0 && protocol && parsed && typeof parsed === "object") {
59117
+ if (!opts.passthrough && hopMarker === void 0 && protocol && parsed && typeof parsed === "object") {
59354
59118
  const sessionHeader = headerValue2(req, opts.sessionHeader);
59355
59119
  let pluginAgent = pluginAgentHeader(req.headers);
59356
59120
  let pluginConversation = pluginConversationHeader(req.headers);
@@ -59611,7 +59375,7 @@ ${bodyBuffer.toString("utf8")}`);
59611
59375
  }
59612
59376
  }
59613
59377
  if (!prepared) {
59614
- if (protocol === null && !opts.passthrough && !routePassthrough && !isModelDiscoveryPath(urlPath)) {
59378
+ if (protocol === null && !opts.passthrough && !isModelDiscoveryPath(urlPath)) {
59615
59379
  logUnrecognizedPath(log2, req.url ?? "");
59616
59380
  }
59617
59381
  await forward(req, res, opts, bodyBuffer, null, core, reqConfig, log2, route, instanceId, void 0);
@@ -65096,22 +64860,17 @@ args = [${JSON.stringify(path14.join(selfPackageRoot(), "dist", "mcp.js"))}]
65096
64860
  env = { BILI_MCP_PROXY = ${JSON.stringify(proxyOriginForInstall())} }
65097
64861
  `;
65098
64862
  }
65099
- function malformedCodexArgs(block) {
65100
- return /^[ \t]*args[ \t]*=[ \t]*["']/m.test(block);
65101
- }
65102
64863
  function codexInstall() {
65103
64864
  const file = codexToml();
65104
64865
  const text = fs11.existsSync(file) ? fs11.readFileSync(file, "utf8") : "";
65105
64866
  const existing = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text);
65106
64867
  if (existing !== null) {
65107
64868
  const block = text.slice(existing.index, text.indexOf("\n[", existing.index + 1) === -1 ? void 0 : text.indexOf("\n[", existing.index + 1));
65108
- const canonical = codexBlock().replace(/^\n/, "");
65109
- if (block.trimEnd() === canonical.trimEnd()) return `codex: already installed (${file})`;
65110
- const refreshed = text.slice(0, existing.index) + canonical + text.slice(existing.index + block.length);
64869
+ if (block.includes(`BILI_MCP_PROXY = ${JSON.stringify(proxyOriginForInstall())}`)) return `codex: already installed (${file})`;
64870
+ const refreshed = text.slice(0, existing.index) + codexBlock().replace(/^\n/, "") + text.slice(existing.index + block.length);
65111
64871
  backupOnce(file);
65112
64872
  fs11.writeFileSync(file, refreshed);
65113
- const healed = malformedCodexArgs(block) ? " (repaired args: was not an array)" : "";
65114
- return `codex: refreshed [mcp_servers.bili] -> ${file}${healed}`;
64873
+ return `codex: refreshed proxy origin -> ${file} [mcp_servers.bili]`;
65115
64874
  }
65116
64875
  fs11.mkdirSync(path14.dirname(file), { recursive: true });
65117
64876
  backupOnce(file);
@@ -66193,31 +65952,10 @@ function stopProxy(handle2) {
66193
65952
  } catch {
66194
65953
  }
66195
65954
  }
66196
- function quoteWinToken(token) {
66197
- if (!/\s/.test(token) || token.includes('"')) return token;
66198
- return `"${token}"`;
66199
- }
66200
- function buildWindowsCommandLine(cmd, args) {
66201
- return `"${[cmd, ...args].map(quoteWinToken).join(" ")}"`;
66202
- }
66203
- function planClientSpawn(cmd, args, env, platform = process.platform) {
66204
- if (platform !== "win32") return { command: cmd, args: [...args] };
66205
- const lower = cmd.toLowerCase();
66206
- const base = cmd.slice(Math.max(cmd.lastIndexOf("/"), cmd.lastIndexOf("\\")) + 1);
66207
- const needsCmd = lower.endsWith(".cmd") || lower.endsWith(".bat") || !path15.extname(base);
66208
- if (!needsCmd) return { command: cmd, args: [...args] };
66209
- const comspec = nonEmpty2(env.COMSPEC) ? env.COMSPEC : "cmd.exe";
66210
- return {
66211
- command: comspec,
66212
- args: ["/d", "/s", "/c", buildWindowsCommandLine(cmd, args)],
66213
- windowsVerbatimArguments: true
66214
- };
66215
- }
66216
65955
  function runClient(cmd, args, env, deps) {
66217
65956
  const spawnImpl = deps?.spawnImpl ?? spawn;
66218
- const plan = planClientSpawn(cmd, args, env, deps?.platform);
66219
65957
  return new Promise((resolve, reject) => {
66220
- const child = spawnImpl(plan.command, plan.args, { stdio: "inherit", env, windowsVerbatimArguments: plan.windowsVerbatimArguments });
65958
+ const child = spawnImpl(cmd, args, { stdio: "inherit", env, shell: process.platform === "win32" });
66221
65959
  child.on?.("error", (...rest) => reject(rest[0]));
66222
65960
  child.on?.("exit", (...rest) => {
66223
65961
  const code = rest[0];