engine7 7.1.148 → 7.1.150

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.
@@ -791,6 +791,16 @@ function tokenize(text2) {
791
791
  function tokenizeToField(text2) {
792
792
  return tokenize(text2).join(" ");
793
793
  }
794
+ function cjkBigrams(text2) {
795
+ const out = [];
796
+ for (const seg of String(text2 ?? "").match(/[\u4e00-\u9fff]{2,}/g) ?? []) {
797
+ for (let i = 0; i + 1 < seg.length; i++) out.push(seg.slice(i, i + 2));
798
+ }
799
+ return out;
800
+ }
801
+ function tokenizeCjk(text2) {
802
+ return [...tokenize(text2), ...cjkBigrams(text2)];
803
+ }
794
804
  var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
795
805
  var init_tokenizer = __esm({
796
806
  "src/mem7/core/tokenizer.ts"() {
@@ -2199,10 +2209,10 @@ function installSQLiteWriteCapture(db, source) {
2199
2209
  if (db.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
2200
2210
  const exec = db.exec, prepare = db.prepare;
2201
2211
  let active, failed = false, closed = false, reading = false;
2202
- let direct;
2212
+ let direct2;
2203
2213
  const check = () => {
2204
2214
  if (closed) throw new Error("REPLICATION_TRANSACTION_CLOSED");
2205
- direct?.assertOpen();
2215
+ direct2?.assertOpen();
2206
2216
  };
2207
2217
  const wrappedExec = function(sql) {
2208
2218
  check();
@@ -2273,10 +2283,10 @@ function installSQLiteWriteCapture(db, source) {
2273
2283
  db.prepare = checkedPrepare;
2274
2284
  const transaction = (operation) => {
2275
2285
  check();
2276
- if (db.isTransaction) return direct.scope(operation);
2286
+ if (db.isTransaction) return direct2.scope(operation);
2277
2287
  db.exec("BEGIN IMMEDIATE");
2278
2288
  try {
2279
- const result = direct.scope(operation);
2289
+ const result = direct2.scope(operation);
2280
2290
  if (result && typeof result.then === "function") throw new Error("REPLICATION_ASYNC_TRANSACTION");
2281
2291
  db.exec("COMMIT");
2282
2292
  return result;
@@ -2285,10 +2295,10 @@ function installSQLiteWriteCapture(db, source) {
2285
2295
  throw error;
2286
2296
  }
2287
2297
  };
2288
- direct = installAutocommitCapture(db, transaction);
2298
+ direct2 = installAutocommitCapture(db, transaction);
2289
2299
  return {
2290
2300
  assertOpen: check,
2291
- scope: (operation) => direct.scope(operation),
2301
+ scope: (operation) => direct2.scope(operation),
2292
2302
  transaction,
2293
2303
  close() {
2294
2304
  if (closed) return;
@@ -2297,7 +2307,7 @@ function installSQLiteWriteCapture(db, source) {
2297
2307
  source.endCapture(active);
2298
2308
  active = void 0;
2299
2309
  }
2300
- direct.close();
2310
+ direct2.close();
2301
2311
  db.prepare = prepare;
2302
2312
  db.exec = exec;
2303
2313
  closed = true;
@@ -2745,18 +2755,31 @@ function forgotten(b, path2) {
2745
2755
  }
2746
2756
  function openIndex(b, version) {
2747
2757
  if (!b.stateDir || !b.topicsDir) return null;
2748
- const root = topicsHistoryRoot(b);
2758
+ const root = topicsHistoryRoot(b), expectedRoot = resolve6(b.topicsDir);
2759
+ let selected = "", actualRoot;
2749
2760
  try {
2750
- const selected = version ?? readJson(join10(root, "current.json")).version;
2761
+ selected = version ?? readJson(join10(root, "current.json")).version;
2751
2762
  if (!/^[a-f0-9-]{36}$/.test(selected)) throw new Error("INVALID_HISTORY_VERSION");
2752
2763
  const db = new DatabaseSync4(unlinked(join10(root, selected, "history.db")), { readOnly: true });
2753
2764
  const meta = db.prepare("SELECT value FROM metadata WHERE key=?").get("binding");
2754
- if (meta?.value !== canonical({ scope: topicsScope(b), root: resolve6(b.topicsDir) })) {
2765
+ if (meta?.value !== canonical({ scope: topicsScope(b), root: expectedRoot })) {
2766
+ try {
2767
+ actualRoot = String(JSON.parse(meta?.value ?? "{}").root ?? "") || void 0;
2768
+ } catch {
2769
+ actualRoot = meta?.value;
2770
+ }
2755
2771
  db.close();
2756
2772
  throw new Error("HISTORY_SCOPE_MISMATCH");
2757
2773
  }
2758
2774
  return db;
2759
- } catch {
2775
+ } catch (error) {
2776
+ if (error instanceof Error && error.message === "HISTORY_SCOPE_MISMATCH") {
2777
+ const signature2 = `${expectedRoot}|${actualRoot ?? ""}`;
2778
+ if (!scopeMismatchWarned.has(signature2)) {
2779
+ scopeMismatchWarned.add(signature2);
2780
+ console.warn(`[topics-history] HISTORY_SCOPE_MISMATCH\uFF1A\u7D22\u5F15\u7ED1\u5B9A\u7684 topics \u6839\u76EE\u5F55\u4E0E\u5F53\u524D\u4E0D\u7B26\uFF0C\u5386\u53F2\u68C0\u7D22\u672C\u6B21\u4E3A\u7A7A\u4E14\u4E0D\u4F1A\u81EA\u6108\uFF08\u9700\u91CD\u5EFA\uFF09\u3002expected root=${expectedRoot} actual root=${actualRoot ?? "(unreadable)"} version=${selected} index=${join10(root, selected, "history.db")}`);
2781
+ }
2782
+ }
2760
2783
  return null;
2761
2784
  }
2762
2785
  }
@@ -2950,15 +2973,15 @@ async function publishTopicsIndex(bundle, cleaned, b) {
2950
2973
  const md = /(?:^|-)\d{2}-\d{2}$/.test(d.value) ? d.value.slice(-5) : void 0;
2951
2974
  return [d.value, d.year?.toString() ?? "", ...md ? [md, `${Number(md.slice(0, 2))}\u6708${Number(md.slice(-2))}\u65E5`] : []];
2952
2975
  });
2953
- const terms = tokenize(`${paragraph}
2976
+ const terms = tokenizeCjk(`${paragraph}
2954
2977
  ${aliases.join(" ")}`);
2955
2978
  documentTerms.push(...terms);
2956
- search.run(id, [...tokenize(item.originalMetadata.title), ...terms].join(" "));
2979
+ search.run(id, [...tokenizeCjk(item.originalMetadata.title), ...terms].join(" "));
2957
2980
  }
2958
2981
  start = end;
2959
2982
  }
2960
2983
  }
2961
- if (documentTerms.length) documentInsert.run(item.path, item.originalHash, [...tokenize(item.originalMetadata.title), ...documentTerms].join(" "));
2984
+ if (documentTerms.length) documentInsert.run(item.path, item.originalHash, [...tokenizeCjk(item.originalMetadata.title), ...documentTerms].join(" "));
2962
2985
  }
2963
2986
  db.exec("COMMIT");
2964
2987
  if (db.prepare("PRAGMA integrity_check").get().integrity_check !== "ok") throw new Error("HISTORY_INDEX_INVALID");
@@ -2979,7 +3002,7 @@ async function searchTopicsHistory(b, query, options = {}) {
2979
3002
  const before = mem7StartDate(b);
2980
3003
  const year = topicQueryYear(query, options);
2981
3004
  const normalized = query.replace(/(?<!\d)(?:19|20)\d{2}\s*年?(?!\d)/g, "").replace(/去年|今年/g, "");
2982
- const terms = [...new Set(tokenize(normalized))].slice(0, 24);
3005
+ const terms = [...new Set(tokenizeCjk(normalized))].slice(0, 24);
2983
3006
  if (!terms.length && year !== void 0) terms.push(String(year));
2984
3007
  if (!terms.length) return [];
2985
3008
  const match = terms.map((term) => `"${term.replace(/"/g, '""')}"`).join(" OR ");
@@ -2990,7 +3013,7 @@ async function searchTopicsHistory(b, query, options = {}) {
2990
3013
  for (const row of rows) {
2991
3014
  const ref = JSON.parse(row.ref);
2992
3015
  const words = terms.filter((term) => !/^\d+[年月日]?$/.test(term));
2993
- if (words.length && !words.some((term) => tokenize(row.body + " " + row.title).includes(term))) continue;
3016
+ if (words.length && !words.some((term) => tokenizeCjk(row.body + " " + row.title).includes(term))) continue;
2994
3017
  try {
2995
3018
  const hit = getTopicHistory(b, ref, before);
2996
3019
  if (!topicMatchesYear(hit.dates, year)) continue;
@@ -3033,7 +3056,7 @@ async function searchTopicsHistory(b, query, options = {}) {
3033
3056
  db.close();
3034
3057
  }
3035
3058
  }
3036
- var topicsScope, key, rootKey, refPath, refId, fallbackChecks, credential2;
3059
+ var topicsScope, key, rootKey, refPath, refId, scopeMismatchWarned, fallbackChecks, credential2;
3037
3060
  var init_index = __esm({
3038
3061
  "src/memory/topics-history/index.ts"() {
3039
3062
  "use strict";
@@ -3048,6 +3071,7 @@ var init_index = __esm({
3048
3071
  rootKey = (b) => digest(resolve6(b.topicsDir));
3049
3072
  refPath = (ref) => `topics-history://${Buffer.from(canonical(ref)).toString("base64url")}`;
3050
3073
  refId = (ref) => digest(canonical(ref));
3074
+ scopeMismatchWarned = /* @__PURE__ */ new Set();
3051
3075
  fallbackChecks = /* @__PURE__ */ new Map();
3052
3076
  credential2 = /(?:api[_-]?key|password|secret|access[_-]?token)["']?\s*[:=]\s*["']?(?!YOUR_|PLACEHOLDER|\*|\[REDACTED\]|env:|\{\{)[\w/+.-]{10,}|-----BEGIN (?:RSA |OPENSSH |EC )?PRIVATE KEY-----|\bsk-[A-Za-z0-9_-]{20,}/i;
3053
3077
  }
@@ -3091,10 +3115,10 @@ import {
3091
3115
  realpathSync as realpathSync3,
3092
3116
  mkdirSync as mkdirSync10
3093
3117
  } from "node:fs";
3094
- import { join as join13, dirname as dirname5, resolve as resolve8 } from "node:path";
3118
+ import { join as join13, dirname as dirname5, resolve as resolve9 } from "node:path";
3095
3119
  function assertPrivateDirectory2(path2) {
3096
3120
  const info = lstatSync6(path2);
3097
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync3(path2) !== resolve8(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
3121
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync3(path2) !== resolve9(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
3098
3122
  throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
3099
3123
  }
3100
3124
  function syncDir(path2) {
@@ -3108,7 +3132,7 @@ function syncDir(path2) {
3108
3132
  }
3109
3133
  function preparePrivateDirectory(path2) {
3110
3134
  const missing = [];
3111
- let parent = resolve8(path2);
3135
+ let parent = resolve9(path2);
3112
3136
  for (; ; ) {
3113
3137
  try {
3114
3138
  lstatSync6(parent);
@@ -7104,16 +7128,15 @@ function stripInjectedContext(text2) {
7104
7128
  function escapeRegExp(s) {
7105
7129
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7106
7130
  }
7107
- var SKILL_GATE_HINT_PREFIX, SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
7131
+ var SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
7108
7132
  var init_strip_injected = __esm({
7109
7133
  "src/messages/strip-injected.ts"() {
7110
7134
  "use strict";
7111
- SKILL_GATE_HINT_PREFIX = "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1";
7112
7135
  SYSTEM_REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
7113
7136
  INJECT_SECTION_HEADS = /^(本轮对话|当前情绪状态|当前模式)/;
7114
7137
  KNOWN_INJECTED_TEXT = [
7115
- SKILL_GATE_HINT_PREFIX,
7116
- // skill-gate hint 默认/自定义前缀(1007 现行)
7138
+ "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1",
7139
+ // 旧版 skill-gate 提示前缀,兼容未打标签的历史
7117
7140
  "\u5F00\u53D1\u4EFB\u52A1\u8DEF\u6807\uFF0C\u6309\u573A\u666F\u5BF9\u53F7\u5165\u5EA7",
7118
7141
  // skill-gate hint(0912 老文案,历史 JSONL 兼容)
7119
7142
  "\u3010\u5B9A\u65F6\u5FC3\u8DF3\u3011\u8BF7 read HEARTBEAT.md"
@@ -7214,7 +7237,7 @@ var init_ingest = __esm({
7214
7237
  // src/mem7/core/legacy-recovery.ts
7215
7238
  import { createHash as createHash13 } from "node:crypto";
7216
7239
  import { readFileSync as readFileSync11, realpathSync as realpathSync4, statSync } from "node:fs";
7217
- import { isAbsolute as isAbsolute2, join as join16, relative as relative2, resolve as resolve9, sep as sep2 } from "node:path";
7240
+ import { isAbsolute as isAbsolute2, join as join16, relative as relative2, resolve as resolve10, sep as sep2 } from "node:path";
7218
7241
  function sessionCandidates(files, mapping) {
7219
7242
  const candidates = /* @__PURE__ */ new Map();
7220
7243
  let accepted = 0, rejected = 0;
@@ -7449,7 +7472,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7449
7472
  const duplicateIds = /* @__PURE__ */ new Set();
7450
7473
  const inside = (path2) => path2 && !isAbsolute2(path2) && path2 !== ".." && !path2.startsWith(`..${sep2}`);
7451
7474
  for (const relativePath of input.files) {
7452
- const logical = resolve9(root, relativePath);
7475
+ const logical = resolve10(root, relativePath);
7453
7476
  let canonical2;
7454
7477
  try {
7455
7478
  canonical2 = realpathSync4(logical);
@@ -11271,32 +11294,32 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11271
11294
  return { built: !hasStats, ms: Date.now() - started };
11272
11295
  }
11273
11296
  async close() {
11274
- const errors = [];
11297
+ const errors2 = [];
11275
11298
  try {
11276
11299
  this.capture?.close();
11277
11300
  } catch (error) {
11278
- errors.push(error);
11301
+ errors2.push(error);
11279
11302
  }
11280
11303
  try {
11281
11304
  this.db.close();
11282
11305
  } catch (error) {
11283
- errors.push(error);
11306
+ errors2.push(error);
11284
11307
  }
11285
11308
  try {
11286
11309
  await this.vectors?.close();
11287
11310
  } catch (error) {
11288
- errors.push(error);
11311
+ errors2.push(error);
11289
11312
  } finally {
11290
11313
  this.vectors = null;
11291
11314
  }
11292
11315
  try {
11293
11316
  this.releaseRuntimeWriter?.();
11294
11317
  } catch (error) {
11295
- errors.push(error);
11318
+ errors2.push(error);
11296
11319
  } finally {
11297
11320
  this.releaseRuntimeWriter = void 0;
11298
11321
  }
11299
- if (errors.length) throw new AggregateError(errors, "MEM7_CLOSE_FAILED");
11322
+ if (errors2.length) throw new AggregateError(errors2, "MEM7_CLOSE_FAILED");
11300
11323
  }
11301
11324
  // ── memcell 账本 ──────────────────────────────────────────
11302
11325
  insertMemcell(cell) {
@@ -12742,7 +12765,7 @@ import { DatabaseSync as DatabaseSync9, backup as backupSqlite } from "node:sqli
12742
12765
  import { randomUUID as randomUUID14 } from "node:crypto";
12743
12766
  import { existsSync as existsSync11, mkdirSync as mkdirSync13, readFileSync as readFileSync16, renameSync as renameSync7, unlinkSync as unlinkSync5, writeFileSync as writeFileSync11 } from "node:fs";
12744
12767
  import { cp, readdir, rm } from "node:fs/promises";
12745
- import { basename as basename5, dirname as dirname10, join as join21, resolve as resolve10 } from "node:path";
12768
+ import { basename as basename5, dirname as dirname10, join as join21, resolve as resolve11 } from "node:path";
12746
12769
  import { fileURLToPath as fileURLToPath4 } from "node:url";
12747
12770
  import { execFile } from "node:child_process";
12748
12771
  function atomicJson(path2, value) {
@@ -12807,7 +12830,7 @@ function backupRoots(stateDir) {
12807
12830
  if (!existsSync11(path2)) return [join21(stateDir, "mem7")];
12808
12831
  const value = readJson(path2);
12809
12832
  checkSeal(value);
12810
- if (value.version !== 1 || value.stateDir !== stateDir || !Array.isArray(value.roots) || value.roots.some((r) => typeof r !== "string" || resolve10(r) !== r)) throw new Error("INVALID_BACKUP_ROOT_REGISTRY");
12833
+ if (value.version !== 1 || value.stateDir !== stateDir || !Array.isArray(value.roots) || value.roots.some((r) => typeof r !== "string" || resolve11(r) !== r)) throw new Error("INVALID_BACKUP_ROOT_REGISTRY");
12811
12834
  return [.../* @__PURE__ */ new Set([join21(stateDir, "mem7"), ...value.roots])];
12812
12835
  }
12813
12836
  function registerRoot(stateDir, root) {
@@ -12916,7 +12939,7 @@ async function validateInHelper(args, allowed) {
12916
12939
  const built = fileURLToPath4(new URL("./sqlite-maintenance-worker.mjs", import.meta.url));
12917
12940
  const source = fileURLToPath4(new URL("../../mem7/sqlite-maintenance-worker.ts", import.meta.url));
12918
12941
  const entrypoint = existsSync11(built) ? built : source;
12919
- return new Promise((resolve11) => {
12942
+ return new Promise((resolve12) => {
12920
12943
  const child = execFile(
12921
12944
  process.execPath,
12922
12945
  [...entrypoint.endsWith(".ts") ? ["--import", "tsx"] : [], entrypoint, ...args],
@@ -12924,7 +12947,7 @@ async function validateInHelper(args, allowed) {
12924
12947
  (error, stdout, stderr) => {
12925
12948
  clearInterval(cancel);
12926
12949
  const reason = stderr.trim().split("\n").filter((line) => line && !line.startsWith("(node:") && !line.startsWith("(Use ")).at(-1);
12927
- resolve11({ verified: !error && stdout.trim() === "verified", reason: reason?.slice(0, 512) ?? "validation interrupted" });
12950
+ resolve12({ verified: !error && stdout.trim() === "verified", reason: reason?.slice(0, 512) ?? "validation interrupted" });
12928
12951
  }
12929
12952
  );
12930
12953
  const cancel = setInterval(() => {
@@ -13574,7 +13597,7 @@ function loadSecretsEnvForConfig(configPath2, options = {}) {
13574
13597
  // src/memory/topics-history/background.ts
13575
13598
  init_materials();
13576
13599
  import { existsSync as existsSync7, mkdirSync as mkdirSync8, renameSync as renameSync4, writeFileSync as writeFileSync7 } from "node:fs";
13577
- import { join as join12 } from "node:path";
13600
+ import { join as join12, resolve as resolve8 } from "node:path";
13578
13601
 
13579
13602
  // src/memory/topics-cleaning/runner.ts
13580
13603
  init_materials();
@@ -13874,6 +13897,9 @@ function topicsBackgroundStatus(b, status) {
13874
13897
  writeFileSync7(temp, JSON.stringify({ ...status, updatedAt: Date.now() }));
13875
13898
  renameSync4(temp, join12(root, "status.json"));
13876
13899
  }
13900
+ function fingerprintSources(records, historicalHashes) {
13901
+ return records.filter((r) => historicalHashes.has(r.sha256)).map((r) => [r.path, r.sha256]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
13902
+ }
13877
13903
  async function runTopicsBackground(options) {
13878
13904
  const { binding: b } = options;
13879
13905
  await options.waitForIdle();
@@ -13881,7 +13907,7 @@ async function runTopicsBackground(options) {
13881
13907
  const records = await scanTopics(b.topicsDir);
13882
13908
  const before = mem7StartDate(b);
13883
13909
  const historicalHashes = new Set(records.filter((record) => topicBeforeMem7(record.data.toString("utf8"), record.path, before)).map((record) => record.sha256));
13884
- const fingerprint = digest(canonical({ sources: records.filter((r) => historicalHashes.has(r.sha256)).map((r) => [r.path, r.sha256]), identity: options.identity, dateRules: TOPIC_DATE_RULES_VERSION, mem7StartDate: before }));
13910
+ const fingerprint = digest(canonical({ sources: fingerprintSources(records, historicalHashes), identity: options.identity, dateRules: TOPIC_DATE_RULES_VERSION, mem7StartDate: before, topicsRoot: resolve8(b.topicsDir) }));
13885
13911
  const root = topicsHistoryRoot(b), batch = join12(root, "batches", fingerprint);
13886
13912
  mkdirSync8(batch, { recursive: true });
13887
13913
  const snapshot = join12(batch, "snapshot"), cleaned = join12(batch, "cleaned"), receipt = join12(batch, "receipt.json");
@@ -13925,9 +13951,12 @@ async function runTopicsBackground(options) {
13925
13951
  } catch {
13926
13952
  }
13927
13953
  }
13928
- topicsBackgroundStatus(b, { phase: "complete", sources: records.length, mem7StartDate: before, version: current2.version, ...droppedStatus() });
13929
- const embedded = await augmentVectors(records.length);
13930
- return { status: "complete", version: current2.version, drained: embedded === 0 };
13954
+ if (hasTopicsHistory(b)) {
13955
+ topicsBackgroundStatus(b, { phase: "complete", sources: records.length, mem7StartDate: before, version: current2.version, ...droppedStatus() });
13956
+ const embedded = await augmentVectors(records.length);
13957
+ return { status: "complete", version: current2.version, drained: embedded === 0 };
13958
+ }
13959
+ console.log(`[topics-history] receipt \u5BF9\u5F97\u4E0A\u4F46\u5DF2\u53D1\u5E03\u7D22\u5F15\u7684\u7ED1\u5B9A\u4E0E\u5F53\u524D topics \u6839\u4E0D\u7B26\uFF0C\u4E0D\u65E9\u9000\u2014\u2014\u91CD\u65B0\u5FEB\u7167\u53D1\u5E03`);
13931
13960
  }
13932
13961
  }
13933
13962
  if (!existsSync7(snapshot)) await snapshotTopics(b.topicsDir, snapshot, topicsScope(b), records);
@@ -14024,8 +14053,119 @@ function normalizeUsage(raw) {
14024
14053
  return { prompt_tokens: prompt, completion_tokens: completion, cached_tokens: cached };
14025
14054
  }
14026
14055
 
14056
+ // src/services/adaptive-proxy.ts
14057
+ import { HttpsProxyAgent } from "https-proxy-agent";
14058
+ import { Agent, Client, ProxyAgent, errors } from "undici";
14059
+ var RETRY_PROXY_AFTER_MS = 5e3;
14060
+ var LOCAL_CONNECT_TIMEOUT_MS = 1e3;
14061
+ var unreachableUntil = /* @__PURE__ */ new Map();
14062
+ var failedProxyDials = /* @__PURE__ */ new WeakSet();
14063
+ var dispatchers = /* @__PURE__ */ new Map();
14064
+ var direct = new Agent();
14065
+ function proxyAddress(value) {
14066
+ const bareLoopback = /^(?:localhost\.?|127(?:\.\d{1,3}){3}|\[::1\]):\d+$/i;
14067
+ return new URL(bareLoopback.test(value) ? `http://${value}` : value);
14068
+ }
14069
+ function localProxyKey(url) {
14070
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
14071
+ const host = url.hostname.replace(/\.$/, "");
14072
+ if (host !== "localhost" && host !== "[::1]" && !/^127\./.test(host)) return;
14073
+ return `${host}:${url.port || (url.protocol === "https:" ? 443 : 80)}`;
14074
+ }
14075
+ function proxyUnavailable(key4) {
14076
+ return (unreachableUntil.get(key4) ?? -Infinity) > Date.now();
14077
+ }
14078
+ function markUnavailable(key4) {
14079
+ unreachableUntil.set(key4, Date.now() + RETRY_PROXY_AFTER_MS);
14080
+ }
14081
+ var dialFailureCodes = /* @__PURE__ */ new Set(["ECONNREFUSED", "ETIMEDOUT", "ENETUNREACH", "EHOSTUNREACH", "EADDRNOTAVAIL"]);
14082
+ function isTcpDialFailure(error) {
14083
+ if (error instanceof AggregateError) {
14084
+ return error.errors.length > 0 && error.errors.every(isTcpDialFailure);
14085
+ }
14086
+ const err = error;
14087
+ return err?.syscall === "connect" && dialFailureCodes.has(err.code ?? "");
14088
+ }
14089
+ var AdaptiveProxyDispatcher = class extends ProxyAgent {
14090
+ constructor(uri, key4) {
14091
+ super({
14092
+ uri,
14093
+ proxyTls: { timeout: LOCAL_CONNECT_TIMEOUT_MS },
14094
+ clientFactory(origin, opts) {
14095
+ const { connect } = opts;
14096
+ return new Client(origin, {
14097
+ connect(options, callback) {
14098
+ let tcpConnected = false;
14099
+ const socket = connect(options, (...result) => {
14100
+ const [error] = result;
14101
+ if (error && !tcpConnected && (isTcpDialFailure(error) || error.code === "UND_ERR_CONNECT_TIMEOUT")) {
14102
+ markUnavailable(key4);
14103
+ failedProxyDials.add(error);
14104
+ }
14105
+ callback(...result);
14106
+ });
14107
+ socket.once("connect", () => {
14108
+ tcpConnected = true;
14109
+ });
14110
+ return socket;
14111
+ }
14112
+ });
14113
+ }
14114
+ });
14115
+ this.key = key4;
14116
+ }
14117
+ dispatch(options, handler) {
14118
+ if (!this.closed && !this.destroyed && proxyUnavailable(this.key)) {
14119
+ const headers = options.headers;
14120
+ const keys = !headers ? [] : Array.isArray(headers) ? headers.filter((_, index) => index % 2 === 0) : Symbol.iterator in headers ? Array.from(headers, ([name]) => name) : Object.keys(headers);
14121
+ if (keys.some((name) => name.toLowerCase() === "proxy-authorization")) {
14122
+ throw new errors.InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
14123
+ }
14124
+ return direct.dispatch(options, handler);
14125
+ }
14126
+ let connected = false;
14127
+ const extended = handler;
14128
+ const guarded = {
14129
+ onConnect: (abort) => {
14130
+ connected = true;
14131
+ handler.onConnect?.(abort);
14132
+ },
14133
+ onError: (error) => {
14134
+ if (!connected && failedProxyDials.has(error)) {
14135
+ direct.dispatch(options, handler);
14136
+ } else {
14137
+ handler.onError?.(error);
14138
+ }
14139
+ },
14140
+ onHeaders: handler.onHeaders?.bind(handler),
14141
+ onData: handler.onData?.bind(handler),
14142
+ onComplete: handler.onComplete?.bind(handler),
14143
+ onUpgrade: handler.onUpgrade?.bind(handler),
14144
+ onResponseStarted: handler.onResponseStarted?.bind(handler),
14145
+ onBodySent: handler.onBodySent?.bind(handler),
14146
+ onRequestSent: extended.onRequestSent?.bind(handler)
14147
+ };
14148
+ return super.dispatch(options, guarded);
14149
+ }
14150
+ };
14151
+ function getProxyDispatcher(value) {
14152
+ const raw = value?.trim();
14153
+ if (!raw) return;
14154
+ const cached = dispatchers.get(raw);
14155
+ if (cached) return cached;
14156
+ const url = proxyAddress(raw);
14157
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
14158
+ throw new Error(
14159
+ `\u4E0D\u652F\u6301\u7684\u4EE3\u7406\u534F\u8BAE ${url.protocol}\uFF08\u4EC5 http/https \u53EF\u76F4\u63A5\u4F7F\u7528\uFF1Bsocks5 \u7B49\u8BF7\u5148\u8F6C\u6210 http \u4EE3\u7406\uFF0C\u5982 gost/privoxy\uFF09\uFF1A${raw}`
14160
+ );
14161
+ }
14162
+ const key4 = localProxyKey(url);
14163
+ const dispatcher = key4 ? new AdaptiveProxyDispatcher(url.href, key4) : new ProxyAgent({ uri: url.href });
14164
+ dispatchers.set(raw, dispatcher);
14165
+ return dispatcher;
14166
+ }
14167
+
14027
14168
  // src/services/withRetry.ts
14028
- import { ProxyAgent } from "undici";
14029
14169
  var DEFAULT_MAX_RETRIES = 10;
14030
14170
  var BASE_DELAY_MS = 500;
14031
14171
  var MAX_DELAY_MS = 32e3;
@@ -14034,14 +14174,14 @@ var READ_TIMEOUT_MS = 6e4;
14034
14174
  var FIRST_READ_TIMEOUT_MS = parseInt(process.env.API_TIMEOUT_MS || "", 10) || 6e5;
14035
14175
  var NO_PROGRESS_TIMEOUT_MS = parseInt(process.env.STREAM_NO_PROGRESS_TIMEOUT_MS || "", 10) || 3e5;
14036
14176
  function sleep(ms, signal) {
14037
- return new Promise((resolve11, reject) => {
14177
+ return new Promise((resolve12, reject) => {
14038
14178
  if (signal?.aborted) {
14039
14179
  reject(new DOMException("Aborted", "AbortError"));
14040
14180
  return;
14041
14181
  }
14042
14182
  const timer = setTimeout(() => {
14043
14183
  signal?.removeEventListener("abort", onAbort);
14044
- resolve11();
14184
+ resolve12();
14045
14185
  }, ms);
14046
14186
  const onAbort = () => {
14047
14187
  clearTimeout(timer);
@@ -14100,16 +14240,6 @@ function shouldRetry(status, errorBody) {
14100
14240
  if (errorBody?.includes('"type":"overloaded_error"')) return true;
14101
14241
  return false;
14102
14242
  }
14103
- var proxyAgentCache = /* @__PURE__ */ new Map();
14104
- function getProxyDispatcher(proxyUrl) {
14105
- if (!proxyUrl) return void 0;
14106
- let agent = proxyAgentCache.get(proxyUrl);
14107
- if (!agent) {
14108
- agent = new ProxyAgent({ uri: proxyUrl });
14109
- proxyAgentCache.set(proxyUrl, agent);
14110
- }
14111
- return agent;
14112
- }
14113
14243
  async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, retryPolicy) {
14114
14244
  const configuredRetries = getMaxRetries();
14115
14245
  const maxRetries = retryPolicy?.maxRetries === void 0 ? configuredRetries : Math.min(configuredRetries, Math.max(0, Math.floor(retryPolicy.maxRetries)));
@@ -16031,6 +16161,7 @@ async function classifyTopicPages(provider, model, pages, signal) {
16031
16161
  maxTokens: 16e3,
16032
16162
  temperature: 0,
16033
16163
  disableThinking: true,
16164
+ expressThinkingOff: true,
16034
16165
  signal
16035
16166
  })) {
16036
16167
  if (chunk.type === "text") answer += chunk.text ?? "";