billion-context 0.1.36 → 0.1.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1141,14 +1141,14 @@ var require_util = __commonJS({
1141
1141
  }
1142
1142
  const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
1143
1143
  let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`;
1144
- let path9 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
1144
+ let path11 = 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 (path9 && path9[0] !== "/") {
1149
- path9 = `/${path9}`;
1148
+ if (path11 && path11[0] !== "/") {
1149
+ path11 = `/${path11}`;
1150
1150
  }
1151
- return new URL(`${origin}${path9}`);
1151
+ return new URL(`${origin}${path11}`);
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: path9, origin }
1972
+ request: { method, path: path11, origin }
1973
1973
  } = evt;
1974
- debugLog("sending request to %s %s%s", method, origin, path9);
1974
+ debugLog("sending request to %s %s%s", method, origin, path11);
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: path9, origin },
1992
+ request: { method, path: path11, 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
- path9,
1999
+ path11,
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: path9, origin }
2008
+ request: { method, path: path11, origin }
2009
2009
  } = evt;
2010
- debugLog("trailers received from %s %s%s", method, origin, path9);
2010
+ debugLog("trailers received from %s %s%s", method, origin, path11);
2011
2011
  }
2012
2012
  );
2013
2013
  diagnosticsChannel.subscribe(
2014
2014
  "undici:request:error",
2015
2015
  (evt) => {
2016
2016
  const {
2017
- request: { method, path: path9, origin },
2017
+ request: { method, path: path11, 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
- path9,
2024
+ path11,
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: path9,
2139
+ path: path11,
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 path9 !== "string") {
2156
+ if (typeof path11 !== "string") {
2157
2157
  throw new InvalidArgumentError("path must be a string");
2158
- } else if (path9[0] !== "/" && !(path9.startsWith("http://") || path9.startsWith("https://")) && method !== "CONNECT") {
2158
+ } else if (path11[0] !== "/" && !(path11.startsWith("http://") || path11.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(path9)) {
2160
+ } else if (invalidPathRegex.test(path11)) {
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(path9, query) : path9;
2235
+ this.path = query ? serializePathWithQuery(path11, query) : path11;
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: path9, host, upgrade, blocking, reset } = request;
7418
+ const { method, path: path11, 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} ${path9} HTTP/1.1\r
7496
+ let header = `${method} ${path11} 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: path9, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
8149
+ const { method, path: path11, 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] = path9;
8217
+ headers[HTTP2_HEADER_PATH] = path11;
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] = path9;
8258
+ headers[HTTP2_HEADER_PATH] = path11;
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: path9 = "/",
10601
+ path: path11 = "/",
10602
10602
  headers = {}
10603
10603
  } = opts;
10604
- opts.path = origin + path9;
10604
+ opts.path = origin + path11;
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(path9) {
12688
- if (typeof path9 !== "string") {
12689
- return path9;
12687
+ function safeUrl(path11) {
12688
+ if (typeof path11 !== "string") {
12689
+ return path11;
12690
12690
  }
12691
- const pathSegments = path9.split("?", 3);
12691
+ const pathSegments = path11.split("?", 3);
12692
12692
  if (pathSegments.length !== 2) {
12693
- return path9;
12693
+ return path11;
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: path9, method, body, headers }) {
12700
- const pathMatch = matchValue(mockDispatch2.path, path9);
12699
+ function matchKey(mockDispatch2, { path: path11, method, body, headers }) {
12700
+ const pathMatch = matchValue(mockDispatch2.path, path11);
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: path9, ignoreTrailingSlash }) => {
12726
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path9)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path9), resolvedPath);
12725
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path11, ignoreTrailingSlash }) => {
12726
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path11)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path11), 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(path9) {
12766
- while (path9.endsWith("/")) {
12767
- path9 = path9.slice(0, -1);
12765
+ function removeTrailingSlash(path11) {
12766
+ while (path11.endsWith("/")) {
12767
+ path11 = path11.slice(0, -1);
12768
12768
  }
12769
- if (path9.length === 0) {
12770
- path9 = "/";
12769
+ if (path11.length === 0) {
12770
+ path11 = "/";
12771
12771
  }
12772
- return path9;
12772
+ return path11;
12773
12773
  }
12774
12774
  function buildKey(opts) {
12775
- const { path: path9, method, body, headers, query } = opts;
12775
+ const { path: path11, method, body, headers, query } = opts;
12776
12776
  return {
12777
- path: path9,
12777
+ path: path11,
12778
12778
  method,
12779
12779
  body,
12780
12780
  headers,
@@ -13464,10 +13464,10 @@ var require_pending_interceptors_formatter = __commonJS({
13464
13464
  }
13465
13465
  format(pendingInterceptors) {
13466
13466
  const withPrettyHeaders = pendingInterceptors.map(
13467
- ({ method, path: path9, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
13467
+ ({ method, path: path11, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
13468
13468
  Method: method,
13469
13469
  Origin: origin,
13470
- Path: path9,
13470
+ Path: path11,
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 [path9, searchParams] = dispatchOpts.path.split("?");
13552
+ const [path11, searchParams] = dispatchOpts.path.split("?");
13553
13553
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
13554
- dispatchOpts.path = `${path9}?${normalizedSearchParams}`;
13554
+ dispatchOpts.path = `${path11}?${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 path9 = filePath || this.#snapshotPath;
13956
- if (!path9) {
13955
+ const path11 = filePath || this.#snapshotPath;
13956
+ if (!path11) {
13957
13957
  throw new InvalidArgumentError("Snapshot path is required");
13958
13958
  }
13959
13959
  try {
13960
- const data = await readFile3(resolve(path9), "utf8");
13960
+ const data = await readFile3(resolve(path11), "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 ${path9}`, { cause: error });
13974
+ throw new UndiciError(`Failed to load snapshots from ${path11}`, { 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 path9 = filePath || this.#snapshotPath;
13986
- if (!path9) {
13985
+ const path11 = filePath || this.#snapshotPath;
13986
+ if (!path11) {
13987
13987
  throw new InvalidArgumentError("Snapshot path is required");
13988
13988
  }
13989
- const resolvedPath = resolve(path9);
13989
+ const resolvedPath = resolve(path11);
13990
13990
  await mkdir3(dirname6(resolvedPath), { recursive: true });
13991
13991
  const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
13992
13992
  hash,
@@ -14618,15 +14618,15 @@ var require_redirect_handler = __commonJS({
14618
14618
  return;
14619
14619
  }
14620
14620
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
14621
- const path9 = search ? `${pathname}${search}` : pathname;
14622
- const redirectUrlString = `${origin}${path9}`;
14621
+ const path11 = search ? `${pathname}${search}` : pathname;
14622
+ const redirectUrlString = `${origin}${path11}`;
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 = path9;
14629
+ this.opts.path = path11;
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, path9) {
16398
+ function deleteCachedUri(store, cacheKey, path11) {
16399
16399
  deleteCachedValue(store, {
16400
16400
  ...cacheKey,
16401
- path: path9
16401
+ path: path11
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: path9
16409
+ path: path11
16410
16410
  });
16411
16411
  }
16412
16412
  }
@@ -16417,9 +16417,9 @@ var require_cache_handler = __commonJS({
16417
16417
  }
16418
16418
  const values = Array.isArray(headerValue2) ? headerValue2 : [headerValue2];
16419
16419
  for (let i = 0; i < values.length; i++) {
16420
- const path9 = getSameOriginPath(cacheKey, values[i]);
16421
- if (path9 !== void 0) {
16422
- deleteCachedUri(store, cacheKey, path9);
16420
+ const path11 = getSameOriginPath(cacheKey, values[i]);
16421
+ if (path11 !== void 0) {
16422
+ deleteCachedUri(store, cacheKey, path11);
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 path9 = url.pathname + url.search;
21300
+ const path11 = 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 ? `${path9}?` : path9,
21304
+ path: hasTrailingQuestionMark ? `${path11}?` : path11,
21305
21305
  origin: url.origin,
21306
21306
  method: request.method,
21307
21307
  body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
@@ -21851,8 +21851,8 @@ var require_cache3 = __commonJS({
21851
21851
  * @returns {requestResponseList}
21852
21852
  */
21853
21853
  #batchCacheOperations(operations) {
21854
- const cache2 = this.#relevantRequestResponseList;
21855
- const backupCache = [...cache2];
21854
+ const cache3 = this.#relevantRequestResponseList;
21855
+ const backupCache = [...cache3];
21856
21856
  const addedItems = [];
21857
21857
  const resultList = [];
21858
21858
  try {
@@ -21879,9 +21879,9 @@ var require_cache3 = __commonJS({
21879
21879
  return [];
21880
21880
  }
21881
21881
  for (const requestResponse of requestResponses) {
21882
- const idx = cache2.indexOf(requestResponse);
21882
+ const idx = cache3.indexOf(requestResponse);
21883
21883
  assert(idx !== -1);
21884
- cache2.splice(idx, 1);
21884
+ cache3.splice(idx, 1);
21885
21885
  }
21886
21886
  } else if (operation.type === "put") {
21887
21887
  if (operation.response == null) {
@@ -21911,11 +21911,11 @@ var require_cache3 = __commonJS({
21911
21911
  }
21912
21912
  requestResponses = this.#queryCache(operation.request);
21913
21913
  for (const requestResponse of requestResponses) {
21914
- const idx = cache2.indexOf(requestResponse);
21914
+ const idx = cache3.indexOf(requestResponse);
21915
21915
  assert(idx !== -1);
21916
- cache2.splice(idx, 1);
21916
+ cache3.splice(idx, 1);
21917
21917
  }
21918
- cache2.push([operation.request, operation.response]);
21918
+ cache3.push([operation.request, operation.response]);
21919
21919
  addedItems.push([operation.request, operation.response]);
21920
21920
  }
21921
21921
  resultList.push([operation.request, operation.response]);
@@ -22092,13 +22092,13 @@ var require_cachestorage = __commonJS({
22092
22092
  if (options.cacheName != null) {
22093
22093
  if (this.#caches.has(options.cacheName)) {
22094
22094
  const cacheList = this.#caches.get(options.cacheName);
22095
- const cache2 = new Cache(kConstruct, cacheList);
22096
- return await cache2.match(request, options);
22095
+ const cache3 = new Cache(kConstruct, cacheList);
22096
+ return await cache3.match(request, options);
22097
22097
  }
22098
22098
  } else {
22099
22099
  for (const cacheList of this.#caches.values()) {
22100
- const cache2 = new Cache(kConstruct, cacheList);
22101
- const response = await cache2.match(request, options);
22100
+ const cache3 = new Cache(kConstruct, cacheList);
22101
+ const response = await cache3.match(request, options);
22102
22102
  if (response !== void 0) {
22103
22103
  return response;
22104
22104
  }
@@ -22128,12 +22128,12 @@ var require_cachestorage = __commonJS({
22128
22128
  webidl.argumentLengthCheck(arguments, 1, prefix);
22129
22129
  cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
22130
22130
  if (this.#caches.has(cacheName)) {
22131
- const cache3 = this.#caches.get(cacheName);
22132
- return new Cache(kConstruct, cache3);
22131
+ const cache4 = this.#caches.get(cacheName);
22132
+ return new Cache(kConstruct, cache4);
22133
22133
  }
22134
- const cache2 = [];
22135
- this.#caches.set(cacheName, cache2);
22136
- return new Cache(kConstruct, cache2);
22134
+ const cache3 = [];
22135
+ this.#caches.set(cacheName, cache3);
22136
+ return new Cache(kConstruct, cache3);
22137
22137
  }
22138
22138
  /**
22139
22139
  * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
@@ -22248,9 +22248,9 @@ var require_util4 = __commonJS({
22248
22248
  }
22249
22249
  }
22250
22250
  }
22251
- function validateCookiePath(path9) {
22252
- for (let i = 0; i < path9.length; ++i) {
22253
- const code = path9.charCodeAt(i);
22251
+ function validateCookiePath(path11) {
22252
+ for (let i = 0; i < path11.length; ++i) {
22253
+ const code = path11.charCodeAt(i);
22254
22254
  if (code < 32 || // exclude CTLs (0-31)
22255
22255
  code > 126 || // exclude DEL and non-ascii
22256
22256
  code === 59) {
@@ -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 path9 = opts.path;
25490
+ let path11 = opts.path;
25491
25491
  if (!opts.path.startsWith("/")) {
25492
- path9 = `/${path9}`;
25492
+ path11 = `/${path11}`;
25493
25493
  }
25494
- url = new URL(util.parseOrigin(url).origin + path9);
25494
+ url = new URL(util.parseOrigin(url).origin + path11);
25495
25495
  } else {
25496
25496
  if (!opts) {
25497
25497
  opts = typeof url === "object" ? url : {};
@@ -39943,20 +39943,20 @@ var require_tls = __commonJS({
39943
39943
  }
39944
39944
  return !c.fail;
39945
39945
  };
39946
- tls4.createSessionCache = function(cache2, capacity) {
39946
+ tls4.createSessionCache = function(cache3, capacity) {
39947
39947
  var rval = null;
39948
- if (cache2 && cache2.getSession && cache2.setSession && cache2.order) {
39949
- rval = cache2;
39948
+ if (cache3 && cache3.getSession && cache3.setSession && cache3.order) {
39949
+ rval = cache3;
39950
39950
  } else {
39951
39951
  rval = {};
39952
- rval.cache = cache2 || {};
39952
+ rval.cache = cache3 || {};
39953
39953
  rval.capacity = Math.max(capacity || 100, 1);
39954
39954
  rval.order = [];
39955
- for (var key2 in cache2) {
39955
+ for (var key2 in cache3) {
39956
39956
  if (rval.order.length <= capacity) {
39957
39957
  rval.order.push(key2);
39958
39958
  } else {
39959
- delete cache2[key2];
39959
+ delete cache3[key2];
39960
39960
  }
39961
39961
  }
39962
39962
  rval.getSession = function(sessionId) {
@@ -46252,13 +46252,13 @@ function getUpstreamConnectionStatus() {
46252
46252
  }
46253
46253
 
46254
46254
  // src/config.ts
46255
- function safeReadJson(path9) {
46255
+ function safeReadJson(path11) {
46256
46256
  try {
46257
- const raw = readFileSync(path9, "utf8").replace(/^\uFEFF/, "");
46257
+ const raw = readFileSync(path11, "utf8").replace(/^\uFEFF/, "");
46258
46258
  return JSON.parse(raw);
46259
46259
  } catch (e) {
46260
46260
  if (e.code !== "ENOENT") {
46261
- log("error", `[acp-config] failed to parse ${path9}: ${String(e)}`);
46261
+ log("error", `[acp-config] failed to parse ${path11}: ${String(e)}`);
46262
46262
  }
46263
46263
  return void 0;
46264
46264
  }
@@ -46481,7 +46481,7 @@ function rejectLegacyRoute(key, value) {
46481
46481
 
46482
46482
  // src/server.ts
46483
46483
  import http from "http";
46484
- import fs3 from "fs";
46484
+ import fs5 from "fs";
46485
46485
 
46486
46486
  // src/registry.ts
46487
46487
  import { readFile, writeFile, mkdir } from "fs/promises";
@@ -46861,6 +46861,17 @@ function openaiToCore(body) {
46861
46861
  break;
46862
46862
  }
46863
46863
  case "assistant": {
46864
+ const reasoning = typeof m2.reasoning_content === "string" ? m2.reasoning_content : "";
46865
+ if (reasoning) {
46866
+ const base = deriveMessageId("assistant", "reasoning", reasoning);
46867
+ msgs.push({
46868
+ id: clusters.next(base),
46869
+ role: "assistant",
46870
+ contentType: "reasoning",
46871
+ text: reasoning,
46872
+ reasoningContent: reasoning
46873
+ });
46874
+ }
46864
46875
  const text = stringContent(m2.content);
46865
46876
  if (text) {
46866
46877
  const base = deriveMessageId("assistant", "text", text);
@@ -46906,21 +46917,27 @@ function coreToOpenai(messages) {
46906
46917
  let pending = null;
46907
46918
  const flush = () => {
46908
46919
  if (!pending) return;
46920
+ const reasoning = pending.reasoning !== null && pending.reasoning.length > 0 ? pending.reasoning : void 0;
46909
46921
  if (pending.toolCalls.length > 0) {
46910
46922
  out.push({
46911
46923
  role: "assistant",
46912
46924
  content: pending.text ?? null,
46913
- tool_calls: pending.toolCalls
46925
+ tool_calls: pending.toolCalls,
46926
+ ...reasoning ? { reasoning_content: reasoning } : {}
46914
46927
  });
46915
46928
  } else if (pending.text !== null) {
46916
- out.push({ role: "assistant", content: pending.text });
46929
+ out.push({ role: "assistant", content: pending.text, ...reasoning ? { reasoning_content: reasoning } : {} });
46930
+ } else if (reasoning) {
46931
+ out.push({ role: "assistant", content: null, reasoning_content: reasoning });
46917
46932
  }
46918
46933
  pending = null;
46919
46934
  };
46920
46935
  for (const m2 of messages) {
46921
46936
  if (m2.role === "assistant") {
46922
- if (!pending) pending = { text: null, toolCalls: [] };
46923
- if (m2.contentType === "text") {
46937
+ if (!pending) pending = { text: null, toolCalls: [], reasoning: null };
46938
+ if (m2.contentType === "reasoning") {
46939
+ pending.reasoning = (pending.reasoning ?? "") + (m2.reasoningContent ?? m2.text ?? "");
46940
+ } else if (m2.contentType === "text") {
46924
46941
  pending.text = (pending.text ?? "") + (m2.text ?? "");
46925
46942
  } else if (m2.contentType === "tool-call") {
46926
46943
  pending.toolCalls.push({
@@ -48569,6 +48586,7 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
48569
48586
  for (let round = 1; round <= MAX_LOOP_ROUNDS; round++) {
48570
48587
  if (signal?.aborted) break;
48571
48588
  let assistantText = "";
48589
+ let assistantReasoning = "";
48572
48590
  const calls = [];
48573
48591
  let usage = {};
48574
48592
  let finishReason;
@@ -48576,11 +48594,20 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
48576
48594
  if (signal?.aborted) break;
48577
48595
  if (ev.kind === "text") {
48578
48596
  assistantText += ev.delta;
48579
- if (!ctx.textProtocol && round === 1 && ev.raw) {
48597
+ if (!ctx.textProtocol && ev.raw) {
48580
48598
  yield ev.raw;
48581
48599
  } else if (!ctx.textProtocol && round > 1 && ev.delta.length > 0) {
48582
48600
  yield adapter.emitText(ev.delta);
48583
48601
  }
48602
+ } else if (ev.kind === "reasoning") {
48603
+ assistantReasoning += ev.delta;
48604
+ if (!ctx.textProtocol) {
48605
+ if (ev.raw) {
48606
+ yield ev.raw;
48607
+ } else if (round > 1 && ev.delta.length > 0 && adapter.emitReasoning) {
48608
+ yield adapter.emitReasoning(ev.delta);
48609
+ }
48610
+ }
48584
48611
  } else if (ev.kind === "tool_call") {
48585
48612
  calls.push({ name: ev.name, callId: ev.callId, arguments: ev.arguments });
48586
48613
  } else if (ev.kind === "usage") {
@@ -48643,6 +48670,16 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
48643
48670
  if (realCalls > 0) ctx.log(`[acp-loop] round ${round}: ${realCalls} real tool call(s) forwarded to client`);
48644
48671
  }
48645
48672
  if (proxyResults.length > 0) {
48673
+ if (assistantReasoning.length > 0) {
48674
+ const reasoningMsg = {
48675
+ id: `acp_loop_r${round}_reasoning`,
48676
+ role: "assistant",
48677
+ contentType: "reasoning",
48678
+ text: assistantReasoning,
48679
+ reasoningContent: assistantReasoning
48680
+ };
48681
+ coreMessages.push(reasoningMsg);
48682
+ }
48646
48683
  if (assistantText.length > 0) {
48647
48684
  coreMessages.push({
48648
48685
  id: `acp_loop_r${round}_asst`,
@@ -48708,11 +48745,11 @@ async function* runCompressLoop(upstream, ctx, requestBody, requestOptions, adap
48708
48745
  const newBody = adapter.buildRequest(coreMessages, systemPrompt, requestBody);
48709
48746
  if (process.env.ACP_DUMP_REQ !== "0" && ctx.debug) {
48710
48747
  try {
48711
- const fs6 = await import("fs");
48748
+ const fs8 = await import("fs");
48712
48749
  const dumpDir = process.env.ACP_DUMP_DIR || `${process.env.HOME}/.local/state/billion-context/dumps`;
48713
- fs6.mkdirSync(dumpDir, { recursive: true });
48750
+ fs8.mkdirSync(dumpDir, { recursive: true });
48714
48751
  const sid = ctx.session.id ?? "unknown";
48715
- fs6.writeFileSync(`${dumpDir}/req-${Date.now()}-${sid}-REREQUEST.json`, JSON.stringify(newBody, null, 2));
48752
+ fs8.writeFileSync(`${dumpDir}/req-${Date.now()}-${sid}-REREQUEST.json`, JSON.stringify(newBody, null, 2));
48716
48753
  } catch {
48717
48754
  }
48718
48755
  }
@@ -49157,6 +49194,18 @@ function createOpenaiAdapter(requestBody) {
49157
49194
  choices: [{ index: 0, delta: { content }, finish_reason: null }]
49158
49195
  })}
49159
49196
 
49197
+ `,
49198
+ "utf8"
49199
+ );
49200
+ const buildReasoning = (content) => Buffer.from(
49201
+ `data: ${JSON.stringify({
49202
+ id: responseId,
49203
+ object: "chat.completion.chunk",
49204
+ created: Date.now(),
49205
+ model,
49206
+ choices: [{ index: 0, delta: { reasoning_content: content }, finish_reason: null }]
49207
+ })}
49208
+
49160
49209
  `,
49161
49210
  "utf8"
49162
49211
  );
@@ -49267,6 +49316,9 @@ function createOpenaiAdapter(requestBody) {
49267
49316
  yield { kind: "done", finishReason };
49268
49317
  }
49269
49318
  if (!delta) continue;
49319
+ if (typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0) {
49320
+ yield { kind: "reasoning", delta: delta.reasoning_content, raw: rawBuf };
49321
+ }
49270
49322
  if (delta.tool_calls) {
49271
49323
  const tcs = delta.tool_calls;
49272
49324
  for (const tc of tcs) {
@@ -49290,9 +49342,10 @@ function createOpenaiAdapter(requestBody) {
49290
49342
  }
49291
49343
  continue;
49292
49344
  }
49345
+ const hasReasoning = typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0;
49293
49346
  if (typeof delta.content === "string" && delta.content.length > 0) {
49294
- yield { kind: "text", delta: delta.content, raw: rawBuf };
49295
- } else if (delta.role || Object.keys(delta).length === 0 && !finishReason) {
49347
+ yield { kind: "text", delta: delta.content, ...hasReasoning ? {} : { raw: rawBuf } };
49348
+ } else if (!hasReasoning && (delta.role || Object.keys(delta).length === 0 && !finishReason)) {
49296
49349
  yield { kind: "meta", chunk: rawBuf, firstRoundOnly: true };
49297
49350
  }
49298
49351
  }
@@ -49300,6 +49353,9 @@ function createOpenaiAdapter(requestBody) {
49300
49353
  emitText(delta) {
49301
49354
  return buildContent(delta);
49302
49355
  },
49356
+ emitReasoning(delta) {
49357
+ return buildReasoning(delta);
49358
+ },
49303
49359
  emitToolCall(call) {
49304
49360
  return buildToolCall(call);
49305
49361
  },
@@ -49487,10 +49543,10 @@ ${systemPrompt}` : systemPrompt;
49487
49543
  const name = typeof block.name === "string" ? block.name : "";
49488
49544
  const id = typeof block.id === "string" ? block.id : `toolu_${upstreamIndex}`;
49489
49545
  pending.set(upstreamIndex, { id, name, json: "" });
49490
- } else if (round === 1) {
49546
+ } else {
49491
49547
  const ci2 = clientIndex++;
49492
49548
  indexMap.set(upstreamIndex, ci2);
49493
- yield { kind: "meta", chunk: remapIndexInEvent(eventStr, ci2), firstRoundOnly: true };
49549
+ yield { kind: "meta", chunk: remapIndexInEvent(eventStr, ci2), firstRoundOnly: round === 1 };
49494
49550
  }
49495
49551
  } else if (type === "content_block_delta") {
49496
49552
  const upstreamIndex = data.index ?? 0;
@@ -49500,12 +49556,8 @@ ${systemPrompt}` : systemPrompt;
49500
49556
  pending.get(upstreamIndex).json += delta.partial_json;
49501
49557
  }
49502
49558
  } else if (delta.type === "text_delta" && typeof delta.text === "string") {
49503
- if (round === 1) {
49504
- const ci2 = indexMap.get(upstreamIndex) ?? upstreamIndex;
49505
- yield { kind: "text", delta: delta.text, raw: remapIndexInEvent(eventStr, ci2) };
49506
- } else {
49507
- yield { kind: "text", delta: delta.text };
49508
- }
49559
+ const ci2 = indexMap.get(upstreamIndex) ?? upstreamIndex;
49560
+ yield { kind: "text", delta: delta.text, raw: remapIndexInEvent(eventStr, ci2) };
49509
49561
  } else if (round === 1) {
49510
49562
  const ci2 = indexMap.get(upstreamIndex) ?? upstreamIndex;
49511
49563
  yield { kind: "meta", chunk: remapIndexInEvent(eventStr, ci2), firstRoundOnly: true };
@@ -49521,9 +49573,9 @@ ${systemPrompt}` : systemPrompt;
49521
49573
  callId: tb.id,
49522
49574
  arguments: tb.json
49523
49575
  };
49524
- } else if (round === 1) {
49576
+ } else {
49525
49577
  const ci2 = indexMap.get(upstreamIndex) ?? upstreamIndex;
49526
- yield { kind: "meta", chunk: remapIndexInEvent(eventStr, ci2), firstRoundOnly: true };
49578
+ yield { kind: "meta", chunk: remapIndexInEvent(eventStr, ci2), firstRoundOnly: round === 1 };
49527
49579
  }
49528
49580
  } else if (type === "message_delta") {
49529
49581
  const u2 = data.usage ?? {};
@@ -50008,17 +50060,239 @@ function getSecureContext(host) {
50008
50060
  return ctx;
50009
50061
  }
50010
50062
 
50063
+ // src/discover.ts
50064
+ import fs4 from "fs";
50065
+ import os2 from "os";
50066
+ import path7 from "path";
50067
+
50068
+ // src/client-config.ts
50069
+ import fs3 from "fs";
50070
+ import os from "os";
50071
+ import path6 from "path";
50072
+ function nonEmpty2(s3) {
50073
+ return typeof s3 === "string" && s3.trim().length > 0;
50074
+ }
50075
+ function readJsonObject(filePath) {
50076
+ try {
50077
+ const txt = fs3.readFileSync(filePath, "utf8");
50078
+ const parsed = JSON.parse(txt);
50079
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
50080
+ } catch {
50081
+ return null;
50082
+ }
50083
+ }
50084
+ function resolvePiHome(env) {
50085
+ const h = os.homedir();
50086
+ return nonEmpty2(env.PI_CODING_AGENT_DIR) ? env.PI_CODING_AGENT_DIR : nonEmpty2(env.PI_HOME) ? env.PI_HOME : path6.join(h, ".pi", "agent");
50087
+ }
50088
+ function readClaudeSettings(homeDir, cwd) {
50089
+ const files = [
50090
+ path6.join(homeDir, ".claude", "settings.json"),
50091
+ path6.join(cwd, ".claude", "settings.json")
50092
+ ];
50093
+ let anthropicBaseUrl;
50094
+ for (const f2 of files) {
50095
+ const obj = readJsonObject(f2);
50096
+ const env = obj?.env;
50097
+ if (env && typeof env === "object" && !Array.isArray(env)) {
50098
+ const v2 = env.ANTHROPIC_BASE_URL;
50099
+ if (nonEmpty2(v2)) anthropicBaseUrl = v2;
50100
+ }
50101
+ }
50102
+ return anthropicBaseUrl ? { anthropicBaseUrl } : {};
50103
+ }
50104
+ function parseCodexToml(text) {
50105
+ const result = { providers: {} };
50106
+ let table = "";
50107
+ let curProvider = null;
50108
+ for (const rawLine of text.split(/\r?\n/)) {
50109
+ const line = rawLine.trim();
50110
+ if (!line || line.startsWith("#")) continue;
50111
+ const tableMatch = /^\[([^\]]+)\]$/.exec(line);
50112
+ if (tableMatch) {
50113
+ table = tableMatch[1].trim();
50114
+ curProvider = table.startsWith("model_providers.") ? table.slice("model_providers.".length).trim() : null;
50115
+ if (curProvider && !result.providers[curProvider]) {
50116
+ result.providers[curProvider] = {};
50117
+ }
50118
+ continue;
50119
+ }
50120
+ const m2 = /^([A-Za-z0-9_.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(line);
50121
+ if (!m2) continue;
50122
+ const key = m2[1];
50123
+ const val = m2[2] !== void 0 ? m2[2] : m2[3];
50124
+ if (table === "") {
50125
+ if (key === "model_provider") result.modelProvider = val;
50126
+ else if (key === "openai_base_url") result.openaiBaseUrl = val;
50127
+ } else if (curProvider && key === "base_url") {
50128
+ result.providers[curProvider].baseUrl = val;
50129
+ }
50130
+ }
50131
+ return result;
50132
+ }
50133
+ function readCodexConfig(codexHome) {
50134
+ const cfgPath = path6.join(codexHome, "config.toml");
50135
+ let text;
50136
+ try {
50137
+ text = fs3.readFileSync(cfgPath, "utf8");
50138
+ } catch {
50139
+ return { providers: {} };
50140
+ }
50141
+ return parseCodexToml(text);
50142
+ }
50143
+ function readPiConfig(piHome) {
50144
+ const cfgPath = path6.join(piHome, "models.json");
50145
+ const obj = readJsonObject(cfgPath);
50146
+ const providers = {};
50147
+ const rawProviders = obj?.providers;
50148
+ if (rawProviders && typeof rawProviders === "object" && !Array.isArray(rawProviders)) {
50149
+ for (const [name, val] of Object.entries(rawProviders)) {
50150
+ if (val && typeof val === "object" && !Array.isArray(val)) {
50151
+ const baseUrl = val.baseUrl;
50152
+ providers[name] = typeof baseUrl === "string" ? { baseUrl } : {};
50153
+ }
50154
+ }
50155
+ }
50156
+ return { providers };
50157
+ }
50158
+ function parseZcodeConfig(obj) {
50159
+ const result = { providers: {} };
50160
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) return result;
50161
+ const root = obj;
50162
+ const providerField = root.provider;
50163
+ if (!providerField || typeof providerField !== "object" || Array.isArray(providerField)) return result;
50164
+ const providerMap = providerField;
50165
+ for (const [name, val] of Object.entries(providerMap)) {
50166
+ if (!val || typeof val !== "object" || Array.isArray(val)) continue;
50167
+ const options = val.options;
50168
+ if (!options || typeof options !== "object" || Array.isArray(options)) continue;
50169
+ const baseURL = options.baseURL;
50170
+ if (typeof baseURL === "string") result.providers[name] = { baseURL };
50171
+ }
50172
+ return result;
50173
+ }
50174
+ function readZcodeConfig(zcodeHome) {
50175
+ const cfgPath = path6.join(zcodeHome, "v2", "config.json");
50176
+ let txt;
50177
+ try {
50178
+ txt = fs3.readFileSync(cfgPath, "utf8");
50179
+ } catch {
50180
+ return { providers: {} };
50181
+ }
50182
+ let parsed;
50183
+ try {
50184
+ parsed = JSON.parse(txt);
50185
+ } catch {
50186
+ return { providers: {} };
50187
+ }
50188
+ return parseZcodeConfig(parsed);
50189
+ }
50190
+ function loadClientConfig(env, cwd) {
50191
+ const home = os.homedir();
50192
+ const config = {};
50193
+ config.claude = readClaudeSettings(home, cwd);
50194
+ const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path6.join(home, ".codex");
50195
+ config.codex = readCodexConfig(codexHome);
50196
+ config.pi = readPiConfig(resolvePiHome(env));
50197
+ const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path6.join(home, ".zcode");
50198
+ config.zcode = readZcodeConfig(zcodeHome);
50199
+ return config;
50200
+ }
50201
+
50202
+ // src/discover.ts
50203
+ var TTL_MS2 = 2e3;
50204
+ function unwrapUpstream(url) {
50205
+ const idx = url.indexOf("/bili/");
50206
+ return idx >= 0 ? url.slice(idx + "/bili/".length) : url;
50207
+ }
50208
+ function extractHttpsHosts(config) {
50209
+ const seen = /* @__PURE__ */ new Set();
50210
+ const out = [];
50211
+ const push = (raw) => {
50212
+ if (typeof raw !== "string" || raw.length === 0) return;
50213
+ let url;
50214
+ try {
50215
+ url = new URL(unwrapUpstream(raw));
50216
+ } catch {
50217
+ return;
50218
+ }
50219
+ if (url.protocol !== "https:") return;
50220
+ const host = url.hostname.toLowerCase();
50221
+ if (!host || seen.has(host)) return;
50222
+ seen.add(host);
50223
+ out.push(host);
50224
+ };
50225
+ if (nonEmpty2(config.claude?.anthropicBaseUrl)) push(config.claude.anthropicBaseUrl);
50226
+ if (config.codex) {
50227
+ for (const prov of Object.values(config.codex.providers)) push(prov.baseUrl);
50228
+ push(config.codex.openaiBaseUrl);
50229
+ }
50230
+ if (config.pi) {
50231
+ for (const prov of Object.values(config.pi.providers)) push(prov.baseUrl);
50232
+ }
50233
+ if (config.zcode) {
50234
+ for (const prov of Object.values(config.zcode.providers)) push(prov.baseURL);
50235
+ }
50236
+ return out;
50237
+ }
50238
+ function configFilePaths(env) {
50239
+ const home = os2.homedir();
50240
+ const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path7.join(home, ".codex");
50241
+ const zcodeHome = nonEmpty2(env.ZCODE_DATA_BASE_DIR) ? env.ZCODE_DATA_BASE_DIR : path7.join(home, ".zcode");
50242
+ return [
50243
+ path7.join(home, ".claude", "settings.json"),
50244
+ path7.join(process.cwd(), ".claude", "settings.json"),
50245
+ path7.join(codexHome, "config.toml"),
50246
+ path7.join(resolvePiHome(env), "models.json"),
50247
+ path7.join(zcodeHome, "v2", "config.json")
50248
+ ];
50249
+ }
50250
+ function readMtimes(paths) {
50251
+ const mtimes = /* @__PURE__ */ new Map();
50252
+ for (const p2 of paths) {
50253
+ try {
50254
+ const st2 = fs4.statSync(p2);
50255
+ mtimes.set(p2, st2.mtimeMs);
50256
+ } catch {
50257
+ }
50258
+ }
50259
+ return mtimes;
50260
+ }
50261
+ function mtimesEqual(a, b2) {
50262
+ if (a.size !== b2.size) return false;
50263
+ for (const [k2, v2] of a) {
50264
+ if (b2.get(k2) !== v2) return false;
50265
+ }
50266
+ return true;
50267
+ }
50268
+ var cache2 = null;
50269
+ function discoverMitmDomains(env = process.env) {
50270
+ const now = Date.now();
50271
+ if (cache2 && now - cache2.checkedAt < TTL_MS2) {
50272
+ return cache2.domains;
50273
+ }
50274
+ const paths = configFilePaths(env);
50275
+ const mtimes = readMtimes(paths);
50276
+ if (cache2 && mtimesEqual(mtimes, cache2.mtimes)) {
50277
+ cache2.checkedAt = now;
50278
+ return cache2.domains;
50279
+ }
50280
+ const config = loadClientConfig(env, process.cwd());
50281
+ const domains = extractHttpsHosts(config);
50282
+ cache2 = { checkedAt: now, mtimes, domains };
50283
+ return domains;
50284
+ }
50285
+
50011
50286
  // src/mitm.ts
50012
50287
  var DEFAULT_MITM_DOMAINS = [
50013
- "open.bigmodel.cn",
50014
50288
  "api.anthropic.com",
50015
50289
  "api.openai.com",
50016
50290
  "chatgpt.com"
50017
50291
  ];
50018
50292
  var MITM_UPSTREAM_KEY = "__biliMitmUpstream";
50019
- function isMitmHost(host, extra = []) {
50293
+ function isMitmHost(host, extraDomains = []) {
50020
50294
  const h = host.toLowerCase();
50021
- const all = [...DEFAULT_MITM_DOMAINS, ...extra].map((d) => d.toLowerCase());
50295
+ const all = [...DEFAULT_MITM_DOMAINS, ...extraDomains, ...discoverMitmDomains()].map((d) => d.toLowerCase());
50022
50296
  return all.some((d) => h === d || h.endsWith("." + d));
50023
50297
  }
50024
50298
  function setupMitm(server, extraDomains = [], log2 = () => {
@@ -51084,7 +51358,7 @@ async function handle(req, res, opts, core, config, log2) {
51084
51358
  urlPath = url.split("?", 2)[0];
51085
51359
  responsesCompact = urlPath.endsWith("/responses/compact");
51086
51360
  route = resolveUpstream(opts, req.url ?? "", req);
51087
- upstreamOrigin = route ? route.upstream : opts.upstream;
51361
+ upstreamOrigin = route ? route.upstream : /^https?:\/\//i.test(url) ? new URL(url).origin : opts.upstream;
51088
51362
  protocol = route?.explicitProtocol ?? (req.method === "POST" && bodyBuffer.length > 0 ? urlPath.endsWith("/chat/completions") ? "openai" : urlPath.endsWith("/v1/messages") || urlPath.endsWith("/messages") ? "anthropic" : urlPath.endsWith("/responses") || responsesCompact ? "responses" : null : null);
51089
51363
  if (protocol !== null && bodyBuffer.length > 0) {
51090
51364
  const decoded = await decodeRequestBody(headerValue(req, "content-encoding"), bodyBuffer, MAX_REQUEST_BYTES);
@@ -51120,11 +51394,11 @@ async function handle(req, res, opts, core, config, log2) {
51120
51394
  log2("info", `[debug] INCOMING previous_response_id=${hasPrev ? String(p2.previous_response_id).slice(0, 16) : "absent"} input_items=${inLen} instructions=${p2.instructions !== void 0 ? "present" : "absent"}`);
51121
51395
  const rawDir = `${stateDir()}/raw`;
51122
51396
  try {
51123
- fs3.mkdirSync(rawDir, { recursive: true });
51397
+ fs5.mkdirSync(rawDir, { recursive: true });
51124
51398
  } catch {
51125
51399
  }
51126
51400
  const hdrs = Object.entries(req.headers).filter(([k2]) => !/authorization|x-api-key|cookie/i.test(k2)).map(([k2, v2]) => `${k2}: ${Array.isArray(v2) ? v2.join(",") : v2}`).join("\n");
51127
- fs3.writeFileSync(`${rawDir}/${Date.now()}-INCOMING.txt`, `${req.method} ${req.url}
51401
+ fs5.writeFileSync(`${rawDir}/${Date.now()}-INCOMING.txt`, `${req.method} ${req.url}
51128
51402
  ${hdrs}
51129
51403
 
51130
51404
  ${bodyBuffer.toString("utf8")}`);
@@ -51506,7 +51780,9 @@ function injectResponsesTool(tools, toolsToAdd = ACP_TOOLS_RESPONSES) {
51506
51780
  return [...tools, ...additions];
51507
51781
  }
51508
51782
  async function forward(req, res, opts, body, prepared, core, config, log2, route, affinity) {
51509
- const rewritten = route ? route.rewrittenUrl : opts.upstream + (req.url ?? "");
51783
+ const reqUrl = req.url ?? "";
51784
+ const isAbsoluteUrl = /^https?:\/\//i.test(reqUrl);
51785
+ const rewritten = route ? route.rewrittenUrl : isAbsoluteUrl ? reqUrl : opts.upstream + reqUrl;
51510
51786
  const upstreamUrl = rewritten.replace(/^mitm:\/\//, "https://");
51511
51787
  log2("info", `forward ${req.method} \u2192 ${upstreamUrl}`);
51512
51788
  if (process.env.ACP_DEBUG && prepared) {
@@ -51533,16 +51809,16 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
51533
51809
  if (process.env.ACP_DUMP_REQ !== "0") {
51534
51810
  const dumpDir = process.env.ACP_DUMP_DIR || `${stateDir()}/dumps`;
51535
51811
  try {
51536
- fs3.mkdirSync(dumpDir, { recursive: true });
51812
+ fs5.mkdirSync(dumpDir, { recursive: true });
51537
51813
  } catch {
51538
51814
  }
51539
51815
  const sid = prepared?.session.id ?? "unknown";
51540
51816
  const out = `${dumpDir}/req-${Date.now()}-${sid}.json`;
51541
51817
  try {
51542
51818
  const pretty = JSON.stringify(JSON.parse(body), null, 2);
51543
- fs3.writeFileSync(out, pretty);
51819
+ fs5.writeFileSync(out, pretty);
51544
51820
  } catch {
51545
- fs3.writeFileSync(out, body);
51821
+ fs5.writeFileSync(out, body);
51546
51822
  }
51547
51823
  log2("info", `[debug] forwarded body written to ${out}`);
51548
51824
  }
@@ -51554,7 +51830,7 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
51554
51830
  if (UPSTREAM_HOP_HEADERS.has(k2.toLowerCase()) || v2 === void 0) continue;
51555
51831
  headers[k2] = Array.isArray(v2) ? v2.join(", ") : v2;
51556
51832
  }
51557
- headers["host"] = new URL(route ? route.upstream : opts.upstream).host;
51833
+ headers["host"] = new URL(upstreamUrl).host;
51558
51834
  const betaKey = Object.keys(headers).find((h) => h.toLowerCase() === "x-codex-beta-features");
51559
51835
  if (betaKey) {
51560
51836
  const kept = headers[betaKey].split(",").map((s3) => s3.trim()).filter((f2) => f2 && f2 !== "remote_compaction_v2");
@@ -51575,7 +51851,7 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
51575
51851
  const rawBase = opts.debug ? (() => {
51576
51852
  try {
51577
51853
  const rawDir = process.env.ACP_RAW_DUMP_DIR || `${stateDir()}/raw`;
51578
- fs3.mkdirSync(rawDir, { recursive: true });
51854
+ fs5.mkdirSync(rawDir, { recursive: true });
51579
51855
  return `${rawDir}/${Date.now()}-${prepared?.session.id ?? "unknown"}`;
51580
51856
  } catch {
51581
51857
  return "";
@@ -51587,7 +51863,7 @@ async function forward(req, res, opts, body, prepared, core, config, log2, route
51587
51863
  const hdrText = Object.entries(headers).map(([k2, v2]) => `${k2}: ${maskHdr(k2, String(v2))}`).join("\n");
51588
51864
  const bodyText = req.method === "GET" || req.method === "HEAD" ? "" : typeof body === "string" ? body : Buffer.from(body).toString("utf8");
51589
51865
  const reqPath = `${rawBase}-REQ.txt`;
51590
- fs3.writeFileSync(reqPath, `${req.method ?? "POST"} ${upstreamUrl}
51866
+ fs5.writeFileSync(reqPath, `${req.method ?? "POST"} ${upstreamUrl}
51591
51867
  ${hdrText}
51592
51868
 
51593
51869
  ${bodyText}`);
@@ -51629,7 +51905,7 @@ ${bodyText}`);
51629
51905
  const maskHdr = (k2, v2) => /key|auth|token/i.test(k2) ? `<masked ${v2.length} chars>` : v2;
51630
51906
  const hdrText = Object.entries(respHeaders).map(([k2, v2]) => `${k2}: ${maskHdr(k2, v2)}`).join("\n");
51631
51907
  const resPath = `${rawBase}-RES.txt`;
51632
- fs3.writeFileSync(resPath, `${upstream.status}
51908
+ fs5.writeFileSync(resPath, `${upstream.status}
51633
51909
  ${hdrText}
51634
51910
  `);
51635
51911
  log2("info", `[debug] RAW response dump: ${resPath}`);
@@ -53360,7 +53636,7 @@ var ss = /* @__PURE__ */ Symbol("lstat");
53360
53636
  var si = /* @__PURE__ */ Symbol("onlstat");
53361
53637
  var rs = /* @__PURE__ */ Symbol("onread");
53362
53638
  var ns = /* @__PURE__ */ Symbol("onreadlink");
53363
- var os = /* @__PURE__ */ Symbol("openfile");
53639
+ var os3 = /* @__PURE__ */ Symbol("openfile");
53364
53640
  var hs = /* @__PURE__ */ Symbol("onopenfile");
53365
53641
  var pt = /* @__PURE__ */ Symbol("close");
53366
53642
  var ri = /* @__PURE__ */ Symbol("mode");
@@ -53475,9 +53751,9 @@ var de = class extends A {
53475
53751
  this.linkCache.set(t, this.absolute);
53476
53752
  }
53477
53753
  if (this[fe](), this.stat.size === 0) return this.end();
53478
- this[os]();
53754
+ this[os3]();
53479
53755
  }
53480
- [os]() {
53756
+ [os3]() {
53481
53757
  X.open(this.absolute, "r", (t, e) => {
53482
53758
  if (t) return this.emit("error", t);
53483
53759
  this[hs](e);
@@ -53540,7 +53816,7 @@ var ni = class extends de {
53540
53816
  [is]() {
53541
53817
  this[ns](X.readlinkSync(this.absolute));
53542
53818
  }
53543
- [os]() {
53819
+ [os3]() {
53544
53820
  this[hs](X.openSync(this.absolute, "r"));
53545
53821
  }
53546
53822
  [ii]() {
@@ -53827,7 +54103,7 @@ var hr = /* @__PURE__ */ Symbol("entry");
53827
54103
  var cs = /* @__PURE__ */ Symbol("entryOpt");
53828
54104
  var ui = /* @__PURE__ */ Symbol("writeEntryClass");
53829
54105
  var lr = /* @__PURE__ */ Symbol("write");
53830
- var fs4 = /* @__PURE__ */ Symbol("ondrain");
54106
+ var fs6 = /* @__PURE__ */ Symbol("ondrain");
53831
54107
  var wt = class extends A {
53832
54108
  sync = false;
53833
54109
  opt;
@@ -53861,8 +54137,8 @@ var wt = class extends A {
53861
54137
  if ((t.gzip ? 1 : 0) + (t.brotli ? 1 : 0) + (t.zstd ? 1 : 0) > 1) throw new TypeError("gzip, brotli, zstd are mutually exclusive");
53862
54138
  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");
53863
54139
  let e = this.zip;
53864
- e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs4]()), this.on("resume", () => e.resume());
53865
- } else this.on("drain", this[fs4]);
54140
+ e.on("data", (i) => super.write(i)), e.on("end", () => super.end()), e.on("drain", () => this[fs6]()), this.on("resume", () => e.resume());
54141
+ } else this.on("drain", this[fs6]);
53866
54142
  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;
53867
54143
  }
53868
54144
  [lr](t) {
@@ -53975,7 +54251,7 @@ var wt = class extends A {
53975
54251
  this.emit("error", e);
53976
54252
  }
53977
54253
  }
53978
- [fs4]() {
54254
+ [fs6]() {
53979
54255
  this[Et] && this[Et].entry && this[Et].entry.resume();
53980
54256
  }
53981
54257
  [di](t) {
@@ -54860,12 +55136,12 @@ var To = (s3) => {
54860
55136
  };
54861
55137
 
54862
55138
  // src/update.ts
54863
- import path6 from "path";
55139
+ import path8 from "path";
54864
55140
  import { fileURLToPath as fileURLToPath2 } from "url";
54865
55141
  var REGISTRY_BASE = "https://registry.npmjs.org";
54866
55142
  var CHECK_INTERVAL_MS = 3 * 60 * 1e3;
54867
- var THROTTLE_FILE = path6.join(cacheDir(), ".update-check");
54868
- var LOCK_FILE = path6.join(cacheDir(), ".update-lock");
55143
+ var THROTTLE_FILE = path8.join(cacheDir(), ".update-check");
55144
+ var LOCK_FILE = path8.join(cacheDir(), ".update-lock");
54869
55145
  var LOCK_STALE_MS = 2 * 60 * 1e3;
54870
55146
  var timer;
54871
55147
  var inFlight = false;
@@ -54894,27 +55170,27 @@ async function readLastCheck() {
54894
55170
  }
54895
55171
  async function writeLastCheck(ts2) {
54896
55172
  try {
54897
- await mkdir2(path6.dirname(THROTTLE_FILE), { recursive: true });
55173
+ await mkdir2(path8.dirname(THROTTLE_FILE), { recursive: true });
54898
55174
  await writeFile2(THROTTLE_FILE, String(ts2), "utf-8");
54899
55175
  } catch {
54900
55176
  }
54901
55177
  }
54902
55178
  async function findInstallDir(packageName) {
54903
- let dir = path6.dirname(fileURLToPath2(import.meta.url));
55179
+ let dir = path8.dirname(fileURLToPath2(import.meta.url));
54904
55180
  for (; ; ) {
54905
55181
  try {
54906
- const pkg = JSON.parse(await readFile2(path6.join(dir, "package.json"), "utf-8"));
55182
+ const pkg = JSON.parse(await readFile2(path8.join(dir, "package.json"), "utf-8"));
54907
55183
  if (pkg.name === packageName) return dir;
54908
55184
  } catch {
54909
55185
  }
54910
- const parent = path6.dirname(dir);
55186
+ const parent = path8.dirname(dir);
54911
55187
  if (parent === dir) return void 0;
54912
55188
  dir = parent;
54913
55189
  }
54914
55190
  }
54915
55191
  async function readDiskVersion(installDir) {
54916
55192
  try {
54917
- const pkg = JSON.parse(await readFile2(path6.join(installDir, "package.json"), "utf-8"));
55193
+ const pkg = JSON.parse(await readFile2(path8.join(installDir, "package.json"), "utf-8"));
54918
55194
  return pkg.version;
54919
55195
  } catch {
54920
55196
  return void 0;
@@ -55088,14 +55364,14 @@ async function installViaTarball(version2, tarballUrl, installDir) {
55088
55364
  } catch (e) {
55089
55365
  return { ok: false, error: `tarball download failed: ${String(e)}` };
55090
55366
  }
55091
- const tmpFile = path6.join(cacheDir(), `.update-${version2}.tgz`);
55367
+ const tmpFile = path8.join(cacheDir(), `.update-${version2}.tgz`);
55092
55368
  try {
55093
55369
  await mkdir2(cacheDir(), { recursive: true });
55094
55370
  await writeFile2(tmpFile, tgzBuffer);
55095
55371
  } catch (e) {
55096
55372
  return { ok: false, error: `failed to write temp file ${tmpFile}: ${String(e)}` };
55097
55373
  }
55098
- const stagingDir = path6.join(cacheDir(), `.update-staging-${version2}`);
55374
+ const stagingDir = path8.join(cacheDir(), `.update-staging-${version2}`);
55099
55375
  try {
55100
55376
  await rm(stagingDir, { recursive: true, force: true });
55101
55377
  await mkdir2(stagingDir, { recursive: true });
@@ -55138,10 +55414,10 @@ function startAutoUpdate(opts) {
55138
55414
  }
55139
55415
 
55140
55416
  // src/launcher.ts
55141
- import fs5 from "fs";
55417
+ import fs7 from "fs";
55142
55418
  import net2 from "net";
55143
- import os2 from "os";
55144
- import path7 from "path";
55419
+ import os4 from "os";
55420
+ import path9 from "path";
55145
55421
  import { spawn } from "child_process";
55146
55422
  var LAUNCHER_DEFAULT_HOST = "127.0.0.1";
55147
55423
  var LAUNCHER_DEFAULT_PORT = 8787;
@@ -55180,20 +55456,13 @@ function wrapUpstream(origin, upstream) {
55180
55456
  if (u2.startsWith(prefix)) return u2;
55181
55457
  return prefix + u2;
55182
55458
  }
55183
- function unwrapUpstream(url) {
55459
+ function unwrapUpstream2(url) {
55184
55460
  const idx = url.indexOf("/bili/");
55185
55461
  return idx >= 0 ? url.slice(idx + "/bili/".length) : url;
55186
55462
  }
55187
- function nonEmpty2(s3) {
55188
- return typeof s3 === "string" && s3.trim().length > 0;
55189
- }
55190
55463
  function resolveCaCertPath(env) {
55191
- const base = env.XDG_DATA_HOME || path7.join(os2.homedir(), ".local/share");
55192
- return path7.join(base, "billion-context", "ca", "root-ca.pem");
55193
- }
55194
- function resolvePiHome(env) {
55195
- const h = os2.homedir();
55196
- return nonEmpty2(env.PI_CODING_AGENT_DIR) ? env.PI_CODING_AGENT_DIR : nonEmpty2(env.PI_HOME) ? env.PI_HOME : path7.join(h, ".pi", "agent");
55464
+ const base = env.XDG_DATA_HOME || path9.join(os4.homedir(), ".local/share");
55465
+ return path9.join(base, "billion-context", "ca", "root-ca.pem");
55197
55466
  }
55198
55467
  function discoverRoutes(client, config) {
55199
55468
  const httpsDomains = [];
@@ -55206,7 +55475,7 @@ function discoverRoutes(client, config) {
55206
55475
  if (!nonEmpty2(raw)) return;
55207
55476
  let url;
55208
55477
  try {
55209
- url = new URL(unwrapUpstream(raw));
55478
+ url = new URL(unwrapUpstream2(raw));
55210
55479
  } catch {
55211
55480
  return;
55212
55481
  }
@@ -55216,14 +55485,14 @@ function discoverRoutes(client, config) {
55216
55485
  httpsSeen.add(host.toLowerCase());
55217
55486
  httpsDomains.push(host);
55218
55487
  }
55219
- if (raw !== unwrapUpstream(raw) && !httpsRewriteKeys.has(key)) {
55488
+ if (raw !== unwrapUpstream2(raw) && !httpsRewriteKeys.has(key)) {
55220
55489
  httpsRewriteKeys.add(key);
55221
- httpsRewrites.push({ key, realUpstream: unwrapUpstream(raw) });
55490
+ httpsRewrites.push({ key, realUpstream: unwrapUpstream2(raw) });
55222
55491
  }
55223
55492
  } else if (url.protocol === "http:") {
55224
55493
  if (!rewriteKeys.has(key)) {
55225
55494
  rewriteKeys.add(key);
55226
- httpRewrites.push({ key, realUpstream: unwrapUpstream(raw) });
55495
+ httpRewrites.push({ key, realUpstream: unwrapUpstream2(raw) });
55227
55496
  }
55228
55497
  }
55229
55498
  };
@@ -55273,10 +55542,10 @@ function buildClaudeEnv(origin, caPath, httpRewrites, httpsRewrites, baseEnv) {
55273
55542
  }
55274
55543
  function preparePiHttpRewrite(piHome, origin, httpRewrites, httpsRewrites) {
55275
55544
  if (httpRewrites.length === 0 && httpsRewrites.length === 0) return void 0;
55276
- const modelsPath = path7.join(piHome, "models.json");
55545
+ const modelsPath = path9.join(piHome, "models.json");
55277
55546
  let txt;
55278
55547
  try {
55279
- txt = fs5.readFileSync(modelsPath, "utf8");
55548
+ txt = fs7.readFileSync(modelsPath, "utf8");
55280
55549
  } catch {
55281
55550
  return void 0;
55282
55551
  }
@@ -55296,7 +55565,7 @@ function preparePiHttpRewrite(piHome, origin, httpRewrites, httpsRewrites) {
55296
55565
  if (prov && typeof prov === "object" && !Array.isArray(prov)) {
55297
55566
  const p2 = prov;
55298
55567
  const existing = typeof p2.baseUrl === "string" ? p2.baseUrl : r.realUpstream;
55299
- p2.baseUrl = wrapUpstream(origin, unwrapUpstream(existing));
55568
+ p2.baseUrl = wrapUpstream(origin, unwrapUpstream2(existing));
55300
55569
  }
55301
55570
  }
55302
55571
  for (const r of httpsRewrites) {
@@ -55307,18 +55576,18 @@ function preparePiHttpRewrite(piHome, origin, httpRewrites, httpsRewrites) {
55307
55576
  }
55308
55577
  }
55309
55578
  }
55310
- const tmp = fs5.mkdtempSync(path7.join(os2.tmpdir(), "bili-pi-"));
55579
+ const tmp = fs7.mkdtempSync(path9.join(os4.tmpdir(), "bili-pi-"));
55311
55580
  try {
55312
- for (const entry of fs5.readdirSync(piHome)) {
55581
+ for (const entry of fs7.readdirSync(piHome)) {
55313
55582
  if (entry === "models.json") continue;
55314
55583
  try {
55315
- fs5.symlinkSync(path7.join(piHome, entry), path7.join(tmp, entry));
55584
+ fs7.symlinkSync(path9.join(piHome, entry), path9.join(tmp, entry));
55316
55585
  } catch {
55317
55586
  }
55318
55587
  }
55319
55588
  } catch {
55320
55589
  }
55321
- fs5.writeFileSync(path7.join(tmp, "models.json"), JSON.stringify(root));
55590
+ fs7.writeFileSync(path9.join(tmp, "models.json"), JSON.stringify(root));
55322
55591
  return tmp;
55323
55592
  }
55324
55593
  function dedupeInOrder(list) {
@@ -55399,8 +55668,8 @@ async function ensureProxyRunning(opts, deps = {}) {
55399
55668
  const spawnedOrigin = proxyOrigin(opts.host, port);
55400
55669
  const script = process.argv[1];
55401
55670
  if (!script) throw new Error("bili: cannot resolve launcher script path");
55402
- const logPath2 = path7.join(os2.tmpdir(), `bili-proxy-${port}.log`);
55403
- const logFd = fs5.openSync(logPath2, "a");
55671
+ const logPath2 = path9.join(os4.tmpdir(), `bili-proxy-${port}.log`);
55672
+ const logFd = fs7.openSync(logPath2, "a");
55404
55673
  let child;
55405
55674
  try {
55406
55675
  child = spawnImpl(
@@ -55417,7 +55686,7 @@ async function ensureProxyRunning(opts, deps = {}) {
55417
55686
  );
55418
55687
  } finally {
55419
55688
  try {
55420
- fs5.closeSync(logFd);
55689
+ fs7.closeSync(logFd);
55421
55690
  } catch {
55422
55691
  }
55423
55692
  }
@@ -55466,8 +55735,8 @@ function isOnPath(name, env) {
55466
55735
  return p2.split(":").some((dir) => {
55467
55736
  if (!dir) return false;
55468
55737
  try {
55469
- const f2 = path7.join(dir, name);
55470
- return fs5.existsSync(f2) && fs5.statSync(f2).isFile();
55738
+ const f2 = path9.join(dir, name);
55739
+ return fs7.existsSync(f2) && fs7.statSync(f2).isFile();
55471
55740
  } catch {
55472
55741
  return false;
55473
55742
  }
@@ -55478,102 +55747,14 @@ function resolveClientCommand(client, env) {
55478
55747
  const piBin = env.PI_BIN?.trim();
55479
55748
  if (piBin) return { command: piBin, prefixArgs: [] };
55480
55749
  if (isOnPath("pi", env)) return { command: "pi", prefixArgs: [] };
55481
- const cli = path7.join(
55482
- os2.homedir(),
55750
+ const cli = path9.join(
55751
+ os4.homedir(),
55483
55752
  ".pi/agent/npm/node_modules/@earendil-works/pi-coding-agent/dist/cli.js"
55484
55753
  );
55485
55754
  return { command: process.execPath, prefixArgs: [cli] };
55486
55755
  }
55487
55756
  return { command: client, prefixArgs: [] };
55488
55757
  }
55489
- function readJsonObject(filePath) {
55490
- try {
55491
- const txt = fs5.readFileSync(filePath, "utf8");
55492
- const parsed = JSON.parse(txt);
55493
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
55494
- } catch {
55495
- return null;
55496
- }
55497
- }
55498
- function readClaudeSettings(homeDir, cwd) {
55499
- const files = [
55500
- path7.join(homeDir, ".claude", "settings.json"),
55501
- path7.join(cwd, ".claude", "settings.json")
55502
- ];
55503
- let anthropicBaseUrl;
55504
- for (const f2 of files) {
55505
- const obj = readJsonObject(f2);
55506
- const env = obj?.env;
55507
- if (env && typeof env === "object" && !Array.isArray(env)) {
55508
- const v2 = env.ANTHROPIC_BASE_URL;
55509
- if (nonEmpty2(v2)) anthropicBaseUrl = v2;
55510
- }
55511
- }
55512
- return anthropicBaseUrl ? { anthropicBaseUrl } : {};
55513
- }
55514
- function parseCodexToml(text) {
55515
- const result = { providers: {} };
55516
- let table = "";
55517
- let curProvider = null;
55518
- for (const rawLine of text.split(/\r?\n/)) {
55519
- const line = rawLine.trim();
55520
- if (!line || line.startsWith("#")) continue;
55521
- const tableMatch = /^\[([^\]]+)\]$/.exec(line);
55522
- if (tableMatch) {
55523
- table = tableMatch[1].trim();
55524
- curProvider = table.startsWith("model_providers.") ? table.slice("model_providers.".length).trim() : null;
55525
- if (curProvider && !result.providers[curProvider]) {
55526
- result.providers[curProvider] = {};
55527
- }
55528
- continue;
55529
- }
55530
- const m2 = /^([A-Za-z0-9_.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(line);
55531
- if (!m2) continue;
55532
- const key = m2[1];
55533
- const val = m2[2] !== void 0 ? m2[2] : m2[3];
55534
- if (table === "") {
55535
- if (key === "model_provider") result.modelProvider = val;
55536
- else if (key === "openai_base_url") result.openaiBaseUrl = val;
55537
- } else if (curProvider && key === "base_url") {
55538
- result.providers[curProvider].baseUrl = val;
55539
- }
55540
- }
55541
- return result;
55542
- }
55543
- function readCodexConfig(codexHome) {
55544
- const cfgPath = path7.join(codexHome, "config.toml");
55545
- let text;
55546
- try {
55547
- text = fs5.readFileSync(cfgPath, "utf8");
55548
- } catch {
55549
- return { providers: {} };
55550
- }
55551
- return parseCodexToml(text);
55552
- }
55553
- function readPiConfig(piHome) {
55554
- const cfgPath = path7.join(piHome, "models.json");
55555
- const obj = readJsonObject(cfgPath);
55556
- const providers = {};
55557
- const rawProviders = obj?.providers;
55558
- if (rawProviders && typeof rawProviders === "object" && !Array.isArray(rawProviders)) {
55559
- for (const [name, val] of Object.entries(rawProviders)) {
55560
- if (val && typeof val === "object" && !Array.isArray(val)) {
55561
- const baseUrl = val.baseUrl;
55562
- providers[name] = typeof baseUrl === "string" ? { baseUrl } : {};
55563
- }
55564
- }
55565
- }
55566
- return { providers };
55567
- }
55568
- function loadClientConfig(env, cwd) {
55569
- const home = os2.homedir();
55570
- const config = {};
55571
- config.claude = readClaudeSettings(home, cwd);
55572
- const codexHome = nonEmpty2(env.CODEX_HOME) ? env.CODEX_HOME : path7.join(home, ".codex");
55573
- config.codex = readCodexConfig(codexHome);
55574
- config.pi = readPiConfig(resolvePiHome(env));
55575
- return config;
55576
- }
55577
55758
  function parsePort(raw) {
55578
55759
  const port = raw && raw.trim() ? parseInt(raw, 10) : LAUNCHER_DEFAULT_PORT;
55579
55760
  if (!Number.isFinite(port) || port <= 0 || port > 65535) {
@@ -55626,7 +55807,7 @@ async function runLaunch(params, deps = {}) {
55626
55807
  if (!handle2.reused) stopProxy(handle2);
55627
55808
  if (piTmpHome) {
55628
55809
  try {
55629
- fs5.rmSync(piTmpHome, { recursive: true, force: true });
55810
+ fs7.rmSync(piTmpHome, { recursive: true, force: true });
55630
55811
  } catch {
55631
55812
  }
55632
55813
  }
@@ -55652,8 +55833,8 @@ async function runTestPi(params, deps = {}) {
55652
55833
  }
55653
55834
  const ca = resolveCaCertPath(process.env);
55654
55835
  const env = buildPiEnv(handle2.origin, ca, process.env);
55655
- const sessionDir = path7.join(os2.tmpdir(), `bili-pi-test-${Date.now()}`);
55656
- fs5.mkdirSync(sessionDir, { recursive: true });
55836
+ const sessionDir = path9.join(os4.tmpdir(), `bili-pi-test-${Date.now()}`);
55837
+ fs7.mkdirSync(sessionDir, { recursive: true });
55657
55838
  const args = [
55658
55839
  "-p",
55659
55840
  "--no-session",
@@ -55682,11 +55863,11 @@ async function runTestPi(params, deps = {}) {
55682
55863
  // src/cli.ts
55683
55864
  import { readFileSync as readFileSync5 } from "fs";
55684
55865
  import { fileURLToPath as fileURLToPath3 } from "url";
55685
- import path8 from "path";
55866
+ import path10 from "path";
55686
55867
  var VERSION = (() => {
55687
55868
  try {
55688
55869
  const here = fileURLToPath3(import.meta.url);
55689
- const pkg = path8.join(path8.dirname(here), "..", "package.json");
55870
+ const pkg = path10.join(path10.dirname(here), "..", "package.json");
55690
55871
  return JSON.parse(readFileSync5(pkg, "utf8")).version ?? "dev";
55691
55872
  } catch {
55692
55873
  return "dev";
@@ -55695,7 +55876,7 @@ var VERSION = (() => {
55695
55876
  var PACKAGE_NAME = (() => {
55696
55877
  try {
55697
55878
  const here = fileURLToPath3(import.meta.url);
55698
- const pkg = path8.join(path8.dirname(here), "..", "package.json");
55879
+ const pkg = path10.join(path10.dirname(here), "..", "package.json");
55699
55880
  return JSON.parse(readFileSync5(pkg, "utf8")).name ?? "billion-context";
55700
55881
  } catch {
55701
55882
  return "billion-context";