@ysgao/web-cli 0.2.0 → 0.3.0

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
@@ -1364,8 +1364,8 @@ var require_command = __commonJS({
1364
1364
  "node_modules/commander/lib/command.js"(exports2) {
1365
1365
  var EventEmitter2 = require("node:events").EventEmitter;
1366
1366
  var childProcess = require("node:child_process");
1367
- var path13 = require("node:path");
1368
- var fs15 = require("node:fs");
1367
+ var path14 = require("node:path");
1368
+ var fs16 = require("node:fs");
1369
1369
  var process2 = require("node:process");
1370
1370
  var { Argument: Argument2, humanReadableArgName } = require_argument();
1371
1371
  var { CommanderError: CommanderError2 } = require_error();
@@ -2297,11 +2297,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2297
2297
  let launchWithNode = false;
2298
2298
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2299
2299
  function findFile(baseDir, baseName) {
2300
- const localBin = path13.resolve(baseDir, baseName);
2301
- if (fs15.existsSync(localBin)) return localBin;
2302
- if (sourceExt.includes(path13.extname(baseName))) return void 0;
2300
+ const localBin = path14.resolve(baseDir, baseName);
2301
+ if (fs16.existsSync(localBin)) return localBin;
2302
+ if (sourceExt.includes(path14.extname(baseName))) return void 0;
2303
2303
  const foundExt = sourceExt.find(
2304
- (ext) => fs15.existsSync(`${localBin}${ext}`)
2304
+ (ext) => fs16.existsSync(`${localBin}${ext}`)
2305
2305
  );
2306
2306
  if (foundExt) return `${localBin}${foundExt}`;
2307
2307
  return void 0;
@@ -2313,21 +2313,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
2313
2313
  if (this._scriptPath) {
2314
2314
  let resolvedScriptPath;
2315
2315
  try {
2316
- resolvedScriptPath = fs15.realpathSync(this._scriptPath);
2316
+ resolvedScriptPath = fs16.realpathSync(this._scriptPath);
2317
2317
  } catch (err) {
2318
2318
  resolvedScriptPath = this._scriptPath;
2319
2319
  }
2320
- executableDir = path13.resolve(
2321
- path13.dirname(resolvedScriptPath),
2320
+ executableDir = path14.resolve(
2321
+ path14.dirname(resolvedScriptPath),
2322
2322
  executableDir
2323
2323
  );
2324
2324
  }
2325
2325
  if (executableDir) {
2326
2326
  let localFile = findFile(executableDir, executableFile);
2327
2327
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
2328
- const legacyName = path13.basename(
2328
+ const legacyName = path14.basename(
2329
2329
  this._scriptPath,
2330
- path13.extname(this._scriptPath)
2330
+ path14.extname(this._scriptPath)
2331
2331
  );
2332
2332
  if (legacyName !== this._name) {
2333
2333
  localFile = findFile(
@@ -2338,7 +2338,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2338
2338
  }
2339
2339
  executableFile = localFile || executableFile;
2340
2340
  }
2341
- launchWithNode = sourceExt.includes(path13.extname(executableFile));
2341
+ launchWithNode = sourceExt.includes(path14.extname(executableFile));
2342
2342
  let proc;
2343
2343
  if (process2.platform !== "win32") {
2344
2344
  if (launchWithNode) {
@@ -3178,7 +3178,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
3178
3178
  * @return {Command}
3179
3179
  */
3180
3180
  nameFromFilename(filename) {
3181
- this._name = path13.basename(filename, path13.extname(filename));
3181
+ this._name = path14.basename(filename, path14.extname(filename));
3182
3182
  return this;
3183
3183
  }
3184
3184
  /**
@@ -3192,9 +3192,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
3192
3192
  * @param {string} [path]
3193
3193
  * @return {(string|null|Command)}
3194
3194
  */
3195
- executableDir(path14) {
3196
- if (path14 === void 0) return this._executableDir;
3197
- this._executableDir = path14;
3195
+ executableDir(path15) {
3196
+ if (path15 === void 0) return this._executableDir;
3197
+ this._executableDir = path15;
3198
3198
  return this;
3199
3199
  }
3200
3200
  /**
@@ -12271,11 +12271,11 @@ var require_mime_types = __commonJS({
12271
12271
  }
12272
12272
  return exts[0];
12273
12273
  }
12274
- function lookup(path13) {
12275
- if (!path13 || typeof path13 !== "string") {
12274
+ function lookup(path14) {
12275
+ if (!path14 || typeof path14 !== "string") {
12276
12276
  return false;
12277
12277
  }
12278
- var extension2 = extname("x." + path13).toLowerCase().substr(1);
12278
+ var extension2 = extname("x." + path14).toLowerCase().substr(1);
12279
12279
  if (!extension2) {
12280
12280
  return false;
12281
12281
  }
@@ -13380,11 +13380,11 @@ var require_form_data = __commonJS({
13380
13380
  "use strict";
13381
13381
  var CombinedStream = require_combined_stream();
13382
13382
  var util4 = require("util");
13383
- var path13 = require("path");
13383
+ var path14 = require("path");
13384
13384
  var http4 = require("http");
13385
13385
  var https2 = require("https");
13386
13386
  var parseUrl2 = require("url").parse;
13387
- var fs15 = require("fs");
13387
+ var fs16 = require("fs");
13388
13388
  var Stream = require("stream").Stream;
13389
13389
  var crypto4 = require("crypto");
13390
13390
  var mime = require_mime_types();
@@ -13454,7 +13454,7 @@ var require_form_data = __commonJS({
13454
13454
  if (value.end != void 0 && value.end != Infinity && value.start != void 0) {
13455
13455
  callback(null, value.end + 1 - (value.start ? value.start : 0));
13456
13456
  } else {
13457
- fs15.stat(value.path, function(err, stat) {
13457
+ fs16.stat(value.path, function(err, stat) {
13458
13458
  if (err) {
13459
13459
  callback(err);
13460
13460
  return;
@@ -13511,11 +13511,11 @@ var require_form_data = __commonJS({
13511
13511
  FormData3.prototype._getContentDisposition = function(value, options) {
13512
13512
  var filename;
13513
13513
  if (typeof options.filepath === "string") {
13514
- filename = path13.normalize(options.filepath).replace(/\\/g, "/");
13514
+ filename = path14.normalize(options.filepath).replace(/\\/g, "/");
13515
13515
  } else if (options.filename || value && (value.name || value.path)) {
13516
- filename = path13.basename(options.filename || value && (value.name || value.path));
13516
+ filename = path14.basename(options.filename || value && (value.name || value.path));
13517
13517
  } else if (value && value.readable && hasOwn(value, "httpVersion")) {
13518
- filename = path13.basename(value.client._httpMessage.path || "");
13518
+ filename = path14.basename(value.client._httpMessage.path || "");
13519
13519
  }
13520
13520
  if (filename) {
13521
13521
  return 'filename="' + escapeHeaderParam(filename) + '"';
@@ -43574,14 +43574,14 @@ var require_devtools = __commonJS({
43574
43574
  var https2 = require("https");
43575
43575
  var defaults2 = require_defaults();
43576
43576
  var externalRequest = require_external_request();
43577
- function devToolsInterface(path13, options, callback) {
43577
+ function devToolsInterface(path14, options, callback) {
43578
43578
  const transport = options.secure ? https2 : http4;
43579
43579
  const requestOptions = {
43580
43580
  method: options.method,
43581
43581
  host: options.host || defaults2.HOST,
43582
43582
  port: options.port || defaults2.PORT,
43583
43583
  useHostName: options.useHostName,
43584
- path: options.alterPath ? options.alterPath(path13) : path13
43584
+ path: options.alterPath ? options.alterPath(path14) : path14
43585
43585
  };
43586
43586
  externalRequest(transport, requestOptions, callback);
43587
43587
  }
@@ -43632,12 +43632,12 @@ var require_devtools = __commonJS({
43632
43632
  });
43633
43633
  }
43634
43634
  function New(options, callback) {
43635
- let path13 = "/json/new";
43635
+ let path14 = "/json/new";
43636
43636
  if (Object.prototype.hasOwnProperty.call(options, "url")) {
43637
- path13 += `?${options.url}`;
43637
+ path14 += `?${options.url}`;
43638
43638
  }
43639
43639
  options.method = options.method || "PUT";
43640
- devToolsInterface(path13, options, (err, tab) => {
43640
+ devToolsInterface(path14, options, (err, tab) => {
43641
43641
  if (err) {
43642
43642
  callback(err);
43643
43643
  } else {
@@ -43812,7 +43812,7 @@ var require_chrome = __commonJS({
43812
43812
  this.port = options.port || defaults2.PORT;
43813
43813
  this.secure = !!options.secure;
43814
43814
  this.useHostName = !!options.useHostName;
43815
- this.alterPath = options.alterPath || ((path13) => path13);
43815
+ this.alterPath = options.alterPath || ((path14) => path14);
43816
43816
  this.protocol = options.protocol;
43817
43817
  this.local = !!options.local;
43818
43818
  this.target = options.target || defaultTarget;
@@ -44072,7 +44072,7 @@ __export(index_exports, {
44072
44072
  program: () => program2
44073
44073
  });
44074
44074
  module.exports = __toCommonJS(index_exports);
44075
- var path12 = __toESM(require("path"));
44075
+ var path13 = __toESM(require("path"));
44076
44076
  var dotenv = __toESM(require_dist());
44077
44077
 
44078
44078
  // src/core/paths.ts
@@ -45198,9 +45198,9 @@ function isVisitable(thing) {
45198
45198
  function removeBrackets(key) {
45199
45199
  return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key;
45200
45200
  }
45201
- function renderKey(path13, key, dots) {
45202
- if (!path13) return key;
45203
- return path13.concat(key).map(function each(token, i) {
45201
+ function renderKey(path14, key, dots) {
45202
+ if (!path14) return key;
45203
+ return path14.concat(key).map(function each(token, i) {
45204
45204
  token = removeBrackets(token);
45205
45205
  return !dots && i ? "[" + token + "]" : token;
45206
45206
  }).join(dots ? "." : "");
@@ -45286,13 +45286,13 @@ function toFormData(obj, formData, options) {
45286
45286
  return currentValue;
45287
45287
  });
45288
45288
  }
45289
- function defaultVisitor(value, key, path13) {
45289
+ function defaultVisitor(value, key, path14) {
45290
45290
  let arr = value;
45291
45291
  if (utils_default.isReactNative(formData) && utils_default.isReactNativeBlob(value)) {
45292
- formData.append(renderKey(path13, key, dots), convertValue(value));
45292
+ formData.append(renderKey(path14, key, dots), convertValue(value));
45293
45293
  return false;
45294
45294
  }
45295
- if (value && !path13 && typeof value === "object") {
45295
+ if (value && !path14 && typeof value === "object") {
45296
45296
  if (utils_default.endsWith(key, "{}")) {
45297
45297
  key = metaTokens ? key : key.slice(0, -2);
45298
45298
  value = stringifyWithDepthLimit(value, 1);
@@ -45311,7 +45311,7 @@ function toFormData(obj, formData, options) {
45311
45311
  if (isVisitable(value)) {
45312
45312
  return true;
45313
45313
  }
45314
- formData.append(renderKey(path13, key, dots), convertValue(value));
45314
+ formData.append(renderKey(path14, key, dots), convertValue(value));
45315
45315
  return false;
45316
45316
  }
45317
45317
  const exposedHelpers = Object.assign(predicates, {
@@ -45319,17 +45319,17 @@ function toFormData(obj, formData, options) {
45319
45319
  convertValue,
45320
45320
  isVisitable
45321
45321
  });
45322
- function build(value, path13, depth = 0) {
45322
+ function build(value, path14, depth = 0) {
45323
45323
  if (utils_default.isUndefined(value)) return;
45324
45324
  throwIfMaxDepthExceeded(depth);
45325
45325
  if (stack.indexOf(value) !== -1) {
45326
- throw new Error("Circular reference detected in " + path13.join("."));
45326
+ throw new Error("Circular reference detected in " + path14.join("."));
45327
45327
  }
45328
45328
  stack.push(value);
45329
45329
  utils_default.forEach(value, function each(el, key) {
45330
- const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path13, exposedHelpers);
45330
+ const result = !(utils_default.isUndefined(el) || el === null) && visitor.call(formData, el, utils_default.isString(key) ? key.trim() : key, path14, exposedHelpers);
45331
45331
  if (result === true) {
45332
- build(el, path13 ? path13.concat(key) : [key], depth + 1);
45332
+ build(el, path14 ? path14.concat(key) : [key], depth + 1);
45333
45333
  }
45334
45334
  });
45335
45335
  stack.pop();
@@ -45541,7 +45541,7 @@ var platform_default = {
45541
45541
  // node_modules/axios/lib/helpers/toURLEncodedForm.js
45542
45542
  function toURLEncodedForm(data, options) {
45543
45543
  return toFormData_default(data, new platform_default.classes.URLSearchParams(), {
45544
- visitor: function(value, key, path13, helpers) {
45544
+ visitor: function(value, key, path14, helpers) {
45545
45545
  if (platform_default.isNode && utils_default.isBuffer(value)) {
45546
45546
  this.append(key, value.toString("base64"));
45547
45547
  return false;
@@ -45563,14 +45563,14 @@ function throwIfDepthExceeded(index) {
45563
45563
  }
45564
45564
  }
45565
45565
  function parsePropPath(name) {
45566
- const path13 = [];
45566
+ const path14 = [];
45567
45567
  const pattern = /[^.[\]]+|\[([^.[\]]*)]/g;
45568
45568
  let match;
45569
45569
  while ((match = pattern.exec(name)) !== null) {
45570
- throwIfDepthExceeded(path13.length);
45571
- path13.push(match[0] === "[]" ? "" : match[1] || match[0]);
45570
+ throwIfDepthExceeded(path14.length);
45571
+ path14.push(match[0] === "[]" ? "" : match[1] || match[0]);
45572
45572
  }
45573
- return path13;
45573
+ return path14;
45574
45574
  }
45575
45575
  function arrayToObject(arr) {
45576
45576
  const obj = {};
@@ -45585,12 +45585,12 @@ function arrayToObject(arr) {
45585
45585
  return obj;
45586
45586
  }
45587
45587
  function formDataToJSON(formData) {
45588
- function buildPath(path13, value, target, index) {
45588
+ function buildPath(path14, value, target, index) {
45589
45589
  throwIfDepthExceeded(index);
45590
- let name = path13[index++];
45590
+ let name = path14[index++];
45591
45591
  if (name === "__proto__") return true;
45592
45592
  const isNumericKey = Number.isFinite(+name);
45593
- const isLast = index >= path13.length;
45593
+ const isLast = index >= path14.length;
45594
45594
  name = !name && utils_default.isArray(target) ? target.length : name;
45595
45595
  if (isLast) {
45596
45596
  if (utils_default.hasOwnProp(target, name)) {
@@ -45603,7 +45603,7 @@ function formDataToJSON(formData) {
45603
45603
  if (!utils_default.hasOwnProp(target, name) || !utils_default.isObject(target[name])) {
45604
45604
  target[name] = [];
45605
45605
  }
45606
- const result = buildPath(path13, value, target[name], index);
45606
+ const result = buildPath(path14, value, target[name], index);
45607
45607
  if (result && utils_default.isArray(target[name])) {
45608
45608
  target[name] = arrayToObject(target[name]);
45609
45609
  }
@@ -47321,9 +47321,9 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config2) {
47321
47321
  auth2 = urlUsername + ":" + urlPassword;
47322
47322
  }
47323
47323
  auth2 && headers.delete("authorization");
47324
- let path13;
47324
+ let path14;
47325
47325
  try {
47326
- path13 = buildURL(
47326
+ path14 = buildURL(
47327
47327
  parsed.pathname + parsed.search,
47328
47328
  own2("params"),
47329
47329
  own2("paramsSerializer")
@@ -47342,7 +47342,7 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config2) {
47342
47342
  false
47343
47343
  );
47344
47344
  const options = Object.assign(/* @__PURE__ */ Object.create(null), {
47345
- path: path13,
47345
+ path: path14,
47346
47346
  method,
47347
47347
  headers: toByteStringHeaderObject(headers),
47348
47348
  agents: { http: httpAgent, https: httpsAgent },
@@ -47744,14 +47744,14 @@ var isURLSameOrigin_default = platform_default.hasStandardBrowserEnv ? /* @__PUR
47744
47744
  var cookies_default = platform_default.hasStandardBrowserEnv ? (
47745
47745
  // Standard browser envs support document.cookie
47746
47746
  {
47747
- write(name, value, expires, path13, domain, secure, sameSite) {
47747
+ write(name, value, expires, path14, domain, secure, sameSite) {
47748
47748
  if (typeof document === "undefined") return;
47749
47749
  const cookie = [`${name}=${encodeURIComponent(value)}`];
47750
47750
  if (utils_default.isNumber(expires)) {
47751
47751
  cookie.push(`expires=${new Date(expires).toUTCString()}`);
47752
47752
  }
47753
- if (utils_default.isString(path13)) {
47754
- cookie.push(`path=${path13}`);
47753
+ if (utils_default.isString(path14)) {
47754
+ cookie.push(`path=${path14}`);
47755
47755
  }
47756
47756
  if (utils_default.isString(domain)) {
47757
47757
  cookie.push(`domain=${domain}`);
@@ -50058,6 +50058,14 @@ function mergeHeadersCaseInsensitively(base, incoming) {
50058
50058
  }
50059
50059
  return merged;
50060
50060
  }
50061
+ var SELECT_FOCUSED_FIELD_SCRIPT = `(() => {
50062
+ const el = document.activeElement;
50063
+ if (el && typeof el.select === 'function') {
50064
+ el.select();
50065
+ return true;
50066
+ }
50067
+ return false;
50068
+ })()`;
50061
50069
  function withTimeout(promise, timeoutMs, message) {
50062
50070
  return new Promise((resolve4, reject) => {
50063
50071
  const timer = setTimeout(() => reject(new Error(message)), timeoutMs);
@@ -50091,8 +50099,8 @@ async function connectToAnyPageTarget(port, connector = realCdpConnector) {
50091
50099
  return connector.connect({ port, target: target.id });
50092
50100
  }
50093
50101
  }
50094
- async function connectCdpSession(port) {
50095
- const client = await connectToAnyPageTarget(port);
50102
+ async function connectCdpSession(port, connector = realCdpConnector) {
50103
+ const client = await connectToAnyPageTarget(port, connector);
50096
50104
  const { Network, Page, Runtime, Browser, Input } = client;
50097
50105
  await Promise.all([Network.enable(), Page.enable(), Runtime.enable()]);
50098
50106
  const version = await Browser.getVersion();
@@ -50141,6 +50149,12 @@ async function connectCdpSession(port) {
50141
50149
  }).catch(() => {
50142
50150
  });
50143
50151
  });
50152
+ async function selectFocusedFieldContents() {
50153
+ try {
50154
+ await Runtime.evaluate({ expression: SELECT_FOCUSED_FIELD_SCRIPT, returnByValue: true });
50155
+ } catch {
50156
+ }
50157
+ }
50144
50158
  async function typeCharacter(ch) {
50145
50159
  await Input.dispatchKeyEvent({ type: "rawKeyDown", text: ch, unmodifiedText: ch });
50146
50160
  await Input.dispatchKeyEvent({ type: "char", text: ch, unmodifiedText: ch });
@@ -50165,6 +50179,9 @@ async function connectCdpSession(port) {
50165
50179
  await Input.dispatchMouseEvent({ type: "mouseReleased", x, y, button: "left", clickCount: 1 });
50166
50180
  },
50167
50181
  async type(text, opts) {
50182
+ if (opts?.replaceExisting) {
50183
+ await selectFocusedFieldContents();
50184
+ }
50168
50185
  for (const ch of text) {
50169
50186
  await typeCharacter(ch);
50170
50187
  }
@@ -51097,7 +51114,7 @@ async function locateFields(session, timeoutMs) {
51097
51114
  }
51098
51115
  async function fillField(session, point, text, pressEnter) {
51099
51116
  await session.click(point.x, point.y);
51100
- await session.type(text, { pressEnter });
51117
+ await session.type(text, { pressEnter, replaceExisting: true });
51101
51118
  }
51102
51119
  async function attemptAutoFillLogin(session, credentials, opts = {}) {
51103
51120
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -51415,10 +51432,11 @@ function mergeStoredSession(profileJar, storedJar) {
51415
51432
  var DEFAULT_LOGIN_TIMEOUT_MS = 24e4;
51416
51433
  var DEFAULT_POLL_INTERVAL_MS = 3e3;
51417
51434
  var SILENT_REFRESH_TIMEOUT_MS = 25e3;
51435
+ var SILENT_REFRESH_NO_CREDENTIAL_TIMEOUT_MS = 8e3;
51418
51436
  var SILENT_REFRESH_POLL_INTERVAL_MS = 2e3;
51419
- async function attemptAutoFill(site, session, deps) {
51437
+ async function attemptAutoFill(site, session, deps, preloaded) {
51420
51438
  try {
51421
- const credentials = await (deps.loadCredentials ?? loadCredentials)(site);
51439
+ const credentials = preloaded === void 0 ? await loadSavedCredentials(site, deps) : preloaded;
51422
51440
  if (!credentials) {
51423
51441
  return false;
51424
51442
  }
@@ -51427,6 +51445,13 @@ async function attemptAutoFill(site, session, deps) {
51427
51445
  return false;
51428
51446
  }
51429
51447
  }
51448
+ async function loadSavedCredentials(site, deps) {
51449
+ try {
51450
+ return await (deps.loadCredentials ?? loadCredentials)(site) ?? null;
51451
+ } catch {
51452
+ return null;
51453
+ }
51454
+ }
51430
51455
  var inFlightLogins = /* @__PURE__ */ new Map();
51431
51456
  var completedLogins = /* @__PURE__ */ new Set();
51432
51457
  function loginKey(site, intent) {
@@ -51462,7 +51487,6 @@ async function attemptSilentRefresh(opts, deps) {
51462
51487
  const connect = deps.connect ?? connectCdpSession;
51463
51488
  const now = deps.now ?? (() => Date.now());
51464
51489
  const sleep = deps.sleep ?? defaultSleep;
51465
- const silentTimeoutMs = deps.silentRefreshTimeoutMs ?? SILENT_REFRESH_TIMEOUT_MS;
51466
51490
  try {
51467
51491
  return await withChrome({ headless: true }, async (chrome) => {
51468
51492
  const session = await connect(chrome.port);
@@ -51471,7 +51495,9 @@ async function attemptSilentRefresh(opts, deps) {
51471
51495
  await session.navigate(opts.loginUrl);
51472
51496
  } catch {
51473
51497
  }
51474
- await attemptAutoFill(opts.site, session, deps);
51498
+ const credentials = await loadSavedCredentials(opts.site, deps);
51499
+ await attemptAutoFill(opts.site, session, deps, credentials);
51500
+ const silentTimeoutMs = deps.silentRefreshTimeoutMs ?? (credentials ? SILENT_REFRESH_TIMEOUT_MS : SILENT_REFRESH_NO_CREDENTIAL_TIMEOUT_MS);
51475
51501
  const deadline = now() + silentTimeoutMs;
51476
51502
  for (; ; ) {
51477
51503
  const jar = await getLoginPageCookies(session, opts.loginUrl);
@@ -51601,17 +51627,74 @@ function getSiteConfig(site) {
51601
51627
  return config2;
51602
51628
  }
51603
51629
 
51630
+ // src/core/callOptions.ts
51631
+ function isAbortError(err) {
51632
+ if (typeof err !== "object" || err === null) {
51633
+ return false;
51634
+ }
51635
+ const e = err;
51636
+ return e.code === "ERR_CANCELED" || e.name === "CanceledError" || e.name === "AbortError";
51637
+ }
51638
+ var SEARCH_CALL_OPTIONS = {
51639
+ timeoutMs: 8e3,
51640
+ retryOnTransportError: { timeoutMs: 15e3 }
51641
+ };
51642
+
51604
51643
  // src/core/replayEngine.ts
51605
51644
  var HTTP_REPLAY_TIMEOUT_MS = 3e4;
51606
- async function callTemplate(rendered, cookieHeader) {
51607
- const response = await axios_default.request({
51645
+ var TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
51646
+ "ECONNABORTED",
51647
+ // axios's own timeout
51648
+ "ETIMEDOUT",
51649
+ "ECONNRESET",
51650
+ "EPIPE",
51651
+ "EAI_AGAIN",
51652
+ "ENETUNREACH",
51653
+ "ERR_NETWORK"
51654
+ ]);
51655
+ function isTransportError(err) {
51656
+ if (typeof err !== "object" || err === null) {
51657
+ return false;
51658
+ }
51659
+ const e = err;
51660
+ if (e.response !== void 0) {
51661
+ return false;
51662
+ }
51663
+ if (typeof e.code === "string" && TRANSPORT_ERROR_CODES.has(e.code)) {
51664
+ return true;
51665
+ }
51666
+ return typeof e.message === "string" && /timeout of \d+ms exceeded|socket hang up/i.test(e.message);
51667
+ }
51668
+ function hostOf(url2) {
51669
+ try {
51670
+ return new URL(url2).host;
51671
+ } catch {
51672
+ return url2;
51673
+ }
51674
+ }
51675
+ async function callTemplate(rendered, cookieHeader, options = {}) {
51676
+ const send = (timeout) => axios_default.request({
51608
51677
  method: rendered.method,
51609
51678
  url: rendered.url,
51610
51679
  headers: { ...rendered.headers, Cookie: cookieHeader },
51611
51680
  data: rendered.body,
51612
51681
  validateStatus: () => true,
51613
- timeout: HTTP_REPLAY_TIMEOUT_MS
51682
+ timeout,
51683
+ signal: options.signal
51614
51684
  });
51685
+ let response;
51686
+ try {
51687
+ response = await send(options.timeoutMs ?? HTTP_REPLAY_TIMEOUT_MS);
51688
+ } catch (err) {
51689
+ if (!options.retryOnTransportError || !isTransportError(err) || rendered.method.toUpperCase() !== "GET") {
51690
+ throw err;
51691
+ }
51692
+ process.stderr.write(
51693
+ `web-cli: request to ${hostOf(rendered.url)} failed (${err instanceof Error ? err.message : String(err)}) \u2014 retrying once.
51694
+ `
51695
+ );
51696
+ response = await send(options.retryOnTransportError.timeoutMs);
51697
+ }
51615
51698
  if (response.status < 200 || response.status >= 300) {
51616
51699
  const body = typeof response.data === "string" ? response.data : JSON.stringify(response.data);
51617
51700
  throw new ReplayHttpError(`Replay got HTTP ${response.status}`, response.status, body);
@@ -51651,7 +51734,7 @@ async function replay(site, intent, param, opts = {}) {
51651
51734
  const siteSupportsLogin = config2.requiresLogin !== false;
51652
51735
  const loginRecoveryDisabled = opts.disableLoginRecovery === true;
51653
51736
  try {
51654
- return await attemptReplay(site, intent, param);
51737
+ return await attemptReplay(site, intent, param, void 0, opts.signal);
51655
51738
  } catch (err) {
51656
51739
  if (!isAuthFailure(err)) {
51657
51740
  throw err;
@@ -51676,7 +51759,7 @@ async function replay(site, intent, param, opts = {}) {
51676
51759
  isSessionReady: (jar) => isSessionUsable(site, intent, param, jar),
51677
51760
  allowVisible: opts.allowVisibleLogin === true
51678
51761
  });
51679
- return await attemptReplay(site, intent, param, freshJar);
51762
+ return await attemptReplay(site, intent, param, freshJar, opts.signal);
51680
51763
  }
51681
51764
  }
51682
51765
  async function isSessionUsable(site, intent, param, jar) {
@@ -51702,7 +51785,11 @@ function assertNotPaywalled(site, intent, data, baseUrl) {
51702
51785
  );
51703
51786
  }
51704
51787
  }
51705
- async function attemptReplay(site, intent, param, jarOverride) {
51788
+ function callOptionsFor(intent, signal) {
51789
+ const base = intent === "search" ? SEARCH_CALL_OPTIONS : {};
51790
+ return signal ? { ...base, signal } : base;
51791
+ }
51792
+ async function attemptReplay(site, intent, param, jarOverride, signal) {
51706
51793
  const config2 = getSiteConfig(site);
51707
51794
  const cookieJar = jarOverride ?? getEstablishedSession(site) ?? mergeStoredSession(await getLiveCookieJar(config2.host), await loadSessionJar(site));
51708
51795
  if (Object.keys(cookieJar).length === 0) {
@@ -51716,10 +51803,13 @@ async function attemptReplay(site, intent, param, jarOverride) {
51716
51803
  const existing = readTemplate(site, intent);
51717
51804
  if (existing) {
51718
51805
  try {
51719
- const data = await callTemplate(renderTemplate(existing, needle), cookieHeader);
51806
+ const data = await callTemplate(renderTemplate(existing, needle), cookieHeader, callOptionsFor(intent, signal));
51720
51807
  assertNotPaywalled(site, intent, data, config2.baseUrl);
51721
51808
  return { data, discovered: false };
51722
51809
  } catch (err) {
51810
+ if (isAbortError(err)) {
51811
+ throw err;
51812
+ }
51723
51813
  if (isAuthFailure(err)) {
51724
51814
  throw err;
51725
51815
  }
@@ -51728,12 +51818,12 @@ async function attemptReplay(site, intent, param, jarOverride) {
51728
51818
  const preseed = getPreseedTemplate(site, intent);
51729
51819
  if (preseed) {
51730
51820
  try {
51731
- const data = await callTemplate(renderTemplate(preseed, needle), cookieHeader);
51821
+ const data = await callTemplate(renderTemplate(preseed, needle), cookieHeader, callOptionsFor(intent, signal));
51732
51822
  assertNotPaywalled(site, intent, data, config2.baseUrl);
51733
51823
  persistTemplateBestEffort(site, intent, preseed);
51734
51824
  return { data, discovered: false };
51735
51825
  } catch (err) {
51736
- if (isAuthFailure(err)) {
51826
+ if (isAuthFailure(err) || isAbortError(err)) {
51737
51827
  throw err;
51738
51828
  }
51739
51829
  }
@@ -51781,6 +51871,107 @@ async function attemptReplay(site, intent, param, jarOverride) {
51781
51871
  }
51782
51872
  }
51783
51873
 
51874
+ // src/commands/fullTextBudget.ts
51875
+ var DEFAULT_FULLTEXT_BUDGET_MS = 5e3;
51876
+ var FullTextBudget = class {
51877
+ constructor(budgetMs, timers = {
51878
+ set: (fn, ms) => setTimeout(fn, ms),
51879
+ clear: (handle) => clearTimeout(handle)
51880
+ }) {
51881
+ this.budgetMs = budgetMs;
51882
+ this.timers = timers;
51883
+ this.signal = this.controller.signal;
51884
+ this.limited = Number.isFinite(budgetMs) && budgetMs > 0;
51885
+ if (this.limited) {
51886
+ this.timer = timers.set(() => {
51887
+ this.expired = true;
51888
+ this.abortIfAnyFetched();
51889
+ }, budgetMs);
51890
+ }
51891
+ }
51892
+ budgetMs;
51893
+ signal;
51894
+ /** Whether this budget can ever abort anything (false for the unlimited form). */
51895
+ limited;
51896
+ controller = new AbortController();
51897
+ timer;
51898
+ expired = false;
51899
+ fetched = 0;
51900
+ timers;
51901
+ /** Report that a full text arrived. If the budget has already run out while nothing had arrived
51902
+ * yet, this is the moment the remaining fetches are cut. */
51903
+ noteFetched() {
51904
+ this.fetched += 1;
51905
+ this.abortIfAnyFetched();
51906
+ }
51907
+ /** Whether the budget has aborted the remaining fetches. */
51908
+ get aborted() {
51909
+ return this.signal.aborted;
51910
+ }
51911
+ /** Stops the timer. Always call when the site's expansions are done, so a finished search never
51912
+ * leaves a live timer behind. */
51913
+ dispose() {
51914
+ if (this.timer !== void 0) {
51915
+ this.timers.clear(this.timer);
51916
+ this.timer = void 0;
51917
+ }
51918
+ }
51919
+ abortIfAnyFetched() {
51920
+ if (this.expired && this.fetched > 0 && !this.controller.signal.aborted) {
51921
+ this.controller.abort();
51922
+ }
51923
+ }
51924
+ };
51925
+
51926
+ // src/parsers/truncateArticle.ts
51927
+ var DEFAULT_MAX_ARTICLE_CHARS = 6e4;
51928
+ function shellQuote3(value) {
51929
+ return `'${value.replace(/'/g, `'\\''`)}'`;
51930
+ }
51931
+ function fetchFullTextCommand(site, url2) {
51932
+ return `web-cli get ${site} ${shellQuote3(url2)}`;
51933
+ }
51934
+ function cutAtBoundary(text, max) {
51935
+ const head = text.slice(0, max);
51936
+ const floor = Math.floor(max * 0.8);
51937
+ const paragraph = head.lastIndexOf("\n\n");
51938
+ if (paragraph >= floor) {
51939
+ return head.slice(0, paragraph).trimEnd();
51940
+ }
51941
+ const sentence = Math.max(head.lastIndexOf(". "), head.lastIndexOf(".\n"));
51942
+ if (sentence >= floor) {
51943
+ return head.slice(0, sentence + 1).trimEnd();
51944
+ }
51945
+ return head.trimEnd();
51946
+ }
51947
+ function truncateArticle(article, maxChars, site, url2) {
51948
+ if (!Number.isFinite(maxChars) || maxChars <= 0 || article.text.length <= maxChars) {
51949
+ return { article };
51950
+ }
51951
+ const totalChars = article.text.length;
51952
+ const kept = cutAtBoundary(article.text, maxChars);
51953
+ const command = fetchFullTextCommand(site, url2);
51954
+ const message = `Only the first ${kept.length.toLocaleString("en-US")} of ${totalChars.toLocaleString("en-US")} characters of this article's text are included here (its full outline is kept in "article.outline"). The complete text can be fetched on demand with the command below.`;
51955
+ const { html: _html, references: _references, ...rest } = article;
51956
+ return {
51957
+ article: {
51958
+ ...rest,
51959
+ text: `${kept}
51960
+
51961
+ [\u2026 truncated: showing the first ${kept.length} of ${totalChars} characters. Fetch the complete text on demand: ${command}]`
51962
+ },
51963
+ moreAvailable: { reason: "truncated", message, command, shownChars: kept.length, totalChars }
51964
+ };
51965
+ }
51966
+ function deferredFullText(site, url2, budgetMs) {
51967
+ const seconds = Math.round(budgetMs / 100) / 10;
51968
+ return {
51969
+ reason: "deferred",
51970
+ message: `Full text was NOT fetched in this search: this article was still being prepared by the site after the ${seconds}s full-text time budget (very large articles, such as book chapters, can take 10s or more), and waiting would have held up everything else. Its title, url and snippet are still valid. The full text can be fetched on demand with the command below.`,
51971
+ command: fetchFullTextCommand(site, url2)
51972
+ };
51973
+ }
51974
+
51784
51975
  // src/output/searchMarkdown.ts
51785
51976
  var fs10 = __toESM(require("fs"));
51786
51977
  var path9 = __toESM(require("path"));
@@ -51873,6 +52064,25 @@ function renderSearchMarkdown(doc, now = /* @__PURE__ */ new Date()) {
51873
52064
  "_Full text was retrieved (kept out of this report to stay readable \u2014 see the search command\u2019s JSON result)._",
51874
52065
  ""
51875
52066
  );
52067
+ if (ref.moreAvailable?.reason === "truncated") {
52068
+ lines.push(
52069
+ `_The text in the JSON result is cut to ${ref.moreAvailable.shownChars ?? "?"} of ${ref.moreAvailable.totalChars ?? "?"} characters (its outline is complete). Fetch the full text on demand:_`,
52070
+ "",
52071
+ "```bash",
52072
+ ref.moreAvailable.command,
52073
+ "```",
52074
+ ""
52075
+ );
52076
+ }
52077
+ } else if (ref.moreAvailable?.reason === "deferred") {
52078
+ lines.push(
52079
+ "_Full text was deferred (the site was still preparing this article when the full-text time budget ran out) \u2014 not a failure. Fetch it on demand:_",
52080
+ "",
52081
+ "```bash",
52082
+ ref.moreAvailable.command,
52083
+ "```",
52084
+ ""
52085
+ );
51876
52086
  } else if (ref.fetchError) {
51877
52087
  lines.push(
51878
52088
  `_Full text unavailable (\`${ref.fetchError.code}\`: ${inline(ref.fetchError.error)})._`,
@@ -52013,6 +52223,63 @@ function isExistingDirectory2(candidate) {
52013
52223
 
52014
52224
  // src/auth/sessionPreflight.ts
52015
52225
  init_endpointLearner();
52226
+
52227
+ // src/auth/validationStamp.ts
52228
+ var import_crypto2 = require("crypto");
52229
+ var fs12 = __toESM(require("fs"));
52230
+ var path11 = __toESM(require("path"));
52231
+ var RECENT_VALIDATION_TTL_MS = 6e4;
52232
+ function defaultValidationDir() {
52233
+ return process.env.WEB_CLI_VALIDATION_DIR || path11.join(WEB_CLI_HOME, "session-validated");
52234
+ }
52235
+ function defaultWorkspaceValidationDir() {
52236
+ return process.env.WEB_CLI_WORKSPACE_VALIDATION_DIR || path11.join(process.cwd(), ".web-cli", "session-validated");
52237
+ }
52238
+ function fingerprintJar(jar) {
52239
+ const canonical = Object.keys(jar).sort().map((name) => `${name}=${jar[name]}`).join("\n");
52240
+ return (0, import_crypto2.createHash)("sha256").update(canonical).digest("hex").slice(0, 32);
52241
+ }
52242
+ function stampFile(dir, site) {
52243
+ return path11.join(dir, `${site.replace(/[^a-zA-Z0-9._-]/g, "_")}.json`);
52244
+ }
52245
+ function readStamp(dir, site) {
52246
+ try {
52247
+ const parsed = JSON.parse(fs12.readFileSync(stampFile(dir, site), "utf8"));
52248
+ if (typeof parsed.validatedAt === "number" && typeof parsed.fingerprint === "string") {
52249
+ return { validatedAt: parsed.validatedAt, fingerprint: parsed.fingerprint };
52250
+ }
52251
+ } catch {
52252
+ }
52253
+ return void 0;
52254
+ }
52255
+ function markSessionValidated(site, jar, deps = {}) {
52256
+ const payload = JSON.stringify({
52257
+ validatedAt: (deps.now ?? Date.now)(),
52258
+ fingerprint: fingerprintJar(jar)
52259
+ });
52260
+ for (const dir of [deps.dir ?? defaultValidationDir(), deps.workspaceDir ?? defaultWorkspaceValidationDir()]) {
52261
+ try {
52262
+ fs12.mkdirSync(dir, { recursive: true, mode: 448 });
52263
+ fs12.writeFileSync(stampFile(dir, site), payload, { mode: 384 });
52264
+ return;
52265
+ } catch {
52266
+ }
52267
+ }
52268
+ }
52269
+ function wasRecentlyValidated(site, jar, deps = {}) {
52270
+ const now = (deps.now ?? Date.now)();
52271
+ const ttlMs = deps.ttlMs ?? RECENT_VALIDATION_TTL_MS;
52272
+ const fingerprint = fingerprintJar(jar);
52273
+ const stamps = [deps.dir ?? defaultValidationDir(), deps.workspaceDir ?? defaultWorkspaceValidationDir()].map((dir) => readStamp(dir, site)).filter((s) => s !== void 0);
52274
+ const newest = stamps.sort((a, b) => b.validatedAt - a.validatedAt)[0];
52275
+ if (!newest || newest.fingerprint !== fingerprint) {
52276
+ return false;
52277
+ }
52278
+ const age = now - newest.validatedAt;
52279
+ return age >= 0 && age <= ttlMs;
52280
+ }
52281
+
52282
+ // src/auth/sessionPreflight.ts
52016
52283
  function templateFor(site, intent = "search") {
52017
52284
  return readTemplate(site, intent) ?? getPreseedTemplate(site, intent);
52018
52285
  }
@@ -52030,30 +52297,34 @@ async function probeWithJar(site, probeQuery, jar) {
52030
52297
  const header = cookieJarToHeader(jar);
52031
52298
  const searchTemplate = templateFor(site, "search");
52032
52299
  if (!searchTemplate) {
52033
- return "unknown";
52300
+ return { state: "unknown" };
52034
52301
  }
52035
52302
  let searchData;
52036
52303
  try {
52037
- searchData = await callTemplate(renderTemplate(searchTemplate, probeQuery), header);
52304
+ searchData = await callTemplate(renderTemplate(searchTemplate, probeQuery), header, SEARCH_CALL_OPTIONS);
52038
52305
  } catch (err) {
52039
- return isAuthFailure(err) ? "expired" : "unknown";
52306
+ return { state: isAuthFailure(err) ? "expired" : "unknown" };
52040
52307
  }
52308
+ const reusable = readTemplate(site, "search") ? { searchData } : {};
52041
52309
  const articleTemplate = templateFor(site, "getArticle");
52042
52310
  if (!articleTemplate) {
52043
- return "valid";
52311
+ return { state: "valid", ...reusable };
52312
+ }
52313
+ if (wasRecentlyValidated(site, jar)) {
52314
+ return { state: "valid", ...reusable };
52044
52315
  }
52045
52316
  let key = articleKeyFrom(site, searchData, config2.baseUrl);
52046
52317
  if (!key && probeQuery !== PROBE_CANARY_QUERY) {
52047
52318
  let canaryData;
52048
52319
  try {
52049
- canaryData = await callTemplate(renderTemplate(searchTemplate, PROBE_CANARY_QUERY), header);
52320
+ canaryData = await callTemplate(renderTemplate(searchTemplate, PROBE_CANARY_QUERY), header, SEARCH_CALL_OPTIONS);
52050
52321
  } catch (err) {
52051
- return isAuthFailure(err) ? "expired" : "valid";
52322
+ return isAuthFailure(err) ? { state: "expired" } : { state: "valid", ...reusable };
52052
52323
  }
52053
52324
  key = articleKeyFrom(site, canaryData, config2.baseUrl);
52054
52325
  }
52055
52326
  if (!key) {
52056
- return "valid";
52327
+ return { state: "valid", ...reusable };
52057
52328
  }
52058
52329
  try {
52059
52330
  const articleData = await callTemplate(
@@ -52061,40 +52332,32 @@ async function probeWithJar(site, probeQuery, jar) {
52061
52332
  header
52062
52333
  );
52063
52334
  if (looksPaywalled(site, articleData, config2.baseUrl)) {
52064
- return "expired";
52335
+ return { state: "expired" };
52065
52336
  }
52066
- return "valid";
52337
+ markSessionValidated(site, jar);
52338
+ const reusableArticle = readTemplate(site, "getArticle") ? { article: { key, data: articleData } } : {};
52339
+ return { state: "valid", ...reusable, ...reusableArticle };
52067
52340
  } catch (err) {
52068
- return isAuthFailure(err) ? "expired" : "valid";
52341
+ return isAuthFailure(err) ? { state: "expired" } : { state: "valid", ...reusable };
52069
52342
  }
52070
52343
  }
52071
- async function checkSessionState(site, probeQuery) {
52344
+ async function probeSession(site, probeQuery) {
52072
52345
  const config2 = getSiteConfig(site);
52073
52346
  const jar = getEstablishedSession(site) ?? mergeStoredSession(await getLiveCookieJar(config2.host), await loadSessionJar(site));
52074
52347
  if (Object.keys(jar).length === 0) {
52075
- return "expired";
52348
+ return { state: "expired" };
52076
52349
  }
52077
52350
  return probeWithJar(site, probeQuery, jar);
52078
52351
  }
52079
- async function ensureSessionsForSites(sites2, probeQuery, opts = {}) {
52080
- const checkState = opts.checkState ?? checkSessionState;
52352
+ function asProbeResult(value) {
52353
+ return typeof value === "string" ? { state: value } : value;
52354
+ }
52355
+ function startSessionPreflight(sites2, probeQuery, opts = {}) {
52356
+ const checkState = opts.checkState ?? probeSession;
52081
52357
  const login = opts.login ?? ensureInteractiveLogin;
52082
52358
  const candidates = sites2.filter((site) => getSiteConfig(site).requiresLogin !== false);
52083
- const states = await Promise.all(
52084
- candidates.map(async (site) => {
52085
- try {
52086
- return { site, state: await checkState(site, probeQuery) };
52087
- } catch {
52088
- return { site, state: "unknown" };
52089
- }
52090
- })
52091
- );
52092
- const outcomes = [];
52093
- for (const { site, state } of states) {
52094
- if (state !== "expired") {
52095
- outcomes.push({ site, state, loggedIn: false });
52096
- continue;
52097
- }
52359
+ let loginChain = Promise.resolve();
52360
+ const signIn = async (site, state) => {
52098
52361
  try {
52099
52362
  await login({
52100
52363
  site,
@@ -52106,20 +52369,41 @@ async function ensureSessionsForSites(sites2, probeQuery, opts = {}) {
52106
52369
  // The same probe as the up-front check, which is what makes this window stay open until
52107
52370
  // the user is genuinely signed in rather than closing the moment the site hands out an
52108
52371
  // anonymous session.
52109
- isSessionReady: async (jar) => await probeWithJar(site, probeQuery, jar) !== "expired",
52372
+ isSessionReady: async (jar) => (await probeWithJar(site, probeQuery, jar)).state !== "expired",
52110
52373
  allowVisible: opts.allowVisible === true
52111
52374
  });
52112
- outcomes.push({ site, state, loggedIn: true });
52375
+ return { site, state, loggedIn: true };
52113
52376
  } catch (err) {
52114
- outcomes.push({
52115
- site,
52116
- state,
52117
- loggedIn: false,
52118
- error: err instanceof Error ? err.message : String(err)
52119
- });
52377
+ return { site, state, loggedIn: false, error: err instanceof Error ? err.message : String(err) };
52120
52378
  }
52379
+ };
52380
+ const result = /* @__PURE__ */ new Map();
52381
+ for (const site of candidates) {
52382
+ result.set(
52383
+ site,
52384
+ (async () => {
52385
+ let probe;
52386
+ try {
52387
+ probe = asProbeResult(await checkState(site, probeQuery));
52388
+ } catch {
52389
+ probe = { state: "unknown" };
52390
+ }
52391
+ if (probe.state !== "expired") {
52392
+ return {
52393
+ site,
52394
+ state: probe.state,
52395
+ loggedIn: false,
52396
+ ...probe.searchData !== void 0 ? { searchData: probe.searchData } : {},
52397
+ ...probe.article !== void 0 ? { article: probe.article } : {}
52398
+ };
52399
+ }
52400
+ const attempt = loginChain.then(() => signIn(site, probe.state));
52401
+ loginChain = attempt;
52402
+ return attempt;
52403
+ })()
52404
+ );
52121
52405
  }
52122
- return outcomes;
52406
+ return result;
52123
52407
  }
52124
52408
 
52125
52409
  // src/commands/search.ts
@@ -52174,6 +52458,12 @@ function buildAgentTask(query, keyReferences, sites2) {
52174
52458
  }
52175
52459
  const failureNote = unrecoveredFailures.length > 0 ? ` IMPORTANT: "unrecoveredFailures" lists ${pluralize(unrecoveredFailures.length, "source")} that did NOT come back (web-cli's own default recovery already ran for these and did not succeed) \u2014 you must state plainly, in your answer, which source(s) failed and why, and follow each entry's own "recommendedAction". Never silently substitute another site's results or any previously-cached/saved data in their place, and never present the answer as if coverage were complete when it wasn't.` : "";
52176
52460
  const withFullText = keyReferences.filter((ref) => !!ref.article?.text);
52461
+ const deferred = keyReferences.filter((ref) => ref.moreAvailable?.reason === "deferred");
52462
+ const truncated = keyReferences.filter((ref) => ref.moreAvailable?.reason === "truncated");
52463
+ const moreAvailableNote = deferred.length + truncated.length > 0 ? ` MORE DETAIL IS AVAILABLE ON DEMAND (this is NOT a failure and is not in "unrecoveredFailures"): ` + [
52464
+ deferred.length > 0 ? `${pluralize(deferred.length, "reference")} ${deferred.length === 1 ? "was" : "were"} DEFERRED \u2014 no "article" is included because the site was still preparing ${deferred.length === 1 ? "it" : "them"} when the full-text time budget ran out; their "title", "url" and "snippet" are valid` : void 0,
52465
+ truncated.length > 0 ? `${pluralize(truncated.length, "reference")} ${truncated.length === 1 ? "is" : "are"} TRUNCATED \u2014 "article.text" stops partway (it ends with a "[\u2026 truncated \u2026]" line) but "article.outline" lists every section, so you can see what the rest holds` : void 0
52466
+ ].filter((part) => part !== void 0).join("; ") + `. Every such entry has a "moreAvailable" field whose "command" is an exact, ready-to-run shell command that fetches that article's COMPLETE text on demand (\`web-cli get <site> '<url>'\` \u2014 the same "url" shown on the entry). If the snippet, outline or truncated text is not enough to answer the question, RUN THAT COMMAND for the one or two entries that matter most (a large chapter can take 10-15s to come back) instead of answering from partial material or guessing; don't fetch every one by reflex. Until you have fetched it, treat what you can see of such an entry as incomplete and say so if you rely on it.` : "";
52177
52467
  if (keyReferences.length === 0) {
52178
52468
  return {
52179
52469
  question: query,
@@ -52183,7 +52473,7 @@ function buildAgentTask(query, keyReferences, sites2) {
52183
52473
  }
52184
52474
  return {
52185
52475
  question: query,
52186
- instructions: `Answer the question above using the material already retrieved into "keyReferences" \u2014 do not just relay this JSON, "summary", or a list of titles as if that were the answer. For each "keyReferences" entry that has "article.text": read it and decide whether it actually helps answer the question. If it does, cite it (its "url") in your answer. If it does not, treat it as irrelevant to this question \u2014 leave it out of your answer entirely, rather than citing it just because it was fetched.` + (withFullText.length < keyReferences.length ? ` For an entry with no "article.text" (see "fetchError"/omitted from ${withFullText.length}/${keyReferences.length} with full text in "summary.keyReferences"), fall back to its "snippet" instead of skipping it, but note that fallback is unconfirmed.` : "") + ` If nothing retrieved actually answers the question, say so plainly rather than forcing an answer out of unrelated material.` + failureNote,
52476
+ instructions: `Answer the question above using the material already retrieved into "keyReferences" \u2014 do not just relay this JSON, "summary", or a list of titles as if that were the answer. For each "keyReferences" entry that has "article.text": read it and decide whether it actually helps answer the question. If it does, cite it (its "url") in your answer. If it does not, treat it as irrelevant to this question \u2014 leave it out of your answer entirely, rather than citing it just because it was fetched.` + (withFullText.length < keyReferences.length ? ` For an entry with no "article.text" (see "fetchError"/omitted from ${withFullText.length}/${keyReferences.length} with full text in "summary.keyReferences"), fall back to its "snippet" instead of skipping it, but note that fallback is unconfirmed.` : "") + moreAvailableNote + ` If nothing retrieved actually answers the question, say so plainly rather than forcing an answer out of unrelated material.` + failureNote,
52187
52477
  ...unrecoveredFailures.length > 0 ? { unrecoveredFailures } : {}
52188
52478
  };
52189
52479
  }
@@ -52202,7 +52492,7 @@ function formatSiteSettledNotice(site, outcome, err) {
52202
52492
  const hitCount = siteHitCount(outcome);
52203
52493
  return hitCount === null ? `web-cli: ${site} finished \u2014 hit count unavailable (response shape not recognized)` : `web-cli: ${site} finished \u2014 ${pluralize(hitCount, "hit")}`;
52204
52494
  }
52205
- async function expandKeyReference(site, hit, baseUrl, replayOpts) {
52495
+ async function expandKeyReference(site, hit, baseUrl, replayOpts, prefetched, limits = {}) {
52206
52496
  const base = {
52207
52497
  site,
52208
52498
  title: hit.title,
@@ -52214,7 +52504,15 @@ async function expandKeyReference(site, hit, baseUrl, replayOpts) {
52214
52504
  };
52215
52505
  const fetchKey = hit.url ?? hit.id;
52216
52506
  try {
52217
- const { data } = await replay(site, "getArticle", fetchKey, replayOpts);
52507
+ const usePrefetched = prefetched !== void 0 && prefetched.key === fetchKey;
52508
+ const { data } = usePrefetched ? { data: prefetched.data } : await replay(
52509
+ site,
52510
+ "getArticle",
52511
+ fetchKey,
52512
+ // Only a LIMITED budget cancels anything; an unlimited one leaves the call exactly as it
52513
+ // was, so a caller that opted out of the budget gets the old behavior byte for byte.
52514
+ limits.budget?.limited ? { ...replayOpts, signal: limits.budget.signal } : replayOpts
52515
+ );
52218
52516
  const article = parseArticle3(site, data, baseUrl);
52219
52517
  if (article?.id !== void 0 && hit.id !== void 0 && String(article.id) !== String(hit.id)) {
52220
52518
  return {
@@ -52234,19 +52532,56 @@ async function expandKeyReference(site, hit, baseUrl, replayOpts) {
52234
52532
  }
52235
52533
  };
52236
52534
  }
52237
- return { ...base, article: article ?? void 0 };
52535
+ if (!article) {
52536
+ return { ...base, article: void 0 };
52537
+ }
52538
+ if (article.text) {
52539
+ limits.budget?.noteFetched();
52540
+ }
52541
+ const truncated = truncateArticle(article, limits.maxArticleChars ?? 0, site, fetchKey);
52542
+ return {
52543
+ ...base,
52544
+ article: truncated.article,
52545
+ ...truncated.moreAvailable ? { moreAvailable: truncated.moreAvailable } : {}
52546
+ };
52238
52547
  } catch (err) {
52548
+ if (limits.budget?.aborted && isAbortError(err)) {
52549
+ return { ...base, moreAvailable: deferredFullText(site, fetchKey, limits.budget.budgetMs) };
52550
+ }
52239
52551
  return { ...base, fetchError: describeError(err) };
52240
52552
  }
52241
52553
  }
52242
- async function searchOneSite(site, query, replayOpts) {
52554
+ async function searchOneSite(site, query, replayOpts, preflight, limits = {}) {
52243
52555
  const config2 = getSiteConfig(site);
52244
- const { data, discovered } = await replay(site, "search", query, replayOpts);
52556
+ const session = preflight ? await preflight : void 0;
52557
+ let data;
52558
+ let discovered;
52559
+ if (session && session.state !== "expired" && session.searchData !== void 0) {
52560
+ data = session.searchData;
52561
+ discovered = false;
52562
+ } else {
52563
+ ({ data, discovered } = await replay(site, "search", query, replayOpts));
52564
+ }
52245
52565
  const parsed = parseSearchResults4(site, data, config2.baseUrl);
52246
52566
  const selected = parsed && !NO_KEY_REFERENCE_EXPANSION_SITES.has(site) ? selectKeyReferences(parsed.hits) : [];
52247
- const keyReferences = await Promise.all(
52248
- selected.map((hit) => expandKeyReference(site, hit, config2.baseUrl, replayOpts))
52249
- );
52567
+ const prefetched = session && session.state !== "expired" ? session.article : void 0;
52568
+ const budget = new FullTextBudget(limits.fullTextBudgetMs ?? 0);
52569
+ if (prefetched) {
52570
+ budget.noteFetched();
52571
+ }
52572
+ let keyReferences;
52573
+ try {
52574
+ keyReferences = await Promise.all(
52575
+ selected.map(
52576
+ (hit) => expandKeyReference(site, hit, config2.baseUrl, replayOpts, prefetched, {
52577
+ budget,
52578
+ maxArticleChars: limits.maxArticleChars
52579
+ })
52580
+ )
52581
+ );
52582
+ } finally {
52583
+ budget.dispose();
52584
+ }
52250
52585
  return { outcome: { discovered, results: data, parsed }, keyReferences };
52251
52586
  }
52252
52587
  var DEFAULT_SITE_TIMEOUT_MS = 18e4;
@@ -52282,6 +52617,8 @@ function withSiteTimeout(promise, site, timeoutMs, excludedWaitMs = getInteracti
52282
52617
  }
52283
52618
  async function runSearch(query, extraSites = [], opts = {}) {
52284
52619
  const siteTimeoutMs = opts.siteTimeoutMs ?? DEFAULT_SITE_TIMEOUT_MS;
52620
+ const fullTextBudgetMs = opts.fullTextBudgetMs ?? DEFAULT_FULLTEXT_BUDGET_MS;
52621
+ const maxArticleChars = opts.maxArticleChars ?? DEFAULT_MAX_ARTICLE_CHARS;
52285
52622
  const notify = opts.notify ?? ((message) => process.stderr.write(`${message}
52286
52623
  `));
52287
52624
  const siteNames = Array.from(/* @__PURE__ */ new Set([...MEDICAL_SEARCH_SITES, ...extraSites]));
@@ -52325,16 +52662,20 @@ async function runSearch(query, extraSites = [], opts = {}) {
52325
52662
  `);
52326
52663
  }
52327
52664
  }
52328
- let loginAttempts = [];
52329
- if (replayOpts.disableLoginRecovery !== true) {
52330
- const outcomes2 = await ensureSessionsForSites(siteNames, query, {
52331
- loginTimeoutMs: replayOpts.loginTimeoutMs,
52332
- allowVisible: replayOpts.allowVisibleLogin
52333
- });
52334
- loginAttempts = outcomes2.filter((outcome) => outcome.state === "expired");
52335
- }
52336
52665
  notify(`web-cli: searching ${pluralize(siteNames.length, "site")} \u2014 ${siteNames.join(", ")}`);
52337
- const sitePromises = siteNames.map((site) => withSiteTimeout(searchOneSite(site, query, replayOpts), site, siteTimeoutMs));
52666
+ const preflight = replayOpts.disableLoginRecovery !== true ? startSessionPreflight(siteNames, query, {
52667
+ loginTimeoutMs: replayOpts.loginTimeoutMs,
52668
+ allowVisible: replayOpts.allowVisibleLogin
52669
+ }) : /* @__PURE__ */ new Map();
52670
+ const settledPreflight = [];
52671
+ preflight.forEach((promise) => void promise.then((outcome) => settledPreflight.push(outcome)));
52672
+ const sitePromises = siteNames.map(
52673
+ (site) => withSiteTimeout(
52674
+ searchOneSite(site, query, replayOpts, preflight.get(site), { fullTextBudgetMs, maxArticleChars }),
52675
+ site,
52676
+ siteTimeoutMs
52677
+ )
52678
+ );
52338
52679
  sitePromises.forEach((promise, i) => {
52339
52680
  const site = siteNames[i];
52340
52681
  promise.then(
@@ -52343,6 +52684,7 @@ async function runSearch(query, extraSites = [], opts = {}) {
52343
52684
  );
52344
52685
  });
52345
52686
  const outcomes = await Promise.allSettled(sitePromises);
52687
+ const loginAttempts = settledPreflight.filter((outcome) => outcome.state === "expired").sort((a, b) => siteNames.indexOf(a.site) - siteNames.indexOf(b.site)).map(({ searchData: _searchData, article: _article, ...outcome }) => outcome);
52346
52688
  const sites2 = {};
52347
52689
  const keyReferences = [];
52348
52690
  const sitesSucceeded = [];
@@ -52367,6 +52709,8 @@ async function runSearch(query, extraSites = [], opts = {}) {
52367
52709
  });
52368
52710
  const fullTextFetched = keyReferences.filter((ref) => !!ref.article?.text).length;
52369
52711
  const fullTextFailed = keyReferences.filter((ref) => ref.fetchError !== void 0).length;
52712
+ const fullTextDeferred = keyReferences.filter((ref) => ref.moreAvailable?.reason === "deferred").length;
52713
+ const fullTextTruncated = keyReferences.filter((ref) => ref.moreAvailable?.reason === "truncated").length;
52370
52714
  const summary = {
52371
52715
  sitesRequested: siteNames,
52372
52716
  sitesSucceeded,
@@ -52377,7 +52721,9 @@ async function runSearch(query, extraSites = [], opts = {}) {
52377
52721
  selected: keyReferences.length,
52378
52722
  fullTextFetched,
52379
52723
  fullTextFailed,
52380
- fullTextUnparsed: keyReferences.length - fullTextFetched - fullTextFailed
52724
+ fullTextDeferred,
52725
+ fullTextTruncated,
52726
+ fullTextUnparsed: keyReferences.length - fullTextFetched - fullTextFailed - fullTextDeferred
52381
52727
  }
52382
52728
  };
52383
52729
  notify(
@@ -52689,6 +53035,8 @@ function renderSearchCoverage(stats) {
52689
53035
  const parts = [
52690
53036
  typeof kr.selected === "number" ? `${kr.selected} selected` : void 0,
52691
53037
  typeof kr.fullTextFetched === "number" ? `${kr.fullTextFetched} with full text` : void 0,
53038
+ typeof kr.fullTextTruncated === "number" && kr.fullTextTruncated > 0 ? `${kr.fullTextTruncated} truncated` : void 0,
53039
+ typeof kr.fullTextDeferred === "number" && kr.fullTextDeferred > 0 ? `${kr.fullTextDeferred} deferred` : void 0,
52692
53040
  typeof kr.fullTextFailed === "number" ? `${kr.fullTextFailed} fetch failed` : void 0,
52693
53041
  typeof kr.fullTextUnparsed === "number" ? `${kr.fullTextUnparsed} unparsed` : void 0
52694
53042
  ].filter((p) => p !== void 0);
@@ -52896,7 +53244,7 @@ async function runFinalize(opts = {}, deps = {}) {
52896
53244
  }
52897
53245
 
52898
53246
  // src/commands/renderMarkdown.ts
52899
- var fs12 = __toESM(require("fs"));
53247
+ var fs13 = __toESM(require("fs"));
52900
53248
  function invalidInput2(message) {
52901
53249
  throw new CliError(
52902
53250
  "INVALID_INPUT",
@@ -52948,13 +53296,13 @@ function describeError3(err) {
52948
53296
  code: err instanceof CliError ? err.code : "INTERNAL_ERROR"
52949
53297
  };
52950
53298
  }
52951
- function readFromFile(path13) {
53299
+ function readFromFile(path14) {
52952
53300
  try {
52953
- return fs12.readFileSync(path13, "utf8");
53301
+ return fs13.readFileSync(path14, "utf8");
52954
53302
  } catch (err) {
52955
53303
  throw new CliError(
52956
53304
  "INPUT_READ_FAILED",
52957
- `Could not read --from ${path13} (${err instanceof Error ? err.message : String(err)}).`
53305
+ `Could not read --from ${path14} (${err instanceof Error ? err.message : String(err)}).`
52958
53306
  );
52959
53307
  }
52960
53308
  }
@@ -53108,7 +53456,7 @@ async function bingWebSearch(query, options = {}) {
53108
53456
  }
53109
53457
 
53110
53458
  // src/search/googleSearch.ts
53111
- var fs13 = __toESM(require("fs"));
53459
+ var fs14 = __toESM(require("fs"));
53112
53460
  var CDP2 = require_chrome_remote_interface();
53113
53461
  var DEFAULT_MAX_RESULTS2 = 10;
53114
53462
  var DEFAULT_SETTLE_MS = 3e3;
@@ -53227,7 +53575,7 @@ async function googleWebSearch(query, options = {}, deps = {}) {
53227
53575
  function writeDebugHtml(debugHtmlPath, html) {
53228
53576
  if (!debugHtmlPath) return;
53229
53577
  try {
53230
- fs13.writeFileSync(debugHtmlPath, html);
53578
+ fs14.writeFileSync(debugHtmlPath, html);
53231
53579
  } catch {
53232
53580
  }
53233
53581
  }
@@ -53408,9 +53756,9 @@ async function runWeather(location, options = {}) {
53408
53756
  var os6 = __toESM(require("os"));
53409
53757
 
53410
53758
  // src/skillInstall.ts
53411
- var fs14 = __toESM(require("fs"));
53759
+ var fs15 = __toESM(require("fs"));
53412
53760
  var os5 = __toESM(require("os"));
53413
- var path11 = __toESM(require("path"));
53761
+ var path12 = __toESM(require("path"));
53414
53762
  var SKILL_NAME = "web-cli";
53415
53763
  var INSTALL_MARKER_FILE = ".installed-by-web-cli.json";
53416
53764
  var COPY_EXCLUDES = /* @__PURE__ */ new Set([".DS_Store"]);
@@ -53418,34 +53766,34 @@ var AGENT_CHOICES = ["claude", "codex", "agents", "dsh"];
53418
53766
  function resolveCodexHomeDir(homeDir, override) {
53419
53767
  const fromEnv = process.env.CODEX_HOME;
53420
53768
  if (override !== void 0) {
53421
- return path11.resolve(override);
53769
+ return path12.resolve(override);
53422
53770
  }
53423
- return fromEnv !== void 0 && fromEnv.trim().length > 0 ? path11.resolve(fromEnv) : path11.join(homeDir, ".codex");
53771
+ return fromEnv !== void 0 && fromEnv.trim().length > 0 ? path12.resolve(fromEnv) : path12.join(homeDir, ".codex");
53424
53772
  }
53425
53773
  function resolveAgentsHomeDir(homeDir, override) {
53426
- return override ?? process.env.DSH_AGENTS_HOME ?? path11.join(homeDir, ".agents");
53774
+ return override ?? process.env.DSH_AGENTS_HOME ?? path12.join(homeDir, ".agents");
53427
53775
  }
53428
53776
  function resolveDshHomeDir(homeDir, override) {
53429
53777
  const fromEnv = process.env.DSH_HOME;
53430
53778
  const configured = override ?? (fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : void 0);
53431
53779
  if (configured === void 0) {
53432
- return path11.join(homeDir, ".dsh");
53780
+ return path12.join(homeDir, ".dsh");
53433
53781
  }
53434
53782
  if (configured === "~") {
53435
53783
  return homeDir;
53436
53784
  }
53437
53785
  if (configured.startsWith("~/") || configured.startsWith("~\\")) {
53438
- return path11.join(homeDir, configured.slice(2));
53786
+ return path12.join(homeDir, configured.slice(2));
53439
53787
  }
53440
- return path11.resolve(configured);
53788
+ return path12.resolve(configured);
53441
53789
  }
53442
53790
  function resolveShippedSkillDir(fromDir) {
53443
53791
  const candidates = [
53444
- path11.resolve(fromDir, "..", "skills", SKILL_NAME),
53445
- path11.resolve(fromDir, "..", "..", "skills", SKILL_NAME)
53792
+ path12.resolve(fromDir, "..", "skills", SKILL_NAME),
53793
+ path12.resolve(fromDir, "..", "..", "skills", SKILL_NAME)
53446
53794
  ];
53447
53795
  for (const candidate of candidates) {
53448
- if (fs14.existsSync(path11.join(candidate, "SKILL.md"))) {
53796
+ if (fs15.existsSync(path12.join(candidate, "SKILL.md"))) {
53449
53797
  return candidate;
53450
53798
  }
53451
53799
  }
@@ -53455,7 +53803,7 @@ function resolveShippedSkillDir(fromDir) {
53455
53803
  }
53456
53804
  function shippedSkillVersion(shippedSkillDir) {
53457
53805
  try {
53458
- const pkg = JSON.parse(fs14.readFileSync(path11.resolve(shippedSkillDir, "..", "..", "package.json"), "utf8"));
53806
+ const pkg = JSON.parse(fs15.readFileSync(path12.resolve(shippedSkillDir, "..", "..", "package.json"), "utf8"));
53459
53807
  return typeof pkg.version === "string" ? pkg.version : void 0;
53460
53808
  } catch {
53461
53809
  return void 0;
@@ -53463,13 +53811,13 @@ function shippedSkillVersion(shippedSkillDir) {
53463
53811
  }
53464
53812
  function detectAgents(homeDir, overrides = {}) {
53465
53813
  const detected = [];
53466
- if (fs14.existsSync(path11.join(homeDir, ".claude"))) {
53814
+ if (fs15.existsSync(path12.join(homeDir, ".claude"))) {
53467
53815
  detected.push("claude");
53468
53816
  }
53469
- if (fs14.existsSync(resolveCodexHomeDir(homeDir, overrides.codexHomeDir))) {
53817
+ if (fs15.existsSync(resolveCodexHomeDir(homeDir, overrides.codexHomeDir))) {
53470
53818
  detected.push("codex");
53471
53819
  }
53472
- if (fs14.existsSync(resolveDshHomeDir(homeDir, overrides.dshHomeDir))) {
53820
+ if (fs15.existsSync(resolveDshHomeDir(homeDir, overrides.dshHomeDir))) {
53473
53821
  detected.push("dsh");
53474
53822
  }
53475
53823
  return detected;
@@ -53492,14 +53840,14 @@ function resolveAgents(requested, homeDir, overrides = {}) {
53492
53840
  var CODEX_PROMPT_MARKER = "# web-cli \u2014 search/retrieval CLI usage guidance";
53493
53841
  function symlinkTarget(target) {
53494
53842
  try {
53495
- return path11.resolve(path11.dirname(target), fs14.readlinkSync(target));
53843
+ return path12.resolve(path12.dirname(target), fs15.readlinkSync(target));
53496
53844
  } catch {
53497
53845
  return null;
53498
53846
  }
53499
53847
  }
53500
53848
  function lstatOrNull(target) {
53501
53849
  try {
53502
- return fs14.lstatSync(target);
53850
+ return fs15.lstatSync(target);
53503
53851
  } catch {
53504
53852
  return null;
53505
53853
  }
@@ -53507,14 +53855,14 @@ function lstatOrNull(target) {
53507
53855
  function describeExisting(target) {
53508
53856
  const linked = symlinkTarget(target);
53509
53857
  if (linked) {
53510
- return fs14.existsSync(linked) ? `an existing symlink -> ${linked}` : `a dangling symlink -> ${linked}`;
53858
+ return fs15.existsSync(linked) ? `an existing symlink -> ${linked}` : `a dangling symlink -> ${linked}`;
53511
53859
  }
53512
53860
  const stats = lstatOrNull(target);
53513
53861
  return stats?.isDirectory() ? "an existing directory" : "an existing file";
53514
53862
  }
53515
53863
  function isOurSkillLink(target) {
53516
53864
  const linked = symlinkTarget(target);
53517
- return linked !== null && path11.basename(linked) === SKILL_NAME && path11.basename(path11.dirname(linked)) === "skills";
53865
+ return linked !== null && path12.basename(linked) === SKILL_NAME && path12.basename(path12.dirname(linked)) === "skills";
53518
53866
  }
53519
53867
  function isOurCodexPrompt(target) {
53520
53868
  const stats = lstatOrNull(target);
@@ -53522,20 +53870,20 @@ function isOurCodexPrompt(target) {
53522
53870
  return false;
53523
53871
  }
53524
53872
  try {
53525
- return fs14.readFileSync(target, "utf8").startsWith(CODEX_PROMPT_MARKER);
53873
+ return fs15.readFileSync(target, "utf8").startsWith(CODEX_PROMPT_MARKER);
53526
53874
  } catch {
53527
53875
  return false;
53528
53876
  }
53529
53877
  }
53530
53878
  function isOurInstalledCopy(target) {
53531
53879
  const stats = lstatOrNull(target);
53532
- return stats !== null && stats.isDirectory() && !stats.isSymbolicLink() && fs14.existsSync(path11.join(target, INSTALL_MARKER_FILE));
53880
+ return stats !== null && stats.isDirectory() && !stats.isSymbolicLink() && fs15.existsSync(path12.join(target, INSTALL_MARKER_FILE));
53533
53881
  }
53534
53882
  function relativeFileList(dir) {
53535
- return fs14.readdirSync(dir, { recursive: true, withFileTypes: true }).filter((entry) => entry.isFile() && entry.name !== INSTALL_MARKER_FILE && !COPY_EXCLUDES.has(entry.name)).map((entry) => path11.relative(dir, path11.join(entry.parentPath, entry.name))).sort();
53883
+ return fs15.readdirSync(dir, { recursive: true, withFileTypes: true }).filter((entry) => entry.isFile() && entry.name !== INSTALL_MARKER_FILE && !COPY_EXCLUDES.has(entry.name)).map((entry) => path12.relative(dir, path12.join(entry.parentPath, entry.name))).sort();
53536
53884
  }
53537
53885
  function matchesShippedSkill(target, shippedSkillDir) {
53538
- if (!shippedSkillDir || !fs14.existsSync(shippedSkillDir) || !lstatOrNull(target)?.isDirectory()) {
53886
+ if (!shippedSkillDir || !fs15.existsSync(shippedSkillDir) || !lstatOrNull(target)?.isDirectory()) {
53539
53887
  return false;
53540
53888
  }
53541
53889
  try {
@@ -53544,17 +53892,17 @@ function matchesShippedSkill(target, shippedSkillDir) {
53544
53892
  return false;
53545
53893
  }
53546
53894
  return shippedFiles.every(
53547
- (file) => fs14.readFileSync(path11.join(target, file)).equals(fs14.readFileSync(path11.join(shippedSkillDir, file)))
53895
+ (file) => fs15.readFileSync(path12.join(target, file)).equals(fs15.readFileSync(path12.join(shippedSkillDir, file)))
53548
53896
  );
53549
53897
  } catch {
53550
53898
  return false;
53551
53899
  }
53552
53900
  }
53553
53901
  function copyShippedSkill(shippedSkillDir, target) {
53554
- fs14.mkdirSync(path11.dirname(target), { recursive: true });
53555
- fs14.cpSync(shippedSkillDir, target, {
53902
+ fs15.mkdirSync(path12.dirname(target), { recursive: true });
53903
+ fs15.cpSync(shippedSkillDir, target, {
53556
53904
  recursive: true,
53557
- filter: (src) => !COPY_EXCLUDES.has(path11.basename(src))
53905
+ filter: (src) => !COPY_EXCLUDES.has(path12.basename(src))
53558
53906
  });
53559
53907
  const marker = {
53560
53908
  installer: "web-cli",
@@ -53563,33 +53911,33 @@ function copyShippedSkill(shippedSkillDir, target) {
53563
53911
  installedAt: (/* @__PURE__ */ new Date()).toISOString(),
53564
53912
  note: "This directory is a copy managed by `web-cli install-skill`; re-run it to refresh, or `web-cli uninstall-skill` to remove."
53565
53913
  };
53566
- fs14.writeFileSync(path11.join(target, INSTALL_MARKER_FILE), JSON.stringify(marker, null, 2) + "\n", "utf8");
53914
+ fs15.writeFileSync(path12.join(target, INSTALL_MARKER_FILE), JSON.stringify(marker, null, 2) + "\n", "utf8");
53567
53915
  }
53568
53916
  function skillsRootFor(agent, options, homeDir, cwd) {
53569
53917
  switch (agent) {
53570
53918
  case "claude":
53571
- return path11.join(options.project ? cwd : homeDir, ".claude", "skills");
53919
+ return path12.join(options.project ? cwd : homeDir, ".claude", "skills");
53572
53920
  case "codex":
53573
- return path11.join(resolveCodexHomeDir(homeDir, options.codexHomeDir), "skills");
53921
+ return path12.join(resolveCodexHomeDir(homeDir, options.codexHomeDir), "skills");
53574
53922
  case "agents":
53575
- return path11.join(resolveAgentsHomeDir(homeDir, options.agentsHomeDir), "skills");
53923
+ return path12.join(resolveAgentsHomeDir(homeDir, options.agentsHomeDir), "skills");
53576
53924
  case "dsh":
53577
- return path11.join(resolveDshHomeDir(homeDir, options.dshHomeDir), "skills");
53925
+ return path12.join(resolveDshHomeDir(homeDir, options.dshHomeDir), "skills");
53578
53926
  }
53579
53927
  }
53580
53928
  function legacyCodexPromptPath(options, homeDir) {
53581
- return path11.join(resolveCodexHomeDir(homeDir, options.codexHomeDir), "prompts", `${SKILL_NAME}.md`);
53929
+ return path12.join(resolveCodexHomeDir(homeDir, options.codexHomeDir), "prompts", `${SKILL_NAME}.md`);
53582
53930
  }
53583
53931
  function cleanUpLegacyCodexPrompt(options, homeDir) {
53584
53932
  const prompt = legacyCodexPromptPath(options, homeDir);
53585
53933
  if (!isOurCodexPrompt(prompt)) {
53586
53934
  return null;
53587
53935
  }
53588
- fs14.rmSync(prompt, { force: true });
53936
+ fs15.rmSync(prompt, { force: true });
53589
53937
  return `removed legacy pointer prompt ${prompt}`;
53590
53938
  }
53591
53939
  function installCopyInto(agent, skillsRoot, options) {
53592
- const target = path11.join(skillsRoot, SKILL_NAME);
53940
+ const target = path12.join(skillsRoot, SKILL_NAME);
53593
53941
  const shipped = options.shippedSkillDir;
53594
53942
  const version = shippedSkillVersion(shipped);
53595
53943
  const provenance = `copied from ${shipped}${version ? ` (v${version})` : ""}`;
@@ -53608,7 +53956,7 @@ function installCopyInto(agent, skillsRoot, options) {
53608
53956
  } else {
53609
53957
  return { agent, path: target, status: "blocked", kind: "copy", detail: describeExisting(target) };
53610
53958
  }
53611
- fs14.rmSync(target, { recursive: true, force: true });
53959
+ fs15.rmSync(target, { recursive: true, force: true });
53612
53960
  }
53613
53961
  copyShippedSkill(shipped, target);
53614
53962
  return { agent, path: target, status, kind: "copy", detail: provenance };
@@ -53632,7 +53980,7 @@ function uninstallSkill(options) {
53632
53980
  const homeDir = options.homeDir ?? os5.homedir();
53633
53981
  const cwd = options.cwd ?? process.cwd();
53634
53982
  return options.agents.map((agent) => {
53635
- const target = path11.join(skillsRootFor(agent, options, homeDir, cwd), SKILL_NAME);
53983
+ const target = path12.join(skillsRootFor(agent, options, homeDir, cwd), SKILL_NAME);
53636
53984
  const legacyNote = agent === "codex" ? cleanUpLegacyCodexPrompt(options, homeDir) : null;
53637
53985
  if (!lstatOrNull(target)) {
53638
53986
  return { agent, path: target, status: "not-registered", ...legacyNote ? { detail: legacyNote } : {} };
@@ -53647,7 +53995,7 @@ function uninstallSkill(options) {
53647
53995
  };
53648
53996
  }
53649
53997
  const what = symlinkTarget(target) ? `symlink -> ${symlinkTarget(target)}` : "installed copy";
53650
- fs14.rmSync(target, { recursive: true, force: true });
53998
+ fs15.rmSync(target, { recursive: true, force: true });
53651
53999
  return { agent, path: target, status: "removed", detail: legacyNote ? `${what}; ${legacyNote}` : what };
53652
54000
  });
53653
54001
  }
@@ -53689,7 +54037,7 @@ function installWarningFilter(target = process) {
53689
54037
  }
53690
54038
 
53691
54039
  // src/index.ts
53692
- dotenv.config({ path: [WEB_CLI_ENV_PATH, path12.join(process.cwd(), ".env")] });
54040
+ dotenv.config({ path: [WEB_CLI_ENV_PATH, path13.join(process.cwd(), ".env")] });
53693
54041
  function printSuccess(value) {
53694
54042
  process.stdout.write(`${JSON.stringify(value)}
53695
54043
  `);
@@ -53714,6 +54062,13 @@ function wrap(fn) {
53714
54062
  }
53715
54063
  };
53716
54064
  }
54065
+ function parseNonNegative(flag, value) {
54066
+ const n = Number(value);
54067
+ if (value.trim() === "" || !Number.isFinite(n) || n < 0) {
54068
+ throw new CliError("INVALID_ARGUMENT", `${flag} must be a number >= 0 (got "${value}").`);
54069
+ }
54070
+ return n;
54071
+ }
53717
54072
  function wantsJsonOutput(opts) {
53718
54073
  if (opts.json && opts.pretty) {
53719
54074
  throw new CliError("INVALID_ARGUMENT", "--json and --pretty are mutually exclusive \u2014 pass at most one.");
@@ -53757,6 +54112,14 @@ program2.command("search <query>").description(
53757
54112
  "--disable-login-recovery",
53758
54113
  "don't attempt ANY recovery at all when a site's session has expired \u2014 not even the default silent, credential-based refresh (zero browser launches of any kind); report SESSION_EXPIRED immediately. A strict, rarely-needed escape hatch for an environment that cannot tolerate ANY browser automation attempt \u2014 most unattended callers want the default (silent refresh still tried) instead of this"
53759
54114
  ).option("--loginTimeoutSeconds <n>", "how long to wait for you to finish signing in", "240").option(
54115
+ "--fulltext-budget <seconds>",
54116
+ `how long to wait, per site, for the key references' full texts before DEFERRING the ones the site is still preparing (large book chapters can take 10s+ on the site's side; nothing shortens that wait but not waiting). Deferred references keep their title/url/snippet and carry a "moreAvailable.command" that fetches them on demand. At least one full text per site is always waited for. 0 waits for every full text, as before`,
54117
+ "5"
54118
+ ).option(
54119
+ "--max-article-chars <n>",
54120
+ "cut each returned article's text to this many characters (its outline is kept whole and a trailing line says how to fetch the rest on demand with `web-cli get`). 0 never truncates",
54121
+ "60000"
54122
+ ).option(
53760
54123
  "--markdown [path]",
53761
54124
  "also write this report to disk as a file (independent of --json \u2014 works either way); omit the value for the current directory, or give a .md file or a directory"
53762
54125
  ).option(
@@ -53776,6 +54139,8 @@ program2.command("search <query>").description(
53776
54139
  disableLoginRecovery: opts.disableLoginRecovery,
53777
54140
  allowVisibleLogin: opts.allowVisibleLogin,
53778
54141
  loginTimeoutMs: Number(opts.loginTimeoutSeconds) * 1e3,
54142
+ fullTextBudgetMs: parseNonNegative("--fulltext-budget", opts.fulltextBudget) * 1e3,
54143
+ maxArticleChars: parseNonNegative("--max-article-chars", opts.maxArticleChars),
53779
54144
  markdown: opts.markdown,
53780
54145
  out: opts.out
53781
54146
  });