billion-context 0.1.79 → 0.1.80-pr.508.331

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
@@ -132,17 +132,17 @@ var require_timers = __commonJS({
132
132
  let idx = 0;
133
133
  let len = fastTimers.length;
134
134
  while (idx < len) {
135
- const timer2 = fastTimers[idx];
136
- if (timer2._state === PENDING) {
137
- timer2._idleStart = fastNow - TICK_MS;
138
- timer2._state = ACTIVE;
139
- } else if (timer2._state === ACTIVE && fastNow >= timer2._idleStart + timer2._idleTimeout) {
140
- timer2._state = TO_BE_CLEARED;
141
- timer2._idleStart = -1;
142
- timer2._onTimeout(timer2._timerArg);
143
- }
144
- if (timer2._state === TO_BE_CLEARED) {
145
- timer2._state = NOT_IN_LIST;
135
+ const timer3 = fastTimers[idx];
136
+ if (timer3._state === PENDING) {
137
+ timer3._idleStart = fastNow - TICK_MS;
138
+ timer3._state = ACTIVE;
139
+ } else if (timer3._state === ACTIVE && fastNow >= timer3._idleStart + timer3._idleTimeout) {
140
+ timer3._state = TO_BE_CLEARED;
141
+ timer3._idleStart = -1;
142
+ timer3._onTimeout(timer3._timerArg);
143
+ }
144
+ if (timer3._state === TO_BE_CLEARED) {
145
+ timer3._state = NOT_IN_LIST;
146
146
  if (--len !== 0) {
147
147
  fastTimers[idx] = fastTimers[len];
148
148
  }
@@ -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 path17 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
1144
+ let path18 = 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 (path17 && path17[0] !== "/") {
1149
- path17 = `/${path17}`;
1148
+ if (path18 && path18[0] !== "/") {
1149
+ path18 = `/${path18}`;
1150
1150
  }
1151
- return new URL(`${origin}${path17}`);
1151
+ return new URL(`${origin}${path18}`);
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: path17, origin }
1972
+ request: { method, path: path18, origin }
1973
1973
  } = evt;
1974
- debugLog("sending request to %s %s%s", method, origin, path17);
1974
+ debugLog("sending request to %s %s%s", method, origin, path18);
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: path17, origin },
1992
+ request: { method, path: path18, 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
- path17,
1999
+ path18,
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: path17, origin }
2008
+ request: { method, path: path18, origin }
2009
2009
  } = evt;
2010
- debugLog("trailers received from %s %s%s", method, origin, path17);
2010
+ debugLog("trailers received from %s %s%s", method, origin, path18);
2011
2011
  }
2012
2012
  );
2013
2013
  diagnosticsChannel.subscribe(
2014
2014
  "undici:request:error",
2015
2015
  (evt) => {
2016
2016
  const {
2017
- request: { method, path: path17, origin },
2017
+ request: { method, path: path18, 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
- path17,
2024
+ path18,
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: path17,
2139
+ path: path18,
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 path17 !== "string") {
2156
+ if (typeof path18 !== "string") {
2157
2157
  throw new InvalidArgumentError("path must be a string");
2158
- } else if (path17[0] !== "/" && !(path17.startsWith("http://") || path17.startsWith("https://")) && method !== "CONNECT") {
2158
+ } else if (path18[0] !== "/" && !(path18.startsWith("http://") || path18.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(path17)) {
2160
+ } else if (invalidPathRegex.test(path18)) {
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(path17, query) : path17;
2235
+ this.path = query ? serializePathWithQuery(path18, query) : path18;
2236
2236
  this.origin = origin;
2237
2237
  this.protocol = getProtocolFromUrlString(origin);
2238
2238
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -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: path17, host, upgrade, blocking, reset } = request;
7418
+ const { method, path: path18, 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} ${path17} HTTP/1.1\r
7496
+ let header = `${method} ${path18} 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: path17, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
8149
+ const { method, path: path18, 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] = path17;
8217
+ headers[HTTP2_HEADER_PATH] = path18;
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] = path17;
8258
+ headers[HTTP2_HEADER_PATH] = path18;
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: path17 = "/",
10601
+ path: path18 = "/",
10602
10602
  headers = {}
10603
10603
  } = opts;
10604
- opts.path = origin + path17;
10604
+ opts.path = origin + path18;
10605
10605
  if (!("host" in headers) && !("Host" in headers)) {
10606
10606
  const { host } = new URL(origin);
10607
10607
  headers.host = host;
@@ -12684,20 +12684,20 @@ var require_mock_utils = __commonJS({
12684
12684
  }
12685
12685
  return normalizedQp;
12686
12686
  }
12687
- function safeUrl(path17) {
12688
- if (typeof path17 !== "string") {
12689
- return path17;
12687
+ function safeUrl(path18) {
12688
+ if (typeof path18 !== "string") {
12689
+ return path18;
12690
12690
  }
12691
- const pathSegments = path17.split("?", 3);
12691
+ const pathSegments = path18.split("?", 3);
12692
12692
  if (pathSegments.length !== 2) {
12693
- return path17;
12693
+ return path18;
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: path17, method, body, headers }) {
12700
- const pathMatch = matchValue(mockDispatch2.path, path17);
12699
+ function matchKey(mockDispatch2, { path: path18, method, body, headers }) {
12700
+ const pathMatch = matchValue(mockDispatch2.path, path18);
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: path17, ignoreTrailingSlash }) => {
12726
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path17)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path17), resolvedPath);
12725
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path18, ignoreTrailingSlash }) => {
12726
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path18)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path18), 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(path17) {
12766
- while (path17.endsWith("/")) {
12767
- path17 = path17.slice(0, -1);
12765
+ function removeTrailingSlash(path18) {
12766
+ while (path18.endsWith("/")) {
12767
+ path18 = path18.slice(0, -1);
12768
12768
  }
12769
- if (path17.length === 0) {
12770
- path17 = "/";
12769
+ if (path18.length === 0) {
12770
+ path18 = "/";
12771
12771
  }
12772
- return path17;
12772
+ return path18;
12773
12773
  }
12774
12774
  function buildKey(opts) {
12775
- const { path: path17, method, body, headers, query } = opts;
12775
+ const { path: path18, method, body, headers, query } = opts;
12776
12776
  return {
12777
- path: path17,
12777
+ path: path18,
12778
12778
  method,
12779
12779
  body,
12780
12780
  headers,
@@ -12825,22 +12825,22 @@ var require_mock_utils = __commonJS({
12825
12825
  return true;
12826
12826
  }
12827
12827
  let aborted = false;
12828
- let timer2 = null;
12828
+ let timer3 = null;
12829
12829
  function abort(err2) {
12830
12830
  if (aborted) {
12831
12831
  return;
12832
12832
  }
12833
12833
  aborted = true;
12834
- if (timer2 !== null) {
12835
- clearTimeout(timer2);
12836
- timer2 = null;
12834
+ if (timer3 !== null) {
12835
+ clearTimeout(timer3);
12836
+ timer3 = null;
12837
12837
  }
12838
12838
  handler.onError(err2);
12839
12839
  }
12840
12840
  handler.onConnect?.(abort, null);
12841
12841
  if (typeof delay === "number" && delay > 0) {
12842
- timer2 = setTimeout(() => {
12843
- timer2 = null;
12842
+ timer3 = setTimeout(() => {
12843
+ timer3 = null;
12844
12844
  handleReply(this[kDispatches]);
12845
12845
  }, delay);
12846
12846
  } else {
@@ -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: path17, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
13467
+ ({ method, path: path18, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
13468
13468
  Method: method,
13469
13469
  Origin: origin,
13470
- Path: path17,
13470
+ Path: path18,
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 [path17, searchParams] = dispatchOpts.path.split("?");
13552
+ const [path18, searchParams] = dispatchOpts.path.split("?");
13553
13553
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
13554
- dispatchOpts.path = `${path17}?${normalizedSearchParams}`;
13554
+ dispatchOpts.path = `${path18}?${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 path17 = filePath || this.#snapshotPath;
13956
- if (!path17) {
13955
+ const path18 = filePath || this.#snapshotPath;
13956
+ if (!path18) {
13957
13957
  throw new InvalidArgumentError("Snapshot path is required");
13958
13958
  }
13959
13959
  try {
13960
- const data = await readFile3(resolve(path17), "utf8");
13960
+ const data = await readFile3(resolve(path18), "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 ${path17}`, { cause: error });
13974
+ throw new UndiciError(`Failed to load snapshots from ${path18}`, { 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 path17 = filePath || this.#snapshotPath;
13986
- if (!path17) {
13985
+ const path18 = filePath || this.#snapshotPath;
13986
+ if (!path18) {
13987
13987
  throw new InvalidArgumentError("Snapshot path is required");
13988
13988
  }
13989
- const resolvedPath = resolve(path17);
13989
+ const resolvedPath = resolve(path18);
13990
13990
  await mkdir3(dirname5(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 path17 = search ? `${pathname}${search}` : pathname;
14622
- const redirectUrlString = `${origin}${path17}`;
14621
+ const path18 = search ? `${pathname}${search}` : pathname;
14622
+ const redirectUrlString = `${origin}${path18}`;
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 = path17;
14629
+ this.opts.path = path18;
14630
14630
  this.opts.origin = origin;
14631
14631
  this.opts.query = null;
14632
14632
  }
@@ -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, path17) {
16398
+ function deleteCachedUri(store, cacheKey, path18) {
16399
16399
  deleteCachedValue(store, {
16400
16400
  ...cacheKey,
16401
- path: path17
16401
+ path: path18
16402
16402
  });
16403
16403
  for (let i = 0; i < util.safeHTTPMethods.length; i++) {
16404
16404
  const method = util.safeHTTPMethods[i];
@@ -16406,7 +16406,7 @@ var require_cache_handler = __commonJS({
16406
16406
  deleteCachedValue(store, {
16407
16407
  ...cacheKey,
16408
16408
  method,
16409
- path: path17
16409
+ path: path18
16410
16410
  });
16411
16411
  }
16412
16412
  }
@@ -16417,9 +16417,9 @@ var require_cache_handler = __commonJS({
16417
16417
  }
16418
16418
  const values = Array.isArray(headerValue3) ? headerValue3 : [headerValue3];
16419
16419
  for (let i = 0; i < values.length; i++) {
16420
- const path17 = getSameOriginPath(cacheKey, values[i]);
16421
- if (path17 !== void 0) {
16422
- deleteCachedUri(store, cacheKey, path17);
16420
+ const path18 = getSameOriginPath(cacheKey, values[i]);
16421
+ if (path18 !== void 0) {
16422
+ deleteCachedUri(store, cacheKey, path18);
16423
16423
  }
16424
16424
  }
16425
16425
  }
@@ -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 path17 = url.pathname + url.search;
21300
+ const path18 = 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 ? `${path17}?` : path17,
21304
+ path: hasTrailingQuestionMark ? `${path18}?` : path18,
21305
21305
  origin: url.origin,
21306
21306
  method: request.method,
21307
21307
  body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
@@ -22248,9 +22248,9 @@ var require_util4 = __commonJS({
22248
22248
  }
22249
22249
  }
22250
22250
  }
22251
- function validateCookiePath(path17) {
22252
- for (let i = 0; i < path17.length; ++i) {
22253
- const code = path17.charCodeAt(i);
22251
+ function validateCookiePath(path18) {
22252
+ for (let i = 0; i < path18.length; ++i) {
22253
+ const code = path18.charCodeAt(i);
22254
22254
  if (code < 32 || // exclude CTLs (0-31)
22255
22255
  code > 126 || // exclude DEL and non-ascii
22256
22256
  code === 59) {
@@ -22944,7 +22944,7 @@ var require_constants5 = __commonJS({
22944
22944
  writable: false,
22945
22945
  configurable: false
22946
22946
  };
22947
- var states = {
22947
+ var states2 = {
22948
22948
  CONNECTING: 0,
22949
22949
  OPEN: 1,
22950
22950
  CLOSING: 2,
@@ -22980,7 +22980,7 @@ var require_constants5 = __commonJS({
22980
22980
  uid,
22981
22981
  sentCloseFrameState,
22982
22982
  staticPropertyDescriptors,
22983
- states,
22983
+ states: states2,
22984
22984
  opcodes,
22985
22985
  maxUnsigned16Bit,
22986
22986
  parserStates,
@@ -22994,21 +22994,21 @@ var require_constants5 = __commonJS({
22994
22994
  var require_util5 = __commonJS({
22995
22995
  "node_modules/undici/lib/web/websocket/util.js"(exports, module) {
22996
22996
  "use strict";
22997
- var { states, opcodes } = require_constants5();
22997
+ var { states: states2, opcodes } = require_constants5();
22998
22998
  var { isUtf8 } = __require("buffer");
22999
22999
  var { removeHTTPWhitespace } = require_data_url();
23000
23000
  var { collectASequenceOfCodePointsFast } = require_infra();
23001
23001
  function isConnecting(readyState) {
23002
- return readyState === states.CONNECTING;
23002
+ return readyState === states2.CONNECTING;
23003
23003
  }
23004
23004
  function isEstablished(readyState) {
23005
- return readyState === states.OPEN;
23005
+ return readyState === states2.OPEN;
23006
23006
  }
23007
23007
  function isClosing(readyState) {
23008
- return readyState === states.CLOSING;
23008
+ return readyState === states2.CLOSING;
23009
23009
  }
23010
23010
  function isClosed(readyState) {
23011
- return readyState === states.CLOSED;
23011
+ return readyState === states2.CLOSED;
23012
23012
  }
23013
23013
  function fireEvent(e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
23014
23014
  const event = eventFactory(e, eventInitDict);
@@ -23276,7 +23276,7 @@ var require_frame = __commonJS({
23276
23276
  var require_connection = __commonJS({
23277
23277
  "node_modules/undici/lib/web/websocket/connection.js"(exports, module) {
23278
23278
  "use strict";
23279
- var { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require_constants5();
23279
+ var { uid, states: states2, sentCloseFrameState, emptyBuffer, opcodes } = require_constants5();
23280
23280
  var { parseExtensions, isClosed, isClosing, isEstablished, isConnecting, validateCloseCodeAndReason } = require_util5();
23281
23281
  var { makeRequest } = require_request2();
23282
23282
  var { fetching } = require_fetch();
@@ -23383,7 +23383,7 @@ var require_connection = __commonJS({
23383
23383
  if (isClosed(object.readyState) || isClosing(object.readyState)) {
23384
23384
  } else if (!isEstablished(object.readyState)) {
23385
23385
  failWebsocketConnection(object);
23386
- object.readyState = states.CLOSING;
23386
+ object.readyState = states2.CLOSING;
23387
23387
  } else if (!object.closeState.has(sentCloseFrameState.SENT) && !object.closeState.has(sentCloseFrameState.RECEIVED)) {
23388
23388
  const frame = new WebsocketFrameSend();
23389
23389
  if (reason.length !== 0 && code === null) {
@@ -23404,9 +23404,9 @@ var require_connection = __commonJS({
23404
23404
  }
23405
23405
  object.socket.write(frame.createFrame(opcodes.CLOSE));
23406
23406
  object.closeState.add(sentCloseFrameState.SENT);
23407
- object.readyState = states.CLOSING;
23407
+ object.readyState = states2.CLOSING;
23408
23408
  } else {
23409
- object.readyState = states.CLOSING;
23409
+ object.readyState = states2.CLOSING;
23410
23410
  }
23411
23411
  }
23412
23412
  function failWebsocketConnection(handler, code, reason, cause) {
@@ -23515,7 +23515,7 @@ var require_receiver = __commonJS({
23515
23515
  "use strict";
23516
23516
  var { Writable } = __require("stream");
23517
23517
  var assert = __require("assert");
23518
- var { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require_constants5();
23518
+ var { parserStates, opcodes, states: states2, emptyBuffer, sentCloseFrameState } = require_constants5();
23519
23519
  var {
23520
23520
  isValidStatusCode,
23521
23521
  isValidOpcode,
@@ -23844,7 +23844,7 @@ var require_receiver = __commonJS({
23844
23844
  this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE));
23845
23845
  this.#handler.closeState.add(sentCloseFrameState.SENT);
23846
23846
  }
23847
- this.#handler.readyState = states.CLOSING;
23847
+ this.#handler.readyState = states2.CLOSING;
23848
23848
  this.#handler.closeState.add(sentCloseFrameState.RECEIVED);
23849
23849
  return false;
23850
23850
  } else if (opcode === opcodes.PING) {
@@ -23963,7 +23963,7 @@ var require_websocket = __commonJS({
23963
23963
  var { webidl } = require_webidl();
23964
23964
  var { URLSerializer } = require_data_url();
23965
23965
  var { environmentSettingsObject } = require_util2();
23966
- var { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = require_constants5();
23966
+ var { staticPropertyDescriptors, states: states2, sentCloseFrameState, sendHints, opcodes } = require_constants5();
23967
23967
  var {
23968
23968
  isConnecting,
23969
23969
  isEstablished,
@@ -24016,7 +24016,7 @@ var require_websocket = __commonJS({
24016
24016
  }
24017
24017
  },
24018
24018
  onSocketError: (err2) => {
24019
- this.#handler.readyState = states.CLOSING;
24019
+ this.#handler.readyState = states2.CLOSING;
24020
24020
  if (channels.socketError.hasSubscribers) {
24021
24021
  channels.socketError.publish(err2);
24022
24022
  }
@@ -24039,7 +24039,7 @@ var require_websocket = __commonJS({
24039
24039
  });
24040
24040
  }
24041
24041
  },
24042
- readyState: states.CONNECTING,
24042
+ readyState: states2.CONNECTING,
24043
24043
  socket: null,
24044
24044
  closeState: /* @__PURE__ */ new Set(),
24045
24045
  controller: null,
@@ -24256,7 +24256,7 @@ var require_websocket = __commonJS({
24256
24256
  parser.on("error", (err2) => this.#handler.onParserError(err2));
24257
24257
  this.#parser = parser;
24258
24258
  this.#sendQueue = new SendQueue(response.socket);
24259
- this.#handler.readyState = states.OPEN;
24259
+ this.#handler.readyState = states2.OPEN;
24260
24260
  const extensions = response.headersList.get("sec-websocket-extensions");
24261
24261
  if (extensions !== null) {
24262
24262
  this.#extensions = extensions;
@@ -24282,7 +24282,7 @@ var require_websocket = __commonJS({
24282
24282
  }
24283
24283
  }
24284
24284
  #onMessage(type, data) {
24285
- if (this.#handler.readyState !== states.OPEN) {
24285
+ if (this.#handler.readyState !== states2.OPEN) {
24286
24286
  return;
24287
24287
  }
24288
24288
  let dataForEvent;
@@ -24321,7 +24321,7 @@ var require_websocket = __commonJS({
24321
24321
  code = result.code ?? 1005;
24322
24322
  reason = result.reason;
24323
24323
  }
24324
- this.#handler.readyState = states.CLOSED;
24324
+ this.#handler.readyState = states2.CLOSED;
24325
24325
  if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
24326
24326
  code = 1006;
24327
24327
  fireEvent("error", this, (type, init) => new ErrorEvent(type, init), {
@@ -24362,10 +24362,10 @@ var require_websocket = __commonJS({
24362
24362
  };
24363
24363
  var { ping } = WebSocket;
24364
24364
  Reflect.deleteProperty(WebSocket, "ping");
24365
- WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING;
24366
- WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN;
24367
- WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING;
24368
- WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED;
24365
+ WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states2.CONNECTING;
24366
+ WebSocket.OPEN = WebSocket.prototype.OPEN = states2.OPEN;
24367
+ WebSocket.CLOSING = WebSocket.prototype.CLOSING = states2.CLOSING;
24368
+ WebSocket.CLOSED = WebSocket.prototype.CLOSED = states2.CLOSED;
24369
24369
  Object.defineProperties(WebSocket.prototype, {
24370
24370
  CONNECTING: staticPropertyDescriptors,
24371
24371
  OPEN: staticPropertyDescriptors,
@@ -24531,7 +24531,7 @@ var require_websocketstream = __commonJS({
24531
24531
  "use strict";
24532
24532
  var { createDeferredPromise } = require_promise();
24533
24533
  var { environmentSettingsObject } = require_util2();
24534
- var { states, opcodes, sentCloseFrameState } = require_constants5();
24534
+ var { states: states2, opcodes, sentCloseFrameState } = require_constants5();
24535
24535
  var { webidl } = require_webidl();
24536
24536
  var { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require_util5();
24537
24537
  var { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = require_connection();
@@ -24575,7 +24575,7 @@ var require_websocketstream = __commonJS({
24575
24575
  }
24576
24576
  },
24577
24577
  onSocketError: (err2) => {
24578
- this.#handler.readyState = states.CLOSING;
24578
+ this.#handler.readyState = states2.CLOSING;
24579
24579
  if (channels.socketError.hasSubscribers) {
24580
24580
  channels.socketError.publish(err2);
24581
24581
  }
@@ -24586,7 +24586,7 @@ var require_websocketstream = __commonJS({
24586
24586
  },
24587
24587
  onPong: () => {
24588
24588
  },
24589
- readyState: states.CONNECTING,
24589
+ readyState: states2.CONNECTING,
24590
24590
  socket: null,
24591
24591
  closeState: /* @__PURE__ */ new Set(),
24592
24592
  controller: null,
@@ -24628,7 +24628,7 @@ var require_websocketstream = __commonJS({
24628
24628
  signal.addEventListener("abort", () => {
24629
24629
  if (!isEstablished(this.#handler.readyState)) {
24630
24630
  failWebsocketConnection(this.#handler);
24631
- this.#handler.readyState = states.CLOSING;
24631
+ this.#handler.readyState = states2.CLOSING;
24632
24632
  this.#openedPromise.reject(signal.reason);
24633
24633
  this.#closedPromise.reject(signal.reason);
24634
24634
  this.#handshakeAborted = true;
@@ -24704,7 +24704,7 @@ var require_websocketstream = __commonJS({
24704
24704
  parser.on("drain", () => this.#handler.onParserDrain());
24705
24705
  parser.on("error", (err2) => this.#handler.onParserError(err2));
24706
24706
  this.#parser = parser;
24707
- this.#handler.readyState = states.OPEN;
24707
+ this.#handler.readyState = states2.OPEN;
24708
24708
  const extensions = parsedExtensions ?? "";
24709
24709
  const protocol = response.headersList.get("sec-websocket-protocol") ?? "";
24710
24710
  const readable = new ReadableStream({
@@ -24729,7 +24729,7 @@ var require_websocketstream = __commonJS({
24729
24729
  }
24730
24730
  /** @type {import('../websocket').Handler['onMessage']} */
24731
24731
  #onMessage(type, data) {
24732
- if (this.#handler.readyState !== states.OPEN) {
24732
+ if (this.#handler.readyState !== states2.OPEN) {
24733
24733
  return;
24734
24734
  }
24735
24735
  let chunk;
@@ -24748,7 +24748,7 @@ var require_websocketstream = __commonJS({
24748
24748
  /** @type {import('../websocket').Handler['onSocketClose']} */
24749
24749
  #onSocketClose() {
24750
24750
  const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
24751
- this.#handler.readyState = states.CLOSED;
24751
+ this.#handler.readyState = states2.CLOSED;
24752
24752
  if (this.#handshakeAborted) {
24753
24753
  return;
24754
24754
  }
@@ -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 path17 = opts.path;
25490
+ let path18 = opts.path;
25491
25491
  if (!opts.path.startsWith("/")) {
25492
- path17 = `/${path17}`;
25492
+ path18 = `/${path18}`;
25493
25493
  }
25494
- url = new URL(util.parseOrigin(url).origin + path17);
25494
+ url = new URL(util.parseOrigin(url).origin + path18);
25495
25495
  } else {
25496
25496
  if (!opts) {
25497
25497
  opts = typeof url === "object" ? url : {};
@@ -47526,16 +47526,16 @@ function connectDirect(host, port, timeoutMs = CONNECT_TIMEOUT_MS) {
47526
47526
  const finishError = (error) => {
47527
47527
  if (settled) return;
47528
47528
  settled = true;
47529
- clearTimeout(timer2);
47529
+ clearTimeout(timer3);
47530
47530
  socket.destroy();
47531
47531
  reject(error);
47532
47532
  };
47533
- const timer2 = setTimeout(() => finishError(new Error(`upstream connect ${host}:${port} timed out after ${timeoutMs}ms`)), timeoutMs);
47533
+ const timer3 = setTimeout(() => finishError(new Error(`upstream connect ${host}:${port} timed out after ${timeoutMs}ms`)), timeoutMs);
47534
47534
  socket.once("error", finishError);
47535
47535
  socket.once("connect", () => {
47536
47536
  if (settled) return;
47537
47537
  settled = true;
47538
- clearTimeout(timer2);
47538
+ clearTimeout(timer3);
47539
47539
  resolve(socket);
47540
47540
  });
47541
47541
  });
@@ -47552,11 +47552,11 @@ function connectThroughProxy(host, port, proxyUrl) {
47552
47552
  const finishError = (error) => {
47553
47553
  if (settled) return;
47554
47554
  settled = true;
47555
- clearTimeout(timer2);
47555
+ clearTimeout(timer3);
47556
47556
  socket.destroy();
47557
47557
  reject(error);
47558
47558
  };
47559
- const timer2 = setTimeout(() => finishError(new Error(`upstream proxy CONNECT ${host}:${port} handshake timeout`)), CONNECT_TIMEOUT_MS);
47559
+ const timer3 = setTimeout(() => finishError(new Error(`upstream proxy CONNECT ${host}:${port} handshake timeout`)), CONNECT_TIMEOUT_MS);
47560
47560
  socket.once("error", finishError);
47561
47561
  const connectedEvent = proxy.protocol === "https:" ? "secureConnect" : "connect";
47562
47562
  socket.once(connectedEvent, () => {
@@ -47585,7 +47585,7 @@ function connectThroughProxy(host, port, proxyUrl) {
47585
47585
  return;
47586
47586
  }
47587
47587
  settled = true;
47588
- clearTimeout(timer2);
47588
+ clearTimeout(timer3);
47589
47589
  socket.removeListener("error", finishError);
47590
47590
  const rest = buffer.subarray(end + 4);
47591
47591
  if (rest.length > 0) socket.unshift(rest);
@@ -47651,13 +47651,13 @@ function getUpstreamConnectionStatus() {
47651
47651
  }
47652
47652
 
47653
47653
  // src/config.ts
47654
- function safeReadJson(path17) {
47654
+ function safeReadJson(path18) {
47655
47655
  try {
47656
- const raw = readFileSync(path17, "utf8").replace(/^\uFEFF/, "");
47656
+ const raw = readFileSync(path18, "utf8").replace(/^\uFEFF/, "");
47657
47657
  return JSON.parse(raw);
47658
47658
  } catch (e) {
47659
47659
  if (e.code !== "ENOENT") {
47660
- log("error", `[acp-config] failed to parse ${path17}: ${String(e)}`);
47660
+ log("error", `[acp-config] failed to parse ${path18}: ${String(e)}`);
47661
47661
  }
47662
47662
  return void 0;
47663
47663
  }
@@ -47937,7 +47937,7 @@ function rejectLegacyRoute(key, value) {
47937
47937
 
47938
47938
  // src/server.ts
47939
47939
  import http from "http";
47940
- import fs7 from "fs";
47940
+ import fs8 from "fs";
47941
47941
  import { randomUUID as randomUUID4 } from "crypto";
47942
47942
 
47943
47943
  // src/compress-settings.ts
@@ -48052,11 +48052,11 @@ async function fetchWithTimeout(url, opts, timeoutMs = UPSTREAM_TIMEOUT_MS, exte
48052
48052
  liveUpstreamTimers.add(t);
48053
48053
  return t;
48054
48054
  };
48055
- let timer2 = armTimer();
48055
+ let timer3 = armTimer();
48056
48056
  const rearm = () => {
48057
- clearTimeout(timer2);
48058
- liveUpstreamTimers.delete(timer2);
48059
- timer2 = armTimer();
48057
+ clearTimeout(timer3);
48058
+ liveUpstreamTimers.delete(timer3);
48059
+ timer3 = armTimer();
48060
48060
  };
48061
48061
  let onExternalAbort = null;
48062
48062
  if (externalSignal) {
@@ -48067,8 +48067,8 @@ async function fetchWithTimeout(url, opts, timeoutMs = UPSTREAM_TIMEOUT_MS, exte
48067
48067
  }
48068
48068
  }
48069
48069
  const cleanup = () => {
48070
- clearTimeout(timer2);
48071
- liveUpstreamTimers.delete(timer2);
48070
+ clearTimeout(timer3);
48071
+ liveUpstreamTimers.delete(timer3);
48072
48072
  if (onExternalAbort && externalSignal) externalSignal.removeEventListener("abort", onExternalAbort);
48073
48073
  };
48074
48074
  try {
@@ -48161,13 +48161,13 @@ function replayBackoffMs(attempt) {
48161
48161
  function sleep(ms2, signal) {
48162
48162
  if (ms2 <= 0 || signal?.aborted) return Promise.resolve();
48163
48163
  return new Promise((resolve) => {
48164
- let timer2 = null;
48164
+ let timer3 = null;
48165
48165
  const finish2 = () => {
48166
- if (timer2) clearTimeout(timer2);
48166
+ if (timer3) clearTimeout(timer3);
48167
48167
  if (signal) signal.removeEventListener("abort", finish2);
48168
48168
  resolve();
48169
48169
  };
48170
- timer2 = setTimeout(finish2, ms2);
48170
+ timer3 = setTimeout(finish2, ms2);
48171
48171
  if (signal) signal.addEventListener("abort", finish2, { once: true });
48172
48172
  });
48173
48173
  }
@@ -49389,7 +49389,7 @@ var StateStore = class {
49389
49389
  this.pending.set(id, build2);
49390
49390
  const existing = this.timers.get(id);
49391
49391
  if (existing) return;
49392
- const timer2 = setTimeout(() => {
49392
+ const timer3 = setTimeout(() => {
49393
49393
  this.timers.delete(id);
49394
49394
  const builder = this.pending.get(id);
49395
49395
  this.pending.delete(id);
@@ -49397,8 +49397,8 @@ var StateStore = class {
49397
49397
  void this.writeNow(id, builder).catch(() => {
49398
49398
  });
49399
49399
  }, this.debounceMs);
49400
- timer2.unref?.();
49401
- this.timers.set(id, timer2);
49400
+ timer3.unref?.();
49401
+ this.timers.set(id, timer3);
49402
49402
  }
49403
49403
  /** Immediate save, serialized per id. Rejects on write failure; a
49404
49404
  * failing write never breaks the chain for the next one. */
@@ -49420,9 +49420,9 @@ var StateStore = class {
49420
49420
  * the result to drop in-memory state must NOT drop it on failure. */
49421
49421
  flushSync(id, build2) {
49422
49422
  if (!this.enabled) return true;
49423
- const timer2 = this.timers.get(id);
49424
- if (timer2) {
49425
- clearTimeout(timer2);
49423
+ const timer3 = this.timers.get(id);
49424
+ if (timer3) {
49425
+ clearTimeout(timer3);
49426
49426
  this.timers.delete(id);
49427
49427
  this.pending.delete(id);
49428
49428
  }
@@ -49545,7 +49545,7 @@ var StateStore = class {
49545
49545
  * writes. For graceful shutdown (SIGTERM/SIGINT). Never rejects. */
49546
49546
  async flushAll() {
49547
49547
  const ids = this.pendingIds();
49548
- for (const timer2 of this.timers.values()) clearTimeout(timer2);
49548
+ for (const timer3 of this.timers.values()) clearTimeout(timer3);
49549
49549
  this.timers.clear();
49550
49550
  const builders = /* @__PURE__ */ new Map();
49551
49551
  for (const id of ids) {
@@ -49564,7 +49564,7 @@ var StateStore = class {
49564
49564
  }
49565
49565
  /** Cancel all pending debounced writes without flushing (tests). */
49566
49566
  cancelAll() {
49567
- for (const timer2 of this.timers.values()) clearTimeout(timer2);
49567
+ for (const timer3 of this.timers.values()) clearTimeout(timer3);
49568
49568
  this.timers.clear();
49569
49569
  this.pending.clear();
49570
49570
  }
@@ -49850,6 +49850,7 @@ var SessionStore = class {
49850
49850
  const byLabel = /* @__PURE__ */ new Map();
49851
49851
  let unlabeled = 0;
49852
49852
  for (const [id, envelope] of loaded) {
49853
+ if (id.startsWith("pfa-")) continue;
49853
49854
  const session = buildSession(envelope.payload);
49854
49855
  const label = session.meta.label;
49855
49856
  if (!label) {
@@ -51572,6 +51573,93 @@ ${icon} [ACP] ${inner}
51572
51573
  `;
51573
51574
  }
51574
51575
 
51576
+ // src/weak-overflow.ts
51577
+ var MIN_USAGE = 0.9;
51578
+ var WINDOW_MS = 15 * 60 * 1e3;
51579
+ var MIN_EVENTS = 3;
51580
+ var MAX_TRACKED_SESSIONS = 512;
51581
+ var states = /* @__PURE__ */ new Map();
51582
+ function resolvedWindow2(session) {
51583
+ const md = session.metadata ?? {};
51584
+ const learned = md.learnedContextLimit;
51585
+ const effective = md.effectiveContextLimit;
51586
+ const candidates = [learned, effective].filter((v2) => typeof v2 === "number" && v2 > 0);
51587
+ if (candidates.length === 0) return 0;
51588
+ return Math.min(...candidates);
51589
+ }
51590
+ function noteWeakOverflow(session, opts) {
51591
+ const window2 = resolvedWindow2(session);
51592
+ if (window2 <= 0) return;
51593
+ const input = opts.inputTokens && opts.inputTokens > 0 ? opts.inputTokens : session.stats?.lastInputTokens ?? 0;
51594
+ if (input <= 0) return;
51595
+ if (input / window2 < MIN_USAGE) return;
51596
+ if (states.size > MAX_TRACKED_SESSIONS) {
51597
+ const oldest = states.keys().next().value;
51598
+ if (oldest !== void 0) states.delete(oldest);
51599
+ }
51600
+ const state = states.get(session.id) ?? { events: [] };
51601
+ const now = Date.now();
51602
+ state.events = state.events.filter((t) => now - t < WINDOW_MS);
51603
+ state.events.push(now);
51604
+ states.set(session.id, state);
51605
+ if (state.events.length < MIN_EVENTS) {
51606
+ log("warn", `[${session.id}] weak overflow signal ${state.events.length}/${MIN_EVENTS} (usage ${Math.round(input / window2 * 100)}%, ${opts.reason})`);
51607
+ return;
51608
+ }
51609
+ states.delete(session.id);
51610
+ const md = session.metadata ?? {};
51611
+ if (md.learnedContextLimits === void 0) md.learnedContextLimits = {};
51612
+ const learnedMap = md.learnedContextLimits;
51613
+ const reqModel = opts.model;
51614
+ const prev = (reqModel ? learnedMap[reqModel] : void 0) ?? md.learnedContextLimit;
51615
+ if (prev === void 0 || input < prev) {
51616
+ if (reqModel) learnedMap[reqModel] = input;
51617
+ else md.learnedContextLimit = input;
51618
+ session.metadata = md;
51619
+ log("warn", `[${session.id}] weak overflow confirmed (${MIN_EVENTS}\xD7 high-usage failures, ${opts.reason}) \u2014 learned conservative window ${input} for ${reqModel ?? "(unknown model)"} (was ${prev ?? "unset"}); arming emergency shrink`);
51620
+ } else {
51621
+ log("warn", `[${session.id}] weak overflow confirmed (${MIN_EVENTS}\xD7 high-usage failures, ${opts.reason}) \u2014 conservative window ${input} not below learned ${prev}; arming emergency shrink only`);
51622
+ }
51623
+ if (!session.stats) session.stats = { lastInputTokens: input };
51624
+ else session.stats.lastInputTokens = Math.max(session.stats.lastInputTokens, input);
51625
+ markDirty(session);
51626
+ }
51627
+
51628
+ // src/cache-warn.ts
51629
+ var MIN_INPUT = 8e3;
51630
+ var HIGH_HIT = 0.5;
51631
+ var LOW_HIT = 0.1;
51632
+ var LOW_RUN = 5;
51633
+ var MAX_TRACKED_SESSIONS2 = 1024;
51634
+ var watches = /* @__PURE__ */ new Map();
51635
+ function warnCacheCollapse(session, input, cached) {
51636
+ if (input < MIN_INPUT) return;
51637
+ if (watches.size > MAX_TRACKED_SESSIONS2) {
51638
+ const oldest = watches.keys().next().value;
51639
+ if (oldest !== void 0) watches.delete(oldest);
51640
+ }
51641
+ const watch = watches.get(session.id) ?? { sawHigh: false, lowRun: 0, warned: false };
51642
+ watches.set(session.id, watch);
51643
+ const hit = cached / input;
51644
+ if (hit >= HIGH_HIT) {
51645
+ watch.sawHigh = true;
51646
+ watch.lowRun = 0;
51647
+ return;
51648
+ }
51649
+ if (!watch.sawHigh || watch.warned) return;
51650
+ if (hit > LOW_HIT) {
51651
+ watch.lowRun = 0;
51652
+ return;
51653
+ }
51654
+ watch.lowRun++;
51655
+ if (watch.lowRun < LOW_RUN) return;
51656
+ watch.warned = true;
51657
+ log(
51658
+ "warn",
51659
+ `[${session.id}] upstream prompt-cache collapse: ${LOW_RUN} consecutive large requests at ~0% hit (last: input=${input}, cached=${cached}) after earlier \u2265${Math.round(HIGH_HIT * 100)}% hits \u2014 the context is being resent cold every turn. Likely causes: proxy/session restart re-forked the session (#499), or the upstream KV cache was dropped (window/deployment change). Check the session id upstream sees and compress.modelContextLimit.`
51660
+ );
51661
+ }
51662
+
51575
51663
  // src/loop/core.ts
51576
51664
  var MAX_LOOP_ROUNDS = 10;
51577
51665
  function isLoopThinking(m2) {
@@ -51654,6 +51742,7 @@ function recordUsage(ctx, usage, round) {
51654
51742
  }
51655
51743
  if (typeof out === "number") ctx.session.stats.outputTokens += out;
51656
51744
  const hitPct = typeof cached === "number" && total > 0 ? Math.round(cached / total * 100) : 0;
51745
+ warnCacheCollapse(ctx.session, total, cached ?? 0);
51657
51746
  ctx.log(
51658
51747
  `[acp-usage] round ${round} input=${total} cached=${cached ?? 0} (cache hit ${hitPct}%)`
51659
51748
  );
@@ -51908,6 +51997,14 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
51908
51997
  }
51909
51998
  const reRequest = proxyResults.length > 0 && realCalls === 0;
51910
51999
  if (!reRequest) {
52000
+ if (!sawDone || truncatedDone) {
52001
+ const reqModel = typeof requestBody["model"] === "string" ? requestBody["model"] : void 0;
52002
+ noteWeakOverflow(ctx.session, {
52003
+ inputTokens: usage.inputTokens,
52004
+ model: reqModel,
52005
+ reason: `round ${round}: upstream stream truncated without a completion event`
52006
+ });
52007
+ }
51911
52008
  if (!sawDone) {
51912
52009
  const partialText = assistantText.length;
51913
52010
  const partialReasoning = assistantReasoning.length;
@@ -51932,11 +52029,11 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
51932
52029
  let newBody = adapter.buildRequest(coreMessages, systemPrompt, requestBody);
51933
52030
  if (process.env.ACP_DUMP_BODY === "1") {
51934
52031
  try {
51935
- const fs12 = await import("fs");
52032
+ const fs13 = await import("fs");
51936
52033
  const dumpDir = process.env.ACP_DUMP_DIR || `${process.env.HOME}/.local/state/billion-context/dumps`;
51937
- fs12.mkdirSync(dumpDir, { recursive: true });
52034
+ fs13.mkdirSync(dumpDir, { recursive: true });
51938
52035
  const sid = ctx.session.id ?? "unknown";
51939
- fs12.writeFileSync(`${dumpDir}/req-${Date.now()}-${sid}-REREQUEST.json`, JSON.stringify(newBody, null, 2));
52036
+ fs13.writeFileSync(`${dumpDir}/req-${Date.now()}-${sid}-REREQUEST.json`, JSON.stringify(newBody, null, 2));
51940
52037
  } catch {
51941
52038
  }
51942
52039
  }
@@ -51962,6 +52059,12 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
51962
52059
  const suffix = e.attempts > 1 ? ` after ${e.attempts} attempt(s)` : "";
51963
52060
  ctx.log(`[acp-proxy: compress loop upstream error ${e.status}${suffix}: ${e.body.slice(0, 200)}]`);
51964
52061
  log("error", `[acp-loop] upstream error ${e.status}${suffix}: ${e.body.slice(0, 200)}`);
52062
+ const reqModel = typeof requestBody["model"] === "string" ? requestBody["model"] : void 0;
52063
+ noteWeakOverflow(ctx.session, {
52064
+ inputTokens: usage.inputTokens,
52065
+ model: reqModel,
52066
+ reason: `round ${round}: upstream error ${e.status}${suffix}`
52067
+ });
51965
52068
  yield adapter.emitError(`upstream error ${e.status}${suffix}: ${e.body.slice(0, 200)}`);
51966
52069
  return;
51967
52070
  }
@@ -53946,7 +54049,7 @@ function codexTurnIdentity(headers) {
53946
54049
  // src/prefix-affinity.ts
53947
54050
  import { createHash as createHash5 } from "crypto";
53948
54051
  var MIN_CANONICAL_BYTES = 24;
53949
- var MAX_TRACKED_SESSIONS = 256;
54052
+ var MAX_TRACKED_SESSIONS3 = 256;
53950
54053
  var TTL_MS2 = 7 * 24 * 60 * 60 * 1e3;
53951
54054
  var TAIL_WINDOW = 8;
53952
54055
  var MIN_TAIL_MATCH = 3;
@@ -54092,7 +54195,7 @@ var PrefixAffinityResolver = class {
54092
54195
  const tracked = this.trackedChains;
54093
54196
  tracked.delete(sessionId);
54094
54197
  tracked.set(sessionId, { sessionId, depth, tailHash, itemHashes, lastSeen: Date.now() });
54095
- while (tracked.size > MAX_TRACKED_SESSIONS) {
54198
+ while (tracked.size > MAX_TRACKED_SESSIONS3) {
54096
54199
  const oldest = [...tracked.values()].sort((a, b2) => a.lastSeen - b2.lastSeen)[0];
54097
54200
  if (!oldest) break;
54098
54201
  tracked.delete(oldest.sessionId);
@@ -54105,6 +54208,48 @@ var PrefixAffinityResolver = class {
54105
54208
  trackedSessionIds() {
54106
54209
  return [...this.trackedChains.keys()];
54107
54210
  }
54211
+ /** Serializable copy of the tracked chains (for #499 P1a persistence). */
54212
+ exportSnapshot() {
54213
+ return [...this.trackedChains.values()].map((e) => ({
54214
+ sessionId: e.sessionId,
54215
+ depth: e.depth,
54216
+ tailHash: e.tailHash,
54217
+ itemHashes: e.itemHashes,
54218
+ lastSeen: e.lastSeen
54219
+ }));
54220
+ }
54221
+ /** Load chains persisted by a previous process. Entries older than the
54222
+ * TTL are dropped (they would not match anyway). Returns the count
54223
+ * actually imported. Defensive: a corrupt/hand-edited file must never
54224
+ * crash the proxy — malformed entries are skipped. */
54225
+ importSnapshot(entries) {
54226
+ if (!Array.isArray(entries)) return 0;
54227
+ const now = Date.now();
54228
+ let imported = 0;
54229
+ for (const raw of entries) {
54230
+ if (!raw || typeof raw !== "object") continue;
54231
+ const e = raw;
54232
+ if (typeof e.sessionId !== "string" || typeof e.depth !== "number" || typeof e.tailHash !== "string") continue;
54233
+ if (!Array.isArray(e.itemHashes) || e.itemHashes.some((h) => typeof h !== "string")) continue;
54234
+ if (typeof e.lastSeen !== "number" || now - e.lastSeen > TTL_MS2) continue;
54235
+ const entry = {
54236
+ sessionId: e.sessionId,
54237
+ depth: e.depth,
54238
+ tailHash: e.tailHash,
54239
+ itemHashes: e.itemHashes.slice(-MAX_STORED_ITEMS),
54240
+ lastSeen: e.lastSeen
54241
+ };
54242
+ this.trackedChains.delete(entry.sessionId);
54243
+ this.trackedChains.set(entry.sessionId, entry);
54244
+ imported++;
54245
+ }
54246
+ while (this.trackedChains.size > MAX_TRACKED_SESSIONS3) {
54247
+ const oldest = [...this.trackedChains.values()].sort((a, b2) => a.lastSeen - b2.lastSeen)[0];
54248
+ if (!oldest) break;
54249
+ this.trackedChains.delete(oldest.sessionId);
54250
+ }
54251
+ return imported;
54252
+ }
54108
54253
  expire(tracked) {
54109
54254
  if (tracked.size === 0) return;
54110
54255
  const now = Date.now();
@@ -54115,6 +54260,58 @@ var PrefixAffinityResolver = class {
54115
54260
  };
54116
54261
  var prefixAffinity = new PrefixAffinityResolver();
54117
54262
 
54263
+ // src/affinity-persist.ts
54264
+ import fs4 from "fs";
54265
+ import path8 from "path";
54266
+ var PERSIST_DEBOUNCE_MS = 5e3;
54267
+ function affinityFile() {
54268
+ return path8.join(stateDir(), "prefix-affinity.json");
54269
+ }
54270
+ var timer = null;
54271
+ var writing = false;
54272
+ function writeSnapshot() {
54273
+ if (writing) return;
54274
+ writing = true;
54275
+ try {
54276
+ const file = affinityFile();
54277
+ const snapshot = { version: 1, entries: prefixAffinity.exportSnapshot() };
54278
+ const tmp = `${file}.tmp`;
54279
+ fs4.mkdirSync(path8.dirname(file), { recursive: true });
54280
+ fs4.writeFileSync(tmp, JSON.stringify(snapshot));
54281
+ fs4.renameSync(tmp, file);
54282
+ } catch (e) {
54283
+ log("warn", `[prefix-affinity] persist failed (${e instanceof Error ? e.message : String(e)}); affinity survives in memory`);
54284
+ } finally {
54285
+ writing = false;
54286
+ }
54287
+ }
54288
+ function scheduleAffinityPersist() {
54289
+ if (timer) clearTimeout(timer);
54290
+ timer = setTimeout(() => {
54291
+ timer = null;
54292
+ writeSnapshot();
54293
+ }, PERSIST_DEBOUNCE_MS);
54294
+ timer.unref?.();
54295
+ }
54296
+ function flushPrefixAffinity() {
54297
+ if (timer) {
54298
+ clearTimeout(timer);
54299
+ timer = null;
54300
+ }
54301
+ writeSnapshot();
54302
+ }
54303
+ function hydratePrefixAffinity() {
54304
+ try {
54305
+ const file = affinityFile();
54306
+ if (!fs4.existsSync(file)) return;
54307
+ const parsed = JSON.parse(fs4.readFileSync(file, "utf8"));
54308
+ const imported = prefixAffinity.importSnapshot(parsed.entries);
54309
+ if (imported > 0) log("info", `[prefix-affinity] hydrated ${imported} chain(s) from ${path8.basename(file)} \u2014 anonymous sessions reattach across restarts`);
54310
+ } catch (e) {
54311
+ log("warn", `[prefix-affinity] hydrate failed (${e instanceof Error ? e.message : String(e)}); starting with empty affinity`);
54312
+ }
54313
+ }
54314
+
54118
54315
  // node_modules/acp-kernel/dist/panel/index.js
54119
54316
  function topicFallback(summary) {
54120
54317
  const first = summary.split(/[.\n]/)[0] ?? "";
@@ -54258,8 +54455,8 @@ function buildStatusPanel(input) {
54258
54455
 
54259
54456
  // src/plugin.ts
54260
54457
  import { fileURLToPath as fileURLToPath2 } from "url";
54261
- import fs4 from "fs";
54262
- import path8 from "path";
54458
+ import fs5 from "fs";
54459
+ import path9 from "path";
54263
54460
 
54264
54461
  // src/sse-util.ts
54265
54462
  function normalizeSseLineEndings(buf) {
@@ -54271,8 +54468,8 @@ function normalizeSseLineEndings(buf) {
54271
54468
  var PROXY_VERSION = (() => {
54272
54469
  try {
54273
54470
  const here = fileURLToPath2(import.meta.url);
54274
- const pkg = path8.join(path8.dirname(here), "..", "package.json");
54275
- return JSON.parse(fs4.readFileSync(pkg, "utf8")).version ?? "dev";
54471
+ const pkg = path9.join(path9.dirname(here), "..", "package.json");
54472
+ return JSON.parse(fs5.readFileSync(pkg, "utf8")).version ?? "dev";
54276
54473
  } catch {
54277
54474
  return "dev";
54278
54475
  }
@@ -54284,8 +54481,8 @@ var PLUGIN_PROTOCOL_VERSION = 1;
54284
54481
  var VERSION = (() => {
54285
54482
  try {
54286
54483
  const here = fileURLToPath2(import.meta.url);
54287
- const pkg = path8.join(path8.dirname(here), "..", "package.json");
54288
- return JSON.parse(fs4.readFileSync(pkg, "utf8")).version ?? "dev";
54484
+ const pkg = path9.join(path9.dirname(here), "..", "package.json");
54485
+ return JSON.parse(fs5.readFileSync(pkg, "utf8")).version ?? "dev";
54289
54486
  } catch {
54290
54487
  return "dev";
54291
54488
  }
@@ -54314,7 +54511,7 @@ function pluginReportedContextWindow(headers) {
54314
54511
  var MAX_PLUGIN_CONVERSATIONS = 1024;
54315
54512
  var conversations = /* @__PURE__ */ new Map();
54316
54513
  var remembered = /* @__PURE__ */ new Map();
54317
- var conversationsFile = () => path8.join(stateDir(), "plugin-conversations.json");
54514
+ var conversationsFile = () => path9.join(stateDir(), "plugin-conversations.json");
54318
54515
  var conversationsSaveTimer;
54319
54516
  var conversationsDirty = false;
54320
54517
  function writeConversationsFile() {
@@ -54322,11 +54519,11 @@ function writeConversationsFile() {
54322
54519
  try {
54323
54520
  const obj = {};
54324
54521
  for (const [k2, v2] of conversations) obj[k2] = v2;
54325
- fs4.mkdirSync(stateDir(), { recursive: true });
54522
+ fs5.mkdirSync(stateDir(), { recursive: true });
54326
54523
  const filePath = conversationsFile();
54327
54524
  const draft = `${filePath}.${process.pid}.bili-tmp`;
54328
- fs4.writeFileSync(draft, JSON.stringify(obj));
54329
- fs4.renameSync(draft, filePath);
54525
+ fs5.writeFileSync(draft, JSON.stringify(obj));
54526
+ fs5.renameSync(draft, filePath);
54330
54527
  conversationsDirty = false;
54331
54528
  } catch {
54332
54529
  }
@@ -54348,7 +54545,7 @@ function flushConversations() {
54348
54545
  function loadConversations() {
54349
54546
  let raw;
54350
54547
  try {
54351
- raw = fs4.readFileSync(conversationsFile(), "utf8");
54548
+ raw = fs5.readFileSync(conversationsFile(), "utf8");
54352
54549
  } catch {
54353
54550
  return;
54354
54551
  }
@@ -54361,7 +54558,7 @@ function loadConversations() {
54361
54558
  }
54362
54559
  } catch {
54363
54560
  try {
54364
- fs4.renameSync(conversationsFile(), `${conversationsFile()}.corrupt-${Date.now()}`);
54561
+ fs5.renameSync(conversationsFile(), `${conversationsFile()}.corrupt-${Date.now()}`);
54365
54562
  } catch {
54366
54563
  }
54367
54564
  log("warn", "[plugin] plugin-conversations.json is corrupt \u2014 backed up beside the original, starting an empty routing table");
@@ -54647,6 +54844,7 @@ function applyUsageSample(session, sample, protocol) {
54647
54844
  const total = sample.inputTokens + (!includesCached && sample.cachedTokens !== void 0 ? sample.cachedTokens : 0);
54648
54845
  session.stats.inputTokens += total;
54649
54846
  session.stats.lastInputTokens = Math.max(0, total - (session.stats.compressCreditTokens ?? 0));
54847
+ warnCacheCollapse(session, total, sample.cachedTokens ?? 0);
54650
54848
  }
54651
54849
  if (sample.outputTokens !== void 0) session.stats.outputTokens += sample.outputTokens;
54652
54850
  }
@@ -54710,6 +54908,14 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
54710
54908
  markDirty(session);
54711
54909
  }
54712
54910
  };
54911
+ let sawTerminal = false;
54912
+ const maybeNoteTruncated = () => {
54913
+ if (sawTerminal || !session || res.destroyed || res.writableEnded) return;
54914
+ noteWeakOverflow(session, {
54915
+ inputTokens: acc.inputTokens,
54916
+ reason: "plugin chat passthrough stream ended without a completion event"
54917
+ });
54918
+ };
54713
54919
  const pushField = (field, index, text) => {
54714
54920
  const s3 = filterFor(field, index);
54715
54921
  const clean = s3.filter.push(text);
@@ -54795,6 +55001,7 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
54795
55001
  const jsonStr = dataLines.map((l) => l.slice(5).replace(/^ /, "")).join("\n").trim();
54796
55002
  if (!jsonStr) continue;
54797
55003
  if (jsonStr === "[DONE]") {
55004
+ sawTerminal = true;
54798
55005
  await write(flushTails() + rawEvent + "\n\n");
54799
55006
  continue;
54800
55007
  }
@@ -54805,6 +55012,7 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
54805
55012
  await write(rawEvent + "\n\n");
54806
55013
  continue;
54807
55014
  }
55015
+ if (ev["type"] === "message_stop") sawTerminal = true;
54808
55016
  const sample = usageFromSseEvent(ev);
54809
55017
  if (sample) mergeUsageSample(acc, sample);
54810
55018
  const out = protocol === "anthropic" ? processAnthropic(ev, rawEvent) : processOpenai(ev, rawEvent);
@@ -54816,8 +55024,10 @@ data: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: delt
54816
55024
  const rest = flushTails();
54817
55025
  if (rest.length > 0 && !res.destroyed && !res.writableEnded) await write(rest);
54818
55026
  settleUsage();
55027
+ maybeNoteTruncated();
54819
55028
  } catch (e) {
54820
55029
  settleUsage();
55030
+ maybeNoteTruncated();
54821
55031
  if (res.destroyed || res.writableEnded) {
54822
55032
  log2?.("client aborted mid-stream");
54823
55033
  return;
@@ -54862,6 +55072,14 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
54862
55072
  markDirty(session);
54863
55073
  }
54864
55074
  };
55075
+ let sawTerminal = false;
55076
+ const maybeNoteTruncated = () => {
55077
+ if (sawTerminal || !session || res.destroyed || res.writableEnded) return;
55078
+ noteWeakOverflow(session, {
55079
+ inputTokens: acc.inputTokens,
55080
+ reason: "plugin responses passthrough stream ended without a completion event"
55081
+ });
55082
+ };
54865
55083
  let lastDeltaMeta = null;
54866
55084
  const flushTail = (after) => {
54867
55085
  const tail = tagFilter.flush();
@@ -54887,6 +55105,7 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
54887
55105
  if (dataLines.length === 0) continue;
54888
55106
  const jsonStr = dataLines.map((l) => l.slice(5).replace(/^ /, "")).join("\n").trim();
54889
55107
  if (!jsonStr || jsonStr === "[DONE]") {
55108
+ if (jsonStr === "[DONE]") sawTerminal = true;
54890
55109
  await write(rawEvent + "\n\n");
54891
55110
  continue;
54892
55111
  }
@@ -54901,6 +55120,7 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
54901
55120
  if (sample) mergeUsageSample(acc, sample);
54902
55121
  const type = ev["type"];
54903
55122
  if (type === "response.output_text.done" || type === "response.content_part.done" || type === "response.output_item.done" || type === "response.completed" || type === "response.failed" || type === "response.incomplete") {
55123
+ if (type === "response.completed" || type === "response.failed" || type === "response.incomplete") sawTerminal = true;
54904
55124
  const out = containsRenderTagText(jsonStr) ? rebuildEvent(rawEvent, stripResponsesText(ev)) : rawEvent + "\n\n";
54905
55125
  await write(flushTail(out));
54906
55126
  continue;
@@ -54935,8 +55155,10 @@ async function pipePluginResponsesWithStrip(stream2, res, session, log2) {
54935
55155
  if (rest.length > 0) await write(rest);
54936
55156
  }
54937
55157
  settleUsage();
55158
+ maybeNoteTruncated();
54938
55159
  } catch (e) {
54939
55160
  settleUsage();
55161
+ maybeNoteTruncated();
54940
55162
  if (res.destroyed || res.writableEnded) {
54941
55163
  log2?.("client aborted mid-stream");
54942
55164
  return;
@@ -55012,14 +55234,14 @@ async function pipePluginJson(stream2, res, session, protocol) {
55012
55234
  import tls3 from "tls";
55013
55235
 
55014
55236
  // src/discover.ts
55015
- import fs6 from "fs";
55237
+ import fs7 from "fs";
55016
55238
  import os2 from "os";
55017
- import path10 from "path";
55239
+ import path11 from "path";
55018
55240
 
55019
55241
  // src/client-config.ts
55020
- import fs5 from "fs";
55242
+ import fs6 from "fs";
55021
55243
  import os from "os";
55022
- import path9 from "path";
55244
+ import path10 from "path";
55023
55245
  function toModelWindow(id, contextWindow) {
55024
55246
  return typeof id === "string" && id.length > 0 && typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0 ? { id, contextWindow: Math.floor(contextWindow) } : null;
55025
55247
  }
@@ -55028,7 +55250,7 @@ function nonEmpty2(s3) {
55028
55250
  }
55029
55251
  function readJsonObject(filePath) {
55030
55252
  try {
55031
- const txt = fs5.readFileSync(filePath, "utf8");
55253
+ const txt = fs6.readFileSync(filePath, "utf8");
55032
55254
  const parsed = JSON.parse(txt);
55033
55255
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
55034
55256
  } catch {
@@ -55037,19 +55259,19 @@ function readJsonObject(filePath) {
55037
55259
  }
55038
55260
  function resolvePiHome(env) {
55039
55261
  const h = os.homedir();
55040
- return nonEmpty2(env.PI_CODING_AGENT_DIR) ? env.PI_CODING_AGENT_DIR : nonEmpty2(env.PI_HOME) ? env.PI_HOME : path9.join(h, ".pi", "agent");
55262
+ return nonEmpty2(env.PI_CODING_AGENT_DIR) ? env.PI_CODING_AGENT_DIR : nonEmpty2(env.PI_HOME) ? env.PI_HOME : path10.join(h, ".pi", "agent");
55041
55263
  }
55042
55264
  function resolveOmpHome(env) {
55043
55265
  const h = os.homedir();
55044
- return nonEmpty2(env.PI_CODING_AGENT_DIR) ? env.PI_CODING_AGENT_DIR : path9.join(h, ".omp", "agent");
55266
+ return nonEmpty2(env.PI_CODING_AGENT_DIR) ? env.PI_CODING_AGENT_DIR : path10.join(h, ".omp", "agent");
55045
55267
  }
55046
55268
  function resolveHermesHome(env) {
55047
55269
  const h = os.homedir();
55048
- return nonEmpty2(env.HERMES_HOME) ? env.HERMES_HOME : path9.join(h, ".hermes");
55270
+ return nonEmpty2(env.HERMES_HOME) ? env.HERMES_HOME : path10.join(h, ".hermes");
55049
55271
  }
55050
55272
  function resolveDshHome(env) {
55051
55273
  const h = os.homedir();
55052
- return nonEmpty2(env.DSH_HOME) ? env.DSH_HOME : path9.join(h, ".dsh");
55274
+ return nonEmpty2(env.DSH_HOME) ? env.DSH_HOME : path10.join(h, ".dsh");
55053
55275
  }
55054
55276
  function parseDshSettingsYaml(text) {
55055
55277
  const out = [];
@@ -55068,7 +55290,7 @@ function parseDshSettingsYaml(text) {
55068
55290
  function readDshConfig(dshHome) {
55069
55291
  let text;
55070
55292
  try {
55071
- text = fs5.readFileSync(path9.join(dshHome, "settings.yaml"), "utf8");
55293
+ text = fs6.readFileSync(path10.join(dshHome, "settings.yaml"), "utf8");
55072
55294
  } catch {
55073
55295
  return { baseUrls: [] };
55074
55296
  }
@@ -55076,8 +55298,8 @@ function readDshConfig(dshHome) {
55076
55298
  }
55077
55299
  function readClaudeSettings(homeDir, cwd, env = process.env) {
55078
55300
  const files = [
55079
- path9.join(homeDir, ".claude", "settings.json"),
55080
- path9.join(cwd, ".claude", "settings.json")
55301
+ path10.join(homeDir, ".claude", "settings.json"),
55302
+ path10.join(cwd, ".claude", "settings.json")
55081
55303
  ];
55082
55304
  let anthropicBaseUrl;
55083
55305
  let model;
@@ -55150,17 +55372,17 @@ function parseCodexToml(text) {
55150
55372
  return result;
55151
55373
  }
55152
55374
  function readCodexConfig(codexHome) {
55153
- const cfgPath = path9.join(codexHome, "config.toml");
55375
+ const cfgPath = path10.join(codexHome, "config.toml");
55154
55376
  let text;
55155
55377
  try {
55156
- text = fs5.readFileSync(cfgPath, "utf8");
55378
+ text = fs6.readFileSync(cfgPath, "utf8");
55157
55379
  } catch {
55158
55380
  return { providers: {} };
55159
55381
  }
55160
55382
  return parseCodexToml(text);
55161
55383
  }
55162
55384
  function readPiConfig(piHome) {
55163
- const cfgPath = path9.join(piHome, "models.json");
55385
+ const cfgPath = path10.join(piHome, "models.json");
55164
55386
  const obj = readJsonObject(cfgPath);
55165
55387
  const providers = {};
55166
55388
  const rawProviders = obj?.providers;
@@ -55241,10 +55463,10 @@ function parseOmpYaml(text) {
55241
55463
  return result;
55242
55464
  }
55243
55465
  function readOmpConfig(ompHome) {
55244
- const cfgPath = path9.join(ompHome, "models.yml");
55466
+ const cfgPath = path10.join(ompHome, "models.yml");
55245
55467
  let text;
55246
55468
  try {
55247
- text = fs5.readFileSync(cfgPath, "utf8");
55469
+ text = fs6.readFileSync(cfgPath, "utf8");
55248
55470
  } catch {
55249
55471
  return { providers: {} };
55250
55472
  }
@@ -55317,10 +55539,10 @@ function parseHermesYaml(text) {
55317
55539
  return result;
55318
55540
  }
55319
55541
  function readHermesConfig(hermesHome) {
55320
- const cfgPath = path9.join(hermesHome, "config.yaml");
55542
+ const cfgPath = path10.join(hermesHome, "config.yaml");
55321
55543
  let text;
55322
55544
  try {
55323
- text = fs5.readFileSync(cfgPath, "utf8");
55545
+ text = fs6.readFileSync(cfgPath, "utf8");
55324
55546
  } catch {
55325
55547
  return { providers: {} };
55326
55548
  }
@@ -55328,13 +55550,13 @@ function readHermesConfig(hermesHome) {
55328
55550
  }
55329
55551
  function resolveOpencodeConfigFile(env) {
55330
55552
  if (nonEmpty2(env.OPENCODE_CONFIG)) return env.OPENCODE_CONFIG;
55331
- const xdg2 = nonEmpty2(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path9.join(os.homedir(), ".config");
55332
- return path9.join(xdg2, "opencode", "opencode.json");
55553
+ const xdg2 = nonEmpty2(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path10.join(os.homedir(), ".config");
55554
+ return path10.join(xdg2, "opencode", "opencode.json");
55333
55555
  }
55334
55556
  function readOpencodeConfig(file) {
55335
55557
  let text;
55336
55558
  try {
55337
- text = fs5.readFileSync(file, "utf8");
55559
+ text = fs6.readFileSync(file, "utf8");
55338
55560
  } catch {
55339
55561
  return { providers: {} };
55340
55562
  }
@@ -55391,10 +55613,10 @@ function parseZcodeConfig(obj) {
55391
55613
  return result;
55392
55614
  }
55393
55615
  function readZcodeConfig(zcodeHome) {
55394
- const cfgPath = path9.join(zcodeHome, "v2", "config.json");
55616
+ const cfgPath = path10.join(zcodeHome, "v2", "config.json");
55395
55617
  let txt;
55396
55618
  try {
55397
- txt = fs5.readFileSync(cfgPath, "utf8");
55619
+ txt = fs6.readFileSync(cfgPath, "utf8");
55398
55620
  } catch {
55399
55621
  return { providers: {} };
55400
55622
  }
@@ -55410,10 +55632,10 @@ function loadClientConfig(env, cwd) {
55410
55632
  const home = os.homedir();
55411
55633
  const config = {};
55412
55634
  config.claude = readClaudeSettings(home, cwd, env);
55413
- const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path9.join(home, ".codex");
55635
+ const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path10.join(home, ".codex");
55414
55636
  config.codex = readCodexConfig(codexHome);
55415
55637
  config.pi = readPiConfig(resolvePiHome(env));
55416
- const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path9.join(home, ".zcode");
55638
+ const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path10.join(home, ".zcode");
55417
55639
  config.zcode = readZcodeConfig(zcodeHome);
55418
55640
  config.omp = readOmpConfig(resolveOmpHome(env));
55419
55641
  config.opencode = readOpencodeConfig(resolveOpencodeConfigFile(env));
@@ -55480,21 +55702,21 @@ function extractHttpsHosts(config) {
55480
55702
  }
55481
55703
  function configFilePaths(env) {
55482
55704
  const home = os2.homedir();
55483
- const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path10.join(home, ".codex");
55484
- const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path10.join(home, ".zcode");
55705
+ const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path11.join(home, ".codex");
55706
+ const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path11.join(home, ".zcode");
55485
55707
  return [
55486
- path10.join(home, ".claude", "settings.json"),
55487
- path10.join(process.cwd(), ".claude", "settings.json"),
55488
- path10.join(codexHome, "config.toml"),
55489
- path10.join(resolvePiHome(env), "models.json"),
55490
- path10.join(zcodeHome, "v2", "config.json")
55708
+ path11.join(home, ".claude", "settings.json"),
55709
+ path11.join(process.cwd(), ".claude", "settings.json"),
55710
+ path11.join(codexHome, "config.toml"),
55711
+ path11.join(resolvePiHome(env), "models.json"),
55712
+ path11.join(zcodeHome, "v2", "config.json")
55491
55713
  ];
55492
55714
  }
55493
55715
  function readMtimes(paths) {
55494
55716
  const mtimes = /* @__PURE__ */ new Map();
55495
55717
  for (const p2 of paths) {
55496
55718
  try {
55497
- const st2 = fs6.statSync(p2);
55719
+ const st2 = fs7.statSync(p2);
55498
55720
  mtimes.set(p2, st2.mtimeMs);
55499
55721
  } catch {
55500
55722
  }
@@ -56676,7 +56898,8 @@ Content-Length: ${Buffer.byteLength(body)}\r
56676
56898
  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;
56677
56899
  const origin = `http://${originHost}:${actualPort}`;
56678
56900
  try {
56679
- fs7.mkdirSync(stateDir(), { recursive: true });
56901
+ fs8.mkdirSync(stateDir(), { recursive: true });
56902
+ hydratePrefixAffinity();
56680
56903
  atomicWriteInstanceFile({
56681
56904
  origin,
56682
56905
  instanceId,
@@ -56741,6 +56964,7 @@ Content-Length: ${Buffer.byteLength(body)}\r
56741
56964
  });
56742
56965
  let shuttingDown = false;
56743
56966
  const finishShutdown = () => {
56967
+ flushPrefixAffinity();
56744
56968
  clearProxyInstanceFile(instanceId);
56745
56969
  unregisterInstance(instanceId);
56746
56970
  closeLogger();
@@ -57017,14 +57241,14 @@ async function handle(req, res, opts, core, config, log2, instanceId, instanceSt
57017
57241
  try {
57018
57242
  const rawDir = process.env.ACP_RAW_DUMP_DIR || `${stateDir()}/raw`;
57019
57243
  try {
57020
- fs7.mkdirSync(rawDir, { recursive: true });
57244
+ fs8.mkdirSync(rawDir, { recursive: true });
57021
57245
  } catch {
57022
57246
  }
57023
57247
  const hdrs = maskHeadersForLog(
57024
57248
  Object.fromEntries(Object.entries(req.headers).map(([k2, v2]) => [k2, Array.isArray(v2) ? v2.join(",") : String(v2)]))
57025
57249
  );
57026
57250
  const hdrText = Object.entries(hdrs).map(([k2, v2]) => `${k2}: ${v2}`).join("\n");
57027
- fs7.writeFileSync(`${rawDir}/${Date.now()}-INCOMING.txt`, `${req.method} ${maskUrlsInText(req.url ?? "")}
57251
+ fs8.writeFileSync(`${rawDir}/${Date.now()}-INCOMING.txt`, `${req.method} ${maskUrlsInText(req.url ?? "")}
57028
57252
  ${hdrText}
57029
57253
 
57030
57254
  ${bodyBuffer.toString("utf8")}`);
@@ -57129,6 +57353,7 @@ ${bodyBuffer.toString("utf8")}`);
57129
57353
  const session = getSession(sessionId, { protocol, upstreamOrigin, label: clientLabel ?? (anonAffinity ? "prefix-affinity" : void 0) });
57130
57354
  if (anonAffinity) {
57131
57355
  prefixAffinity.note(sessionId, anonAffinity.incomingDepth, anonAffinity.tailHash, anonAffinity.itemHashes);
57356
+ scheduleAffinityPersist();
57132
57357
  session.metadata.anonymousPrefixAffinity = {
57133
57358
  depth: anonAffinity.incomingDepth,
57134
57359
  tailHash: anonAffinity.tailHash,
@@ -57783,9 +58008,17 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
57783
58008
  const session = prepared.session;
57784
58009
  const limit = config.modelContextLimit;
57785
58010
  const imageTokens = imageTokensInRawBody(prepared.protocol, prepared.body);
57786
- const payloadEstimate = estimateCoreMessages(prepared.processedMessages) + imageTokens;
58011
+ const textEstimate = estimateCoreMessages(prepared.processedMessages);
58012
+ const payloadEstimate = textEstimate + imageTokens;
57787
58013
  const tokenCount = Math.max(session.stats.lastInputTokens, payloadEstimate);
57788
58014
  if (limit <= 0 || !model || tokenCount < limit) return prepared;
58015
+ const learnedMap = session.metadata.learnedContextLimits;
58016
+ const learnedLimit = (model ? learnedMap?.[model] : void 0) ?? session.metadata.learnedContextLimit;
58017
+ const noOverflowEvidence = session.stats.lastInputTokens < limit && learnedLimit === void 0;
58018
+ if (imageTokens > 0 && textEstimate < limit && noOverflowEvidence) {
58019
+ log2("warn", `[${session.id}] image-dominated payload (~${textEstimate} text + ~${imageTokens} image tokens) exceeds window ${limit} by estimate only, no upstream overflow evidence \u2014 forwarding once so the upstream arbitrates billing (#496)`);
58020
+ return prepared;
58021
+ }
57789
58022
  const failFast = (status2, detail, retryable) => {
57790
58023
  const imageNote = imageTokens >= limit ? ` Images alone account for ~${imageTokens} tokens (\u2265 window ${limit}); compression cannot remove them \u2014 shrink or remove the images, or raise the window.` : "";
57791
58024
  const message = `context ~${tokenCount} tokens exceeds the model window ${limit} (model=${model}) and preflight compression could not bring it under: ${detail}.` + imageNote + ` The over-window payload was NOT forwarded.`;
@@ -57876,16 +58109,16 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
57876
58109
  if (bodyDumpEnabled() && process.env.ACP_DUMP_REQ !== "0") {
57877
58110
  const dumpDir = process.env.ACP_DUMP_DIR || `${stateDir()}/dumps`;
57878
58111
  try {
57879
- fs7.mkdirSync(dumpDir, { recursive: true });
58112
+ fs8.mkdirSync(dumpDir, { recursive: true });
57880
58113
  } catch {
57881
58114
  }
57882
58115
  const sid = prepared?.session.id ?? "unknown";
57883
58116
  const out = `${dumpDir}/req-${Date.now()}-${safeSessionId(sid)}.json`;
57884
58117
  try {
57885
58118
  const pretty = JSON.stringify(JSON.parse(body), null, 2);
57886
- fs7.writeFileSync(out, pretty);
58119
+ fs8.writeFileSync(out, pretty);
57887
58120
  } catch {
57888
- fs7.writeFileSync(out, body);
58121
+ fs8.writeFileSync(out, body);
57889
58122
  }
57890
58123
  log2("info", `[debug] forwarded body written to ${out}`);
57891
58124
  }
@@ -57905,7 +58138,7 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
57905
58138
  const rawBase = bodyDumpEnabled() ? (() => {
57906
58139
  try {
57907
58140
  const rawDir = process.env.ACP_RAW_DUMP_DIR || `${stateDir()}/raw`;
57908
- fs7.mkdirSync(rawDir, { recursive: true });
58141
+ fs8.mkdirSync(rawDir, { recursive: true });
57909
58142
  return `${rawDir}/${Date.now()}-${safeSessionId(prepared?.session.id)}`;
57910
58143
  } catch {
57911
58144
  return "";
@@ -57916,7 +58149,7 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
57916
58149
  const hdrText = Object.entries(maskHeadersForLog(headers)).map(([k2, v2]) => `${k2}: ${v2}`).join("\n");
57917
58150
  const bodyText = req.method === "GET" || req.method === "HEAD" ? "" : typeof body === "string" ? body : Buffer.from(body).toString("utf8");
57918
58151
  const reqPath = `${rawBase}-REQ.txt`;
57919
- fs7.writeFileSync(reqPath, `${req.method ?? "POST"} ${maskUrlForLog(upstreamUrl)}
58152
+ fs8.writeFileSync(reqPath, `${req.method ?? "POST"} ${maskUrlForLog(upstreamUrl)}
57920
58153
  ${hdrText}
57921
58154
 
57922
58155
  ${bodyText}`);
@@ -57966,7 +58199,7 @@ ${bodyText}`);
57966
58199
  try {
57967
58200
  const hdrText = Object.entries(maskHeadersForLog(respHeaders)).map(([k2, v2]) => `${k2}: ${v2}`).join("\n");
57968
58201
  const resPath = `${rawBase}-RES.txt`;
57969
- fs7.writeFileSync(resPath, `${upstream.status}
58202
+ fs8.writeFileSync(resPath, `${upstream.status}
57970
58203
  ${hdrText}
57971
58204
  `);
57972
58205
  log2("info", `[debug] RAW response dump: ${resPath}`);
@@ -60382,7 +60615,7 @@ var hr = /* @__PURE__ */ Symbol("entry");
60382
60615
  var cs = /* @__PURE__ */ Symbol("entryOpt");
60383
60616
  var ui = /* @__PURE__ */ Symbol("writeEntryClass");
60384
60617
  var lr = /* @__PURE__ */ Symbol("write");
60385
- var fs8 = /* @__PURE__ */ Symbol("ondrain");
60618
+ var fs9 = /* @__PURE__ */ Symbol("ondrain");
60386
60619
  var wt = class extends A {
60387
60620
  sync = false;
60388
60621
  opt;
@@ -60416,8 +60649,8 @@ var wt = class extends A {
60416
60649
  if ((t.gzip ? 1 : 0) + (t.brotli ? 1 : 0) + (t.zstd ? 1 : 0) > 1) throw new TypeError("gzip, brotli, zstd are mutually exclusive");
60417
60650
  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");
60418
60651
  let e = this.zip;
60419
- e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs8]()), this.on("resume", () => e.resume());
60420
- } else this.on("drain", this[fs8]);
60652
+ e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs9]()), this.on("resume", () => e.resume());
60653
+ } else this.on("drain", this[fs9]);
60421
60654
  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;
60422
60655
  }
60423
60656
  [lr](t) {
@@ -60530,7 +60763,7 @@ var wt = class extends A {
60530
60763
  this.emit("error", e);
60531
60764
  }
60532
60765
  }
60533
- [fs8]() {
60766
+ [fs9]() {
60534
60767
  this[Et] && this[Et].entry && this[Et].entry.resume();
60535
60768
  }
60536
60769
  [di](t) {
@@ -61415,17 +61648,17 @@ var To = (s3) => {
61415
61648
  };
61416
61649
 
61417
61650
  // src/update.ts
61418
- import path11 from "path";
61651
+ import path12 from "path";
61419
61652
  import { fileURLToPath as fileURLToPath3 } from "url";
61420
61653
  var REGISTRY_BASE = "https://registry.npmjs.org";
61421
61654
  var CHECK_INTERVAL_MS = 3 * 60 * 1e3;
61422
- var THROTTLE_FILE = path11.join(cacheDir(), ".update-check");
61423
- var LOCK_FILE = path11.join(cacheDir(), ".update-lock");
61655
+ var THROTTLE_FILE = path12.join(cacheDir(), ".update-check");
61656
+ var LOCK_FILE = path12.join(cacheDir(), ".update-lock");
61424
61657
  var LOCK_MAX_AGE_MS = 30 * 60 * 1e3;
61425
61658
  function shouldStealLock(holderAlive, ageMs) {
61426
61659
  return !holderAlive || ageMs >= LOCK_MAX_AGE_MS;
61427
61660
  }
61428
- var timer;
61661
+ var timer2;
61429
61662
  var inFlight = false;
61430
61663
  var firstCheckDone = false;
61431
61664
  function parseVersion(v2) {
@@ -61455,27 +61688,27 @@ async function readLastCheck() {
61455
61688
  }
61456
61689
  async function writeLastCheck(ts2) {
61457
61690
  try {
61458
- await mkdir2(path11.dirname(THROTTLE_FILE), { recursive: true });
61691
+ await mkdir2(path12.dirname(THROTTLE_FILE), { recursive: true });
61459
61692
  await writeFile2(THROTTLE_FILE, String(ts2), "utf-8");
61460
61693
  } catch {
61461
61694
  }
61462
61695
  }
61463
61696
  async function findInstallDir(packageName) {
61464
- let dir = path11.dirname(fileURLToPath3(import.meta.url));
61697
+ let dir = path12.dirname(fileURLToPath3(import.meta.url));
61465
61698
  for (; ; ) {
61466
61699
  try {
61467
- const pkg = JSON.parse(await readFile2(path11.join(dir, "package.json"), "utf-8"));
61700
+ const pkg = JSON.parse(await readFile2(path12.join(dir, "package.json"), "utf-8"));
61468
61701
  if (pkg.name === packageName) return dir;
61469
61702
  } catch {
61470
61703
  }
61471
- const parent = path11.dirname(dir);
61704
+ const parent = path12.dirname(dir);
61472
61705
  if (parent === dir) return void 0;
61473
61706
  dir = parent;
61474
61707
  }
61475
61708
  }
61476
61709
  async function readDiskVersion(installDir) {
61477
61710
  try {
61478
- const pkg = JSON.parse(await readFile2(path11.join(installDir, "package.json"), "utf-8"));
61711
+ const pkg = JSON.parse(await readFile2(path12.join(installDir, "package.json"), "utf-8"));
61479
61712
  return pkg.version;
61480
61713
  } catch {
61481
61714
  return void 0;
@@ -61512,13 +61745,13 @@ async function syntaxCheckEntry(entryAbs) {
61512
61745
  } catch (e) {
61513
61746
  return `entry unreadable: ${String(e)}`;
61514
61747
  }
61515
- const tmpCheck = path11.join(cacheDir(), ".update-syntax-check.mjs");
61748
+ const tmpCheck = path12.join(cacheDir(), ".update-syntax-check.mjs");
61516
61749
  try {
61517
61750
  await mkdir2(cacheDir(), { recursive: true });
61518
61751
  await writeFile2(tmpCheck, source);
61519
61752
  const r = await runNodeCheck(tmpCheck);
61520
61753
  if (r.code !== 0) {
61521
- return `entry does not parse (${path11.basename(entryAbs)}): ${r.stderr.split("\n").filter(Boolean).slice(0, 3).join(" | ").slice(0, 300)}`;
61754
+ return `entry does not parse (${path12.basename(entryAbs)}): ${r.stderr.split("\n").filter(Boolean).slice(0, 3).join(" | ").slice(0, 300)}`;
61522
61755
  }
61523
61756
  return null;
61524
61757
  } finally {
@@ -61531,7 +61764,7 @@ async function syntaxCheckEntry(entryAbs) {
61531
61764
  async function verifyEntries(dir, label) {
61532
61765
  let pkg;
61533
61766
  try {
61534
- pkg = JSON.parse(await readFile2(path11.join(dir, "package.json"), "utf-8"));
61767
+ pkg = JSON.parse(await readFile2(path12.join(dir, "package.json"), "utf-8"));
61535
61768
  } catch (e) {
61536
61769
  return `${label}: package.json unreadable: ${String(e)}`;
61537
61770
  }
@@ -61541,11 +61774,11 @@ async function verifyEntries(dir, label) {
61541
61774
  }
61542
61775
  for (const rel2 of entries) {
61543
61776
  try {
61544
- await access(path11.join(dir, rel2));
61777
+ await access(path12.join(dir, rel2));
61545
61778
  } catch {
61546
61779
  return `${label}: entry missing: ${rel2}`;
61547
61780
  }
61548
- const reason = await syntaxCheckEntry(path11.join(dir, rel2));
61781
+ const reason = await syntaxCheckEntry(path12.join(dir, rel2));
61549
61782
  if (reason) return `${label}: ${reason}`;
61550
61783
  }
61551
61784
  return null;
@@ -61750,14 +61983,14 @@ async function installViaTarball(version2, tarballUrl, installDir, integrity, sh
61750
61983
  if (!v2.ok) {
61751
61984
  return { ok: false, error: `tarball integrity verification failed: ${v2.error}` };
61752
61985
  }
61753
- const tmpFile = path11.join(cacheDir(), `.update-${version2}.tgz`);
61986
+ const tmpFile = path12.join(cacheDir(), `.update-${version2}.tgz`);
61754
61987
  try {
61755
61988
  await mkdir2(cacheDir(), { recursive: true });
61756
61989
  await writeFile2(tmpFile, tgzBuffer);
61757
61990
  } catch (e) {
61758
61991
  return { ok: false, error: `failed to write temp file ${tmpFile}: ${String(e)}` };
61759
61992
  }
61760
- const stagingDir = path11.join(cacheDir(), `.update-staging-${version2}`);
61993
+ const stagingDir = path12.join(cacheDir(), `.update-staging-${version2}`);
61761
61994
  try {
61762
61995
  await rm2(stagingDir, { recursive: true, force: true });
61763
61996
  await mkdir2(stagingDir, { recursive: true });
@@ -61779,7 +62012,7 @@ async function installViaTarball(version2, tarballUrl, installDir, integrity, sh
61779
62012
  } finally {
61780
62013
  await rm2(tmpFile, { force: true });
61781
62014
  }
61782
- const backupDir = path11.join(cacheDir(), `.update-backup-${version2}`);
62015
+ const backupDir = path12.join(cacheDir(), `.update-backup-${version2}`);
61783
62016
  try {
61784
62017
  await rm2(backupDir, { recursive: true, force: true });
61785
62018
  await cp(installDir, backupDir, { recursive: true, force: true });
@@ -61828,21 +62061,21 @@ function startAutoUpdate(opts) {
61828
62061
  setTimeout(() => {
61829
62062
  void checkForUpdate(opts);
61830
62063
  }, 1e4);
61831
- timer = setInterval(() => {
62064
+ timer2 = setInterval(() => {
61832
62065
  void checkForUpdate(opts);
61833
62066
  }, CHECK_INTERVAL_MS);
61834
- timer.unref?.();
62067
+ timer2.unref?.();
61835
62068
  }
61836
62069
 
61837
62070
  // src/mcp.ts
61838
- import fs9 from "fs";
61839
- import path12 from "path";
62071
+ import fs10 from "fs";
62072
+ import path13 from "path";
61840
62073
  import { fileURLToPath as fileURLToPath4 } from "url";
61841
62074
  var VERSION2 = (() => {
61842
62075
  try {
61843
62076
  const here = fileURLToPath4(import.meta.url);
61844
- const pkg = path12.join(path12.dirname(here), "..", "package.json");
61845
- return JSON.parse(fs9.readFileSync(pkg, "utf8")).version ?? "dev";
62077
+ const pkg = path13.join(path13.dirname(here), "..", "package.json");
62078
+ return JSON.parse(fs10.readFileSync(pkg, "utf8")).version ?? "dev";
61846
62079
  } catch {
61847
62080
  return "dev";
61848
62081
  }
@@ -62011,8 +62244,8 @@ if (process.argv[1] && /(?:^|[\\/])mcp\.(?:ts|js)$/.test(process.argv[1])) {
62011
62244
  }
62012
62245
 
62013
62246
  // src/plugin-install.ts
62014
- import fs10 from "fs";
62015
- import path13 from "path";
62247
+ import fs11 from "fs";
62248
+ import path14 from "path";
62016
62249
  import os4 from "os";
62017
62250
  import { execFileSync as execFileSync2 } from "child_process";
62018
62251
  import { fileURLToPath as fileURLToPath5 } from "url";
@@ -62031,22 +62264,22 @@ function proxyOriginForInstall() {
62031
62264
  var PLUGIN_AGENTS = ["pi", "omp", "claude", "codex", "opencode"];
62032
62265
  function selfPackageRoot() {
62033
62266
  const here = fileURLToPath5(import.meta.url);
62034
- return path13.resolve(path13.dirname(here), "..");
62267
+ return path14.resolve(path14.dirname(here), "..");
62035
62268
  }
62036
62269
  function homeFile(rel2, envOverride) {
62037
62270
  const raw = (envOverride !== void 0 ? process.env[envOverride] : void 0)?.trim();
62038
62271
  const base = raw && raw.length > 0 ? raw : os4.homedir();
62039
- return path13.join(base, rel2);
62272
+ return path14.join(base, rel2);
62040
62273
  }
62041
62274
  function backupOnce(file) {
62042
- if (fs10.existsSync(file) && !fs10.existsSync(`${file}.bili-bak`)) {
62043
- fs10.copyFileSync(file, `${file}.bili-bak`);
62275
+ if (fs11.existsSync(file) && !fs11.existsSync(`${file}.bili-bak`)) {
62276
+ fs11.copyFileSync(file, `${file}.bili-bak`);
62044
62277
  }
62045
62278
  }
62046
62279
  function readJson(file) {
62047
62280
  let text;
62048
62281
  try {
62049
- text = fs10.readFileSync(file, "utf8");
62282
+ text = fs11.readFileSync(file, "utf8");
62050
62283
  } catch (err2) {
62051
62284
  if (err2.code === "ENOENT") return {};
62052
62285
  throw err2;
@@ -62055,7 +62288,7 @@ function readJson(file) {
62055
62288
  try {
62056
62289
  parsed = JSON.parse(text);
62057
62290
  } catch (err2) {
62058
- throw new Error(`${file}: not valid JSON (${err2 instanceof Error ? err2.message : String(err2)}) \u2014 fix it or restore ${path13.basename(file)}.bili-bak first; refusing to overwrite`);
62291
+ throw new Error(`${file}: not valid JSON (${err2 instanceof Error ? err2.message : String(err2)}) \u2014 fix it or restore ${path14.basename(file)}.bili-bak first; refusing to overwrite`);
62059
62292
  }
62060
62293
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
62061
62294
  throw new Error(`${file}: expected a JSON object at top level, refusing to overwrite`);
@@ -62063,18 +62296,18 @@ function readJson(file) {
62063
62296
  return parsed;
62064
62297
  }
62065
62298
  function writeJson(file, data) {
62066
- fs10.mkdirSync(path13.dirname(file), { recursive: true });
62299
+ fs11.mkdirSync(path14.dirname(file), { recursive: true });
62067
62300
  backupOnce(file);
62068
- fs10.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
62301
+ fs11.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
62069
62302
  }
62070
62303
  function requireDistFile(file) {
62071
- if (!fs10.existsSync(file)) {
62304
+ if (!fs11.existsSync(file)) {
62072
62305
  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
62073
62306
  `);
62074
62307
  }
62075
62308
  }
62076
62309
  function piSettingsFile() {
62077
- return path13.join(resolvePiHome(process.env), "settings.json");
62310
+ return path14.join(resolvePiHome(process.env), "settings.json");
62078
62311
  }
62079
62312
  function isPiEntry(entry, root) {
62080
62313
  return entry === root || /^npm:billion-context(-pi)?(@|$)/.test(entry) || /(^|[/\\])node_modules[/\\]billion-context(-pi)?([\/\\]|$)/.test(entry) || /(^|[/\\])billion-context(-pi)?$/.test(entry);
@@ -62140,14 +62373,14 @@ function ompConfigFile() {
62140
62373
  `bili plugin: PI_CODING_AGENT_DIR points at the bili overlay ${raw} \u2014 operating on the real omp home ${realHome} instead
62141
62374
  `
62142
62375
  );
62143
- return path13.join(realHome, "config.yml");
62376
+ return path14.join(realHome, "config.yml");
62144
62377
  }
62145
- return path13.join(raw, "config.yml");
62378
+ return path14.join(raw, "config.yml");
62146
62379
  }
62147
- return path13.join(os4.homedir(), ".omp", "agent", "config.yml");
62380
+ return path14.join(os4.homedir(), ".omp", "agent", "config.yml");
62148
62381
  }
62149
62382
  function ompExtensionPath() {
62150
- return path13.join(selfPackageRoot(), "dist", "agent", "omp.js");
62383
+ return path14.join(selfPackageRoot(), "dist", "agent", "omp.js");
62151
62384
  }
62152
62385
  function ompEntryValue(line) {
62153
62386
  return line.replace(/#.*$/, "").trim().replace(/^-\s*/, "").replace(/^["']|["']$/g, "").trim();
@@ -62156,13 +62389,13 @@ function ompBlockLoaded(text) {
62156
62389
  const lines = text.split("\n");
62157
62390
  return ompExtensionItemLines(text).some((i) => {
62158
62391
  const v2 = ompEntryValue(lines[i]);
62159
- return OMP_ENTRY_RE.test(v2) && fs10.existsSync(v2);
62392
+ return OMP_ENTRY_RE.test(v2) && fs11.existsSync(v2);
62160
62393
  });
62161
62394
  }
62162
62395
  function ompRemove() {
62163
62396
  const file = ompConfigFile();
62164
- if (!fs10.existsSync(file)) return `omp: not installed (${file})`;
62165
- const text = fs10.readFileSync(file, "utf8");
62397
+ if (!fs11.existsSync(file)) return `omp: not installed (${file})`;
62398
+ const text = fs11.readFileSync(file, "utf8");
62166
62399
  const lines = text.split("\n");
62167
62400
  const drop = new Set(
62168
62401
  ompExtensionItemLines(text).filter((i) => OMP_ENTRY_RE.test(ompEntryValue(lines[i])))
@@ -62170,15 +62403,15 @@ function ompRemove() {
62170
62403
  if (drop.size === 0) return `omp: not installed (${file})`;
62171
62404
  const cleaned = lines.filter((_2, i) => !drop.has(i)).join("\n");
62172
62405
  backupOnce(file);
62173
- fs10.writeFileSync(file, cleaned);
62406
+ fs11.writeFileSync(file, cleaned);
62174
62407
  return `omp: removed from ${file}`;
62175
62408
  }
62176
62409
  function ompInstall() {
62177
62410
  const file = ompConfigFile();
62178
62411
  const entry = ompExtensionPath();
62179
62412
  requireDistFile(entry);
62180
- fs10.mkdirSync(path13.dirname(file), { recursive: true });
62181
- let text = fs10.existsSync(file) ? fs10.readFileSync(file, "utf8") : "";
62413
+ fs11.mkdirSync(path14.dirname(file), { recursive: true });
62414
+ let text = fs11.existsSync(file) ? fs11.readFileSync(file, "utf8") : "";
62182
62415
  if (ompBlockLoaded(text)) return `omp: already installed (${file})`;
62183
62416
  {
62184
62417
  const lines = text.split("\n");
@@ -62220,25 +62453,25 @@ ${tail}`;
62220
62453
  throw new Error(`${file}: edit would leave ${occurrences} copies of the entry \u2014 aborting without writing`);
62221
62454
  }
62222
62455
  backupOnce(file);
62223
- fs10.writeFileSync(file, out);
62456
+ fs11.writeFileSync(file, out);
62224
62457
  return `omp: installed -> ${file} extensions += ${entry}`;
62225
62458
  }
62226
62459
  function ompStatus() {
62227
62460
  const file = ompConfigFile();
62228
- const text = fs10.existsSync(file) ? fs10.readFileSync(file, "utf8") : "";
62461
+ const text = fs11.existsSync(file) ? fs11.readFileSync(file, "utf8") : "";
62229
62462
  const lines = text.split("\n");
62230
62463
  let broken = false;
62231
62464
  for (const i of ompExtensionItemLines(text)) {
62232
62465
  const v2 = ompEntryValue(lines[i]);
62233
62466
  if (!OMP_ENTRY_RE.test(v2)) continue;
62234
- if (fs10.existsSync(v2)) return "installed";
62467
+ if (fs11.existsSync(v2)) return "installed";
62235
62468
  broken = true;
62236
62469
  }
62237
62470
  return broken ? "broken" : "not installed";
62238
62471
  }
62239
62472
  function ompPluginLoadedFrom(ompHome) {
62240
62473
  try {
62241
- return ompBlockLoaded(fs10.readFileSync(path13.join(ompHome, "config.yml"), "utf8"));
62474
+ return ompBlockLoaded(fs11.readFileSync(path14.join(ompHome, "config.yml"), "utf8"));
62242
62475
  } catch {
62243
62476
  return false;
62244
62477
  }
@@ -62249,7 +62482,7 @@ function claudeMcpJson() {
62249
62482
  }
62250
62483
  function claudeInstall() {
62251
62484
  const root = selfPackageRoot();
62252
- const mcpJs = path13.join(root, "dist", "mcp.js");
62485
+ const mcpJs = path14.join(root, "dist", "mcp.js");
62253
62486
  requireDistFile(mcpJs);
62254
62487
  const claude = process.env.CLAUDE?.trim() || "claude";
62255
62488
  try {
@@ -62276,38 +62509,38 @@ function claudeStatus() {
62276
62509
  }
62277
62510
  function codexToml() {
62278
62511
  const raw = process.env.CODEX_HOME?.trim();
62279
- if (raw && raw.length > 0) return path13.join(raw, "config.toml");
62512
+ if (raw && raw.length > 0) return path14.join(raw, "config.toml");
62280
62513
  return homeFile(".codex/config.toml");
62281
62514
  }
62282
62515
  function codexBlock() {
62283
62516
  return `
62284
62517
  [mcp_servers.bili]
62285
62518
  command = ${JSON.stringify(process.execPath)}
62286
- args = [${JSON.stringify(path13.join(selfPackageRoot(), "dist", "mcp.js"))}]
62519
+ args = [${JSON.stringify(path14.join(selfPackageRoot(), "dist", "mcp.js"))}]
62287
62520
  env = { BILI_MCP_PROXY = ${JSON.stringify(proxyOriginForInstall())} }
62288
62521
  `;
62289
62522
  }
62290
62523
  function codexInstall() {
62291
62524
  const file = codexToml();
62292
- const text = fs10.existsSync(file) ? fs10.readFileSync(file, "utf8") : "";
62525
+ const text = fs11.existsSync(file) ? fs11.readFileSync(file, "utf8") : "";
62293
62526
  const existing = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text);
62294
62527
  if (existing !== null) {
62295
62528
  const block = text.slice(existing.index, text.indexOf("\n[", existing.index + 1) === -1 ? void 0 : text.indexOf("\n[", existing.index + 1));
62296
62529
  if (block.includes(`BILI_MCP_PROXY = ${JSON.stringify(proxyOriginForInstall())}`)) return `codex: already installed (${file})`;
62297
62530
  const refreshed = text.slice(0, existing.index) + codexBlock().replace(/^\n/, "") + text.slice(existing.index + block.length);
62298
62531
  backupOnce(file);
62299
- fs10.writeFileSync(file, refreshed);
62532
+ fs11.writeFileSync(file, refreshed);
62300
62533
  return `codex: refreshed proxy origin -> ${file} [mcp_servers.bili]`;
62301
62534
  }
62302
- fs10.mkdirSync(path13.dirname(file), { recursive: true });
62535
+ fs11.mkdirSync(path14.dirname(file), { recursive: true });
62303
62536
  backupOnce(file);
62304
- fs10.writeFileSync(file, text + (text.endsWith("\n") || text.length === 0 ? "" : "\n") + codexBlock());
62537
+ fs11.writeFileSync(file, text + (text.endsWith("\n") || text.length === 0 ? "" : "\n") + codexBlock());
62305
62538
  return `codex: installed -> ${file} [mcp_servers.bili]`;
62306
62539
  }
62307
62540
  function codexRemove() {
62308
62541
  const file = codexToml();
62309
- if (!fs10.existsSync(file)) return `codex: not installed (${file})`;
62310
- const text = fs10.readFileSync(file, "utf8");
62542
+ if (!fs11.existsSync(file)) return `codex: not installed (${file})`;
62543
+ const text = fs11.readFileSync(file, "utf8");
62311
62544
  const start = (() => {
62312
62545
  const m2 = /^[ \t]*\[mcp_servers\.bili\][ \t]*$/m.exec(text);
62313
62546
  return m2 === null ? -1 : m2.index;
@@ -62320,23 +62553,23 @@ function codexRemove() {
62320
62553
  const end = nextTable >= 0 ? start + firstNewline + 1 + nextTable : text.length;
62321
62554
  const cleaned = (text.slice(0, lineStart).replace(/\n+$/, "\n") + text.slice(end)).replace(/^\n+/, "");
62322
62555
  backupOnce(file);
62323
- fs10.writeFileSync(file, cleaned);
62556
+ fs11.writeFileSync(file, cleaned);
62324
62557
  return `codex: removed from ${file}`;
62325
62558
  }
62326
62559
  function codexStatus() {
62327
- const text = fs10.existsSync(codexToml()) ? fs10.readFileSync(codexToml(), "utf8") : "";
62560
+ const text = fs11.existsSync(codexToml()) ? fs11.readFileSync(codexToml(), "utf8") : "";
62328
62561
  return /^\[mcp_servers\.bili\]\s*$/m.test(text) ? "installed" : "not installed";
62329
62562
  }
62330
62563
  function opencodeJson() {
62331
62564
  const raw = process.env.OPENCODE_CONFIG?.trim();
62332
62565
  if (raw && raw.length > 0) return raw;
62333
62566
  const xdg2 = process.env.XDG_CONFIG_HOME?.trim();
62334
- if (xdg2 && xdg2.length > 0) return path13.join(xdg2, "opencode/opencode.json");
62335
- return path13.join(os4.homedir(), ".config", "opencode", "opencode.json");
62567
+ if (xdg2 && xdg2.length > 0) return path14.join(xdg2, "opencode/opencode.json");
62568
+ return path14.join(os4.homedir(), ".config", "opencode", "opencode.json");
62336
62569
  }
62337
62570
  function opencodeInstall() {
62338
62571
  const file = opencodeJson();
62339
- const mcpJs = path13.join(selfPackageRoot(), "dist", "mcp.js");
62572
+ const mcpJs = path14.join(selfPackageRoot(), "dist", "mcp.js");
62340
62573
  requireDistFile(mcpJs);
62341
62574
  const data = readJson(file);
62342
62575
  const mcp = data.mcp ?? {};
@@ -62388,14 +62621,14 @@ function pluginStatusAll() {
62388
62621
 
62389
62622
  // src/launcher.ts
62390
62623
  import { randomUUID as randomUUID5 } from "crypto";
62391
- import fs11 from "fs";
62624
+ import fs12 from "fs";
62392
62625
  import net2 from "net";
62393
62626
  import os5 from "os";
62394
- import path14 from "path";
62627
+ import path15 from "path";
62395
62628
  import { pathToFileURL } from "url";
62396
62629
  import { spawn } from "child_process";
62397
62630
  function selfDistFile(name) {
62398
- return path14.join(selfPackageRoot(), "dist", name);
62631
+ return path15.join(selfPackageRoot(), "dist", name);
62399
62632
  }
62400
62633
  var LAUNCHER_DEFAULT_HOST = "127.0.0.1";
62401
62634
  var LAUNCHER_DEFAULT_PORT = 8787;
@@ -62431,12 +62664,12 @@ function unwrapUpstream2(url) {
62431
62664
  return idx >= 0 ? url.slice(idx + "/bili/".length) : url;
62432
62665
  }
62433
62666
  function resolveCaCertPath(env) {
62434
- const base = env.XDG_DATA_HOME || path14.join(os5.homedir(), ".local/share");
62435
- return path14.join(base, "billion-context", "ca", "root-ca.pem");
62667
+ const base = env.XDG_DATA_HOME || path15.join(os5.homedir(), ".local/share");
62668
+ return path15.join(base, "billion-context", "ca", "root-ca.pem");
62436
62669
  }
62437
62670
  function resolveCombinedCaPath(env) {
62438
- const base = env.XDG_DATA_HOME || path14.join(os5.homedir(), ".local/share");
62439
- return path14.join(base, "billion-context", "ca", "combined-ca.pem");
62671
+ const base = env.XDG_DATA_HOME || path15.join(os5.homedir(), ".local/share");
62672
+ return path15.join(base, "billion-context", "ca", "combined-ca.pem");
62440
62673
  }
62441
62674
  function discoverRoutes(client, config) {
62442
62675
  const httpsDomains = [];
@@ -62669,12 +62902,12 @@ function buildCodexMcpArgs(origin, conversationId2) {
62669
62902
  ];
62670
62903
  }
62671
62904
  function overlayLockPath(overlay) {
62672
- return path14.join(overlay, ".bili-launch.pid");
62905
+ return path15.join(overlay, ".bili-launch.pid");
62673
62906
  }
62674
62907
  function livePidHoldsOverlay(overlay) {
62675
62908
  let raw;
62676
62909
  try {
62677
- raw = fs11.readFileSync(overlayLockPath(overlay), "utf8");
62910
+ raw = fs12.readFileSync(overlayLockPath(overlay), "utf8");
62678
62911
  } catch {
62679
62912
  return void 0;
62680
62913
  }
@@ -62688,17 +62921,17 @@ function livePidHoldsOverlay(overlay) {
62688
62921
  return pid;
62689
62922
  }
62690
62923
  function linkOverlayEntry(realHome, overlay, entry) {
62691
- const target = path14.join(realHome, entry);
62692
- const link = path14.join(overlay, entry);
62924
+ const target = path15.join(realHome, entry);
62925
+ const link = path15.join(overlay, entry);
62693
62926
  let st2;
62694
62927
  try {
62695
- st2 = fs11.lstatSync(target);
62928
+ st2 = fs12.lstatSync(target);
62696
62929
  } catch {
62697
62930
  return false;
62698
62931
  }
62699
62932
  const kind = st2.isDirectory() ? process.platform === "win32" ? "junction" : "dir" : "file";
62700
62933
  try {
62701
- fs11.symlinkSync(target, link, kind);
62934
+ fs12.symlinkSync(target, link, kind);
62702
62935
  return true;
62703
62936
  } catch (err2) {
62704
62937
  const code = err2.code;
@@ -62706,18 +62939,18 @@ function linkOverlayEntry(realHome, overlay, entry) {
62706
62939
  }
62707
62940
  if (st2.isDirectory()) {
62708
62941
  try {
62709
- fs11.symlinkSync(target, link, "junction");
62942
+ fs12.symlinkSync(target, link, "junction");
62710
62943
  return true;
62711
62944
  } catch {
62712
62945
  return false;
62713
62946
  }
62714
62947
  }
62715
62948
  try {
62716
- fs11.linkSync(target, link);
62949
+ fs12.linkSync(target, link);
62717
62950
  return true;
62718
62951
  } catch {
62719
62952
  try {
62720
- fs11.copyFileSync(target, link);
62953
+ fs12.copyFileSync(target, link);
62721
62954
  return true;
62722
62955
  } catch {
62723
62956
  return false;
@@ -62727,7 +62960,7 @@ function linkOverlayEntry(realHome, overlay, entry) {
62727
62960
  function isWriteThroughHardlink(overlayPath, realPath, st2) {
62728
62961
  if (st2.isDirectory() || st2.isSymbolicLink() || st2.nlink <= 1) return false;
62729
62962
  try {
62730
- const realSt = fs11.lstatSync(realPath);
62963
+ const realSt = fs12.lstatSync(realPath);
62731
62964
  return st2.dev === realSt.dev && st2.ino === realSt.ino;
62732
62965
  } catch {
62733
62966
  return false;
@@ -62741,7 +62974,7 @@ function freeConflictName(dst) {
62741
62974
  let n = 1;
62742
62975
  while (n < 1e5) {
62743
62976
  try {
62744
- fs11.lstatSync(candidate);
62977
+ fs12.lstatSync(candidate);
62745
62978
  candidate = `${dst}.bili-conflict.${n}`;
62746
62979
  n += 1;
62747
62980
  } catch {
@@ -62754,7 +62987,7 @@ function mergeSqliteSet(overlay, realHome, base) {
62754
62987
  const members = sqliteSetMembers(base);
62755
62988
  const statFile = (dir, m2) => {
62756
62989
  try {
62757
- const st2 = fs11.lstatSync(path14.join(dir, m2));
62990
+ const st2 = fs12.lstatSync(path15.join(dir, m2));
62758
62991
  return st2.isFile() ? st2 : void 0;
62759
62992
  } catch {
62760
62993
  return void 0;
@@ -62780,35 +63013,35 @@ function mergeSqliteSet(overlay, realHome, base) {
62780
63013
  const movePreserving = (src, dst) => {
62781
63014
  let dstStat;
62782
63015
  try {
62783
- dstStat = fs11.lstatSync(dst);
63016
+ dstStat = fs12.lstatSync(dst);
62784
63017
  } catch {
62785
63018
  }
62786
63019
  if (dstStat) {
62787
63020
  if (dstStat.isDirectory()) throw new Error("target is a directory");
62788
63021
  const conflict = freeConflictName(dst);
62789
- fs11.renameSync(dst, conflict);
62790
- undo.push(() => fs11.renameSync(conflict, dst));
63022
+ fs12.renameSync(dst, conflict);
63023
+ undo.push(() => fs12.renameSync(conflict, dst));
62791
63024
  }
62792
- fs11.renameSync(src, dst);
62793
- undo.push(() => fs11.renameSync(dst, src));
63025
+ fs12.renameSync(src, dst);
63026
+ undo.push(() => fs12.renameSync(dst, src));
62794
63027
  };
62795
63028
  const preserveAsConflict = (src, name) => {
62796
- const conflict = freeConflictName(path14.join(realHome, name));
62797
- fs11.renameSync(src, conflict);
62798
- undo.push(() => fs11.renameSync(conflict, src));
63029
+ const conflict = freeConflictName(path15.join(realHome, name));
63030
+ fs12.renameSync(src, conflict);
63031
+ undo.push(() => fs12.renameSync(conflict, src));
62799
63032
  };
62800
63033
  try {
62801
63034
  for (const m2 of members) {
62802
63035
  const o = statFile(overlay, m2);
62803
63036
  const r = statFile(realHome, m2);
62804
63037
  if (winner === "overlay") {
62805
- if (o) movePreserving(path14.join(overlay, m2), path14.join(realHome, m2));
62806
- else if (r) preserveAsConflict(path14.join(realHome, m2), m2);
63038
+ if (o) movePreserving(path15.join(overlay, m2), path15.join(realHome, m2));
63039
+ else if (r) preserveAsConflict(path15.join(realHome, m2), m2);
62807
63040
  } else if (winner === "real") {
62808
- if (o) preserveAsConflict(path14.join(overlay, m2), m2);
63041
+ if (o) preserveAsConflict(path15.join(overlay, m2), m2);
62809
63042
  } else {
62810
- if (o) preserveAsConflict(path14.join(overlay, m2), m2);
62811
- else if (r) preserveAsConflict(path14.join(realHome, m2), m2);
63043
+ if (o) preserveAsConflict(path15.join(overlay, m2), m2);
63044
+ else if (r) preserveAsConflict(path15.join(realHome, m2), m2);
62812
63045
  }
62813
63046
  }
62814
63047
  return true;
@@ -62821,7 +63054,7 @@ function refreshOverlayHome(realHome, overlay, generatedFile) {
62821
63054
  const generatedFiles = new Set(Array.isArray(generatedFile) ? generatedFile : [generatedFile]);
62822
63055
  const isGeneratedDraft = (name) => [...generatedFiles].some((g2) => name.startsWith(`.${g2}.`) && name.endsWith(".tmp"));
62823
63056
  try {
62824
- fs11.mkdirSync(overlay, { recursive: true });
63057
+ fs12.mkdirSync(overlay, { recursive: true });
62825
63058
  } catch {
62826
63059
  return false;
62827
63060
  }
@@ -62832,19 +63065,19 @@ function refreshOverlayHome(realHome, overlay, generatedFile) {
62832
63065
  );
62833
63066
  }
62834
63067
  try {
62835
- fs11.writeFileSync(overlayLockPath(overlay), `${process.pid}
63068
+ fs12.writeFileSync(overlayLockPath(overlay), `${process.pid}
62836
63069
  `);
62837
63070
  } catch {
62838
63071
  }
62839
63072
  const realEntries = /* @__PURE__ */ new Set();
62840
63073
  try {
62841
- for (const entry of fs11.readdirSync(realHome)) realEntries.add(entry);
63074
+ for (const entry of fs12.readdirSync(realHome)) realEntries.add(entry);
62842
63075
  } catch {
62843
63076
  }
62844
63077
  try {
62845
63078
  let overlayEntries;
62846
63079
  try {
62847
- overlayEntries = fs11.readdirSync(overlay);
63080
+ overlayEntries = fs12.readdirSync(overlay);
62848
63081
  } catch {
62849
63082
  overlayEntries = [];
62850
63083
  }
@@ -62855,10 +63088,10 @@ function refreshOverlayHome(realHome, overlay, generatedFile) {
62855
63088
  if (!members.some((m2) => m2 !== entry && overlayEntries.includes(m2))) continue;
62856
63089
  let mainSt;
62857
63090
  try {
62858
- mainSt = fs11.lstatSync(path14.join(overlay, entry));
63091
+ mainSt = fs12.lstatSync(path15.join(overlay, entry));
62859
63092
  } catch {
62860
63093
  }
62861
- const keepSidecars = mainSt !== void 0 && isWriteThroughHardlink(path14.join(overlay, entry), path14.join(realHome, entry), mainSt);
63094
+ const keepSidecars = mainSt !== void 0 && isWriteThroughHardlink(path15.join(overlay, entry), path15.join(realHome, entry), mainSt);
62862
63095
  dbSets.push({ base: entry, keepSidecars });
62863
63096
  }
62864
63097
  const skipEntries = /* @__PURE__ */ new Set();
@@ -62869,10 +63102,10 @@ function refreshOverlayHome(realHome, overlay, generatedFile) {
62869
63102
  }
62870
63103
  for (const entry of overlayEntries) {
62871
63104
  if (generatedFiles.has(entry)) continue;
62872
- const overlayPath = path14.join(overlay, entry);
63105
+ const overlayPath = path15.join(overlay, entry);
62873
63106
  if (isGeneratedDraft(entry)) {
62874
63107
  try {
62875
- fs11.unlinkSync(overlayPath);
63108
+ fs12.unlinkSync(overlayPath);
62876
63109
  } catch {
62877
63110
  }
62878
63111
  continue;
@@ -62880,33 +63113,33 @@ function refreshOverlayHome(realHome, overlay, generatedFile) {
62880
63113
  if (skipEntries.has(entry)) continue;
62881
63114
  let st2;
62882
63115
  try {
62883
- st2 = fs11.lstatSync(overlayPath);
63116
+ st2 = fs12.lstatSync(overlayPath);
62884
63117
  } catch {
62885
63118
  continue;
62886
63119
  }
62887
63120
  if (st2.isSymbolicLink()) {
62888
63121
  let target;
62889
63122
  try {
62890
- target = fs11.readlinkSync(overlayPath);
63123
+ target = fs12.readlinkSync(overlayPath);
62891
63124
  } catch {
62892
63125
  }
62893
- const wanted = realEntries.has(entry) ? path14.join(realHome, entry) : void 0;
63126
+ const wanted = realEntries.has(entry) ? path15.join(realHome, entry) : void 0;
62894
63127
  if (!wanted || target !== wanted) {
62895
63128
  try {
62896
- fs11.unlinkSync(overlayPath);
63129
+ fs12.unlinkSync(overlayPath);
62897
63130
  } catch {
62898
63131
  }
62899
63132
  }
62900
63133
  } else if (realEntries.has(entry)) {
62901
- const realPath = path14.join(realHome, entry);
63134
+ const realPath = path15.join(realHome, entry);
62902
63135
  if (isWriteThroughHardlink(overlayPath, realPath, st2)) {
62903
63136
  try {
62904
- fs11.unlinkSync(overlayPath);
63137
+ fs12.unlinkSync(overlayPath);
62905
63138
  } catch {
62906
63139
  }
62907
63140
  } else if (mergeOverlayEntry(overlayPath, realPath, generatedFiles)) {
62908
63141
  try {
62909
- fs11.rmSync(overlayPath, { recursive: true, force: true });
63142
+ fs12.rmSync(overlayPath, { recursive: true, force: true });
62910
63143
  } catch {
62911
63144
  }
62912
63145
  } else {
@@ -62928,10 +63161,10 @@ function refreshOverlayHome(realHome, overlay, generatedFile) {
62928
63161
  for (const entry of realEntries) {
62929
63162
  if (generatedFiles.has(entry)) continue;
62930
63163
  total += 1;
62931
- const overlayPath = path14.join(overlay, entry);
63164
+ const overlayPath = path15.join(overlay, entry);
62932
63165
  let present = false;
62933
63166
  try {
62934
- fs11.lstatSync(overlayPath);
63167
+ fs12.lstatSync(overlayPath);
62935
63168
  present = true;
62936
63169
  } catch {
62937
63170
  }
@@ -62963,45 +63196,45 @@ function refreshOverlayHome(realHome, overlay, generatedFile) {
62963
63196
  function mergeOverlayEntry(src, dst, excludedNames) {
62964
63197
  let st2;
62965
63198
  try {
62966
- st2 = fs11.lstatSync(src);
63199
+ st2 = fs12.lstatSync(src);
62967
63200
  } catch {
62968
63201
  return true;
62969
63202
  }
62970
63203
  let dstStat;
62971
63204
  try {
62972
- dstStat = fs11.lstatSync(dst);
63205
+ dstStat = fs12.lstatSync(dst);
62973
63206
  } catch {
62974
63207
  }
62975
63208
  if (st2.isDirectory()) {
62976
63209
  if (dstStat && !dstStat.isDirectory()) {
62977
63210
  try {
62978
- fs11.renameSync(dst, freeConflictName(dst));
63211
+ fs12.renameSync(dst, freeConflictName(dst));
62979
63212
  dstStat = void 0;
62980
63213
  } catch {
62981
63214
  return false;
62982
63215
  }
62983
63216
  }
62984
63217
  try {
62985
- fs11.mkdirSync(dst, { recursive: true });
63218
+ fs12.mkdirSync(dst, { recursive: true });
62986
63219
  } catch {
62987
63220
  return false;
62988
63221
  }
62989
63222
  let entries;
62990
63223
  try {
62991
- entries = fs11.readdirSync(src);
63224
+ entries = fs12.readdirSync(src);
62992
63225
  } catch {
62993
63226
  return false;
62994
63227
  }
62995
63228
  let ok = true;
62996
63229
  for (const entry of entries) {
62997
63230
  if (excludedNames?.has(entry)) continue;
62998
- if (!mergeOverlayEntry(path14.join(src, entry), path14.join(dst, entry), excludedNames)) ok = false;
63231
+ if (!mergeOverlayEntry(path15.join(src, entry), path15.join(dst, entry), excludedNames)) ok = false;
62999
63232
  }
63000
63233
  return ok;
63001
63234
  }
63002
63235
  if (dstStat && dstStat.isDirectory()) {
63003
63236
  try {
63004
- fs11.renameSync(src, freeConflictName(dst));
63237
+ fs12.renameSync(src, freeConflictName(dst));
63005
63238
  return true;
63006
63239
  } catch {
63007
63240
  return false;
@@ -63010,13 +63243,13 @@ function mergeOverlayEntry(src, dst, excludedNames) {
63010
63243
  if (st2.isSymbolicLink()) {
63011
63244
  if (dstStat) {
63012
63245
  try {
63013
- fs11.unlinkSync(src);
63246
+ fs12.unlinkSync(src);
63014
63247
  } catch {
63015
63248
  }
63016
63249
  return true;
63017
63250
  }
63018
63251
  try {
63019
- fs11.renameSync(src, dst);
63252
+ fs12.renameSync(src, dst);
63020
63253
  } catch {
63021
63254
  return false;
63022
63255
  }
@@ -63024,7 +63257,7 @@ function mergeOverlayEntry(src, dst, excludedNames) {
63024
63257
  }
63025
63258
  if (dstStat && dstStat.mtimeMs >= st2.mtimeMs) {
63026
63259
  try {
63027
- fs11.renameSync(src, freeConflictName(dst));
63260
+ fs12.renameSync(src, freeConflictName(dst));
63028
63261
  return true;
63029
63262
  } catch {
63030
63263
  return false;
@@ -63032,13 +63265,13 @@ function mergeOverlayEntry(src, dst, excludedNames) {
63032
63265
  }
63033
63266
  if (dstStat) {
63034
63267
  try {
63035
- fs11.renameSync(dst, freeConflictName(dst));
63268
+ fs12.renameSync(dst, freeConflictName(dst));
63036
63269
  } catch {
63037
63270
  return false;
63038
63271
  }
63039
63272
  }
63040
63273
  try {
63041
- fs11.renameSync(src, dst);
63274
+ fs12.renameSync(src, dst);
63042
63275
  return true;
63043
63276
  } catch {
63044
63277
  return false;
@@ -63048,7 +63281,7 @@ function piPluginInstalled(piHome) {
63048
63281
  const root = selfPackageRoot();
63049
63282
  if (!root) return false;
63050
63283
  try {
63051
- const parsed = JSON.parse(fs11.readFileSync(path14.join(piHome, "settings.json"), "utf8"));
63284
+ const parsed = JSON.parse(fs12.readFileSync(path15.join(piHome, "settings.json"), "utf8"));
63052
63285
  const list = Array.isArray(parsed.packages) ? parsed.packages.map(String) : [];
63053
63286
  return list.some((p2) => isBiliPiEntry(p2, root));
63054
63287
  } catch {
@@ -63056,13 +63289,13 @@ function piPluginInstalled(piHome) {
63056
63289
  }
63057
63290
  }
63058
63291
  function writeOverlayFileAtomic(overlay, fileName, contents) {
63059
- const draft = path14.join(overlay, `.${fileName}.${process.pid}.tmp`);
63292
+ const draft = path15.join(overlay, `.${fileName}.${process.pid}.tmp`);
63060
63293
  try {
63061
- fs11.writeFileSync(draft, contents);
63062
- fs11.renameSync(draft, path14.join(overlay, fileName));
63294
+ fs12.writeFileSync(draft, contents);
63295
+ fs12.renameSync(draft, path15.join(overlay, fileName));
63063
63296
  } catch {
63064
63297
  try {
63065
- fs11.rmSync(draft, { force: true });
63298
+ fs12.rmSync(draft, { force: true });
63066
63299
  } catch {
63067
63300
  }
63068
63301
  }
@@ -63070,7 +63303,7 @@ function writeOverlayFileAtomic(overlay, fileName, contents) {
63070
63303
  function writePiCompactionDisabledSettings(piHome, overlay) {
63071
63304
  let settings = {};
63072
63305
  try {
63073
- const parsed = JSON.parse(fs11.readFileSync(path14.join(piHome, "settings.json"), "utf8"));
63306
+ const parsed = JSON.parse(fs12.readFileSync(path15.join(piHome, "settings.json"), "utf8"));
63074
63307
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
63075
63308
  settings = parsed;
63076
63309
  }
@@ -63083,12 +63316,12 @@ function writePiCompactionDisabledSettings(piHome, overlay) {
63083
63316
  writeOverlayFileAtomic(overlay, "settings.json", JSON.stringify(settings, null, 2));
63084
63317
  }
63085
63318
  function preparePiHttpRewrite(piHome, origin, httpRewrites, httpsRewrites) {
63086
- if (!fs11.existsSync(piHome)) return void 0;
63319
+ if (!fs12.existsSync(piHome)) return void 0;
63087
63320
  const overlay = `${piHome}-bili`;
63088
63321
  const generated = ["settings.json"];
63089
63322
  let modelsRoot;
63090
63323
  try {
63091
- const parsed = JSON.parse(fs11.readFileSync(path14.join(piHome, "models.json"), "utf8"));
63324
+ const parsed = JSON.parse(fs12.readFileSync(path15.join(piHome, "models.json"), "utf8"));
63092
63325
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
63093
63326
  modelsRoot = parsed;
63094
63327
  generated.push("models.json");
@@ -63124,11 +63357,11 @@ function preparePiHttpRewrite(piHome, origin, httpRewrites, httpsRewrites) {
63124
63357
  function atomicWriteTextFile(filePath, contents) {
63125
63358
  const draft = `${filePath}.${process.pid}.bili-tmp`;
63126
63359
  try {
63127
- fs11.writeFileSync(draft, contents);
63128
- fs11.renameSync(draft, filePath);
63360
+ fs12.writeFileSync(draft, contents);
63361
+ fs12.renameSync(draft, filePath);
63129
63362
  } catch {
63130
63363
  try {
63131
- fs11.rmSync(draft, { force: true });
63364
+ fs12.rmSync(draft, { force: true });
63132
63365
  } catch {
63133
63366
  }
63134
63367
  throw new Error(`bili: could not write ${filePath}`);
@@ -63150,7 +63383,7 @@ function liveProxyPorts() {
63150
63383
  function unpackDeadProxyUrlsInFile(filePath, livePorts) {
63151
63384
  let txt;
63152
63385
  try {
63153
- txt = fs11.readFileSync(filePath, "utf8");
63386
+ txt = fs12.readFileSync(filePath, "utf8");
63154
63387
  } catch {
63155
63388
  return 0;
63156
63389
  }
@@ -63221,14 +63454,14 @@ function writeOmpCompactionDisabledConfig(ompHome, overlay) {
63221
63454
  let baseIsJson = false;
63222
63455
  for (const name of ["config.yml", "config.yaml"]) {
63223
63456
  try {
63224
- base = fs11.readFileSync(path14.join(ompHome, name), "utf8");
63457
+ base = fs12.readFileSync(path15.join(ompHome, name), "utf8");
63225
63458
  break;
63226
63459
  } catch {
63227
63460
  }
63228
63461
  }
63229
63462
  if (base === void 0) {
63230
63463
  try {
63231
- base = fs11.readFileSync(path14.join(ompHome, "settings.json"), "utf8");
63464
+ base = fs12.readFileSync(path15.join(ompHome, "settings.json"), "utf8");
63232
63465
  baseIsJson = true;
63233
63466
  } catch {
63234
63467
  }
@@ -63256,17 +63489,17 @@ function writeOmpCompactionDisabledConfig(ompHome, overlay) {
63256
63489
  writeOverlayFileAtomic(overlay, "config.yml", merged);
63257
63490
  }
63258
63491
  function prepareOmpHttpRewrite(ompHome, origin, httpRewrites, httpsRewrites) {
63259
- if (!fs11.existsSync(ompHome)) return void 0;
63492
+ if (!fs12.existsSync(ompHome)) return void 0;
63260
63493
  const overlay = `${ompHome}-bili`;
63261
63494
  const generated = ["config.yml"];
63262
- const modelsPath = path14.join(ompHome, "models.yml");
63495
+ const modelsPath = path15.join(ompHome, "models.yml");
63263
63496
  const unpacked = unpackDeadProxyUrlsInFile(modelsPath, liveProxyPorts());
63264
63497
  if (unpacked > 0) {
63265
63498
  console.error(`bili: unpacked ${unpacked} dead proxy URL(s) from the real ${modelsPath}`);
63266
63499
  }
63267
63500
  let modelsText;
63268
63501
  try {
63269
- modelsText = fs11.readFileSync(modelsPath, "utf8");
63502
+ modelsText = fs12.readFileSync(modelsPath, "utf8");
63270
63503
  generated.push("models.yml");
63271
63504
  } catch {
63272
63505
  }
@@ -63312,10 +63545,10 @@ function prepareOmpHttpRewrite(ompHome, origin, httpRewrites, httpsRewrites) {
63312
63545
  }
63313
63546
  function prepareHermesHome(hermesHome, origin, rewrites) {
63314
63547
  if (rewrites.length === 0) return void 0;
63315
- const cfgPath = path14.join(hermesHome, "config.yaml");
63548
+ const cfgPath = path15.join(hermesHome, "config.yaml");
63316
63549
  let txt;
63317
63550
  try {
63318
- txt = fs11.readFileSync(cfgPath, "utf8");
63551
+ txt = fs12.readFileSync(cfgPath, "utf8");
63319
63552
  } catch {
63320
63553
  return void 0;
63321
63554
  }
@@ -63342,21 +63575,21 @@ function prepareHermesHome(hermesHome, origin, rewrites) {
63342
63575
  }
63343
63576
  function writeHermesIdentityPlugin(hermesHome, overlay, rewrites) {
63344
63577
  try {
63345
- if (fs11.existsSync(path14.join(hermesHome, "plugins"))) return false;
63578
+ if (fs12.existsSync(path15.join(hermesHome, "plugins"))) return false;
63346
63579
  } catch {
63347
63580
  return false;
63348
63581
  }
63349
- const dir = path14.join("plugins", "model-providers", "bili-session-identity");
63582
+ const dir = path15.join("plugins", "model-providers", "bili-session-identity");
63350
63583
  try {
63351
- fs11.mkdirSync(path14.join(overlay, dir), { recursive: true });
63584
+ fs12.mkdirSync(path15.join(overlay, dir), { recursive: true });
63352
63585
  } catch {
63353
63586
  return false;
63354
63587
  }
63355
63588
  const keys = rewrites.map((r) => r.key);
63356
- const pluginDir = path14.join(overlay, dir);
63589
+ const pluginDir = path15.join(overlay, dir);
63357
63590
  try {
63358
- fs11.writeFileSync(path14.join(pluginDir, "__init__.py"), hermesIdentityPluginSource(keys));
63359
- fs11.writeFileSync(path14.join(pluginDir, "plugin.yaml"), [
63591
+ fs12.writeFileSync(path15.join(pluginDir, "__init__.py"), hermesIdentityPluginSource(keys));
63592
+ fs12.writeFileSync(path15.join(pluginDir, "plugin.yaml"), [
63360
63593
  "name: bili-session-identity",
63361
63594
  "kind: model-provider",
63362
63595
  "version: 1.0.0",
@@ -63368,7 +63601,7 @@ function writeHermesIdentityPlugin(hermesHome, overlay, rewrites) {
63368
63601
  return false;
63369
63602
  }
63370
63603
  try {
63371
- return fs11.existsSync(path14.join(overlay, dir, "__init__.py"));
63604
+ return fs12.existsSync(path15.join(overlay, dir, "__init__.py"));
63372
63605
  } catch {
63373
63606
  return false;
63374
63607
  }
@@ -63425,10 +63658,10 @@ function hermesIdentityPluginSource(providerKeys) {
63425
63658
  ].join("\n");
63426
63659
  }
63427
63660
  function prepareDshHome(dshHome, origin, rewrites) {
63428
- const cfgPath = path14.join(dshHome, "settings.yaml");
63661
+ const cfgPath = path15.join(dshHome, "settings.yaml");
63429
63662
  let txt;
63430
63663
  try {
63431
- txt = fs11.readFileSync(cfgPath, "utf8");
63664
+ txt = fs12.readFileSync(cfgPath, "utf8");
63432
63665
  } catch {
63433
63666
  return void 0;
63434
63667
  }
@@ -63456,16 +63689,16 @@ function writeDshAcpPatch(dshHome) {
63456
63689
  const pluginUrl = pathToFileURL(selfDistFile("agent/dsh-acp.js")).href;
63457
63690
  const dir = `${dshHome}-bili`;
63458
63691
  try {
63459
- fs11.mkdirSync(dir, { recursive: true });
63692
+ fs12.mkdirSync(dir, { recursive: true });
63460
63693
  } catch {
63461
63694
  return void 0;
63462
63695
  }
63463
63696
  writeOverlayFileAtomic(dir, ".bili-acp.patch.yml", `- insert:
63464
63697
  - name: ${pluginUrl}
63465
63698
  `);
63466
- const file = path14.join(dir, ".bili-acp.patch.yml");
63699
+ const file = path15.join(dir, ".bili-acp.patch.yml");
63467
63700
  try {
63468
- return fs11.existsSync(file) ? file : void 0;
63701
+ return fs12.existsSync(file) ? file : void 0;
63469
63702
  } catch {
63470
63703
  return void 0;
63471
63704
  }
@@ -63480,7 +63713,7 @@ function prepareOpencodeHttpRewrite(configFile2, origin, httpRewrites, httpsRewr
63480
63713
  if (httpRewrites.length === 0 && httpsRewrites.length === 0 && !pluginPath) return void 0;
63481
63714
  let root = {};
63482
63715
  try {
63483
- const txt = fs11.readFileSync(configFile2, "utf8");
63716
+ const txt = fs12.readFileSync(configFile2, "utf8");
63484
63717
  const parsed = JSON.parse(txt);
63485
63718
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
63486
63719
  root = { ...parsed };
@@ -63508,9 +63741,9 @@ function prepareOpencodeHttpRewrite(configFile2, origin, httpRewrites, httpsRewr
63508
63741
  if (!plugins.includes(pluginPath)) plugins.push(pluginPath);
63509
63742
  root.plugin = plugins;
63510
63743
  }
63511
- const tmp = fs11.mkdtempSync(path14.join(os5.tmpdir(), "bili-opencode-"));
63512
- const tmpFile = path14.join(tmp, "opencode.json");
63513
- fs11.writeFileSync(tmpFile, JSON.stringify(root));
63744
+ const tmp = fs12.mkdtempSync(path15.join(os5.tmpdir(), "bili-opencode-"));
63745
+ const tmpFile = path15.join(tmp, "opencode.json");
63746
+ fs12.writeFileSync(tmpFile, JSON.stringify(root));
63514
63747
  return tmpFile;
63515
63748
  }
63516
63749
  function dedupeInOrder(list) {
@@ -63600,8 +63833,8 @@ async function ensureProxyRunning(opts, deps = {}) {
63600
63833
  const port = opts.port;
63601
63834
  const script = process.argv[1];
63602
63835
  if (!script) throw new Error("bili: cannot resolve launcher script path");
63603
- const logPath2 = path14.join(os5.tmpdir(), `bili-proxy-${port}.log`);
63604
- const logFd = fs11.openSync(logPath2, "a");
63836
+ const logPath2 = path15.join(os5.tmpdir(), `bili-proxy-${port}.log`);
63837
+ const logFd = fs12.openSync(logPath2, "a");
63605
63838
  let child;
63606
63839
  try {
63607
63840
  child = spawnImpl(
@@ -63621,7 +63854,7 @@ async function ensureProxyRunning(opts, deps = {}) {
63621
63854
  );
63622
63855
  } finally {
63623
63856
  try {
63624
- fs11.closeSync(logFd);
63857
+ fs12.closeSync(logFd);
63625
63858
  } catch {
63626
63859
  }
63627
63860
  }
@@ -63680,12 +63913,12 @@ var PATH_EXTS = process.platform === "win32" ? [".cmd", ".bat", ".exe", ""] : ["
63680
63913
  function resolveOnPath(name, env) {
63681
63914
  const p2 = env.PATH;
63682
63915
  if (!p2) return void 0;
63683
- for (const dir of p2.split(path14.delimiter)) {
63916
+ for (const dir of p2.split(path15.delimiter)) {
63684
63917
  if (!dir) continue;
63685
63918
  for (const ext of PATH_EXTS) {
63686
- const f2 = path14.join(dir, name + ext);
63919
+ const f2 = path15.join(dir, name + ext);
63687
63920
  try {
63688
- if (fs11.existsSync(f2) && fs11.statSync(f2).isFile()) return f2;
63921
+ if (fs12.existsSync(f2) && fs12.statSync(f2).isFile()) return f2;
63689
63922
  } catch {
63690
63923
  }
63691
63924
  }
@@ -63703,7 +63936,7 @@ function resolveClientCommand(client, env) {
63703
63936
  if (piBin) return { command: piBin, prefixArgs: [] };
63704
63937
  const piResolved = resolveOnPath("pi", env);
63705
63938
  if (piResolved) return { command: piResolved, prefixArgs: [] };
63706
- const cli = path14.join(
63939
+ const cli = path15.join(
63707
63940
  os5.homedir(),
63708
63941
  ".pi/agent/npm/node_modules/@earendil-works/pi-coding-agent/dist/cli.js"
63709
63942
  );
@@ -63775,7 +64008,7 @@ async function runLaunch(params, deps = {}) {
63775
64008
  piOverlayHome = preparePiHttpRewrite(resolvePiHome(process.env), origin, routes.httpRewrites, routes.httpsRewrites);
63776
64009
  if (piOverlayHome) env.PI_CODING_AGENT_DIR = piOverlayHome;
63777
64010
  const piExt = selfDistFile("agent/pi.js");
63778
- if (piExt && fs11.existsSync(piExt) && !piPluginInstalled(resolvePiHome(process.env))) {
64011
+ if (piExt && fs12.existsSync(piExt) && !piPluginInstalled(resolvePiHome(process.env))) {
63779
64012
  clientArgs = ["-e", piExt, ...clientArgs];
63780
64013
  }
63781
64014
  } else if (base === "omp") {
@@ -63783,13 +64016,13 @@ async function runLaunch(params, deps = {}) {
63783
64016
  ompOverlayHome = prepareOmpHttpRewrite(resolveOmpHome(process.env), origin, routes.httpRewrites, routes.httpsRewrites);
63784
64017
  if (ompOverlayHome) env.PI_CODING_AGENT_DIR = ompOverlayHome;
63785
64018
  const ompExt = selfDistFile("agent/omp.js");
63786
- if (ompExt && fs11.existsSync(ompExt) && !ompPluginLoadedFrom(resolveOmpHome(process.env))) {
64019
+ if (ompExt && fs12.existsSync(ompExt) && !ompPluginLoadedFrom(resolveOmpHome(process.env))) {
63787
64020
  clientArgs = ["-e", ompExt, ...clientArgs];
63788
64021
  }
63789
64022
  } else if (base === "opencode") {
63790
64023
  env = { ...process.env, HTTPS_PROXY: origin, NODE_EXTRA_CA_CERTS: ca, BILLION_CONTEXT_PROXY: origin };
63791
64024
  const opencodePlugin = selfDistFile("agent/opencode.js");
63792
- const opencodePluginPath = opencodePlugin && fs11.existsSync(opencodePlugin) ? opencodePlugin : void 0;
64025
+ const opencodePluginPath = opencodePlugin && fs12.existsSync(opencodePlugin) ? opencodePlugin : void 0;
63793
64026
  opencodeTmpFile = prepareOpencodeHttpRewrite(resolveOpencodeConfigFile(process.env), origin, routes.httpRewrites, routes.httpsRewrites, opencodePluginPath);
63794
64027
  if (opencodeTmpFile) env.OPENCODE_CONFIG = opencodeTmpFile;
63795
64028
  } else if (base === "hermes") {
@@ -63862,8 +64095,8 @@ async function runLaunch(params, deps = {}) {
63862
64095
  console.error(`bili: claude budget aligned \u2014 CLAUDE_CODE_AUTO_COMPACT_WINDOW=${claudeBudget.CLAUDE_CODE_AUTO_COMPACT_WINDOW}`);
63863
64096
  }
63864
64097
  if (injectMcp) {
63865
- const mcpFile = path14.join(os5.tmpdir(), `bili-mcp-${Date.now()}.json`);
63866
- fs11.writeFileSync(mcpFile, JSON.stringify(buildMcpConfig(origin)));
64098
+ const mcpFile = path15.join(os5.tmpdir(), `bili-mcp-${Date.now()}.json`);
64099
+ fs12.writeFileSync(mcpFile, JSON.stringify(buildMcpConfig(origin)));
63867
64100
  tmpFiles.push(mcpFile);
63868
64101
  clientArgs = ["--mcp-config", mcpFile, ...clientArgs];
63869
64102
  }
@@ -63882,13 +64115,13 @@ async function runLaunch(params, deps = {}) {
63882
64115
  stopProxy(handle2);
63883
64116
  if (opencodeTmpFile) {
63884
64117
  try {
63885
- fs11.rmSync(path14.dirname(opencodeTmpFile), { recursive: true, force: true });
64118
+ fs12.rmSync(path15.dirname(opencodeTmpFile), { recursive: true, force: true });
63886
64119
  } catch {
63887
64120
  }
63888
64121
  }
63889
64122
  for (const f2 of tmpFiles) {
63890
64123
  try {
63891
- fs11.rmSync(f2, { force: true });
64124
+ fs12.rmSync(f2, { force: true });
63892
64125
  } catch {
63893
64126
  }
63894
64127
  }
@@ -63914,8 +64147,8 @@ async function runTestPi(params, deps = {}) {
63914
64147
  }
63915
64148
  const ca = resolveCaCertPath(process.env);
63916
64149
  const env = buildPiEnv(handle2.origin, ca, process.env);
63917
- const sessionDir = path14.join(os5.tmpdir(), `bili-pi-test-${Date.now()}`);
63918
- fs11.mkdirSync(sessionDir, { recursive: true });
64150
+ const sessionDir = path15.join(os5.tmpdir(), `bili-pi-test-${Date.now()}`);
64151
+ fs12.mkdirSync(sessionDir, { recursive: true });
63919
64152
  const args = [
63920
64153
  "-p",
63921
64154
  "--no-session",
@@ -63943,7 +64176,7 @@ async function runTestPi(params, deps = {}) {
63943
64176
 
63944
64177
  // src/export.ts
63945
64178
  import { mkdirSync as mkdirSync5, writeFileSync as writeFileSync4 } from "fs";
63946
- import path15 from "path";
64179
+ import path16 from "path";
63947
64180
  function fmtDate(ms2) {
63948
64181
  return ms2 ? new Date(ms2).toISOString().replace("T", " ").slice(0, 19) + " UTC" : "\u2014";
63949
64182
  }
@@ -64075,7 +64308,7 @@ async function exportSession(selector, opts = {}) {
64075
64308
  }
64076
64309
  const markdown = renderHandoff(matches[0], opts.full ?? false);
64077
64310
  if (opts.output) {
64078
- mkdirSync5(path15.dirname(path15.resolve(opts.output)), { recursive: true });
64311
+ mkdirSync5(path16.dirname(path16.resolve(opts.output)), { recursive: true });
64079
64312
  writeFileSync4(opts.output, markdown, "utf8");
64080
64313
  return `written to ${opts.output}`;
64081
64314
  }
@@ -64085,11 +64318,11 @@ async function exportSession(selector, opts = {}) {
64085
64318
  // src/cli.ts
64086
64319
  import { readFileSync as readFileSync4 } from "fs";
64087
64320
  import { fileURLToPath as fileURLToPath6 } from "url";
64088
- import path16 from "path";
64321
+ import path17 from "path";
64089
64322
  var VERSION3 = (() => {
64090
64323
  try {
64091
64324
  const here = fileURLToPath6(import.meta.url);
64092
- const pkg = path16.join(path16.dirname(here), "..", "package.json");
64325
+ const pkg = path17.join(path17.dirname(here), "..", "package.json");
64093
64326
  return JSON.parse(readFileSync4(pkg, "utf8")).version ?? "dev";
64094
64327
  } catch {
64095
64328
  return "dev";
@@ -64098,7 +64331,7 @@ var VERSION3 = (() => {
64098
64331
  var PACKAGE_NAME = (() => {
64099
64332
  try {
64100
64333
  const here = fileURLToPath6(import.meta.url);
64101
- const pkg = path16.join(path16.dirname(here), "..", "package.json");
64334
+ const pkg = path17.join(path17.dirname(here), "..", "package.json");
64102
64335
  return JSON.parse(readFileSync4(pkg, "utf8")).name ?? "billion-context";
64103
64336
  } catch {
64104
64337
  return "billion-context";