engine7 7.1.147 → 7.1.149

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.
@@ -1315,6 +1315,13 @@ var init_change_feed = __esm({
1315
1315
  }
1316
1316
  });
1317
1317
 
1318
+ // src/mem7/core/state/watermarks.ts
1319
+ var init_watermarks = __esm({
1320
+ "src/mem7/core/state/watermarks.ts"() {
1321
+ "use strict";
1322
+ }
1323
+ });
1324
+
1318
1325
  // src/mem7/core/state/predicates.ts
1319
1326
  var init_predicates = __esm({
1320
1327
  "src/mem7/core/state/predicates.ts"() {
@@ -1347,6 +1354,7 @@ var init_source_store = __esm({
1347
1354
  init_dependencies();
1348
1355
  init_knowledge_history();
1349
1356
  init_read_budget();
1357
+ init_watermarks();
1350
1358
  init_interpretation_impact();
1351
1359
  init_conversation_text();
1352
1360
  }
@@ -1843,6 +1851,7 @@ var init_store = __esm({
1843
1851
  init_change_feed();
1844
1852
  init_dependencies();
1845
1853
  init_tombstones();
1854
+ init_watermarks();
1846
1855
  init_scope();
1847
1856
  init_knowledge_history();
1848
1857
  init_host_turns();
@@ -2199,10 +2199,10 @@ function installSQLiteWriteCapture(db, source) {
2199
2199
  if (db.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
2200
2200
  const exec = db.exec, prepare = db.prepare;
2201
2201
  let active, failed = false, closed = false, reading = false;
2202
- let direct;
2202
+ let direct2;
2203
2203
  const check = () => {
2204
2204
  if (closed) throw new Error("REPLICATION_TRANSACTION_CLOSED");
2205
- direct?.assertOpen();
2205
+ direct2?.assertOpen();
2206
2206
  };
2207
2207
  const wrappedExec = function(sql) {
2208
2208
  check();
@@ -2273,10 +2273,10 @@ function installSQLiteWriteCapture(db, source) {
2273
2273
  db.prepare = checkedPrepare;
2274
2274
  const transaction = (operation) => {
2275
2275
  check();
2276
- if (db.isTransaction) return direct.scope(operation);
2276
+ if (db.isTransaction) return direct2.scope(operation);
2277
2277
  db.exec("BEGIN IMMEDIATE");
2278
2278
  try {
2279
- const result = direct.scope(operation);
2279
+ const result = direct2.scope(operation);
2280
2280
  if (result && typeof result.then === "function") throw new Error("REPLICATION_ASYNC_TRANSACTION");
2281
2281
  db.exec("COMMIT");
2282
2282
  return result;
@@ -2285,10 +2285,10 @@ function installSQLiteWriteCapture(db, source) {
2285
2285
  throw error;
2286
2286
  }
2287
2287
  };
2288
- direct = installAutocommitCapture(db, transaction);
2288
+ direct2 = installAutocommitCapture(db, transaction);
2289
2289
  return {
2290
2290
  assertOpen: check,
2291
- scope: (operation) => direct.scope(operation),
2291
+ scope: (operation) => direct2.scope(operation),
2292
2292
  transaction,
2293
2293
  close() {
2294
2294
  if (closed) return;
@@ -2297,7 +2297,7 @@ function installSQLiteWriteCapture(db, source) {
2297
2297
  source.endCapture(active);
2298
2298
  active = void 0;
2299
2299
  }
2300
- direct.close();
2300
+ direct2.close();
2301
2301
  db.prepare = prepare;
2302
2302
  db.exec = exec;
2303
2303
  closed = true;
@@ -4379,7 +4379,7 @@ function textColumnOf(kind) {
4379
4379
  return "fact";
4380
4380
  }
4381
4381
  }
4382
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, bootAt, schemasCache, Mem7VectorStore;
4382
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
4383
4383
  var init_vector_store = __esm({
4384
4384
  "src/mem7/core/vector-store.ts"() {
4385
4385
  "use strict";
@@ -4413,6 +4413,7 @@ var init_vector_store = __esm({
4413
4413
  RRF_K = 60;
4414
4414
  warnedFts = /* @__PURE__ */ new Set();
4415
4415
  warnedVecIdx = /* @__PURE__ */ new Set();
4416
+ incompatibleIndexSegments = (error) => error instanceof Error && error.message.includes("Index type URL should be present and identical across all segments");
4416
4417
  bootAt = Date.now();
4417
4418
  schemasCache = null;
4418
4419
  Mem7VectorStore = class {
@@ -4582,18 +4583,18 @@ var init_vector_store = __esm({
4582
4583
  * 快照版本——18:46 实测:香港相关 episode 在库、探针 BM25 可召回,线上 hybrid 却
4583
4584
  * 0 命中,时序与连续 3 次 conflict 吻合)。
4584
4585
  */
4585
- async ensureFtsIndexes(kind, tbl) {
4586
+ async ensureFtsIndexes(kind, tbl, indices) {
4586
4587
  const lance = await loadLance();
4587
4588
  if (!lance) return;
4588
- let existing = null;
4589
+ let existing;
4590
+ try {
4591
+ existing = new Set((indices ?? await tbl.listIndices()).filter((index) => index.indexType === "FTS").flatMap((index) => index.columns));
4592
+ } catch (err) {
4593
+ console.warn(`[mem7] FTS index check failed for ${kind}: ${err instanceof Error ? err.message : err}`);
4594
+ return;
4595
+ }
4589
4596
  for (const col of BM25_FIELDS[kind]) {
4590
4597
  try {
4591
- if (existing === null) {
4592
- existing = /* @__PURE__ */ new Set();
4593
- for (const idx of await tbl.listIndices()) {
4594
- if (idx.indexType === "FTS") for (const c of idx.columns) existing.add(c);
4595
- }
4596
- }
4597
4598
  if (existing.has(col)) continue;
4598
4599
  assertRuntimeAuthority(this.stateDir, "WRITE");
4599
4600
  await tbl.createIndex(col, {
@@ -4612,6 +4613,34 @@ var init_vector_store = __esm({
4612
4613
  }
4613
4614
  }
4614
4615
  }
4616
+ /** Called by the idle writer. Intel's all-in-one optimize can append an unreadable ANN delta
4617
+ * to a returned table, even with no new rows. Keep the existing ANN and let queries scan its tail. */
4618
+ async maintainIndexes(kind, canStart) {
4619
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
4620
+ const tbl = await this.table(kind);
4621
+ if (!canStart()) return;
4622
+ let indices;
4623
+ try {
4624
+ indices = await tbl.listIndices();
4625
+ } catch (error) {
4626
+ if (isIntelMac || !incompatibleIndexSegments(error)) throw error;
4627
+ const statsError = await tbl.indexStats("vector_idx").then(() => void 0, (failure) => failure);
4628
+ if (!incompatibleIndexSegments(statsError)) throw error;
4629
+ const lance = await loadLance();
4630
+ if (!lance || typeof lance.Index?.hnswSq !== "function") throw error;
4631
+ if (!canStart()) return;
4632
+ assertRuntimeAuthority(this.stateDir, "WRITE");
4633
+ await tbl.createIndex("vector", { config: lance.Index.hnswSq({ distanceType: "cosine" }), replace: true });
4634
+ if (this.tables.get(kind) === tbl) this.vectorIndexesReady.add(kind);
4635
+ await this.ensureFtsIndexes(kind, tbl, await tbl.listIndices());
4636
+ console.log(`[mem7] ANN \u7D22\u5F15\u517C\u5BB9\u4FEE\u590D\u5B8C\u6210\uFF08${kind}.vector\uFF09`);
4637
+ return "repaired";
4638
+ }
4639
+ if (isIntelMac && indices.some((index) => index.columns.includes("vector"))) return "preserved";
4640
+ if (!canStart()) return;
4641
+ assertRuntimeAuthority(this.stateDir, "WRITE");
4642
+ return tbl.optimize();
4643
+ }
4615
4644
  /**
4616
4645
  * ANN 向量索引(1004 妹妹 review 版):
4617
4646
  * - ★ **HNSW_SQ + distanceType:'cosine'**——距离必须配 cosine,不传默认 L2 与查询不兼容会
@@ -5360,6 +5389,44 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
5360
5389
  }
5361
5390
  });
5362
5391
 
5392
+ // src/mem7/core/state/watermarks.ts
5393
+ function readRetractionSeq(db, scope) {
5394
+ return Number(db.prepare(`SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED}`).get(scope)?.seq ?? 0);
5395
+ }
5396
+ function readRetractionsSince(db, scope, sinceSeq) {
5397
+ return db.prepare(`SELECT event_seq, payload_json FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED} AND event_seq>? ORDER BY event_seq`).all(scope, sinceSeq).map((row) => {
5398
+ const payload = JSON.parse(row.payload_json);
5399
+ const aggregate = !payload.targetKind || payload.targetKind === "source" ? [payload.aggregateId] : [];
5400
+ return { eventSeq: Number(row.event_seq), sourceIds: [.../* @__PURE__ */ new Set([...payload.sourceIds ?? [], ...aggregate])].filter((id) => Boolean(id)) };
5401
+ });
5402
+ }
5403
+ function readSourceSeq(db, scope, sourceId) {
5404
+ const row = db.prepare("SELECT source_seq FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, sourceId);
5405
+ return row && Number.isSafeInteger(row.source_seq) ? Number(row.source_seq) : null;
5406
+ }
5407
+ function deletionHits(db, scope, events, sourceWatermark, sourceSeqs) {
5408
+ return events.some((event) => event.sourceIds.some((id) => {
5409
+ const key4 = JSON.stringify([scope, id]);
5410
+ if (!sourceSeqs.has(key4)) sourceSeqs.set(key4, readSourceSeq(db, scope, id));
5411
+ const seq = sourceSeqs.get(key4);
5412
+ return seq === null || seq <= sourceWatermark;
5413
+ }));
5414
+ }
5415
+ function deletedWithinView(db, scope, sinceSeq, sourceWatermark, cache) {
5416
+ if (!cache.latest.has(scope)) cache.latest.set(scope, readRetractionSeq(db, scope));
5417
+ if (cache.latest.get(scope) <= sinceSeq) return false;
5418
+ const key4 = JSON.stringify([scope, sinceSeq]);
5419
+ if (!cache.events.has(key4)) cache.events.set(key4, readRetractionsSince(db, scope, sinceSeq));
5420
+ return deletionHits(db, scope, cache.events.get(key4), sourceWatermark, cache.sourceSeqs);
5421
+ }
5422
+ var RETRACTED;
5423
+ var init_watermarks = __esm({
5424
+ "src/mem7/core/state/watermarks.ts"() {
5425
+ "use strict";
5426
+ RETRACTED = `kind IN ('evidence.retracted','memory.deleted')`;
5427
+ }
5428
+ });
5429
+
5363
5430
  // src/mem7/core/state/predicates.ts
5364
5431
  function hasReportedAttribution(text2, value, mentions) {
5365
5432
  const ref = value.attributionQuote;
@@ -5473,6 +5540,7 @@ var init_source_store = __esm({
5473
5540
  init_dependencies();
5474
5541
  init_knowledge_history();
5475
5542
  init_read_budget();
5543
+ init_watermarks();
5476
5544
  init_interpretation_impact();
5477
5545
  init_conversation_text();
5478
5546
  SOURCE_SCHEMA = `
@@ -5803,6 +5871,20 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5803
5871
  const row = this.db.prepare("SELECT fact_revision,source_seq,interpreted_seq FROM memory_scopes WHERE scope_id=?").get(scopeId(scope));
5804
5872
  return { factRevision: Number(row?.fact_revision ?? 0), sourceSeq: Number(row?.source_seq ?? 0), interpretedSeq: Number(row?.interpreted_seq ?? 0) };
5805
5873
  }
5874
+ /** Latest deletion or retraction event of the scope; 0 when none ever happened. */
5875
+ retractionSeq(scope) {
5876
+ return readRetractionSeq(this.db, scopeId(scope));
5877
+ }
5878
+ /** Sequence of a source whatever its status. get() hides deleted sources; this does not. */
5879
+ sourceSeqOf(scope, sourceId) {
5880
+ return readSourceSeq(this.db, scopeId(scope), sourceId);
5881
+ }
5882
+ /** A deletion after `sinceSeq` removed a source the node could have seen. One indexed lookup per scope
5883
+ * for the latest deletion, then one event query per (scope, watermark) per cache. */
5884
+ deletedWithinView(scope, sinceSeq, sourceWatermark, cache) {
5885
+ checkMemoryReadBudget();
5886
+ return deletedWithinView(this.db, scopeId(scope), sinceSeq, sourceWatermark, cache);
5887
+ }
5806
5888
  contextRevision(scope) {
5807
5889
  return Number(this.db.prepare("SELECT context_revision FROM memory_scopes WHERE scope_id=?").get(scopeId(scope))?.context_revision ?? 0);
5808
5890
  }
@@ -7022,16 +7104,15 @@ function stripInjectedContext(text2) {
7022
7104
  function escapeRegExp(s) {
7023
7105
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7024
7106
  }
7025
- var SKILL_GATE_HINT_PREFIX, SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
7107
+ var SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
7026
7108
  var init_strip_injected = __esm({
7027
7109
  "src/messages/strip-injected.ts"() {
7028
7110
  "use strict";
7029
- SKILL_GATE_HINT_PREFIX = "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1";
7030
7111
  SYSTEM_REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
7031
7112
  INJECT_SECTION_HEADS = /^(本轮对话|当前情绪状态|当前模式)/;
7032
7113
  KNOWN_INJECTED_TEXT = [
7033
- SKILL_GATE_HINT_PREFIX,
7034
- // skill-gate hint 默认/自定义前缀(1007 现行)
7114
+ "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1",
7115
+ // 旧版 skill-gate 提示前缀,兼容未打标签的历史
7035
7116
  "\u5F00\u53D1\u4EFB\u52A1\u8DEF\u6807\uFF0C\u6309\u573A\u666F\u5BF9\u53F7\u5165\u5EA7",
7036
7117
  // skill-gate hint(0912 老文案,历史 JSONL 兼容)
7037
7118
  "\u3010\u5B9A\u65F6\u5FC3\u8DF3\u3011\u8BF7 read HEARTBEAT.md"
@@ -10259,11 +10340,13 @@ var init_facts = __esm({
10259
10340
  if (subjectIds?.length === 0) return [];
10260
10341
  const placeholders = subjectIds?.map(() => "?").join(",");
10261
10342
  const relations = relationshipPredicates.map((predicate) => `'${predicate}'`).join(",");
10343
+ const key4 = scopeId(scope);
10344
+ const incomingIds = includeIncoming ? subjectIds : void 0;
10262
10345
  return this.readTransaction(() => {
10263
- const slots = this.db.prepare(`SELECT * FROM fact_slots s WHERE scope_id=?${subjectIds ? ` AND (subject_id IN (${placeholders})${includeIncoming ? ` OR (predicate IN (${relations}) AND EXISTS (
10264
- SELECT 1 FROM fact_assertions a WHERE a.scope_id=s.scope_id AND a.slot_id=s.slot_id AND json_extract(a.value_json,'$.entityId') IN (${placeholders})))` : ""})` : ""} ORDER BY slot_id`).all(scopeId(scope), ...subjectIds ?? [], ...includeIncoming ? subjectIds ?? [] : []);
10265
- const assertionsBySlot = this.versionsBySlot(scopeId(scope), knownAtRevision);
10266
- const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(scopeId(scope), knownAtRevision);
10346
+ const slots = this.db.prepare(`SELECT * FROM fact_slots s WHERE scope_id=?${subjectIds ? ` AND (subject_id IN (${placeholders})${incomingIds ? ` OR (predicate IN (${relations}) AND s.slot_id IN (
10347
+ SELECT a.slot_id FROM fact_assertions a WHERE a.scope_id=? AND json_extract(a.value_json,'$.entityId') IN (${placeholders})))` : ""})` : ""} ORDER BY slot_id`).all(key4, ...subjectIds ?? [], ...incomingIds ? [key4, ...incomingIds] : []);
10348
+ const assertionsBySlot = this.versionsBySlot(key4, knownAtRevision);
10349
+ const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(key4, knownAtRevision);
10267
10350
  return slots.map((slot) => ({
10268
10351
  subjectId: slot.subject_id,
10269
10352
  predicate: slot.predicate,
@@ -10899,6 +10982,7 @@ var init_store = __esm({
10899
10982
  init_change_feed();
10900
10983
  init_dependencies();
10901
10984
  init_tombstones();
10985
+ init_watermarks();
10902
10986
  init_scope();
10903
10987
  init_knowledge_history();
10904
10988
  init_host_turns();
@@ -11186,32 +11270,32 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11186
11270
  return { built: !hasStats, ms: Date.now() - started };
11187
11271
  }
11188
11272
  async close() {
11189
- const errors = [];
11273
+ const errors2 = [];
11190
11274
  try {
11191
11275
  this.capture?.close();
11192
11276
  } catch (error) {
11193
- errors.push(error);
11277
+ errors2.push(error);
11194
11278
  }
11195
11279
  try {
11196
11280
  this.db.close();
11197
11281
  } catch (error) {
11198
- errors.push(error);
11282
+ errors2.push(error);
11199
11283
  }
11200
11284
  try {
11201
11285
  await this.vectors?.close();
11202
11286
  } catch (error) {
11203
- errors.push(error);
11287
+ errors2.push(error);
11204
11288
  } finally {
11205
11289
  this.vectors = null;
11206
11290
  }
11207
11291
  try {
11208
11292
  this.releaseRuntimeWriter?.();
11209
11293
  } catch (error) {
11210
- errors.push(error);
11294
+ errors2.push(error);
11211
11295
  } finally {
11212
11296
  this.releaseRuntimeWriter = void 0;
11213
11297
  }
11214
- if (errors.length) throw new AggregateError(errors, "MEM7_CLOSE_FAILED");
11298
+ if (errors2.length) throw new AggregateError(errors2, "MEM7_CLOSE_FAILED");
11215
11299
  }
11216
11300
  // ── memcell 账本 ──────────────────────────────────────────
11217
11301
  insertMemcell(cell) {
@@ -11607,13 +11691,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11607
11691
  /** Interpretation reads entities, facts and confirmed mentions, independently of later chat intake. */
11608
11692
  interpretationReadStamp(scope, sourceIds, excludedPredicates = []) {
11609
11693
  return this.readTransaction(() => {
11610
- const retractions = this.db.prepare("SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND kind IN ('evidence.retracted','memory.deleted')").get(scopeId(scope));
11694
+ const retractions = readRetractionSeq(this.db, scopeId(scope));
11611
11695
  const factRevision = excludedPredicates.length ? this.db.prepare(`SELECT slot_id,revision FROM fact_slots
11612
11696
  WHERE scope_id=? AND predicate NOT IN (${excludedPredicates.map(() => "?").join(",")}) ORDER BY slot_id`).all(scopeId(scope), ...excludedPredicates) : this.facts.revision(scope);
11613
11697
  return JSON.stringify([
11614
11698
  this.entities.revision(scope),
11615
11699
  factRevision,
11616
- retractions.seq,
11700
+ retractions,
11617
11701
  sourceIds.map((id) => this.entities.sourceMentions(scope, id))
11618
11702
  ]);
11619
11703
  });
@@ -11630,7 +11714,7 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11630
11714
  }
11631
11715
  /** History retrieval validates each publication; unrelated received/interpreted prose is not its basis. */
11632
11716
  captureHistoricalReadGuard(scope) {
11633
- const stamp = () => this.db.prepare("SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND kind IN ('evidence.retracted','memory.deleted')").get(scopeId(scope)).seq;
11717
+ const stamp = () => readRetractionSeq(this.db, scopeId(scope));
11634
11718
  const captured = stamp();
11635
11719
  return () => {
11636
11720
  if (stamp() !== captured) throw new MemoryReadSupersededError();
@@ -13939,8 +14023,114 @@ function normalizeUsage(raw) {
13939
14023
  return { prompt_tokens: prompt, completion_tokens: completion, cached_tokens: cached };
13940
14024
  }
13941
14025
 
14026
+ // src/services/adaptive-proxy.ts
14027
+ import { HttpsProxyAgent } from "https-proxy-agent";
14028
+ import { Agent, Client, ProxyAgent, errors } from "undici";
14029
+ var RETRY_PROXY_AFTER_MS = 5e3;
14030
+ var LOCAL_CONNECT_TIMEOUT_MS = 1e3;
14031
+ var unreachableUntil = /* @__PURE__ */ new Map();
14032
+ var failedProxyDials = /* @__PURE__ */ new WeakSet();
14033
+ var dispatchers = /* @__PURE__ */ new Map();
14034
+ var direct = new Agent();
14035
+ function proxyAddress(value) {
14036
+ const bareLoopback = /^(?:localhost\.?|127(?:\.\d{1,3}){3}|\[::1\]):\d+$/i;
14037
+ return new URL(bareLoopback.test(value) ? `http://${value}` : value);
14038
+ }
14039
+ function localProxyKey(url) {
14040
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
14041
+ const host = url.hostname.replace(/\.$/, "");
14042
+ if (host !== "localhost" && host !== "[::1]" && !/^127\./.test(host)) return;
14043
+ return `${host}:${url.port || (url.protocol === "https:" ? 443 : 80)}`;
14044
+ }
14045
+ function proxyUnavailable(key4) {
14046
+ return (unreachableUntil.get(key4) ?? -Infinity) > Date.now();
14047
+ }
14048
+ function markUnavailable(key4) {
14049
+ unreachableUntil.set(key4, Date.now() + RETRY_PROXY_AFTER_MS);
14050
+ }
14051
+ var dialFailureCodes = /* @__PURE__ */ new Set(["ECONNREFUSED", "ETIMEDOUT", "ENETUNREACH", "EHOSTUNREACH", "EADDRNOTAVAIL"]);
14052
+ function isTcpDialFailure(error) {
14053
+ if (error instanceof AggregateError) {
14054
+ return error.errors.length > 0 && error.errors.every(isTcpDialFailure);
14055
+ }
14056
+ const err = error;
14057
+ return err?.syscall === "connect" && dialFailureCodes.has(err.code ?? "");
14058
+ }
14059
+ var AdaptiveProxyDispatcher = class extends ProxyAgent {
14060
+ constructor(uri, key4) {
14061
+ super({
14062
+ uri,
14063
+ proxyTls: { timeout: LOCAL_CONNECT_TIMEOUT_MS },
14064
+ clientFactory(origin, opts) {
14065
+ const { connect } = opts;
14066
+ return new Client(origin, {
14067
+ connect(options, callback) {
14068
+ let tcpConnected = false;
14069
+ const socket = connect(options, (...result) => {
14070
+ const [error] = result;
14071
+ if (error && !tcpConnected && (isTcpDialFailure(error) || error.code === "UND_ERR_CONNECT_TIMEOUT")) {
14072
+ markUnavailable(key4);
14073
+ failedProxyDials.add(error);
14074
+ }
14075
+ callback(...result);
14076
+ });
14077
+ socket.once("connect", () => {
14078
+ tcpConnected = true;
14079
+ });
14080
+ return socket;
14081
+ }
14082
+ });
14083
+ }
14084
+ });
14085
+ this.key = key4;
14086
+ }
14087
+ dispatch(options, handler) {
14088
+ if (!this.closed && !this.destroyed && proxyUnavailable(this.key)) {
14089
+ const headers = options.headers;
14090
+ const keys = !headers ? [] : Array.isArray(headers) ? headers.filter((_, index) => index % 2 === 0) : Symbol.iterator in headers ? Array.from(headers, ([name]) => name) : Object.keys(headers);
14091
+ if (keys.some((name) => name.toLowerCase() === "proxy-authorization")) {
14092
+ throw new errors.InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
14093
+ }
14094
+ return direct.dispatch(options, handler);
14095
+ }
14096
+ let connected = false;
14097
+ const extended = handler;
14098
+ const guarded = {
14099
+ onConnect: (abort) => {
14100
+ connected = true;
14101
+ handler.onConnect?.(abort);
14102
+ },
14103
+ onError: (error) => {
14104
+ if (!connected && failedProxyDials.has(error)) {
14105
+ direct.dispatch(options, handler);
14106
+ } else {
14107
+ handler.onError?.(error);
14108
+ }
14109
+ },
14110
+ onHeaders: handler.onHeaders?.bind(handler),
14111
+ onData: handler.onData?.bind(handler),
14112
+ onComplete: handler.onComplete?.bind(handler),
14113
+ onUpgrade: handler.onUpgrade?.bind(handler),
14114
+ onResponseStarted: handler.onResponseStarted?.bind(handler),
14115
+ onBodySent: handler.onBodySent?.bind(handler),
14116
+ onRequestSent: extended.onRequestSent?.bind(handler)
14117
+ };
14118
+ return super.dispatch(options, guarded);
14119
+ }
14120
+ };
14121
+ function getProxyDispatcher(value) {
14122
+ const raw = value?.trim();
14123
+ if (!raw) return;
14124
+ const cached = dispatchers.get(raw);
14125
+ if (cached) return cached;
14126
+ const url = proxyAddress(raw);
14127
+ const key4 = localProxyKey(url);
14128
+ const dispatcher = key4 ? new AdaptiveProxyDispatcher(url.href, key4) : new ProxyAgent({ uri: url.href });
14129
+ dispatchers.set(raw, dispatcher);
14130
+ return dispatcher;
14131
+ }
14132
+
13942
14133
  // src/services/withRetry.ts
13943
- import { ProxyAgent } from "undici";
13944
14134
  var DEFAULT_MAX_RETRIES = 10;
13945
14135
  var BASE_DELAY_MS = 500;
13946
14136
  var MAX_DELAY_MS = 32e3;
@@ -14015,16 +14205,6 @@ function shouldRetry(status, errorBody) {
14015
14205
  if (errorBody?.includes('"type":"overloaded_error"')) return true;
14016
14206
  return false;
14017
14207
  }
14018
- var proxyAgentCache = /* @__PURE__ */ new Map();
14019
- function getProxyDispatcher(proxyUrl) {
14020
- if (!proxyUrl) return void 0;
14021
- let agent = proxyAgentCache.get(proxyUrl);
14022
- if (!agent) {
14023
- agent = new ProxyAgent({ uri: proxyUrl });
14024
- proxyAgentCache.set(proxyUrl, agent);
14025
- }
14026
- return agent;
14027
- }
14028
14208
  async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, retryPolicy) {
14029
14209
  const configuredRetries = getMaxRetries();
14030
14210
  const maxRetries = retryPolicy?.maxRetries === void 0 ? configuredRetries : Math.min(configuredRetries, Math.max(0, Math.floor(retryPolicy.maxRetries)));