billion-context 0.1.43 → 0.1.45

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
@@ -1141,14 +1141,14 @@ var require_util = __commonJS({
1141
1141
  }
1142
1142
  const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
1143
1143
  let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`;
1144
- let path12 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
1144
+ let path15 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
1145
1145
  if (origin[origin.length - 1] === "/") {
1146
1146
  origin = origin.slice(0, origin.length - 1);
1147
1147
  }
1148
- if (path12 && path12[0] !== "/") {
1149
- path12 = `/${path12}`;
1148
+ if (path15 && path15[0] !== "/") {
1149
+ path15 = `/${path15}`;
1150
1150
  }
1151
- return new URL(`${origin}${path12}`);
1151
+ return new URL(`${origin}${path15}`);
1152
1152
  }
1153
1153
  if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
1154
1154
  throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -1969,9 +1969,9 @@ var require_diagnostics = __commonJS({
1969
1969
  "undici:client:sendHeaders",
1970
1970
  (evt) => {
1971
1971
  const {
1972
- request: { method, path: path12, origin }
1972
+ request: { method, path: path15, origin }
1973
1973
  } = evt;
1974
- debugLog("sending request to %s %s%s", method, origin, path12);
1974
+ debugLog("sending request to %s %s%s", method, origin, path15);
1975
1975
  }
1976
1976
  );
1977
1977
  }
@@ -1989,14 +1989,14 @@ var require_diagnostics = __commonJS({
1989
1989
  "undici:request:headers",
1990
1990
  (evt) => {
1991
1991
  const {
1992
- request: { method, path: path12, origin },
1992
+ request: { method, path: path15, origin },
1993
1993
  response: { statusCode }
1994
1994
  } = evt;
1995
1995
  debugLog(
1996
1996
  "received response to %s %s%s - HTTP %d",
1997
1997
  method,
1998
1998
  origin,
1999
- path12,
1999
+ path15,
2000
2000
  statusCode
2001
2001
  );
2002
2002
  }
@@ -2005,23 +2005,23 @@ var require_diagnostics = __commonJS({
2005
2005
  "undici:request:trailers",
2006
2006
  (evt) => {
2007
2007
  const {
2008
- request: { method, path: path12, origin }
2008
+ request: { method, path: path15, origin }
2009
2009
  } = evt;
2010
- debugLog("trailers received from %s %s%s", method, origin, path12);
2010
+ debugLog("trailers received from %s %s%s", method, origin, path15);
2011
2011
  }
2012
2012
  );
2013
2013
  diagnosticsChannel.subscribe(
2014
2014
  "undici:request:error",
2015
2015
  (evt) => {
2016
2016
  const {
2017
- request: { method, path: path12, origin },
2017
+ request: { method, path: path15, origin },
2018
2018
  error
2019
2019
  } = evt;
2020
2020
  debugLog(
2021
2021
  "request to %s %s%s errored - %s",
2022
2022
  method,
2023
2023
  origin,
2024
- path12,
2024
+ path15,
2025
2025
  error.message
2026
2026
  );
2027
2027
  }
@@ -2136,7 +2136,7 @@ var require_request = __commonJS({
2136
2136
  var kHandler = /* @__PURE__ */ Symbol("handler");
2137
2137
  var Request = class {
2138
2138
  constructor(origin, {
2139
- path: path12,
2139
+ path: path15,
2140
2140
  method,
2141
2141
  body,
2142
2142
  headers,
@@ -2153,11 +2153,11 @@ var require_request = __commonJS({
2153
2153
  maxRedirections,
2154
2154
  typeOfService
2155
2155
  }, handler) {
2156
- if (typeof path12 !== "string") {
2156
+ if (typeof path15 !== "string") {
2157
2157
  throw new InvalidArgumentError("path must be a string");
2158
- } else if (path12[0] !== "/" && !(path12.startsWith("http://") || path12.startsWith("https://")) && method !== "CONNECT") {
2158
+ } else if (path15[0] !== "/" && !(path15.startsWith("http://") || path15.startsWith("https://")) && method !== "CONNECT") {
2159
2159
  throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
2160
- } else if (invalidPathRegex.test(path12)) {
2160
+ } else if (invalidPathRegex.test(path15)) {
2161
2161
  throw new InvalidArgumentError("invalid request path");
2162
2162
  }
2163
2163
  if (typeof method !== "string") {
@@ -2232,7 +2232,7 @@ var require_request = __commonJS({
2232
2232
  this.completed = false;
2233
2233
  this.aborted = false;
2234
2234
  this.upgrade = upgrade || null;
2235
- this.path = query ? serializePathWithQuery(path12, query) : path12;
2235
+ this.path = query ? serializePathWithQuery(path15, query) : path15;
2236
2236
  this.origin = origin;
2237
2237
  this.protocol = getProtocolFromUrlString(origin);
2238
2238
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -6068,20 +6068,20 @@ var require_formdata_parser = __commonJS({
6068
6068
  );
6069
6069
  let value;
6070
6070
  if (isExtended) {
6071
- const headerValue2 = collectASequenceOfBytes(
6071
+ const headerValue3 = collectASequenceOfBytes(
6072
6072
  (char) => char !== 32 && char !== 13 && char !== 10 && char !== 59,
6073
6073
  // not space, CRLF, or ;
6074
6074
  input,
6075
6075
  position
6076
6076
  );
6077
- if (headerValue2[0] !== 117 && headerValue2[0] !== 85 || // u or U
6078
- headerValue2[1] !== 116 && headerValue2[1] !== 84 || // t or T
6079
- headerValue2[2] !== 102 && headerValue2[2] !== 70 || // f or F
6080
- headerValue2[3] !== 45 || // -
6081
- headerValue2[4] !== 56) {
6077
+ if (headerValue3[0] !== 117 && headerValue3[0] !== 85 || // u or U
6078
+ headerValue3[1] !== 116 && headerValue3[1] !== 84 || // t or T
6079
+ headerValue3[2] !== 102 && headerValue3[2] !== 70 || // f or F
6080
+ headerValue3[3] !== 45 || // -
6081
+ headerValue3[4] !== 56) {
6082
6082
  throw parsingError("unknown encoding, expected utf-8''");
6083
6083
  }
6084
- value = decodeURIComponent(decoder.decode(headerValue2.subarray(7)));
6084
+ value = decodeURIComponent(decoder.decode(headerValue3.subarray(7)));
6085
6085
  } else if (input[position.position] === 34) {
6086
6086
  position.position++;
6087
6087
  const quotedValue = collectASequenceOfBytes(
@@ -6170,23 +6170,23 @@ var require_formdata_parser = __commonJS({
6170
6170
  break;
6171
6171
  }
6172
6172
  case "content-type": {
6173
- let headerValue2 = collectASequenceOfBytes(
6173
+ let headerValue3 = collectASequenceOfBytes(
6174
6174
  (char) => char !== 10 && char !== 13,
6175
6175
  input,
6176
6176
  position
6177
6177
  );
6178
- headerValue2 = removeChars(headerValue2, false, true, (char) => char === 9 || char === 32);
6179
- contentType = isomorphicDecode(headerValue2);
6178
+ headerValue3 = removeChars(headerValue3, false, true, (char) => char === 9 || char === 32);
6179
+ contentType = isomorphicDecode(headerValue3);
6180
6180
  break;
6181
6181
  }
6182
6182
  case "content-transfer-encoding": {
6183
- let headerValue2 = collectASequenceOfBytes(
6183
+ let headerValue3 = collectASequenceOfBytes(
6184
6184
  (char) => char !== 10 && char !== 13,
6185
6185
  input,
6186
6186
  position
6187
6187
  );
6188
- headerValue2 = removeChars(headerValue2, false, true, (char) => char === 9 || char === 32);
6189
- encoding = isomorphicDecode(headerValue2);
6188
+ headerValue3 = removeChars(headerValue3, false, true, (char) => char === 9 || char === 32);
6189
+ encoding = isomorphicDecode(headerValue3);
6190
6190
  break;
6191
6191
  }
6192
6192
  default: {
@@ -7415,7 +7415,7 @@ var require_client_h1 = __commonJS({
7415
7415
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
7416
7416
  }
7417
7417
  function writeH1(client, request) {
7418
- const { method, path: path12, host, upgrade, blocking, reset } = request;
7418
+ const { method, path: path15, host, upgrade, blocking, reset } = request;
7419
7419
  let { body, headers, contentLength } = request;
7420
7420
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
7421
7421
  if (util.isFormDataLike(body)) {
@@ -7493,7 +7493,7 @@ var require_client_h1 = __commonJS({
7493
7493
  if (socket.setTypeOfService) {
7494
7494
  socket.setTypeOfService(request.typeOfService);
7495
7495
  }
7496
- let header = `${method} ${path12} HTTP/1.1\r
7496
+ let header = `${method} ${path15} HTTP/1.1\r
7497
7497
  `;
7498
7498
  if (typeof host === "string") {
7499
7499
  header += `host: ${host}\r
@@ -8146,7 +8146,7 @@ var require_client_h2 = __commonJS({
8146
8146
  function writeH2(client, request) {
8147
8147
  const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout];
8148
8148
  const session = client[kHTTP2Session];
8149
- const { method, path: path12, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
8149
+ const { method, path: path15, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
8150
8150
  let { body } = request;
8151
8151
  if (upgrade != null && upgrade !== "websocket") {
8152
8152
  util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -8214,7 +8214,7 @@ var require_client_h2 = __commonJS({
8214
8214
  }
8215
8215
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
8216
8216
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
8217
- headers[HTTP2_HEADER_PATH] = path12;
8217
+ headers[HTTP2_HEADER_PATH] = path15;
8218
8218
  if (protocol === "ws:" || protocol === "wss:") {
8219
8219
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
8220
8220
  } else {
@@ -8255,7 +8255,7 @@ var require_client_h2 = __commonJS({
8255
8255
  stream2.setTimeout(requestTimeout);
8256
8256
  return true;
8257
8257
  }
8258
- headers[HTTP2_HEADER_PATH] = path12;
8258
+ headers[HTTP2_HEADER_PATH] = path15;
8259
8259
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
8260
8260
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
8261
8261
  if (body && typeof body.read === "function") {
@@ -10598,10 +10598,10 @@ var require_proxy_agent = __commonJS({
10598
10598
  };
10599
10599
  const {
10600
10600
  origin,
10601
- path: path12 = "/",
10601
+ path: path15 = "/",
10602
10602
  headers = {}
10603
10603
  } = opts;
10604
- opts.path = origin + path12;
10604
+ opts.path = origin + path15;
10605
10605
  if (!("host" in headers) && !("Host" in headers)) {
10606
10606
  const { host } = new URL(origin);
10607
10607
  headers.host = host;
@@ -12612,8 +12612,8 @@ var require_mock_utils = __commonJS({
12612
12612
  }
12613
12613
  function lowerCaseEntries(headers) {
12614
12614
  return Object.fromEntries(
12615
- Object.entries(headers).map(([headerName, headerValue2]) => {
12616
- return [headerName.toLocaleLowerCase(), headerValue2];
12615
+ Object.entries(headers).map(([headerName, headerValue3]) => {
12616
+ return [headerName.toLocaleLowerCase(), headerValue3];
12617
12617
  })
12618
12618
  );
12619
12619
  }
@@ -12653,8 +12653,8 @@ var require_mock_utils = __commonJS({
12653
12653
  return false;
12654
12654
  }
12655
12655
  for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch2.headers)) {
12656
- const headerValue2 = getHeaderByName(headers, matchHeaderName);
12657
- if (!matchValue(matchHeaderValue, headerValue2)) {
12656
+ const headerValue3 = getHeaderByName(headers, matchHeaderName);
12657
+ if (!matchValue(matchHeaderValue, headerValue3)) {
12658
12658
  return false;
12659
12659
  }
12660
12660
  }
@@ -12684,20 +12684,20 @@ var require_mock_utils = __commonJS({
12684
12684
  }
12685
12685
  return normalizedQp;
12686
12686
  }
12687
- function safeUrl(path12) {
12688
- if (typeof path12 !== "string") {
12689
- return path12;
12687
+ function safeUrl(path15) {
12688
+ if (typeof path15 !== "string") {
12689
+ return path15;
12690
12690
  }
12691
- const pathSegments = path12.split("?", 3);
12691
+ const pathSegments = path15.split("?", 3);
12692
12692
  if (pathSegments.length !== 2) {
12693
- return path12;
12693
+ return path15;
12694
12694
  }
12695
12695
  const qp = new URLSearchParams(pathSegments.pop());
12696
12696
  qp.sort();
12697
12697
  return [...pathSegments, qp.toString()].join("?");
12698
12698
  }
12699
- function matchKey(mockDispatch2, { path: path12, method, body, headers }) {
12700
- const pathMatch = matchValue(mockDispatch2.path, path12);
12699
+ function matchKey(mockDispatch2, { path: path15, method, body, headers }) {
12700
+ const pathMatch = matchValue(mockDispatch2.path, path15);
12701
12701
  const methodMatch = matchValue(mockDispatch2.method, method);
12702
12702
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
12703
12703
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -12722,8 +12722,8 @@ var require_mock_utils = __commonJS({
12722
12722
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
12723
12723
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
12724
12724
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
12725
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path12, ignoreTrailingSlash }) => {
12726
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path12)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path12), resolvedPath);
12725
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path15, ignoreTrailingSlash }) => {
12726
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path15)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path15), resolvedPath);
12727
12727
  });
12728
12728
  if (matchedMockDispatches.length === 0) {
12729
12729
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -12762,19 +12762,19 @@ var require_mock_utils = __commonJS({
12762
12762
  mockDispatches.splice(index, 1);
12763
12763
  }
12764
12764
  }
12765
- function removeTrailingSlash(path12) {
12766
- while (path12.endsWith("/")) {
12767
- path12 = path12.slice(0, -1);
12765
+ function removeTrailingSlash(path15) {
12766
+ while (path15.endsWith("/")) {
12767
+ path15 = path15.slice(0, -1);
12768
12768
  }
12769
- if (path12.length === 0) {
12770
- path12 = "/";
12769
+ if (path15.length === 0) {
12770
+ path15 = "/";
12771
12771
  }
12772
- return path12;
12772
+ return path15;
12773
12773
  }
12774
12774
  function buildKey(opts) {
12775
- const { path: path12, method, body, headers, query } = opts;
12775
+ const { path: path15, method, body, headers, query } = opts;
12776
12776
  return {
12777
- path: path12,
12777
+ path: path15,
12778
12778
  method,
12779
12779
  body,
12780
12780
  headers,
@@ -13464,10 +13464,10 @@ var require_pending_interceptors_formatter = __commonJS({
13464
13464
  }
13465
13465
  format(pendingInterceptors) {
13466
13466
  const withPrettyHeaders = pendingInterceptors.map(
13467
- ({ method, path: path12, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
13467
+ ({ method, path: path15, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
13468
13468
  Method: method,
13469
13469
  Origin: origin,
13470
- Path: path12,
13470
+ Path: path15,
13471
13471
  "Status code": statusCode,
13472
13472
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
13473
13473
  Invocations: timesInvoked,
@@ -13549,9 +13549,9 @@ var require_mock_agent = __commonJS({
13549
13549
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
13550
13550
  const dispatchOpts = { ...opts };
13551
13551
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
13552
- const [path12, searchParams] = dispatchOpts.path.split("?");
13552
+ const [path15, searchParams] = dispatchOpts.path.split("?");
13553
13553
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
13554
- dispatchOpts.path = `${path12}?${normalizedSearchParams}`;
13554
+ dispatchOpts.path = `${path15}?${normalizedSearchParams}`;
13555
13555
  }
13556
13556
  return this[kAgent].dispatch(dispatchOpts, handler);
13557
13557
  }
@@ -13952,12 +13952,12 @@ var require_snapshot_recorder = __commonJS({
13952
13952
  * @return {Promise<void>} - Resolves when snapshots are loaded
13953
13953
  */
13954
13954
  async loadSnapshots(filePath) {
13955
- const path12 = filePath || this.#snapshotPath;
13956
- if (!path12) {
13955
+ const path15 = filePath || this.#snapshotPath;
13956
+ if (!path15) {
13957
13957
  throw new InvalidArgumentError("Snapshot path is required");
13958
13958
  }
13959
13959
  try {
13960
- const data = await readFile3(resolve(path12), "utf8");
13960
+ const data = await readFile3(resolve(path15), "utf8");
13961
13961
  const parsed = JSON.parse(data);
13962
13962
  if (Array.isArray(parsed)) {
13963
13963
  this.#snapshots.clear();
@@ -13971,7 +13971,7 @@ var require_snapshot_recorder = __commonJS({
13971
13971
  if (error.code === "ENOENT") {
13972
13972
  this.#snapshots.clear();
13973
13973
  } else {
13974
- throw new UndiciError(`Failed to load snapshots from ${path12}`, { cause: error });
13974
+ throw new UndiciError(`Failed to load snapshots from ${path15}`, { cause: error });
13975
13975
  }
13976
13976
  }
13977
13977
  }
@@ -13982,11 +13982,11 @@ var require_snapshot_recorder = __commonJS({
13982
13982
  * @returns {Promise<void>} - Resolves when snapshots are saved
13983
13983
  */
13984
13984
  async saveSnapshots(filePath) {
13985
- const path12 = filePath || this.#snapshotPath;
13986
- if (!path12) {
13985
+ const path15 = filePath || this.#snapshotPath;
13986
+ if (!path15) {
13987
13987
  throw new InvalidArgumentError("Snapshot path is required");
13988
13988
  }
13989
- const resolvedPath = resolve(path12);
13989
+ const resolvedPath = resolve(path15);
13990
13990
  await mkdir3(dirname6(resolvedPath), { recursive: true });
13991
13991
  const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
13992
13992
  hash,
@@ -14618,15 +14618,15 @@ var require_redirect_handler = __commonJS({
14618
14618
  return;
14619
14619
  }
14620
14620
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
14621
- const path12 = search ? `${pathname}${search}` : pathname;
14622
- const redirectUrlString = `${origin}${path12}`;
14621
+ const path15 = search ? `${pathname}${search}` : pathname;
14622
+ const redirectUrlString = `${origin}${path15}`;
14623
14623
  for (const historyUrl of this.history) {
14624
14624
  if (historyUrl.toString() === redirectUrlString) {
14625
14625
  throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
14626
14626
  }
14627
14627
  }
14628
14628
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
14629
- this.opts.path = path12;
14629
+ this.opts.path = path15;
14630
14630
  this.opts.origin = origin;
14631
14631
  this.opts.query = null;
14632
14632
  }
@@ -15748,8 +15748,8 @@ var require_cache = __commonJS({
15748
15748
  if (!isValidHTTPToken(trimmedHeader)) {
15749
15749
  return void 0;
15750
15750
  }
15751
- const headerValue2 = headers[trimmedHeader];
15752
- output[trimmedHeader] = Array.isArray(headerValue2) ? headerValue2.slice() : headerValue2 ?? null;
15751
+ const headerValue3 = headers[trimmedHeader];
15752
+ output[trimmedHeader] = Array.isArray(headerValue3) ? headerValue3.slice() : headerValue3 ?? null;
15753
15753
  }
15754
15754
  return output;
15755
15755
  }
@@ -16395,10 +16395,10 @@ var require_cache_handler = __commonJS({
16395
16395
  }
16396
16396
  return locationUrl.pathname + locationUrl.search;
16397
16397
  }
16398
- function deleteCachedUri(store, cacheKey, path12) {
16398
+ function deleteCachedUri(store, cacheKey, path15) {
16399
16399
  deleteCachedValue(store, {
16400
16400
  ...cacheKey,
16401
- path: path12
16401
+ path: path15
16402
16402
  });
16403
16403
  for (let i = 0; i < util.safeHTTPMethods.length; i++) {
16404
16404
  const method = util.safeHTTPMethods[i];
@@ -16406,20 +16406,20 @@ var require_cache_handler = __commonJS({
16406
16406
  deleteCachedValue(store, {
16407
16407
  ...cacheKey,
16408
16408
  method,
16409
- path: path12
16409
+ path: path15
16410
16410
  });
16411
16411
  }
16412
16412
  }
16413
16413
  }
16414
- function deleteLocationTargets(store, cacheKey, headerValue2) {
16415
- if (headerValue2 === void 0) {
16414
+ function deleteLocationTargets(store, cacheKey, headerValue3) {
16415
+ if (headerValue3 === void 0) {
16416
16416
  return;
16417
16417
  }
16418
- const values = Array.isArray(headerValue2) ? headerValue2 : [headerValue2];
16418
+ const values = Array.isArray(headerValue3) ? headerValue3 : [headerValue3];
16419
16419
  for (let i = 0; i < values.length; i++) {
16420
- const path12 = getSameOriginPath(cacheKey, values[i]);
16421
- if (path12 !== void 0) {
16422
- deleteCachedUri(store, cacheKey, path12);
16420
+ const path15 = getSameOriginPath(cacheKey, values[i]);
16421
+ if (path15 !== void 0) {
16422
+ deleteCachedUri(store, cacheKey, path15);
16423
16423
  }
16424
16424
  }
16425
16425
  }
@@ -18206,7 +18206,7 @@ var require_sqlite_cache_store = __commonJS({
18206
18206
  var { Writable } = __require("stream");
18207
18207
  var { assertCacheKey, assertCacheValue } = require_cache();
18208
18208
  var DatabaseSync;
18209
- var VERSION2 = 3;
18209
+ var VERSION4 = 3;
18210
18210
  var MAX_ENTRY_SIZE = 2 * 1e3 * 1e3 * 1e3;
18211
18211
  module.exports = class SqliteCacheStore {
18212
18212
  #maxEntrySize = MAX_ENTRY_SIZE;
@@ -18277,7 +18277,7 @@ var require_sqlite_cache_store = __commonJS({
18277
18277
  PRAGMA temp_store = memory;
18278
18278
  PRAGMA optimize;
18279
18279
 
18280
- CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION2} (
18280
+ CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION4} (
18281
18281
  -- Data specific to us
18282
18282
  id INTEGER PRIMARY KEY AUTOINCREMENT,
18283
18283
  url TEXT NOT NULL,
@@ -18296,8 +18296,8 @@ var require_sqlite_cache_store = __commonJS({
18296
18296
  staleAt INTEGER NOT NULL
18297
18297
  );
18298
18298
 
18299
- CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION2}_getValuesQuery ON cacheInterceptorV${VERSION2}(url, method, deleteAt);
18300
- CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION2}_deleteByUrlQuery ON cacheInterceptorV${VERSION2}(deleteAt);
18299
+ CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION4}_getValuesQuery ON cacheInterceptorV${VERSION4}(url, method, deleteAt);
18300
+ CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION4}_deleteByUrlQuery ON cacheInterceptorV${VERSION4}(deleteAt);
18301
18301
  `);
18302
18302
  this.#getValuesQuery = this.#db.prepare(`
18303
18303
  SELECT
@@ -18312,7 +18312,7 @@ var require_sqlite_cache_store = __commonJS({
18312
18312
  vary,
18313
18313
  cachedAt,
18314
18314
  staleAt
18315
- FROM cacheInterceptorV${VERSION2}
18315
+ FROM cacheInterceptorV${VERSION4}
18316
18316
  WHERE
18317
18317
  url = ?
18318
18318
  AND method = ?
@@ -18320,7 +18320,7 @@ var require_sqlite_cache_store = __commonJS({
18320
18320
  deleteAt ASC
18321
18321
  `);
18322
18322
  this.#updateValueQuery = this.#db.prepare(`
18323
- UPDATE cacheInterceptorV${VERSION2} SET
18323
+ UPDATE cacheInterceptorV${VERSION4} SET
18324
18324
  body = ?,
18325
18325
  deleteAt = ?,
18326
18326
  statusCode = ?,
@@ -18334,7 +18334,7 @@ var require_sqlite_cache_store = __commonJS({
18334
18334
  id = ?
18335
18335
  `);
18336
18336
  this.#insertValueQuery = this.#db.prepare(`
18337
- INSERT INTO cacheInterceptorV${VERSION2} (
18337
+ INSERT INTO cacheInterceptorV${VERSION4} (
18338
18338
  url,
18339
18339
  method,
18340
18340
  body,
@@ -18350,20 +18350,20 @@ var require_sqlite_cache_store = __commonJS({
18350
18350
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
18351
18351
  `);
18352
18352
  this.#deleteByUrlQuery = this.#db.prepare(
18353
- `DELETE FROM cacheInterceptorV${VERSION2} WHERE url = ?`
18353
+ `DELETE FROM cacheInterceptorV${VERSION4} WHERE url = ?`
18354
18354
  );
18355
18355
  this.#countEntriesQuery = this.#db.prepare(
18356
- `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION2}`
18356
+ `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION4}`
18357
18357
  );
18358
18358
  this.#deleteExpiredValuesQuery = this.#db.prepare(
18359
- `DELETE FROM cacheInterceptorV${VERSION2} WHERE deleteAt <= ?`
18359
+ `DELETE FROM cacheInterceptorV${VERSION4} WHERE deleteAt <= ?`
18360
18360
  );
18361
18361
  this.#deleteOldValuesQuery = this.#maxCount === Infinity ? null : this.#db.prepare(`
18362
- DELETE FROM cacheInterceptorV${VERSION2}
18362
+ DELETE FROM cacheInterceptorV${VERSION4}
18363
18363
  WHERE id IN (
18364
18364
  SELECT
18365
18365
  id
18366
- FROM cacheInterceptorV${VERSION2}
18366
+ FROM cacheInterceptorV${VERSION4}
18367
18367
  ORDER BY cachedAt ASC
18368
18368
  LIMIT ?
18369
18369
  )
@@ -21297,11 +21297,11 @@ var require_fetch = __commonJS({
21297
21297
  function dispatch({ body }) {
21298
21298
  const url = requestCurrentURL(request);
21299
21299
  const agent = fetchParams.controller.dispatcher;
21300
- const path12 = url.pathname + url.search;
21300
+ const path15 = url.pathname + url.search;
21301
21301
  const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === "?";
21302
21302
  return new Promise((resolve, reject) => agent.dispatch(
21303
21303
  {
21304
- path: hasTrailingQuestionMark ? `${path12}?` : path12,
21304
+ path: hasTrailingQuestionMark ? `${path15}?` : path15,
21305
21305
  origin: url.origin,
21306
21306
  method: request.method,
21307
21307
  body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
@@ -21851,8 +21851,8 @@ var require_cache3 = __commonJS({
21851
21851
  * @returns {requestResponseList}
21852
21852
  */
21853
21853
  #batchCacheOperations(operations) {
21854
- const cache3 = this.#relevantRequestResponseList;
21855
- const backupCache = [...cache3];
21854
+ const cache4 = this.#relevantRequestResponseList;
21855
+ const backupCache = [...cache4];
21856
21856
  const addedItems = [];
21857
21857
  const resultList = [];
21858
21858
  try {
@@ -21879,9 +21879,9 @@ var require_cache3 = __commonJS({
21879
21879
  return [];
21880
21880
  }
21881
21881
  for (const requestResponse of requestResponses) {
21882
- const idx = cache3.indexOf(requestResponse);
21882
+ const idx = cache4.indexOf(requestResponse);
21883
21883
  assert(idx !== -1);
21884
- cache3.splice(idx, 1);
21884
+ cache4.splice(idx, 1);
21885
21885
  }
21886
21886
  } else if (operation.type === "put") {
21887
21887
  if (operation.response == null) {
@@ -21911,11 +21911,11 @@ var require_cache3 = __commonJS({
21911
21911
  }
21912
21912
  requestResponses = this.#queryCache(operation.request);
21913
21913
  for (const requestResponse of requestResponses) {
21914
- const idx = cache3.indexOf(requestResponse);
21914
+ const idx = cache4.indexOf(requestResponse);
21915
21915
  assert(idx !== -1);
21916
- cache3.splice(idx, 1);
21916
+ cache4.splice(idx, 1);
21917
21917
  }
21918
- cache3.push([operation.request, operation.response]);
21918
+ cache4.push([operation.request, operation.response]);
21919
21919
  addedItems.push([operation.request, operation.response]);
21920
21920
  }
21921
21921
  resultList.push([operation.request, operation.response]);
@@ -22092,13 +22092,13 @@ var require_cachestorage = __commonJS({
22092
22092
  if (options.cacheName != null) {
22093
22093
  if (this.#caches.has(options.cacheName)) {
22094
22094
  const cacheList = this.#caches.get(options.cacheName);
22095
- const cache3 = new Cache(kConstruct, cacheList);
22096
- return await cache3.match(request, options);
22095
+ const cache4 = new Cache(kConstruct, cacheList);
22096
+ return await cache4.match(request, options);
22097
22097
  }
22098
22098
  } else {
22099
22099
  for (const cacheList of this.#caches.values()) {
22100
- const cache3 = new Cache(kConstruct, cacheList);
22101
- const response = await cache3.match(request, options);
22100
+ const cache4 = new Cache(kConstruct, cacheList);
22101
+ const response = await cache4.match(request, options);
22102
22102
  if (response !== void 0) {
22103
22103
  return response;
22104
22104
  }
@@ -22128,12 +22128,12 @@ var require_cachestorage = __commonJS({
22128
22128
  webidl.argumentLengthCheck(arguments, 1, prefix);
22129
22129
  cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
22130
22130
  if (this.#caches.has(cacheName)) {
22131
- const cache4 = this.#caches.get(cacheName);
22132
- return new Cache(kConstruct, cache4);
22131
+ const cache5 = this.#caches.get(cacheName);
22132
+ return new Cache(kConstruct, cache5);
22133
22133
  }
22134
- const cache3 = [];
22135
- this.#caches.set(cacheName, cache3);
22136
- return new Cache(kConstruct, cache3);
22134
+ const cache4 = [];
22135
+ this.#caches.set(cacheName, cache4);
22136
+ return new Cache(kConstruct, cache4);
22137
22137
  }
22138
22138
  /**
22139
22139
  * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
@@ -22248,9 +22248,9 @@ var require_util4 = __commonJS({
22248
22248
  }
22249
22249
  }
22250
22250
  }
22251
- function validateCookiePath(path12) {
22252
- for (let i = 0; i < path12.length; ++i) {
22253
- const code = path12.charCodeAt(i);
22251
+ function validateCookiePath(path15) {
22252
+ for (let i = 0; i < path15.length; ++i) {
22253
+ const code = path15.charCodeAt(i);
22254
22254
  if (code < 32 || // exclude CTLs (0-31)
22255
22255
  code > 126 || // exclude DEL and non-ascii
22256
22256
  code === 59) {
@@ -23096,8 +23096,8 @@ var require_util5 = __commonJS({
23096
23096
  return false;
23097
23097
  }
23098
23098
  }
23099
- const num = Number.parseInt(value, 10);
23100
- return num >= 8 && num <= 15;
23099
+ const num2 = Number.parseInt(value, 10);
23100
+ return num2 >= 8 && num2 <= 15;
23101
23101
  }
23102
23102
  function getURLRecord(url, baseURL) {
23103
23103
  let urlRecord;
@@ -25487,11 +25487,11 @@ var require_undici = __commonJS({
25487
25487
  if (typeof opts.path !== "string") {
25488
25488
  throw new InvalidArgumentError("invalid opts.path");
25489
25489
  }
25490
- let path12 = opts.path;
25490
+ let path15 = opts.path;
25491
25491
  if (!opts.path.startsWith("/")) {
25492
- path12 = `/${path12}`;
25492
+ path15 = `/${path15}`;
25493
25493
  }
25494
- url = new URL(util.parseOrigin(url).origin + path12);
25494
+ url = new URL(util.parseOrigin(url).origin + path15);
25495
25495
  } else {
25496
25496
  if (!opts) {
25497
25497
  opts = typeof url === "object" ? url : {};
@@ -25523,14 +25523,14 @@ var require_undici = __commonJS({
25523
25523
  if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) {
25524
25524
  return;
25525
25525
  }
25526
- const capture = {};
25527
- Error.captureStackTrace(capture, appendFetchStackTrace);
25528
- if (!capture.stack) {
25526
+ const capture2 = {};
25527
+ Error.captureStackTrace(capture2, appendFetchStackTrace);
25528
+ if (!capture2.stack) {
25529
25529
  return;
25530
25530
  }
25531
- const captureLines = capture.stack.split("\n").slice(1).join("\n");
25531
+ const captureLines = capture2.stack.split("\n").slice(1).join("\n");
25532
25532
  err2.stack = stack ? `${stack}
25533
- ${captureLines}` : capture.stack;
25533
+ ${captureLines}` : capture2.stack;
25534
25534
  }
25535
25535
  module.exports.fetch = function fetch2(init, options = void 0) {
25536
25536
  return fetchImpl(init, options).catch((err2) => {
@@ -26930,11 +26930,11 @@ var require_util7 = __commonJS({
26930
26930
  }
26931
26931
  var b2 = util.createBuffer();
26932
26932
  for (var i = 0; i < ip.length; ++i) {
26933
- var num = parseInt(ip[i], 10);
26934
- if (isNaN(num)) {
26933
+ var num2 = parseInt(ip[i], 10);
26934
+ if (isNaN(num2)) {
26935
26935
  return null;
26936
26936
  }
26937
- b2.putByte(num);
26937
+ b2.putByte(num2);
26938
26938
  }
26939
26939
  return b2.getBytes();
26940
26940
  };
@@ -27873,8 +27873,8 @@ var require_cipherModes = __commonJS({
27873
27873
  function inc32(block) {
27874
27874
  block[block.length - 1] = block[block.length - 1] + 1 & 4294967295;
27875
27875
  }
27876
- function from64To32(num) {
27877
- return [num / 4294967296 | 0, num & 4294967295];
27876
+ function from64To32(num2) {
27877
+ return [num2 / 4294967296 | 0, num2 & 4294967295];
27878
27878
  }
27879
27879
  }
27880
27880
  });
@@ -28859,7 +28859,7 @@ var require_asn1 = __commonJS({
28859
28859
  }
28860
28860
  return bytes.getSignedInt(n);
28861
28861
  };
28862
- asn1.validate = function(obj, v2, capture, errors) {
28862
+ asn1.validate = function(obj, v2, capture2, errors) {
28863
28863
  var rval = false;
28864
28864
  if ((obj.tagClass === v2.tagClass || typeof v2.tagClass === "undefined") && (obj.type === v2.type || typeof v2.type === "undefined")) {
28865
28865
  if (obj.constructed === v2.constructed || typeof v2.constructed === "undefined") {
@@ -28892,7 +28892,7 @@ var require_asn1 = __commonJS({
28892
28892
  break;
28893
28893
  }
28894
28894
  }
28895
- var childRval = asn1.validate(objChild, schemaItem, capture, errors);
28895
+ var childRval = asn1.validate(objChild, schemaItem, capture2, errors);
28896
28896
  if (childRval) {
28897
28897
  ++j2;
28898
28898
  rval = true;
@@ -28904,20 +28904,20 @@ var require_asn1 = __commonJS({
28904
28904
  }
28905
28905
  }
28906
28906
  }
28907
- if (rval && capture) {
28907
+ if (rval && capture2) {
28908
28908
  if (v2.capture) {
28909
- capture[v2.capture] = obj.value;
28909
+ capture2[v2.capture] = obj.value;
28910
28910
  }
28911
28911
  if (v2.captureAsn1) {
28912
- capture[v2.captureAsn1] = obj;
28912
+ capture2[v2.captureAsn1] = obj;
28913
28913
  }
28914
28914
  if (v2.captureBitStringContents && "bitStringContents" in obj) {
28915
- capture[v2.captureBitStringContents] = obj.bitStringContents;
28915
+ capture2[v2.captureBitStringContents] = obj.bitStringContents;
28916
28916
  }
28917
28917
  if (v2.captureBitStringValue && "bitStringContents" in obj) {
28918
28918
  var value;
28919
28919
  if (obj.bitStringContents.length < 2) {
28920
- capture[v2.captureBitStringValue] = "";
28920
+ capture2[v2.captureBitStringValue] = "";
28921
28921
  } else {
28922
28922
  var unused = obj.bitStringContents.charCodeAt(0);
28923
28923
  if (unused !== 0) {
@@ -28925,7 +28925,7 @@ var require_asn1 = __commonJS({
28925
28925
  "captureBitStringValue only supported for zero unused bits"
28926
28926
  );
28927
28927
  }
28928
- capture[v2.captureBitStringValue] = obj.bitStringContents.slice(1);
28928
+ capture2[v2.captureBitStringValue] = obj.bitStringContents.slice(1);
28929
28929
  }
28930
28930
  }
28931
28931
  }
@@ -32653,9 +32653,9 @@ var require_prime = __commonJS({
32653
32653
  return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);
32654
32654
  }
32655
32655
  function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {
32656
- var num = generateRandom(bits, rng);
32656
+ var num2 = generateRandom(bits, rng);
32657
32657
  var deltaIdx = 0;
32658
- var mrTests = getMillerRabinTests(num.bitLength());
32658
+ var mrTests = getMillerRabinTests(num2.bitLength());
32659
32659
  if ("millerRabinTests" in options) {
32660
32660
  mrTests = options.millerRabinTests;
32661
32661
  }
@@ -32663,28 +32663,28 @@ var require_prime = __commonJS({
32663
32663
  if ("maxBlockTime" in options) {
32664
32664
  maxBlockTime = options.maxBlockTime;
32665
32665
  }
32666
- _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);
32666
+ _primeinc(num2, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);
32667
32667
  }
32668
- function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {
32668
+ function _primeinc(num2, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {
32669
32669
  var start = +/* @__PURE__ */ new Date();
32670
32670
  do {
32671
- if (num.bitLength() > bits) {
32672
- num = generateRandom(bits, rng);
32671
+ if (num2.bitLength() > bits) {
32672
+ num2 = generateRandom(bits, rng);
32673
32673
  }
32674
- if (num.isProbablePrime(mrTests)) {
32675
- return callback(null, num);
32674
+ if (num2.isProbablePrime(mrTests)) {
32675
+ return callback(null, num2);
32676
32676
  }
32677
- num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
32677
+ num2.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
32678
32678
  } while (maxBlockTime < 0 || +/* @__PURE__ */ new Date() - start < maxBlockTime);
32679
32679
  forge2.util.setImmediate(function() {
32680
- _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);
32680
+ _primeinc(num2, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);
32681
32681
  });
32682
32682
  }
32683
32683
  function primeincFindPrimeWithWorkers(bits, rng, options, callback) {
32684
32684
  if (typeof Worker === "undefined") {
32685
32685
  return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);
32686
32686
  }
32687
- var num = generateRandom(bits, rng);
32687
+ var num2 = generateRandom(bits, rng);
32688
32688
  var numWorkers = options.workers;
32689
32689
  var workLoad = options.workLoad || 100;
32690
32690
  var range = workLoad * 30 / 8;
@@ -32723,26 +32723,26 @@ var require_prime = __commonJS({
32723
32723
  found = true;
32724
32724
  return callback(null, new BigInteger(data.prime, 16));
32725
32725
  }
32726
- if (num.bitLength() > bits) {
32727
- num = generateRandom(bits, rng);
32726
+ if (num2.bitLength() > bits) {
32727
+ num2 = generateRandom(bits, rng);
32728
32728
  }
32729
- var hex = num.toString(16);
32729
+ var hex = num2.toString(16);
32730
32730
  e.target.postMessage({
32731
32731
  hex,
32732
32732
  workLoad
32733
32733
  });
32734
- num.dAddOffset(range, 0);
32734
+ num2.dAddOffset(range, 0);
32735
32735
  }
32736
32736
  }
32737
32737
  }
32738
32738
  function generateRandom(bits, rng) {
32739
- var num = new BigInteger(bits, rng);
32739
+ var num2 = new BigInteger(bits, rng);
32740
32740
  var bits1 = bits - 1;
32741
- if (!num.testBit(bits1)) {
32742
- num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);
32741
+ if (!num2.testBit(bits1)) {
32742
+ num2.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num2);
32743
32743
  }
32744
- num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);
32745
- return num;
32744
+ num2.dAddOffset(31 - num2.mod(THIRTY).byteValue(), 0);
32745
+ return num2;
32746
32746
  }
32747
32747
  function getMillerRabinTests(bits) {
32748
32748
  if (bits <= 100) return 27;
@@ -33462,16 +33462,16 @@ var require_rsa = __commonJS({
33462
33462
  var obj = asn1.fromDer(d2, {
33463
33463
  parseAllBytes: options._parseAllDigestBytes
33464
33464
  });
33465
- var capture = {};
33465
+ var capture2 = {};
33466
33466
  var errors = [];
33467
- if (!asn1.validate(obj, digestInfoValidator, capture, errors) || obj.value.length !== 2) {
33467
+ if (!asn1.validate(obj, digestInfoValidator, capture2, errors) || obj.value.length !== 2) {
33468
33468
  var error = new Error(
33469
33469
  "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value."
33470
33470
  );
33471
33471
  error.errors = errors;
33472
33472
  throw error;
33473
33473
  }
33474
- var oid = asn1.derToOid(capture.algorithmIdentifier);
33474
+ var oid = asn1.derToOid(capture2.algorithmIdentifier);
33475
33475
  if (!(oid === forge2.oids.md2 || oid === forge2.oids.md5 || oid === forge2.oids.sha1 || oid === forge2.oids.sha224 || oid === forge2.oids.sha256 || oid === forge2.oids.sha384 || oid === forge2.oids.sha512 || oid === forge2.oids["sha512-224"] || oid === forge2.oids["sha512-256"])) {
33476
33476
  var error = new Error(
33477
33477
  "Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier."
@@ -33480,13 +33480,13 @@ var require_rsa = __commonJS({
33480
33480
  throw error;
33481
33481
  }
33482
33482
  if (oid === forge2.oids.md2 || oid === forge2.oids.md5) {
33483
- if (!("parameters" in capture)) {
33483
+ if (!("parameters" in capture2)) {
33484
33484
  throw new Error(
33485
33485
  "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters."
33486
33486
  );
33487
33487
  }
33488
33488
  }
33489
- return digest2 === capture.digest;
33489
+ return digest2 === capture2.digest;
33490
33490
  }
33491
33491
  };
33492
33492
  } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) {
@@ -33585,27 +33585,27 @@ var require_rsa = __commonJS({
33585
33585
  ]);
33586
33586
  };
33587
33587
  pki.privateKeyFromAsn1 = function(obj) {
33588
- var capture = {};
33588
+ var capture2 = {};
33589
33589
  var errors = [];
33590
- if (asn1.validate(obj, privateKeyValidator, capture, errors)) {
33591
- obj = asn1.fromDer(forge2.util.createBuffer(capture.privateKey));
33590
+ if (asn1.validate(obj, privateKeyValidator, capture2, errors)) {
33591
+ obj = asn1.fromDer(forge2.util.createBuffer(capture2.privateKey));
33592
33592
  }
33593
- capture = {};
33593
+ capture2 = {};
33594
33594
  errors = [];
33595
- if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) {
33595
+ if (!asn1.validate(obj, rsaPrivateKeyValidator, capture2, errors)) {
33596
33596
  var error = new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");
33597
33597
  error.errors = errors;
33598
33598
  throw error;
33599
33599
  }
33600
33600
  var n, e, d, p2, q2, dP, dQ, qInv;
33601
- n = forge2.util.createBuffer(capture.privateKeyModulus).toHex();
33602
- e = forge2.util.createBuffer(capture.privateKeyPublicExponent).toHex();
33603
- d = forge2.util.createBuffer(capture.privateKeyPrivateExponent).toHex();
33604
- p2 = forge2.util.createBuffer(capture.privateKeyPrime1).toHex();
33605
- q2 = forge2.util.createBuffer(capture.privateKeyPrime2).toHex();
33606
- dP = forge2.util.createBuffer(capture.privateKeyExponent1).toHex();
33607
- dQ = forge2.util.createBuffer(capture.privateKeyExponent2).toHex();
33608
- qInv = forge2.util.createBuffer(capture.privateKeyCoefficient).toHex();
33601
+ n = forge2.util.createBuffer(capture2.privateKeyModulus).toHex();
33602
+ e = forge2.util.createBuffer(capture2.privateKeyPublicExponent).toHex();
33603
+ d = forge2.util.createBuffer(capture2.privateKeyPrivateExponent).toHex();
33604
+ p2 = forge2.util.createBuffer(capture2.privateKeyPrime1).toHex();
33605
+ q2 = forge2.util.createBuffer(capture2.privateKeyPrime2).toHex();
33606
+ dP = forge2.util.createBuffer(capture2.privateKeyExponent1).toHex();
33607
+ dQ = forge2.util.createBuffer(capture2.privateKeyExponent2).toHex();
33608
+ qInv = forge2.util.createBuffer(capture2.privateKeyCoefficient).toHex();
33609
33609
  return pki.setRsaPrivateKey(
33610
33610
  new BigInteger(n, 16),
33611
33611
  new BigInteger(e, 16),
@@ -33685,25 +33685,25 @@ var require_rsa = __commonJS({
33685
33685
  ]);
33686
33686
  };
33687
33687
  pki.publicKeyFromAsn1 = function(obj) {
33688
- var capture = {};
33688
+ var capture2 = {};
33689
33689
  var errors = [];
33690
- if (asn1.validate(obj, publicKeyValidator, capture, errors)) {
33691
- var oid = asn1.derToOid(capture.publicKeyOid);
33690
+ if (asn1.validate(obj, publicKeyValidator, capture2, errors)) {
33691
+ var oid = asn1.derToOid(capture2.publicKeyOid);
33692
33692
  if (oid !== pki.oids.rsaEncryption) {
33693
33693
  var error = new Error("Cannot read public key. Unknown OID.");
33694
33694
  error.oid = oid;
33695
33695
  throw error;
33696
33696
  }
33697
- obj = capture.rsaPublicKey;
33697
+ obj = capture2.rsaPublicKey;
33698
33698
  }
33699
33699
  errors = [];
33700
- if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) {
33700
+ if (!asn1.validate(obj, rsaPublicKeyValidator, capture2, errors)) {
33701
33701
  var error = new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");
33702
33702
  error.errors = errors;
33703
33703
  throw error;
33704
33704
  }
33705
- var n = forge2.util.createBuffer(capture.publicKeyModulus).toHex();
33706
- var e = forge2.util.createBuffer(capture.publicKeyExponent).toHex();
33705
+ var n = forge2.util.createBuffer(capture2.publicKeyModulus).toHex();
33706
+ var e = forge2.util.createBuffer(capture2.publicKeyExponent).toHex();
33707
33707
  return pki.setRsaPublicKey(
33708
33708
  new BigInteger(n, 16),
33709
33709
  new BigInteger(e, 16)
@@ -33852,11 +33852,11 @@ var require_rsa = __commonJS({
33852
33852
  }
33853
33853
  generate();
33854
33854
  function generate() {
33855
- getPrime(state.pBits, function(err2, num) {
33855
+ getPrime(state.pBits, function(err2, num2) {
33856
33856
  if (err2) {
33857
33857
  return callback(err2);
33858
33858
  }
33859
- state.p = num;
33859
+ state.p = num2;
33860
33860
  if (state.q !== null) {
33861
33861
  return finish(err2, state.q);
33862
33862
  }
@@ -33866,11 +33866,11 @@ var require_rsa = __commonJS({
33866
33866
  function getPrime(bits, callback2) {
33867
33867
  forge2.prime.generateProbablePrime(bits, opts, callback2);
33868
33868
  }
33869
- function finish(err2, num) {
33869
+ function finish(err2, num2) {
33870
33870
  if (err2) {
33871
33871
  return callback(err2);
33872
33872
  }
33873
- state.q = num;
33873
+ state.q = num2;
33874
33874
  if (state.p.compareTo(state.q) < 0) {
33875
33875
  var tmp = state.p;
33876
33876
  state.p = state.q;
@@ -34266,16 +34266,16 @@ var require_pbe = __commonJS({
34266
34266
  };
34267
34267
  pki.decryptPrivateKeyInfo = function(obj, password) {
34268
34268
  var rval = null;
34269
- var capture = {};
34269
+ var capture2 = {};
34270
34270
  var errors = [];
34271
- if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {
34271
+ if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture2, errors)) {
34272
34272
  var error = new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");
34273
34273
  error.errors = errors;
34274
34274
  throw error;
34275
34275
  }
34276
- var oid = asn1.derToOid(capture.encryptionOid);
34277
- var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password);
34278
- var encrypted = forge2.util.createBuffer(capture.encryptedData);
34276
+ var oid = asn1.derToOid(capture2.encryptionOid);
34277
+ var cipher = pki.pbe.getCipher(oid, capture2.encryptionParams, password);
34278
+ var encrypted = forge2.util.createBuffer(capture2.encryptedData);
34279
34279
  cipher.update(encrypted);
34280
34280
  if (cipher.finish()) {
34281
34281
  rval = asn1.fromDer(cipher.output);
@@ -34530,21 +34530,21 @@ var require_pbe = __commonJS({
34530
34530
  }
34531
34531
  };
34532
34532
  pki.pbe.getCipherForPBES2 = function(oid, params, password) {
34533
- var capture = {};
34533
+ var capture2 = {};
34534
34534
  var errors = [];
34535
- if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) {
34535
+ if (!asn1.validate(params, PBES2AlgorithmsValidator, capture2, errors)) {
34536
34536
  var error = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");
34537
34537
  error.errors = errors;
34538
34538
  throw error;
34539
34539
  }
34540
- oid = asn1.derToOid(capture.kdfOid);
34540
+ oid = asn1.derToOid(capture2.kdfOid);
34541
34541
  if (oid !== pki.oids["pkcs5PBKDF2"]) {
34542
34542
  var error = new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");
34543
34543
  error.oid = oid;
34544
34544
  error.supportedOids = ["pkcs5PBKDF2"];
34545
34545
  throw error;
34546
34546
  }
34547
- oid = asn1.derToOid(capture.encOid);
34547
+ oid = asn1.derToOid(capture2.encOid);
34548
34548
  if (oid !== pki.oids["aes128-CBC"] && oid !== pki.oids["aes192-CBC"] && oid !== pki.oids["aes256-CBC"] && oid !== pki.oids["des-EDE3-CBC"] && oid !== pki.oids["desCBC"]) {
34549
34549
  var error = new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");
34550
34550
  error.oid = oid;
@@ -34557,8 +34557,8 @@ var require_pbe = __commonJS({
34557
34557
  ];
34558
34558
  throw error;
34559
34559
  }
34560
- var salt = capture.kdfSalt;
34561
- var count = forge2.util.createBuffer(capture.kdfIterationCount);
34560
+ var salt = capture2.kdfSalt;
34561
+ var count = forge2.util.createBuffer(capture2.kdfIterationCount);
34562
34562
  count = count.getInt(count.length() << 3);
34563
34563
  var dkLen;
34564
34564
  var cipherFn;
@@ -34584,23 +34584,23 @@ var require_pbe = __commonJS({
34584
34584
  cipherFn = forge2.des.createDecryptionCipher;
34585
34585
  break;
34586
34586
  }
34587
- var md = prfOidToMessageDigest(capture.prfOid);
34587
+ var md = prfOidToMessageDigest(capture2.prfOid);
34588
34588
  var dk = forge2.pkcs5.pbkdf2(password, salt, count, dkLen, md);
34589
- var iv = capture.encIv;
34589
+ var iv = capture2.encIv;
34590
34590
  var cipher = cipherFn(dk);
34591
34591
  cipher.start(iv);
34592
34592
  return cipher;
34593
34593
  };
34594
34594
  pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) {
34595
- var capture = {};
34595
+ var capture2 = {};
34596
34596
  var errors = [];
34597
- if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) {
34597
+ if (!asn1.validate(params, pkcs12PbeParamsValidator, capture2, errors)) {
34598
34598
  var error = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");
34599
34599
  error.errors = errors;
34600
34600
  throw error;
34601
34601
  }
34602
- var salt = forge2.util.createBuffer(capture.salt);
34603
- var count = forge2.util.createBuffer(capture.iterations);
34602
+ var salt = forge2.util.createBuffer(capture2.salt);
34603
+ var count = forge2.util.createBuffer(capture2.iterations);
34604
34604
  count = count.getInt(count.length() << 3);
34605
34605
  var dkLen, dIvLen, cipherFn;
34606
34606
  switch (oid) {
@@ -34623,7 +34623,7 @@ var require_pbe = __commonJS({
34623
34623
  error.oid = oid;
34624
34624
  throw error;
34625
34625
  }
34626
- var md = prfOidToMessageDigest(capture.prfOid);
34626
+ var md = prfOidToMessageDigest(capture2.prfOid);
34627
34627
  var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);
34628
34628
  md.start();
34629
34629
  var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);
@@ -35689,25 +35689,25 @@ var require_x509 = __commonJS({
35689
35689
  saltLength: 20
35690
35690
  };
35691
35691
  }
35692
- var capture = {};
35692
+ var capture2 = {};
35693
35693
  var errors = [];
35694
- if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {
35694
+ if (!asn1.validate(obj, rsassaPssParameterValidator, capture2, errors)) {
35695
35695
  var error = new Error("Cannot read RSASSA-PSS parameter block.");
35696
35696
  error.errors = errors;
35697
35697
  throw error;
35698
35698
  }
35699
- if (capture.hashOid !== void 0) {
35699
+ if (capture2.hashOid !== void 0) {
35700
35700
  params.hash = params.hash || {};
35701
- params.hash.algorithmOid = asn1.derToOid(capture.hashOid);
35701
+ params.hash.algorithmOid = asn1.derToOid(capture2.hashOid);
35702
35702
  }
35703
- if (capture.maskGenOid !== void 0) {
35703
+ if (capture2.maskGenOid !== void 0) {
35704
35704
  params.mgf = params.mgf || {};
35705
- params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);
35705
+ params.mgf.algorithmOid = asn1.derToOid(capture2.maskGenOid);
35706
35706
  params.mgf.hash = params.mgf.hash || {};
35707
- params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);
35707
+ params.mgf.hash.algorithmOid = asn1.derToOid(capture2.maskGenHashOid);
35708
35708
  }
35709
- if (capture.saltLength !== void 0) {
35710
- params.saltLength = capture.saltLength.charCodeAt(0);
35709
+ if (capture2.saltLength !== void 0) {
35710
+ params.saltLength = capture2.saltLength.charCodeAt(0);
35711
35711
  }
35712
35712
  return params;
35713
35713
  };
@@ -36040,49 +36040,49 @@ var require_x509 = __commonJS({
36040
36040
  return cert;
36041
36041
  };
36042
36042
  pki.certificateFromAsn1 = function(obj, computeHash) {
36043
- var capture = {};
36043
+ var capture2 = {};
36044
36044
  var errors = [];
36045
- if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) {
36045
+ if (!asn1.validate(obj, x509CertificateValidator, capture2, errors)) {
36046
36046
  var error = new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");
36047
36047
  error.errors = errors;
36048
36048
  throw error;
36049
36049
  }
36050
- var oid = asn1.derToOid(capture.publicKeyOid);
36050
+ var oid = asn1.derToOid(capture2.publicKeyOid);
36051
36051
  if (oid !== pki.oids.rsaEncryption) {
36052
36052
  throw new Error("Cannot read public key. OID is not RSA.");
36053
36053
  }
36054
36054
  var cert = pki.createCertificate();
36055
- cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0;
36056
- var serial = forge2.util.createBuffer(capture.certSerialNumber);
36055
+ cert.version = capture2.certVersion ? capture2.certVersion.charCodeAt(0) : 0;
36056
+ var serial = forge2.util.createBuffer(capture2.certSerialNumber);
36057
36057
  cert.serialNumber = serial.toHex();
36058
- cert.signatureOid = forge2.asn1.derToOid(capture.certSignatureOid);
36058
+ cert.signatureOid = forge2.asn1.derToOid(capture2.certSignatureOid);
36059
36059
  cert.signatureParameters = _readSignatureParameters(
36060
36060
  cert.signatureOid,
36061
- capture.certSignatureParams,
36061
+ capture2.certSignatureParams,
36062
36062
  true
36063
36063
  );
36064
- cert.siginfo.algorithmOid = forge2.asn1.derToOid(capture.certinfoSignatureOid);
36064
+ cert.siginfo.algorithmOid = forge2.asn1.derToOid(capture2.certinfoSignatureOid);
36065
36065
  cert.siginfo.parameters = _readSignatureParameters(
36066
36066
  cert.siginfo.algorithmOid,
36067
- capture.certinfoSignatureParams,
36067
+ capture2.certinfoSignatureParams,
36068
36068
  false
36069
36069
  );
36070
- cert.signature = capture.certSignature;
36070
+ cert.signature = capture2.certSignature;
36071
36071
  var validity = [];
36072
- if (capture.certValidity1UTCTime !== void 0) {
36073
- validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));
36072
+ if (capture2.certValidity1UTCTime !== void 0) {
36073
+ validity.push(asn1.utcTimeToDate(capture2.certValidity1UTCTime));
36074
36074
  }
36075
- if (capture.certValidity2GeneralizedTime !== void 0) {
36075
+ if (capture2.certValidity2GeneralizedTime !== void 0) {
36076
36076
  validity.push(asn1.generalizedTimeToDate(
36077
- capture.certValidity2GeneralizedTime
36077
+ capture2.certValidity2GeneralizedTime
36078
36078
  ));
36079
36079
  }
36080
- if (capture.certValidity3UTCTime !== void 0) {
36081
- validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));
36080
+ if (capture2.certValidity3UTCTime !== void 0) {
36081
+ validity.push(asn1.utcTimeToDate(capture2.certValidity3UTCTime));
36082
36082
  }
36083
- if (capture.certValidity4GeneralizedTime !== void 0) {
36083
+ if (capture2.certValidity4GeneralizedTime !== void 0) {
36084
36084
  validity.push(asn1.generalizedTimeToDate(
36085
- capture.certValidity4GeneralizedTime
36085
+ capture2.certValidity4GeneralizedTime
36086
36086
  ));
36087
36087
  }
36088
36088
  if (validity.length > 2) {
@@ -36093,7 +36093,7 @@ var require_x509 = __commonJS({
36093
36093
  }
36094
36094
  cert.validity.notBefore = validity[0];
36095
36095
  cert.validity.notAfter = validity[1];
36096
- cert.tbsCertificate = capture.tbsCertificate;
36096
+ cert.tbsCertificate = capture2.tbsCertificate;
36097
36097
  if (computeHash) {
36098
36098
  cert.md = _createSignatureDigest({
36099
36099
  signatureOid: cert.signatureOid,
@@ -36103,7 +36103,7 @@ var require_x509 = __commonJS({
36103
36103
  cert.md.update(bytes.getBytes());
36104
36104
  }
36105
36105
  var imd = forge2.md.sha1.create();
36106
- var ibytes = asn1.toDer(capture.certIssuer);
36106
+ var ibytes = asn1.toDer(capture2.certIssuer);
36107
36107
  imd.update(ibytes.getBytes());
36108
36108
  cert.issuer.getField = function(sn2) {
36109
36109
  return _getAttribute(cert.issuer, sn2);
@@ -36112,13 +36112,13 @@ var require_x509 = __commonJS({
36112
36112
  _fillMissingFields([attr]);
36113
36113
  cert.issuer.attributes.push(attr);
36114
36114
  };
36115
- cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer);
36116
- if (capture.certIssuerUniqueId) {
36117
- cert.issuer.uniqueId = capture.certIssuerUniqueId;
36115
+ cert.issuer.attributes = pki.RDNAttributesAsArray(capture2.certIssuer);
36116
+ if (capture2.certIssuerUniqueId) {
36117
+ cert.issuer.uniqueId = capture2.certIssuerUniqueId;
36118
36118
  }
36119
36119
  cert.issuer.hash = imd.digest().toHex();
36120
36120
  var smd = forge2.md.sha1.create();
36121
- var sbytes = asn1.toDer(capture.certSubject);
36121
+ var sbytes = asn1.toDer(capture2.certSubject);
36122
36122
  smd.update(sbytes.getBytes());
36123
36123
  cert.subject.getField = function(sn2) {
36124
36124
  return _getAttribute(cert.subject, sn2);
@@ -36127,17 +36127,17 @@ var require_x509 = __commonJS({
36127
36127
  _fillMissingFields([attr]);
36128
36128
  cert.subject.attributes.push(attr);
36129
36129
  };
36130
- cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject);
36131
- if (capture.certSubjectUniqueId) {
36132
- cert.subject.uniqueId = capture.certSubjectUniqueId;
36130
+ cert.subject.attributes = pki.RDNAttributesAsArray(capture2.certSubject);
36131
+ if (capture2.certSubjectUniqueId) {
36132
+ cert.subject.uniqueId = capture2.certSubjectUniqueId;
36133
36133
  }
36134
36134
  cert.subject.hash = smd.digest().toHex();
36135
- if (capture.certExtensions) {
36136
- cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);
36135
+ if (capture2.certExtensions) {
36136
+ cert.extensions = pki.certificateExtensionsFromAsn1(capture2.certExtensions);
36137
36137
  } else {
36138
36138
  cert.extensions = [];
36139
36139
  }
36140
- cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
36140
+ cert.publicKey = pki.publicKeyFromAsn1(capture2.subjectPublicKeyInfo);
36141
36141
  return cert;
36142
36142
  };
36143
36143
  pki.certificateExtensionsFromAsn1 = function(exts) {
@@ -36257,33 +36257,33 @@ var require_x509 = __commonJS({
36257
36257
  return e;
36258
36258
  };
36259
36259
  pki.certificationRequestFromAsn1 = function(obj, computeHash) {
36260
- var capture = {};
36260
+ var capture2 = {};
36261
36261
  var errors = [];
36262
- if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) {
36262
+ if (!asn1.validate(obj, certificationRequestValidator, capture2, errors)) {
36263
36263
  var error = new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");
36264
36264
  error.errors = errors;
36265
36265
  throw error;
36266
36266
  }
36267
- var oid = asn1.derToOid(capture.publicKeyOid);
36267
+ var oid = asn1.derToOid(capture2.publicKeyOid);
36268
36268
  if (oid !== pki.oids.rsaEncryption) {
36269
36269
  throw new Error("Cannot read public key. OID is not RSA.");
36270
36270
  }
36271
36271
  var csr = pki.createCertificationRequest();
36272
- csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;
36273
- csr.signatureOid = forge2.asn1.derToOid(capture.csrSignatureOid);
36272
+ csr.version = capture2.csrVersion ? capture2.csrVersion.charCodeAt(0) : 0;
36273
+ csr.signatureOid = forge2.asn1.derToOid(capture2.csrSignatureOid);
36274
36274
  csr.signatureParameters = _readSignatureParameters(
36275
36275
  csr.signatureOid,
36276
- capture.csrSignatureParams,
36276
+ capture2.csrSignatureParams,
36277
36277
  true
36278
36278
  );
36279
- csr.siginfo.algorithmOid = forge2.asn1.derToOid(capture.csrSignatureOid);
36279
+ csr.siginfo.algorithmOid = forge2.asn1.derToOid(capture2.csrSignatureOid);
36280
36280
  csr.siginfo.parameters = _readSignatureParameters(
36281
36281
  csr.siginfo.algorithmOid,
36282
- capture.csrSignatureParams,
36282
+ capture2.csrSignatureParams,
36283
36283
  false
36284
36284
  );
36285
- csr.signature = capture.csrSignature;
36286
- csr.certificationRequestInfo = capture.certificationRequestInfo;
36285
+ csr.signature = capture2.csrSignature;
36286
+ csr.certificationRequestInfo = capture2.certificationRequestInfo;
36287
36287
  if (computeHash) {
36288
36288
  csr.md = _createSignatureDigest({
36289
36289
  signatureOid: csr.signatureOid,
@@ -36301,11 +36301,11 @@ var require_x509 = __commonJS({
36301
36301
  csr.subject.attributes.push(attr);
36302
36302
  };
36303
36303
  csr.subject.attributes = pki.RDNAttributesAsArray(
36304
- capture.certificationRequestInfoSubject,
36304
+ capture2.certificationRequestInfoSubject,
36305
36305
  smd
36306
36306
  );
36307
36307
  csr.subject.hash = smd.digest().toHex();
36308
- csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
36308
+ csr.publicKey = pki.publicKeyFromAsn1(capture2.subjectPublicKeyInfo);
36309
36309
  csr.getAttribute = function(sn2) {
36310
36310
  return _getAttribute(csr, sn2);
36311
36311
  };
@@ -36314,7 +36314,7 @@ var require_x509 = __commonJS({
36314
36314
  csr.attributes.push(attr);
36315
36315
  };
36316
36316
  csr.attributes = pki.CRIAttributesAsArray(
36317
- capture.certificationRequestInfoAttributes || []
36317
+ capture2.certificationRequestInfoAttributes || []
36318
36318
  );
36319
36319
  return csr;
36320
36320
  };
@@ -37544,15 +37544,15 @@ var require_pkcs12 = __commonJS({
37544
37544
  } else if (strict === void 0) {
37545
37545
  strict = true;
37546
37546
  }
37547
- var capture = {};
37547
+ var capture2 = {};
37548
37548
  var errors = [];
37549
- if (!asn1.validate(obj, pfxValidator, capture, errors)) {
37549
+ if (!asn1.validate(obj, pfxValidator, capture2, errors)) {
37550
37550
  var error = new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");
37551
37551
  error.errors = error;
37552
37552
  throw error;
37553
37553
  }
37554
37554
  var pfx = {
37555
- version: capture.version.charCodeAt(0),
37555
+ version: capture2.version.charCodeAt(0),
37556
37556
  safeContents: [],
37557
37557
  /**
37558
37558
  * Gets bags with matching attributes.
@@ -37638,25 +37638,25 @@ var require_pkcs12 = __commonJS({
37638
37638
  );
37639
37639
  }
37640
37640
  };
37641
- if (capture.version.charCodeAt(0) !== 3) {
37641
+ if (capture2.version.charCodeAt(0) !== 3) {
37642
37642
  var error = new Error("PKCS#12 PFX of version other than 3 not supported.");
37643
- error.version = capture.version.charCodeAt(0);
37643
+ error.version = capture2.version.charCodeAt(0);
37644
37644
  throw error;
37645
37645
  }
37646
- if (asn1.derToOid(capture.contentType) !== pki.oids.data) {
37646
+ if (asn1.derToOid(capture2.contentType) !== pki.oids.data) {
37647
37647
  var error = new Error("Only PKCS#12 PFX in password integrity mode supported.");
37648
- error.oid = asn1.derToOid(capture.contentType);
37648
+ error.oid = asn1.derToOid(capture2.contentType);
37649
37649
  throw error;
37650
37650
  }
37651
- var data = capture.content.value[0];
37651
+ var data = capture2.content.value[0];
37652
37652
  if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) {
37653
37653
  throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.");
37654
37654
  }
37655
37655
  data = _decodePkcs7Data(data);
37656
- if (capture.mac) {
37656
+ if (capture2.mac) {
37657
37657
  var md = null;
37658
37658
  var macKeyBytes = 0;
37659
- var macAlgorithm = asn1.derToOid(capture.macAlgorithm);
37659
+ var macAlgorithm = asn1.derToOid(capture2.macAlgorithm);
37660
37660
  switch (macAlgorithm) {
37661
37661
  case pki.oids.sha1:
37662
37662
  md = forge2.md.sha1.create();
@@ -37682,8 +37682,8 @@ var require_pkcs12 = __commonJS({
37682
37682
  if (md === null) {
37683
37683
  throw new Error("PKCS#12 uses unsupported MAC algorithm: " + macAlgorithm);
37684
37684
  }
37685
- var macSalt = new forge2.util.ByteBuffer(capture.macSalt);
37686
- var macIterations = "macIterations" in capture ? parseInt(forge2.util.bytesToHex(capture.macIterations), 16) : 1;
37685
+ var macSalt = new forge2.util.ByteBuffer(capture2.macSalt);
37686
+ var macIterations = "macIterations" in capture2 ? parseInt(forge2.util.bytesToHex(capture2.macIterations), 16) : 1;
37687
37687
  var macKey = p12.generateKey(
37688
37688
  password,
37689
37689
  macSalt,
@@ -37696,7 +37696,7 @@ var require_pkcs12 = __commonJS({
37696
37696
  mac.start(md, macKey);
37697
37697
  mac.update(data.value);
37698
37698
  var macValue = mac.getMac();
37699
- if (macValue.getBytes() !== capture.macDigest) {
37699
+ if (macValue.getBytes() !== capture2.macDigest) {
37700
37700
  throw new Error("PKCS#12 MAC could not be verified. Invalid password?");
37701
37701
  }
37702
37702
  } else if (Array.isArray(obj.value) && obj.value.length > 2) {
@@ -37723,9 +37723,9 @@ var require_pkcs12 = __commonJS({
37723
37723
  }
37724
37724
  for (var i = 0; i < authSafe.value.length; i++) {
37725
37725
  var contentInfo = authSafe.value[i];
37726
- var capture = {};
37726
+ var capture2 = {};
37727
37727
  var errors = [];
37728
- if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) {
37728
+ if (!asn1.validate(contentInfo, contentInfoValidator, capture2, errors)) {
37729
37729
  var error = new Error("Cannot read ContentInfo.");
37730
37730
  error.errors = errors;
37731
37731
  throw error;
@@ -37734,8 +37734,8 @@ var require_pkcs12 = __commonJS({
37734
37734
  encrypted: false
37735
37735
  };
37736
37736
  var safeContents = null;
37737
- var data = capture.content.value[0];
37738
- switch (asn1.derToOid(capture.contentType)) {
37737
+ var data = capture2.content.value[0];
37738
+ switch (asn1.derToOid(capture2.contentType)) {
37739
37739
  case pki.oids.data:
37740
37740
  if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) {
37741
37741
  throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING.");
@@ -37748,7 +37748,7 @@ var require_pkcs12 = __commonJS({
37748
37748
  break;
37749
37749
  default:
37750
37750
  var error = new Error("Unsupported PKCS#12 contentType.");
37751
- error.contentType = asn1.derToOid(capture.contentType);
37751
+ error.contentType = asn1.derToOid(capture2.contentType);
37752
37752
  throw error;
37753
37753
  }
37754
37754
  obj.safeBags = _decodeSafeContents(safeContents, strict, password);
@@ -37756,19 +37756,19 @@ var require_pkcs12 = __commonJS({
37756
37756
  }
37757
37757
  }
37758
37758
  function _decryptSafeContents(data, password) {
37759
- var capture = {};
37759
+ var capture2 = {};
37760
37760
  var errors = [];
37761
37761
  if (!asn1.validate(
37762
37762
  data,
37763
37763
  forge2.pkcs7.asn1.encryptedDataValidator,
37764
- capture,
37764
+ capture2,
37765
37765
  errors
37766
37766
  )) {
37767
37767
  var error = new Error("Cannot read EncryptedContentInfo.");
37768
37768
  error.errors = errors;
37769
37769
  throw error;
37770
37770
  }
37771
- var oid = asn1.derToOid(capture.contentType);
37771
+ var oid = asn1.derToOid(capture2.contentType);
37772
37772
  if (oid !== pki.oids.data) {
37773
37773
  var error = new Error(
37774
37774
  "PKCS#12 EncryptedContentInfo ContentType is not Data."
@@ -37776,9 +37776,9 @@ var require_pkcs12 = __commonJS({
37776
37776
  error.oid = oid;
37777
37777
  throw error;
37778
37778
  }
37779
- oid = asn1.derToOid(capture.encAlgorithm);
37780
- var cipher = pki.pbe.getCipher(oid, capture.encParameter, password);
37781
- var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);
37779
+ oid = asn1.derToOid(capture2.encAlgorithm);
37780
+ var cipher = pki.pbe.getCipher(oid, capture2.encParameter, password);
37781
+ var encryptedContentAsn1 = _decodePkcs7Data(capture2.encryptedContentAsn1);
37782
37782
  var encrypted = forge2.util.createBuffer(encryptedContentAsn1.value);
37783
37783
  cipher.update(encrypted);
37784
37784
  if (!cipher.finish()) {
@@ -37799,20 +37799,20 @@ var require_pkcs12 = __commonJS({
37799
37799
  var res = [];
37800
37800
  for (var i = 0; i < safeContents.value.length; i++) {
37801
37801
  var safeBag = safeContents.value[i];
37802
- var capture = {};
37802
+ var capture2 = {};
37803
37803
  var errors = [];
37804
- if (!asn1.validate(safeBag, safeBagValidator, capture, errors)) {
37804
+ if (!asn1.validate(safeBag, safeBagValidator, capture2, errors)) {
37805
37805
  var error = new Error("Cannot read SafeBag.");
37806
37806
  error.errors = errors;
37807
37807
  throw error;
37808
37808
  }
37809
37809
  var bag = {
37810
- type: asn1.derToOid(capture.bagId),
37811
- attributes: _decodeBagAttributes(capture.bagAttributes)
37810
+ type: asn1.derToOid(capture2.bagId),
37811
+ attributes: _decodeBagAttributes(capture2.bagAttributes)
37812
37812
  };
37813
37813
  res.push(bag);
37814
37814
  var validator, decoder;
37815
- var bagAsn1 = capture.bagValue.value[0];
37815
+ var bagAsn1 = capture2.bagValue.value[0];
37816
37816
  switch (bag.type) {
37817
37817
  case pki.oids.pkcs8ShroudedKeyBag:
37818
37818
  bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password);
@@ -37834,14 +37834,14 @@ var require_pkcs12 = __commonJS({
37834
37834
  case pki.oids.certBag:
37835
37835
  validator = certBagValidator;
37836
37836
  decoder = function() {
37837
- if (asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) {
37837
+ if (asn1.derToOid(capture2.certId) !== pki.oids.x509Certificate) {
37838
37838
  var error2 = new Error(
37839
37839
  "Unsupported certificate type, only X.509 supported."
37840
37840
  );
37841
- error2.oid = asn1.derToOid(capture.certId);
37841
+ error2.oid = asn1.derToOid(capture2.certId);
37842
37842
  throw error2;
37843
37843
  }
37844
- var certAsn1 = asn1.fromDer(capture.cert, strict);
37844
+ var certAsn1 = asn1.fromDer(capture2.cert, strict);
37845
37845
  try {
37846
37846
  bag.cert = pki.certificateFromAsn1(certAsn1, true);
37847
37847
  } catch (e) {
@@ -37855,7 +37855,7 @@ var require_pkcs12 = __commonJS({
37855
37855
  error.oid = bag.type;
37856
37856
  throw error;
37857
37857
  }
37858
- if (validator !== void 0 && !asn1.validate(bagAsn1, validator, capture, errors)) {
37858
+ if (validator !== void 0 && !asn1.validate(bagAsn1, validator, capture2, errors)) {
37859
37859
  var error = new Error("Cannot read PKCS#12 " + validator.name);
37860
37860
  error.errors = errors;
37861
37861
  throw error;
@@ -37868,20 +37868,20 @@ var require_pkcs12 = __commonJS({
37868
37868
  var decodedAttrs = {};
37869
37869
  if (attributes !== void 0) {
37870
37870
  for (var i = 0; i < attributes.length; ++i) {
37871
- var capture = {};
37871
+ var capture2 = {};
37872
37872
  var errors = [];
37873
- if (!asn1.validate(attributes[i], attributeValidator, capture, errors)) {
37873
+ if (!asn1.validate(attributes[i], attributeValidator, capture2, errors)) {
37874
37874
  var error = new Error("Cannot read PKCS#12 BagAttribute.");
37875
37875
  error.errors = errors;
37876
37876
  throw error;
37877
37877
  }
37878
- var oid = asn1.derToOid(capture.oid);
37878
+ var oid = asn1.derToOid(capture2.oid);
37879
37879
  if (pki.oids[oid] === void 0) {
37880
37880
  continue;
37881
37881
  }
37882
37882
  decodedAttrs[pki.oids[oid]] = [];
37883
- for (var j2 = 0; j2 < capture.values.length; ++j2) {
37884
- decodedAttrs[pki.oids[oid]].push(capture.values[j2].value);
37883
+ for (var j2 = 0; j2 < capture2.values.length; ++j2) {
37884
+ decodedAttrs[pki.oids[oid]].push(capture2.values[j2].value);
37885
37885
  }
37886
37886
  }
37887
37887
  }
@@ -39943,20 +39943,20 @@ var require_tls = __commonJS({
39943
39943
  }
39944
39944
  return !c.fail;
39945
39945
  };
39946
- tls4.createSessionCache = function(cache3, capacity) {
39946
+ tls4.createSessionCache = function(cache4, capacity) {
39947
39947
  var rval = null;
39948
- if (cache3 && cache3.getSession && cache3.setSession && cache3.order) {
39949
- rval = cache3;
39948
+ if (cache4 && cache4.getSession && cache4.setSession && cache4.order) {
39949
+ rval = cache4;
39950
39950
  } else {
39951
39951
  rval = {};
39952
- rval.cache = cache3 || {};
39952
+ rval.cache = cache4 || {};
39953
39953
  rval.capacity = Math.max(capacity || 100, 1);
39954
39954
  rval.order = [];
39955
- for (var key2 in cache3) {
39955
+ for (var key2 in cache4) {
39956
39956
  if (rval.order.length <= capacity) {
39957
39957
  rval.order.push(key2);
39958
39958
  } else {
39959
- delete cache3[key2];
39959
+ delete cache4[key2];
39960
39960
  }
39961
39961
  }
39962
39962
  rval.getSession = function(sessionId) {
@@ -40994,20 +40994,20 @@ var require_ed25519 = __commonJS({
40994
40994
  return { publicKey: pk, privateKey: sk };
40995
40995
  };
40996
40996
  ed25519.privateKeyFromAsn1 = function(obj) {
40997
- var capture = {};
40997
+ var capture2 = {};
40998
40998
  var errors = [];
40999
- var valid = forge2.asn1.validate(obj, privateKeyValidator, capture, errors);
40999
+ var valid = forge2.asn1.validate(obj, privateKeyValidator, capture2, errors);
41000
41000
  if (!valid) {
41001
41001
  var error = new Error("Invalid Key.");
41002
41002
  error.errors = errors;
41003
41003
  throw error;
41004
41004
  }
41005
- var oid = forge2.asn1.derToOid(capture.privateKeyOid);
41005
+ var oid = forge2.asn1.derToOid(capture2.privateKeyOid);
41006
41006
  var ed25519Oid = forge2.oids.EdDSA25519;
41007
41007
  if (oid !== ed25519Oid) {
41008
41008
  throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".');
41009
41009
  }
41010
- var privateKey = capture.privateKey;
41010
+ var privateKey = capture2.privateKey;
41011
41011
  var privateKeyBytes = messageToNativeBuffer({
41012
41012
  message: forge2.asn1.fromDer(privateKey).value,
41013
41013
  encoding: "binary"
@@ -41015,20 +41015,20 @@ var require_ed25519 = __commonJS({
41015
41015
  return { privateKeyBytes };
41016
41016
  };
41017
41017
  ed25519.publicKeyFromAsn1 = function(obj) {
41018
- var capture = {};
41018
+ var capture2 = {};
41019
41019
  var errors = [];
41020
- var valid = forge2.asn1.validate(obj, publicKeyValidator, capture, errors);
41020
+ var valid = forge2.asn1.validate(obj, publicKeyValidator, capture2, errors);
41021
41021
  if (!valid) {
41022
41022
  var error = new Error("Invalid Key.");
41023
41023
  error.errors = errors;
41024
41024
  throw error;
41025
41025
  }
41026
- var oid = forge2.asn1.derToOid(capture.publicKeyOid);
41026
+ var oid = forge2.asn1.derToOid(capture2.publicKeyOid);
41027
41027
  var ed25519Oid = forge2.oids.EdDSA25519;
41028
41028
  if (oid !== ed25519Oid) {
41029
41029
  throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".');
41030
41030
  }
41031
- var publicKeyBytes = capture.ed25519PublicKey;
41031
+ var publicKeyBytes = capture2.ed25519PublicKey;
41032
41032
  if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {
41033
41033
  throw new Error("Key length is invalid.");
41034
41034
  }
@@ -41485,31 +41485,31 @@ var require_ed25519 = __commonJS({
41485
41485
  }
41486
41486
  }
41487
41487
  function unpackneg(r, p2) {
41488
- var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();
41488
+ var t = gf(), chk = gf(), num2 = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();
41489
41489
  set25519(r[2], gf1);
41490
41490
  unpack25519(r[1], p2);
41491
- S2(num, r[1]);
41492
- M2(den, num, D);
41493
- Z2(num, num, r[2]);
41491
+ S2(num2, r[1]);
41492
+ M2(den, num2, D);
41493
+ Z2(num2, num2, r[2]);
41494
41494
  A2(den, r[2], den);
41495
41495
  S2(den2, den);
41496
41496
  S2(den4, den2);
41497
41497
  M2(den6, den4, den2);
41498
- M2(t, den6, num);
41498
+ M2(t, den6, num2);
41499
41499
  M2(t, t, den);
41500
41500
  pow2523(t, t);
41501
- M2(t, t, num);
41501
+ M2(t, t, num2);
41502
41502
  M2(t, t, den);
41503
41503
  M2(t, t, den);
41504
41504
  M2(r[0], t, den);
41505
41505
  S2(chk, r[0]);
41506
41506
  M2(chk, chk, den);
41507
- if (neq25519(chk, num)) {
41507
+ if (neq25519(chk, num2)) {
41508
41508
  M2(r[0], r[0], I2);
41509
41509
  }
41510
41510
  S2(chk, r[0]);
41511
41511
  M2(chk, chk, den);
41512
- if (neq25519(chk, num)) {
41512
+ if (neq25519(chk, num2)) {
41513
41513
  return -1;
41514
41514
  }
41515
41515
  if (par25519(r[0]) === p2[31] >> 7) {
@@ -42344,14 +42344,14 @@ var require_pkcs7 = __commonJS({
42344
42344
  return forge2.pem.encode(pemObj, { maxline });
42345
42345
  };
42346
42346
  p7.messageFromAsn1 = function(obj) {
42347
- var capture = {};
42347
+ var capture2 = {};
42348
42348
  var errors = [];
42349
- if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {
42349
+ if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture2, errors)) {
42350
42350
  var error = new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");
42351
42351
  error.errors = errors;
42352
42352
  throw error;
42353
42353
  }
42354
- var contentType = asn1.derToOid(capture.contentType);
42354
+ var contentType = asn1.derToOid(capture2.contentType);
42355
42355
  var msg2;
42356
42356
  switch (contentType) {
42357
42357
  case forge2.pki.oids.envelopedData:
@@ -42366,7 +42366,7 @@ var require_pkcs7 = __commonJS({
42366
42366
  default:
42367
42367
  throw new Error("Cannot read PKCS#7 message. ContentType with OID " + contentType + " is not (yet) supported.");
42368
42368
  }
42369
- msg2.fromAsn1(capture.content.value[0]);
42369
+ msg2.fromAsn1(capture2.content.value[0]);
42370
42370
  return msg2;
42371
42371
  };
42372
42372
  p7.createSignedData = function() {
@@ -42787,8 +42787,8 @@ var require_pkcs7 = __commonJS({
42787
42787
  * @param obj the ASN.1 representation of the EnvelopedData content block.
42788
42788
  */
42789
42789
  fromAsn1: function(obj) {
42790
- var capture = _fromAsn1(msg2, obj, p7.asn1.envelopedDataValidator);
42791
- msg2.recipients = _recipientsFromAsn1(capture.recipientInfos.value);
42790
+ var capture2 = _fromAsn1(msg2, obj, p7.asn1.envelopedDataValidator);
42791
+ msg2.recipients = _recipientsFromAsn1(capture2.recipientInfos.value);
42792
42792
  },
42793
42793
  toAsn1: function() {
42794
42794
  return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
@@ -42977,21 +42977,21 @@ var require_pkcs7 = __commonJS({
42977
42977
  return msg2;
42978
42978
  };
42979
42979
  function _recipientFromAsn1(obj) {
42980
- var capture = {};
42980
+ var capture2 = {};
42981
42981
  var errors = [];
42982
- if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {
42982
+ if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture2, errors)) {
42983
42983
  var error = new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");
42984
42984
  error.errors = errors;
42985
42985
  throw error;
42986
42986
  }
42987
42987
  return {
42988
- version: capture.version.charCodeAt(0),
42989
- issuer: forge2.pki.RDNAttributesAsArray(capture.issuer),
42990
- serialNumber: forge2.util.createBuffer(capture.serial).toHex(),
42988
+ version: capture2.version.charCodeAt(0),
42989
+ issuer: forge2.pki.RDNAttributesAsArray(capture2.issuer),
42990
+ serialNumber: forge2.util.createBuffer(capture2.serial).toHex(),
42991
42991
  encryptedContent: {
42992
- algorithm: asn1.derToOid(capture.encAlgorithm),
42993
- parameter: capture.encParameter ? capture.encParameter.value : void 0,
42994
- content: capture.encKey
42992
+ algorithm: asn1.derToOid(capture2.encAlgorithm),
42993
+ parameter: capture2.encParameter ? capture2.encParameter.value : void 0,
42994
+ content: capture2.encKey
42995
42995
  }
42996
42996
  };
42997
42997
  }
@@ -43220,52 +43220,52 @@ var require_pkcs7 = __commonJS({
43220
43220
  ];
43221
43221
  }
43222
43222
  function _fromAsn1(msg2, obj, validator) {
43223
- var capture = {};
43223
+ var capture2 = {};
43224
43224
  var errors = [];
43225
- if (!asn1.validate(obj, validator, capture, errors)) {
43225
+ if (!asn1.validate(obj, validator, capture2, errors)) {
43226
43226
  var error = new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");
43227
43227
  error.errors = error;
43228
43228
  throw error;
43229
43229
  }
43230
- var contentType = asn1.derToOid(capture.contentType);
43230
+ var contentType = asn1.derToOid(capture2.contentType);
43231
43231
  if (contentType !== forge2.pki.oids.data) {
43232
43232
  throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");
43233
43233
  }
43234
- if (capture.encryptedContent) {
43234
+ if (capture2.encryptedContent) {
43235
43235
  var content = "";
43236
- if (forge2.util.isArray(capture.encryptedContent)) {
43237
- for (var i = 0; i < capture.encryptedContent.length; ++i) {
43238
- if (capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {
43236
+ if (forge2.util.isArray(capture2.encryptedContent)) {
43237
+ for (var i = 0; i < capture2.encryptedContent.length; ++i) {
43238
+ if (capture2.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {
43239
43239
  throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");
43240
43240
  }
43241
- content += capture.encryptedContent[i].value;
43241
+ content += capture2.encryptedContent[i].value;
43242
43242
  }
43243
43243
  } else {
43244
- content = capture.encryptedContent;
43244
+ content = capture2.encryptedContent;
43245
43245
  }
43246
43246
  msg2.encryptedContent = {
43247
- algorithm: asn1.derToOid(capture.encAlgorithm),
43248
- parameter: forge2.util.createBuffer(capture.encParameter.value),
43247
+ algorithm: asn1.derToOid(capture2.encAlgorithm),
43248
+ parameter: forge2.util.createBuffer(capture2.encParameter.value),
43249
43249
  content: forge2.util.createBuffer(content)
43250
43250
  };
43251
43251
  }
43252
- if (capture.content) {
43252
+ if (capture2.content) {
43253
43253
  var content = "";
43254
- if (forge2.util.isArray(capture.content)) {
43255
- for (var i = 0; i < capture.content.length; ++i) {
43256
- if (capture.content[i].type !== asn1.Type.OCTETSTRING) {
43254
+ if (forge2.util.isArray(capture2.content)) {
43255
+ for (var i = 0; i < capture2.content.length; ++i) {
43256
+ if (capture2.content[i].type !== asn1.Type.OCTETSTRING) {
43257
43257
  throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");
43258
43258
  }
43259
- content += capture.content[i].value;
43259
+ content += capture2.content[i].value;
43260
43260
  }
43261
43261
  } else {
43262
- content = capture.content;
43262
+ content = capture2.content;
43263
43263
  }
43264
43264
  msg2.content = forge2.util.createBuffer(content);
43265
43265
  }
43266
- msg2.version = capture.version.charCodeAt(0);
43267
- msg2.rawCapture = capture;
43268
- return capture;
43266
+ msg2.version = capture2.version.charCodeAt(0);
43267
+ msg2.rawCapture = capture2;
43268
+ return capture2;
43269
43269
  }
43270
43270
  function _decryptContent(msg2) {
43271
43271
  if (msg2.encryptedContent.key === void 0) {
@@ -43425,8 +43425,8 @@ var require_ssh = __commonJS({
43425
43425
  }
43426
43426
  function _sha1() {
43427
43427
  var sha = forge2.md.sha1.create();
43428
- var num = arguments.length;
43429
- for (var i = 0; i < num; ++i) {
43428
+ var num2 = arguments.length;
43429
+ for (var i = 0; i < num2; ++i) {
43430
43430
  sha.update(arguments[i]);
43431
43431
  }
43432
43432
  return sha.digest();
@@ -43868,8 +43868,13 @@ function resolveBoundaries(input) {
43868
43868
  input.messages.forEach(
43869
43869
  (message, index) => indexByRawId.set(message.id, index)
43870
43870
  );
43871
- let startIndex = resolveAnchorIndex(start, input.state, indexByRawId, "start");
43872
- let endIndex = resolveAnchorIndex(end, input.state, indexByRawId, "end");
43871
+ let snappedBoundaries = [];
43872
+ const startAnchor = resolveAnchorIndex(start, input.state, indexByRawId, "start");
43873
+ if (startAnchor.snapped) snappedBoundaries.push(startAnchor.snapped);
43874
+ const endAnchor = resolveAnchorIndex(end, input.state, indexByRawId, "end");
43875
+ if (endAnchor.snapped) snappedBoundaries.push(endAnchor.snapped);
43876
+ let startIndex = startAnchor.index;
43877
+ let endIndex = endAnchor.index;
43873
43878
  if (startIndex > endIndex) {
43874
43879
  [startIndex, endIndex] = [endIndex, startIndex];
43875
43880
  }
@@ -43897,7 +43902,8 @@ function resolveBoundaries(input) {
43897
43902
  messageIds,
43898
43903
  nestedBlockIds,
43899
43904
  boundaryKind,
43900
- protectedGaps
43905
+ protectedGaps,
43906
+ snappedBoundaries
43901
43907
  };
43902
43908
  }
43903
43909
  function resolveAnchorIndex(boundary, state, indexByRawId, endpoint) {
@@ -43912,14 +43918,21 @@ function resolveAnchorIndex(boundary, state, indexByRawId, endpoint) {
43912
43918
  );
43913
43919
  }
43914
43920
  const index = indexByRawId.get(rawId);
43915
- if (index === void 0) {
43916
- throw new BoundaryNotFoundError(
43917
- "consumed",
43918
- endpoint,
43919
- `${label}="${boundary.raw}" not found in visible context (likely consumed by an existing block).`
43920
- );
43921
+ if (index !== void 0) {
43922
+ return { index, snapped: null };
43921
43923
  }
43922
- return index;
43924
+ const owner2 = activeOwnerAnchor(state, [rawId], indexByRawId);
43925
+ if (owner2 !== null) {
43926
+ return {
43927
+ index: owner2,
43928
+ snapped: `${label}="${boundary.raw}" refers to a message already compressed into an active block \u2014 anchored to that block's summary instead.`
43929
+ };
43930
+ }
43931
+ throw new BoundaryNotFoundError(
43932
+ "consumed",
43933
+ endpoint,
43934
+ `${label}="${boundary.raw}" not found in visible context (likely consumed by an existing block).`
43935
+ );
43923
43936
  }
43924
43937
  const block = blockById(state, `b${boundary.numericId}`);
43925
43938
  if (!block) {
@@ -43929,6 +43942,19 @@ function resolveAnchorIndex(boundary, state, indexByRawId, endpoint) {
43929
43942
  `${label}="b${boundary.numericId}" does not exist in this session (typo or wrong session) \u2014 run acp_status for current refs.`
43930
43943
  );
43931
43944
  }
43945
+ if (block.active) {
43946
+ const anchor = earliestIndexOfIds(block.effectiveMessageIds, indexByRawId);
43947
+ if (anchor !== null) {
43948
+ return { index: anchor, snapped: null };
43949
+ }
43950
+ }
43951
+ const owner = activeOwnerAnchor(state, block.effectiveMessageIds, indexByRawId);
43952
+ if (owner !== null) {
43953
+ return {
43954
+ index: owner,
43955
+ snapped: `${label}="b${boundary.numericId}" was consumed by a higher-tier block \u2014 anchored to the active block covering its content instead.`
43956
+ };
43957
+ }
43932
43958
  if (!block.active) {
43933
43959
  throw new BoundaryNotFoundError(
43934
43960
  "consumed",
@@ -43936,15 +43962,26 @@ function resolveAnchorIndex(boundary, state, indexByRawId, endpoint) {
43936
43962
  `${label}="b${boundary.numericId}" not found in visible context (block distilled/consumed by a higher-tier block).`
43937
43963
  );
43938
43964
  }
43939
- const anchor = earliestIndexOfIds(block.effectiveMessageIds, indexByRawId);
43940
- if (anchor === null) {
43941
- throw new BoundaryNotFoundError(
43942
- "consumed",
43943
- endpoint,
43944
- `${label}="b${boundary.numericId}" not found in visible context (block messages consumed by a higher-tier block).`
43945
- );
43965
+ throw new BoundaryNotFoundError(
43966
+ "consumed",
43967
+ endpoint,
43968
+ `${label}="b${boundary.numericId}" not found in visible context (block messages consumed by a higher-tier block).`
43969
+ );
43970
+ }
43971
+ function activeOwnerAnchor(state, ownedIds, indexByRawId) {
43972
+ if (ownedIds.length === 0) return null;
43973
+ const owned = new Set(ownedIds);
43974
+ let best = null;
43975
+ for (const block of state.blocks) {
43976
+ if (!block.active) continue;
43977
+ const anchor = earliestIndexOfIds(block.effectiveMessageIds, indexByRawId);
43978
+ if (anchor === null) continue;
43979
+ const ownsContent = block.effectiveMessageIds.some((id) => owned.has(id));
43980
+ if (ownsContent && (best === null || anchor < best)) {
43981
+ best = anchor;
43982
+ }
43946
43983
  }
43947
- return anchor;
43984
+ return best;
43948
43985
  }
43949
43986
  function formatPaddedRef(index) {
43950
43987
  return `m${String(index).padStart(5, "0")}`;
@@ -44010,7 +44047,7 @@ function truncateLargeToolOutputs(messages, tokenCount, config, countTokens, opt
44010
44047
  );
44011
44048
  return { messages: updated, truncatedCount, savedTokens };
44012
44049
  }
44013
- var KEEP_LAST_ORPHANED = 0;
44050
+ var KEEP_LAST_ORPHANED = 2;
44014
44051
  function rangeKey(startRef, endRef) {
44015
44052
  return `${startRef}::${endRef}`;
44016
44053
  }
@@ -44565,6 +44602,10 @@ function runPipeline(nodes, initial, ctx) {
44565
44602
  function rangeError(spec, message) {
44566
44603
  return `range ${spec.startRef}..${spec.endRef}: ${message}`;
44567
44604
  }
44605
+ function numericBlockId(id) {
44606
+ const parsed = /^b(\d+)$/.exec(id);
44607
+ return parsed ? Number(parsed[1]) : 0;
44608
+ }
44568
44609
  function createCore(ports = {}) {
44569
44610
  const countTokens = ports.countTokens ?? defaultCountTokens;
44570
44611
  function applyCompression(input) {
@@ -44610,6 +44651,12 @@ function createCore(ports = {}) {
44610
44651
  }
44611
44652
  }
44612
44653
  }
44654
+ let resolvableCount = 0;
44655
+ let unknownCount = 0;
44656
+ for (const resolution of classifications.values()) {
44657
+ if (resolution.status === "ok") resolvableCount++;
44658
+ else if (resolution.status === "unknown") unknownCount++;
44659
+ }
44613
44660
  const rangeIndexSets = [];
44614
44661
  for (const [spec, resolution] of classifications) {
44615
44662
  if (resolution.status !== "ok") continue;
@@ -44654,7 +44701,9 @@ function createCore(ports = {}) {
44654
44701
  }
44655
44702
  }
44656
44703
  if (!hasBlockBoundaryRange && totalRangeChars < input.config.compress.minCompressRange) {
44657
- const gateMessage = consumedRanges.length > 0 ? `Requested range(s) already compressed (e.g. ${consumedRanges[0].startRef}..${consumedRanges[0].endRef}); remaining compressible content ${totalRangeChars} chars < min ${input.config.compress.minCompressRange}. Nothing to do \u2014 run acp_status to see current compressible ranges.` : `Total compressible content too small (${totalRangeChars} chars across ${countedRanges} range(s), min ${input.config.compress.minCompressRange}). Combine more messages into your range(s) to meet the threshold.`;
44704
+ const live = activeBlocks(state).map((b2) => b2.blockId).sort((x, y) => numericBlockId(x) - numericBlockId(y));
44705
+ const liveHint = live.length > 0 ? ` Current active blocks span ${live[0]}..${live[live.length - 1]} \u2014 retry with startId/endId set to active block IDs in that span.` : "";
44706
+ const gateMessage = resolvableCount === 0 && consumedRanges.length === 0 && unknownCount > 0 ? `None of the ${input.ranges.length} requested range(s) resolved \u2014 every ref failed with "does not exist in this session". Refs recorded before an earlier compress are stale: each successful compress renumbers the remaining refs. Run acp_status, then re-issue the compress in the same turn using only the refs it reports.` : consumedRanges.length > 0 ? `Requested range(s) already compressed (e.g. ${consumedRanges[0].startRef}..${consumedRanges[0].endRef}); remaining compressible content ${totalRangeChars} chars < min ${input.config.compress.minCompressRange}. Nothing to do.${liveHint}` : `Total compressible content too small (${totalRangeChars} chars across ${countedRanges} range(s), min ${input.config.compress.minCompressRange}). Combine more messages into your range(s) to meet the threshold.`;
44658
44707
  return {
44659
44708
  state: input.state,
44660
44709
  result: {
@@ -44680,6 +44729,7 @@ function createCore(ports = {}) {
44680
44729
  errors.push(rangeError(spec, resolution.error.message));
44681
44730
  continue;
44682
44731
  }
44732
+ warnings.push(...resolution.resolved.snappedBoundaries);
44683
44733
  try {
44684
44734
  const outcome = applySingleRange({
44685
44735
  spec,
@@ -45845,14 +45895,14 @@ function renderUncompressedRanges(visible) {
45845
45895
  };
45846
45896
  const merged = [];
45847
45897
  for (const m2 of visible) {
45848
- const num = refNum2(m2.ref);
45898
+ const num2 = refNum2(m2.ref);
45849
45899
  const last = merged[merged.length - 1];
45850
- if (last && num === last.startNum + last.count) {
45900
+ if (last && num2 === last.startNum + last.count) {
45851
45901
  last.endRef = m2.ref;
45852
45902
  last.count += 1;
45853
45903
  last.tokens += m2.tokens;
45854
45904
  } else {
45855
- merged.push({ startRef: m2.ref, endRef: m2.ref, startNum: num, count: 1, tokens: m2.tokens, tool: m2.tool });
45905
+ merged.push({ startRef: m2.ref, endRef: m2.ref, startNum: num2, count: 1, tokens: m2.tokens, tool: m2.tool });
45856
45906
  }
45857
45907
  }
45858
45908
  for (const r of merged.slice(0, 30)) {
@@ -45919,24 +45969,6 @@ function renderCompressedDrilldown(blocks, state, sort, limit, countTokens) {
45919
45969
  }
45920
45970
  return lines.join("\n");
45921
45971
  }
45922
- var substringAlgorithm = {
45923
- name: "substring",
45924
- description: "Exact substring counting (original baseline). Predictable, no normalization.",
45925
- score(docs, query) {
45926
- const terms = query.toLowerCase().trim().split(/\s+/).filter((t) => t.length > 0);
45927
- if (terms.length === 0) return docs.map((d) => ({ ref: d.ref, score: 0 }));
45928
- return docs.map((d) => {
45929
- const haystack = d.text.toLowerCase();
45930
- let score = 0;
45931
- for (const term of terms) score += countOccurrences2(haystack, term);
45932
- return { ref: d.ref, score };
45933
- });
45934
- }
45935
- };
45936
- function countOccurrences2(haystack, needle) {
45937
- if (!needle) return 0;
45938
- return haystack.split(needle).length - 1;
45939
- }
45940
45972
  function stem(word) {
45941
45973
  let w2 = word;
45942
45974
  if (w2.length <= 3) return w2;
@@ -45955,8 +45987,17 @@ function stem(word) {
45955
45987
  return w2;
45956
45988
  }
45957
45989
  var CJK = /[\u3400-\u9fff\uf900-\ufaff\u3040-\u30ff\uac00-\ud7af]/;
45958
- var CJK_RUN = new RegExp(`${CJK.source}+`, "g");
45959
45990
  var LATIN_WORD = /[a-z][a-z0-9_]*[a-z0-9]|[a-z0-9]/g;
45991
+ var cjkSegmenter = new Intl.Segmenter("zh", { granularity: "word" });
45992
+ function cjkRunTokens(segs) {
45993
+ const words = segs.filter((w2) => w2.length >= 2);
45994
+ if (words.length > 0) return words;
45995
+ const run = segs.join("");
45996
+ const out = [];
45997
+ for (let i = 0; i < run.length - 1; i++) out.push(run.slice(i, i + 2));
45998
+ for (const ch of run) out.push(ch);
45999
+ return out;
46000
+ }
45960
46001
  function tokenize(text, opts = {}) {
45961
46002
  const lower = text.toLowerCase();
45962
46003
  const tokens = [];
@@ -45967,15 +46008,23 @@ function tokenize(text, opts = {}) {
45967
46008
  tokens.push(w2);
45968
46009
  }
45969
46010
  }
45970
- const cjkRuns = lower.match(CJK_RUN) ?? [];
45971
- for (const run of cjkRuns) {
45972
- if (run.length === 1) {
45973
- tokens.push(run);
45974
- } else {
45975
- for (let i = 0; i < run.length - 1; i++) tokens.push(run.slice(i, i + 2));
45976
- for (const ch of run) tokens.push(ch);
46011
+ if (!CJK.test(lower)) return tokens;
46012
+ const runSegs = [];
46013
+ let cur = null;
46014
+ for (const s3 of cjkSegmenter.segment(lower)) {
46015
+ const t = s3.segment;
46016
+ if (t.length === 0) continue;
46017
+ if (CJK.test(t)) {
46018
+ (cur ??= []).push(t);
46019
+ } else if (cur) {
46020
+ runSegs.push(cur);
46021
+ cur = null;
45977
46022
  }
45978
46023
  }
46024
+ if (cur) runSegs.push(cur);
46025
+ for (const segs of runSegs) {
46026
+ tokens.push(...cjkRunTokens(segs));
46027
+ }
45979
46028
  return tokens;
45980
46029
  }
45981
46030
  function charBigrams(text) {
@@ -45991,6 +46040,50 @@ function tfMap(text, stem2) {
45991
46040
  for (const t of tokenize(text, { stem: stem2 })) m2.set(t, (m2.get(t) ?? 0) + 1);
45992
46041
  return m2;
45993
46042
  }
46043
+ var DEFAULT_CAP_CHARS = 8 * 1024 * 1024;
46044
+ var capChars = DEFAULT_CAP_CHARS;
46045
+ var cache = /* @__PURE__ */ new Map();
46046
+ var cachedChars = 0;
46047
+ function build(text) {
46048
+ const tf = tfMap(text, true);
46049
+ let len = 0;
46050
+ for (const v2 of tf.values()) len += v2;
46051
+ const lower = text.toLowerCase();
46052
+ return { tf, len, lower, grams: new Set(charBigrams(lower)) };
46053
+ }
46054
+ function docFeatures(text) {
46055
+ const hit = cache.get(text);
46056
+ if (hit) return hit;
46057
+ const f2 = build(text);
46058
+ if (text.length > 0 && text.length <= capChars) {
46059
+ while (cachedChars + text.length > capChars && cache.size > 0) {
46060
+ const k2 = cache.keys().next().value;
46061
+ cachedChars -= k2.length;
46062
+ cache.delete(k2);
46063
+ }
46064
+ cache.set(text, f2);
46065
+ cachedChars += text.length;
46066
+ }
46067
+ return f2;
46068
+ }
46069
+ var substringAlgorithm = {
46070
+ name: "substring",
46071
+ description: "Exact substring counting (original baseline). Predictable, no normalization.",
46072
+ score(docs, query) {
46073
+ const terms = query.toLowerCase().trim().split(/\s+/).filter((t) => t.length > 0);
46074
+ if (terms.length === 0) return docs.map((d) => ({ ref: d.ref, score: 0 }));
46075
+ return docs.map((d) => {
46076
+ const haystack = docFeatures(d.text).lower;
46077
+ let score = 0;
46078
+ for (const term of terms) score += countOccurrences2(haystack, term);
46079
+ return { ref: d.ref, score };
46080
+ });
46081
+ }
46082
+ };
46083
+ function countOccurrences2(haystack, needle) {
46084
+ if (!needle) return 0;
46085
+ return haystack.split(needle).length - 1;
46086
+ }
45994
46087
  var bm25Algorithm = {
45995
46088
  name: "bm25",
45996
46089
  description: "BM25 with stemming + CJK bigram tokenization. IR-standard relevance ranking.",
@@ -45999,11 +46092,8 @@ var bm25Algorithm = {
45999
46092
  const k1 = 1.2;
46000
46093
  const b2 = 0.75;
46001
46094
  const parsed = docs.map((d) => {
46002
- const text = d.text;
46003
- const tf = tfMap(text, true);
46004
- let len = 0;
46005
- for (const v2 of tf.values()) len += v2;
46006
- return { id: d.ref, tf, len };
46095
+ const f2 = docFeatures(d.text);
46096
+ return { id: d.ref, tf: f2.tf, len: f2.len };
46007
46097
  });
46008
46098
  const avgdl = parsed.reduce((s3, d) => s3 + d.len, 0) / (N2 || 1);
46009
46099
  const qTerms = tokenize(query, { stem: true });
@@ -46030,14 +46120,13 @@ var fuzzyAlgorithm = {
46030
46120
  name: "fuzzy",
46031
46121
  description: "Character bigram overlap. Typo-tolerant, script-agnostic, high recall.",
46032
46122
  score(docs, query) {
46033
- const qTokens = query.toLowerCase().split(/[\s,]+/).filter((t) => t.length >= 4);
46123
+ const qTokens = query.toLowerCase().split(/[\s,]+/).filter((t) => t.length >= 4 || t.length >= 2 && CJK.test(t));
46034
46124
  if (qTokens.length === 0) return docs.map((d) => ({ ref: d.ref, score: 0 }));
46035
46125
  const qGrams = /* @__PURE__ */ new Set();
46036
46126
  for (const t of qTokens) for (const g2 of charBigrams(t)) qGrams.add(g2);
46037
46127
  if (qGrams.size === 0) return docs.map((d) => ({ ref: d.ref, score: 0 }));
46038
46128
  return docs.map((d) => {
46039
- const haystack = d.text.toLowerCase();
46040
- const docGrams = new Set(charBigrams(haystack));
46129
+ const docGrams = docFeatures(d.text).grams;
46041
46130
  let hits = 0;
46042
46131
  for (const g2 of qGrams) if (docGrams.has(g2)) hits++;
46043
46132
  return { ref: d.ref, score: hits / qGrams.size };
@@ -46108,6 +46197,9 @@ function stateDir() {
46108
46197
  function defaultLogFile() {
46109
46198
  return path.join(stateDir(), "bili.log");
46110
46199
  }
46200
+ function proxyOriginFile() {
46201
+ return path.join(stateDir(), "proxy-origin");
46202
+ }
46111
46203
  function caDir() {
46112
46204
  return path.join(dataDir(), "ca");
46113
46205
  }
@@ -46164,7 +46256,14 @@ function configureLogger(file) {
46164
46256
  stream = openStream(file);
46165
46257
  return file;
46166
46258
  }
46259
+ var capture = null;
46167
46260
  var log = (level, msg2) => {
46261
+ if (capture) {
46262
+ try {
46263
+ capture(level, msg2);
46264
+ } catch {
46265
+ }
46266
+ }
46168
46267
  const ts2 = (/* @__PURE__ */ new Date()).toISOString();
46169
46268
  const line = `${ts2} [${level}] ${msg2}
46170
46269
  `;
@@ -46430,13 +46529,32 @@ function openProxySocket(proxy) {
46430
46529
  }
46431
46530
  return net.connect(proxy.port, proxy.host);
46432
46531
  }
46532
+ var CONNECT_TIMEOUT_MS = 1e4;
46533
+ var connectFactory = (port, host) => net.connect(port, host);
46534
+ function connectDirect(host, port, timeoutMs = CONNECT_TIMEOUT_MS) {
46535
+ return new Promise((resolve, reject) => {
46536
+ const socket = connectFactory(port, host);
46537
+ let settled = false;
46538
+ const finishError = (error) => {
46539
+ if (settled) return;
46540
+ settled = true;
46541
+ clearTimeout(timer2);
46542
+ socket.destroy();
46543
+ reject(error);
46544
+ };
46545
+ const timer2 = setTimeout(() => finishError(new Error(`upstream connect ${host}:${port} timed out after ${timeoutMs}ms`)), timeoutMs);
46546
+ socket.once("error", finishError);
46547
+ socket.once("connect", () => {
46548
+ if (settled) return;
46549
+ settled = true;
46550
+ clearTimeout(timer2);
46551
+ resolve(socket);
46552
+ });
46553
+ });
46554
+ }
46433
46555
  function connectThroughProxy(host, port, proxyUrl) {
46434
46556
  if (!proxyUrl) {
46435
- return new Promise((resolve, reject) => {
46436
- const socket = net.connect(port, host);
46437
- socket.once("connect", () => resolve(socket));
46438
- socket.once("error", reject);
46439
- });
46557
+ return connectDirect(host, port);
46440
46558
  }
46441
46559
  const proxy = parseHttpProxy(proxyUrl);
46442
46560
  if (!proxy) return Promise.reject(new Error(`invalid upstream proxy: ${redactProxyUrl(proxyUrl)}`));
@@ -46450,7 +46568,7 @@ function connectThroughProxy(host, port, proxyUrl) {
46450
46568
  socket.destroy();
46451
46569
  reject(error);
46452
46570
  };
46453
- const timer2 = setTimeout(() => finishError(new Error(`upstream proxy CONNECT ${host}:${port} handshake timeout`)), 1e4);
46571
+ const timer2 = setTimeout(() => finishError(new Error(`upstream proxy CONNECT ${host}:${port} handshake timeout`)), CONNECT_TIMEOUT_MS);
46454
46572
  socket.once("error", finishError);
46455
46573
  const connectedEvent = proxy.protocol === "https:" ? "secureConnect" : "connect";
46456
46574
  socket.once(connectedEvent, () => {
@@ -46538,13 +46656,13 @@ function getUpstreamConnectionStatus() {
46538
46656
  }
46539
46657
 
46540
46658
  // src/config.ts
46541
- function safeReadJson(path12) {
46659
+ function safeReadJson(path15) {
46542
46660
  try {
46543
- const raw = readFileSync(path12, "utf8").replace(/^\uFEFF/, "");
46661
+ const raw = readFileSync(path15, "utf8").replace(/^\uFEFF/, "");
46544
46662
  return JSON.parse(raw);
46545
46663
  } catch (e) {
46546
46664
  if (e.code !== "ENOENT") {
46547
- log("error", `[acp-config] failed to parse ${path12}: ${String(e)}`);
46665
+ log("error", `[acp-config] failed to parse ${path15}: ${String(e)}`);
46548
46666
  }
46549
46667
  return void 0;
46550
46668
  }
@@ -46624,7 +46742,8 @@ function loadOptions(env = process.env) {
46624
46742
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
46625
46743
  throw new Error(`Invalid port ${Number.isNaN(port) ? "(not a number)" : port}; must be 1-65535`);
46626
46744
  }
46627
- const host = env.ACP_HOST ?? fileConfig.host ?? "127.0.0.1";
46745
+ const rawHost = env.ACP_HOST ?? fileConfig.host ?? "127.0.0.1";
46746
+ const host = rawHost === "localhost" ? "127.0.0.1" : rawHost;
46628
46747
  const upstream = (env.ACP_UPSTREAM ?? fileConfig.upstream ?? "https://api.anthropic.com").replace(/\/$/, "");
46629
46748
  const routes = loadRoutes(env);
46630
46749
  const modelContextLimit = parseInt(env.ACP_MODEL_CONTEXT_LIMIT ?? `${fileConfig.modelContextLimit ?? 2e5}`, 10);
@@ -46823,7 +46942,7 @@ function rejectLegacyRoute(key, value) {
46823
46942
 
46824
46943
  // src/server.ts
46825
46944
  import http from "http";
46826
- import fs5 from "fs";
46945
+ import fs6 from "fs";
46827
46946
 
46828
46947
  // src/compress-settings.ts
46829
46948
  function resolveContextLimitValue(raw, nativeLimit) {
@@ -46924,7 +47043,7 @@ import path3 from "path";
46924
47043
  var REGISTRY_URL = "https://models.dev/models.json";
46925
47044
  var CACHE_FILE = path3.join(cacheDir(), "models-dev.json");
46926
47045
  var TTL_MS = 24 * 60 * 60 * 1e3;
46927
- var cache = null;
47046
+ var cache2 = null;
46928
47047
  var loading = null;
46929
47048
  function parse(raw) {
46930
47049
  try {
@@ -46976,25 +47095,25 @@ async function fetchFresh() {
46976
47095
  }
46977
47096
  }
46978
47097
  async function loadRegistry() {
46979
- if (cache) return cache;
47098
+ if (cache2) return cache2;
46980
47099
  if (diskCacheFresh()) {
46981
47100
  const disk = await readDiskCache();
46982
47101
  if (disk) {
46983
- cache = disk;
46984
- return cache;
47102
+ cache2 = disk;
47103
+ return cache2;
46985
47104
  }
46986
47105
  }
46987
47106
  if (loading) return loading;
46988
47107
  loading = (async () => {
46989
47108
  const fresh = await fetchFresh();
46990
47109
  if (fresh) {
46991
- cache = fresh;
47110
+ cache2 = fresh;
46992
47111
  log("info", `[acp-registry] loaded models.dev (${Object.keys(fresh).length} models)`);
46993
47112
  return fresh;
46994
47113
  }
46995
47114
  const disk = await readDiskCache();
46996
47115
  if (disk) {
46997
- cache = disk;
47116
+ cache2 = disk;
46998
47117
  log("info", `[acp-registry] using stale disk cache (${Object.keys(disk).length} models, fetch failed)`);
46999
47118
  return disk;
47000
47119
  }
@@ -47229,8 +47348,8 @@ function coreToAnthropic(messages, cacheControls) {
47229
47348
  flush();
47230
47349
  return out;
47231
47350
  }
47232
- function conversationSignalAnthropic(body, headerValue2) {
47233
- if (headerValue2 && headerValue2.trim()) return headerValue2.trim();
47351
+ function conversationSignalAnthropic(body, headerValue3) {
47352
+ if (headerValue3 && headerValue3.trim()) return headerValue3.trim();
47234
47353
  const firstUser = body.messages.find((m2) => m2.role === "user");
47235
47354
  const seed = firstUser ? JSON.stringify(firstUser.content) : "default";
47236
47355
  return hashId(seed);
@@ -47268,14 +47387,17 @@ function openaiToCore(body) {
47268
47387
  }
47269
47388
  case "user": {
47270
47389
  const text = stringContent(m2.content);
47271
- const img = firstImagePart(m2.content);
47390
+ const imgs = allImageParts(m2.content);
47391
+ const firstImg = imgs[0];
47392
+ const firstUrl = firstImg ? firstImg.image_url.url : void 0;
47393
+ const firstParsed = firstUrl ? parseDataUrl(firstUrl) : void 0;
47272
47394
  const base = deriveMessageId("user", "text", text);
47273
47395
  msgs.push({
47274
47396
  id: clusters.next(base),
47275
47397
  role: "user",
47276
47398
  contentType: "text",
47277
47399
  text,
47278
- ...img ? { rawOpenaiContent: img.part, imageMediaType: img.mediaType, imageBase64: img.base64 } : {}
47400
+ ...imgs.length === 1 && firstParsed ? { rawOpenaiContent: imgs[0], imageMediaType: firstParsed.mediaType, imageBase64: firstParsed.base64 } : imgs.length > 1 ? { rawOpenaiContentParts: imgs } : {}
47279
47401
  });
47280
47402
  break;
47281
47403
  }
@@ -47370,10 +47492,12 @@ function coreToOpenai(messages) {
47370
47492
  if (m2.role === "system") {
47371
47493
  out.push({ role: m2.originalRole === "developer" ? "developer" : "system", content: m2.text ?? "" });
47372
47494
  } else if (m2.role === "user") {
47373
- if (m2.rawOpenaiContent || m2.imageBase64) {
47495
+ if (m2.rawOpenaiContent || m2.imageBase64 || m2.rawOpenaiContentParts) {
47374
47496
  const parts = [];
47375
47497
  if (m2.text) parts.push({ type: "text", text: m2.text });
47376
- if (m2.rawOpenaiContent) {
47498
+ if (m2.rawOpenaiContentParts && m2.rawOpenaiContentParts.length > 0) {
47499
+ for (const part of m2.rawOpenaiContentParts) parts.push(part);
47500
+ } else if (m2.rawOpenaiContent) {
47377
47501
  parts.push(m2.rawOpenaiContent);
47378
47502
  } else if (m2.imageBase64 && m2.imageMediaType) {
47379
47503
  parts.push({ type: "image_url", image_url: { url: `data:${m2.imageMediaType};base64,${m2.imageBase64}` } });
@@ -47405,8 +47529,8 @@ ${extra}` : extra;
47405
47529
  }
47406
47530
  return [{ role: "system", content: extra }, ...messages];
47407
47531
  }
47408
- function conversationSignalOpenai(body, headerValue2) {
47409
- if (headerValue2 && headerValue2.trim()) return headerValue2.trim();
47532
+ function conversationSignalOpenai(body, headerValue3) {
47533
+ if (headerValue3 && headerValue3.trim()) return headerValue3.trim();
47410
47534
  const firstUser = body.messages.find((m2) => m2.role === "user");
47411
47535
  const seed = firstUser ? stringContent(firstUser.content) : "default";
47412
47536
  return hashId(seed);
@@ -47419,19 +47543,17 @@ function stringContent(content) {
47419
47543
  }
47420
47544
  return "";
47421
47545
  }
47422
- function firstImagePart(content) {
47423
- if (!Array.isArray(content)) return void 0;
47546
+ function allImageParts(content) {
47547
+ if (!Array.isArray(content)) return [];
47548
+ const out = [];
47424
47549
  for (const p2 of content) {
47425
- if (p2 && typeof p2 === "object" && p2.type === "image_url") {
47426
- const iu = p2.image_url;
47427
- const url = iu?.url;
47428
- if (typeof url === "string") {
47429
- const parsed = parseDataUrl(url);
47430
- if (parsed) return { part: p2, mediaType: parsed.mediaType, base64: parsed.base64 };
47431
- }
47432
- }
47550
+ if (typeof p2 !== "object" || p2 === null) continue;
47551
+ if (!("type" in p2) || p2.type !== "image_url" || !("image_url" in p2)) continue;
47552
+ const imagePart = p2;
47553
+ const url = imagePart.image_url.url;
47554
+ if (typeof url === "string" && parseDataUrl(url)) out.push(p2);
47433
47555
  }
47434
- return void 0;
47556
+ return out;
47435
47557
  }
47436
47558
  var OPAQUE_ITEM_TYPES = /* @__PURE__ */ new Set([
47437
47559
  "additional_tools",
@@ -47691,8 +47813,8 @@ function injectResponsesDeveloperMessage(input, content) {
47691
47813
  items.splice(index, 0, { type: "message", role: "developer", content });
47692
47814
  return items;
47693
47815
  }
47694
- function conversationIdentityResponses(body, headerValue2) {
47695
- if (headerValue2?.trim()) return { value: headerValue2.trim(), source: "header", clientProvided: true };
47816
+ function conversationIdentityResponses(body, headerValue3) {
47817
+ if (headerValue3?.trim()) return { value: headerValue3.trim(), source: "header", clientProvided: true };
47696
47818
  if (typeof body.session_id === "string" && body.session_id.trim()) {
47697
47819
  return { value: body.session_id.trim(), source: "body-session", clientProvided: true };
47698
47820
  }
@@ -47705,8 +47827,8 @@ function conversationIdentityResponses(body, headerValue2) {
47705
47827
  }
47706
47828
  return { value: hashId(JSON.stringify(body.input ?? [])), source: "content-fingerprint", clientProvided: false };
47707
47829
  }
47708
- function conversationSignalResponses(body, headerValue2) {
47709
- return conversationIdentityResponses(body, headerValue2).value;
47830
+ function conversationSignalResponses(body, headerValue3) {
47831
+ return conversationIdentityResponses(body, headerValue3).value;
47710
47832
  }
47711
47833
  function createSubagentNamespaces() {
47712
47834
  const anchors = /* @__PURE__ */ new Map();
@@ -48176,6 +48298,9 @@ async function withSessionLock(session, fn) {
48176
48298
  function listSessions() {
48177
48299
  return [...sessions.values()].sort((a, b2) => b2.lastSeen - a.lastSeen);
48178
48300
  }
48301
+ function peekSession(id) {
48302
+ return sessions.get(id);
48303
+ }
48179
48304
  function snapshotMessages(session, messages) {
48180
48305
  if (messages.length > 0) session.lastMessages = messages;
48181
48306
  }
@@ -48278,8 +48403,17 @@ function parseCompressInput(input, callId) {
48278
48403
  return [];
48279
48404
  }
48280
48405
  const obj = input;
48406
+ let content = obj.content;
48407
+ if (typeof content === "string") {
48408
+ try {
48409
+ content = JSON.parse(content);
48410
+ } catch {
48411
+ log("warn", `[acp-compress-input] content is a string but not valid JSON; parsed 0 valid ranges`);
48412
+ return [];
48413
+ }
48414
+ }
48281
48415
  const single = toRange(obj);
48282
- const ranges = Array.isArray(obj.content) ? obj.content.map((r) => toRange(r)).filter((r) => r !== null) : single ? [single] : [];
48416
+ const ranges = Array.isArray(content) ? content.map((r) => toRange(r)).filter((r) => r !== null) : single ? [single] : [];
48283
48417
  if (ranges.length === 0) {
48284
48418
  log("warn", `[acp-compress-input] parsed 0 valid ranges. top keys: ${Object.keys(obj).join(",")}`);
48285
48419
  }
@@ -48584,6 +48718,12 @@ ${body.slice(0, 4e3)}...`;
48584
48718
  ${body}`;
48585
48719
  }
48586
48720
 
48721
+ // src/sse-util.ts
48722
+ function normalizeSseLineEndings(buf) {
48723
+ if (buf.indexOf("\r") === -1) return buf;
48724
+ return buf.replace(/\r\n|\r/g, "\n");
48725
+ }
48726
+
48587
48727
  // src/stream.ts
48588
48728
  function executeAnthropicProxyTool(toolName, args, ctx) {
48589
48729
  if (toolName === COMPRESS_TOOL_NAME) {
@@ -48735,7 +48875,7 @@ function renderPage(origin, version2) {
48735
48875
  <p class="hint">\u5728\u5BA2\u6237\u7AEF\u914D\u7F6E\u91CC\u628A\u539F baseURL \u524D\u52A0\u4E0A <span class="mono">${origin}/bili/</span> \u5373\u53EF\uFF0C\u5176\u4F59\u4E0D\u53D8\u3002</p>
48736
48876
  <div class="card"><div class="card-head"><h2>OpenCode</h2><button class="btn small copy-btn" data-copy="${origin}/bili/https://open.bigmodel.cn/api/coding/paas/v4">\u590D\u5236</button></div><dl class="kv"><dt>\u914D\u7F6E\u6587\u4EF6</dt><dd class="mono">~/.config/opencode/opencode.json</dd><dt>baseURL</dt><dd class="mono">${origin}/bili/https://open.bigmodel.cn/api/coding/paas/v4</dd></dl></div>
48737
48877
  <div class="card"><div class="card-head"><h2>Codex\uFF08API key\uFF09</h2><button class="btn small copy-btn" data-copy="${origin}/bili/https://api.openai.com/v1">\u590D\u5236</button></div><dl class="kv"><dt>\u914D\u7F6E\u6587\u4EF6</dt><dd class="mono">~/.codex/config.toml</dd><dt>base_url</dt><dd class="mono">${origin}/bili/https://api.openai.com/v1</dd></dl></div>
48738
- <div class="card"><div class="card-head"><h2>Codex\uFF08ChatGPT \u767B\u5F55\uFF09</h2><button class="btn small copy-btn" data-copy="model_provider = &quot;openai&quot;&#10;openai_base_url = &quot;${origin}/bili/https://chatgpt.com/backend-api/codex&quot;">\u590D\u5236\u914D\u7F6E</button></div><dl class="kv"><dt>\u914D\u7F6E\u6587\u4EF6</dt><dd class="mono">~/.codex/config.toml</dd><dt>\u914D\u7F6E</dt><dd class="mono">model_provider = "openai"<br>openai_base_url = "${origin}/bili/https://chatgpt.com/backend-api/codex"</dd><dt>\u8BA4\u8BC1</dt><dd><span class="mono">codex login</span>\uFF08OAuth token \u900F\u4F20\uFF0C\u65E0\u9700\u8BC1\u4E66\uFF09</dd></dl></div>
48878
+ <div class="card"><div class="card-head"><h2>Codex\uFF08ChatGPT \u767B\u5F55\uFF09</h2><button class="btn small copy-btn" data-copy="openai_base_url = &quot;${origin}/bili/https://chatgpt.com/backend-api/codex&quot;">\u590D\u5236\u914D\u7F6E</button></div><dl class="kv"><dt>\u914D\u7F6E\u6587\u4EF6</dt><dd class="mono">~/.codex/config.toml</dd><dt>\u914D\u7F6E</dt><dd class="mono">openai_base_url = "${origin}/bili/https://chatgpt.com/backend-api/codex"</dd><dt>\u8BA4\u8BC1</dt><dd><span class="mono">codex login</span>\uFF08OAuth token \u900F\u4F20\uFF0C\u65E0\u9700\u8BC1\u4E66\uFF09</dd><dt>\u8BF4\u660E</dt><dd>\u9ED8\u8BA4 provider \u5C31\u662F openai\uFF0C\u65E0\u9700 model_provider\uFF1B\u82E5 config.toml \u91CC\u6539\u8FC7 <span class="mono">model_provider</span>\uFF0C\u9700\u518D\u52A0\u4E00\u884C <span class="mono">model_provider = "openai"</span>\u3002\u8FDE\u4E0D\u4E0A\u65F6\u68C0\u67E5\u4EE3\u7406\u73AF\u5883\u53D8\u91CF\uFF1A\u8BBE\u4E86 HTTP(S)_PROXY \u9700\u52A0 <span class="mono">NO_PROXY=localhost,127.0.0.1</span>\uFF1Bbili \u8DD1\u5728 WSL2/Docker \u91CC\u65F6 Windows \u4FA7\u8BF7\u7528 <span class="mono">localhost</span>\uFF08\u81EA\u52A8\u8F6C\u53D1\uFF09\uFF0C127.0.0.1 \u4E0D\u901A\u3002</dd></dl></div>
48739
48879
  <div class="card"><div class="card-head"><h2>Claude Code\uFF08API key\uFF09</h2><button class="btn small copy-btn" data-copy="${origin}/bili/https://api.anthropic.com">\u590D\u5236</button></div><dl class="kv"><dt>\u73AF\u5883\u53D8\u91CF</dt><dd class="mono">ANTHROPIC_BASE_URL=${origin}/bili/https://api.anthropic.com</dd></dl></div>
48740
48880
  <div class="card"><div class="card-head"><h2>Pi</h2><span class="badge">\u4E0D\u63A8\u8350</span><button class="btn small copy-btn" data-copy="${origin}/bili/https://api.anthropic.com">\u590D\u5236</button></div><dl class="kv"><dt>\u914D\u7F6E\u6587\u4EF6</dt><dd class="mono">~/.pi/agent/models.json</dd><dt>baseUrl</dt><dd class="mono">${origin}/bili/https://api.anthropic.com</dd></dl><p class="hint">\u26A0\uFE0F \u4E0D\u63A8\u8350\uFF1APi \u7684 session \u7BA1\u7406\u4E0E bili \u538B\u7F29\u72B6\u6001\u5B58\u5728\u51B2\u7A81\uFF0C\u8BE6\u89C1 README\u3002</p></div>
48741
48881
  <div class="card"><div class="card-head"><h2>\u5176\u4ED6\uFF08Cursor / Aider / Continue\uFF09</h2><button class="btn small copy-btn" data-copy="${origin}/bili/">\u590D\u5236</button></div><dl class="kv"><dt>\u89C4\u5219</dt><dd>\u4EFB\u610F baseURL \u524D\u52A0 <span class="mono">${origin}/bili/</span></dd><dt>\u793A\u4F8B</dt><dd class="mono">${origin}/bili/https://api.openai.com/v1</dd></dl></div>
@@ -49026,16 +49166,18 @@ function recordUsage(ctx, usage, round) {
49026
49166
  const prompt = usage.inputTokens;
49027
49167
  const cached = usage.cachedTokens;
49028
49168
  const out = usage.outputTokens;
49029
- if (typeof prompt === "number") ctx.session.stats.inputTokens += prompt;
49030
- ctx.session.stats.lastInputTokens = (typeof prompt === "number" ? prompt : 0) + (typeof cached === "number" ? cached : 0);
49169
+ const includesCached = ctx.protocol === "openai" || ctx.protocol === "responses";
49170
+ const total = (typeof prompt === "number" ? prompt : 0) + (!includesCached && typeof cached === "number" ? cached : 0);
49171
+ if (total > 0) ctx.session.stats.inputTokens += total;
49172
+ ctx.session.stats.lastInputTokens = total;
49031
49173
  if (typeof cached === "number") {
49032
49174
  ctx.session.stats.cachedTokens += cached;
49033
49175
  ctx.session.stats.cacheSamples += 1;
49034
49176
  }
49035
49177
  if (typeof out === "number") ctx.session.stats.outputTokens += out;
49036
- const hitPct = typeof prompt === "number" && typeof cached === "number" && prompt + cached > 0 ? Math.round(cached / (prompt + cached) * 100) : 0;
49178
+ const hitPct = typeof cached === "number" && total > 0 ? Math.round(cached / total * 100) : 0;
49037
49179
  ctx.log(
49038
- `[acp-usage] round ${round} input=${ctx.session.stats.lastInputTokens} cached=${cached ?? 0} (cache hit ${hitPct}%)`
49180
+ `[acp-usage] round ${round} input=${total} cached=${cached ?? 0} (cache hit ${hitPct}%)`
49039
49181
  );
49040
49182
  }
49041
49183
  async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adapter, systemPrompt, signal) {
@@ -49222,11 +49364,11 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
49222
49364
  const newBody = adapter.buildRequest(coreMessages, systemPrompt, requestBody);
49223
49365
  if (process.env.ACP_DUMP_REQ !== "0" && ctx.debug) {
49224
49366
  try {
49225
- const fs8 = await import("fs");
49367
+ const fs11 = await import("fs");
49226
49368
  const dumpDir = process.env.ACP_DUMP_DIR || `${process.env.HOME}/.local/state/billion-context/dumps`;
49227
- fs8.mkdirSync(dumpDir, { recursive: true });
49369
+ fs11.mkdirSync(dumpDir, { recursive: true });
49228
49370
  const sid = ctx.session.id ?? "unknown";
49229
- fs8.writeFileSync(`${dumpDir}/req-${Date.now()}-${sid}-REREQUEST.json`, JSON.stringify(newBody, null, 2));
49371
+ fs11.writeFileSync(`${dumpDir}/req-${Date.now()}-${sid}-REREQUEST.json`, JSON.stringify(newBody, null, 2));
49230
49372
  } catch {
49231
49373
  }
49232
49374
  }
@@ -49865,6 +50007,7 @@ function createOpenaiAdapter(requestBody) {
49865
50007
  const usage = opts?.usage ? {
49866
50008
  prompt_tokens: opts.usage.inputTokens,
49867
50009
  completion_tokens: opts.usage.outputTokens,
50010
+ total_tokens: (opts.usage.inputTokens ?? 0) + (opts.usage.outputTokens ?? 0),
49868
50011
  ...typeof opts.usage.cachedTokens === "number" ? { prompt_tokens_details: { cached_tokens: opts.usage.cachedTokens } } : {}
49869
50012
  } : null;
49870
50013
  return Buffer.concat([buildFinish(finishReason, usage), Buffer.from("data: [DONE]\n\n", "utf8")]);
@@ -50101,8 +50244,8 @@ ${systemPrompt}` : systemPrompt;
50101
50244
  } else if (type === "message_delta") {
50102
50245
  const u2 = data.usage ?? {};
50103
50246
  if (typeof u2.output_tokens === "number") roundOutput = u2.output_tokens;
50104
- if (typeof u2.input_tokens === "number") roundInput = u2.input_tokens;
50105
- if (typeof u2.cache_read_input_tokens === "number") roundCached = u2.cache_read_input_tokens;
50247
+ if (typeof u2.input_tokens === "number" && u2.input_tokens > 0) roundInput = u2.input_tokens;
50248
+ if (typeof u2.cache_read_input_tokens === "number" && u2.cache_read_input_tokens > 0) roundCached = u2.cache_read_input_tokens;
50106
50249
  const d = data.delta ?? {};
50107
50250
  if (typeof d.stop_reason === "string") stopReason = d.stop_reason;
50108
50251
  if (!usageYielded) {
@@ -50367,6 +50510,71 @@ function safeJsonParse(s3) {
50367
50510
  function isLoopbackAddress(addr) {
50368
50511
  return !!addr && (addr.startsWith("127.") || addr === "::1" || addr.startsWith("::ffff:127."));
50369
50512
  }
50513
+ function usageTotals(protocol, usage) {
50514
+ const num2 = (v2) => typeof v2 === "number" && Number.isFinite(v2) ? v2 : void 0;
50515
+ if (protocol === "anthropic") {
50516
+ const fresh = num2(usage["input_tokens"]);
50517
+ const read = num2(usage["cache_read_input_tokens"]);
50518
+ const creation = num2(usage["cache_creation_input_tokens"]);
50519
+ const any = fresh !== void 0 || read !== void 0 || creation !== void 0;
50520
+ return {
50521
+ total: any ? (fresh ?? 0) + (read ?? 0) + (creation ?? 0) : void 0,
50522
+ cached: read
50523
+ };
50524
+ }
50525
+ if (protocol === "openai") {
50526
+ return {
50527
+ total: num2(usage["prompt_tokens"]),
50528
+ cached: num2(usage["prompt_tokens_details"]?.["cached_tokens"])
50529
+ };
50530
+ }
50531
+ return {
50532
+ total: num2(usage["input_tokens"]),
50533
+ cached: num2(usage["input_tokens_details"]?.["cached_tokens"])
50534
+ };
50535
+ }
50536
+ var CONTEXT_OVERFLOW_PATTERNS = [
50537
+ /context_length_exceeded/i,
50538
+ /context length exceeded/i,
50539
+ /maximum context length/i,
50540
+ /max context length/i,
50541
+ /maximum context size/i,
50542
+ /exceeds the context window/i,
50543
+ /exceeded model token limit/i,
50544
+ /prompt is too long/i,
50545
+ /prompt_too_long/i,
50546
+ /prompt_is_too_long/i,
50547
+ /request_too_large/i,
50548
+ /token limit exceeded/i
50549
+ ];
50550
+ function toTokenNumber(s3) {
50551
+ const n = parseInt(s3.replace(/,/g, ""), 10);
50552
+ return Number.isFinite(n) && n >= 1e3 ? n : void 0;
50553
+ }
50554
+ function parseOverflowWindow(text) {
50555
+ let m2 = text.match(/>\s*(\d[\d,]*)\s*maximum/i);
50556
+ if (m2) return toTokenNumber(m2[1]);
50557
+ m2 = text.match(/maximum context length is (\d[\d,]*)/i) ?? text.match(/maximum context length of (\d[\d,]*)/i) ?? text.match(/maximum context size (?:is|of) (\d[\d,]*)/i) ?? text.match(/(?:maximum|max)\s+(?:context\s+)?length\s+(?:is\s+)?(\d[\d,]*)/i) ?? text.match(/limit of (\d[\d,]*)\s*token/i) ?? text.match(/(\d[\d,]*)\s*maximum\b/i);
50558
+ if (m2) return toTokenNumber(m2[1]);
50559
+ return void 0;
50560
+ }
50561
+ function inspectContextOverflow(status, bodyText) {
50562
+ const message = (bodyText ?? "").slice(0, 300);
50563
+ if (status !== 400 && status !== 413) return { isOverflow: false, message };
50564
+ if (!bodyText) return { isOverflow: false, message };
50565
+ const isOverflow = CONTEXT_OVERFLOW_PATTERNS.some((p2) => p2.test(bodyText));
50566
+ if (!isOverflow) return { isOverflow: false, message };
50567
+ return { isOverflow: true, window: parseOverflowWindow(bodyText), message };
50568
+ }
50569
+ function reserveOutputHeadroom(window2, maxOutput) {
50570
+ if (Number.isFinite(window2) && window2 > 0 && Number.isFinite(maxOutput) && maxOutput > 0 && maxOutput < window2) {
50571
+ return window2 - maxOutput;
50572
+ }
50573
+ return window2;
50574
+ }
50575
+ function shouldReserveOutputHeadroom(protocol) {
50576
+ return protocol !== "anthropic";
50577
+ }
50370
50578
 
50371
50579
  // src/stream-openai.ts
50372
50580
  function rewriteOpenaiJsonResponse(body, ctx) {
@@ -50526,8 +50734,10 @@ function extractKey(headers) {
50526
50734
  return "(no-key)";
50527
50735
  }
50528
50736
  function clientConversationHeader(headers) {
50529
- const names = ["x-claude-code-session-id", "x-session-affinity", "x-acp-session", "x-session-id", "x-opencode-session", "session-id", "session_id"];
50737
+ const pluginMarker = typeof headers["x-bili-plugin"] === "string";
50738
+ const names = ["x-bili-plugin-conversation", "x-claude-code-session-id", "x-session-affinity", "x-acp-session", "x-session-id", "x-opencode-session", "session-id", "session_id"];
50530
50739
  for (const name of names) {
50740
+ if (name === "x-bili-plugin-conversation" && !pluginMarker) continue;
50531
50741
  const v2 = headers[name];
50532
50742
  if (typeof v2 === "string" && v2.trim().length > 0) return v2.trim();
50533
50743
  }
@@ -50542,13 +50752,351 @@ function affinityToken(identity) {
50542
50752
  return identity.clientProvided ? identity.value : void 0;
50543
50753
  }
50544
50754
 
50755
+ // src/plugin.ts
50756
+ import { fileURLToPath as fileURLToPath2 } from "url";
50757
+ import fs2 from "fs";
50758
+ import path5 from "path";
50759
+ var PLUGIN_AGENT_HEADER = "x-bili-plugin";
50760
+ var PLUGIN_CONVERSATION_HEADER = "x-bili-plugin-conversation";
50761
+ var PLUGIN_CONTEXT_WINDOW_HEADER = "x-bili-plugin-context-window";
50762
+ var PLUGIN_PROTOCOL_VERSION = 1;
50763
+ var VERSION = (() => {
50764
+ try {
50765
+ const here = fileURLToPath2(import.meta.url);
50766
+ const pkg = path5.join(path5.dirname(here), "..", "package.json");
50767
+ return JSON.parse(fs2.readFileSync(pkg, "utf8")).version ?? "dev";
50768
+ } catch {
50769
+ return "dev";
50770
+ }
50771
+ })();
50772
+ function headerValue(headers, name) {
50773
+ const v2 = headers[name];
50774
+ const s3 = typeof v2 === "string" ? v2 : Array.isArray(v2) ? v2[0] : void 0;
50775
+ const t = s3?.trim();
50776
+ return t && t.length > 0 ? t : void 0;
50777
+ }
50778
+ function pluginAgentHeader(headers) {
50779
+ return headerValue(headers, PLUGIN_AGENT_HEADER);
50780
+ }
50781
+ function pluginConversationHeader(headers) {
50782
+ return headerValue(headers, PLUGIN_CONVERSATION_HEADER);
50783
+ }
50784
+ function pluginContextWindowHeader(headers) {
50785
+ const raw = headerValue(headers, PLUGIN_CONTEXT_WINDOW_HEADER);
50786
+ if (raw === void 0) return void 0;
50787
+ const n = Number.parseInt(raw, 10);
50788
+ return Number.isFinite(n) && n > 0 ? n : void 0;
50789
+ }
50790
+ function pluginReportedContextWindow(headers) {
50791
+ return pluginAgentHeader(headers) !== void 0 ? pluginContextWindowHeader(headers) : void 0;
50792
+ }
50793
+ var MAX_PLUGIN_CONVERSATIONS = 1024;
50794
+ var conversations = /* @__PURE__ */ new Map();
50795
+ var remembered = /* @__PURE__ */ new Map();
50796
+ function recordPluginSession(conversationId2, sessionId) {
50797
+ conversations.delete(conversationId2);
50798
+ conversations.set(conversationId2, { sessionId, lastSeen: Date.now() });
50799
+ if (conversations.size > MAX_PLUGIN_CONVERSATIONS) {
50800
+ const oldest = conversations.keys().next().value;
50801
+ if (oldest !== void 0) conversations.delete(oldest);
50802
+ }
50803
+ }
50804
+ function rememberPluginMessages(sessionId, processed, original, nudge) {
50805
+ const staleSessionIds = new Set(
50806
+ [...remembered.keys()].filter((id) => id === sessionId || !peekSession(id))
50807
+ );
50808
+ for (const id of staleSessionIds) remembered.delete(id);
50809
+ remembered.set(sessionId, { processed, original, nudge });
50810
+ }
50811
+ var MAX_PENDING_REGISTERS = 64;
50812
+ var pendingRegisters = [];
50813
+ function queuePluginRegister(conversationId2, agent, identity) {
50814
+ if (!identity) {
50815
+ for (let i = 0; i < pendingRegisters.length; i++) {
50816
+ if (pendingRegisters[i].conversationId === conversationId2) {
50817
+ pendingRegisters.splice(i, 1);
50818
+ break;
50819
+ }
50820
+ }
50821
+ pendingRegisters.push({ conversationId: conversationId2, agent, ts: Date.now() });
50822
+ while (pendingRegisters.length > MAX_PENDING_REGISTERS) pendingRegisters.shift();
50823
+ } else {
50824
+ registeredIds.set(conversationId2, agent);
50825
+ while (registeredIds.size > MAX_PENDING_REGISTERS) {
50826
+ const oldest = registeredIds.keys().next().value;
50827
+ if (oldest !== void 0) registeredIds.delete(oldest);
50828
+ }
50829
+ }
50830
+ }
50831
+ var PENDING_REGISTER_TTL_MS = 10 * 60 * 1e3;
50832
+ function takePendingPluginRegister() {
50833
+ const now = Date.now();
50834
+ while (pendingRegisters.length > 0 && now - pendingRegisters[0].ts > PENDING_REGISTER_TTL_MS) {
50835
+ pendingRegisters.shift();
50836
+ }
50837
+ return pendingRegisters.shift();
50838
+ }
50839
+ var registeredIds = /* @__PURE__ */ new Map();
50840
+ function consumePluginRegisterFor(conversationId2) {
50841
+ const agent = registeredIds.get(conversationId2);
50842
+ if (agent !== void 0) registeredIds.delete(conversationId2);
50843
+ return agent;
50844
+ }
50845
+ function handlePluginRegister(payload, res) {
50846
+ let parsed;
50847
+ try {
50848
+ parsed = JSON.parse(payload);
50849
+ } catch {
50850
+ res.writeHead(400, { "content-type": "application/json" });
50851
+ res.end(JSON.stringify({ ok: false, error: "invalid JSON body" }));
50852
+ return;
50853
+ }
50854
+ const conversationId2 = typeof parsed.conversationId === "string" ? parsed.conversationId.trim() : "";
50855
+ if (!conversationId2) {
50856
+ res.writeHead(400, { "content-type": "application/json" });
50857
+ res.end(JSON.stringify({ ok: false, error: "conversationId is required" }));
50858
+ return;
50859
+ }
50860
+ const agent = typeof parsed.agent === "string" && parsed.agent.trim() ? parsed.agent.trim() : "launcher";
50861
+ queuePluginRegister(conversationId2, agent, parsed.identity === true);
50862
+ res.end(JSON.stringify({ ok: true, conversationId: conversationId2, agent }));
50863
+ }
50864
+ function handlePluginManifest(res) {
50865
+ res.writeHead(200, { "content-type": "application/json" });
50866
+ res.end(JSON.stringify({
50867
+ ok: true,
50868
+ protocolVersion: PLUGIN_PROTOCOL_VERSION,
50869
+ proxy: "billion-context",
50870
+ version: VERSION,
50871
+ toolNames: [...PROXY_TOOL_NAMES],
50872
+ tools: {
50873
+ anthropic: ACP_TOOLS_ANTHROPIC,
50874
+ openai: ACP_TOOLS_OPENAI,
50875
+ responses: ACP_TOOLS_RESPONSES
50876
+ },
50877
+ headers: { agent: PLUGIN_AGENT_HEADER, conversation: PLUGIN_CONVERSATION_HEADER, contextWindow: PLUGIN_CONTEXT_WINDOW_HEADER },
50878
+ toolEndpoint: "/__bili/plugin/tool",
50879
+ statusEndpoint: "/__bili/plugin/status"
50880
+ }));
50881
+ }
50882
+ function handlePluginStatus(conversationId2, res) {
50883
+ const entry = conversations.get(conversationId2);
50884
+ const session = entry ? peekSession(entry.sessionId) : void 0;
50885
+ if (!entry || !session) {
50886
+ res.writeHead(404, { "content-type": "application/json" });
50887
+ res.end(JSON.stringify({ ok: false, error: "unknown plugin conversation" }));
50888
+ return;
50889
+ }
50890
+ entry.lastSeen = Date.now();
50891
+ const limit = session.metadata.effectiveContextLimit;
50892
+ res.writeHead(200, { "content-type": "application/json" });
50893
+ res.end(JSON.stringify({
50894
+ ok: true,
50895
+ conversationId: conversationId2,
50896
+ sessionId: session.id,
50897
+ label: session.meta.label ?? null,
50898
+ pluginAgent: session.metadata.pluginAgent ?? null,
50899
+ contextLimit: typeof limit === "number" ? limit : null,
50900
+ contextTokens: session.stats.lastInputTokens,
50901
+ inputTokens: session.stats.inputTokens,
50902
+ outputTokens: session.stats.outputTokens,
50903
+ cachedTokens: session.stats.cachedTokens,
50904
+ requests: session.stats.requests,
50905
+ blocks: session.state.blocks.map((b2) => ({ id: b2.blockId, tier: b2.tier, active: b2.active })),
50906
+ lastSeen: session.lastSeen
50907
+ }));
50908
+ }
50909
+ async function handlePluginTool(payload, res, deps) {
50910
+ let parsed;
50911
+ try {
50912
+ parsed = JSON.parse(payload);
50913
+ } catch {
50914
+ res.writeHead(400, { "content-type": "application/json" });
50915
+ res.end(JSON.stringify({ ok: false, error: "invalid JSON body" }));
50916
+ return;
50917
+ }
50918
+ const conversationId2 = typeof parsed.conversationId === "string" ? parsed.conversationId.trim() : "";
50919
+ const tool = typeof parsed.tool === "string" ? parsed.tool : "";
50920
+ if (!conversationId2) {
50921
+ res.writeHead(400, { "content-type": "application/json" });
50922
+ res.end(JSON.stringify({ ok: false, error: `conversationId is required (send the same value as the ${PLUGIN_CONVERSATION_HEADER} header)` }));
50923
+ return;
50924
+ }
50925
+ if (!PROXY_TOOL_NAMES.has(tool)) {
50926
+ res.writeHead(400, { "content-type": "application/json" });
50927
+ res.end(JSON.stringify({ ok: false, error: `unknown tool "${tool}" (expected one of: ${[...PROXY_TOOL_NAMES].join(", ")})` }));
50928
+ return;
50929
+ }
50930
+ const entry = conversations.get(conversationId2);
50931
+ const session = entry ? peekSession(entry.sessionId) : void 0;
50932
+ if (!entry || !session) {
50933
+ res.writeHead(404, { "content-type": "application/json" });
50934
+ res.end(JSON.stringify({ ok: false, error: "unknown plugin conversation (no model request has arrived with this conversation id yet)" }));
50935
+ return;
50936
+ }
50937
+ entry.lastSeen = Date.now();
50938
+ const args = parsed.args && typeof parsed.args === "object" ? parsed.args : {};
50939
+ const callId = `plugin_${Date.now().toString(36)}`;
50940
+ acquireInFlight(session);
50941
+ let result;
50942
+ try {
50943
+ result = await withSessionLock(session, async () => {
50944
+ const mem = remembered.get(session.id);
50945
+ const messages = mem ? mem.processed.length > 0 ? mem.processed : mem.original : [];
50946
+ return executeProxyTool(tool, args, {
50947
+ core: deps.core,
50948
+ config: deps.config,
50949
+ messages,
50950
+ session,
50951
+ log: (m2) => deps.log("info", `[${session.id}] [plugin] ${m2}`),
50952
+ nudge: mem?.nudge
50953
+ }, callId);
50954
+ });
50955
+ } catch (err2) {
50956
+ releaseInFlight(session);
50957
+ deps.log("warn", `[${session.id}] [plugin] tool ${tool} threw: ${String(err2)}`);
50958
+ res.writeHead(500, { "content-type": "application/json" });
50959
+ res.end(JSON.stringify({ ok: false, error: String(err2) }));
50960
+ return;
50961
+ }
50962
+ releaseInFlight(session);
50963
+ markDirty(session);
50964
+ deps.log("info", `[${session.id}] [plugin] tool ${tool} executed via plugin (${result.length} chars)`);
50965
+ res.writeHead(200, { "content-type": "application/json" });
50966
+ res.end(JSON.stringify({ ok: true, tool, conversationId: conversationId2, result }));
50967
+ }
50968
+ function num(v2) {
50969
+ return typeof v2 === "number" && Number.isFinite(v2) ? v2 : void 0;
50970
+ }
50971
+ function usageFromSseEvent(obj) {
50972
+ const type = obj["type"];
50973
+ if (type === "message_start") {
50974
+ const usage2 = obj["message"]?.["usage"];
50975
+ if (!usage2) return void 0;
50976
+ const input = num(usage2["input_tokens"]);
50977
+ if (input === void 0) return void 0;
50978
+ return { inputTokens: input, cachedTokens: num(usage2["cache_read_input_tokens"]) };
50979
+ }
50980
+ if (type === "message_delta") {
50981
+ const usage2 = obj["usage"];
50982
+ if (!usage2) return void 0;
50983
+ const input = num(usage2["input_tokens"]);
50984
+ return { inputTokens: input && input > 0 ? input : void 0, outputTokens: num(usage2["output_tokens"]) };
50985
+ }
50986
+ if (type === "response.completed") {
50987
+ const usage2 = obj["response"]?.["usage"];
50988
+ if (!usage2) return void 0;
50989
+ return {
50990
+ inputTokens: num(usage2["input_tokens"]),
50991
+ outputTokens: num(usage2["output_tokens"]),
50992
+ cachedTokens: num(usage2["input_tokens_details"]?.["cached_tokens"])
50993
+ };
50994
+ }
50995
+ const usage = obj["usage"];
50996
+ if (usage && (num(usage["prompt_tokens"]) !== void 0 || num(usage["completion_tokens"]) !== void 0)) {
50997
+ return {
50998
+ inputTokens: num(usage["prompt_tokens"]),
50999
+ outputTokens: num(usage["completion_tokens"]),
51000
+ cachedTokens: num(usage["prompt_tokens_details"]?.["cached_tokens"])
51001
+ };
51002
+ }
51003
+ return void 0;
51004
+ }
51005
+ function applyUsageSample(session, sample, protocol) {
51006
+ const includesCached = protocol === "openai" || protocol === "responses";
51007
+ if (sample.cachedTokens !== void 0) {
51008
+ session.stats.cachedTokens += sample.cachedTokens;
51009
+ session.stats.cacheSamples += 1;
51010
+ }
51011
+ if (sample.inputTokens !== void 0) {
51012
+ const total = sample.inputTokens + (!includesCached && sample.cachedTokens !== void 0 ? sample.cachedTokens : 0);
51013
+ session.stats.inputTokens += total;
51014
+ session.stats.lastInputTokens = total;
51015
+ }
51016
+ if (sample.outputTokens !== void 0) session.stats.outputTokens += sample.outputTokens;
51017
+ }
51018
+ function mergeUsageSample(acc, sample) {
51019
+ if (sample.inputTokens !== void 0) acc.inputTokens = sample.inputTokens;
51020
+ if (sample.cachedTokens !== void 0) acc.cachedTokens = sample.cachedTokens;
51021
+ if (sample.outputTokens !== void 0) acc.outputTokens = sample.outputTokens;
51022
+ }
51023
+ async function pipeThroughWithUsage(stream2, res, session, protocol) {
51024
+ const reader = stream2.getReader();
51025
+ const decoder = new TextDecoder("utf-8");
51026
+ let buf = "";
51027
+ const acc = {};
51028
+ try {
51029
+ for (; ; ) {
51030
+ const { done, value } = await reader.read();
51031
+ if (done) break;
51032
+ if (value && value.length > 0) {
51033
+ if (!res.write(Buffer.from(value))) {
51034
+ await new Promise((r) => res.once("drain", () => r()));
51035
+ }
51036
+ buf = normalizeSseLineEndings(buf + decoder.decode(value, { stream: true }));
51037
+ let idx;
51038
+ while ((idx = buf.indexOf("\n\n")) !== -1) {
51039
+ const rawEvent = buf.slice(0, idx);
51040
+ buf = buf.slice(idx + 2);
51041
+ const dataLines = rawEvent.split("\n").filter((l) => l.startsWith("data:"));
51042
+ if (dataLines.length === 0) continue;
51043
+ const jsonStr = dataLines.map((l) => l.slice(5).replace(/^ /, "")).join("\n").trim();
51044
+ if (!jsonStr || jsonStr === "[DONE]") continue;
51045
+ try {
51046
+ const ev = JSON.parse(jsonStr);
51047
+ const sample = usageFromSseEvent(ev);
51048
+ if (sample) mergeUsageSample(acc, sample);
51049
+ } catch {
51050
+ }
51051
+ }
51052
+ }
51053
+ if (res.destroyed || res.writableEnded) break;
51054
+ }
51055
+ if (acc.inputTokens !== void 0 || acc.outputTokens !== void 0 || acc.cachedTokens !== void 0) {
51056
+ applyUsageSample(session, acc, protocol);
51057
+ markDirty(session);
51058
+ }
51059
+ } finally {
51060
+ reader.releaseLock();
51061
+ res.end();
51062
+ }
51063
+ }
51064
+ async function pipePluginJson(stream2, res, session, protocol) {
51065
+ const reader = stream2.getReader();
51066
+ const chunks = [];
51067
+ for (; ; ) {
51068
+ const { done, value } = await reader.read();
51069
+ if (done) break;
51070
+ if (value && value.length > 0) chunks.push(Buffer.from(value));
51071
+ }
51072
+ reader.releaseLock();
51073
+ const text = Buffer.concat(chunks).toString("utf8");
51074
+ try {
51075
+ const json = JSON.parse(text);
51076
+ const usage = json["usage"];
51077
+ if (usage) {
51078
+ const input = num(usage["prompt_tokens"]) ?? num(usage["input_tokens"]);
51079
+ if (input !== void 0) {
51080
+ applyUsageSample(session, {
51081
+ inputTokens: input,
51082
+ outputTokens: num(usage["completion_tokens"]) ?? num(usage["output_tokens"]),
51083
+ cachedTokens: num(usage["prompt_tokens_details"]?.["cached_tokens"]) ?? num(usage["input_tokens_details"]?.["cached_tokens"]) ?? num(usage["cache_read_input_tokens"])
51084
+ }, protocol);
51085
+ markDirty(session);
51086
+ }
51087
+ }
51088
+ } catch {
51089
+ }
51090
+ res.end(text);
51091
+ }
51092
+
50545
51093
  // src/mitm.ts
50546
51094
  import tls3 from "tls";
50547
51095
 
50548
51096
  // src/ca.ts
50549
51097
  var import_node_forge = __toESM(require_lib(), 1);
50550
- import fs2 from "fs";
50551
- import path5 from "path";
51098
+ import fs3 from "fs";
51099
+ import path6 from "path";
50552
51100
  import tls2 from "tls";
50553
51101
  var ROOT_CERT_FILE = "root-ca.pem";
50554
51102
  var ROOT_KEY_FILE = "root-ca-key.pem";
@@ -50572,7 +51120,7 @@ function collectSystemCaPems(env = process.env) {
50572
51120
  const seen = /* @__PURE__ */ new Set();
50573
51121
  const pushFile = (file) => {
50574
51122
  try {
50575
- const text = fs2.readFileSync(file, "utf8");
51123
+ const text = fs3.readFileSync(file, "utf8");
50576
51124
  if (!text.includes("BEGIN CERTIFICATE") || seen.has(text)) return false;
50577
51125
  seen.add(text);
50578
51126
  pems.push(text);
@@ -50594,7 +51142,7 @@ function writeCombinedBundle() {
50594
51142
  for (const pem of tls2.rootCertificates) certs.add(pem.trim());
50595
51143
  certs.add(rootCertPem.trim());
50596
51144
  const body = [...certs].map((pem) => pem.endsWith("\n") ? pem : pem + "\n").join("");
50597
- fs2.writeFileSync(path5.join(caDir(), COMBINED_CA_FILE), body, { mode: 420 });
51145
+ fs3.writeFileSync(path6.join(caDir(), COMBINED_CA_FILE), body, { mode: 420 });
50598
51146
  }
50599
51147
  function generateRootCA() {
50600
51148
  const keys = import_node_forge.default.pki.rsa.generateKeyPair({ bits: 2048 });
@@ -50627,20 +51175,20 @@ function ensureRootCA() {
50627
51175
  return;
50628
51176
  }
50629
51177
  const dir = caDir();
50630
- fs2.mkdirSync(dir, { recursive: true });
50631
- const certPath = path5.join(dir, ROOT_CERT_FILE);
50632
- const keyPath = path5.join(dir, ROOT_KEY_FILE);
50633
- if (fs2.existsSync(certPath) && fs2.existsSync(keyPath)) {
50634
- rootCertPem = fs2.readFileSync(certPath, "utf8");
50635
- rootKeyPem = fs2.readFileSync(keyPath, "utf8");
51178
+ fs3.mkdirSync(dir, { recursive: true });
51179
+ const certPath = path6.join(dir, ROOT_CERT_FILE);
51180
+ const keyPath = path6.join(dir, ROOT_KEY_FILE);
51181
+ if (fs3.existsSync(certPath) && fs3.existsSync(keyPath)) {
51182
+ rootCertPem = fs3.readFileSync(certPath, "utf8");
51183
+ rootKeyPem = fs3.readFileSync(keyPath, "utf8");
50636
51184
  rootCert = import_node_forge.default.pki.certificateFromPem(rootCertPem);
50637
51185
  rootKey = import_node_forge.default.pki.privateKeyFromPem(rootKeyPem);
50638
51186
  writeCombinedBundle();
50639
51187
  return;
50640
51188
  }
50641
51189
  const { cert, key } = generateRootCA();
50642
- fs2.writeFileSync(certPath, cert, { mode: 420 });
50643
- fs2.writeFileSync(keyPath, key, { mode: 384 });
51190
+ fs3.writeFileSync(certPath, cert, { mode: 420 });
51191
+ fs3.writeFileSync(keyPath, key, { mode: 384 });
50644
51192
  rootCertPem = cert;
50645
51193
  rootKeyPem = key;
50646
51194
  rootCert = import_node_forge.default.pki.certificateFromPem(cert);
@@ -50687,20 +51235,20 @@ function getSecureContext(host) {
50687
51235
  }
50688
51236
 
50689
51237
  // src/discover.ts
50690
- import fs4 from "fs";
51238
+ import fs5 from "fs";
50691
51239
  import os2 from "os";
50692
- import path7 from "path";
51240
+ import path8 from "path";
50693
51241
 
50694
51242
  // src/client-config.ts
50695
- import fs3 from "fs";
51243
+ import fs4 from "fs";
50696
51244
  import os from "os";
50697
- import path6 from "path";
51245
+ import path7 from "path";
50698
51246
  function nonEmpty2(s3) {
50699
51247
  return typeof s3 === "string" && s3.trim().length > 0;
50700
51248
  }
50701
51249
  function readJsonObject(filePath) {
50702
51250
  try {
50703
- const txt = fs3.readFileSync(filePath, "utf8");
51251
+ const txt = fs4.readFileSync(filePath, "utf8");
50704
51252
  const parsed = JSON.parse(txt);
50705
51253
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
50706
51254
  } catch {
@@ -50709,12 +51257,12 @@ function readJsonObject(filePath) {
50709
51257
  }
50710
51258
  function resolvePiHome(env) {
50711
51259
  const h = os.homedir();
50712
- return nonEmpty2(env.PI_CODING_AGENT_DIR) ? env.PI_CODING_AGENT_DIR : nonEmpty2(env.PI_HOME) ? env.PI_HOME : path6.join(h, ".pi", "agent");
51260
+ return nonEmpty2(env.PI_CODING_AGENT_DIR) ? env.PI_CODING_AGENT_DIR : nonEmpty2(env.PI_HOME) ? env.PI_HOME : path7.join(h, ".pi", "agent");
50713
51261
  }
50714
51262
  function readClaudeSettings(homeDir, cwd) {
50715
51263
  const files = [
50716
- path6.join(homeDir, ".claude", "settings.json"),
50717
- path6.join(cwd, ".claude", "settings.json")
51264
+ path7.join(homeDir, ".claude", "settings.json"),
51265
+ path7.join(cwd, ".claude", "settings.json")
50718
51266
  ];
50719
51267
  let anthropicBaseUrl;
50720
51268
  for (const f2 of files) {
@@ -50757,17 +51305,17 @@ function parseCodexToml(text) {
50757
51305
  return result;
50758
51306
  }
50759
51307
  function readCodexConfig(codexHome) {
50760
- const cfgPath = path6.join(codexHome, "config.toml");
51308
+ const cfgPath = path7.join(codexHome, "config.toml");
50761
51309
  let text;
50762
51310
  try {
50763
- text = fs3.readFileSync(cfgPath, "utf8");
51311
+ text = fs4.readFileSync(cfgPath, "utf8");
50764
51312
  } catch {
50765
51313
  return { providers: {} };
50766
51314
  }
50767
51315
  return parseCodexToml(text);
50768
51316
  }
50769
51317
  function readPiConfig(piHome) {
50770
- const cfgPath = path6.join(piHome, "models.json");
51318
+ const cfgPath = path7.join(piHome, "models.json");
50771
51319
  const obj = readJsonObject(cfgPath);
50772
51320
  const providers = {};
50773
51321
  const rawProviders = obj?.providers;
@@ -50798,10 +51346,10 @@ function parseZcodeConfig(obj) {
50798
51346
  return result;
50799
51347
  }
50800
51348
  function readZcodeConfig(zcodeHome) {
50801
- const cfgPath = path6.join(zcodeHome, "v2", "config.json");
51349
+ const cfgPath = path7.join(zcodeHome, "v2", "config.json");
50802
51350
  let txt;
50803
51351
  try {
50804
- txt = fs3.readFileSync(cfgPath, "utf8");
51352
+ txt = fs4.readFileSync(cfgPath, "utf8");
50805
51353
  } catch {
50806
51354
  return { providers: {} };
50807
51355
  }
@@ -50817,10 +51365,10 @@ function loadClientConfig(env, cwd) {
50817
51365
  const home = os.homedir();
50818
51366
  const config = {};
50819
51367
  config.claude = readClaudeSettings(home, cwd);
50820
- const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path6.join(home, ".codex");
51368
+ const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path7.join(home, ".codex");
50821
51369
  config.codex = readCodexConfig(codexHome);
50822
51370
  config.pi = readPiConfig(resolvePiHome(env));
50823
- const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path6.join(home, ".zcode");
51371
+ const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path7.join(home, ".zcode");
50824
51372
  config.zcode = readZcodeConfig(zcodeHome);
50825
51373
  return config;
50826
51374
  }
@@ -50863,21 +51411,21 @@ function extractHttpsHosts(config) {
50863
51411
  }
50864
51412
  function configFilePaths(env) {
50865
51413
  const home = os2.homedir();
50866
- const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path7.join(home, ".codex");
50867
- const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path7.join(home, ".zcode");
51414
+ const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path8.join(home, ".codex");
51415
+ const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path8.join(home, ".zcode");
50868
51416
  return [
50869
- path7.join(home, ".claude", "settings.json"),
50870
- path7.join(process.cwd(), ".claude", "settings.json"),
50871
- path7.join(codexHome, "config.toml"),
50872
- path7.join(resolvePiHome(env), "models.json"),
50873
- path7.join(zcodeHome, "v2", "config.json")
51417
+ path8.join(home, ".claude", "settings.json"),
51418
+ path8.join(process.cwd(), ".claude", "settings.json"),
51419
+ path8.join(codexHome, "config.toml"),
51420
+ path8.join(resolvePiHome(env), "models.json"),
51421
+ path8.join(zcodeHome, "v2", "config.json")
50874
51422
  ];
50875
51423
  }
50876
51424
  function readMtimes(paths) {
50877
51425
  const mtimes = /* @__PURE__ */ new Map();
50878
51426
  for (const p2 of paths) {
50879
51427
  try {
50880
- const st2 = fs4.statSync(p2);
51428
+ const st2 = fs5.statSync(p2);
50881
51429
  mtimes.set(p2, st2.mtimeMs);
50882
51430
  } catch {
50883
51431
  }
@@ -50891,21 +51439,21 @@ function mtimesEqual(a, b2) {
50891
51439
  }
50892
51440
  return true;
50893
51441
  }
50894
- var cache2 = null;
51442
+ var cache3 = null;
50895
51443
  function discoverMitmDomains(env = process.env) {
50896
51444
  const now = Date.now();
50897
- if (cache2 && now - cache2.checkedAt < TTL_MS2) {
50898
- return cache2.domains;
51445
+ if (cache3 && now - cache3.checkedAt < TTL_MS2) {
51446
+ return cache3.domains;
50899
51447
  }
50900
51448
  const paths = configFilePaths(env);
50901
51449
  const mtimes = readMtimes(paths);
50902
- if (cache2 && mtimesEqual(mtimes, cache2.mtimes)) {
50903
- cache2.checkedAt = now;
50904
- return cache2.domains;
51450
+ if (cache3 && mtimesEqual(mtimes, cache3.mtimes)) {
51451
+ cache3.checkedAt = now;
51452
+ return cache3.domains;
50905
51453
  }
50906
51454
  const config = loadClientConfig(env, process.cwd());
50907
51455
  const domains = extractHttpsHosts(config);
50908
- cache2 = { checkedAt: now, mtimes, domains };
51456
+ cache3 = { checkedAt: now, mtimes, domains };
50909
51457
  return domains;
50910
51458
  }
50911
51459
 
@@ -51841,11 +52389,32 @@ async function startServer(opts) {
51841
52389
  }
51842
52390
  }
51843
52391
  });
52392
+ server.on("upgrade", (req, socket) => {
52393
+ log2("info", `[ws] rejected ${req.method} ${req.url ?? ""} host=${req.headers.host ?? "?"} with 426`);
52394
+ socket.on("error", () => {
52395
+ });
52396
+ const body = JSON.stringify({ error: "WebSocket upgrades are not supported; use HTTP POST" });
52397
+ socket.end(
52398
+ `HTTP/1.1 426 Upgrade Required\r
52399
+ Connection: close\r
52400
+ Content-Type: application/json\r
52401
+ Content-Length: ${Buffer.byteLength(body)}\r
52402
+ \r
52403
+ ` + body
52404
+ );
52405
+ });
51844
52406
  if (opts.mitm.enabled) {
51845
52407
  setupMitm(server, opts.mitm.domains, (msg2) => log2("info", msg2), (host) => resolveProxy(opts.routes, opts.proxy, `https://${host}`, opts.proxyFallback));
51846
52408
  }
51847
52409
  server.listen(opts.port, opts.host, () => {
51848
52410
  const displayHost = opts.host === "0.0.0.0" ? "localhost" : opts.host;
52411
+ try {
52412
+ fs6.mkdirSync(stateDir(), { recursive: true });
52413
+ const originHost = opts.host === "0.0.0.0" || opts.host === "::" || opts.host === "localhost" ? "127.0.0.1" : opts.host.includes(":") && !opts.host.startsWith("[") ? `[${opts.host}]` : opts.host;
52414
+ fs6.writeFileSync(proxyOriginFile(), `http://${originHost}:${server.address() === null ? opts.port : server.address().port}
52415
+ `);
52416
+ } catch {
52417
+ }
51849
52418
  const nOverrides = Object.keys(opts.routes).length;
51850
52419
  log2(
51851
52420
  "info",
@@ -52018,10 +52587,37 @@ async function handle(req, res, opts, core, config, log2) {
52018
52587
  }
52019
52588
  return;
52020
52589
  }
52021
- if (req.headers.upgrade === "websocket") {
52022
- res.writeHead(426, { "content-type": "application/json" });
52023
- res.end(JSON.stringify({ error: "WebSocket upgrades are not supported; use HTTP POST" }));
52024
- return;
52590
+ if (req.method === "GET" && req.url === "/__bili/plugin/manifest") return handlePluginManifest(res);
52591
+ if (req.method === "GET" && req.url?.startsWith("/__bili/plugin/status")) {
52592
+ const query = req.url.slice(req.url.indexOf("?") + 1);
52593
+ const conversationId2 = new URLSearchParams(query).get("conversationId")?.trim() ?? "";
52594
+ if (!conversationId2) {
52595
+ res.writeHead(400, { "content-type": "application/json" });
52596
+ res.end(JSON.stringify({ ok: false, error: "conversationId query parameter is required" }));
52597
+ return;
52598
+ }
52599
+ return handlePluginStatus(conversationId2, res);
52600
+ }
52601
+ if (req.method === "POST" && req.url === "/__bili/plugin/tool") {
52602
+ try {
52603
+ const body = await readBody(req);
52604
+ return await handlePluginTool(body.toString("utf8"), res, { core, config, log: log2 });
52605
+ } catch (err2) {
52606
+ res.writeHead(err2 instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" });
52607
+ res.end(JSON.stringify({ ok: false, error: String(err2) }));
52608
+ return;
52609
+ }
52610
+ }
52611
+ if (req.method === "POST" && req.url === "/__bili/plugin/register") {
52612
+ try {
52613
+ const body = await readBody(req);
52614
+ handlePluginRegister(body.toString("utf8"), res);
52615
+ return;
52616
+ } catch (err2) {
52617
+ res.writeHead(err2 instanceof BodyTooLargeError ? 413 : 400, { "content-type": "application/json" });
52618
+ res.end(JSON.stringify({ ok: false, error: String(err2) }));
52619
+ return;
52620
+ }
52025
52621
  }
52026
52622
  let bodyBuffer;
52027
52623
  let urlPath;
@@ -52038,7 +52634,7 @@ async function handle(req, res, opts, core, config, log2) {
52038
52634
  upstreamOrigin = route ? route.upstream : /^https?:\/\//i.test(url) ? new URL(url).origin : opts.upstream;
52039
52635
  protocol = route?.explicitProtocol ?? (req.method === "POST" && bodyBuffer.length > 0 ? urlPath.endsWith("/chat/completions") ? "openai" : urlPath.endsWith("/v1/messages") || urlPath.endsWith("/messages") ? "anthropic" : urlPath.endsWith("/responses") || responsesCompact ? "responses" : null : null);
52040
52636
  if (protocol !== null && bodyBuffer.length > 0) {
52041
- const decoded = await decodeRequestBody(headerValue(req, "content-encoding"), bodyBuffer, MAX_REQUEST_BYTES);
52637
+ const decoded = await decodeRequestBody(headerValue2(req, "content-encoding"), bodyBuffer, MAX_REQUEST_BYTES);
52042
52638
  bodyBuffer = decoded.body;
52043
52639
  if (decoded.decoded) delete req.headers["content-encoding"];
52044
52640
  }
@@ -52071,11 +52667,11 @@ async function handle(req, res, opts, core, config, log2) {
52071
52667
  log2("info", `[debug] INCOMING previous_response_id=${hasPrev ? String(p2.previous_response_id).slice(0, 16) : "absent"} input_items=${inLen} instructions=${p2.instructions !== void 0 ? "present" : "absent"}`);
52072
52668
  const rawDir = `${stateDir()}/raw`;
52073
52669
  try {
52074
- fs5.mkdirSync(rawDir, { recursive: true });
52670
+ fs6.mkdirSync(rawDir, { recursive: true });
52075
52671
  } catch {
52076
52672
  }
52077
52673
  const hdrs = Object.entries(req.headers).filter(([k2]) => !/authorization|x-api-key|cookie/i.test(k2)).map(([k2, v2]) => `${k2}: ${Array.isArray(v2) ? v2.join(",") : v2}`).join("\n");
52078
- fs5.writeFileSync(`${rawDir}/${Date.now()}-INCOMING.txt`, `${req.method} ${req.url}
52674
+ fs6.writeFileSync(`${rawDir}/${Date.now()}-INCOMING.txt`, `${req.method} ${req.url}
52079
52675
  ${hdrs}
52080
52676
 
52081
52677
  ${bodyBuffer.toString("utf8")}`);
@@ -52088,7 +52684,7 @@ ${bodyBuffer.toString("utf8")}`);
52088
52684
  const model = parsed.model;
52089
52685
  if (model) {
52090
52686
  const embeddedUrl = route?.rewrittenUrl;
52091
- let native = resolveContextLimit(opts.routes, embeddedUrl, model);
52687
+ let native = pluginReportedContextWindow(req.headers) ?? resolveContextLimit(opts.routes, embeddedUrl, model);
52092
52688
  if (!native && embeddedUrl) {
52093
52689
  const host = (() => {
52094
52690
  try {
@@ -52105,7 +52701,9 @@ ${bodyBuffer.toString("utf8")}`);
52105
52701
  }
52106
52702
  let prepared = null;
52107
52703
  if (!opts.passthrough && protocol && parsed && typeof parsed === "object") {
52108
- const sessionHeader = headerValue(req, opts.sessionHeader);
52704
+ const sessionHeader = headerValue2(req, opts.sessionHeader);
52705
+ let pluginAgent = pluginAgentHeader(req.headers);
52706
+ let pluginConversation = pluginConversationHeader(req.headers);
52109
52707
  const clientConv = clientConversationHeader(req.headers);
52110
52708
  const convHeader = clientConv ?? sessionHeader;
52111
52709
  const responsesIdentity = protocol === "responses" ? conversationIdentityResponses(parsed, convHeader) : void 0;
@@ -52121,11 +52719,51 @@ ${bodyBuffer.toString("utf8")}`);
52121
52719
  });
52122
52720
  const clientLabel = responsesIdentity?.clientProvided ? responsesIdentity.value : clientConversationHeader(req.headers);
52123
52721
  const session = getSession(sessionId, { protocol, upstreamOrigin, label: clientLabel ?? void 0 });
52722
+ if (!pluginAgent) {
52723
+ const identityAgent = consumePluginRegisterFor(clientConv ?? conversation);
52724
+ if (identityAgent) {
52725
+ pluginAgent = identityAgent;
52726
+ pluginConversation = clientConv ?? conversation;
52727
+ }
52728
+ }
52729
+ if (!pluginAgent && session.stats.requests === 0) {
52730
+ const pending = takePendingPluginRegister();
52731
+ if (pending) {
52732
+ pluginAgent = pending.agent;
52733
+ pluginConversation = pending.conversationId;
52734
+ }
52735
+ }
52736
+ if (!pluginAgent && typeof session.metadata.pluginAgent === "string") pluginAgent = session.metadata.pluginAgent;
52737
+ if (pluginAgent && !pluginConversation) pluginConversation = conversation;
52738
+ if (pluginAgent) {
52739
+ if (session.metadata.pluginAgent !== pluginAgent) session.metadata.pluginAgent = pluginAgent;
52740
+ session.metadata.effectiveContextLimit = reqConfig.modelContextLimit;
52741
+ recordPluginSession(pluginConversation ?? conversation, session.id);
52742
+ }
52743
+ const pluginMode = pluginAgent !== void 0;
52744
+ const reqModel = parsed.model;
52745
+ const learnedMap = session.metadata.learnedContextLimits;
52746
+ const learnedLimit = (reqModel && learnedMap ? learnedMap[reqModel] : void 0) ?? session.metadata.learnedContextLimit;
52747
+ if (learnedLimit && learnedLimit > 0 && learnedLimit < reqConfig.modelContextLimit) {
52748
+ const resolved = reqConfig.modelContextLimit;
52749
+ reqConfig = { ...reqConfig, modelContextLimit: learnedLimit };
52750
+ log2("info", `[${session.id}] self-healed context window: ${resolved} \u2192 ${learnedLimit} (learned from an upstream overflow)`);
52751
+ }
52752
+ if (shouldReserveOutputHeadroom(protocol)) {
52753
+ const p2 = parsed;
52754
+ const rawMax = p2.max_tokens ?? p2.max_completion_tokens ?? p2.max_output_tokens;
52755
+ const maxOutput = typeof rawMax === "number" ? rawMax : 0;
52756
+ const reserved = reserveOutputHeadroom(reqConfig.modelContextLimit, maxOutput);
52757
+ if (reserved !== reqConfig.modelContextLimit) reqConfig = { ...reqConfig, modelContextLimit: reserved };
52758
+ }
52124
52759
  acquireInFlight(session);
52125
52760
  try {
52126
52761
  await withSessionLock(session, async () => {
52127
- prepared = countTokens ? prepareCountTokens(parsed, core, reqConfig, log2, session) : protocol === "anthropic" ? prepareAnthropic(parsed, req, opts, core, reqConfig, reqPrompts, log2, session) : protocol === "openai" ? prepareOpenai(parsed, req, opts, core, reqConfig, reqPrompts, log2, session) : responsesCompact ? prepareResponsesCompact(bodyBuffer, parsed, session) : prepareResponses(parsed, req, opts, core, reqConfig, reqPrompts, log2, session, responsesIdentity);
52762
+ prepared = 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);
52128
52763
  await forward(req, res, opts, prepared.body, prepared, core, reqConfig, log2, route, affinity);
52764
+ if (pluginMode && prepared) {
52765
+ rememberPluginMessages(sessionId, prepared.processedMessages, prepared.originalMessages, prepared.nudge);
52766
+ }
52129
52767
  });
52130
52768
  } finally {
52131
52769
  releaseInFlight(session);
@@ -52167,10 +52805,11 @@ function diagNudge(turn, sessionId, tokenCount, limit, model) {
52167
52805
  const modelTag = model ? ` model=${model}` : "";
52168
52806
  return `[${sessionId}] nudge ${inject}: usage=${pct2} (${tokenCount}/${limit}), growth=${growth}/${floor} (ref=${ref}, interval=${interval}), pendingT1=${pendingT1}/${interval}${modelTag}, reason="${n.reason.slice(0, 120)}"`;
52169
52807
  }
52170
- function prepareAnthropic(parsed, req, opts, core, config, prompts, log2, session) {
52808
+ function prepareAnthropic(parsed, req, opts, core, config, prompts, log2, session, pluginMode) {
52171
52809
  const sessionId = session.id;
52172
52810
  const stream2 = parsed.stream === true;
52173
52811
  ++session.stats.requests;
52812
+ const injectTools = opts.compress.injectTool && !pluginMode;
52174
52813
  let processedMessages = [];
52175
52814
  let originalMessages = [];
52176
52815
  let nudge;
@@ -52196,7 +52835,7 @@ function prepareAnthropic(parsed, req, opts, core, config, prompts, log2, sessio
52196
52835
  reapOrphanBlocks(session, msgs, deactivateBlock);
52197
52836
  rebuiltMessages = coreToAnthropic(processedMessages, cacheControls);
52198
52837
  systemOut = injectSystem(parsed, opts, prompts);
52199
- if (opts.compress.injectTool) {
52838
+ if (injectTools) {
52200
52839
  toolsOut = injectTool(parsed.tools);
52201
52840
  }
52202
52841
  if (opts.compress.injectNudge && turn.nudge?.shouldInject) {
@@ -52215,9 +52854,9 @@ function prepareAnthropic(parsed, req, opts, core, config, prompts, log2, sessio
52215
52854
  snapshotMessages(session, originalMessages);
52216
52855
  markDirty(session);
52217
52856
  const rebuilt = { ...parsed, messages: rebuiltMessages, system: systemOut, tools: toolsOut };
52218
- return { body: JSON.stringify(rebuilt), session, processedMessages, originalMessages, anthropicSystem: parsed.system, protocol: "anthropic", stream: stream2, compressInjected: opts.compress.injectTool, nudge, prompts };
52857
+ return { body: JSON.stringify(rebuilt), session, processedMessages, originalMessages, anthropicSystem: parsed.system, protocol: "anthropic", stream: stream2, compressInjected: injectTools, pluginMode, nudge, prompts };
52219
52858
  }
52220
- function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session) {
52859
+ function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session, pluginMode) {
52221
52860
  const sessionId = session.id;
52222
52861
  const stream2 = parsed.stream === true;
52223
52862
  ++session.stats.requests;
@@ -52229,6 +52868,7 @@ function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session)
52229
52868
  const maxTokens = typeof parsed.max_tokens === "number" ? parsed.max_tokens : 8192;
52230
52869
  const isTitleGen = maxTokens <= 200;
52231
52870
  const shouldInject = opts.compress.injectTool && !isTitleGen;
52871
+ const injectTools = shouldInject && !pluginMode;
52232
52872
  try {
52233
52873
  const { msgs } = openaiToCore(parsed);
52234
52874
  originalMessages = msgs;
@@ -52249,7 +52889,7 @@ function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session)
52249
52889
  const sysParts = [];
52250
52890
  if (shouldInject) sysParts.push(buildCompressSystemPrompt(prompts));
52251
52891
  rebuiltMessages = injectOpenaiSystem(rebuiltMessages, sysParts);
52252
- if (shouldInject) {
52892
+ if (injectTools) {
52253
52893
  toolsOut = injectOpenaiTool(parsed.tools);
52254
52894
  }
52255
52895
  if (opts.compress.injectNudge && turn.nudge?.shouldInject && shouldInject) {
@@ -52271,9 +52911,9 @@ function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session)
52271
52911
  }
52272
52912
  snapshotMessages(session, originalMessages);
52273
52913
  markDirty(session);
52274
- return { body: JSON.stringify(rebuilt), session, processedMessages, originalMessages, protocol: "openai", stream: stream2, compressInjected: shouldInject, nudge, prompts };
52914
+ return { body: JSON.stringify(rebuilt), session, processedMessages, originalMessages, protocol: "openai", stream: stream2, compressInjected: injectTools, pluginMode, nudge, prompts };
52275
52915
  }
52276
- function prepareResponses(parsed, req, opts, core, config, prompts, log2, session, identity) {
52916
+ function prepareResponses(parsed, req, opts, core, config, prompts, log2, session, identity, pluginMode) {
52277
52917
  const sessionId = session.id;
52278
52918
  const stream2 = parsed.stream === true;
52279
52919
  ++session.stats.requests;
@@ -52287,6 +52927,7 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
52287
52927
  let rebuiltInput = parsed.input;
52288
52928
  let toolsOut = parsed.tools;
52289
52929
  const shouldInject = opts.compress.injectTool;
52930
+ const injectTools = shouldInject && !pluginMode;
52290
52931
  const responsesTextProtocol = FORCE_TEXT_PROTOCOL || resolveCompressProtocol(opts.routes, session.meta.upstreamOrigin) === "marker";
52291
52932
  try {
52292
52933
  const projection = responsesToCore(parsed);
@@ -52314,7 +52955,7 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
52314
52955
  const prompt = responsesTextProtocol ? buildCompressHybridSystemPrompt(prompts) : buildCompressSystemPrompt(prompts);
52315
52956
  const devContent = [...projection.systemParts, prompt].join("\n\n---\n\n");
52316
52957
  rebuiltInput = injectResponsesDeveloperMessage(rebuiltInput, devContent);
52317
- if (!process.env.ACP_NO_INJECT_TOOL) {
52958
+ if (!process.env.ACP_NO_INJECT_TOOL && injectTools) {
52318
52959
  toolsOut = responsesTextProtocol ? injectResponsesTool(parsed.tools, ACP_READONLY_TOOLS_RESPONSES) : injectResponsesTool(parsed.tools);
52319
52960
  }
52320
52961
  } else if (projection.systemParts.length > 0) {
@@ -52363,7 +53004,8 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
52363
53004
  responsesProjection,
52364
53005
  protocol: "responses",
52365
53006
  stream: stream2,
52366
- compressInjected: shouldInject,
53007
+ compressInjected: injectTools,
53008
+ pluginMode,
52367
53009
  responsesTextProtocol,
52368
53010
  nudge,
52369
53011
  prompts
@@ -52494,16 +53136,16 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
52494
53136
  if (process.env.ACP_DUMP_REQ !== "0") {
52495
53137
  const dumpDir = process.env.ACP_DUMP_DIR || `${stateDir()}/dumps`;
52496
53138
  try {
52497
- fs5.mkdirSync(dumpDir, { recursive: true });
53139
+ fs6.mkdirSync(dumpDir, { recursive: true });
52498
53140
  } catch {
52499
53141
  }
52500
53142
  const sid = prepared?.session.id ?? "unknown";
52501
53143
  const out = `${dumpDir}/req-${Date.now()}-${sid}.json`;
52502
53144
  try {
52503
53145
  const pretty = JSON.stringify(JSON.parse(body), null, 2);
52504
- fs5.writeFileSync(out, pretty);
53146
+ fs6.writeFileSync(out, pretty);
52505
53147
  } catch {
52506
- fs5.writeFileSync(out, body);
53148
+ fs6.writeFileSync(out, body);
52507
53149
  }
52508
53150
  log2("info", `[debug] forwarded body written to ${out}`);
52509
53151
  }
@@ -52538,7 +53180,7 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
52538
53180
  const rawBase = opts.debug ? (() => {
52539
53181
  try {
52540
53182
  const rawDir = process.env.ACP_RAW_DUMP_DIR || `${stateDir()}/raw`;
52541
- fs5.mkdirSync(rawDir, { recursive: true });
53183
+ fs6.mkdirSync(rawDir, { recursive: true });
52542
53184
  return `${rawDir}/${Date.now()}-${prepared?.session.id ?? "unknown"}`;
52543
53185
  } catch {
52544
53186
  return "";
@@ -52550,7 +53192,7 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
52550
53192
  const hdrText = Object.entries(headers).map(([k2, v2]) => `${k2}: ${maskHdr(k2, String(v2))}`).join("\n");
52551
53193
  const bodyText = req.method === "GET" || req.method === "HEAD" ? "" : typeof body === "string" ? body : Buffer.from(body).toString("utf8");
52552
53194
  const reqPath = `${rawBase}-REQ.txt`;
52553
- fs5.writeFileSync(reqPath, `${req.method ?? "POST"} ${upstreamUrl}
53195
+ fs6.writeFileSync(reqPath, `${req.method ?? "POST"} ${upstreamUrl}
52554
53196
  ${hdrText}
52555
53197
 
52556
53198
  ${bodyText}`);
@@ -52565,9 +53207,13 @@ ${bodyText}`);
52565
53207
  body: req.method === "GET" || req.method === "HEAD" ? void 0 : body
52566
53208
  };
52567
53209
  if (dispatcher) init.dispatcher = dispatcher;
53210
+ const clientAbort = new AbortController();
53211
+ res.on("close", () => {
53212
+ if (!res.writableEnded) clientAbort.abort();
53213
+ });
52568
53214
  let upstreamResult;
52569
53215
  try {
52570
- upstreamResult = await fetchWithTimeout(upstreamUrl, init);
53216
+ upstreamResult = await fetchWithTimeout(upstreamUrl, init, void 0, clientAbort.signal);
52571
53217
  recordUpstreamConnection(upstreamUrl, proxyUrl);
52572
53218
  } catch (error) {
52573
53219
  recordUpstreamConnection(upstreamUrl, proxyUrl, error);
@@ -52595,7 +53241,7 @@ ${bodyText}`);
52595
53241
  const maskHdr = (k2, v2) => /key|auth|token/i.test(k2) ? `<masked ${v2.length} chars>` : v2;
52596
53242
  const hdrText = Object.entries(respHeaders).map(([k2, v2]) => `${k2}: ${maskHdr(k2, v2)}`).join("\n");
52597
53243
  const resPath = `${rawBase}-RES.txt`;
52598
- fs5.writeFileSync(resPath, `${upstream.status}
53244
+ fs6.writeFileSync(resPath, `${upstream.status}
52599
53245
  ${hdrText}
52600
53246
  `);
52601
53247
  log2("info", `[debug] RAW response dump: ${resPath}`);
@@ -52603,8 +53249,53 @@ ${hdrText}
52603
53249
  }
52604
53250
  }
52605
53251
  if (!upstream.ok) {
52606
- res.writeHead(upstream.status, respHeaders);
52607
- if (upstream.body) await pipeThrough(upstream.body, res);
53252
+ let errBody = null;
53253
+ if (upstream.body) {
53254
+ try {
53255
+ errBody = await readStreamToBuffer(upstream.body);
53256
+ } catch {
53257
+ errBody = null;
53258
+ }
53259
+ }
53260
+ if (prepared?.session && errBody) {
53261
+ const s3 = prepared.session;
53262
+ const info = inspectContextOverflow(upstream.status, errBody.toString("utf8"));
53263
+ if (info.isOverflow) {
53264
+ let reqModel;
53265
+ try {
53266
+ const rawBody = typeof prepared.body === "string" ? prepared.body : prepared.body.toString("utf8");
53267
+ reqModel = JSON.parse(rawBody).model;
53268
+ } catch {
53269
+ reqModel = void 0;
53270
+ }
53271
+ const learnedMap = s3.metadata.learnedContextLimits ?? {};
53272
+ if (info.window) {
53273
+ const prev = (reqModel ? learnedMap[reqModel] : void 0) ?? s3.metadata.learnedContextLimit;
53274
+ if (reqModel) learnedMap[reqModel] = info.window;
53275
+ else s3.metadata.learnedContextLimit = info.window;
53276
+ s3.metadata.learnedContextLimits = learnedMap;
53277
+ log2("warn", `[${s3.id}] upstream context overflow \u2014 learned real window ${info.window} for ${reqModel ?? "(unknown model)"} (was ${prev ?? "unset"}); arming emergency shrink`);
53278
+ } else {
53279
+ log2("warn", `[${s3.id}] upstream context overflow (window not parseable): ${info.message}`);
53280
+ }
53281
+ const floor = info.window ?? (reqModel ? learnedMap[reqModel] : void 0) ?? s3.metadata.learnedContextLimit ?? s3.metadata.effectiveContextLimit ?? 0;
53282
+ if (floor > 0) s3.stats.lastInputTokens = Math.max(s3.stats.lastInputTokens, floor);
53283
+ markDirty(s3);
53284
+ }
53285
+ }
53286
+ const errSid = prepared?.session.id ?? "unknown";
53287
+ const reqId = upstream.headers.get("x-request-id") ?? upstream.headers.get("request-id");
53288
+ const reqIdText = reqId ? ` request-id=${reqId}` : "";
53289
+ const bodyText = errBody ? new TextDecoder().decode(errBody) : "";
53290
+ let snippet = bodyText.slice(0, 600).replace(/\s+/g, " ").trim();
53291
+ if (bodyText.length > 600) snippet += " \u2026";
53292
+ if (!snippet) snippet = "(no body)";
53293
+ log("warn", `[${errSid}] \u2190 upstream ${upstream.status}${reqIdText}: ${snippet}`);
53294
+ const errHeaders = { ...respHeaders };
53295
+ delete errHeaders["content-length"];
53296
+ delete errHeaders["transfer-encoding"];
53297
+ res.writeHead(upstream.status, errHeaders);
53298
+ res.end(errBody ?? void 0);
52608
53299
  clearUpstreamTimer();
52609
53300
  return;
52610
53301
  }
@@ -52618,6 +53309,15 @@ ${hdrText}
52618
53309
  }
52619
53310
  return;
52620
53311
  }
53312
+ if (prepared?.pluginMode) {
53313
+ if (prepared.stream) {
53314
+ await pipeThroughWithUsage(upstream.body, res, prepared.session, prepared.protocol);
53315
+ } else {
53316
+ await pipePluginJson(upstream.body, res, prepared.session, prepared.protocol);
53317
+ }
53318
+ clearUpstreamTimer();
53319
+ return;
53320
+ }
52621
53321
  const useRewriter = prepared !== null && prepared.compressInjected && prepared.processedMessages.length > 0;
52622
53322
  if (!useRewriter || prepared === null) {
52623
53323
  await pipeThrough(upstream.body, res);
@@ -52650,20 +53350,17 @@ ${hdrText}
52650
53350
  const textProtocol = prepared.protocol === "responses" && !!prepared.responsesTextProtocol;
52651
53351
  const systemPrompt = textProtocol ? buildCompressHybridSystemPrompt(prepared.prompts ?? defaultPrompts) : buildCompressSystemPrompt(prepared.prompts ?? defaultPrompts);
52652
53352
  const adapter = pickAdapter(prepared.protocol, parsedReq, textProtocol, prepared.responsesProjection, prepared.anthropicSystem);
52653
- const abortCtrl = new AbortController();
52654
- req.on("close", () => {
52655
- if (!res.writableEnded) abortCtrl.abort();
52656
- });
52657
53353
  const loop = runCompressLoop(
52658
53354
  streamToRead,
52659
- { core, config, messages: prepared.processedMessages.length > 0 ? prepared.processedMessages : prepared.originalMessages, session: prepared.session, log: ctx.log, proxyUrl, textProtocol, debug: opts.debug, nudge: prepared.nudge },
53355
+ { core, config, messages: prepared.processedMessages.length > 0 ? prepared.processedMessages : prepared.originalMessages, session: prepared.session, log: ctx.log, proxyUrl, protocol: prepared.protocol, textProtocol, debug: opts.debug, nudge: prepared.nudge },
52660
53356
  parsedReq,
52661
53357
  { url: upstreamUrl, headers: reqHeaders },
52662
53358
  adapter,
52663
53359
  systemPrompt,
52664
- abortCtrl.signal
53360
+ clientAbort.signal
52665
53361
  );
52666
53362
  for await (const chunk of loop) {
53363
+ if (res.destroyed || res.writableEnded) break;
52667
53364
  {
52668
53365
  const s3 = chunk.toString("utf8");
52669
53366
  if (s3.includes("<acp ") || s3.includes("</acp")) {
@@ -52703,13 +53400,10 @@ ${hdrText}
52703
53400
  );
52704
53401
  }
52705
53402
  const u2 = json.usage ?? {};
52706
- const prompt = u2.prompt_tokens ?? u2.input_tokens;
52707
- if (typeof prompt === "number") {
52708
- prepared.session.stats.inputTokens += prompt;
52709
- const promptDetails = u2.prompt_tokens_details;
52710
- const inputDetails = u2.input_tokens_details;
52711
- const cached = promptDetails?.cached_tokens ?? inputDetails?.cached_tokens ?? u2.cache_read_input_tokens;
52712
- prepared.session.stats.lastInputTokens = prompt + (typeof cached === "number" ? cached : 0);
53403
+ const { total, cached } = usageTotals(prepared.protocol, u2);
53404
+ if (typeof total === "number") {
53405
+ prepared.session.stats.inputTokens += total;
53406
+ prepared.session.stats.lastInputTokens = total;
52713
53407
  if (typeof cached === "number") {
52714
53408
  prepared.session.stats.cachedTokens += cached;
52715
53409
  prepared.session.stats.cacheSamples += 1;
@@ -52734,6 +53428,25 @@ ${hdrText}
52734
53428
  }
52735
53429
  markDirty(prepared.session);
52736
53430
  }
53431
+ async function readStreamToBuffer(stream2, maxBytes = 1 << 20) {
53432
+ const reader = stream2.getReader();
53433
+ const chunks = [];
53434
+ let kept = 0;
53435
+ try {
53436
+ for (; ; ) {
53437
+ const { done, value } = await reader.read();
53438
+ if (done) break;
53439
+ if (value && kept < maxBytes) {
53440
+ const take = Math.min(value.length, maxBytes - kept);
53441
+ chunks.push(Buffer.from(value.subarray(0, take)));
53442
+ kept += take;
53443
+ }
53444
+ }
53445
+ } finally {
53446
+ reader.releaseLock();
53447
+ }
53448
+ return Buffer.concat(chunks);
53449
+ }
52737
53450
  async function pipeThrough(stream2, res) {
52738
53451
  const reader = stream2.getReader();
52739
53452
  try {
@@ -52810,7 +53523,7 @@ function sendStats(res) {
52810
53523
  res.writeHead(200, { "content-type": "application/json" });
52811
53524
  res.end(JSON.stringify({ sessions: sessions2 }, null, 2));
52812
53525
  }
52813
- function headerValue(req, name) {
53526
+ function headerValue2(req, name) {
52814
53527
  const lower = name.toLowerCase();
52815
53528
  for (const [k2, v2] of Object.entries(req.headers)) {
52816
53529
  if (k2.toLowerCase() === lower) return Array.isArray(v2) ? v2[0] : v2;
@@ -52856,6 +53569,7 @@ function logMsg(opts, level, msg2) {
52856
53569
 
52857
53570
  // src/update.ts
52858
53571
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, access, constants, rm, cp, unlink } from "fs/promises";
53572
+ import { execFile } from "child_process";
52859
53573
  import crypto from "crypto";
52860
53574
 
52861
53575
  // node_modules/tar/dist/esm/index.min.js
@@ -54795,7 +55509,7 @@ var hr = /* @__PURE__ */ Symbol("entry");
54795
55509
  var cs = /* @__PURE__ */ Symbol("entryOpt");
54796
55510
  var ui = /* @__PURE__ */ Symbol("writeEntryClass");
54797
55511
  var lr = /* @__PURE__ */ Symbol("write");
54798
- var fs6 = /* @__PURE__ */ Symbol("ondrain");
55512
+ var fs7 = /* @__PURE__ */ Symbol("ondrain");
54799
55513
  var wt = class extends A {
54800
55514
  sync = false;
54801
55515
  opt;
@@ -54829,8 +55543,8 @@ var wt = class extends A {
54829
55543
  if ((t.gzip ? 1 : 0) + (t.brotli ? 1 : 0) + (t.zstd ? 1 : 0) > 1) throw new TypeError("gzip, brotli, zstd are mutually exclusive");
54830
55544
  if (t.gzip && (typeof t.gzip != "object" && (t.gzip = {}), this.portable && (t.gzip.portable = true), this.zip = new ze(t.gzip)), t.brotli && (typeof t.brotli != "object" && (t.brotli = {}), this.zip = new We(t.brotli)), t.zstd && (typeof t.zstd != "object" && (t.zstd = {}), this.zip = new Ye(t.zstd)), !this.zip) throw new Error("impossible");
54831
55545
  let e = this.zip;
54832
- e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs6]()), this.on("resume", () => e.resume());
54833
- } else this.on("drain", this[fs6]);
55546
+ e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs7]()), this.on("resume", () => e.resume());
55547
+ } else this.on("drain", this[fs7]);
54834
55548
  this.noDirRecurse = !!t.noDirRecurse, this.follow = !!t.follow, this.noMtime = !!t.noMtime, t.mtime && (this.mtime = t.mtime), this.filter = typeof t.filter == "function" ? t.filter : () => true, this[W] = new hi(), this[G] = 0, this.jobs = Number(t.jobs) || 4, this[Ee] = false, this[me] = false;
54835
55549
  }
54836
55550
  [lr](t) {
@@ -54943,7 +55657,7 @@ var wt = class extends A {
54943
55657
  this.emit("error", e);
54944
55658
  }
54945
55659
  }
54946
- [fs6]() {
55660
+ [fs7]() {
54947
55661
  this[Et] && this[Et].entry && this[Et].entry.resume();
54948
55662
  }
54949
55663
  [di](t) {
@@ -55828,12 +56542,12 @@ var To = (s3) => {
55828
56542
  };
55829
56543
 
55830
56544
  // src/update.ts
55831
- import path8 from "path";
55832
- import { fileURLToPath as fileURLToPath2 } from "url";
56545
+ import path9 from "path";
56546
+ import { fileURLToPath as fileURLToPath3 } from "url";
55833
56547
  var REGISTRY_BASE = "https://registry.npmjs.org";
55834
56548
  var CHECK_INTERVAL_MS = 3 * 60 * 1e3;
55835
- var THROTTLE_FILE = path8.join(cacheDir(), ".update-check");
55836
- var LOCK_FILE = path8.join(cacheDir(), ".update-lock");
56549
+ var THROTTLE_FILE = path9.join(cacheDir(), ".update-check");
56550
+ var LOCK_FILE = path9.join(cacheDir(), ".update-lock");
55837
56551
  var LOCK_MAX_AGE_MS = 30 * 60 * 1e3;
55838
56552
  function shouldStealLock(holderAlive, ageMs) {
55839
56553
  return !holderAlive || ageMs >= LOCK_MAX_AGE_MS;
@@ -55865,32 +56579,101 @@ async function readLastCheck() {
55865
56579
  }
55866
56580
  async function writeLastCheck(ts2) {
55867
56581
  try {
55868
- await mkdir2(path8.dirname(THROTTLE_FILE), { recursive: true });
56582
+ await mkdir2(path9.dirname(THROTTLE_FILE), { recursive: true });
55869
56583
  await writeFile2(THROTTLE_FILE, String(ts2), "utf-8");
55870
56584
  } catch {
55871
56585
  }
55872
56586
  }
55873
56587
  async function findInstallDir(packageName) {
55874
- let dir = path8.dirname(fileURLToPath2(import.meta.url));
56588
+ let dir = path9.dirname(fileURLToPath3(import.meta.url));
55875
56589
  for (; ; ) {
55876
56590
  try {
55877
- const pkg = JSON.parse(await readFile2(path8.join(dir, "package.json"), "utf-8"));
56591
+ const pkg = JSON.parse(await readFile2(path9.join(dir, "package.json"), "utf-8"));
55878
56592
  if (pkg.name === packageName) return dir;
55879
56593
  } catch {
55880
56594
  }
55881
- const parent = path8.dirname(dir);
56595
+ const parent = path9.dirname(dir);
55882
56596
  if (parent === dir) return void 0;
55883
56597
  dir = parent;
55884
56598
  }
55885
56599
  }
55886
56600
  async function readDiskVersion(installDir) {
55887
56601
  try {
55888
- const pkg = JSON.parse(await readFile2(path8.join(installDir, "package.json"), "utf-8"));
56602
+ const pkg = JSON.parse(await readFile2(path9.join(installDir, "package.json"), "utf-8"));
55889
56603
  return pkg.version;
55890
56604
  } catch {
55891
56605
  return void 0;
55892
56606
  }
55893
56607
  }
56608
+ function declaredEntryRelPaths(pkg) {
56609
+ const entries = /* @__PURE__ */ new Set();
56610
+ if (typeof pkg.main === "string") entries.add(pkg.main);
56611
+ const bin = pkg.bin;
56612
+ if (typeof bin === "string") entries.add(bin);
56613
+ else if (bin && typeof bin === "object") {
56614
+ for (const v2 of Object.values(bin)) {
56615
+ if (typeof v2 === "string") entries.add(v2);
56616
+ }
56617
+ }
56618
+ return [...entries];
56619
+ }
56620
+ function runNodeCheck(file) {
56621
+ return new Promise((resolve) => {
56622
+ execFile(
56623
+ process.execPath,
56624
+ ["--check", file],
56625
+ { timeout: 15e3, maxBuffer: 4 * 1024 * 1024 },
56626
+ (err2, _stdout, stderr) => {
56627
+ resolve({ code: err2 ? 1 : 0, stderr: String(stderr) });
56628
+ }
56629
+ );
56630
+ });
56631
+ }
56632
+ async function syntaxCheckEntry(entryAbs) {
56633
+ let source;
56634
+ try {
56635
+ source = await readFile2(entryAbs, "utf-8");
56636
+ } catch (e) {
56637
+ return `entry unreadable: ${String(e)}`;
56638
+ }
56639
+ const tmpCheck = path9.join(cacheDir(), ".update-syntax-check.mjs");
56640
+ try {
56641
+ await mkdir2(cacheDir(), { recursive: true });
56642
+ await writeFile2(tmpCheck, source);
56643
+ const r = await runNodeCheck(tmpCheck);
56644
+ if (r.code !== 0) {
56645
+ return `entry does not parse (${path9.basename(entryAbs)}): ${r.stderr.split("\n").filter(Boolean).slice(0, 3).join(" | ").slice(0, 300)}`;
56646
+ }
56647
+ return null;
56648
+ } finally {
56649
+ try {
56650
+ await rm(tmpCheck, { force: true });
56651
+ } catch {
56652
+ }
56653
+ }
56654
+ }
56655
+ async function verifyEntries(dir, label) {
56656
+ let pkg;
56657
+ try {
56658
+ pkg = JSON.parse(await readFile2(path9.join(dir, "package.json"), "utf-8"));
56659
+ } catch (e) {
56660
+ return `${label}: package.json unreadable: ${String(e)}`;
56661
+ }
56662
+ const entries = declaredEntryRelPaths(pkg);
56663
+ if (entries.length === 0) {
56664
+ return `${label}: no declared entry (main/bin)`;
56665
+ }
56666
+ for (const rel of entries) {
56667
+ try {
56668
+ await access(path9.join(dir, rel));
56669
+ } catch {
56670
+ return `${label}: entry missing: ${rel}`;
56671
+ }
56672
+ const reason = await syntaxCheckEntry(path9.join(dir, rel));
56673
+ if (reason) return `${label}: ${reason}`;
56674
+ }
56675
+ return null;
56676
+ }
55894
56677
  async function tryAcquireLock() {
55895
56678
  const pid = process.pid;
55896
56679
  const now = Date.now();
@@ -56087,14 +56870,14 @@ async function installViaTarball(version2, tarballUrl, installDir, integrity, sh
56087
56870
  if (!v2.ok) {
56088
56871
  return { ok: false, error: `tarball integrity verification failed: ${v2.error}` };
56089
56872
  }
56090
- const tmpFile = path8.join(cacheDir(), `.update-${version2}.tgz`);
56873
+ const tmpFile = path9.join(cacheDir(), `.update-${version2}.tgz`);
56091
56874
  try {
56092
56875
  await mkdir2(cacheDir(), { recursive: true });
56093
56876
  await writeFile2(tmpFile, tgzBuffer);
56094
56877
  } catch (e) {
56095
56878
  return { ok: false, error: `failed to write temp file ${tmpFile}: ${String(e)}` };
56096
56879
  }
56097
- const stagingDir = path8.join(cacheDir(), `.update-staging-${version2}`);
56880
+ const stagingDir = path9.join(cacheDir(), `.update-staging-${version2}`);
56098
56881
  try {
56099
56882
  await rm(stagingDir, { recursive: true, force: true });
56100
56883
  await mkdir2(stagingDir, { recursive: true });
@@ -56107,22 +56890,57 @@ async function installViaTarball(version2, tarballUrl, installDir, integrity, sh
56107
56890
  if (stagingVersion !== version2) {
56108
56891
  return { ok: false, error: `staging verification failed: version is ${stagingVersion ?? "missing"}, expected ${version2}` };
56109
56892
  }
56893
+ const stagingEntryErr = await verifyEntries(stagingDir, "staging verification failed");
56894
+ if (stagingEntryErr) {
56895
+ return { ok: false, error: stagingEntryErr };
56896
+ }
56110
56897
  } catch (e) {
56111
56898
  return { ok: false, error: `extraction failed: ${String(e)}` };
56112
56899
  } finally {
56113
56900
  await rm(tmpFile, { force: true });
56114
56901
  }
56902
+ const backupDir = path9.join(cacheDir(), `.update-backup-${version2}`);
56903
+ try {
56904
+ await rm(backupDir, { recursive: true, force: true });
56905
+ await cp(installDir, backupDir, { recursive: true, force: true });
56906
+ } catch (e) {
56907
+ return { ok: false, error: `backup of current install failed (install left untouched): ${String(e)}` };
56908
+ }
56909
+ const restoreFromBackup = async () => {
56910
+ try {
56911
+ await rm(installDir, { recursive: true, force: true });
56912
+ await cp(backupDir, installDir, { recursive: true, force: true });
56913
+ return null;
56914
+ } catch (e) {
56915
+ return `ROLLBACK FAILED \u2014 restore ${backupDir} to ${installDir} manually: ${String(e)}`;
56916
+ }
56917
+ };
56918
+ let copyError = null;
56115
56919
  try {
56116
56920
  await cp(stagingDir, installDir, { recursive: true, force: true });
56117
56921
  } catch (e) {
56118
- return { ok: false, error: `failed to copy to install dir: ${String(e)}` };
56922
+ copyError = `failed to copy to install dir: ${String(e)}`;
56119
56923
  } finally {
56120
56924
  await rm(stagingDir, { recursive: true, force: true });
56121
56925
  }
56926
+ if (copyError !== null) {
56927
+ const rb2 = await restoreFromBackup();
56928
+ return { ok: false, error: rb2 ?? copyError };
56929
+ }
56122
56930
  const newVersion = await readDiskVersion(installDir);
56123
56931
  if (newVersion !== version2) {
56124
- return { ok: false, error: `post-install verification failed: package.json version is ${newVersion ?? "missing"}, expected ${version2}` };
56932
+ const rb2 = await restoreFromBackup();
56933
+ return {
56934
+ ok: false,
56935
+ error: rb2 ?? `post-install verification failed: package.json version is ${newVersion ?? "missing"}, expected ${version2}`
56936
+ };
56937
+ }
56938
+ const postEntryErr = await verifyEntries(installDir, "post-install verification failed");
56939
+ if (postEntryErr) {
56940
+ const rb2 = await restoreFromBackup();
56941
+ return { ok: false, error: rb2 ?? postEntryErr };
56125
56942
  }
56943
+ await rm(backupDir, { recursive: true, force: true });
56126
56944
  return { ok: true };
56127
56945
  }
56128
56946
  function startAutoUpdate(opts) {
@@ -56136,11 +56954,490 @@ function startAutoUpdate(opts) {
56136
56954
  timer.unref?.();
56137
56955
  }
56138
56956
 
56957
+ // src/mcp.ts
56958
+ import fs8 from "fs";
56959
+ import path10 from "path";
56960
+ import { fileURLToPath as fileURLToPath4 } from "url";
56961
+ var VERSION2 = (() => {
56962
+ try {
56963
+ const here = fileURLToPath4(import.meta.url);
56964
+ const pkg = path10.join(path10.dirname(here), "..", "package.json");
56965
+ return JSON.parse(fs8.readFileSync(pkg, "utf8")).version ?? "dev";
56966
+ } catch {
56967
+ return "dev";
56968
+ }
56969
+ })();
56970
+ var DEFAULT_PROXY_ORIGIN = "http://127.0.0.1:8787";
56971
+ function resolveProxyOrigin() {
56972
+ const fromEnv = process.env.BILI_MCP_PROXY?.trim();
56973
+ if (fromEnv && fromEnv.length > 0) return fromEnv;
56974
+ try {
56975
+ const discovered = fs8.readFileSync(proxyOriginFile(), "utf8").trim();
56976
+ if (/^https?:\/\/\S+$/.test(discovered)) return discovered;
56977
+ } catch {
56978
+ }
56979
+ return DEFAULT_PROXY_ORIGIN;
56980
+ }
56981
+ var TOOL_TIMEOUT_MS = 6e4;
56982
+ var CONVERSATION_FROM_ENV = process.env.CLAUDE_CODE_SESSION_ID?.trim() || process.env.BILI_CONVERSATION_ID?.trim() || void 0;
56983
+ var IDENTITY_BINDING = Boolean(process.env.CLAUDE_CODE_SESSION_ID?.trim());
56984
+ var manifestTools = [];
56985
+ var conversationId = CONVERSATION_FROM_ENV;
56986
+ var registered = false;
56987
+ var initialized2 = false;
56988
+ function send(msg2) {
56989
+ process.stdout.write(JSON.stringify(msg2) + "\n");
56990
+ }
56991
+ function sendResult(id, result) {
56992
+ if (id === null) return;
56993
+ send({ jsonrpc: "2.0", id, result });
56994
+ }
56995
+ function sendError2(id, code, message) {
56996
+ if (id === null) return;
56997
+ send({ jsonrpc: "2.0", id, error: { code, message } });
56998
+ }
56999
+ async function fetchManifest() {
57000
+ const res = await fetch(`${resolveProxyOrigin()}/__bili/plugin/manifest`, { signal: AbortSignal.timeout(5e3) });
57001
+ if (!res.ok) throw new Error(`manifest fetch failed: ${res.status}`);
57002
+ const data = await res.json();
57003
+ const anthropic = data.tools?.anthropic ?? [];
57004
+ manifestTools = anthropic.map((t) => ({ name: t.name, description: t.description, inputSchema: t.input_schema }));
57005
+ if (manifestTools.length === 0) throw new Error("manifest served no anthropic tools");
57006
+ }
57007
+ var manifestPromise = null;
57008
+ function ensureManifest() {
57009
+ manifestPromise ??= fetchManifest().catch((err2) => {
57010
+ manifestPromise = null;
57011
+ throw err2;
57012
+ });
57013
+ return manifestPromise;
57014
+ }
57015
+ async function forwardTool(tool, args, timeoutMs = TOOL_TIMEOUT_MS) {
57016
+ let res;
57017
+ try {
57018
+ res = await fetch(`${resolveProxyOrigin()}/__bili/plugin/tool`, {
57019
+ method: "POST",
57020
+ headers: { "content-type": "application/json" },
57021
+ body: JSON.stringify({ conversationId, tool, args }),
57022
+ signal: AbortSignal.timeout(timeoutMs)
57023
+ });
57024
+ } catch (err2) {
57025
+ if (err2 instanceof Error && err2.name === "TimeoutError") throw new Error(`tool forward timed out after ${timeoutMs}ms: ${tool}`);
57026
+ throw err2;
57027
+ }
57028
+ const data = await res.json();
57029
+ if (!res.ok || !data.ok) throw new Error(data.error ?? `tool forward failed: ${res.status}`);
57030
+ return data.result ?? "";
57031
+ }
57032
+ var ERR_TOOL = -32602;
57033
+ async function handleMessage(msg2) {
57034
+ const { id = null, method } = msg2;
57035
+ const params = typeof msg2.params === "object" && msg2.params !== null ? msg2.params : {};
57036
+ switch (method) {
57037
+ case "initialize": {
57038
+ const fromMeta = params._meta?.ui?.sessionId?.trim();
57039
+ if (fromMeta) conversationId ??= fromMeta;
57040
+ initialized2 = true;
57041
+ if (conversationId && !registered) {
57042
+ const registerFetch = fetch(`${resolveProxyOrigin()}/__bili/plugin/register`, {
57043
+ method: "POST",
57044
+ headers: { "content-type": "application/json" },
57045
+ body: JSON.stringify({ conversationId, agent: "mcp", identity: IDENTITY_BINDING }),
57046
+ signal: AbortSignal.timeout(5e3)
57047
+ });
57048
+ registered = true;
57049
+ if (IDENTITY_BINDING) {
57050
+ void registerFetch.catch(() => {
57051
+ });
57052
+ } else {
57053
+ await registerFetch.catch(() => {
57054
+ });
57055
+ }
57056
+ }
57057
+ sendResult(id, {
57058
+ protocolVersion: "2025-06-18",
57059
+ serverInfo: { name: "bili", version: VERSION2 },
57060
+ capabilities: { tools: {} }
57061
+ });
57062
+ return;
57063
+ }
57064
+ case "notifications/initialized":
57065
+ return;
57066
+ case "tools/list": {
57067
+ if (!initialized2) {
57068
+ sendError2(id, -32002, "server not initialized");
57069
+ return;
57070
+ }
57071
+ try {
57072
+ await ensureManifest();
57073
+ sendResult(id, { tools: manifestTools });
57074
+ } catch (err2) {
57075
+ sendError2(id, -32003, `bili proxy unreachable at ${resolveProxyOrigin()} (${err2 instanceof Error ? err2.message : String(err2)}) \u2014 start bili or set BILI_MCP_PROXY`);
57076
+ }
57077
+ return;
57078
+ }
57079
+ case "tools/call": {
57080
+ const tool = typeof params.name === "string" ? params.name : "";
57081
+ const args = params.arguments && typeof params.arguments === "object" ? params.arguments : {};
57082
+ if (!tool) {
57083
+ sendError2(id, ERR_TOOL, "params.name is required");
57084
+ return;
57085
+ }
57086
+ if (!conversationId) {
57087
+ sendError2(id, ERR_TOOL, "no conversation id (set BILI_CONVERSATION_ID or connect via Claude Code MCP session meta)");
57088
+ return;
57089
+ }
57090
+ try {
57091
+ const text = await forwardTool(tool, args);
57092
+ sendResult(id, { content: [{ type: "text", text }], isError: false });
57093
+ } catch (err2) {
57094
+ sendResult(id, { content: [{ type: "text", text: `bili tool error: ${err2 instanceof Error ? err2.message : String(err2)}` }], isError: true });
57095
+ }
57096
+ return;
57097
+ }
57098
+ case "ping":
57099
+ sendResult(id, {});
57100
+ return;
57101
+ default:
57102
+ if (method?.startsWith("notifications/")) return;
57103
+ sendError2(id, -32601, `method not found: ${method ?? "(none)"}`);
57104
+ }
57105
+ }
57106
+ async function mcpMain() {
57107
+ let buf = "";
57108
+ process.stdin.setEncoding("utf8");
57109
+ process.stdin.on("data", (chunk) => {
57110
+ buf += chunk;
57111
+ let nl;
57112
+ while ((nl = buf.indexOf("\n")) >= 0) {
57113
+ const line = buf.slice(0, nl).trim();
57114
+ buf = buf.slice(nl + 1);
57115
+ if (!line) continue;
57116
+ let parsed;
57117
+ try {
57118
+ parsed = JSON.parse(line);
57119
+ } catch {
57120
+ continue;
57121
+ }
57122
+ if (parsed && typeof parsed === "object") {
57123
+ void handleMessage(parsed);
57124
+ }
57125
+ }
57126
+ });
57127
+ process.stdin.on("end", () => process.exit(0));
57128
+ }
57129
+ function runMcpStdio() {
57130
+ void mcpMain();
57131
+ }
57132
+ if (process.argv[1] && /(?:^|[\\/])mcp\.(?:ts|js)$/.test(process.argv[1])) {
57133
+ void mcpMain();
57134
+ }
57135
+
57136
+ // src/plugin-install.ts
57137
+ import fs9 from "fs";
57138
+ import path11 from "path";
57139
+ import os4 from "os";
57140
+ import { execFileSync as execFileSync2 } from "child_process";
57141
+ import { fileURLToPath as fileURLToPath5 } from "url";
57142
+ var PLUGIN_AGENTS = ["pi", "omp", "claude", "codex", "opencode"];
57143
+ function selfPackageRoot() {
57144
+ const here = fileURLToPath5(import.meta.url);
57145
+ return path11.resolve(path11.dirname(here), "..");
57146
+ }
57147
+ function homeFile(rel, envOverride) {
57148
+ const raw = (envOverride !== void 0 ? process.env[envOverride] : void 0)?.trim();
57149
+ const base = raw && raw.length > 0 ? raw : os4.homedir();
57150
+ return path11.join(base, rel);
57151
+ }
57152
+ function backupOnce(file) {
57153
+ if (fs9.existsSync(file) && !fs9.existsSync(`${file}.bili-bak`)) {
57154
+ fs9.copyFileSync(file, `${file}.bili-bak`);
57155
+ }
57156
+ }
57157
+ function readJson(file) {
57158
+ let text;
57159
+ try {
57160
+ text = fs9.readFileSync(file, "utf8");
57161
+ } catch (err2) {
57162
+ if (err2.code === "ENOENT") return {};
57163
+ throw err2;
57164
+ }
57165
+ let parsed;
57166
+ try {
57167
+ parsed = JSON.parse(text);
57168
+ } catch (err2) {
57169
+ throw new Error(`${file}: not valid JSON (${err2 instanceof Error ? err2.message : String(err2)}) \u2014 fix it or restore ${path11.basename(file)}.bili-bak first; refusing to overwrite`);
57170
+ }
57171
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
57172
+ throw new Error(`${file}: expected a JSON object at top level, refusing to overwrite`);
57173
+ }
57174
+ return parsed;
57175
+ }
57176
+ function writeJson(file, data) {
57177
+ fs9.mkdirSync(path11.dirname(file), { recursive: true });
57178
+ backupOnce(file);
57179
+ fs9.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
57180
+ }
57181
+ function requireDistFile(file) {
57182
+ if (!fs9.existsSync(file)) {
57183
+ process.stderr.write(`bili plugin: warning: ${file} does not exist yet (run \`npm run build\` in ${selfPackageRoot()}) \u2014 the entry will be dead until built
57184
+ `);
57185
+ }
57186
+ }
57187
+ function piSettingsFile() {
57188
+ return path11.join(resolvePiHome(process.env), "settings.json");
57189
+ }
57190
+ function isPiEntry(entry, root) {
57191
+ return entry === root || entry === `npm:billion-context` || /^npm:billion-context@/.test(entry) || /(^|\/)node_modules\/billion-context(\/|$)/.test(entry);
57192
+ }
57193
+ function piInstall() {
57194
+ const root = selfPackageRoot();
57195
+ const file = piSettingsFile();
57196
+ const settings = readJson(file);
57197
+ const packages = Array.isArray(settings.packages) ? settings.packages.map(String) : [];
57198
+ if (packages.some((p2) => p2 === root)) return `pi: already installed (${file})`;
57199
+ const kept = packages.filter((p2) => !isPiEntry(p2, root));
57200
+ kept.push(root);
57201
+ settings.packages = kept;
57202
+ writeJson(file, settings);
57203
+ return `pi: installed -> ${file} packages += ${root}`;
57204
+ }
57205
+ function piRemove() {
57206
+ const root = selfPackageRoot();
57207
+ const file = piSettingsFile();
57208
+ const settings = readJson(file);
57209
+ const packages = Array.isArray(settings.packages) ? settings.packages.map(String) : [];
57210
+ const kept = packages.filter((p2) => !isPiEntry(p2, root));
57211
+ if (kept.length === packages.length) return `pi: not installed (${file})`;
57212
+ settings.packages = kept;
57213
+ writeJson(file, settings);
57214
+ return `pi: removed from ${file}`;
57215
+ }
57216
+ function piStatus() {
57217
+ const root = selfPackageRoot();
57218
+ const packages = readJson(piSettingsFile()).packages;
57219
+ const list = Array.isArray(packages) ? packages.map(String) : [];
57220
+ return list.some((p2) => isPiEntry(p2, root)) ? "installed" : "not installed";
57221
+ }
57222
+ function ompConfigFile() {
57223
+ const raw = process.env.PI_CODING_AGENT_DIR?.trim();
57224
+ if (raw && raw.length > 0) return path11.join(raw, "config.yml");
57225
+ return path11.join(os4.homedir(), ".omp", "agent", "config.yml");
57226
+ }
57227
+ function ompExtensionPath() {
57228
+ return path11.join(selfPackageRoot(), "dist", "agent", "omp.js");
57229
+ }
57230
+ function ompEntryValue(line) {
57231
+ return line.replace(/#.*$/, "").trim().replace(/^-\s*/, "").replace(/^["']|["']$/g, "").trim();
57232
+ }
57233
+ function ompRemove() {
57234
+ const file = ompConfigFile();
57235
+ const entry = ompExtensionPath();
57236
+ if (!fs9.existsSync(file)) return `omp: not installed (${file})`;
57237
+ const text = fs9.readFileSync(file, "utf8");
57238
+ const cleaned = text.split("\n").filter((line) => ompEntryValue(line) !== entry).join("\n");
57239
+ if (cleaned === text) return `omp: not installed (${file})`;
57240
+ backupOnce(file);
57241
+ fs9.writeFileSync(file, cleaned);
57242
+ return `omp: removed from ${file}`;
57243
+ }
57244
+ function ompInstall() {
57245
+ const file = ompConfigFile();
57246
+ const entry = ompExtensionPath();
57247
+ requireDistFile(entry);
57248
+ fs9.mkdirSync(path11.dirname(file), { recursive: true });
57249
+ const text = fs9.existsSync(file) ? fs9.readFileSync(file, "utf8") : "";
57250
+ if (text.split("\n").some((line) => ompEntryValue(line) === entry)) return `omp: already installed (${file})`;
57251
+ const keyCount = (text.match(/^extensions:/gm) ?? []).length;
57252
+ if (keyCount > 1) throw new Error(`${file}: multiple \`extensions:\` keys \u2014 fix the file first, refusing to edit`);
57253
+ if (/^extensions:\s*\S/m.test(text) && !/^extensions:\s*$/m.test(text)) {
57254
+ throw new Error(`${file}: \`extensions:\` uses flow style or an inline value; convert it to a block list first, refusing to edit`);
57255
+ }
57256
+ let out;
57257
+ const extMatch = /^extensions:\s*$/m.exec(text);
57258
+ if (extMatch !== null) {
57259
+ const afterKey = text.indexOf("\n", extMatch.index);
57260
+ const rest = afterKey < 0 ? "" : text.slice(afterKey + 1);
57261
+ const firstNonList = rest.search(/^(?!\s*-\s)\S/m);
57262
+ const existingIndent = /^(\s*)-\s\S/m.exec(rest)?.[1] ?? " ";
57263
+ let head;
57264
+ let tail;
57265
+ if (firstNonList >= 0) {
57266
+ head = text.slice(0, afterKey + 1 + firstNonList);
57267
+ tail = text.slice(afterKey + 1 + firstNonList);
57268
+ } else {
57269
+ head = text.length === 0 || text.endsWith("\n") ? text : text + "\n";
57270
+ tail = "";
57271
+ }
57272
+ out = `${head}${existingIndent}- ${entry}
57273
+ ${tail}`;
57274
+ } else {
57275
+ out = text.endsWith("\n") || text.length === 0 ? text : text + "\n";
57276
+ out += `extensions:
57277
+ - ${entry}
57278
+ `;
57279
+ }
57280
+ const occurrences = out.split("\n").filter((line) => ompEntryValue(line) === entry).length;
57281
+ if (occurrences !== 1) {
57282
+ throw new Error(`${file}: edit would leave ${occurrences} copies of the entry \u2014 aborting without writing`);
57283
+ }
57284
+ backupOnce(file);
57285
+ fs9.writeFileSync(file, out);
57286
+ return `omp: installed -> ${file} extensions += ${entry}`;
57287
+ }
57288
+ function ompStatus() {
57289
+ const file = ompConfigFile();
57290
+ const text = fs9.existsSync(file) ? fs9.readFileSync(file, "utf8") : "";
57291
+ return text.split("\n").some((line) => ompEntryValue(line) === ompExtensionPath()) ? "installed" : "not installed";
57292
+ }
57293
+ var CLAUDE_EXEC_TIMEOUT_MS = 15e3;
57294
+ function claudeMcpJson() {
57295
+ return homeFile(".claude.json", "CLAUDE_CONFIG_DIR");
57296
+ }
57297
+ function claudeInstall() {
57298
+ const root = selfPackageRoot();
57299
+ const mcpJs = path11.join(root, "dist", "mcp.js");
57300
+ requireDistFile(mcpJs);
57301
+ const claude = process.env.CLAUDE?.trim() || "claude";
57302
+ try {
57303
+ execFileSync2(claude, ["mcp", "add", "bili", "--scope", "user", "-e", `BILI_MCP_PROXY=${resolveProxyOrigin()}`, "--", process.execPath, mcpJs], { stdio: ["ignore", "pipe", "pipe"], timeout: CLAUDE_EXEC_TIMEOUT_MS });
57304
+ return `claude: installed via \`claude mcp add\` (user scope) -> ${claudeMcpJson()}`;
57305
+ } catch (err2) {
57306
+ const stderr = err2 instanceof Error && "stderr" in err2 ? String(err2.stderr ?? "") : "";
57307
+ throw new Error(`claude: install failed (${stderr.trim() || (err2 instanceof Error ? err2.message : String(err2))}) \u2014 is the claude CLI on PATH?`);
57308
+ }
57309
+ }
57310
+ function claudeRemove() {
57311
+ if (claudeStatus() === "not installed") return `claude: not installed (${claudeMcpJson()})`;
57312
+ const claude = process.env.CLAUDE?.trim() || "claude";
57313
+ try {
57314
+ execFileSync2(claude, ["mcp", "remove", "bili", "--scope", "user"], { stdio: ["ignore", "pipe", "pipe"], timeout: CLAUDE_EXEC_TIMEOUT_MS });
57315
+ return "claude: removed";
57316
+ } catch (err2) {
57317
+ throw new Error(`claude: remove failed (${err2 instanceof Error ? err2.message : String(err2)})`);
57318
+ }
57319
+ }
57320
+ function claudeStatus() {
57321
+ const data = readJson(claudeMcpJson());
57322
+ return data.mcpServers && "bili" in data.mcpServers ? "installed" : "not installed";
57323
+ }
57324
+ function codexToml() {
57325
+ const raw = process.env.CODEX_HOME?.trim();
57326
+ if (raw && raw.length > 0) return path11.join(raw, "config.toml");
57327
+ return homeFile(".codex/config.toml");
57328
+ }
57329
+ function codexBlock() {
57330
+ return `
57331
+ [mcp_servers.bili]
57332
+ command = ${JSON.stringify(process.execPath)}
57333
+ args = [${JSON.stringify(path11.join(selfPackageRoot(), "dist", "mcp.js"))}]
57334
+ env = { BILI_MCP_PROXY = ${JSON.stringify(resolveProxyOrigin())} }
57335
+ `;
57336
+ }
57337
+ function codexInstall() {
57338
+ const file = codexToml();
57339
+ const text = fs9.existsSync(file) ? fs9.readFileSync(file, "utf8") : "";
57340
+ const existing = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text);
57341
+ if (existing !== null) {
57342
+ const block = text.slice(existing.index, text.indexOf("\n[", existing.index + 1) === -1 ? void 0 : text.indexOf("\n[", existing.index + 1));
57343
+ if (block.includes(`BILI_MCP_PROXY = ${JSON.stringify(resolveProxyOrigin())}`)) return `codex: already installed (${file})`;
57344
+ const refreshed = text.slice(0, existing.index) + codexBlock().replace(/^\n/, "") + text.slice(existing.index + block.length);
57345
+ backupOnce(file);
57346
+ fs9.writeFileSync(file, refreshed);
57347
+ return `codex: refreshed proxy origin -> ${file} [mcp_servers.bili]`;
57348
+ }
57349
+ fs9.mkdirSync(path11.dirname(file), { recursive: true });
57350
+ backupOnce(file);
57351
+ fs9.writeFileSync(file, text + (text.endsWith("\n") || text.length === 0 ? "" : "\n") + codexBlock());
57352
+ return `codex: installed -> ${file} [mcp_servers.bili]`;
57353
+ }
57354
+ function codexRemove() {
57355
+ const file = codexToml();
57356
+ if (!fs9.existsSync(file)) return `codex: not installed (${file})`;
57357
+ const text = fs9.readFileSync(file, "utf8");
57358
+ const start = (() => {
57359
+ const m2 = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text);
57360
+ return m2 === null ? -1 : m2.index;
57361
+ })();
57362
+ if (start < 0) return `codex: not installed (${file})`;
57363
+ const lineStart = text.lastIndexOf("\n", start - 1) + 1;
57364
+ const after = text.slice(start);
57365
+ const nextTable = after.slice(after.indexOf("\n") + 1).search(/^[ \t]*\[/m);
57366
+ const end = nextTable >= 0 ? start + after.indexOf("\n") + 1 + nextTable : text.length;
57367
+ const cleaned = (text.slice(0, lineStart).replace(/\n+$/, "\n") + text.slice(end)).replace(/^\n+/, "");
57368
+ backupOnce(file);
57369
+ fs9.writeFileSync(file, cleaned);
57370
+ return `codex: removed from ${file}`;
57371
+ }
57372
+ function codexStatus() {
57373
+ const text = fs9.existsSync(codexToml()) ? fs9.readFileSync(codexToml(), "utf8") : "";
57374
+ return /^\[mcp_servers\.bili\]\s*$/m.test(text) ? "installed" : "not installed";
57375
+ }
57376
+ function opencodeJson() {
57377
+ const raw = process.env.OPENCODE_CONFIG?.trim();
57378
+ if (raw && raw.length > 0) return raw;
57379
+ const xdg2 = process.env.XDG_CONFIG_HOME?.trim();
57380
+ if (xdg2 && xdg2.length > 0) return path11.join(xdg2, "opencode/opencode.json");
57381
+ return path11.join(os4.homedir(), ".config", "opencode", "opencode.json");
57382
+ }
57383
+ function opencodeInstall() {
57384
+ const file = opencodeJson();
57385
+ const mcpJs = path11.join(selfPackageRoot(), "dist", "mcp.js");
57386
+ requireDistFile(mcpJs);
57387
+ const data = readJson(file);
57388
+ const mcp = data.mcp ?? {};
57389
+ if ("bili" in mcp) return `opencode: already installed (${file})`;
57390
+ mcp.bili = { type: "local", command: [process.execPath, mcpJs], environment: { BILI_MCP_PROXY: resolveProxyOrigin() }, enabled: true };
57391
+ data.mcp = mcp;
57392
+ writeJson(file, data);
57393
+ return `opencode: installed -> ${file} mcp.bili`;
57394
+ }
57395
+ function opencodeRemove() {
57396
+ const file = opencodeJson();
57397
+ const data = readJson(file);
57398
+ const mcp = data.mcp;
57399
+ if (!mcp || !("bili" in mcp)) return `opencode: not installed (${file})`;
57400
+ delete mcp.bili;
57401
+ if (Object.keys(mcp).length === 0) delete data.mcp;
57402
+ writeJson(file, data);
57403
+ return `opencode: removed from ${file}`;
57404
+ }
57405
+ function opencodeStatus() {
57406
+ const mcp = readJson(opencodeJson()).mcp;
57407
+ return mcp && "bili" in mcp ? "installed" : "not installed";
57408
+ }
57409
+ function isPluginAgent(value) {
57410
+ return PLUGIN_AGENTS.includes(value);
57411
+ }
57412
+ function pluginInstall(agent) {
57413
+ return agent === "pi" ? piInstall() : agent === "omp" ? ompInstall() : agent === "claude" ? claudeInstall() : agent === "codex" ? codexInstall() : opencodeInstall();
57414
+ }
57415
+ function pluginRemove(agent) {
57416
+ return agent === "pi" ? piRemove() : agent === "omp" ? ompRemove() : agent === "claude" ? claudeRemove() : agent === "codex" ? codexRemove() : opencodeRemove();
57417
+ }
57418
+ function pluginStatusAll() {
57419
+ const checks = [
57420
+ ["pi", piStatus],
57421
+ ["omp", ompStatus],
57422
+ ["claude", claudeStatus],
57423
+ ["codex", codexStatus],
57424
+ ["opencode", opencodeStatus]
57425
+ ];
57426
+ return checks.map(([agent, check]) => {
57427
+ try {
57428
+ return { agent, status: check() };
57429
+ } catch (err2) {
57430
+ return { agent, status: `error: ${err2 instanceof Error ? err2.message : String(err2)}` };
57431
+ }
57432
+ });
57433
+ }
57434
+
56139
57435
  // src/launcher.ts
56140
- import fs7 from "fs";
57436
+ import { randomUUID as randomUUID2 } from "crypto";
57437
+ import fs10 from "fs";
56141
57438
  import net2 from "net";
56142
- import os4 from "os";
56143
- import path9 from "path";
57439
+ import os5 from "os";
57440
+ import path12 from "path";
56144
57441
  import { spawn } from "child_process";
56145
57442
  var LAUNCHER_DEFAULT_HOST = "127.0.0.1";
56146
57443
  var LAUNCHER_DEFAULT_PORT = 8787;
@@ -56184,12 +57481,12 @@ function unwrapUpstream2(url) {
56184
57481
  return idx >= 0 ? url.slice(idx + "/bili/".length) : url;
56185
57482
  }
56186
57483
  function resolveCaCertPath(env) {
56187
- const base = env.XDG_DATA_HOME || path9.join(os4.homedir(), ".local/share");
56188
- return path9.join(base, "billion-context", "ca", "root-ca.pem");
57484
+ const base = env.XDG_DATA_HOME || path12.join(os5.homedir(), ".local/share");
57485
+ return path12.join(base, "billion-context", "ca", "root-ca.pem");
56189
57486
  }
56190
57487
  function resolveCombinedCaPath(env) {
56191
- const base = env.XDG_DATA_HOME || path9.join(os4.homedir(), ".local/share");
56192
- return path9.join(base, "billion-context", "ca", "combined-ca.pem");
57488
+ const base = env.XDG_DATA_HOME || path12.join(os5.homedir(), ".local/share");
57489
+ return path12.join(base, "billion-context", "ca", "combined-ca.pem");
56193
57490
  }
56194
57491
  function discoverRoutes(client, config) {
56195
57492
  const httpsDomains = [];
@@ -56243,10 +57540,10 @@ function discoverDomains(client, config) {
56243
57540
  return discoverRoutes(client, config).httpsDomains;
56244
57541
  }
56245
57542
  function buildPiEnv(origin, caPath, baseEnv) {
56246
- return { ...baseEnv, HTTPS_PROXY: origin, NODE_EXTRA_CA_CERTS: caPath };
57543
+ return { ...baseEnv, HTTPS_PROXY: origin, NODE_EXTRA_CA_CERTS: caPath, BILLION_CONTEXT_PROXY: origin };
56247
57544
  }
56248
57545
  function buildCodexEnv(origin, caPath, baseEnv) {
56249
- return { ...baseEnv, HTTPS_PROXY: origin, SSL_CERT_FILE: caPath };
57546
+ return { ...baseEnv, HTTPS_PROXY: origin, SSL_CERT_FILE: caPath, BILLION_CONTEXT_PROXY: origin };
56250
57547
  }
56251
57548
  function buildCodexArgs(origin, httpRewrites, httpsRewrites, extra) {
56252
57549
  const args = [];
@@ -56260,19 +57557,55 @@ function buildCodexArgs(origin, httpRewrites, httpsRewrites, extra) {
56260
57557
  return args;
56261
57558
  }
56262
57559
  function buildClaudeEnv(origin, caPath, httpRewrites, httpsRewrites, baseEnv) {
56263
- const env = { ...baseEnv, HTTPS_PROXY: origin, NODE_EXTRA_CA_CERTS: caPath };
57560
+ const env = { ...baseEnv, HTTPS_PROXY: origin, NODE_EXTRA_CA_CERTS: caPath, BILLION_CONTEXT_PROXY: origin };
56264
57561
  const r = httpRewrites.find((rw) => rw.key === "ANTHROPIC_BASE_URL");
56265
57562
  if (r) env.ANTHROPIC_BASE_URL = wrapUpstream(origin, r.realUpstream);
56266
57563
  const hr2 = httpsRewrites.find((rw) => rw.key === "ANTHROPIC_BASE_URL");
56267
57564
  if (hr2) env.ANTHROPIC_BASE_URL = hr2.realUpstream;
56268
57565
  return env;
56269
57566
  }
57567
+ function launcherDirectUrl(env) {
57568
+ return env.BILI_LAUNCHER_DIRECT === "1";
57569
+ }
57570
+ function launcherInjectMcp(env, base) {
57571
+ return base !== "pi" && env.BILI_LAUNCHER_PLUGIN === "1";
57572
+ }
57573
+ function buildMcpConfig(origin) {
57574
+ const script = process.argv[1] ? path12.resolve(path12.dirname(process.argv[1]), "mcp.js") : "bili-mcp";
57575
+ return {
57576
+ mcpServers: {
57577
+ bili: {
57578
+ command: process.execPath,
57579
+ args: [script],
57580
+ env: { BILI_MCP_PROXY: origin }
57581
+ }
57582
+ }
57583
+ };
57584
+ }
57585
+ function buildClaudePluginEnv(origin, directUrl, baseEnv) {
57586
+ if (!directUrl) return baseEnv;
57587
+ const upstream = baseEnv.BILI_CLAUDE_UPSTREAM?.trim() || "https://api.anthropic.com";
57588
+ return { ...baseEnv, ANTHROPIC_BASE_URL: wrapUpstream(origin, upstream) };
57589
+ }
57590
+ function buildCodexMcpArgs(origin, conversationId2) {
57591
+ const script = process.argv[1] ? path12.resolve(path12.dirname(process.argv[1]), "mcp.js") : "bili-mcp";
57592
+ return [
57593
+ "-c",
57594
+ `mcp_servers.bili.command=${JSON.stringify(process.execPath)}`,
57595
+ "-c",
57596
+ `mcp_servers.bili.args=${JSON.stringify([script])}`,
57597
+ "-c",
57598
+ `mcp_servers.bili.env.BILI_MCP_PROXY=${JSON.stringify(origin)}`,
57599
+ "-c",
57600
+ `mcp_servers.bili.env.BILI_CONVERSATION_ID=${JSON.stringify(conversationId2)}`
57601
+ ];
57602
+ }
56270
57603
  function preparePiHttpRewrite(piHome, origin, httpRewrites, httpsRewrites) {
56271
57604
  if (httpRewrites.length === 0 && httpsRewrites.length === 0) return void 0;
56272
- const modelsPath = path9.join(piHome, "models.json");
57605
+ const modelsPath = path12.join(piHome, "models.json");
56273
57606
  let txt;
56274
57607
  try {
56275
- txt = fs7.readFileSync(modelsPath, "utf8");
57608
+ txt = fs10.readFileSync(modelsPath, "utf8");
56276
57609
  } catch {
56277
57610
  return void 0;
56278
57611
  }
@@ -56303,18 +57636,18 @@ function preparePiHttpRewrite(piHome, origin, httpRewrites, httpsRewrites) {
56303
57636
  }
56304
57637
  }
56305
57638
  }
56306
- const tmp = fs7.mkdtempSync(path9.join(os4.tmpdir(), "bili-pi-"));
57639
+ const tmp = fs10.mkdtempSync(path12.join(os5.tmpdir(), "bili-pi-"));
56307
57640
  try {
56308
- for (const entry of fs7.readdirSync(piHome)) {
57641
+ for (const entry of fs10.readdirSync(piHome)) {
56309
57642
  if (entry === "models.json") continue;
56310
57643
  try {
56311
- fs7.symlinkSync(path9.join(piHome, entry), path9.join(tmp, entry));
57644
+ fs10.symlinkSync(path12.join(piHome, entry), path12.join(tmp, entry));
56312
57645
  } catch {
56313
57646
  }
56314
57647
  }
56315
57648
  } catch {
56316
57649
  }
56317
- fs7.writeFileSync(path9.join(tmp, "models.json"), JSON.stringify(root));
57650
+ fs10.writeFileSync(path12.join(tmp, "models.json"), JSON.stringify(root));
56318
57651
  return tmp;
56319
57652
  }
56320
57653
  function dedupeInOrder(list) {
@@ -56395,8 +57728,8 @@ async function ensureProxyRunning(opts, deps = {}) {
56395
57728
  const spawnedOrigin = proxyOrigin(opts.host, port);
56396
57729
  const script = process.argv[1];
56397
57730
  if (!script) throw new Error("bili: cannot resolve launcher script path");
56398
- const logPath2 = path9.join(os4.tmpdir(), `bili-proxy-${port}.log`);
56399
- const logFd = fs7.openSync(logPath2, "a");
57731
+ const logPath2 = path12.join(os5.tmpdir(), `bili-proxy-${port}.log`);
57732
+ const logFd = fs10.openSync(logPath2, "a");
56400
57733
  let child;
56401
57734
  try {
56402
57735
  child = spawnImpl(
@@ -56413,7 +57746,7 @@ async function ensureProxyRunning(opts, deps = {}) {
56413
57746
  );
56414
57747
  } finally {
56415
57748
  try {
56416
- fs7.closeSync(logFd);
57749
+ fs10.closeSync(logFd);
56417
57750
  } catch {
56418
57751
  }
56419
57752
  }
@@ -56460,12 +57793,12 @@ var PATH_EXTS = process.platform === "win32" ? [".cmd", ".bat", ".exe", ""] : ["
56460
57793
  function resolveOnPath(name, env) {
56461
57794
  const p2 = env.PATH;
56462
57795
  if (!p2) return void 0;
56463
- for (const dir of p2.split(path9.delimiter)) {
57796
+ for (const dir of p2.split(path12.delimiter)) {
56464
57797
  if (!dir) continue;
56465
57798
  for (const ext of PATH_EXTS) {
56466
- const f2 = path9.join(dir, name + ext);
57799
+ const f2 = path12.join(dir, name + ext);
56467
57800
  try {
56468
- if (fs7.existsSync(f2) && fs7.statSync(f2).isFile()) return f2;
57801
+ if (fs10.existsSync(f2) && fs10.statSync(f2).isFile()) return f2;
56469
57802
  } catch {
56470
57803
  }
56471
57804
  }
@@ -56478,8 +57811,8 @@ function resolveClientCommand(client, env) {
56478
57811
  if (piBin) return { command: piBin, prefixArgs: [] };
56479
57812
  const piResolved = resolveOnPath("pi", env);
56480
57813
  if (piResolved) return { command: piResolved, prefixArgs: [] };
56481
- const cli = path9.join(
56482
- os4.homedir(),
57814
+ const cli = path12.join(
57815
+ os5.homedir(),
56483
57816
  ".pi/agent/npm/node_modules/@earendil-works/pi-coding-agent/dist/cli.js"
56484
57817
  );
56485
57818
  return { command: process.execPath, prefixArgs: [cli] };
@@ -56515,15 +57848,47 @@ async function runLaunch(params, deps = {}) {
56515
57848
  let env;
56516
57849
  let clientArgs = params.clientArgs;
56517
57850
  let piTmpHome;
57851
+ const tmpFiles = [];
57852
+ const directUrl = launcherDirectUrl(process.env);
57853
+ if (directUrl) {
57854
+ if (base === "codex") {
57855
+ console.error(
57856
+ "bili: direct-URL mode \u2014 codex's LLM traffic does NOT go through the proxy, so compression is not applied (only the bili MCP tool calls do). For full compression use the default MITM mode (unset BILI_LAUNCHER_DIRECT)."
57857
+ );
57858
+ } else if (base === "claude") {
57859
+ console.error(
57860
+ "bili: direct-URL mode \u2014 claude's ANTHROPIC_BASE_URL is overridden to the proxy; a pre-configured relay is bypassed unless BILI_CLAUDE_UPSTREAM=<relay> is set. OAuth-subscription traffic requires the default MITM mode."
57861
+ );
57862
+ }
57863
+ }
57864
+ const injectMcp = launcherInjectMcp(process.env, base);
57865
+ if (!injectMcp && (base === "claude" || base === "codex")) {
57866
+ console.error("bili: plugin mode off \u2014 set BILI_LAUNCHER_PLUGIN=1 to enable native MCP tools (experimental; verified with claude 2.1.227 / codex 0.147.0).");
57867
+ }
57868
+ const origin = handle2.origin;
56518
57869
  if (base === "pi") {
56519
- env = buildPiEnv(handle2.origin, ca, process.env);
56520
- piTmpHome = preparePiHttpRewrite(resolvePiHome(process.env), handle2.origin, routes.httpRewrites, routes.httpsRewrites);
57870
+ env = buildPiEnv(origin, ca, process.env);
57871
+ piTmpHome = preparePiHttpRewrite(resolvePiHome(process.env), origin, routes.httpRewrites, routes.httpsRewrites);
56521
57872
  if (piTmpHome) env.PI_CODING_AGENT_DIR = piTmpHome;
56522
57873
  } else if (base === "codex") {
56523
- env = buildCodexEnv(handle2.origin, resolveCombinedCaPath(process.env), process.env);
56524
- clientArgs = buildCodexArgs(handle2.origin, routes.httpRewrites, routes.httpsRewrites, params.clientArgs);
57874
+ const codexConversationId = injectMcp ? randomUUID2() : void 0;
57875
+ if (directUrl) {
57876
+ env = { ...process.env, BILLION_CONTEXT_PROXY: origin };
57877
+ if (codexConversationId) clientArgs = [...buildCodexMcpArgs(origin, codexConversationId), ...clientArgs];
57878
+ } else {
57879
+ env = buildCodexEnv(origin, resolveCombinedCaPath(process.env), process.env);
57880
+ clientArgs = buildCodexArgs(origin, routes.httpRewrites, routes.httpsRewrites, clientArgs);
57881
+ if (injectMcp && codexConversationId) clientArgs = [...buildCodexMcpArgs(origin, codexConversationId), ...clientArgs];
57882
+ }
56525
57883
  } else {
56526
- env = buildClaudeEnv(handle2.origin, ca, routes.httpRewrites, routes.httpsRewrites, process.env);
57884
+ env = directUrl ? buildClaudePluginEnv(origin, true, process.env) : buildClaudeEnv(origin, ca, routes.httpRewrites, routes.httpsRewrites, process.env);
57885
+ if (directUrl) env.BILLION_CONTEXT_PROXY = origin;
57886
+ if (injectMcp) {
57887
+ const mcpFile = path12.join(os5.tmpdir(), `bili-mcp-${Date.now()}.json`);
57888
+ fs10.writeFileSync(mcpFile, JSON.stringify(buildMcpConfig(origin)));
57889
+ tmpFiles.push(mcpFile);
57890
+ clientArgs = ["--mcp-config", mcpFile, ...clientArgs];
57891
+ }
56527
57892
  }
56528
57893
  const { command, prefixArgs } = resolveClientCommand(base, process.env);
56529
57894
  const effectiveClientArgs = piTestArgs(params.client, clientArgs);
@@ -56539,7 +57904,13 @@ async function runLaunch(params, deps = {}) {
56539
57904
  if (!handle2.reused) stopProxy(handle2);
56540
57905
  if (piTmpHome) {
56541
57906
  try {
56542
- fs7.rmSync(piTmpHome, { recursive: true, force: true });
57907
+ fs10.rmSync(piTmpHome, { recursive: true, force: true });
57908
+ } catch {
57909
+ }
57910
+ }
57911
+ for (const f2 of tmpFiles) {
57912
+ try {
57913
+ fs10.rmSync(f2, { force: true });
56543
57914
  } catch {
56544
57915
  }
56545
57916
  }
@@ -56565,8 +57936,8 @@ async function runTestPi(params, deps = {}) {
56565
57936
  }
56566
57937
  const ca = resolveCaCertPath(process.env);
56567
57938
  const env = buildPiEnv(handle2.origin, ca, process.env);
56568
- const sessionDir = path9.join(os4.tmpdir(), `bili-pi-test-${Date.now()}`);
56569
- fs7.mkdirSync(sessionDir, { recursive: true });
57939
+ const sessionDir = path12.join(os5.tmpdir(), `bili-pi-test-${Date.now()}`);
57940
+ fs10.mkdirSync(sessionDir, { recursive: true });
56570
57941
  const args = [
56571
57942
  "-p",
56572
57943
  "--no-session",
@@ -56594,7 +57965,7 @@ async function runTestPi(params, deps = {}) {
56594
57965
 
56595
57966
  // src/export.ts
56596
57967
  import { mkdirSync as mkdirSync6, writeFileSync as writeFileSync5 } from "fs";
56597
- import path10 from "path";
57968
+ import path13 from "path";
56598
57969
  function fmtDate(ms2) {
56599
57970
  return ms2 ? new Date(ms2).toISOString().replace("T", " ").slice(0, 19) + " UTC" : "\u2014";
56600
57971
  }
@@ -56726,7 +58097,7 @@ async function exportSession(selector, opts = {}) {
56726
58097
  }
56727
58098
  const markdown = renderHandoff(matches[0], opts.full ?? false);
56728
58099
  if (opts.output) {
56729
- mkdirSync6(path10.dirname(path10.resolve(opts.output)), { recursive: true });
58100
+ mkdirSync6(path13.dirname(path13.resolve(opts.output)), { recursive: true });
56730
58101
  writeFileSync5(opts.output, markdown, "utf8");
56731
58102
  return `written to ${opts.output}`;
56732
58103
  }
@@ -56735,12 +58106,12 @@ async function exportSession(selector, opts = {}) {
56735
58106
 
56736
58107
  // src/cli.ts
56737
58108
  import { readFileSync as readFileSync5 } from "fs";
56738
- import { fileURLToPath as fileURLToPath3 } from "url";
56739
- import path11 from "path";
56740
- var VERSION = (() => {
58109
+ import { fileURLToPath as fileURLToPath6 } from "url";
58110
+ import path14 from "path";
58111
+ var VERSION3 = (() => {
56741
58112
  try {
56742
- const here = fileURLToPath3(import.meta.url);
56743
- const pkg = path11.join(path11.dirname(here), "..", "package.json");
58113
+ const here = fileURLToPath6(import.meta.url);
58114
+ const pkg = path14.join(path14.dirname(here), "..", "package.json");
56744
58115
  return JSON.parse(readFileSync5(pkg, "utf8")).version ?? "dev";
56745
58116
  } catch {
56746
58117
  return "dev";
@@ -56748,14 +58119,14 @@ var VERSION = (() => {
56748
58119
  })();
56749
58120
  var PACKAGE_NAME = (() => {
56750
58121
  try {
56751
- const here = fileURLToPath3(import.meta.url);
56752
- const pkg = path11.join(path11.dirname(here), "..", "package.json");
58122
+ const here = fileURLToPath6(import.meta.url);
58123
+ const pkg = path14.join(path14.dirname(here), "..", "package.json");
56753
58124
  return JSON.parse(readFileSync5(pkg, "utf8")).name ?? "billion-context";
56754
58125
  } catch {
56755
58126
  return "billion-context";
56756
58127
  }
56757
58128
  })();
56758
- var HELP = `bili ${VERSION} \u2014 billion-context proxy
58129
+ var HELP = `bili ${VERSION3} \u2014 billion-context proxy
56759
58130
 
56760
58131
  Usage:
56761
58132
  bili [start] [options] start the proxy (default: reads ${configFile()})
@@ -56767,6 +58138,13 @@ Usage:
56767
58138
  bili export [session] [--full] list sessions / export one as a Markdown handoff
56768
58139
  (--full includes original messages; --output FILE)
56769
58140
  bili update check for & install a newer version now
58141
+ bili plugin install <agent> install the thin plugin into a host (pi/omp/
58142
+ claude/codex/opencode; original backed up once)
58143
+ bili plugin remove <agent> remove it again
58144
+ bili plugin list show install status for every host
58145
+ bili mcp run the bili MCP server standalone (stdio)
58146
+ bili plugin-register <id> pre-bind a conversation to the plugin mode
58147
+ (--origin URL, --agent name)
56770
58148
  bili --version print version
56771
58149
  bili --help show this help
56772
58150
 
@@ -56809,8 +58187,11 @@ function parseArgs(argv) {
56809
58187
  let clientArgs = [];
56810
58188
  const mitmDomains = [];
56811
58189
  let exportSelector;
58190
+ let registerConversationId;
56812
58191
  let exportOutput;
56813
58192
  let exportFull = false;
58193
+ let pluginAction;
58194
+ let pluginAgent;
56814
58195
  for (let i = 0; i < argv.length; i++) {
56815
58196
  const a = argv[i];
56816
58197
  if (!client && positional.length === 0 && isLaunchClient(a)) {
@@ -56862,15 +58243,19 @@ function parseArgs(argv) {
56862
58243
  }
56863
58244
  case "--port":
56864
58245
  case "--host":
56865
- case "--config": {
58246
+ case "--config":
58247
+ case "--origin":
58248
+ case "--agent": {
56866
58249
  const val = argv[++i];
56867
- if (val === void 0) {
56868
- console.error(`bili: ${a} requires a value`);
58250
+ if (val === void 0 || val.length === 0) {
58251
+ console.error(`bili: ${a} requires a non-empty value`);
56869
58252
  process.exit(2);
56870
58253
  }
56871
58254
  if (a === "--port") overrides.ACP_PORT = val;
56872
58255
  else if (a === "--host") overrides.ACP_HOST = val;
56873
- else overrides.BILI_CONFIG_FILE = val;
58256
+ else if (a === "--config") overrides.BILI_CONFIG_FILE = val;
58257
+ else if (a === "--origin") overrides.BILI_MCP_PROXY = val;
58258
+ else overrides.BILI_PLUGIN_AGENT = val;
56874
58259
  break;
56875
58260
  }
56876
58261
  default:
@@ -56898,6 +58283,32 @@ function parseArgs(argv) {
56898
58283
  } else if (cmd === "export") {
56899
58284
  command = "export";
56900
58285
  exportSelector = positional[1];
58286
+ } else if (cmd === "plugin-register") {
58287
+ command = "plugin-register";
58288
+ registerConversationId = positional[1];
58289
+ } else if (cmd === "mcp") {
58290
+ command = "mcp";
58291
+ } else if (cmd === "plugin") {
58292
+ command = "plugin";
58293
+ const action = positional[1];
58294
+ if (action === "install" || action === "remove" || action === "list") {
58295
+ pluginAction = action;
58296
+ } else {
58297
+ console.error(`bili plugin: unknown action "${action ?? ""}" (try "bili plugin install|remove|list <agent>")`);
58298
+ process.exit(2);
58299
+ }
58300
+ const agent = positional[2];
58301
+ if (agent !== void 0) {
58302
+ if (!isPluginAgent(agent)) {
58303
+ console.error(`bili plugin: unknown agent "${agent}" (try one of: ${PLUGIN_AGENTS.join(", ")})`);
58304
+ process.exit(2);
58305
+ }
58306
+ pluginAgent = agent;
58307
+ }
58308
+ if (pluginAction !== "list" && pluginAgent === void 0) {
58309
+ console.error(`bili plugin ${pluginAction}: agent is required (try one of: ${PLUGIN_AGENTS.join(", ")})`);
58310
+ process.exit(2);
58311
+ }
56901
58312
  } else if (cmd === "test") {
56902
58313
  const target = positional[1];
56903
58314
  if (target && isLaunchClient(target)) {
@@ -56912,18 +58323,72 @@ function parseArgs(argv) {
56912
58323
  process.exit(2);
56913
58324
  }
56914
58325
  }
56915
- return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull };
58326
+ return { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, registerConversationId, pluginAction, pluginAgent };
56916
58327
  }
56917
58328
  async function main() {
56918
- const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull } = parseArgs(process.argv.slice(2));
58329
+ const { command, client, clientArgs, mitmDomains, overrides, exportSelector, exportOutput, exportFull, registerConversationId, pluginAction, pluginAgent } = parseArgs(process.argv.slice(2));
56919
58330
  if (command === "help") {
56920
58331
  process.stdout.write(HELP);
56921
58332
  return;
56922
58333
  }
56923
58334
  if (command === "version") {
56924
- process.stdout.write(VERSION + "\n");
58335
+ process.stdout.write(VERSION3 + "\n");
58336
+ return;
58337
+ }
58338
+ if (command === "plugin-register") {
58339
+ const conversationId2 = registerConversationId?.trim();
58340
+ if (!conversationId2) {
58341
+ console.error('bili plugin-register: conversation id is required (e.g. bili plugin-register "$CLAUDE_SESSION_ID" --origin http://127.0.0.1:8787 --agent claude)');
58342
+ process.exit(2);
58343
+ }
58344
+ const agent = (overrides.BILI_PLUGIN_AGENT ?? process.env.BILI_PLUGIN_AGENT ?? "claude").trim() || "claude";
58345
+ const origin = (overrides.BILI_MCP_PROXY ?? process.env.BILI_MCP_PROXY ?? "http://127.0.0.1:8787").replace(/\/$/, "");
58346
+ try {
58347
+ const res = await fetch(`${origin}/__bili/plugin/register`, {
58348
+ method: "POST",
58349
+ headers: { "content-type": "application/json" },
58350
+ body: JSON.stringify({ conversationId: conversationId2, agent, identity: true }),
58351
+ signal: AbortSignal.timeout(5e3)
58352
+ });
58353
+ const data = await res.json();
58354
+ if (!res.ok || !data.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
58355
+ } catch (error) {
58356
+ console.error(`bili plugin-register: ${error instanceof Error ? error.message : String(error)}`);
58357
+ process.exit(1);
58358
+ }
56925
58359
  return;
56926
58360
  }
58361
+ if (command === "mcp") {
58362
+ runMcpStdio();
58363
+ return;
58364
+ }
58365
+ if (command === "plugin") {
58366
+ if (overrides.BILI_MCP_PROXY !== void 0) process.env.BILI_MCP_PROXY = overrides.BILI_MCP_PROXY;
58367
+ if (pluginAction === "list") {
58368
+ for (const row of pluginStatusAll()) {
58369
+ console.log(`${row.agent.padEnd(10)} ${row.status}`);
58370
+ }
58371
+ return;
58372
+ }
58373
+ if (pluginAction === "install") {
58374
+ try {
58375
+ console.log(pluginInstall(pluginAgent));
58376
+ } catch (error) {
58377
+ console.error(`bili plugin: ${error instanceof Error ? error.message : String(error)}`);
58378
+ process.exit(1);
58379
+ }
58380
+ return;
58381
+ }
58382
+ if (pluginAction === "remove") {
58383
+ try {
58384
+ console.log(pluginRemove(pluginAgent));
58385
+ } catch (error) {
58386
+ console.error(`bili plugin: ${error instanceof Error ? error.message : String(error)}`);
58387
+ process.exit(1);
58388
+ }
58389
+ return;
58390
+ }
58391
+ }
56927
58392
  if (command === "export") {
56928
58393
  try {
56929
58394
  const text = await exportSession(exportSelector, { output: exportOutput, full: exportFull });
@@ -56935,7 +58400,7 @@ async function main() {
56935
58400
  return;
56936
58401
  }
56937
58402
  if (command === "update") {
56938
- await checkForUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true }, true);
58403
+ await checkForUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION3, autoUpdate: true }, true);
56939
58404
  return;
56940
58405
  }
56941
58406
  if (command === "test") {
@@ -56957,7 +58422,7 @@ async function main() {
56957
58422
  const opts = loadOptions();
56958
58423
  await startServer(opts);
56959
58424
  if (opts.autoUpdate) {
56960
- startAutoUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION, autoUpdate: true });
58425
+ startAutoUpdate({ packageName: PACKAGE_NAME, currentVersion: VERSION3, autoUpdate: true });
56961
58426
  }
56962
58427
  }
56963
58428