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.
@@ -45,23 +45,23 @@ function validateFileContent(file2) {
45
45
  }
46
46
  if (total !== file2.bytes || !Number.isSafeInteger(total)) throw new Error("PUBLICATION_INVALID_FILE");
47
47
  }
48
- function assertPrivateDirectory(path35) {
49
- const info = lstatSync(path35);
50
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path35) !== resolve(path35) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
48
+ function assertPrivateDirectory(path36) {
49
+ const info = lstatSync(path36);
50
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path36) !== resolve(path36) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
51
51
  throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
52
52
  }
53
- function syncDir(path35) {
53
+ function syncDir(path36) {
54
54
  if (process.platform === "win32") return;
55
- const fd = openSync(path35, constants.O_RDONLY);
55
+ const fd = openSync(path36, constants.O_RDONLY);
56
56
  try {
57
57
  fsyncSync(fd);
58
58
  } finally {
59
59
  closeSync(fd);
60
60
  }
61
61
  }
62
- function preparePrivateDirectory(path35) {
62
+ function preparePrivateDirectory(path36) {
63
63
  const missing = [];
64
- let parent = resolve(path35);
64
+ let parent = resolve(path36);
65
65
  for (; ; ) {
66
66
  try {
67
67
  lstatSync(parent);
@@ -82,10 +82,10 @@ function preparePrivateDirectory(path35) {
82
82
  assertPrivateDirectory(directory2);
83
83
  syncDir(dirname(directory2));
84
84
  }
85
- assertPrivateDirectory(path35);
85
+ assertPrivateDirectory(path36);
86
86
  }
87
- function preparePrivateDatabase(path35) {
88
- for (const file2 of [path35, path35 + "-journal", path35 + "-wal", path35 + "-shm"]) {
87
+ function preparePrivateDatabase(path36) {
88
+ for (const file2 of [path36, path36 + "-journal", path36 + "-wal", path36 + "-shm"]) {
89
89
  try {
90
90
  const info2 = lstatSync(file2);
91
91
  if (!info2.isFile() || info2.isSymbolicLink() || process.platform !== "win32" && (info2.mode & 63 || info2.uid !== process.getuid()))
@@ -95,31 +95,31 @@ function preparePrivateDatabase(path35) {
95
95
  }
96
96
  }
97
97
  try {
98
- const fd = openSync(path35, "wx", 384);
98
+ const fd = openSync(path36, "wx", 384);
99
99
  closeSync(fd);
100
100
  } catch (error) {
101
101
  if (error.code !== "EEXIST") throw error;
102
102
  }
103
- const info = lstatSync(path35);
103
+ const info = lstatSync(path36);
104
104
  if (!info.isFile() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
105
105
  throw new Error("PUBLICATION_PRIVATE_FILE_REQUIRED");
106
- syncDir(dirname(path35));
106
+ syncDir(dirname(path36));
107
107
  }
108
- async function syncDirAsync(path35) {
108
+ async function syncDirAsync(path36) {
109
109
  if (process.platform === "win32") return;
110
- const fd = await open(path35, constants.O_RDONLY);
110
+ const fd = await open(path36, constants.O_RDONLY);
111
111
  try {
112
112
  await fd.sync();
113
113
  } finally {
114
114
  await fd.close();
115
115
  }
116
116
  }
117
- async function exclusivePublish(path35, body, deferDirectorySync = false) {
118
- const temp = join(dirname(path35), "." + randomUUID() + ".partial");
117
+ async function exclusivePublish(path36, body, deferDirectorySync = false) {
118
+ const temp = join(dirname(path36), "." + randomUUID() + ".partial");
119
119
  try {
120
120
  await writeFile(temp, body, { flag: "wx", mode: 384, flush: true });
121
- await link(temp, path35);
122
- if (!deferDirectorySync) await syncDirAsync(dirname(path35));
121
+ await link(temp, path36);
122
+ if (!deferDirectorySync) await syncDirAsync(dirname(path36));
123
123
  } finally {
124
124
  try {
125
125
  await unlink(temp);
@@ -338,8 +338,8 @@ var init_publication_objects = __esm({
338
338
  if (plain.length !== ref.bytes || sha(plain) !== ref.sha256) throw new Error("PUBLICATION_OBJECT_CORRUPT");
339
339
  return plain;
340
340
  }
341
- const path35 = join(this.directory, "chunks", ref.sha256);
342
- const file2 = await open(path35, constants.O_RDONLY | noFollow);
341
+ const path36 = join(this.directory, "chunks", ref.sha256);
342
+ const file2 = await open(path36, constants.O_RDONLY | noFollow);
343
343
  try {
344
344
  const info = await file2.stat();
345
345
  if (!info.isFile() || info.size !== ref.bytes + OVERHEAD || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
@@ -461,8 +461,8 @@ var init_publication_objects = __esm({
461
461
  onBytes?.(bytes2);
462
462
  if (chunks.length % 32 === 0) await setImmediate2();
463
463
  }
464
- const after = fstatSync(fd, { bigint: true }), path35 = lstatSync(source, { bigint: true });
465
- if (path35.isSymbolicLink() || [after, path35].some((s) => ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((k) => s[k] !== before[k])) || BigInt(bytes2) !== before.size) throw new Error("PUBLICATION_SOURCE_CHANGED");
464
+ const after = fstatSync(fd, { bigint: true }), path36 = lstatSync(source, { bigint: true });
465
+ if (path36.isSymbolicLink() || [after, path36].some((s) => ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((k) => s[k] !== before[k])) || BigInt(bytes2) !== before.size) throw new Error("PUBLICATION_SOURCE_CHANGED");
466
466
  return { bytes: bytes2, sha256: digest7.digest("hex"), chunks };
467
467
  } finally {
468
468
  closeSync(fd);
@@ -555,17 +555,17 @@ function assertPrivateStat(stat3, directory2) {
555
555
  if ((directory2 ? !stat3.isDirectory() : !stat3.isFile()) || process.platform !== "win32" && ((stat3.mode & 63) !== 0 || stat3.uid !== process.getuid?.()))
556
556
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
557
557
  }
558
- function privateDirectory(path35) {
558
+ function privateDirectory(path36) {
559
559
  try {
560
- mkdirSync2(path35, { mode: 448 });
560
+ mkdirSync2(path36, { mode: 448 });
561
561
  } catch (error) {
562
562
  if (error.code !== "EEXIST") throw error;
563
563
  }
564
- assertPrivateStat(lstatSync2(path35), true);
564
+ assertPrivateStat(lstatSync2(path36), true);
565
565
  }
566
- function readPrivateFile(path35, maximumBytes = 65536) {
567
- assertPrivateStat(lstatSync2(path35), false);
568
- const fd = openSync2(path35, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
566
+ function readPrivateFile(path36, maximumBytes = 65536) {
567
+ assertPrivateStat(lstatSync2(path36), false);
568
+ const fd = openSync2(path36, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
569
569
  try {
570
570
  const stat3 = fstatSync2(fd);
571
571
  assertPrivateStat(stat3, false);
@@ -585,21 +585,21 @@ var init_key_service_store = __esm({
585
585
  privateDirectory(directory2);
586
586
  this.secrets = join2(directory2, "secrets");
587
587
  privateDirectory(this.secrets);
588
- const path35 = join2(directory2, "control.sqlite");
588
+ const path36 = join2(directory2, "control.sqlite");
589
589
  try {
590
- closeSync2(openSync2(path35, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384));
590
+ closeSync2(openSync2(path36, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384));
591
591
  } catch (error) {
592
592
  if (error.code !== "EEXIST") throw error;
593
593
  }
594
- assertPrivateStat(lstatSync2(path35), false);
594
+ assertPrivateStat(lstatSync2(path36), false);
595
595
  for (const suffix of ["-wal", "-shm", "-journal"]) {
596
596
  try {
597
- assertPrivateStat(lstatSync2(path35 + suffix), false);
597
+ assertPrivateStat(lstatSync2(path36 + suffix), false);
598
598
  } catch (error) {
599
599
  if (error.code !== "ENOENT") throw error;
600
600
  }
601
601
  }
602
- this.db = new DatabaseSync2(path35);
602
+ this.db = new DatabaseSync2(path36);
603
603
  try {
604
604
  this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
605
605
  CREATE TABLE IF NOT EXISTS seat_keys (
@@ -633,16 +633,16 @@ var init_key_service_store = __esm({
633
633
  this.transaction(() => {
634
634
  if (this.db.prepare("SELECT key_id FROM seat_keys WHERE key_id=?").get(identity.keyId))
635
635
  throw new Error("KEY_SERVICE_KEY_EXISTS");
636
- const filename = `${randomUUID2()}.key`, path35 = join2(this.secrets, filename);
636
+ const filename = `${randomUUID2()}.key`, path36 = join2(this.secrets, filename);
637
637
  assertPrivateStat(lstatSync2(this.secrets), true);
638
- const fd = openSync2(path35, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384);
638
+ const fd = openSync2(path36, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384);
639
639
  try {
640
640
  let written = 0;
641
641
  while (written < key4.byteLength) written += writeSync(fd, key4, written, key4.byteLength - written);
642
642
  fsyncSync2(fd);
643
643
  } catch (error) {
644
644
  closeSync2(fd);
645
- unlinkSync(path35);
645
+ unlinkSync(path36);
646
646
  throw error;
647
647
  }
648
648
  closeSync2(fd);
@@ -657,7 +657,7 @@ var init_key_service_store = __esm({
657
657
  try {
658
658
  this.db.prepare("INSERT INTO seat_keys(key_id,identity,secret_file,state) VALUES(?,?,?,'active')").run(identity.keyId, text2, filename);
659
659
  } catch (error) {
660
- unlinkSync(path35);
660
+ unlinkSync(path36);
661
661
  throw error;
662
662
  }
663
663
  });
@@ -770,14 +770,14 @@ var init_key_service_store = __esm({
770
770
  import { randomUUID as randomUUID4, verify as verify2 } from "node:crypto";
771
771
  import { constants as constants3, closeSync as closeSync3, existsSync as existsSync2, fstatSync as fstatSync3, fsyncSync as fsyncSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
772
772
  import { basename, dirname as dirname2, join as join5, resolve as resolve3 } from "node:path";
773
- function assertPrivateDirectory2(path35) {
774
- const stat3 = lstatSync3(path35);
773
+ function assertPrivateDirectory2(path36) {
774
+ const stat3 = lstatSync3(path36);
775
775
  if (!stat3.isDirectory() || stat3.isSymbolicLink() || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
776
776
  }
777
- function readPrivateFile2(path35, maximum) {
778
- const before = lstatSync3(path35);
777
+ function readPrivateFile2(path36, maximum) {
778
+ const before = lstatSync3(path36);
779
779
  if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
780
- const fd = openSync3(path35, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
780
+ const fd = openSync3(path36, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
781
781
  try {
782
782
  if (fstatSync3(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
783
783
  return readFileSync2(fd);
@@ -785,12 +785,12 @@ function readPrivateFile2(path35, maximum) {
785
785
  closeSync3(fd);
786
786
  }
787
787
  }
788
- function writeControl(path35, value) {
789
- const temporary = path35 + "." + randomUUID4() + ".tmp";
788
+ function writeControl(path36, value) {
789
+ const temporary = path36 + "." + randomUUID4() + ".tmp";
790
790
  writeFileSync2(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
791
- renameSync(temporary, path35);
791
+ renameSync(temporary, path36);
792
792
  if (process.platform !== "win32") {
793
- const fd = openSync3(dirname2(path35), "r");
793
+ const fd = openSync3(dirname2(path36), "r");
794
794
  try {
795
795
  fsyncSync3(fd);
796
796
  } finally {
@@ -2101,14 +2101,14 @@ var init_live = __esm({
2101
2101
  }
2102
2102
  /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
2103
2103
  async persistToFile(dotPath, val, atomic = false) {
2104
- const fs25 = await import("node:fs");
2104
+ const fs26 = await import("node:fs");
2105
2105
  const cfgPath = this.current?._configFilePath;
2106
- if (!cfgPath || !fs25.existsSync(cfgPath)) {
2106
+ if (!cfgPath || !fs26.existsSync(cfgPath)) {
2107
2107
  console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
2108
2108
  return false;
2109
2109
  }
2110
2110
  try {
2111
- const raw = JSON.parse(fs25.readFileSync(cfgPath, "utf-8"));
2111
+ const raw = JSON.parse(fs26.readFileSync(cfgPath, "utf-8"));
2112
2112
  const keys = dotPath.split(".");
2113
2113
  let o = raw;
2114
2114
  for (let i = 0; i < keys.length - 1; i++) {
@@ -2118,7 +2118,7 @@ var init_live = __esm({
2118
2118
  o[keys[keys.length - 1]] = val;
2119
2119
  if (atomic) {
2120
2120
  writeConfigAtomic(cfgPath, raw);
2121
- } else fs25.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
2121
+ } else fs26.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
2122
2122
  const lastKey = keys[keys.length - 1].toLowerCase();
2123
2123
  const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
2124
2124
  const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
@@ -3556,7 +3556,7 @@ function textColumnOf(kind) {
3556
3556
  return "fact";
3557
3557
  }
3558
3558
  }
3559
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, bootAt, schemasCache, Mem7VectorStore;
3559
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3560
3560
  var init_vector_store = __esm({
3561
3561
  "src/mem7/core/vector-store.ts"() {
3562
3562
  "use strict";
@@ -3590,6 +3590,7 @@ var init_vector_store = __esm({
3590
3590
  RRF_K = 60;
3591
3591
  warnedFts = /* @__PURE__ */ new Set();
3592
3592
  warnedVecIdx = /* @__PURE__ */ new Set();
3593
+ incompatibleIndexSegments = (error) => error instanceof Error && error.message.includes("Index type URL should be present and identical across all segments");
3593
3594
  bootAt = Date.now();
3594
3595
  schemasCache = null;
3595
3596
  Mem7VectorStore = class {
@@ -3759,18 +3760,18 @@ var init_vector_store = __esm({
3759
3760
  * 快照版本——18:46 实测:香港相关 episode 在库、探针 BM25 可召回,线上 hybrid 却
3760
3761
  * 0 命中,时序与连续 3 次 conflict 吻合)。
3761
3762
  */
3762
- async ensureFtsIndexes(kind, tbl) {
3763
+ async ensureFtsIndexes(kind, tbl, indices) {
3763
3764
  const lance = await loadLance();
3764
3765
  if (!lance) return;
3765
- let existing = null;
3766
+ let existing;
3767
+ try {
3768
+ existing = new Set((indices ?? await tbl.listIndices()).filter((index) => index.indexType === "FTS").flatMap((index) => index.columns));
3769
+ } catch (err) {
3770
+ console.warn(`[mem7] FTS index check failed for ${kind}: ${err instanceof Error ? err.message : err}`);
3771
+ return;
3772
+ }
3766
3773
  for (const col of BM25_FIELDS[kind]) {
3767
3774
  try {
3768
- if (existing === null) {
3769
- existing = /* @__PURE__ */ new Set();
3770
- for (const idx of await tbl.listIndices()) {
3771
- if (idx.indexType === "FTS") for (const c of idx.columns) existing.add(c);
3772
- }
3773
- }
3774
3775
  if (existing.has(col)) continue;
3775
3776
  assertRuntimeAuthority(this.stateDir, "WRITE");
3776
3777
  await tbl.createIndex(col, {
@@ -3789,6 +3790,34 @@ var init_vector_store = __esm({
3789
3790
  }
3790
3791
  }
3791
3792
  }
3793
+ /** Called by the idle writer. Intel's all-in-one optimize can append an unreadable ANN delta
3794
+ * to a returned table, even with no new rows. Keep the existing ANN and let queries scan its tail. */
3795
+ async maintainIndexes(kind, canStart) {
3796
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
3797
+ const tbl = await this.table(kind);
3798
+ if (!canStart()) return;
3799
+ let indices;
3800
+ try {
3801
+ indices = await tbl.listIndices();
3802
+ } catch (error) {
3803
+ if (isIntelMac || !incompatibleIndexSegments(error)) throw error;
3804
+ const statsError = await tbl.indexStats("vector_idx").then(() => void 0, (failure2) => failure2);
3805
+ if (!incompatibleIndexSegments(statsError)) throw error;
3806
+ const lance = await loadLance();
3807
+ if (!lance || typeof lance.Index?.hnswSq !== "function") throw error;
3808
+ if (!canStart()) return;
3809
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3810
+ await tbl.createIndex("vector", { config: lance.Index.hnswSq({ distanceType: "cosine" }), replace: true });
3811
+ if (this.tables.get(kind) === tbl) this.vectorIndexesReady.add(kind);
3812
+ await this.ensureFtsIndexes(kind, tbl, await tbl.listIndices());
3813
+ console.log(`[mem7] ANN \u7D22\u5F15\u517C\u5BB9\u4FEE\u590D\u5B8C\u6210\uFF08${kind}.vector\uFF09`);
3814
+ return "repaired";
3815
+ }
3816
+ if (isIntelMac && indices.some((index) => index.columns.includes("vector"))) return "preserved";
3817
+ if (!canStart()) return;
3818
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3819
+ return tbl.optimize();
3820
+ }
3792
3821
  /**
3793
3822
  * ANN 向量索引(1004 妹妹 review 版):
3794
3823
  * - ★ **HNSW_SQ + distanceType:'cosine'**——距离必须配 cosine,不传默认 L2 与查询不兼容会
@@ -4537,6 +4566,45 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4537
4566
  }
4538
4567
  });
4539
4568
 
4569
+ // src/mem7/core/state/watermarks.ts
4570
+ function readRetractionSeq(db2, scope) {
4571
+ return Number(db2.prepare(`SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED}`).get(scope)?.seq ?? 0);
4572
+ }
4573
+ function readRetractionsSince(db2, scope, sinceSeq) {
4574
+ return db2.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) => {
4575
+ const payload = JSON.parse(row.payload_json);
4576
+ const aggregate = !payload.targetKind || payload.targetKind === "source" ? [payload.aggregateId] : [];
4577
+ return { eventSeq: Number(row.event_seq), sourceIds: [.../* @__PURE__ */ new Set([...payload.sourceIds ?? [], ...aggregate])].filter((id3) => Boolean(id3)) };
4578
+ });
4579
+ }
4580
+ function readSourceSeq(db2, scope, sourceId) {
4581
+ const row = db2.prepare("SELECT source_seq FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, sourceId);
4582
+ return row && Number.isSafeInteger(row.source_seq) ? Number(row.source_seq) : null;
4583
+ }
4584
+ function deletionHits(db2, scope, events, sourceWatermark, sourceSeqs) {
4585
+ return events.some((event2) => event2.sourceIds.some((id3) => {
4586
+ const key4 = JSON.stringify([scope, id3]);
4587
+ if (!sourceSeqs.has(key4)) sourceSeqs.set(key4, readSourceSeq(db2, scope, id3));
4588
+ const seq = sourceSeqs.get(key4);
4589
+ return seq === null || seq <= sourceWatermark;
4590
+ }));
4591
+ }
4592
+ function deletedWithinView(db2, scope, sinceSeq, sourceWatermark, cache) {
4593
+ if (!cache.latest.has(scope)) cache.latest.set(scope, readRetractionSeq(db2, scope));
4594
+ if (cache.latest.get(scope) <= sinceSeq) return false;
4595
+ const key4 = JSON.stringify([scope, sinceSeq]);
4596
+ if (!cache.events.has(key4)) cache.events.set(key4, readRetractionsSince(db2, scope, sinceSeq));
4597
+ return deletionHits(db2, scope, cache.events.get(key4), sourceWatermark, cache.sourceSeqs);
4598
+ }
4599
+ var emptyRetractionCache, RETRACTED;
4600
+ var init_watermarks = __esm({
4601
+ "src/mem7/core/state/watermarks.ts"() {
4602
+ "use strict";
4603
+ emptyRetractionCache = () => ({ latest: /* @__PURE__ */ new Map(), events: /* @__PURE__ */ new Map(), sourceSeqs: /* @__PURE__ */ new Map() });
4604
+ RETRACTED = `kind IN ('evidence.retracted','memory.deleted')`;
4605
+ }
4606
+ });
4607
+
4540
4608
  // src/mem7/core/state/predicates.ts
4541
4609
  function hasReportedAttribution(text2, value, mentions) {
4542
4610
  const ref = value.attributionQuote;
@@ -4650,6 +4718,7 @@ var init_source_store = __esm({
4650
4718
  init_dependencies();
4651
4719
  init_knowledge_history();
4652
4720
  init_read_budget();
4721
+ init_watermarks();
4653
4722
  init_interpretation_impact();
4654
4723
  init_conversation_text();
4655
4724
  SOURCE_SCHEMA = `
@@ -4980,6 +5049,20 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4980
5049
  const row = this.db.prepare("SELECT fact_revision,source_seq,interpreted_seq FROM memory_scopes WHERE scope_id=?").get(scopeId(scope));
4981
5050
  return { factRevision: Number(row?.fact_revision ?? 0), sourceSeq: Number(row?.source_seq ?? 0), interpretedSeq: Number(row?.interpreted_seq ?? 0) };
4982
5051
  }
5052
+ /** Latest deletion or retraction event of the scope; 0 when none ever happened. */
5053
+ retractionSeq(scope) {
5054
+ return readRetractionSeq(this.db, scopeId(scope));
5055
+ }
5056
+ /** Sequence of a source whatever its status. get() hides deleted sources; this does not. */
5057
+ sourceSeqOf(scope, sourceId) {
5058
+ return readSourceSeq(this.db, scopeId(scope), sourceId);
5059
+ }
5060
+ /** A deletion after `sinceSeq` removed a source the node could have seen. One indexed lookup per scope
5061
+ * for the latest deletion, then one event query per (scope, watermark) per cache. */
5062
+ deletedWithinView(scope, sinceSeq, sourceWatermark, cache) {
5063
+ checkMemoryReadBudget();
5064
+ return deletedWithinView(this.db, scopeId(scope), sinceSeq, sourceWatermark, cache);
5065
+ }
4983
5066
  contextRevision(scope) {
4984
5067
  return Number(this.db.prepare("SELECT context_revision FROM memory_scopes WHERE scope_id=?").get(scopeId(scope))?.context_revision ?? 0);
4985
5068
  }
@@ -5512,8 +5595,8 @@ var init_recovery_deletion = __esm({
5512
5595
  const { owners, parents } = this.links(table, row);
5513
5596
  for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
5514
5597
  if (table === "memory_artifact_publications") {
5515
- const medium = text(row, "medium"), path35 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5516
- const identity = medium === "markdown" && path35 ? "file:mem7/" + path35 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash11("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5598
+ const medium = text(row, "medium"), path36 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5599
+ const identity = medium === "markdown" && path36 ? "file:mem7/" + path36 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash11("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5517
5600
  if (identity) {
5518
5601
  const rows = this.artifactPaths.get(identity) ?? [];
5519
5602
  rows.push(row);
@@ -5521,8 +5604,8 @@ var init_recovery_deletion = __esm({
5521
5604
  }
5522
5605
  }
5523
5606
  }
5524
- blocksArtifactPath(kind, path35) {
5525
- const rows = this.artifactPaths.get(kind + ":" + path35);
5607
+ blocksArtifactPath(kind, path36) {
5608
+ const rows = this.artifactPaths.get(kind + ":" + path36);
5526
5609
  return rows?.some((row) => this.blocks("memory_artifact_publications", row));
5527
5610
  }
5528
5611
  blocks(table, row) {
@@ -6199,16 +6282,15 @@ function stripInjectedContext(text2) {
6199
6282
  function escapeRegExp(s) {
6200
6283
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6201
6284
  }
6202
- var SKILL_GATE_HINT_PREFIX, SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
6285
+ var SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
6203
6286
  var init_strip_injected = __esm({
6204
6287
  "src/messages/strip-injected.ts"() {
6205
6288
  "use strict";
6206
- SKILL_GATE_HINT_PREFIX = "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1";
6207
6289
  SYSTEM_REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
6208
6290
  INJECT_SECTION_HEADS = /^(本轮对话|当前情绪状态|当前模式)/;
6209
6291
  KNOWN_INJECTED_TEXT = [
6210
- SKILL_GATE_HINT_PREFIX,
6211
- // skill-gate hint 默认/自定义前缀(1007 现行)
6292
+ "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1",
6293
+ // 旧版 skill-gate 提示前缀,兼容未打标签的历史
6212
6294
  "\u5F00\u53D1\u4EFB\u52A1\u8DEF\u6807\uFF0C\u6309\u573A\u666F\u5BF9\u53F7\u5165\u5EA7",
6213
6295
  // skill-gate hint(0912 老文案,历史 JSONL 兼容)
6214
6296
  "\u3010\u5B9A\u65F6\u5FC3\u8DF3\u3011\u8BF7 read HEARTBEAT.md"
@@ -6542,7 +6624,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6542
6624
  };
6543
6625
  const candidates2 = [];
6544
6626
  const duplicateIds = /* @__PURE__ */ new Set();
6545
- const inside = (path35) => path35 && !isAbsolute2(path35) && path35 !== ".." && !path35.startsWith(`..${sep2}`);
6627
+ const inside = (path36) => path36 && !isAbsolute2(path36) && path36 !== ".." && !path36.startsWith(`..${sep2}`);
6546
6628
  for (const relativePath of input.files) {
6547
6629
  const logical = resolve4(root, relativePath);
6548
6630
  let canonical4;
@@ -6556,10 +6638,10 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6556
6638
  gap("projection_path_unverified");
6557
6639
  continue;
6558
6640
  }
6559
- const path35 = relative2(root, canonical4).replace(/\\/g, "/");
6641
+ const path36 = relative2(root, canonical4).replace(/\\/g, "/");
6560
6642
  const user = `users/${input.scope.ownerId}/`;
6561
6643
  const agent = store.ownerProjectionPath("agents", input.scope.ownerId, input.scope).replace(/\\/g, "/") + "/";
6562
- const kind = path35.startsWith(`${user}episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(path35) ? "episode" : path35.startsWith(`${user}.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(path35) ? "atomic_fact" : path35.startsWith(`${user}.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(path35) ? "foresight" : path35.startsWith(`${agent}.cases/`) && /\/agent_case-\d{4}-\d{2}-\d{2}\.md$/.test(path35) ? "agent_case" : void 0;
6644
+ const kind = path36.startsWith(`${user}episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "episode" : path36.startsWith(`${user}.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "atomic_fact" : path36.startsWith(`${user}.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "foresight" : path36.startsWith(`${agent}.cases/`) && /\/agent_case-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "agent_case" : void 0;
6563
6645
  if (!kind) {
6564
6646
  gap("projection_kind_or_owner_unverified");
6565
6647
  continue;
@@ -6596,9 +6678,9 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6596
6678
  continue;
6597
6679
  }
6598
6680
  const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key4, kind, match[1]);
6599
- const target = join9(store.mem7RootPath(), path35);
6681
+ const target = join9(store.mem7RootPath(), path36);
6600
6682
  if (previous) {
6601
- if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path35 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6683
+ if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path36 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6602
6684
  gap("projection_mapping_conflict");
6603
6685
  continue;
6604
6686
  }
@@ -6614,7 +6696,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6614
6696
  candidates2.push({
6615
6697
  file: canonical4,
6616
6698
  fileHash,
6617
- relativePath: path35,
6699
+ relativePath: path36,
6618
6700
  id: match[1],
6619
6701
  kind,
6620
6702
  parent,
@@ -8096,9 +8178,9 @@ function normalize3(input) {
8096
8178
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
8097
8179
  return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
8098
8180
  }
8099
- function directory(path35) {
8100
- const info = lstatSync6(path35);
8101
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path35) !== resolve5(path35) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
8181
+ function directory(path36) {
8182
+ const info = lstatSync6(path36);
8183
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path36) !== resolve5(path36) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
8102
8184
  throw new Error("REPLICATION_REGISTRATION_INVALID");
8103
8185
  }
8104
8186
  function readRuntimeReplicationRegistration(stateDir, component, key4) {
@@ -8202,10 +8284,10 @@ var init_runtime_replication = __esm({
8202
8284
 
8203
8285
  // src/memory/topics-history/index.ts
8204
8286
  import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
8205
- function parseTopicHistoryPath(path35) {
8206
- if (!path35.startsWith("topics-history://") || path35.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8287
+ function parseTopicHistoryPath(path36) {
8288
+ if (!path36.startsWith("topics-history://") || path36.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8207
8289
  try {
8208
- return JSON.parse(Buffer.from(path35.slice(17), "base64url").toString("utf8"));
8290
+ return JSON.parse(Buffer.from(path36.slice(17), "base64url").toString("utf8"));
8209
8291
  } catch {
8210
8292
  throw new Error("INVALID_HISTORY_REFERENCE");
8211
8293
  }
@@ -9897,11 +9979,13 @@ var init_facts = __esm({
9897
9979
  if (subjectIds?.length === 0) return [];
9898
9980
  const placeholders = subjectIds?.map(() => "?").join(",");
9899
9981
  const relations = relationshipPredicates.map((predicate) => `'${predicate}'`).join(",");
9982
+ const key4 = scopeId(scope);
9983
+ const incomingIds = includeIncoming ? subjectIds : void 0;
9900
9984
  return this.readTransaction(() => {
9901
- 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 (
9902
- 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 ?? [] : []);
9903
- const assertionsBySlot = this.versionsBySlot(scopeId(scope), knownAtRevision);
9904
- const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(scopeId(scope), knownAtRevision);
9985
+ 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 (
9986
+ 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] : []);
9987
+ const assertionsBySlot = this.versionsBySlot(key4, knownAtRevision);
9988
+ const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(key4, knownAtRevision);
9905
9989
  return slots.map((slot) => ({
9906
9990
  subjectId: slot.subject_id,
9907
9991
  predicate: slot.predicate,
@@ -10146,23 +10230,23 @@ var init_facts = __esm({
10146
10230
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
10147
10231
  }
10148
10232
  for (const [index, evidence] of proposal.evidence.entries()) {
10149
- const path35 = `evidence[${index}]`;
10150
- if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path35} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
10233
+ const path36 = `evidence[${index}]`;
10234
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path36} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
10151
10235
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
10152
10236
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
10153
10237
  AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
10154
- if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path35}.sourceId \u2014 \u672C\u6C60\u8BFB\u4E0D\u5230\u8FD9\u6761\u6765\u6E90\uFF08\u4E0D\u5B58\u5728\u3001\u5DF2\u5220\u9664\u6216\u5DF2\u6709\u65B0\u7248\u672C\uFF09\uFF1B\u7528 memory_get({source_id}) \u6838\u5BF9\u5E76\u590D\u5236\u771F\u5B9E\u6765\u6E90 ID`);
10155
- if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path35}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
10238
+ if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path36}.sourceId \u2014 \u672C\u6C60\u8BFB\u4E0D\u5230\u8FD9\u6761\u6765\u6E90\uFF08\u4E0D\u5B58\u5728\u3001\u5DF2\u5220\u9664\u6216\u5DF2\u6709\u65B0\u7248\u672C\uFF09\uFF1B\u7528 memory_get({source_id}) \u6838\u5BF9\u5E76\u590D\u5236\u771F\u5B9E\u6765\u6E90 ID`);
10239
+ if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path36}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
10156
10240
  if (!Number.isSafeInteger(evidence.start) || !Number.isSafeInteger(evidence.end) || evidence.start < 0 || evidence.end <= evidence.start || evidence.end > source.text.length || source.text.slice(evidence.start, evidence.end) !== evidence.quote) {
10157
10241
  const count = occurrences(source.text, evidence.quote);
10158
- throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path35}.quote \u2014 \u5F15\u6587\u5FC5\u987B\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587\uFF08\u539F\u6587\u957F ${source.text.length}\uFF09\uFF1B\u7528 memory_get({source_id}) \u590D\u5236\u539F\u53E5\uFF0C\u4E0D\u8981\u6539\u5199` : `INVALID_EVIDENCE_SPAN: ${path35} \u2014 \u5F15\u6587\u5728\u539F\u6587\u4E2D\u51FA\u73B0 ${count} \u6B21\uFF0C\u8BF7\u7ED9\u51C6\u786E\u7684\u90A3\u4E00\u5904 start/end\uFF08UTF-16 \u4E0B\u6807\uFF0C\u539F\u6587\u957F ${source.text.length}\uFF09`);
10242
+ throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path36}.quote \u2014 \u5F15\u6587\u5FC5\u987B\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587\uFF08\u539F\u6587\u957F ${source.text.length}\uFF09\uFF1B\u7528 memory_get({source_id}) \u590D\u5236\u539F\u53E5\uFF0C\u4E0D\u8981\u6539\u5199` : `INVALID_EVIDENCE_SPAN: ${path36} \u2014 \u5F15\u6587\u5728\u539F\u6587\u4E2D\u51FA\u73B0 ${count} \u6B21\uFF0C\u8BF7\u7ED9\u51C6\u786E\u7684\u90A3\u4E00\u5904 start/end\uFF08UTF-16 \u4E0B\u6807\uFF0C\u539F\u6587\u957F ${source.text.length}\uFF09`);
10159
10243
  }
10160
- if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path35}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
10244
+ if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path36}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
10161
10245
  const relationValue = proposal.value;
10162
10246
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
10163
10247
  throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED: attribution=reported \u65F6 claimKind \u987B\u4E3A reported_statement\uFF0C\u4E14 attributionQuote \u5FC5\u987B\u662F\u539F\u8BDD\u91CC\u9010\u5B57\u7684\u8F6C\u8FF0\u53E5\uFF08\u5982\u300C\u67D0\u67D0\u8BF4\uFF1A\u300D\uFF09");
10164
10248
  }
10165
- const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path35} \u7684\u4F5C\u8005/\u89D2\u8272\u4E0E claimKind=${proposal.claimKind} \u4E0D\u7B26\uFF08\u6765\u6E90 role=${source.role}, originClass=${source.origin_class}\uFF09 \u2014 \u7528\u6237\u539F\u8BDD\u914D user_statement\u3001\u5DE5\u5177\u7ED3\u679C\u914D tool_observation\u3001\u8F6C\u8FF0\u4ED6\u4EBA\u914D reported_statement\u3001\u4F60\u81EA\u5DF1\u8BF4\u7684\u8BDD\u914D agent_statement\uFF1B\u6362\u5339\u914D\u7684\u6765\u6E90\u6216\u6539 claimKind`);
10249
+ const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path36} \u7684\u4F5C\u8005/\u89D2\u8272\u4E0E claimKind=${proposal.claimKind} \u4E0D\u7B26\uFF08\u6765\u6E90 role=${source.role}, originClass=${source.origin_class}\uFF09 \u2014 \u7528\u6237\u539F\u8BDD\u914D user_statement\u3001\u5DE5\u5177\u7ED3\u679C\u914D tool_observation\u3001\u8F6C\u8FF0\u4ED6\u4EBA\u914D reported_statement\u3001\u4F60\u81EA\u5DF1\u8BF4\u7684\u8BDD\u914D agent_statement\uFF1B\u6362\u5339\u914D\u7684\u6765\u6E90\u6216\u6539 claimKind`);
10166
10250
  if (proposal.claimKind !== "inference") {
10167
10251
  if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
10168
10252
  if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
@@ -10543,6 +10627,7 @@ var init_store = __esm({
10543
10627
  init_change_feed();
10544
10628
  init_dependencies();
10545
10629
  init_tombstones();
10630
+ init_watermarks();
10546
10631
  init_scope();
10547
10632
  init_knowledge_history();
10548
10633
  init_host_turns();
@@ -10830,32 +10915,32 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10830
10915
  return { built: !hasStats, ms: Date.now() - started };
10831
10916
  }
10832
10917
  async close() {
10833
- const errors2 = [];
10918
+ const errors3 = [];
10834
10919
  try {
10835
10920
  this.capture?.close();
10836
10921
  } catch (error) {
10837
- errors2.push(error);
10922
+ errors3.push(error);
10838
10923
  }
10839
10924
  try {
10840
10925
  this.db.close();
10841
10926
  } catch (error) {
10842
- errors2.push(error);
10927
+ errors3.push(error);
10843
10928
  }
10844
10929
  try {
10845
10930
  await this.vectors?.close();
10846
10931
  } catch (error) {
10847
- errors2.push(error);
10932
+ errors3.push(error);
10848
10933
  } finally {
10849
10934
  this.vectors = null;
10850
10935
  }
10851
10936
  try {
10852
10937
  this.releaseRuntimeWriter?.();
10853
10938
  } catch (error) {
10854
- errors2.push(error);
10939
+ errors3.push(error);
10855
10940
  } finally {
10856
10941
  this.releaseRuntimeWriter = void 0;
10857
10942
  }
10858
- if (errors2.length) throw new AggregateError(errors2, "MEM7_CLOSE_FAILED");
10943
+ if (errors3.length) throw new AggregateError(errors3, "MEM7_CLOSE_FAILED");
10859
10944
  }
10860
10945
  // ── memcell 账本 ──────────────────────────────────────────
10861
10946
  insertMemcell(cell) {
@@ -11152,13 +11237,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11152
11237
  const version = expectedVersion ?? this.dependencies.version(scope, kind, id3);
11153
11238
  this.dependencies.assertCurrent(scope, kind, id3, version);
11154
11239
  const digest7 = createHash20("sha256").update(content.trim()).digest("hex");
11155
- const path35 = relative3(this.root, file2).replace(/\\/g, "/");
11240
+ const path36 = relative3(this.root, file2).replace(/\\/g, "/");
11156
11241
  const previous = this.db.prepare("SELECT version,digest,path FROM memory_projection_entries WHERE scope_id=? AND kind=? AND entry_id=?").get(scopeId(scope), kind, id3);
11157
- if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path35)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
11242
+ if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path36)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
11158
11243
  this.db.prepare(`INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)
11159
11244
  ON CONFLICT(scope_id,kind,entry_id) DO UPDATE SET path=excluded.path,version=excluded.version,digest=excluded.digest
11160
- WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path35, version, digest7);
11161
- this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path35, markdown: content.trim() });
11245
+ WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path36, version, digest7);
11246
+ this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path36, markdown: content.trim() });
11162
11247
  });
11163
11248
  }
11164
11249
  projectionMatches(scope, kind, id3, file2, content) {
@@ -11251,13 +11336,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11251
11336
  /** Interpretation reads entities, facts and confirmed mentions, independently of later chat intake. */
11252
11337
  interpretationReadStamp(scope, sourceIds, excludedPredicates = []) {
11253
11338
  return this.readTransaction(() => {
11254
- 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));
11339
+ const retractions = readRetractionSeq(this.db, scopeId(scope));
11255
11340
  const factRevision = excludedPredicates.length ? this.db.prepare(`SELECT slot_id,revision FROM fact_slots
11256
11341
  WHERE scope_id=? AND predicate NOT IN (${excludedPredicates.map(() => "?").join(",")}) ORDER BY slot_id`).all(scopeId(scope), ...excludedPredicates) : this.facts.revision(scope);
11257
11342
  return JSON.stringify([
11258
11343
  this.entities.revision(scope),
11259
11344
  factRevision,
11260
- retractions.seq,
11345
+ retractions,
11261
11346
  sourceIds.map((id3) => this.entities.sourceMentions(scope, id3))
11262
11347
  ]);
11263
11348
  });
@@ -11274,7 +11359,7 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11274
11359
  }
11275
11360
  /** History retrieval validates each publication; unrelated received/interpreted prose is not its basis. */
11276
11361
  captureHistoricalReadGuard(scope) {
11277
- 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;
11362
+ const stamp = () => readRetractionSeq(this.db, scopeId(scope));
11278
11363
  const captured = stamp();
11279
11364
  return () => {
11280
11365
  if (stamp() !== captured) throw new MemoryReadSupersededError();
@@ -11355,8 +11440,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11355
11440
  };
11356
11441
  }
11357
11442
  unscopedProjectionMatches(ownerId, kind, id3, file2, content) {
11358
- const path35 = relative3(this.root, file2).replace(/\\/g, "/");
11359
- const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path35);
11443
+ const path36 = relative3(this.root, file2).replace(/\\/g, "/");
11444
+ const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path36);
11360
11445
  if (mappings.length) {
11361
11446
  if (mappings.length !== 1) return false;
11362
11447
  const scope = this.sources.scope(mappings[0].scope_id);
@@ -14760,6 +14845,159 @@ var init_router = __esm({
14760
14845
  }
14761
14846
  });
14762
14847
 
14848
+ // src/services/adaptive-proxy.ts
14849
+ var adaptive_proxy_exports = {};
14850
+ __export(adaptive_proxy_exports, {
14851
+ createProxySocketAgent: () => createProxySocketAgent,
14852
+ getProxyDispatcher: () => getProxyDispatcher,
14853
+ isAdaptiveProxy: () => isAdaptiveProxy
14854
+ });
14855
+ import net from "node:net";
14856
+ import tls from "node:tls";
14857
+ import { HttpsProxyAgent } from "https-proxy-agent";
14858
+ import { Agent as Agent2, Client, ProxyAgent, errors as errors2 } from "undici";
14859
+ function proxyAddress(value) {
14860
+ const bareLoopback = /^(?:localhost\.?|127(?:\.\d{1,3}){3}|\[::1\]):\d+$/i;
14861
+ return new URL(bareLoopback.test(value) ? `http://${value}` : value);
14862
+ }
14863
+ function localProxyKey(url) {
14864
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
14865
+ const host = url.hostname.replace(/\.$/, "");
14866
+ if (host !== "localhost" && host !== "[::1]" && !/^127\./.test(host)) return;
14867
+ return `${host}:${url.port || (url.protocol === "https:" ? 443 : 80)}`;
14868
+ }
14869
+ function isAdaptiveProxy(proxy) {
14870
+ return localProxyKey(proxyAddress(proxy.trim())) !== void 0;
14871
+ }
14872
+ function proxyUnavailable(key4) {
14873
+ return (unreachableUntil.get(key4) ?? -Infinity) > Date.now();
14874
+ }
14875
+ function markUnavailable(key4) {
14876
+ unreachableUntil.set(key4, Date.now() + RETRY_PROXY_AFTER_MS);
14877
+ }
14878
+ function isTcpDialFailure(error) {
14879
+ if (error instanceof AggregateError) {
14880
+ return error.errors.length > 0 && error.errors.every(isTcpDialFailure);
14881
+ }
14882
+ const err = error;
14883
+ return err?.syscall === "connect" && dialFailureCodes.has(err.code ?? "");
14884
+ }
14885
+ function getProxyDispatcher(value) {
14886
+ const raw = value?.trim();
14887
+ if (!raw) return;
14888
+ const cached2 = dispatchers.get(raw);
14889
+ if (cached2) return cached2;
14890
+ const url = proxyAddress(raw);
14891
+ const key4 = localProxyKey(url);
14892
+ const dispatcher = key4 ? new AdaptiveProxyDispatcher(url.href, key4) : new ProxyAgent({ uri: url.href });
14893
+ dispatchers.set(raw, dispatcher);
14894
+ return dispatcher;
14895
+ }
14896
+ function createProxySocketAgent(value) {
14897
+ const url = proxyAddress(value.trim());
14898
+ const key4 = localProxyKey(url);
14899
+ return key4 ? new AdaptiveProxySocketAgent(url, key4) : new HttpsProxyAgent(url);
14900
+ }
14901
+ var RETRY_PROXY_AFTER_MS, LOCAL_CONNECT_TIMEOUT_MS, unreachableUntil, failedProxyDials, dispatchers, direct, dialFailureCodes, AdaptiveProxyDispatcher, AdaptiveProxySocketAgent;
14902
+ var init_adaptive_proxy = __esm({
14903
+ "src/services/adaptive-proxy.ts"() {
14904
+ "use strict";
14905
+ RETRY_PROXY_AFTER_MS = 5e3;
14906
+ LOCAL_CONNECT_TIMEOUT_MS = 1e3;
14907
+ unreachableUntil = /* @__PURE__ */ new Map();
14908
+ failedProxyDials = /* @__PURE__ */ new WeakSet();
14909
+ dispatchers = /* @__PURE__ */ new Map();
14910
+ direct = new Agent2();
14911
+ dialFailureCodes = /* @__PURE__ */ new Set(["ECONNREFUSED", "ETIMEDOUT", "ENETUNREACH", "EHOSTUNREACH", "EADDRNOTAVAIL"]);
14912
+ AdaptiveProxyDispatcher = class extends ProxyAgent {
14913
+ constructor(uri, key4) {
14914
+ super({
14915
+ uri,
14916
+ proxyTls: { timeout: LOCAL_CONNECT_TIMEOUT_MS },
14917
+ clientFactory(origin, opts) {
14918
+ const { connect } = opts;
14919
+ return new Client(origin, {
14920
+ connect(options, callback) {
14921
+ let tcpConnected = false;
14922
+ const socket = connect(options, (...result) => {
14923
+ const [error] = result;
14924
+ if (error && !tcpConnected && (isTcpDialFailure(error) || error.code === "UND_ERR_CONNECT_TIMEOUT")) {
14925
+ markUnavailable(key4);
14926
+ failedProxyDials.add(error);
14927
+ }
14928
+ callback(...result);
14929
+ });
14930
+ socket.once("connect", () => {
14931
+ tcpConnected = true;
14932
+ });
14933
+ return socket;
14934
+ }
14935
+ });
14936
+ }
14937
+ });
14938
+ this.key = key4;
14939
+ }
14940
+ dispatch(options, handler) {
14941
+ if (!this.closed && !this.destroyed && proxyUnavailable(this.key)) {
14942
+ const headers = options.headers;
14943
+ const keys = !headers ? [] : Array.isArray(headers) ? headers.filter((_, index) => index % 2 === 0) : Symbol.iterator in headers ? Array.from(headers, ([name]) => name) : Object.keys(headers);
14944
+ if (keys.some((name) => name.toLowerCase() === "proxy-authorization")) {
14945
+ throw new errors2.InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
14946
+ }
14947
+ return direct.dispatch(options, handler);
14948
+ }
14949
+ let connected = false;
14950
+ const extended = handler;
14951
+ const guarded = {
14952
+ onConnect: (abort) => {
14953
+ connected = true;
14954
+ handler.onConnect?.(abort);
14955
+ },
14956
+ onError: (error) => {
14957
+ if (!connected && failedProxyDials.has(error)) {
14958
+ direct.dispatch(options, handler);
14959
+ } else {
14960
+ handler.onError?.(error);
14961
+ }
14962
+ },
14963
+ onHeaders: handler.onHeaders?.bind(handler),
14964
+ onData: handler.onData?.bind(handler),
14965
+ onComplete: handler.onComplete?.bind(handler),
14966
+ onUpgrade: handler.onUpgrade?.bind(handler),
14967
+ onResponseStarted: handler.onResponseStarted?.bind(handler),
14968
+ onBodySent: handler.onBodySent?.bind(handler),
14969
+ onRequestSent: extended.onRequestSent?.bind(handler)
14970
+ };
14971
+ return super.dispatch(options, guarded);
14972
+ }
14973
+ };
14974
+ AdaptiveProxySocketAgent = class extends HttpsProxyAgent {
14975
+ constructor(url, key4) {
14976
+ super(url);
14977
+ this.key = key4;
14978
+ }
14979
+ async connect(req, opts) {
14980
+ if (!proxyUnavailable(this.key)) {
14981
+ try {
14982
+ return await super.connect(req, opts);
14983
+ } catch (error) {
14984
+ if (!isTcpDialFailure(error)) throw error;
14985
+ markUnavailable(this.key);
14986
+ if (req.destroyed) throw error;
14987
+ }
14988
+ }
14989
+ if (!opts.secureEndpoint) return net.connect({ ...opts, path: void 0 });
14990
+ const { host, servername } = opts;
14991
+ return tls.connect({
14992
+ ...opts,
14993
+ path: void 0,
14994
+ servername: servername ?? (host && !net.isIP(host) ? host : void 0)
14995
+ });
14996
+ }
14997
+ };
14998
+ }
14999
+ });
15000
+
14763
15001
  // src/calendar/dispatches.ts
14764
15002
  var dispatches_exports = {};
14765
15003
  __export(dispatches_exports, {
@@ -14820,10 +15058,10 @@ function installSQLiteWriteCapture(db2, source) {
14820
15058
  if (db2.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
14821
15059
  const exec = db2.exec, prepare = db2.prepare;
14822
15060
  let active, failed = false, closed = false, reading = false;
14823
- let direct;
15061
+ let direct2;
14824
15062
  const check = () => {
14825
15063
  if (closed) throw new Error("REPLICATION_TRANSACTION_CLOSED");
14826
- direct?.assertOpen();
15064
+ direct2?.assertOpen();
14827
15065
  };
14828
15066
  const wrappedExec = function(sql) {
14829
15067
  check();
@@ -14894,10 +15132,10 @@ function installSQLiteWriteCapture(db2, source) {
14894
15132
  db2.prepare = checkedPrepare;
14895
15133
  const transaction = (operation) => {
14896
15134
  check();
14897
- if (db2.isTransaction) return direct.scope(operation);
15135
+ if (db2.isTransaction) return direct2.scope(operation);
14898
15136
  db2.exec("BEGIN IMMEDIATE");
14899
15137
  try {
14900
- const result = direct.scope(operation);
15138
+ const result = direct2.scope(operation);
14901
15139
  if (result && typeof result.then === "function") throw new Error("REPLICATION_ASYNC_TRANSACTION");
14902
15140
  db2.exec("COMMIT");
14903
15141
  return result;
@@ -14906,10 +15144,10 @@ function installSQLiteWriteCapture(db2, source) {
14906
15144
  throw error;
14907
15145
  }
14908
15146
  };
14909
- direct = installAutocommitCapture(db2, transaction);
15147
+ direct2 = installAutocommitCapture(db2, transaction);
14910
15148
  return {
14911
15149
  assertOpen: check,
14912
- scope: (operation) => direct.scope(operation),
15150
+ scope: (operation) => direct2.scope(operation),
14913
15151
  transaction,
14914
15152
  close() {
14915
15153
  if (closed) return;
@@ -14918,7 +15156,7 @@ function installSQLiteWriteCapture(db2, source) {
14918
15156
  source.endCapture(active);
14919
15157
  active = void 0;
14920
15158
  }
14921
- direct.close();
15159
+ direct2.close();
14922
15160
  db2.prepare = prepare;
14923
15161
  db2.exec = exec;
14924
15162
  closed = true;
@@ -15417,8 +15655,8 @@ var init_graph_store = __esm({
15417
15655
  function graphNodeReadable(node, scope, allowGuarded = true) {
15418
15656
  return graphScopeId(node) === scope && !["needs_revalidation", "deleted"].includes(String(node.data.evidenceState)) && (allowGuarded || node.data.automationState !== "pending_execution_guard");
15419
15657
  }
15420
- function graphMemoryReferences(node) {
15421
- const refs = Array.isArray(node.data.memoryDependencies) ? structuredClone(node.data.memoryDependencies) : [];
15658
+ function graphOwnEvidence(node) {
15659
+ const refs = [];
15422
15660
  if (Array.isArray(node.data.sourceRefs)) for (const source of node.data.sourceRefs) refs.push({
15423
15661
  parentKind: "source",
15424
15662
  parentId: source.sourceId,
@@ -15438,6 +15676,9 @@ function graphMemoryReferences(node) {
15438
15676
  });
15439
15677
  return refs;
15440
15678
  }
15679
+ function graphMemoryReferences(node) {
15680
+ return [...Array.isArray(node.data.memoryDependencies) ? structuredClone(node.data.memoryDependencies) : [], ...graphOwnEvidence(node)];
15681
+ }
15441
15682
  function assertGraphMemoryReferences(memory, nodes, forGeneration = false) {
15442
15683
  const validate = createGraphMemoryValidator(memory);
15443
15684
  if (memory) memory.readTransaction(() => validate(nodes, forGeneration));
@@ -15445,6 +15686,8 @@ function assertGraphMemoryReferences(memory, nodes, forGeneration = false) {
15445
15686
  }
15446
15687
  function createGraphMemoryValidator(memory) {
15447
15688
  const checkedRefs = /* @__PURE__ */ new Set(), checkedSources = /* @__PURE__ */ new Set(), checkedRelations = /* @__PURE__ */ new Set();
15689
+ const scopes = /* @__PURE__ */ new Map();
15690
+ const retractions = emptyRetractionCache();
15448
15691
  return (nodes, forGeneration = false) => {
15449
15692
  const checkedScopes = /* @__PURE__ */ new Set();
15450
15693
  for (const node of nodes) {
@@ -15454,7 +15697,11 @@ function createGraphMemoryValidator(memory) {
15454
15697
  if (refs.length) throw new Error("GRAPH_MEMORY_SCOPE_REQUIRED");
15455
15698
  continue;
15456
15699
  }
15457
- const scope = memory?.sources.scope(scopeKey);
15700
+ let scope = scopes.get(scopeKey);
15701
+ if (scope === void 0) {
15702
+ scope = memory?.sources.scope(scopeKey) ?? null;
15703
+ scopes.set(scopeKey, scope);
15704
+ }
15458
15705
  if (!memory || !scope) throw new Error("GRAPH_MEMORY_READ_GUARD_REQUIRED");
15459
15706
  const unseen = [...new Map(refs.map((ref) => [JSON.stringify([scopeKey, ref]), ref])).entries()].filter(([key4]) => !checkedRefs.has(key4));
15460
15707
  memory.dependencies.assertReferences(scope, unseen.map(([, ref]) => ref));
@@ -15476,6 +15723,9 @@ function createGraphMemoryValidator(memory) {
15476
15723
  if (!record2 || record2.groundingState !== "current" || record2.recordVersion !== relation.recordVersion || record2.current !== relation.current) throw new Error("STALE_GRAPH_RELATIONSHIP");
15477
15724
  checkedRelations.add(relationshipKey);
15478
15725
  }
15726
+ if (typeof node.data.retractionWatermark === "number" && typeof node.data.sourceWatermark === "number" && memory.sources.deletedWithinView(scope, node.data.retractionWatermark, node.data.sourceWatermark, retractions)) {
15727
+ throw new Error("STALE_GRAPH_RETRACTION");
15728
+ }
15479
15729
  if (forGeneration && !checkedScopes.has(scopeKey)) {
15480
15730
  const snapshot = memory.sources.snapshot(scope);
15481
15731
  if (snapshot.interpretedSeq < snapshot.sourceSeq) throw new Error("SOURCE_INTERPRETATION_PENDING");
@@ -15489,6 +15739,7 @@ var init_graph_reads = __esm({
15489
15739
  "src/memory/proactive/graph-reads.ts"() {
15490
15740
  "use strict";
15491
15741
  init_graph_store();
15742
+ init_watermarks();
15492
15743
  graphScopeId = (node) => String(node.data.scopeId || "legacy");
15493
15744
  }
15494
15745
  });
@@ -15804,21 +16055,15 @@ CREATE TABLE graph_redirects (
15804
16055
  }
15805
16056
  }
15806
16057
  }
15807
- replace(node) {
15808
- const scope = String(node.data.scopeId ?? "legacy");
15809
- this.db.prepare("DELETE FROM graph_dependencies WHERE child_id=?").run(node.id);
15810
- const insert = this.db.prepare("INSERT OR IGNORE INTO graph_dependencies VALUES (?,?,?,?,?,?,?,?)");
16058
+ /** Rows the node must own. A repeated key keeps its first entry, as INSERT OR IGNORE did. */
16059
+ desiredRows(node, scope) {
16060
+ const rows = /* @__PURE__ */ new Map();
16061
+ const add = (kind, parentId, version, slotId, slotRevision, role) => {
16062
+ const key4 = JSON.stringify([scope, kind, parentId, role]);
16063
+ if (!rows.has(key4)) rows.set(key4, [scope, node.id, kind, parentId, version, slotId, slotRevision, role]);
16064
+ };
15811
16065
  const memoryRefs = Array.isArray(node.data.memoryDependencies) ? node.data.memoryDependencies : [];
15812
- for (const ref of memoryRefs) insert.run(
15813
- scope,
15814
- node.id,
15815
- ref.parentKind,
15816
- ref.parentId,
15817
- ref.parentVersion,
15818
- ref.slotId ?? null,
15819
- ref.slotRevision ?? null,
15820
- ref.role
15821
- );
16066
+ for (const ref of memoryRefs) add(ref.parentKind, ref.parentId, ref.parentVersion, ref.slotId ?? null, ref.slotRevision ?? null, ref.role);
15822
16067
  for (const parent of node.groundedIn) {
15823
16068
  let parentId = parent;
15824
16069
  let row = this.db.prepare("SELECT semantic_revision,data FROM nodes WHERE id=?").get(parentId);
@@ -15841,12 +16086,10 @@ CREATE TABLE graph_redirects (
15841
16086
  }
15842
16087
  const parentScope = String(JSON.parse(row.data).scopeId ?? "legacy");
15843
16088
  if (parentScope !== scope) throw new Error("GRAPH_DEPENDENCY_SCOPE_MISMATCH");
15844
- insert.run(scope, node.id, "node", parentId, row.semantic_revision, null, null, "supports");
16089
+ add("node", parentId, Number(row.semantic_revision), null, null, "supports");
15845
16090
  }
15846
16091
  const sources = Array.isArray(node.data.sourceRefs) ? node.data.sourceRefs : [];
15847
- for (const source of sources) insert.run(
15848
- scope,
15849
- node.id,
16092
+ for (const source of sources) add(
15850
16093
  "source",
15851
16094
  source.sourceId,
15852
16095
  source.sourceVersion,
@@ -15857,9 +16100,36 @@ CREATE TABLE graph_redirects (
15857
16100
  const facts = Array.isArray(node.data.basisRefs) ? node.data.basisRefs : [];
15858
16101
  for (const fact of facts) {
15859
16102
  if (fact.scopeId !== scope) throw new Error("GRAPH_FACT_SCOPE_MISMATCH");
15860
- insert.run(scope, node.id, "fact", fact.assertionId, fact.assertionVersion, fact.slotId, fact.slotRevision, "supports");
15861
- insert.run(scope, node.id, "entity", fact.subjectId, fact.subjectVersion ?? 1, null, null, "supports");
16103
+ add("fact", fact.assertionId, fact.assertionVersion, fact.slotId, fact.slotRevision, "supports");
16104
+ add("entity", fact.subjectId, fact.subjectVersion ?? 1, null, null, "supports");
16105
+ }
16106
+ return rows;
16107
+ }
16108
+ /** Brings the node's rows in line with its data. Unchanged rows are not written. */
16109
+ replace(node, options = {}) {
16110
+ const scope = String(node.data.scopeId ?? "legacy");
16111
+ const rows = this.desiredRows(node, scope);
16112
+ const insert = this.db.prepare("INSERT OR IGNORE INTO graph_dependencies VALUES (?,?,?,?,?,?,?,?)");
16113
+ if (options.fresh) {
16114
+ for (const row of rows.values()) insert.run(...row);
16115
+ return;
16116
+ }
16117
+ const remove = this.db.prepare("DELETE FROM graph_dependencies WHERE rowid=?");
16118
+ const update = this.db.prepare("UPDATE graph_dependencies SET parent_version=?, slot_id=?, slot_revision=? WHERE rowid=?");
16119
+ const present = /* @__PURE__ */ new Set();
16120
+ for (const row of this.db.prepare(`SELECT rowid rid, scope_id, parent_kind, parent_id, role, parent_version, slot_id, slot_revision
16121
+ FROM graph_dependencies WHERE child_id=?`).all(node.id)) {
16122
+ const key4 = JSON.stringify([row.scope_id, row.parent_kind, row.parent_id, row.role]);
16123
+ const want = rows.get(key4);
16124
+ if (!want) {
16125
+ remove.run(row.rid);
16126
+ continue;
16127
+ }
16128
+ present.add(key4);
16129
+ if (want[4] !== row.parent_version || want[5] !== row.slot_id || want[6] !== row.slot_revision)
16130
+ update.run(want[4], want[5], want[6], row.rid);
15862
16131
  }
16132
+ for (const [key4, row] of rows) if (!present.has(key4)) insert.run(...row);
15863
16133
  }
15864
16134
  /** parent_id 的全部失效别名:graph_redirects 图上与它同属一个重定向分量的全部 id
15865
16135
  * (双向多跳——按存活目标查要够到记旧 id 的存量行,按旧 id 查也要够到解析
@@ -16023,11 +16293,27 @@ var persistence_exports = {};
16023
16293
  __export(persistence_exports, {
16024
16294
  PROACTIVE_SCHEMA_VERSION: () => PROACTIVE_SCHEMA_VERSION,
16025
16295
  Persistence: () => Persistence,
16026
- normalizeToUtcIso: () => normalizeToUtcIso
16296
+ normalizeToUtcIso: () => normalizeToUtcIso,
16297
+ readableNodesSql: () => readableNodesSql
16027
16298
  });
16028
16299
  import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
16029
16300
  import { mkdirSync as mkdirSync11 } from "node:fs";
16030
16301
  import { basename as basename3, dirname as dirname7, resolve as resolve6 } from "node:path";
16302
+ function graphNodeFromRow(row) {
16303
+ return {
16304
+ id: row.id,
16305
+ type: row.type,
16306
+ data: JSON.parse(row.data),
16307
+ reasoning: row.reasoning ?? void 0,
16308
+ groundedIn: JSON.parse(row.grounded_in ?? "[]"),
16309
+ createdAt: row.created_at,
16310
+ lastAccessed: row.last_accessed,
16311
+ accessCount: row.access_count
16312
+ };
16313
+ }
16314
+ function readableNodesSql(allowGuarded) {
16315
+ return `SELECT * FROM nodes WHERE ${NODE_SCOPE}=? AND ${NODE_READABLE}=1${allowGuarded ? "" : ` AND ${NODE_UNGUARDED}=0`} ORDER BY rowid`;
16316
+ }
16031
16317
  function rowToAction(r) {
16032
16318
  return {
16033
16319
  id: r.id,
@@ -16061,7 +16347,7 @@ function normalizeToUtcIso(s) {
16061
16347
  if (!s) return s;
16062
16348
  return parseWall(s);
16063
16349
  }
16064
- var PROACTIVE_SCHEMA_VERSION, graphSubscribers, SCHEMA2, Persistence;
16350
+ var PROACTIVE_SCHEMA_VERSION, graphSubscribers, NODE_SCOPE, NODE_READABLE, NODE_UNGUARDED, SCHEMA2, Persistence;
16065
16351
  var init_persistence = __esm({
16066
16352
  "src/memory/proactive/persistence.ts"() {
16067
16353
  "use strict";
@@ -16084,6 +16370,9 @@ var init_persistence = __esm({
16084
16370
  init_runtime_lock();
16085
16371
  PROACTIVE_SCHEMA_VERSION = 12;
16086
16372
  graphSubscribers = /* @__PURE__ */ new Map();
16373
+ NODE_SCOPE = "COALESCE(NULLIF(json_extract(data,'$.scopeId'),''),'legacy')";
16374
+ NODE_READABLE = `CASE WHEN COALESCE(json_extract(data,'$.evidenceState'),'undefined') IN ('needs_revalidation','deleted') THEN 0 ELSE 1 END`;
16375
+ NODE_UNGUARDED = "CASE WHEN json_extract(data,'$.automationState')='pending_execution_guard' THEN 1 ELSE 0 END";
16087
16376
  SCHEMA2 = `
16088
16377
  CREATE TABLE IF NOT EXISTS nodes (
16089
16378
  id TEXT PRIMARY KEY,
@@ -16240,6 +16529,13 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16240
16529
  name: "rebuildable-person-node-index",
16241
16530
  apply: (db2) => db2.exec(PERSON_INDEX_SCHEMA)
16242
16531
  }]);
16532
+ if (!registration && !options.replication) {
16533
+ try {
16534
+ this.db.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_readable ON nodes(${NODE_SCOPE}, ${NODE_READABLE}, ${NODE_UNGUARDED})`);
16535
+ } catch (error) {
16536
+ console.warn(`[proactive] readable-node index not built, reads fall back to a scan: ${error.message}`);
16537
+ }
16538
+ }
16243
16539
  this.db.exec("PRAGMA journal_mode=WAL");
16244
16540
  this.intentRuns = new IntentRunStore(this.db, (fn) => this.withMemoryTransaction(fn), () => this.loadNodes(), () => this.loadEdges(), memory);
16245
16541
  this.projection = new ProjectionInbox(this.db);
@@ -16400,6 +16696,10 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16400
16696
  ownsIntentRun(run, now2 = Date.now()) {
16401
16697
  return this.intentRuns.owns(run, now2);
16402
16698
  }
16699
+ /** A worker opens its graph before its memory store exists; the first store to arrive stays for the life of the handle. */
16700
+ attachMemory(memory) {
16701
+ if (!this.memory) this.memory = memory;
16702
+ }
16403
16703
  withMemoryTransaction(operation) {
16404
16704
  return this.memory ? this.memory.transaction(() => this.transaction(operation)) : this.transaction(operation);
16405
16705
  }
@@ -16445,15 +16745,21 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16445
16745
  loadGraphSnapshot(ids) {
16446
16746
  const read2 = () => {
16447
16747
  if (!ids) return { nodes: this.loadNodes(), edges: this.loadEdges(), revision: this.graphRevision() };
16448
- const keys = [...new Set(ids)];
16449
- const nodes = keys.map((id3) => this.loadNodeById(id3)).filter((node) => node !== void 0);
16450
- const edges = new Map(keys.flatMap((id3) => this.loadIncidentEdges(id3)).map((edge) => [edgeKey(edge.source, edge.target, edge.edgeType), edge]));
16451
- return { nodes, edges: [...edges.values()], revision: this.graphRevision() };
16748
+ const keys = new Set(ids);
16749
+ if (!keys.size) return { nodes: [], edges: [], revision: this.graphRevision() };
16750
+ const rows = this.db.prepare(`SELECT n.* FROM json_each(?) AS requested
16751
+ JOIN nodes n ON n.id=requested.value ORDER BY requested.key`).iterate(JSON.stringify([...keys]));
16752
+ const nodes = Array.from(rows, graphNodeFromRow);
16753
+ let edges = this.loadIncidentEdgesFor(keys);
16754
+ if (new Set(edges.map((edge) => edgeKey(edge.source, edge.target, edge.edgeType))).size !== edges.length) {
16755
+ edges = [...new Map([...keys].flatMap((id3) => this.loadIncidentEdges(id3)).map((edge) => [edgeKey(edge.source, edge.target, edge.edgeType), edge])).values()];
16756
+ }
16757
+ return { nodes, edges, revision: this.graphRevision() };
16452
16758
  };
16453
16759
  return this.readGraphTransaction(read2);
16454
16760
  }
16455
16761
  readGraphTransaction(read2) {
16456
- if (this.inTransaction) return read2();
16762
+ if (this.db.isTransaction) return read2();
16457
16763
  this.db.exec("BEGIN");
16458
16764
  try {
16459
16765
  const snapshot = read2();
@@ -16471,36 +16777,23 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16471
16777
  values.push(type);
16472
16778
  }
16473
16779
  if (scope !== void 0) {
16474
- clauses.push("COALESCE(NULLIF(json_extract(data,'$.scopeId'),''),'legacy')=?");
16780
+ clauses.push(`${NODE_SCOPE}=?`);
16475
16781
  values.push(scope);
16476
16782
  }
16477
- const rows = this.db.prepare("SELECT * FROM nodes" + (clauses.length ? " WHERE " + clauses.join(" AND ") : "")).iterate(...values);
16478
- return Array.from(rows, (r) => ({
16479
- id: r.id,
16480
- type: r.type,
16481
- data: JSON.parse(r.data),
16482
- reasoning: r.reasoning ?? void 0,
16483
- groundedIn: JSON.parse(r.grounded_in ?? "[]"),
16484
- createdAt: r.created_at,
16485
- lastAccessed: r.last_accessed,
16486
- accessCount: r.access_count
16487
- }));
16783
+ const rows = this.db.prepare("SELECT * FROM nodes" + (clauses.length ? " WHERE " + clauses.join(" AND ") : "") + (scope === void 0 ? "" : " ORDER BY rowid")).iterate(...values);
16784
+ return Array.from(rows, graphNodeFromRow);
16488
16785
  }
16489
16786
  /** 单行读(1016:touched-row 校验用——旧 updateNodeRow 为找前像整表 loadNodes(),
16490
16787
  * 每次 touch/更新都全库扫一遍,是图写路径的隐藏大头) */
16491
16788
  loadNodeById(id3) {
16492
- const r = this.db.prepare("SELECT * FROM nodes WHERE id=?").get(id3);
16493
- if (!r) return void 0;
16494
- return {
16495
- id: r.id,
16496
- type: r.type,
16497
- data: JSON.parse(r.data),
16498
- reasoning: r.reasoning ?? void 0,
16499
- groundedIn: JSON.parse(r.grounded_in ?? "[]"),
16500
- createdAt: r.created_at,
16501
- lastAccessed: r.last_accessed,
16502
- accessCount: r.access_count
16503
- };
16789
+ const row = this.db.prepare("SELECT * FROM nodes WHERE id=?").get(id3);
16790
+ return row ? graphNodeFromRow(row) : void 0;
16791
+ }
16792
+ /** The scope's nodes whose state is readable, in the order a full scope read has. With the index only those
16793
+ * rows are touched; without it the same conditions scan the table. */
16794
+ loadReadableNodes(scope, allowGuarded) {
16795
+ const rows = this.db.prepare(readableNodesSql(allowGuarded)).iterate(scope);
16796
+ return Array.from(rows, graphNodeFromRow);
16504
16797
  }
16505
16798
  /** 定向邻接边读(1016:basis/删除校验用,替代全表 loadEdges) */
16506
16799
  loadIncidentEdges(id3) {
@@ -16527,8 +16820,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16527
16820
  loadEdgesAmong(ids) {
16528
16821
  if (!ids.size) return [];
16529
16822
  const keys = JSON.stringify([...ids]);
16530
- const rows = this.db.prepare(`SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?))
16531
- AND target IN (SELECT value FROM json_each(?))`).iterate(keys, keys);
16823
+ const rows = this.db.prepare(`WITH visible(value) AS MATERIALIZED (SELECT value FROM json_each(?))
16824
+ SELECT e.* FROM edges e JOIN visible s ON e.source = s.value JOIN visible t ON e.target = t.value
16825
+ ORDER BY e.source,e.target,e.edge_type`).iterate(keys);
16532
16826
  return Array.from(rows, (row) => ({
16533
16827
  source: row.source,
16534
16828
  target: row.target,
@@ -16537,6 +16831,29 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16537
16831
  createdAt: row.created_at
16538
16832
  }));
16539
16833
  }
16834
+ /** Every edge with an end in the set, in one query; one lookup per node costs one round trip each. */
16835
+ loadIncidentEdgesFor(ids) {
16836
+ if (!ids.size) return [];
16837
+ const keys = JSON.stringify([...ids]);
16838
+ const rows = this.db.prepare(`WITH members(value) AS MATERIALIZED (SELECT value FROM json_each(?))
16839
+ SELECT source, target, edge_type, weight, created_at FROM edges WHERE source IN (SELECT value FROM members)
16840
+ UNION
16841
+ SELECT source, target, edge_type, weight, created_at FROM edges WHERE target IN (SELECT value FROM members)`).all(keys);
16842
+ return rows.map((r) => ({
16843
+ source: r.source,
16844
+ target: r.target,
16845
+ edgeType: r.edge_type,
16846
+ weight: r.weight,
16847
+ createdAt: r.created_at
16848
+ }));
16849
+ }
16850
+ /** Nodes of these types in the scope with no edge at either end, named by the indexes alone. */
16851
+ isolatedNodeIds(types, scope) {
16852
+ return this.db.prepare(`SELECT n.id FROM nodes n WHERE n.type IN (SELECT value FROM json_each(?))
16853
+ ${scope === void 0 ? "" : `AND (${NODE_SCOPE}=? OR json_type(n.data,'$.scopeId') NOT IN ('text','null'))`}
16854
+ AND NOT EXISTS (SELECT 1 FROM edges e WHERE e.source = n.id)
16855
+ AND NOT EXISTS (SELECT 1 FROM edges e WHERE e.target = n.id)`).all(...scope === void 0 ? [JSON.stringify(types)] : [JSON.stringify(types), scope]).map((row) => String(row.id));
16856
+ }
16540
16857
  // === 图:写(GraphStore 镜像调用) ===
16541
16858
  insertNode(node) {
16542
16859
  this.transaction(() => {
@@ -16720,7 +17037,7 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16720
17037
  "INSERT INTO edges (source, target, edge_type, weight, created_at) VALUES (?,?,?,?,?)"
16721
17038
  );
16722
17039
  for (const e of edges) insEdge.run(e.source, e.target, e.edgeType, e.weight, e.createdAt);
16723
- for (const node of nodes) this.dependencies.replace(node);
17040
+ for (const node of nodes) this.dependencies.replace(node, { fresh: true });
16724
17041
  this.personNodes.rebuild(nodes);
16725
17042
  this.noteGraphChange();
16726
17043
  });
@@ -17206,8 +17523,22 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
17206
17523
  /** Fast invalidation runs before any model work and commits with the consumer receipt. */
17207
17524
  invalidateMemoryEvent(event2) {
17208
17525
  const affected = new Set(this.dependencies.affected(event2));
17209
- const updated = [];
17210
17526
  const scope = this.memory?.sources.scope(event2.scopeId);
17527
+ if (event2.kind === "evidence.retracted" || event2.kind === "memory.deleted") {
17528
+ if (!this.memory) {
17529
+ console.error(`[proactive] ${event2.kind} ${event2.eventId} (scope ${event2.scopeId}, seq ${event2.eventSeq}) reached a graph handle without a memory store: nodes that carry only a watermark for the deleted source keep their state, and the retained-source check is skipped. Attach the Mem7Store to this Persistence.`);
17530
+ } else if (scope) {
17531
+ const deleted = [...new Set(event2.targetKind && event2.targetKind !== "source" ? event2.sourceIds : [...event2.sourceIds, event2.aggregateId])].filter(Boolean);
17532
+ if (deleted.length) {
17533
+ const seqs = deleted.map((id3) => this.memory.sources.sourceSeqOf(scope, id3));
17534
+ const known = seqs.filter((seq) => seq !== null);
17535
+ const oldest = known.length < seqs.length ? 0 : Math.min(...known);
17536
+ for (const row of this.db.prepare(`SELECT id FROM nodes WHERE json_extract(data,'$.scopeId')=? AND json_extract(data,'$.sourceWatermark')>=?
17537
+ AND COALESCE(json_extract(data,'$.retractionWatermark'),0)<?`).all(event2.scopeId, oldest, event2.eventSeq)) affected.add(row.id);
17538
+ }
17539
+ }
17540
+ }
17541
+ const updated = [];
17211
17542
  if (event2.kind === "memory.deleted" && scope && this.memory) {
17212
17543
  this.memory.readTransaction(() => {
17213
17544
  for (const node of this.loadNodes().filter((node2) => node2.data.scopeId === event2.scopeId)) {
@@ -17355,7 +17686,7 @@ __export(voice_chat_tts_daemon_exports, {
17355
17686
  stopTtsDaemon: () => stopTtsDaemon
17356
17687
  });
17357
17688
  import { spawn } from "child_process";
17358
- import net from "net";
17689
+ import net2 from "net";
17359
17690
  import path13 from "path";
17360
17691
  import fs10 from "fs";
17361
17692
  function _log(msg2) {
@@ -17363,7 +17694,7 @@ function _log(msg2) {
17363
17694
  }
17364
17695
  function _healthOnce() {
17365
17696
  return new Promise((resolve13) => {
17366
- const sock = net.connect(SOCK_PATH);
17697
+ const sock = net2.connect(SOCK_PATH);
17367
17698
  sock.setTimeout(2e3);
17368
17699
  sock.on("connect", () => {
17369
17700
  sock.write(JSON.stringify({ action: "health" }) + "\n");
@@ -17416,9 +17747,6 @@ async function startTtsDaemon(warmupCfg) {
17416
17747
  _log(`spawning ${script}`);
17417
17748
  const env = {
17418
17749
  ...process.env,
17419
- // 显式注入代理(dashscope SDK 不自动读系统代理)
17420
- HTTP_PROXY: process.env.HTTP_PROXY || "http://127.0.0.1:7892",
17421
- HTTPS_PROXY: process.env.HTTPS_PROXY || "http://127.0.0.1:7892",
17422
17750
  TTS_DAEMON_SOCK: SOCK_PATH,
17423
17751
  ...warmupCfg?.apiKey ? { ALIYUN_API_KEY: warmupCfg.apiKey } : {},
17424
17752
  ...warmupCfg?.model ? { TTS_MODEL: warmupCfg.model } : {},
@@ -17488,7 +17816,6 @@ __export(withRetry_exports, {
17488
17816
  getRetryDelay: () => getRetryDelay,
17489
17817
  readWithTimeout: () => readWithTimeout
17490
17818
  });
17491
- import { ProxyAgent } from "undici";
17492
17819
  function sleep2(ms, signal) {
17493
17820
  return new Promise((resolve13, reject) => {
17494
17821
  if (signal?.aborted) {
@@ -17556,15 +17883,6 @@ function shouldRetry(status, errorBody) {
17556
17883
  if (errorBody?.includes('"type":"overloaded_error"')) return true;
17557
17884
  return false;
17558
17885
  }
17559
- function getProxyDispatcher(proxyUrl) {
17560
- if (!proxyUrl) return void 0;
17561
- let agent = proxyAgentCache.get(proxyUrl);
17562
- if (!agent) {
17563
- agent = new ProxyAgent({ uri: proxyUrl });
17564
- proxyAgentCache.set(proxyUrl, agent);
17565
- }
17566
- return agent;
17567
- }
17568
17886
  async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, retryPolicy) {
17569
17887
  const configuredRetries = getMaxRetries();
17570
17888
  const maxRetries = retryPolicy?.maxRetries === void 0 ? configuredRetries : Math.min(configuredRetries, Math.max(0, Math.floor(retryPolicy.maxRetries)));
@@ -17614,17 +17932,17 @@ async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, r
17614
17932
  }
17615
17933
  if (attempt <= maxRetries && shouldRetry(status, errorBody)) {
17616
17934
  const retryAfter = response.headers.get("retry-after");
17617
- let delay = getRetryDelay(attempt, retryAfter);
17935
+ let delay2 = getRetryDelay(attempt, retryAfter);
17618
17936
  if (retryPolicy?.maxDelayMs !== void 0) {
17619
17937
  const retryAt = retryAfter && !/^\d+$/.test(retryAfter.trim()) ? Date.parse(retryAfter) : NaN;
17620
- if (Number.isFinite(retryAt)) delay = Math.max(0, retryAt - Date.now());
17621
- if (delay > retryPolicy.maxDelayMs) return response;
17938
+ if (Number.isFinite(retryAt)) delay2 = Math.max(0, retryAt - Date.now());
17939
+ if (delay2 > retryPolicy.maxDelayMs) return response;
17622
17940
  }
17623
17941
  console.log(
17624
- `[${label}] Retry ${attempt}/${maxRetries} after HTTP ${status}, delay=${delay}ms, url=${url}` + (retryAfter ? `, retry-after=${retryAfter}` : "") + (errorBody ? `, body=${errorBody}` : "")
17942
+ `[${label}] Retry ${attempt}/${maxRetries} after HTTP ${status}, delay=${delay2}ms, url=${url}` + (retryAfter ? `, retry-after=${retryAfter}` : "") + (errorBody ? `, body=${errorBody}` : "")
17625
17943
  );
17626
- yield { type: "api_retry", reason: `HTTP ${status}`, attempt, maxRetries, delayMs: delay, status };
17627
- await sleep2(delay, userSignal);
17944
+ yield { type: "api_retry", reason: `HTTP ${status}`, attempt, maxRetries, delayMs: delay2, status };
17945
+ await sleep2(delay2, userSignal);
17628
17946
  continue;
17629
17947
  }
17630
17948
  return response;
@@ -17641,10 +17959,10 @@ async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, r
17641
17959
  console.log(
17642
17960
  `[${label}] Timeout retry ${attempt}/${maxRetries} (${timeout}ms)`
17643
17961
  );
17644
- const delay = getRetryDelay(attempt);
17645
- if (retryPolicy?.maxDelayMs !== void 0 && delay > retryPolicy.maxDelayMs) throw err;
17646
- yield { type: "api_retry", reason: "timeout", attempt, maxRetries, delayMs: delay };
17647
- await sleep2(delay, init.signal ?? void 0);
17962
+ const delay2 = getRetryDelay(attempt);
17963
+ if (retryPolicy?.maxDelayMs !== void 0 && delay2 > retryPolicy.maxDelayMs) throw err;
17964
+ yield { type: "api_retry", reason: "timeout", attempt, maxRetries, delayMs: delay2 };
17965
+ await sleep2(delay2, init.signal ?? void 0);
17648
17966
  continue;
17649
17967
  }
17650
17968
  throw new Error(
@@ -17653,14 +17971,14 @@ async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, r
17653
17971
  }
17654
17972
  lastError = err;
17655
17973
  if (isConnectionError(err) && attempt <= maxRetries) {
17656
- const delay = getRetryDelay(attempt);
17657
- if (retryPolicy?.maxDelayMs !== void 0 && delay > retryPolicy.maxDelayMs) throw err;
17974
+ const delay2 = getRetryDelay(attempt);
17975
+ if (retryPolicy?.maxDelayMs !== void 0 && delay2 > retryPolicy.maxDelayMs) throw err;
17658
17976
  const cause = err?.cause ? ` cause=${err.cause.code ?? err.cause.message}` : "";
17659
17977
  console.log(
17660
- `[${label}] Connection error retry ${attempt}/${maxRetries}: ${err.message}${cause}, delay=${delay}ms`
17978
+ `[${label}] Connection error retry ${attempt}/${maxRetries}: ${err.message}${cause}, delay=${delay2}ms`
17661
17979
  );
17662
- yield { type: "api_retry", reason: `connection: ${err.message}`, attempt, maxRetries, delayMs: delay };
17663
- await sleep2(delay, init.signal ?? void 0);
17980
+ yield { type: "api_retry", reason: `connection: ${err.message}`, attempt, maxRetries, delayMs: delay2 };
17981
+ await sleep2(delay2, init.signal ?? void 0);
17664
17982
  continue;
17665
17983
  }
17666
17984
  throw err;
@@ -17702,10 +18020,11 @@ function readWithTimeout(reader, timeoutMs, signal) {
17702
18020
  if (onAbort) signal?.removeEventListener("abort", onAbort);
17703
18021
  });
17704
18022
  }
17705
- var DEFAULT_MAX_RETRIES, BASE_DELAY_MS, MAX_DELAY_MS, DEFAULT_TIMEOUT_MS, READ_TIMEOUT_MS, FIRST_READ_TIMEOUT_MS, NO_PROGRESS_TIMEOUT_MS, proxyAgentCache;
18023
+ var DEFAULT_MAX_RETRIES, BASE_DELAY_MS, MAX_DELAY_MS, DEFAULT_TIMEOUT_MS, READ_TIMEOUT_MS, FIRST_READ_TIMEOUT_MS, NO_PROGRESS_TIMEOUT_MS;
17706
18024
  var init_withRetry = __esm({
17707
18025
  "src/services/withRetry.ts"() {
17708
18026
  "use strict";
18027
+ init_adaptive_proxy();
17709
18028
  DEFAULT_MAX_RETRIES = 10;
17710
18029
  BASE_DELAY_MS = 500;
17711
18030
  MAX_DELAY_MS = 32e3;
@@ -17713,7 +18032,6 @@ var init_withRetry = __esm({
17713
18032
  READ_TIMEOUT_MS = 6e4;
17714
18033
  FIRST_READ_TIMEOUT_MS = parseInt(process.env.API_TIMEOUT_MS || "", 10) || 6e5;
17715
18034
  NO_PROGRESS_TIMEOUT_MS = parseInt(process.env.STREAM_NO_PROGRESS_TIMEOUT_MS || "", 10) || 3e5;
17716
- proxyAgentCache = /* @__PURE__ */ new Map();
17717
18035
  }
17718
18036
  });
17719
18037
 
@@ -17750,26 +18068,26 @@ __export(paths_exports, {
17750
18068
  isAutoMemPath: () => isAutoMemPath,
17751
18069
  setMemoryDirOverride: () => setMemoryDirOverride
17752
18070
  });
17753
- import { join as join28, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve10 } from "node:path";
18071
+ import { join as join23, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve8 } from "node:path";
17754
18072
  function setMemoryDirOverride(dir) {
17755
18073
  _overrideMemoryDir = dir;
17756
18074
  }
17757
18075
  function getAutoMemPath(workspace) {
17758
- const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve10(workspace, _overrideMemoryDir) : join28(workspace, AUTO_MEM_DIRNAME);
18076
+ const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve8(workspace, _overrideMemoryDir) : join23(workspace, AUTO_MEM_DIRNAME);
17759
18077
  const normalized = normalize5(dir);
17760
18078
  return (normalized + sep4).normalize("NFC");
17761
18079
  }
17762
18080
  function getAutoMemEntrypoint(workspace) {
17763
- return join28(getAutoMemPath(workspace), ENTRYPOINT_NAME);
18081
+ return join23(getAutoMemPath(workspace), ENTRYPOINT_NAME);
17764
18082
  }
17765
18083
  function isAutoMemPath(absolutePath, workspace) {
17766
18084
  const normalizedPath = normalize5(absolutePath);
17767
18085
  return normalizedPath.startsWith(getAutoMemPath(workspace));
17768
18086
  }
17769
18087
  async function ensureMemoryDirExists(memoryDir) {
17770
- const fs25 = await import("node:fs");
18088
+ const fs26 = await import("node:fs");
17771
18089
  try {
17772
- await fs25.promises.mkdir(memoryDir, { recursive: true });
18090
+ await fs26.promises.mkdir(memoryDir, { recursive: true });
17773
18091
  } catch (e) {
17774
18092
  const code = e?.code;
17775
18093
  if (code !== "EEXIST") {
@@ -18045,10 +18363,12 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
18045
18363
  function buildMemoryPrompt(params) {
18046
18364
  const { displayName, memoryDir, extraGuidelines } = params;
18047
18365
  const entrypoint = join29(memoryDir, ENTRYPOINT_NAME);
18048
- let entrypointContent = "";
18049
- try {
18050
- entrypointContent = readFileSync15(entrypoint, { encoding: "utf-8" });
18051
- } catch {
18366
+ let entrypointContent = params.entrypointContent ?? "";
18367
+ if (params.entrypointContent === void 0) {
18368
+ try {
18369
+ entrypointContent = readFileSync15(entrypoint, "utf-8");
18370
+ } catch {
18371
+ }
18052
18372
  }
18053
18373
  const lines = buildMemoryLines(displayName, memoryDir, extraGuidelines);
18054
18374
  if (entrypointContent.trim()) {
@@ -18092,8 +18412,8 @@ __export(context_analyzer_exports, {
18092
18412
  formatContextReport: () => formatContextReport,
18093
18413
  scanMemoryFiles: () => scanMemoryFiles
18094
18414
  });
18095
- import * as fs21 from "node:fs";
18096
- import * as path28 from "node:path";
18415
+ import * as fs22 from "node:fs";
18416
+ import * as path29 from "node:path";
18097
18417
  function estimateMessageTokens2(m) {
18098
18418
  let tokens = 0;
18099
18419
  if (typeof m.content === "string") {
@@ -18203,9 +18523,9 @@ function breakdownMessages(messages) {
18203
18523
  }
18204
18524
  async function scanMemoryFiles(workspace) {
18205
18525
  const files = [];
18206
- const soul = readFileIfExists(path28.join(workspace, "SOUL.md"));
18526
+ const soul = readFileIfExists(path29.join(workspace, "SOUL.md"));
18207
18527
  if (soul) files.push({ path: "SOUL.md", tokens: roughTokenCountEstimation(soul), stable: true });
18208
- const agents = readFileIfExists(path28.join(workspace, "AGENTS.md"));
18528
+ const agents = readFileIfExists(path29.join(workspace, "AGENTS.md"));
18209
18529
  if (agents) files.push({ path: "AGENTS.md", tokens: roughTokenCountEstimation(agents), stable: true });
18210
18530
  try {
18211
18531
  const { buildMemoryPrompt: buildMemoryPrompt2 } = await Promise.resolve().then(() => (init_memdir(), memdir_exports));
@@ -18221,7 +18541,7 @@ async function scanMemoryFiles(workspace) {
18221
18541
  }
18222
18542
  function readFileIfExists(filePath2) {
18223
18543
  try {
18224
- if (fs21.existsSync(filePath2)) return fs21.readFileSync(filePath2, "utf-8");
18544
+ if (fs22.existsSync(filePath2)) return fs22.readFileSync(filePath2, "utf-8");
18225
18545
  } catch {
18226
18546
  }
18227
18547
  return null;
@@ -18447,7 +18767,7 @@ import { writeFileSync as writeFileSync15, existsSync as existsSync15, rmSync as
18447
18767
  import { join as join32, resolve as resolve12 } from "node:path";
18448
18768
  import { fileURLToPath as fileURLToPath5 } from "node:url";
18449
18769
  import { createServer as createServer4 } from "node:https";
18450
- import { timingSafeEqual, X509Certificate, createHash as createHash37 } from "node:crypto";
18770
+ import { timingSafeEqual, X509Certificate, createHash as createHash38 } from "node:crypto";
18451
18771
 
18452
18772
  // src/continuity/authority.ts
18453
18773
  init_publication_objects();
@@ -18512,9 +18832,9 @@ var TravelAuthority = class {
18512
18832
  this.owner.close();
18513
18833
  throw new Error("TRAVEL_AUTHORITY_BUSY", { cause: error });
18514
18834
  }
18515
- const path35 = join3(options.directory, "authority.sqlite"), keyFile = join3(options.directory, "authority-signing.pem");
18835
+ const path36 = join3(options.directory, "authority.sqlite"), keyFile = join3(options.directory, "authority-signing.pem");
18516
18836
  try {
18517
- const present = existsSync(path35), keyPresent = existsSync(keyFile);
18837
+ const present = existsSync(path36), keyPresent = existsSync(keyFile);
18518
18838
  if (present !== keyPresent) throw new Error("TRAVEL_AUTHORITY_RECOVERY_REQUIRED");
18519
18839
  if (!keyPresent) {
18520
18840
  const keys = generateKeyPairSync("ed25519");
@@ -18522,8 +18842,8 @@ var TravelAuthority = class {
18522
18842
  }
18523
18843
  this.signingKey = readPrivateFile(keyFile).toString();
18524
18844
  this.publicKey = createPublicKey(this.signingKey).export({ format: "pem", type: "spki" }).toString();
18525
- preparePrivateDatabase(path35);
18526
- this.db = new DatabaseSync3(path35);
18845
+ preparePrivateDatabase(path36);
18846
+ this.db = new DatabaseSync3(path36);
18527
18847
  this.db.exec(`PRAGMA busy_timeout=1000; PRAGMA synchronous=FULL;
18528
18848
  CREATE TABLE IF NOT EXISTS seats(identity TEXT PRIMARY KEY,epoch INTEGER NOT NULL,active_node TEXT,active_boot TEXT,
18529
18849
  floor INTEGER NOT NULL,checkpoint TEXT NOT NULL,build TEXT NOT NULL,retired TEXT,frozen INTEGER NOT NULL DEFAULT 0);
@@ -18983,8 +19303,8 @@ init_key_service_store();
18983
19303
  init_key_service_store();
18984
19304
  import { createServer } from "node:https";
18985
19305
  function createKeyServiceServer(options) {
18986
- const { store, ...tls2 } = options;
18987
- const server = createServer({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19306
+ const { store, ...tls3 } = options;
19307
+ const server = createServer({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
18988
19308
  res.setHeader("Cache-Control", "no-store");
18989
19309
  res.setHeader("Content-Type", "application/json");
18990
19310
  const reply = (status, error) => {
@@ -19056,7 +19376,7 @@ function createKeyServiceServer(options) {
19056
19376
  // src/continuity/gateway-main.ts
19057
19377
  import { isAbsolute as isAbsolute5, resolve as resolve11 } from "node:path";
19058
19378
  import { fileURLToPath as fileURLToPath4 } from "node:url";
19059
- import { createHash as createHash36 } from "node:crypto";
19379
+ import { createHash as createHash37 } from "node:crypto";
19060
19380
  import * as lark3 from "@larksuiteoapi/node-sdk";
19061
19381
 
19062
19382
  // src/continuity/publication.ts
@@ -19068,9 +19388,9 @@ import { isAbsolute, join as join4, relative, resolve as resolve2, sep } from "n
19068
19388
  var STATE = new Set(`workspace agents auth configs cron media mem7 memory runtime session-memory steer tasks teams todos tools topics topics-history .everos .calendar calendar proactive skills prompts goals.json goal-events.jsonl SESSION-STATE.md install-identity.json license.json report-failures.jsonl report-state.json service-suggestions.json weixin cc-driver engines.json settings.json onboarding.json onboarding-tips.json remote-watchers.json plans telegram state`.split(" "));
19069
19389
  var CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts topics .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
19070
19390
  var CORE_OMITTED = new Set(`media images videos audio content content-library docs output outputs dogfood-output backup backups topics-history node_modules .venvs venv .venv asr .cache cache caches tmp temp .playwright-mcp lancedb`.split(" "));
19071
- function validateRelativePath(path35) {
19072
- if (typeof path35 !== "string" || !path35 || path35.length > 2048 || isAbsolute(path35)) throw new Error("INVALID_ARTIFACT_PATH");
19073
- for (const part of path35.split("/")) {
19391
+ function validateRelativePath(path36) {
19392
+ if (typeof path36 !== "string" || !path36 || path36.length > 2048 || isAbsolute(path36)) throw new Error("INVALID_ARTIFACT_PATH");
19393
+ for (const part of path36.split("/")) {
19074
19394
  if (!part || part === "." || part === ".." || /[\x00-\x1f]/.test(part) || Buffer.byteLength(part) > 255 || process.platform === "win32" && (/[<>:"|?*\\]/.test(part) || /[. ]$/.test(part) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(part)))
19075
19395
  throw new Error("INVALID_ARTIFACT_PATH");
19076
19396
  }
@@ -19118,10 +19438,10 @@ function normalizePublicationProfile(value) {
19118
19438
  Object.freeze(profile.trees);
19119
19439
  return Object.freeze(profile);
19120
19440
  }
19121
- function validatePublicationPath(path35) {
19122
- if (typeof path35 !== "string" || path35.normalize("NFC") !== path35) throw new Error("PUBLICATION_INVALID_PATH");
19441
+ function validatePublicationPath(path36) {
19442
+ if (typeof path36 !== "string" || path36.normalize("NFC") !== path36) throw new Error("PUBLICATION_INVALID_PATH");
19123
19443
  try {
19124
- validateRelativePath(path35);
19444
+ validateRelativePath(path36);
19125
19445
  } catch {
19126
19446
  throw new Error("PUBLICATION_INVALID_PATH");
19127
19447
  }
@@ -19140,15 +19460,15 @@ function normalizePublication(value) {
19140
19460
  if (!Array.isArray(tree.files) || !Array.isArray(tree.directories) || (paths += tree.files.length + tree.directories.length) > 1e5)
19141
19461
  throw new Error("PUBLICATION_INVALID_TREE");
19142
19462
  const occupied = /* @__PURE__ */ new Map();
19143
- const claim = (path35, kind) => {
19144
- validatePublicationPath(path35);
19145
- const folded = path35.toLowerCase();
19463
+ const claim = (path36, kind) => {
19464
+ validatePublicationPath(path36);
19465
+ const folded = path36.toLowerCase();
19146
19466
  if (occupied.has(folded)) throw new Error("PUBLICATION_PATH_COLLISION");
19147
19467
  occupied.set(folded, kind);
19148
19468
  };
19149
- const directories = tree.directories.map((path35) => {
19150
- claim(path35, "directory");
19151
- return path35;
19469
+ const directories = tree.directories.map((path36) => {
19470
+ claim(path36, "directory");
19471
+ return path36;
19152
19472
  }).sort();
19153
19473
  const files = tree.files.map((file2) => {
19154
19474
  claim(file2?.path, "file");
@@ -19160,8 +19480,8 @@ function normalizePublication(value) {
19160
19480
  chunks: file2.content.chunks.map((r) => ({ sha256: r.sha256, bytes: r.bytes }))
19161
19481
  } };
19162
19482
  }).sort((a, b) => a.path.localeCompare(b.path, "en"));
19163
- for (const path35 of occupied.keys()) {
19164
- const parts = path35.split("/");
19483
+ for (const path36 of occupied.keys()) {
19484
+ const parts = path36.split("/");
19165
19485
  for (let i = 1; i < parts.length; i++) if (occupied.get(parts.slice(0, i).join("/")) === "file") throw new Error("PUBLICATION_PATH_COLLISION");
19166
19486
  }
19167
19487
  return { id: tree.id, directories, files };
@@ -19248,7 +19568,7 @@ function validManagement(input) {
19248
19568
  return true;
19249
19569
  }
19250
19570
  function createTravelAuthorityServer(options) {
19251
- const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, bootstrapPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls2 } = options;
19571
+ const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, bootstrapPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls3 } = options;
19252
19572
  const proxies = /* @__PURE__ */ new Set(), peers = /* @__PURE__ */ new Map(), managers = /* @__PURE__ */ new Map();
19253
19573
  const fingerprint2 = (value) => {
19254
19574
  const normalized = value.replaceAll(":", "").toLowerCase();
@@ -19293,7 +19613,7 @@ function createTravelAuthorityServer(options) {
19293
19613
  retirees.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
19294
19614
  }
19295
19615
  const reports = /* @__PURE__ */ new Set(), management = /* @__PURE__ */ new Set();
19296
- const server = createServer2({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19616
+ const server = createServer2({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19297
19617
  res.setHeader("Content-Type", "application/json");
19298
19618
  res.setHeader("Cache-Control", "no-store");
19299
19619
  const reply = (status, value) => {
@@ -19592,9 +19912,9 @@ var TravelGatewayStore = class {
19592
19912
  throw new Error("TRAVEL_GATEWAY_BUSY");
19593
19913
  }
19594
19914
  try {
19595
- const path35 = join13(options.directory, "gateway.sqlite"), present = existsSync6(path35);
19596
- preparePrivateDatabase(path35);
19597
- this.db = new DatabaseSync10(path35);
19915
+ const path36 = join13(options.directory, "gateway.sqlite"), present = existsSync6(path36);
19916
+ preparePrivateDatabase(path36);
19917
+ this.db = new DatabaseSync10(path36);
19598
19918
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
19599
19919
  if (!present) this.db.exec([
19600
19920
  "CREATE TABLE binding(identity TEXT NOT NULL,format TEXT NOT NULL);",
@@ -20148,7 +20468,7 @@ function decodeBody(value, maximum = 16 * 1024 * 1024) {
20148
20468
  return body;
20149
20469
  }
20150
20470
  function createTravelGatewayServer(options) {
20151
- const { authority, store, allowedPeers, recoveryPeers = {}, platform, assertReady, ...tls2 } = options, peers = /* @__PURE__ */ new Map(), recovery = /* @__PURE__ */ new Map();
20471
+ const { authority, store, allowedPeers, recoveryPeers = {}, platform, assertReady, ...tls3 } = options, peers = /* @__PURE__ */ new Map(), recovery = /* @__PURE__ */ new Map();
20152
20472
  for (const [fingerprint2, credential] of Object.entries(allowedPeers)) {
20153
20473
  const normalized = fingerprint2.replaceAll(":", "").toLowerCase();
20154
20474
  if (!/^[a-f0-9]{64}$/.test(normalized) || peers.has(normalized)) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
@@ -20161,7 +20481,7 @@ function createTravelGatewayServer(options) {
20161
20481
  }
20162
20482
  if (!peers.size || typeof platform.deliver !== "function") throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
20163
20483
  let inFlight = 0;
20164
- const server = createServer3({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
20484
+ const server = createServer3({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
20165
20485
  res.setHeader("Cache-Control", "no-store");
20166
20486
  res.setHeader("Content-Type", "application/json");
20167
20487
  const reply = (status, value) => {
@@ -20542,12 +20862,55 @@ var AgentRegistryImpl = class {
20542
20862
  var agentRegistry = new AgentRegistryImpl();
20543
20863
 
20544
20864
  // src/channels/discord.ts
20545
- import { Client, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20546
- import { ProxyAgent as UndiciProxyAgent } from "undici";
20547
- import { HttpsProxyAgent } from "https-proxy-agent";
20865
+ init_adaptive_proxy();
20866
+ import { Client as Client2, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20867
+
20868
+ // src/channels/discord-gateway-proxy.ts
20869
+ init_adaptive_proxy();
20870
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
20871
+ import https from "node:https";
20872
+ import { SimpleShardingStrategy } from "@discordjs/ws";
20873
+ var gatewayRoute = new AsyncLocalStorage4();
20874
+ function gatewayDestination(url) {
20875
+ const { hostname, port } = new URL(url);
20876
+ return `${hostname.replace(/^\[|\]$/g, "")}:${port || 443}`;
20877
+ }
20878
+ var installed = false;
20879
+ function discordGatewayProxy(proxy) {
20880
+ if (!installed) {
20881
+ installed = true;
20882
+ const request4 = https.request;
20883
+ https.request = (...args) => {
20884
+ const route = gatewayRoute.getStore();
20885
+ const [options] = args;
20886
+ if (route && options && typeof options === "object" && !(options instanceof URL) && options.agent === void 0 && options.headers?.Upgrade === "websocket" && route.destinations.has(`${options.hostname ?? options.host}:${options.port ?? 443}`)) {
20887
+ args[0] = { ...options, agent: route.agent };
20888
+ }
20889
+ return Reflect.apply(request4, https, args);
20890
+ };
20891
+ }
20892
+ const agent = createProxySocketAgent(proxy);
20893
+ return (manager) => {
20894
+ const strategy = new SimpleShardingStrategy(manager);
20895
+ const destinations = /* @__PURE__ */ new Set();
20896
+ const retrieveSession = manager.options.retrieveSessionInfo.bind(manager.options);
20897
+ manager.options.retrieveSessionInfo = async (shardId) => {
20898
+ const session = await retrieveSession(shardId);
20899
+ if (session?.resumeURL) destinations.add(gatewayDestination(session.resumeURL));
20900
+ return session;
20901
+ };
20902
+ const connect = strategy.connect.bind(strategy);
20903
+ strategy.connect = async () => {
20904
+ const { url } = await manager.fetchGatewayInformation();
20905
+ destinations.add(gatewayDestination(url));
20906
+ return gatewayRoute.run({ agent, destinations }, connect);
20907
+ };
20908
+ return strategy;
20909
+ };
20910
+ }
20548
20911
 
20549
20912
  // src/memory/external-effect.ts
20550
- import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
20913
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
20551
20914
  import { createHash as createHash25 } from "node:crypto";
20552
20915
  import { join as join18 } from "node:path";
20553
20916
 
@@ -20559,6 +20922,7 @@ init_migrations();
20559
20922
  init_context_time();
20560
20923
  init_relationship_notice_check();
20561
20924
  init_dependencies();
20925
+ init_watermarks();
20562
20926
  import { join as join17 } from "node:path";
20563
20927
  var MemoryExecutionBlockedError = class extends Error {
20564
20928
  constructor(reason) {
@@ -20607,6 +20971,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20607
20971
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
20608
20972
  proactive = new DatabaseSync11(join17(workspace, ".proactive", "proactive.db"), { readOnly: true });
20609
20973
  proactive.exec("PRAGMA query_only=ON; BEGIN");
20974
+ const retractions = emptyRetractionCache();
20610
20975
  for (const [id3, version] of Object.entries(context.actionVersions)) {
20611
20976
  const action = proactive.prepare("SELECT * FROM actions WHERE id=?").get(id3);
20612
20977
  if (action?.dispatch_state === "delivery_unknown" || action?.dispatch_state === "started" && action.dispatch_key !== activeDispatchKey) {
@@ -20642,6 +21007,9 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20642
21007
  }
20643
21008
  }
20644
21009
  if (!data || data.scopeId !== context.scopeId || ["resolved", "rejected", "expired"].includes(data.status) && !(handled && data.status === "resolved" && ["notification_completed", "calendar_accepted"].includes(data.reasonCode)) || ["candidate", "needs_revalidation", "deleted"].includes(data.evidenceState) || data.automationState === "pending_execution_guard") return { ok: false, reason: "INTENT_BASIS_INVALID" };
21010
+ if (typeof data.sourceWatermark === "number" && typeof data.retractionWatermark === "number" && deletedWithinView(memory, context.scopeId, data.retractionWatermark, data.sourceWatermark, retractions)) {
21011
+ return { ok: false, reason: "INTENT_BASIS_INVALID" };
21012
+ }
20645
21013
  }
20646
21014
  }
20647
21015
  return { ok: true };
@@ -20662,8 +21030,8 @@ function assertMemoryExecution(stateDir, workspace, context) {
20662
21030
  // src/mem7/host-turn.ts
20663
21031
  init_store();
20664
21032
  init_host_turns();
20665
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
20666
- var turns = new AsyncLocalStorage4();
21033
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
21034
+ var turns = new AsyncLocalStorage5();
20667
21035
  function hasHostTurnContext() {
20668
21036
  return Boolean(turns.getStore());
20669
21037
  }
@@ -20707,8 +21075,8 @@ function beginHostTurnEffect() {
20707
21075
 
20708
21076
  // src/memory/external-effect.ts
20709
21077
  init_runtime_authority();
20710
- var effects = new AsyncLocalStorage5();
20711
- var externalFences = new AsyncLocalStorage5();
21078
+ var effects = new AsyncLocalStorage6();
21079
+ var externalFences = new AsyncLocalStorage6();
20712
21080
  function withExternalEffectFence(check, run) {
20713
21081
  return externalFences.run(check, run);
20714
21082
  }
@@ -20982,6 +21350,7 @@ var settled = (status) => status !== "run" && status !== "wait";
20982
21350
  var DISCORD_MSG_LIMIT = 2e3;
20983
21351
  var DiscordAdapter = class _DiscordAdapter {
20984
21352
  name = "discord";
21353
+ supportsQuietPreview = true;
20985
21354
  memoryGuardedSends = true;
20986
21355
  client;
20987
21356
  config;
@@ -20996,7 +21365,7 @@ var DiscordAdapter = class _DiscordAdapter {
20996
21365
  // 🔴 P0: 消息去重 — Discord RESUME 重连会重放 messageCreate
20997
21366
  recentMessageIds = /* @__PURE__ */ new Set();
20998
21367
  constructor(clientOrConfig, config) {
20999
- if (clientOrConfig instanceof Client) {
21368
+ if (clientOrConfig instanceof Client2) {
21000
21369
  this.client = clientOrConfig;
21001
21370
  this.config = config ?? {};
21002
21371
  this.ownsClient = false;
@@ -21014,24 +21383,10 @@ var DiscordAdapter = class _DiscordAdapter {
21014
21383
  partials: [Partials.Channel, Partials.Message]
21015
21384
  };
21016
21385
  if (this.config.proxy) {
21017
- const proxyUrl = this.config.proxy;
21018
- clientOptions.rest = { agent: new UndiciProxyAgent({ uri: proxyUrl }) };
21019
- const httpsAgent = new HttpsProxyAgent(proxyUrl);
21020
- const https = __require("https");
21021
- const origRequest = https.request;
21022
- if (!origRequest.__discordProxyPatched) {
21023
- https.request = function(opts, cb) {
21024
- const host = typeof opts === "string" ? "" : opts?.hostname || opts?.host || "";
21025
- if ((host.includes("discord") || host.includes("gateway")) && typeof opts === "object" && !opts.agent) {
21026
- opts.agent = httpsAgent;
21027
- }
21028
- return origRequest.call(this, opts, cb);
21029
- };
21030
- https.request.__discordProxyPatched = true;
21031
- console.log(`[discord] https.request patched for Discord gateway \u2192 ${proxyUrl}`);
21032
- }
21386
+ clientOptions.rest = { agent: getProxyDispatcher(this.config.proxy) };
21387
+ clientOptions.ws = { buildStrategy: discordGatewayProxy(this.config.proxy) };
21033
21388
  }
21034
- this.client = new Client(clientOptions);
21389
+ this.client = new Client2(clientOptions);
21035
21390
  this.ownsClient = true;
21036
21391
  }
21037
21392
  this.progressCards = new DiscordProgressCards({
@@ -21092,7 +21447,7 @@ var DiscordAdapter = class _DiscordAdapter {
21092
21447
  }
21093
21448
  try {
21094
21449
  const init = { signal: AbortSignal.timeout(HISTORY_ATTACH_TIMEOUT_MS) };
21095
- if (this.config.proxy) init.dispatcher = new UndiciProxyAgent({ uri: this.config.proxy });
21450
+ if (this.config.proxy) init.dispatcher = getProxyDispatcher(this.config.proxy);
21096
21451
  const res = await fetch(att.url, init);
21097
21452
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
21098
21453
  const buf = Buffer.from(await res.arrayBuffer());
@@ -21165,9 +21520,9 @@ var DiscordAdapter = class _DiscordAdapter {
21165
21520
  throw err;
21166
21521
  }
21167
21522
  if (attempt < MAX_RETRIES2) {
21168
- const delay = Math.min(5e3 * Math.pow(2, attempt - 1), 6e4);
21169
- console.warn(`[discord] Login attempt ${attempt}/${MAX_RETRIES2} failed (${code || err.message}): ${err.message} \u2014 retrying in ${delay / 1e3}s`);
21170
- await new Promise((r) => setTimeout(r, delay));
21523
+ const delay2 = Math.min(5e3 * Math.pow(2, attempt - 1), 6e4);
21524
+ console.warn(`[discord] Login attempt ${attempt}/${MAX_RETRIES2} failed (${code || err.message}): ${err.message} \u2014 retrying in ${delay2 / 1e3}s`);
21525
+ await new Promise((r) => setTimeout(r, delay2));
21171
21526
  }
21172
21527
  }
21173
21528
  }
@@ -21244,13 +21599,13 @@ var DiscordAdapter = class _DiscordAdapter {
21244
21599
  }
21245
21600
  /** 发送媒体附件(图片/文件/音频)— discord.js channel.send({ files }) */
21246
21601
  async sendFile(target, message, attachment) {
21247
- const fs25 = await import("node:fs");
21248
- const path35 = await import("node:path");
21249
- if (!fs25.existsSync(attachment.path)) {
21602
+ const fs26 = await import("node:fs");
21603
+ const path36 = await import("node:path");
21604
+ if (!fs26.existsSync(attachment.path)) {
21250
21605
  throw new Error(`File not found: ${attachment.path}`);
21251
21606
  }
21252
- const filename = attachment.filename || path35.basename(attachment.path);
21253
- const fileBuffer = fs25.readFileSync(attachment.path);
21607
+ const filename = attachment.filename || path36.basename(attachment.path);
21608
+ const fileBuffer = fs26.readFileSync(attachment.path);
21254
21609
  const filePayload = {
21255
21610
  attachment: fileBuffer,
21256
21611
  name: filename
@@ -21453,7 +21808,7 @@ var DiscordAdapter = class _DiscordAdapter {
21453
21808
  return this.config.previewColor ?? _DiscordAdapter.COLOR_RUNNING;
21454
21809
  }
21455
21810
  /** 发送初始 preview 消息(Embed),返回 handle */
21456
- async sendPreview(channelId, content, agentName) {
21811
+ async sendPreview(channelId, content, agentName, presentation) {
21457
21812
  const channel = this.client.channels.cache.get(channelId) ?? await this.client.channels.fetch(channelId);
21458
21813
  if (!channel?.isTextBased() || !("send" in channel)) {
21459
21814
  throw new Error(`discord: sendPreview: channel ${channelId} not found or not text-based`);
@@ -21463,7 +21818,7 @@ var DiscordAdapter = class _DiscordAdapter {
21463
21818
  assertExternalEffectCurrent();
21464
21819
  const sent = await channel.send({
21465
21820
  embeds: [{
21466
- title: `${agent} \xB7 \u5904\u7406\u4E2D`,
21821
+ ...presentation !== "quiet" && { title: `${agent} \xB7 \u5904\u7406\u4E2D` },
21467
21822
  description: text2,
21468
21823
  color: this.previewColor
21469
21824
  }]
@@ -21707,6 +22062,7 @@ var FEISHU_POST_BYTES = 3e4;
21707
22062
  var FEISHU_POST_BUDGET = FEISHU_POST_BYTES - 1024;
21708
22063
  var FeishuAdapter = class _FeishuAdapter {
21709
22064
  name = "feishu";
22065
+ supportsQuietPreview = true;
21710
22066
  memoryGuardedSends = true;
21711
22067
  client;
21712
22068
  wsClient;
@@ -21863,13 +22219,13 @@ var FeishuAdapter = class _FeishuAdapter {
21863
22219
  }
21864
22220
  /** 发送媒体附件(图片/文件) */
21865
22221
  async sendFile(target, message, attachment) {
21866
- const fs25 = await import("node:fs");
21867
- const path35 = await import("node:path");
21868
- if (!fs25.existsSync(attachment.path)) {
22222
+ const fs26 = await import("node:fs");
22223
+ const path36 = await import("node:path");
22224
+ if (!fs26.existsSync(attachment.path)) {
21869
22225
  throw new Error(`File not found: ${attachment.path}`);
21870
22226
  }
21871
- const filename = attachment.filename || path35.basename(attachment.path);
21872
- const fileBuffer = fs25.readFileSync(attachment.path);
22227
+ const filename = attachment.filename || path36.basename(attachment.path);
22228
+ const fileBuffer = fs26.readFileSync(attachment.path);
21873
22229
  const safeTarget = target || this.config.defaultTarget || "";
21874
22230
  if (!safeTarget) throw new Error("Feishu sendFile: no target (\u4E3B\u52A8\u53D1\u9001\u9700\u914D\u7F6E defaultTarget \u6216\u4F20\u5165 target)");
21875
22231
  const receiveIdType = safeTarget.startsWith("ou_") ? "open_id" : "chat_id";
@@ -22291,7 +22647,7 @@ var FeishuAdapter = class _FeishuAdapter {
22291
22647
  }
22292
22648
  }
22293
22649
  // === Streaming preview — 用飞书消息卡片实现"正在思考"效果 ===
22294
- async sendPreview(channelId, content, agentName) {
22650
+ async sendPreview(channelId, content, agentName, presentation) {
22295
22651
  const agent = agentName || "Agent";
22296
22652
  const text2 = content.length > 2e3 ? content.slice(0, 1999) + "\u2026" : content;
22297
22653
  assertExternalEffectCurrent();
@@ -22302,10 +22658,10 @@ var FeishuAdapter = class _FeishuAdapter {
22302
22658
  msg_type: "interactive",
22303
22659
  content: JSON.stringify({
22304
22660
  config: { wide_screen_mode: true },
22305
- header: {
22661
+ ...presentation !== "quiet" && { header: {
22306
22662
  title: { tag: "plain_text", content: `${agent} \xB7 \u5904\u7406\u4E2D` },
22307
22663
  template: this.config.previewTemplate || "yellow"
22308
- },
22664
+ } },
22309
22665
  elements: [
22310
22666
  // 1013:预览卡也用 lark_md —— 生成过程中粗体/斜体/删除线/链接就能渲染了。
22311
22667
  // 表格、列表、代码块、行内代码是 lark_md 的能力边界(卡片 1.0 的 div 文本就只有
@@ -23884,7 +24240,7 @@ import { promisify as promisify3 } from "node:util";
23884
24240
  init_voice_chat_tts_daemon();
23885
24241
  import * as path14 from "node:path";
23886
24242
  import * as os6 from "node:os";
23887
- import net2 from "net";
24243
+ import net3 from "net";
23888
24244
  var execFileAsync = promisify3(execFile);
23889
24245
  var VOICE_DIR = path14.join(os6.tmpdir(), "engine-voice");
23890
24246
  async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
@@ -23896,7 +24252,7 @@ async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
23896
24252
  }
23897
24253
  }
23898
24254
  return new Promise((resolve13, reject) => {
23899
- const sock = net2.connect(getSockPath());
24255
+ const sock = net3.connect(getSockPath());
23900
24256
  let buf = "";
23901
24257
  const finish = (err) => {
23902
24258
  try {
@@ -23995,22 +24351,22 @@ var DeskBuddyAdapter = class {
23995
24351
  try {
23996
24352
  if (!this.historyFile) {
23997
24353
  const os7 = __require("os");
23998
- const fs26 = __require("fs");
23999
- const path35 = __require("path");
24000
- const dir = path35.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
24001
- fs26.mkdirSync(dir, { recursive: true });
24002
- this.historyFile = path35.join(dir, "history.json");
24003
- this._fs = fs26;
24004
- }
24005
- const fs25 = this._fs;
24354
+ const fs27 = __require("fs");
24355
+ const path36 = __require("path");
24356
+ const dir = path36.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
24357
+ fs27.mkdirSync(dir, { recursive: true });
24358
+ this.historyFile = path36.join(dir, "history.json");
24359
+ this._fs = fs27;
24360
+ }
24361
+ const fs26 = this._fs;
24006
24362
  let arr = [];
24007
24363
  try {
24008
- arr = JSON.parse(fs25.readFileSync(this.historyFile, "utf-8")) || [];
24364
+ arr = JSON.parse(fs26.readFileSync(this.historyFile, "utf-8")) || [];
24009
24365
  } catch {
24010
24366
  }
24011
24367
  arr.push({ ...entry, ts: (/* @__PURE__ */ new Date()).toLocaleString("zh-CN", { hour12: false }) });
24012
24368
  if (arr.length > 500) arr = arr.slice(-500);
24013
- fs25.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
24369
+ fs26.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
24014
24370
  } catch (e) {
24015
24371
  console.warn("[deskBuddy] history write fail", e);
24016
24372
  }
@@ -24108,8 +24464,8 @@ var DeskBuddyAdapter = class {
24108
24464
  startAsr() {
24109
24465
  if (this.asrSock) return;
24110
24466
  const port = this.asrBackend === "sensevoice" ? 9790 : 9791;
24111
- const net3 = __require("node:net");
24112
- const sock = net3.connect(port, "127.0.0.1");
24467
+ const net4 = __require("node:net");
24468
+ const sock = net4.connect(port, "127.0.0.1");
24113
24469
  sock.setNoDelay(true);
24114
24470
  this.asrSock = sock;
24115
24471
  this.asrBuf = "";
@@ -24661,7 +25017,7 @@ var CcBridgeAdapter = class {
24661
25017
 
24662
25018
  // src/channels/telegram.ts
24663
25019
  import fs13 from "node:fs";
24664
- import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
25020
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
24665
25021
  import path17 from "node:path";
24666
25022
 
24667
25023
  // src/channels/telegram-offset.ts
@@ -24853,7 +25209,7 @@ var PreviewEditThrottle = class {
24853
25209
  /** 提交一次编辑;返回的 promise 在"该内容(或其后覆盖它的更新内容)真实落盘"后 settle,失败 reject */
24854
25210
  submit(key4, req, run) {
24855
25211
  const s = this.st.get(key4) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
24856
- const guardedRun = AsyncLocalStorage6.bind(run);
25212
+ const guardedRun = AsyncLocalStorage7.bind(run);
24857
25213
  this.st.set(key4, s);
24858
25214
  return new Promise((resolve13, reject) => {
24859
25215
  const waiter = { resolve: resolve13, reject };
@@ -25635,7 +25991,7 @@ var TelegramAdapter = class {
25635
25991
 
25636
25992
  // src/channels/whatsapp/adapter.ts
25637
25993
  import fsSync4 from "node:fs";
25638
- import path30 from "node:path";
25994
+ import path31 from "node:path";
25639
25995
  import { spawn as spawn5 } from "node:child_process";
25640
25996
  import { randomUUID as randomUUID18 } from "node:crypto";
25641
25997
 
@@ -26039,9 +26395,6 @@ var QrManager = class {
26039
26395
  }
26040
26396
  };
26041
26397
 
26042
- // src/channels/whatsapp/socket.ts
26043
- import { HttpsProxyAgent as HttpsProxyAgent2 } from "https-proxy-agent";
26044
-
26045
26398
  // src/version.ts
26046
26399
  import { readFileSync as readFileSync12 } from "node:fs";
26047
26400
  import { dirname as dirname10, join as join22 } from "node:path";
@@ -26068,7 +26421,7 @@ function readEngineVersion() {
26068
26421
  }
26069
26422
 
26070
26423
  // src/channels/whatsapp/socket.ts
26071
- init_withRetry();
26424
+ init_adaptive_proxy();
26072
26425
  var VERSION_SOURCE_URL = "https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts";
26073
26426
  var VERSION_FETCH_TIMEOUT_MS = 3e3;
26074
26427
  var VERSION_FALLBACK_TIMEOUT_MS = 5e3;
@@ -26162,7 +26515,7 @@ async function makeWaSocket(opts) {
26162
26515
  connectTimeoutMs: 6e4,
26163
26516
  defaultQueryTimeoutMs: 6e4,
26164
26517
  // ws 层代理(https-proxy-agent,baileys 原生支持)
26165
- agent: opts.proxy ? new HttpsProxyAgent2(opts.proxy) : void 0,
26518
+ agent: opts.proxy ? createProxySocketAgent(opts.proxy) : void 0,
26166
26519
  // 媒体上传/下载走 native fetch,只认 undici dispatcher(防线 4,见文件头)
26167
26520
  fetchAgent: opts.proxy ? getProxyDispatcher(opts.proxy) : void 0,
26168
26521
  auth: { creds: auth.state.creds, keys },
@@ -26566,7 +26919,7 @@ function headerOf(groupJid) {
26566
26919
 
26567
26920
  // src/channels/whatsapp/patrol.ts
26568
26921
  import fsSync3 from "node:fs";
26569
- import path29 from "node:path";
26922
+ import path30 from "node:path";
26570
26923
  import { randomBytes as randomBytes7 } from "node:crypto";
26571
26924
 
26572
26925
  // src/models/model-capabilities.ts
@@ -26890,6 +27243,185 @@ function isQuotaExhaustedError(message) {
26890
27243
  // src/core/query.ts
26891
27244
  import { setTimeout as waitForRetry } from "node:timers/promises";
26892
27245
 
27246
+ // src/utils/file-transaction.ts
27247
+ import { mkdir as mkdir3 } from "node:fs/promises";
27248
+ import { dirname as dirname11 } from "node:path";
27249
+ import { DatabaseSync as DatabaseSync14 } from "node:sqlite";
27250
+ import { setTimeout as delay } from "node:timers/promises";
27251
+ async function withFileTransaction(file2, action, signal, waitMs = 5e3) {
27252
+ await mkdir3(dirname11(file2), { recursive: true });
27253
+ const db2 = new DatabaseSync14(file2);
27254
+ try {
27255
+ const deadline = waitMs === null ? Infinity : Date.now() + waitMs;
27256
+ const retryMs = waitMs === null ? 50 : waitMs > 5e3 ? 200 : 15;
27257
+ for (; ; ) {
27258
+ signal?.throwIfAborted();
27259
+ try {
27260
+ db2.exec("BEGIN IMMEDIATE");
27261
+ break;
27262
+ } catch (error) {
27263
+ const code = error.errcode;
27264
+ if (code !== 5 || Date.now() >= deadline) throw error;
27265
+ await delay(retryMs, void 0, { signal });
27266
+ }
27267
+ }
27268
+ const result = await action();
27269
+ db2.exec("COMMIT");
27270
+ return result;
27271
+ } finally {
27272
+ db2.close();
27273
+ }
27274
+ }
27275
+
27276
+ // src/tools/file-path.ts
27277
+ import { createHash as createHash31 } from "node:crypto";
27278
+ import fs14 from "node:fs";
27279
+ import path21 from "node:path";
27280
+
27281
+ // src/utils/path.ts
27282
+ import * as path20 from "node:path";
27283
+ function isWithin(root, target) {
27284
+ const name = path20.relative(root, target);
27285
+ return !path20.isAbsolute(name) && name !== ".." && !name.startsWith(".." + path20.sep);
27286
+ }
27287
+ var extraAllowedPaths = [];
27288
+ var sandboxOff = false;
27289
+ function fixMsysPath(p) {
27290
+ let fixed = p.includes("\\") ? p.replace(/\\/g, "/") : p;
27291
+ if (process.platform === "win32") {
27292
+ fixed = fixed.replace(/^\/([a-zA-Z])\//, (_, letter) => `${letter.toUpperCase()}:/`);
27293
+ }
27294
+ return fixed;
27295
+ }
27296
+ function resolvePath(p, workspace) {
27297
+ const fixed = fixMsysPath(p);
27298
+ const resolved = path20.isAbsolute(fixed) ? path20.normalize(fixed) : path20.resolve(workspace, fixed);
27299
+ const normalized = path20.normalize(resolved);
27300
+ const normalizedWorkspace = path20.normalize(workspace);
27301
+ if (sandboxOff) return normalized;
27302
+ if (normalized === normalizedWorkspace || normalized.startsWith(normalizedWorkspace + path20.sep)) {
27303
+ return normalized;
27304
+ }
27305
+ for (const allowed of extraAllowedPaths) {
27306
+ if (normalized === allowed || normalized.startsWith(allowed + path20.sep)) {
27307
+ return normalized;
27308
+ }
27309
+ }
27310
+ throw new Error(`\u8DEF\u5F84\u8D85\u51FA workspace \u8303\u56F4: ${p} \u2192 ${normalized} (workspace: ${normalizedWorkspace})`);
27311
+ }
27312
+
27313
+ // src/tools/file-path.ts
27314
+ init_paths();
27315
+ function physicalPath(target) {
27316
+ let ancestor = target;
27317
+ for (; ; ) {
27318
+ try {
27319
+ fs14.lstatSync(ancestor);
27320
+ break;
27321
+ } catch (error) {
27322
+ if (error.code !== "ENOENT") throw error;
27323
+ const parent = path21.dirname(ancestor);
27324
+ if (parent === ancestor) throw error;
27325
+ ancestor = parent;
27326
+ }
27327
+ }
27328
+ return path21.resolve(fs14.realpathSync(ancestor), path21.relative(ancestor, target));
27329
+ }
27330
+ function withoutRepeatedDirectories(relative5) {
27331
+ const parts = relative5.split(path21.sep);
27332
+ while (parts.length > 1 && parts[0].toLowerCase() === AUTO_MEM_DIRNAME) parts.shift();
27333
+ return parts.filter((part, index) => index === parts.length - 1 || index === 0 || part.toLowerCase() !== parts[index - 1].toLowerCase()).join(path21.sep);
27334
+ }
27335
+ function resolveFilePath(requested, context, writing = false) {
27336
+ if (!context.memoryToolRoot) {
27337
+ if (!context.projectTask) return resolvePath(requested, context.workspace);
27338
+ const target = path21.resolve(context.workspace, requested.replaceAll("\\", "/"));
27339
+ const roots = [context.projectTask.topicsDir, ...!writing && context.taskSessionsDir ? [context.taskSessionsDir] : [], context.workspace];
27340
+ const root2 = roots.find((directory2) => isWithin(directory2, target));
27341
+ const physical = physicalPath(target);
27342
+ if (!root2 || !isWithin(physicalPath(root2), physical)) throw new Error("Path is outside this task workspace and project context");
27343
+ if (root2 === context.workspace && context.stateDir && isWithin(physicalPath(path21.join(context.stateDir, "agents")), physical)) {
27344
+ throw new Error("Path is outside this task\u2019s project storage");
27345
+ }
27346
+ if (root2 !== context.workspace && path21.relative(root2, target).split(path21.sep).some((part) => part.startsWith("."))) {
27347
+ throw new Error("Project task storage metadata is internal");
27348
+ }
27349
+ return target;
27350
+ }
27351
+ const root = path21.resolve(context.memoryToolRoot);
27352
+ const resolved = resolvePath(requested, root);
27353
+ if (!isWithin(root, resolved) || !isWithin(physicalPath(root), physicalPath(resolved))) {
27354
+ throw new Error("\u8DEF\u5F84\u8D85\u51FA\u5F53\u524D\u8BB0\u5FC6\u76EE\u5F55\uFF1B\u8BF7\u4F7F\u7528\u76F8\u5BF9\u8BB0\u5FC6\u76EE\u5F55\u7684\u8DEF\u5F84\u3002");
27355
+ }
27356
+ const relative5 = path21.relative(root, resolved);
27357
+ if (writing) {
27358
+ if (path21.basename(resolved).toUpperCase() === "MEMORY.MD") {
27359
+ const canonicalIndex = path21.join(root, "MEMORY.md");
27360
+ const indexNames = fs14.existsSync(root) ? fs14.readdirSync(root).filter((name) => name.toUpperCase() === "MEMORY.MD") : [];
27361
+ let sameIndex = false;
27362
+ if (path21.dirname(relative5) === "." && indexNames.length === 1 && fs14.existsSync(resolved) && fs14.existsSync(canonicalIndex)) {
27363
+ const requestedEntry = fs14.lstatSync(resolved);
27364
+ const canonicalEntry = fs14.lstatSync(canonicalIndex);
27365
+ sameIndex = requestedEntry.dev === canonicalEntry.dev && requestedEntry.ino === canonicalEntry.ino;
27366
+ }
27367
+ if (relative5 !== "MEMORY.md" && !sameIndex || relative5 === "MEMORY.md" && indexNames.length > 0 && !fs14.existsSync(canonicalIndex)) {
27368
+ throw new Error("\u8BB0\u5FC6\u7D22\u5F15\u53EA\u80FD\u4F7F\u7528\u6839\u76EE\u5F55\u7684 MEMORY.md\uFF0C\u4E0D\u80FD\u521B\u5EFA\u6216\u66F4\u65B0\u7B2C\u4E8C\u4EFD\u7D22\u5F15\u3002");
27369
+ }
27370
+ }
27371
+ if (!fs14.existsSync(resolved)) {
27372
+ const parts = relative5.split(path21.sep);
27373
+ if (parts[0].toLowerCase() === AUTO_MEM_DIRNAME || parts.some((part, index) => index > 0 && index < parts.length - 1 && part.toLowerCase() === parts[index - 1].toLowerCase())) {
27374
+ throw new Error("\u91CD\u590D\u8BB0\u5FC6\u76EE\u5F55\u524D\u7F00\uFF1B\u8DEF\u5F84\u4ECE\u8BB0\u5FC6\u76EE\u5F55\u5185\u5F00\u59CB\uFF0C\u4F8B\u5982 project/project_YYYY-MM-DD_name.md\u3002");
27375
+ }
27376
+ if (fs14.existsSync(root)) {
27377
+ const existing = fs14.readdirSync(root, { recursive: true }).filter((entry) => typeof entry === "string" && entry.endsWith(".md") && entry !== relative5 && path21.basename(entry).toUpperCase() !== "MEMORY.MD" && withoutRepeatedDirectories(entry) === relative5);
27378
+ if (existing.length > 0) {
27379
+ throw new Error(`\u5DF2\u6709\u8BB0\u5FC6\u6587\u4EF6\u4F4D\u4E8E ${existing.map((entry) => entry.replace(/\\/g, "/")).join("\u3001")}\uFF1B\u4E0D\u80FD\u901A\u8FC7\u7F29\u77ED\u65E7\u5206\u53C9\u8DEF\u5F84\u521B\u5EFA\u53E6\u4E00\u4EFD\u6587\u4EF6\u3002\u8BF7\u6309\u539F\u8DEF\u5F84\u8BFB\u53D6\u540E\u66F4\u65B0\u3002`);
27380
+ }
27381
+ }
27382
+ }
27383
+ }
27384
+ return resolved;
27385
+ }
27386
+ function indexVersion(file2) {
27387
+ try {
27388
+ return createHash31("sha256").update(fs14.readFileSync(file2)).digest("hex");
27389
+ } catch (error) {
27390
+ if (error.code !== "ENOENT" && error.code !== "EISDIR") throw error;
27391
+ }
27392
+ }
27393
+ async function runFileTool(tool, requested, context, action, signal) {
27394
+ const root = context.memoryToolRoot ?? context.projectTask?.topicsDir;
27395
+ if (!root || typeof requested !== "string" || !["read", "write", "edit"].includes(tool)) return action();
27396
+ let file2;
27397
+ try {
27398
+ file2 = resolveFilePath(requested, context);
27399
+ } catch {
27400
+ return action();
27401
+ }
27402
+ if (!isWithin(path21.resolve(root), file2)) return action();
27403
+ if (tool === "read") {
27404
+ return withFileTransaction(path21.join(root, ".write-lock.sqlite"), async () => {
27405
+ const result = await action();
27406
+ const version = indexVersion(file2);
27407
+ if (version !== void 0 && !result.isError) context.topicReads?.set(file2, version);
27408
+ return result;
27409
+ }, signal);
27410
+ }
27411
+ return withFileTransaction(path21.join(root, ".write-lock.sqlite"), async () => {
27412
+ const current2 = indexVersion(file2);
27413
+ if (current2 !== void 0 && context.topicReads?.get(file2) !== current2) {
27414
+ throw new Error("Project topic changed or has not been read. Read it again before updating.");
27415
+ }
27416
+ const result = await action();
27417
+ if (!result.isError) {
27418
+ const version = indexVersion(file2);
27419
+ if (version !== void 0) context.topicReads?.set(file2, version);
27420
+ }
27421
+ return result;
27422
+ }, signal);
27423
+ }
27424
+
26893
27425
  // src/tools/ToolSearchTool/constants.ts
26894
27426
  var TOOL_SEARCH_TOOL_NAME = "load_missing_tools";
26895
27427
 
@@ -27013,9 +27545,9 @@ function isPlanMode() {
27013
27545
  init_runtime_authority();
27014
27546
 
27015
27547
  // src/continuity/gateway-context.ts
27016
- import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
27017
- var contexts = new AsyncLocalStorage7();
27018
- var outputKinds = new AsyncLocalStorage7();
27548
+ import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
27549
+ var contexts = new AsyncLocalStorage8();
27550
+ var outputKinds = new AsyncLocalStorage8();
27019
27551
  var travelOutputKind = () => outputKinds.getStore() ?? "REPLY";
27020
27552
  function withTravelOutputKind(kind, run) {
27021
27553
  return outputKinds.run(kind, run);
@@ -27148,27 +27680,45 @@ function emitHookResponse(data) {
27148
27680
  emit({ type: "response", ...data });
27149
27681
  }
27150
27682
 
27683
+ // src/skills/skill-gate.ts
27684
+ init_strip_injected();
27685
+ init_writer();
27686
+ var USER_CHANNELS = /* @__PURE__ */ new Set(["discord", "feishu", "wechat", "telegram", "cli", "console", "voice-chat", "deskBuddy", "ccBridge"]);
27687
+ var SKILL_CHANNELS = /* @__PURE__ */ new Set([...USER_CHANNELS, "chan7", "webhook"]);
27688
+ var loadedBySession = /* @__PURE__ */ new Map();
27689
+ var MAX_TRACKED_SESSIONS = 100;
27690
+ function beginSkillGate(sessionId) {
27691
+ if (loadedBySession.size >= MAX_TRACKED_SESSIONS && !loadedBySession.has(sessionId)) {
27692
+ const oldest = loadedBySession.keys().next().value;
27693
+ if (oldest !== void 0) loadedBySession.delete(oldest);
27694
+ }
27695
+ loadedBySession.set(sessionId, /* @__PURE__ */ new Set());
27696
+ }
27697
+ function isUserChannel(ch) {
27698
+ return !!ch && USER_CHANNELS.has(ch);
27699
+ }
27700
+
27151
27701
  // src/hooks/executor.ts
27152
- init_runtime_authority();
27153
27702
  import { spawn as spawn2 } from "child_process";
27154
27703
  import { randomUUID as randomUUID15 } from "node:crypto";
27704
+ init_runtime_authority();
27155
27705
  import { basename as basename5 } from "node:path";
27156
27706
 
27157
27707
  // src/router/cpu-router.ts
27158
- import fs14 from "node:fs";
27159
- import path20 from "node:path";
27708
+ import fs15 from "node:fs";
27709
+ import path22 from "node:path";
27160
27710
  init_strip_injected();
27161
27711
  import { fileURLToPath as fileURLToPath3 } from "node:url";
27162
- var bundledModelDir = [new URL("./models/cpu-router-v2/", import.meta.url), new URL("../../assets/cpu-router-v2/", import.meta.url)].map((url) => fileURLToPath3(url)).find((dir) => fs14.existsSync(path20.join(dir, "runtime.json")));
27712
+ var bundledModelDir = [new URL("./models/cpu-router-v2/", import.meta.url), new URL("../../assets/cpu-router-v2/", import.meta.url)].map((url) => fileURLToPath3(url)).find((dir) => fs15.existsSync(path22.join(dir, "runtime.json")));
27163
27713
 
27164
27714
  // src/router/cpu-router-mode-hook.ts
27165
- import fs15 from "node:fs";
27166
- import path21 from "node:path";
27715
+ import fs16 from "node:fs";
27716
+ import path23 from "node:path";
27167
27717
  function isCpuModeHook(command) {
27168
27718
  if (!/^(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>]+)\s+(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>]+)\s*$/.test(command)) return false;
27169
27719
  const tokens = command.match(/"[^"\r\n]*"|'[^'\r\n]*'|[^\s]+/g).map((token) => token.replace(/^["']|["']$/g, ""));
27170
- const executable = path21.basename(tokens[0].replaceAll("\\", "/"));
27171
- const script = path21.basename(tokens[1].replaceAll("\\", "/"));
27720
+ const executable = path23.basename(tokens[0].replaceAll("\\", "/"));
27721
+ const script = path23.basename(tokens[1].replaceAll("\\", "/"));
27172
27722
  return (tokens[0] === process.execPath || /^(?:node|python[\d.]*|py)(?:\.exe)?$/i.test(executable)) && /^emotion(?:_state_machine\.(?:mjs|py)|-hook-gate\.js)$/i.test(script);
27173
27723
  }
27174
27724
  function cpuModeHookOutput(command, input, workspace) {
@@ -27183,7 +27733,7 @@ function cpuModeOutput(input, workspace) {
27183
27733
  let fixed = "auto";
27184
27734
  if (!input.source || input.source === "user") {
27185
27735
  try {
27186
- fixed = fs15.readFileSync(path21.join(workspace, ".work-mode"), "utf8").trim();
27736
+ fixed = fs16.readFileSync(path23.join(workspace, ".work-mode"), "utf8").trim();
27187
27737
  } catch {
27188
27738
  }
27189
27739
  }
@@ -27752,6 +28302,9 @@ async function executeOne(tc, ctx, signal) {
27752
28302
  if (ctx.yieldSignal?.aborted) {
27753
28303
  return { call: tc, result: { content: "[not executed: new user input received; reconsider this call after reading it]", isError: false }, summary: null };
27754
28304
  }
28305
+ if (ctx.projectTask && /^(?:memory_|calendar_memory_|calendar_delivery_|calendar_reconcile_|goal_|proactive_|chat_history$)/.test(tc.function.name)) {
28306
+ return { call: tc, result: { content: "This tool has no project-task memory or conversation context. Use the project topics and task records.", isError: true }, summary: null };
28307
+ }
27755
28308
  const tool = registry.get(tc.function.name);
27756
28309
  if (!tool) {
27757
28310
  return { call: tc, result: { content: `Unknown tool: ${tc.function.name}`, isError: true }, summary: null };
@@ -27854,7 +28407,13 @@ async function executeOne(tc, ctx, signal) {
27854
28407
  workspace: ctx.workspace,
27855
28408
  executionContext: guardContext,
27856
28409
  effectId: `tool:${tc.id}`
27857
- }, () => tool.handler(args, { ...ctx, toolCallId: tc.id }, signal));
28410
+ }, () => runFileTool(
28411
+ tc.function.name,
28412
+ args.file_path ?? args.path,
28413
+ ctx,
28414
+ () => tool.handler(args, { ...ctx, toolCallId: tc.id }, signal),
28415
+ signal
28416
+ ));
27858
28417
  assertRuntimeTool(ctx.stateDir, tc.function.name);
27859
28418
  await executePostToolUseHooks(tc.function.name, args, result.content, hookCtx, signal);
27860
28419
  if (repeatN >= LOOP_SOFT_AT) {
@@ -28083,8 +28642,11 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
28083
28642
  }
28084
28643
 
28085
28644
  // src/utils/context-dump.ts
28086
- import * as fs16 from "node:fs";
28087
- import * as path22 from "node:path";
28645
+ import * as fs17 from "node:fs";
28646
+ import * as path24 from "node:path";
28647
+ function isContextDumpEnabled() {
28648
+ return process.env.ENGINE7_DUMP_CONTEXT === "1" || process.env.ENGINE_DUMP_REQUEST === "1";
28649
+ }
28088
28650
  function dumpApiRequest(opts) {
28089
28651
  const lines = [
28090
28652
  "=== API Request Debug\uFF08\u53D1\u7ED9 LLM \u7684\u6700\u7EC8\u8BF7\u6C42\u4F53\uFF0C\u6BCF\u6B21\u8986\u76D6\u5199\uFF09===",
@@ -28117,7 +28679,7 @@ function dumpApiRequest(opts) {
28117
28679
  lines.push(`[${i}] ${m.role}: (empty)`);
28118
28680
  }
28119
28681
  }
28120
- fs16.writeFileSync(path22.join(opts.workspace, ".context-debug.txt"), lines.join("\n") + "\n", "utf-8");
28682
+ fs17.writeFileSync(path24.join(opts.workspace, ".context-debug.txt"), lines.join("\n") + "\n", "utf-8");
28121
28683
  }
28122
28684
 
28123
28685
  // src/core/query.ts
@@ -28125,24 +28687,24 @@ init_types();
28125
28687
  import { randomUUID as randomUUID17 } from "node:crypto";
28126
28688
 
28127
28689
  // src/core/steer-mailbox.ts
28128
- import * as fs17 from "node:fs";
28129
- import * as path23 from "node:path";
28130
- import { createHash as createHash31, randomUUID as randomUUID16 } from "node:crypto";
28690
+ import * as fs18 from "node:fs";
28691
+ import * as path25 from "node:path";
28692
+ import { createHash as createHash32, randomUUID as randomUUID16 } from "node:crypto";
28131
28693
  var MAX_FILE = 1024 * 1024;
28132
28694
  var MAX_PENDING = 128;
28133
28695
  var MAX_PENDING_BYTES = 512 * 1024;
28134
28696
  var SteerMailbox = class {
28135
28697
  constructor(stateDir, sessionId) {
28136
28698
  this.sessionId = sessionId;
28137
- const key4 = createHash31("sha256").update(sessionId).digest("hex");
28138
- this.path = path23.join(stateDir, "steer", `${key4}.json`);
28699
+ const key4 = createHash32("sha256").update(sessionId).digest("hex");
28700
+ this.path = path25.join(stateDir, "steer", `${key4}.json`);
28139
28701
  }
28140
28702
  path;
28141
28703
  list() {
28142
28704
  let raw;
28143
28705
  try {
28144
- if (fs17.statSync(this.path).size > MAX_FILE) throw new Error("Steer mailbox exceeds size limit");
28145
- raw = fs17.readFileSync(this.path, "utf8");
28706
+ if (fs18.statSync(this.path).size > MAX_FILE) throw new Error("Steer mailbox exceeds size limit");
28707
+ raw = fs18.readFileSync(this.path, "utf8");
28146
28708
  } catch (error) {
28147
28709
  if (error.code === "ENOENT") return [];
28148
28710
  throw error;
@@ -28168,7 +28730,7 @@ var SteerMailbox = class {
28168
28730
  if (input.attachment) this.assertAttachment(input);
28169
28731
  input.images?.forEach(assertImageAssetRef);
28170
28732
  const records = this.list();
28171
- const id3 = input.messageId ? createHash31("sha256").update(JSON.stringify([
28733
+ const id3 = input.messageId ? createHash32("sha256").update(JSON.stringify([
28172
28734
  this.sessionId,
28173
28735
  input.channel,
28174
28736
  input.channelTarget ?? "",
@@ -28245,20 +28807,20 @@ var SteerMailbox = class {
28245
28807
  data = serialize();
28246
28808
  }
28247
28809
  if (Buffer.byteLength(data) > MAX_FILE) throw new Error("Steer mailbox full");
28248
- fs17.mkdirSync(path23.dirname(this.path), { recursive: true });
28810
+ fs18.mkdirSync(path25.dirname(this.path), { recursive: true });
28249
28811
  const temporary = `${this.path}.${randomUUID16()}.tmp`;
28250
28812
  try {
28251
- const fd = fs17.openSync(temporary, "wx", 384);
28813
+ const fd = fs18.openSync(temporary, "wx", 384);
28252
28814
  try {
28253
- fs17.writeFileSync(fd, data);
28254
- fs17.fsyncSync(fd);
28815
+ fs18.writeFileSync(fd, data);
28816
+ fs18.fsyncSync(fd);
28255
28817
  } finally {
28256
- fs17.closeSync(fd);
28818
+ fs18.closeSync(fd);
28257
28819
  }
28258
- fs17.renameSync(temporary, this.path);
28820
+ fs18.renameSync(temporary, this.path);
28259
28821
  } finally {
28260
28822
  try {
28261
- fs17.unlinkSync(temporary);
28823
+ fs18.unlinkSync(temporary);
28262
28824
  } catch {
28263
28825
  }
28264
28826
  }
@@ -28267,7 +28829,7 @@ var SteerMailbox = class {
28267
28829
 
28268
28830
  // src/compact/recent-tail.ts
28269
28831
  init_tokenEstimate();
28270
- function splitRecentHistory(messages, keepRecentTokens, budget) {
28832
+ function splitRecentHistory(messages, keepRecentTokens, budget, activeQueryId) {
28271
28833
  const protectedHistory = splitProtectedCompactHistory(messages, budget);
28272
28834
  let start = protectedHistory.prefix.length;
28273
28835
  if (keepRecentTokens > 0) {
@@ -28280,6 +28842,10 @@ function splitRecentHistory(messages, keepRecentTokens, budget) {
28280
28842
  }
28281
28843
  start = Math.min(start, recentStart);
28282
28844
  }
28845
+ if (activeQueryId) {
28846
+ const activeStart = messages.findIndex((m) => "role" in m && m.role === "user" && (m.inputSource?.queryId === activeQueryId || m.steerInput?.queryId === activeQueryId));
28847
+ if (activeStart >= 0) start = Math.min(start, activeStart);
28848
+ }
28283
28849
  const suffix = messages.slice(start);
28284
28850
  if (estimateMessageTokens(suffix) > budget) {
28285
28851
  const fused = fitProtectedTail(suffix, budget);
@@ -28793,14 +29359,14 @@ function shouldAutoCompact(messages, config) {
28793
29359
  compactLog(TAG3, `tokens=${tokenCount} threshold=${threshold} triggered=${result}`);
28794
29360
  return result;
28795
29361
  }
28796
- async function autoCompactIfNeeded(messages, config, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact = false) {
29362
+ async function autoCompactIfNeeded(messages, config, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact = false, activeQueryId) {
28797
29363
  const starts = messages.filter((m) => isAttachmentMessage(m) && m.attachment.type === "session_start");
28798
29364
  if (starts.length) {
28799
29365
  const body = messages.filter((m) => !starts.includes(m));
28800
29366
  const result = await autoCompactIfNeeded(body, {
28801
29367
  ...config,
28802
29368
  systemOverheadTokens: (config.systemOverheadTokens ?? 0) + estimateMessageTokens(starts)
28803
- }, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact);
29369
+ }, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact, activeQueryId);
28804
29370
  const retained = result.wasCompacted ? [...starts, ...result.messages] : messages;
28805
29371
  return { ...result, messages: retained, ...result.compactionResult ? { compactionResult: {
28806
29372
  ...result.compactionResult,
@@ -28809,8 +29375,8 @@ async function autoCompactIfNeeded(messages, config, tracking, provider, model,
28809
29375
  postCompactTokenCount: estimateMessageTokens(retained)
28810
29376
  } } : {} };
28811
29377
  }
28812
- if ((config.keepRecentTokens ?? 0) > 0 && config.enabled !== false) {
28813
- const { prefix: prefix3, suffix: suffix2 } = splitRecentHistory(messages, config.keepRecentTokens, getAutoCompactThreshold(config));
29378
+ if (((config.keepRecentTokens ?? 0) > 0 || activeQueryId) && config.enabled !== false) {
29379
+ const { prefix: prefix3, suffix: suffix2 } = splitRecentHistory(messages, config.keepRecentTokens ?? 0, getAutoCompactThreshold(config), activeQueryId);
28814
29380
  if (suffix2.length) {
28815
29381
  if (!prefix3.length) return { wasCompacted: false, messages, consecutiveFailures: tracking.consecutiveFailures };
28816
29382
  const result = await autoCompactIfNeeded(prefix3, {
@@ -29291,9 +29857,9 @@ async function streamCompactSummary(messages, compactPrompt, provider, model, ma
29291
29857
  init_tokenEstimate();
29292
29858
 
29293
29859
  // src/compact/background.ts
29294
- import { createHash as createHash32 } from "node:crypto";
29860
+ import { createHash as createHash33 } from "node:crypto";
29295
29861
  init_tokenEstimate();
29296
- var historyFingerprint = (messages) => createHash32("sha256").update(JSON.stringify(messages)).digest("hex");
29862
+ var historyFingerprint = (messages) => createHash33("sha256").update(JSON.stringify(messages)).digest("hex");
29297
29863
 
29298
29864
  // src/models/contextOverflow.ts
29299
29865
  var CONTEXT_OVERFLOW_SAFETY_BUFFER = 1e3;
@@ -29384,8 +29950,8 @@ init_live();
29384
29950
  // src/goals/store.ts
29385
29951
  init_db();
29386
29952
  init_schema2();
29387
- import fs18 from "node:fs";
29388
- import path24 from "node:path";
29953
+ import fs19 from "node:fs";
29954
+ import path26 from "node:path";
29389
29955
  import crypto3 from "node:crypto";
29390
29956
 
29391
29957
  // src/goals/read-snapshot.ts
@@ -29393,10 +29959,10 @@ init_db();
29393
29959
 
29394
29960
  // src/goals/store.ts
29395
29961
  function file(stateDir) {
29396
- return path24.join(stateDir, "goals.json");
29962
+ return path26.join(stateDir, "goals.json");
29397
29963
  }
29398
29964
  function eventFile(stateDir) {
29399
- return path24.join(stateDir, "goal-events.jsonl");
29965
+ return path26.join(stateDir, "goal-events.jsonl");
29400
29966
  }
29401
29967
  function db(stateDir) {
29402
29968
  const d = openDb(stateDir);
@@ -29404,17 +29970,17 @@ function db(stateDir) {
29404
29970
  return d;
29405
29971
  }
29406
29972
  function event(stateDir, goalId, type, payload = {}) {
29407
- fs18.mkdirSync(stateDir, { recursive: true });
29973
+ fs19.mkdirSync(stateDir, { recursive: true });
29408
29974
  const id3 = `ge-${Date.now()}-${crypto3.randomBytes(3).toString("hex")}`;
29409
29975
  const at = (/* @__PURE__ */ new Date()).toISOString();
29410
- fs18.appendFileSync(eventFile(stateDir), JSON.stringify({ eventId: id3, goalId, type, at, ...payload }) + "\n", "utf8");
29976
+ fs19.appendFileSync(eventFile(stateDir), JSON.stringify({ eventId: id3, goalId, type, at, ...payload }) + "\n", "utf8");
29411
29977
  const d = db(stateDir);
29412
29978
  d.prepare("INSERT INTO goal_events (event_id, goal_id, type, payload_json, created_at) VALUES (?, ?, ?, ?, ?)").run(id3, goalId, type, JSON.stringify(payload), at);
29413
29979
  d.close?.();
29414
29980
  }
29415
29981
  function read(stateDir) {
29416
29982
  try {
29417
- const v = JSON.parse(fs18.readFileSync(file(stateDir), "utf8"));
29983
+ const v = JSON.parse(fs19.readFileSync(file(stateDir), "utf8"));
29418
29984
  return Array.isArray(v) ? v : [];
29419
29985
  } catch {
29420
29986
  return [];
@@ -29469,41 +30035,13 @@ function markGoalBudgetLimited(stateDir, id3) {
29469
30035
  // src/tools/task-manager.ts
29470
30036
  import { randomBytes as randomBytes6 } from "node:crypto";
29471
30037
  import { spawn as spawn4 } from "node:child_process";
29472
- import * as fs20 from "node:fs";
29473
- import * as path27 from "node:path";
29474
-
29475
- // src/utils/path.ts
29476
- import * as path25 from "node:path";
29477
- var extraAllowedPaths = [];
29478
- var sandboxOff = false;
29479
- function fixMsysPath(p) {
29480
- let fixed = p.includes("\\") ? p.replace(/\\/g, "/") : p;
29481
- if (process.platform === "win32") {
29482
- fixed = fixed.replace(/^\/([a-zA-Z])\//, (_, letter) => `${letter.toUpperCase()}:/`);
29483
- }
29484
- return fixed;
29485
- }
29486
- function resolvePath(p, workspace) {
29487
- const fixed = fixMsysPath(p);
29488
- const resolved = path25.isAbsolute(fixed) ? path25.normalize(fixed) : path25.resolve(workspace, fixed);
29489
- const normalized = path25.normalize(resolved);
29490
- const normalizedWorkspace = path25.normalize(workspace);
29491
- if (sandboxOff) return normalized;
29492
- if (normalized === normalizedWorkspace || normalized.startsWith(normalizedWorkspace + path25.sep)) {
29493
- return normalized;
29494
- }
29495
- for (const allowed of extraAllowedPaths) {
29496
- if (normalized === allowed || normalized.startsWith(allowed + path25.sep)) {
29497
- return normalized;
29498
- }
29499
- }
29500
- throw new Error(`\u8DEF\u5F84\u8D85\u51FA workspace \u8303\u56F4: ${p} \u2192 ${normalized} (workspace: ${normalizedWorkspace})`);
29501
- }
30038
+ import * as fs21 from "node:fs";
30039
+ import * as path28 from "node:path";
29502
30040
 
29503
30041
  // src/tools/BashTool/BashTool.ts
29504
30042
  import { spawn as spawn3, execSync } from "node:child_process";
29505
- import * as fs19 from "node:fs";
29506
- import * as path26 from "node:path";
30043
+ import * as fs20 from "node:fs";
30044
+ import * as path27 from "node:path";
29507
30045
 
29508
30046
  // src/tools/BashTool/prompt.ts
29509
30047
  var GLOB_TOOL_NAME = "glob";
@@ -29724,7 +30262,7 @@ function findShell() {
29724
30262
  });
29725
30263
  const candidates2 = result.trim().split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
29726
30264
  const nonWsl = candidates2.find((p) => !isWslBash(p));
29727
- if (nonWsl && fs19.existsSync(nonWsl)) {
30265
+ if (nonWsl && fs20.existsSync(nonWsl)) {
29728
30266
  cachedShell = { shell: nonWsl, args: ["-c"] };
29729
30267
  return cachedShell;
29730
30268
  }
@@ -29734,10 +30272,10 @@ function findShell() {
29734
30272
  "C:\\Program Files\\Git\\bin\\bash.exe",
29735
30273
  "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
29736
30274
  "C:\\Program Files\\Git\\usr\\bin\\bash.exe",
29737
- path26.join(process.env.LOCALAPPDATA || "", "Programs", "Git", "bin", "bash.exe")
30275
+ path27.join(process.env.LOCALAPPDATA || "", "Programs", "Git", "bin", "bash.exe")
29738
30276
  ];
29739
30277
  for (const p of knownPaths) {
29740
- if (p && fs19.existsSync(p)) {
30278
+ if (p && fs20.existsSync(p)) {
29741
30279
  cachedShell = { shell: p, args: ["-c"] };
29742
30280
  return cachedShell;
29743
30281
  }
@@ -29801,7 +30339,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29801
30339
  const runInBackground = args.run_in_background || false;
29802
30340
  let cwd;
29803
30341
  try {
29804
- cwd = args.cwd ? resolvePath(args.cwd, ctx.workspace) : ctx.workspace;
30342
+ cwd = args.cwd ? resolveFilePath(args.cwd, ctx, true) : ctx.workspace;
29805
30343
  } catch (e) {
29806
30344
  return { content: e.message, isError: true };
29807
30345
  }
@@ -29830,12 +30368,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29830
30368
  }
29831
30369
  const MAX_OUTPUT = 100 * 1024;
29832
30370
  const startTime = Date.now();
29833
- fs19.mkdirSync(getTaskOutputDir(), { recursive: true });
29834
- const outputFile = path26.join(getTaskOutputDir(), `exec-${startTime}-${Math.random().toString(36).slice(2)}.output`);
29835
- const outputHandle = await fs19.promises.open(outputFile, "w");
30371
+ fs20.mkdirSync(getTaskOutputDir(), { recursive: true });
30372
+ const outputFile = path27.join(getTaskOutputDir(), `exec-${startTime}-${Math.random().toString(36).slice(2)}.output`);
30373
+ const outputHandle = await fs20.promises.open(outputFile, "w");
29836
30374
  if (signal?.aborted || ctx.yieldSignal?.aborted) {
29837
30375
  await outputHandle.close();
29838
- await fs19.promises.unlink(outputFile);
30376
+ await fs20.promises.unlink(outputFile);
29839
30377
  return { content: "[not executed: new user input or stop received before command start]" };
29840
30378
  }
29841
30379
  return new Promise((resolve13) => {
@@ -29865,18 +30403,18 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29865
30403
  let output = "";
29866
30404
  let truncated = false;
29867
30405
  try {
29868
- const fd = fs19.openSync(outputFile, "r");
30406
+ const fd = fs20.openSync(outputFile, "r");
29869
30407
  try {
29870
- truncated = fs19.fstatSync(fd).size > MAX_OUTPUT;
30408
+ truncated = fs20.fstatSync(fd).size > MAX_OUTPUT;
29871
30409
  const buffer = Buffer.alloc(MAX_OUTPUT);
29872
- output = buffer.subarray(0, fs19.readSync(fd, buffer, 0, MAX_OUTPUT, 0)).toString("utf8");
30410
+ output = buffer.subarray(0, fs20.readSync(fd, buffer, 0, MAX_OUTPUT, 0)).toString("utf8");
29873
30411
  } finally {
29874
- fs19.closeSync(fd);
30412
+ fs20.closeSync(fd);
29875
30413
  }
29876
30414
  } catch {
29877
30415
  }
29878
30416
  try {
29879
- await fs19.promises.unlink(outputFile);
30417
+ await fs20.promises.unlink(outputFile);
29880
30418
  } catch {
29881
30419
  }
29882
30420
  const parts = [
@@ -29950,8 +30488,9 @@ init_temporal();
29950
30488
  init_dependencies();
29951
30489
  init_basis_check();
29952
30490
  init_relationship_notice_check();
30491
+ init_watermarks();
29953
30492
  init_scope();
29954
- import { join as join26, resolve as resolve8 } from "node:path";
30493
+ import { join as join27, resolve as resolve9 } from "node:path";
29955
30494
  var contextIdentity = (context) => canonicalJson({
29956
30495
  scopeId: context.scopeId,
29957
30496
  basisRefs: context.basisRefs,
@@ -29963,8 +30502,8 @@ var contextIdentity = (context) => canonicalJson({
29963
30502
  function createNotificationStateReader() {
29964
30503
  const databases = /* @__PURE__ */ new Map();
29965
30504
  const checkers = /* @__PURE__ */ new Map();
29966
- const open3 = (path35) => {
29967
- const key4 = resolve8(path35);
30505
+ const open3 = (path36) => {
30506
+ const key4 = resolve9(path36);
29968
30507
  let db2 = databases.get(key4);
29969
30508
  if (!db2) {
29970
30509
  db2 = new DatabaseSync11(key4, { readOnly: true });
@@ -29999,14 +30538,14 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29999
30538
  const context = route.executionContext;
30000
30539
  const runtime = route.memoryRuntime ?? (route.hostDelivery ? { workspace: route.hostDelivery.workspace, stateDir: queueStateDir } : void 0);
30001
30540
  if (!context || !runtime) return {};
30002
- if (route.hostDelivery && resolve8(route.hostDelivery.workspace) !== resolve8(runtime.workspace)) {
30541
+ if (route.hostDelivery && resolve9(route.hostDelivery.workspace) !== resolve9(runtime.workspace)) {
30003
30542
  return { state: "blocked", reason: "MEMORY_NOTIFICATION_RUNTIME_MISMATCH", redact: true };
30004
30543
  }
30005
30544
  let memory;
30006
30545
  let proactive;
30007
30546
  let calendar;
30008
30547
  try {
30009
- memory = open3(join26(runtime.stateDir, "mem7", "index", "mem7.db"));
30548
+ memory = open3(join27(runtime.stateDir, "mem7", "index", "mem7.db"));
30010
30549
  const scope = memory.prepare("SELECT * FROM memory_scopes WHERE scope_id=?").get(context.scopeId);
30011
30550
  if (!scope) {
30012
30551
  return { state: "blocked", reason: "MEMORY_NOTIFICATION_SCOPE_MISSING", redact: true };
@@ -30033,7 +30572,8 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
30033
30572
  }
30034
30573
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
30035
30574
  const ledgerDependencies = new MemoryDependencies(memory, (operation) => operation());
30036
- proactive = open3(join26(runtime.workspace, ".proactive", "proactive.db"));
30575
+ const retractions = emptyRetractionCache();
30576
+ proactive = open3(join27(runtime.workspace, ".proactive", "proactive.db"));
30037
30577
  for (const id3 of Object.keys(context.actionVersions)) {
30038
30578
  const action = proactive.prepare("SELECT scope_id,intent_id FROM actions WHERE id=?").get(id3);
30039
30579
  if (!action || action.scope_id !== context.scopeId) return { state: "blocked", reason: "MEMORY_NOTIFICATION_ACTION_MISMATCH", redact: true };
@@ -30046,6 +30586,9 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
30046
30586
  const row = proactive.prepare("SELECT data FROM nodes WHERE id=?").get(nodeId);
30047
30587
  const data = row && JSON.parse(row.data);
30048
30588
  if (!data || data.scopeId !== context.scopeId || data.evidenceState === "deleted") return { state: "blocked", reason: "memory_deleted", redact: true };
30589
+ if (typeof data.sourceWatermark === "number" && typeof data.retractionWatermark === "number" && deletedWithinView(memory, context.scopeId, data.retractionWatermark, data.sourceWatermark, retractions)) {
30590
+ return { state: "blocked", reason: "memory_deleted", redact: true };
30591
+ }
30049
30592
  for (const evidence of [...data.sourceRefs ?? [], ...data.sourceEvidence ?? []]) {
30050
30593
  if (evidence.sourceId && deletedSource(evidence.sourceId)) return { state: "blocked", reason: "memory_deleted", redact: true };
30051
30594
  if (evidence.sourceId && Number.isSafeInteger(evidence.sourceVersion)) {
@@ -30087,7 +30630,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
30087
30630
  }
30088
30631
  if (route.hostDelivery) {
30089
30632
  if (!proactive) {
30090
- proactive = open3(join26(runtime.workspace, ".proactive", "proactive.db"));
30633
+ proactive = open3(join27(runtime.workspace, ".proactive", "proactive.db"));
30091
30634
  }
30092
30635
  const receipt = proactive.prepare("SELECT * FROM proactive_host_deliveries WHERE delivery_key=?").get(route.hostDelivery.key);
30093
30636
  if (!receipt || contextIdentity(JSON.parse(receipt.context_json)) !== contextIdentity(context)) {
@@ -30098,7 +30641,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
30098
30641
  if (["blocked", "delivery_unknown"].includes(receipt.state)) return { state: receipt.state, reason: receipt.reason ?? receipt.state };
30099
30642
  }
30100
30643
  if (context.calendarBinding) {
30101
- calendar = open3(join26(runtime.workspace, ".calendar", "calendar.db"));
30644
+ calendar = open3(join27(runtime.workspace, ".calendar", "calendar.db"));
30102
30645
  const binding = context.calendarBinding;
30103
30646
  const rows = calendar.prepare("SELECT state,closure FROM calendar_dispatches WHERE scope_id=? AND event_id=? AND occurrence_id=?").all(context.scopeId, binding.eventId, binding.occurrenceId);
30104
30647
  if (rows.some((row) => ["started", "delivery_unknown"].includes(row.state) && !row.closure)) {
@@ -30133,50 +30676,50 @@ var _taskOutputDir;
30133
30676
  function getTaskOutputDir() {
30134
30677
  if (_taskOutputDir === void 0) {
30135
30678
  const stateDir = process.env.ENGINE_STATE_DIR || process.cwd();
30136
- _taskOutputDir = path27.join(stateDir, "tasks");
30679
+ _taskOutputDir = path28.join(stateDir, "tasks");
30137
30680
  }
30138
30681
  return _taskOutputDir;
30139
30682
  }
30140
30683
  function getTaskOutputPath(taskId) {
30141
- return path27.join(getTaskOutputDir(), `${taskId}.output`);
30684
+ return path28.join(getTaskOutputDir(), `${taskId}.output`);
30142
30685
  }
30143
30686
  function ensureOutputDir() {
30144
30687
  const dir = getTaskOutputDir();
30145
- if (!fs20.existsSync(dir)) {
30146
- fs20.mkdirSync(dir, { recursive: true });
30688
+ if (!fs21.existsSync(dir)) {
30689
+ fs21.mkdirSync(dir, { recursive: true });
30147
30690
  }
30148
30691
  }
30149
30692
  function initTaskOutput(taskId) {
30150
30693
  ensureOutputDir();
30151
30694
  const outputPath = getTaskOutputPath(taskId);
30152
- fs20.writeFileSync(outputPath, "", "utf-8");
30695
+ fs21.writeFileSync(outputPath, "", "utf-8");
30153
30696
  return outputPath;
30154
30697
  }
30155
30698
  var tasks = /* @__PURE__ */ new Map();
30156
30699
  var processes = /* @__PURE__ */ new Map();
30157
- var taskIndexPath = () => path27.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "index.json");
30700
+ var taskIndexPath = () => path28.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "index.json");
30158
30701
  function persistTask(state) {
30159
30702
  try {
30160
30703
  ensureOutputDir();
30161
30704
  const p = taskIndexPath();
30162
- const existing = fs20.existsSync(p) ? JSON.parse(fs20.readFileSync(p, "utf8")) : [];
30705
+ const existing = fs21.existsSync(p) ? JSON.parse(fs21.readFileSync(p, "utf8")) : [];
30163
30706
  const next = existing.filter((t) => t.id !== state.id);
30164
30707
  next.push({ ...state });
30165
30708
  const tmp = `${p}.${process.pid}.tmp`;
30166
- fs20.writeFileSync(tmp, JSON.stringify(next, null, 2));
30167
- fs20.renameSync(tmp, p);
30709
+ fs21.writeFileSync(tmp, JSON.stringify(next, null, 2));
30710
+ fs21.renameSync(tmp, p);
30168
30711
  } catch (err) {
30169
30712
  console.warn(`[task-manager] persist failed: ${err.message}`);
30170
30713
  }
30171
30714
  }
30172
30715
  var pendingNotifications = [];
30173
30716
  var notificationsLoaded = false;
30174
- var notificationQueuePath = () => path27.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "notifications.json");
30717
+ var notificationQueuePath = () => path28.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "notifications.json");
30175
30718
  function loadNotificationQueue() {
30176
30719
  if (notificationsLoaded) return;
30177
30720
  notificationsLoaded = true;
30178
30721
  try {
30179
- const value = JSON.parse(fs20.readFileSync(notificationQueuePath(), "utf8"));
30722
+ const value = JSON.parse(fs21.readFileSync(notificationQueuePath(), "utf8"));
30180
30723
  if (Array.isArray(value)) pendingNotifications.push(...value.filter((x) => x && typeof x.notification === "string"));
30181
30724
  } catch {
30182
30725
  }
@@ -30186,8 +30729,8 @@ function persistNotificationQueue(strict = false) {
30186
30729
  ensureOutputDir();
30187
30730
  const p = notificationQueuePath();
30188
30731
  const tmp = `${p}.${process.pid}.tmp`;
30189
- fs20.writeFileSync(tmp, JSON.stringify(pendingNotifications, null, 2), "utf8");
30190
- fs20.renameSync(tmp, p);
30732
+ fs21.writeFileSync(tmp, JSON.stringify(pendingNotifications, null, 2), "utf8");
30733
+ fs21.renameSync(tmp, p);
30191
30734
  } catch (err) {
30192
30735
  if (strict) throw err;
30193
30736
  console.warn(`[task-manager] notification persist failed: ${err.message}`);
@@ -30341,7 +30884,7 @@ function syncPendingNotificationState(runtime) {
30341
30884
  try {
30342
30885
  for (const record2 of pendingNotifications) {
30343
30886
  const route = record2.route;
30344
- if (!route?.executionContext || runtime && (route.executionContext.scopeId !== runtime.scopeId || path27.resolve(route.memoryRuntime?.workspace ?? route.hostDelivery?.workspace ?? "") !== path27.resolve(runtime.workspace) || path27.resolve(route.memoryRuntime?.stateDir ?? process.env.ENGINE_STATE_DIR ?? process.cwd()) !== path27.resolve(runtime.stateDir))) {
30887
+ if (!route?.executionContext || runtime && (route.executionContext.scopeId !== runtime.scopeId || path28.resolve(route.memoryRuntime?.workspace ?? route.hostDelivery?.workspace ?? "") !== path28.resolve(runtime.workspace) || path28.resolve(route.memoryRuntime?.stateDir ?? process.env.ENGINE_STATE_DIR ?? process.cwd()) !== path28.resolve(runtime.stateDir))) {
30345
30888
  next.push(record2);
30346
30889
  continue;
30347
30890
  }
@@ -30382,7 +30925,7 @@ function spawnBackgroundTask(opts) {
30382
30925
  const taskId = generateTaskId("local_bash");
30383
30926
  const outputPath = initTaskOutput(taskId);
30384
30927
  const { shell, args: shellArgs } = findShell();
30385
- const outputFd = fs20.openSync(outputPath, "w");
30928
+ const outputFd = fs21.openSync(outputPath, "w");
30386
30929
  const child = spawn4(shell, [...shellArgs, opts.command], {
30387
30930
  cwd: opts.cwd,
30388
30931
  env: opts.env || process.env,
@@ -30393,7 +30936,7 @@ function spawnBackgroundTask(opts) {
30393
30936
  // 1011:GUI 宿主(Electron 装机版)下后台任务别闪黑窗,同 BashTool
30394
30937
  });
30395
30938
  try {
30396
- fs20.closeSync(outputFd);
30939
+ fs21.closeSync(outputFd);
30397
30940
  } catch {
30398
30941
  }
30399
30942
  return trackBackgroundTask(opts, child, outputPath, Date.now(), taskId);
@@ -30435,12 +30978,12 @@ function trackBackgroundTask(opts, child, outputPath, startTime, taskId) {
30435
30978
  let killedForSize = false;
30436
30979
  sizeWatchdog = setInterval(() => {
30437
30980
  if (tasks.get(taskId)?.status !== "running") return;
30438
- fs20.stat(outputPath, (err, st) => {
30981
+ fs21.stat(outputPath, (err, st) => {
30439
30982
  if (err || st.size <= MAX_TASK_OUTPUT_BYTES) return;
30440
30983
  killedForSize = true;
30441
30984
  if (sizeWatchdog) clearInterval(sizeWatchdog);
30442
30985
  try {
30443
- fs20.appendFileSync(outputPath, "\n[output truncated: exceeded 5GB disk cap]\n");
30986
+ fs21.appendFileSync(outputPath, "\n[output truncated: exceeded 5GB disk cap]\n");
30444
30987
  } catch {
30445
30988
  }
30446
30989
  killChild(child);
@@ -30570,22 +31113,6 @@ function killTask(taskId) {
30570
31113
  return true;
30571
31114
  }
30572
31115
 
30573
- // src/skills/skill-gate.ts
30574
- init_strip_injected();
30575
- var USER_CHANNELS = /* @__PURE__ */ new Set(["discord", "feishu", "wechat", "telegram", "cli", "console", "voice-chat", "deskBuddy", "ccBridge"]);
30576
- var loadedBySession = /* @__PURE__ */ new Map();
30577
- var MAX_TRACKED_SESSIONS = 100;
30578
- function beginSkillGate(sessionId) {
30579
- if (loadedBySession.size >= MAX_TRACKED_SESSIONS && !loadedBySession.has(sessionId)) {
30580
- const oldest = loadedBySession.keys().next().value;
30581
- if (oldest !== void 0) loadedBySession.delete(oldest);
30582
- }
30583
- loadedBySession.set(sessionId, /* @__PURE__ */ new Set());
30584
- }
30585
- function isUserChannel(ch) {
30586
- return !!ch && USER_CHANNELS.has(ch);
30587
- }
30588
-
30589
31116
  // src/core/query.ts
30590
31117
  function blockedToolCallsForOverride(calls, override2) {
30591
31118
  if (!override2) return [];
@@ -30657,12 +31184,12 @@ var QueryEngine = class _QueryEngine {
30657
31184
  try {
30658
31185
  const url = "https://localhost:8116/voice-reply";
30659
31186
  if (url.startsWith("https://")) {
30660
- const https = await import("node:https");
31187
+ const https2 = await import("node:https");
30661
31188
  const postData = JSON.stringify({ text: line, isPlaceholder: true });
30662
31189
  assertExternalEffectCurrent();
30663
31190
  beginHostTurnEffect();
30664
31191
  await new Promise((resolve13, reject) => {
30665
- const req = https.request(url, {
31192
+ const req = https2.request(url, {
30666
31193
  method: "POST",
30667
31194
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) },
30668
31195
  rejectUnauthorized: false
@@ -30871,7 +31398,7 @@ var QueryEngine = class _QueryEngine {
30871
31398
  let currentMessages = [...messages];
30872
31399
  const stopUserMessages = [];
30873
31400
  const stopToolResults = [];
30874
- const collectStopEvidence = !this.options.skipStopHook && !perTurnEmotion;
31401
+ const collectStopEvidence = !context?.projectTask && !this.options.skipStopHook && !perTurnEmotion;
30875
31402
  const currentUser = collectStopEvidence ? messages.findLast((m) => "role" in m && m.role === "user") : void 0;
30876
31403
  if (currentUser && "role" in currentUser) {
30877
31404
  stopUserMessages.push(currentUser.memoryOriginalText ?? (typeof currentUser.content === "string" ? currentUser.content : currentUser.content.filter((b) => b.type === "text").map((b) => b.text).join("\n")));
@@ -31165,6 +31692,7 @@ var QueryEngine = class _QueryEngine {
31165
31692
  provider: queryProvider,
31166
31693
  model: queryModel,
31167
31694
  identity,
31695
+ activeQueryId: queryId,
31168
31696
  hookContext: context ? {
31169
31697
  sessionId: compactSessionId,
31170
31698
  workspace: context.workspace || "",
@@ -31215,7 +31743,9 @@ var QueryEngine = class _QueryEngine {
31215
31743
  channel: context.channel || "console",
31216
31744
  cwd: context.workspace || process.env.ENGINE_WORKSPACE || ""
31217
31745
  } : void 0,
31218
- snapshotContext
31746
+ snapshotContext,
31747
+ false,
31748
+ queryId
31219
31749
  ).catch((error) => {
31220
31750
  throw new Error(`\u4E0A\u4E0B\u6587\u6574\u7406\u5931\u8D25\uFF08\u5BF9\u8BDD\u5DF2\u4FDD\u7559\uFF0C\u53EF\u7A0D\u540E\u91CD\u8BD5\u6216 /compact\uFF09\uFF1A${error instanceof Error ? error.message : error}`);
31221
31751
  });
@@ -31301,7 +31831,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
31301
31831
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
31302
31832
 
31303
31833
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31304
- if (process.env.ENGINE_DUMP_REQUEST === "1" && (!this.options.agentLabel || this.options.agentLabel === "main")) {
31834
+ if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
31305
31835
  try {
31306
31836
  const ws = process.env.ENGINE7_WORKSPACE;
31307
31837
  if (ws) {
@@ -31402,13 +31932,13 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31402
31932
  yield { type: "error", error: `\u4E0A\u4E0B\u6587\u8D85\u51FA\u6A21\u578B\u7A97\u53E3\uFF08\u8F93\u5165 ${overflow.inputTokens} / \u7A97\u53E3 ${overflow.contextLimit}\uFF09\uFF0C\u9700\u8981\u538B\u7F29\u540E\u624D\u80FD\u7EE7\u7EED\u3002` };
31403
31933
  return;
31404
31934
  }
31405
- const delay = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
31935
+ const delay2 = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
31406
31936
  if (streamRetries < MAX_STREAM_RETRIES && !ac.signal.aborted) {
31407
- console.log(`${this.logPrefix} Turn ${turnCount}: stream retry ${streamRetries + 1}/${MAX_STREAM_RETRIES}, delay=${delay}ms`);
31937
+ console.log(`${this.logPrefix} Turn ${turnCount}: stream retry ${streamRetries + 1}/${MAX_STREAM_RETRIES}, delay=${delay2}ms`);
31408
31938
  yield { type: "status", text: `\u26A0\uFE0F API error, retrying (${streamRetries + 1}/${MAX_STREAM_RETRIES})...` };
31409
31939
  this.phase = "tools";
31410
31940
  try {
31411
- await waitForRetry(delay, void 0, { signal: ac.signal });
31941
+ await waitForRetry(delay2, void 0, { signal: ac.signal });
31412
31942
  } catch (error) {
31413
31943
  if (!ac.signal.aborted) throw error;
31414
31944
  }
@@ -31545,7 +32075,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31545
32075
  completionReason = "output_limit";
31546
32076
  break;
31547
32077
  }
31548
- if (this.options.skipStopHook || perTurnEmotion) {
32078
+ if (context?.projectTask || this.options.skipStopHook || perTurnEmotion) {
31549
32079
  if (this.pendingSteers.length > 0) {
31550
32080
  const carried = carryReply();
31551
32081
  if (carried) yield* carried;
@@ -31854,8 +32384,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31854
32384
  return this.provider;
31855
32385
  }
31856
32386
  /** Share model configuration, but give concurrent sessions their own abort/steer/compact state. */
31857
- fork(agentLabel) {
31858
- const fork = new _QueryEngine(this.provider, { ...this.options, agentLabel });
32387
+ fork(agentLabel, prompts) {
32388
+ const fork = new _QueryEngine(this.provider, { ...this.options, ...prompts, agentLabel });
31859
32389
  fork.backgroundOwners = this.backgroundOwners;
31860
32390
  return fork;
31861
32391
  }
@@ -31999,9 +32529,9 @@ function readState(stateFile) {
31999
32529
  return { lastPatrolAt: 0, lastLineCounts: {} };
32000
32530
  }
32001
32531
  function writeState(stateFile, state) {
32002
- const dir = path29.dirname(stateFile);
32532
+ const dir = path30.dirname(stateFile);
32003
32533
  fsSync3.mkdirSync(dir, { recursive: true });
32004
- const tmp = path29.join(dir, `.${path29.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
32534
+ const tmp = path30.join(dir, `.${path30.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
32005
32535
  try {
32006
32536
  fsSync3.writeFileSync(tmp, JSON.stringify(state), "utf-8");
32007
32537
  fsSync3.renameSync(tmp, stateFile);
@@ -32030,7 +32560,7 @@ function buildPatrolPrompt(materials) {
32030
32560
  ].join("\n");
32031
32561
  }
32032
32562
  function defaultWriteMemoryNote(workspace) {
32033
- const dir = path29.join(getAutoMemPath(workspace), "whatsapp-patrol");
32563
+ const dir = path30.join(getAutoMemPath(workspace), "whatsapp-patrol");
32034
32564
  return (note) => {
32035
32565
  fsSync3.mkdirSync(dir, { recursive: true });
32036
32566
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
@@ -32044,7 +32574,7 @@ function defaultWriteMemoryNote(workspace) {
32044
32574
  note,
32045
32575
  ""
32046
32576
  ].join("\n");
32047
- fsSync3.writeFileSync(path29.join(dir, `patrol-${stamp}.md`), body, "utf-8");
32577
+ fsSync3.writeFileSync(path30.join(dir, `patrol-${stamp}.md`), body, "utf-8");
32048
32578
  };
32049
32579
  }
32050
32580
  function makeSubmitToMain(engineDeps) {
@@ -32189,15 +32719,15 @@ ${quoted}`);
32189
32719
 
32190
32720
  // src/utils/ffmpeg-path.ts
32191
32721
  init_dep_downloader();
32192
- import * as fs22 from "node:fs";
32722
+ import * as fs23 from "node:fs";
32193
32723
  function resolveFfmpegPath() {
32194
32724
  const env = (process.env.E7_FFMPEG_PATH || "").trim();
32195
- if (env && fs22.existsSync(env)) return env;
32725
+ if (env && fs23.existsSync(env)) return env;
32196
32726
  const downloaded = optionalFfmpegPath();
32197
32727
  if (downloaded) return downloaded;
32198
32728
  try {
32199
32729
  const p = __require("@ffmpeg-installer/ffmpeg")?.path;
32200
- if (p && fs22.existsSync(p)) return p;
32730
+ if (p && fs23.existsSync(p)) return p;
32201
32731
  } catch {
32202
32732
  }
32203
32733
  return "ffmpeg";
@@ -32283,10 +32813,10 @@ function normalizeAllowEntry(entry) {
32283
32813
  }
32284
32814
  function atomicWriteFile(dir, fileName, content) {
32285
32815
  fsSync4.mkdirSync(dir, { recursive: true });
32286
- const tmp = path30.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID18().slice(0, 8)}`);
32816
+ const tmp = path31.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID18().slice(0, 8)}`);
32287
32817
  try {
32288
32818
  fsSync4.writeFileSync(tmp, content, "utf-8");
32289
- fsSync4.renameSync(tmp, path30.join(dir, fileName));
32819
+ fsSync4.renameSync(tmp, path31.join(dir, fileName));
32290
32820
  } catch (e) {
32291
32821
  try {
32292
32822
  fsSync4.rmSync(tmp, { force: true });
@@ -32401,13 +32931,13 @@ var WhatsAppAdapter = class {
32401
32931
  constructor(cfg, opts = {}) {
32402
32932
  this.cfg = cfg;
32403
32933
  this.stateDir = cfg.stateDir;
32404
- this.authDir = path30.join(cfg.stateDir, "whatsapp-auth");
32405
- this.qrFilePath = path30.join(cfg.stateDir, "whatsapp-qr.txt");
32934
+ this.authDir = path31.join(cfg.stateDir, "whatsapp-auth");
32935
+ this.qrFilePath = path31.join(cfg.stateDir, "whatsapp-qr.txt");
32406
32936
  this.opts = opts;
32407
32937
  this.credsStore = opts.credsStoreOverride ?? makeCredsStore(this.authDir);
32408
32938
  this.loginTtlMs = opts.loginTtlMs ?? LOGIN_TTL_MS;
32409
32939
  this.digestEnabled = cfg.groupDigest?.enabled !== false;
32410
- this.digest = this.digestEnabled ? new GroupDigestStore(path30.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
32940
+ this.digest = this.digestEnabled ? new GroupDigestStore(path31.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
32411
32941
  this.typing = new PresenceTypingCoalescer(async (jid) => {
32412
32942
  const sock = this.sock;
32413
32943
  if (!sock || typeof sock.sendPresenceUpdate !== "function") return;
@@ -32542,7 +33072,7 @@ var WhatsAppAdapter = class {
32542
33072
  this.patrol = startPatrolLoop({
32543
33073
  digest: this.digest,
32544
33074
  intervalMin: this.cfg.groupDigest?.patrolIntervalMin ?? 60,
32545
- stateFile: path30.join(this.stateDir, "whatsapp-patrol-state.json"),
33075
+ stateFile: path31.join(this.stateDir, "whatsapp-patrol-state.json"),
32546
33076
  runReadOnlyAgent: makeReadOnlyAgentRunner(this.opts.patrolDeps),
32547
33077
  // ⚠️ 升级接线(终审 C1,1003):摘要含 ⚠️ 行时宿主经主 session 投递(spec §4)——
32548
33078
  // makeSubmitToMain 吃的正是 patrolDeps {dispatcher, deps}(patrol.ts)形状。漏接这行 =
@@ -32839,11 +33369,11 @@ ${r}` : r;
32839
33369
  const idRaw = typeof raw?.key?.id === "string" && raw.key.id ? raw.key.id : "";
32840
33370
  const idSafe = idRaw.replace(/[^\w.-]/g, "_");
32841
33371
  const id3 = !idRaw || idSafe !== idRaw || !idSafe ? randomUUID18() : idSafe;
32842
- const dir = path30.join(this.stateDir, "media", "whatsapp");
33372
+ const dir = path31.join(this.stateDir, "media", "whatsapp");
32843
33373
  fsSync4.mkdirSync(dir, { recursive: true });
32844
- const abs = path30.join(dir, `${id3}.${ext}`);
32845
- const resolved = path30.resolve(abs);
32846
- if (!resolved.startsWith(path30.resolve(dir) + path30.sep)) {
33374
+ const abs = path31.join(dir, `${id3}.${ext}`);
33375
+ const resolved = path31.resolve(abs);
33376
+ if (!resolved.startsWith(path31.resolve(dir) + path31.sep)) {
32847
33377
  console.warn(`[whatsapp] DM \u5A92\u4F53\u843D\u76D8\u8DEF\u5F84\u8D8A\u754C\uFF08\u62D2\u7EDD\u5199\u5165\uFF0C\u964D\u7EA7\u5360\u4F4D\u7B26\uFF09: ${id3}`);
32848
33378
  return `${placeholder}\uFF08\u4E0B\u8F7D\u5931\u8D25\uFF09`;
32849
33379
  }
@@ -32877,7 +33407,7 @@ ${r}` : r;
32877
33407
  const lids = [jid, participant].filter((j) => j.endsWith("@lid"));
32878
33408
  if (lids.length === 0) return;
32879
33409
  try {
32880
- const filePath2 = path30.join(this.authDir, "lid-mapping.json");
33410
+ const filePath2 = path31.join(this.authDir, "lid-mapping.json");
32881
33411
  let arr = [];
32882
33412
  try {
32883
33413
  const parsed = JSON.parse(fsSync4.readFileSync(filePath2, "utf-8"));
@@ -32987,7 +33517,7 @@ ${r}` : r;
32987
33517
  if (isGroupJid(jid)) throw new Error(`WhatsApp \u7FA4\u53D1\u9001\u7269\u7406\u4E0D\u5B58\u5728\uFF08\u7EA2\u7EBF\uFF09\uFF1Atarget=${jid}`);
32988
33518
  const sock = this.requireSock();
32989
33519
  const mime = attachment.mimeType ?? "";
32990
- const filename = attachment.filename ?? path30.basename(attachment.path);
33520
+ const filename = attachment.filename ?? path31.basename(attachment.path);
32991
33521
  if (mime.startsWith("image/")) {
32992
33522
  assertExternalEffectCurrent();
32993
33523
  const res2 = await sock.sendMessage(jid, { image: { url: attachment.path }, caption: message });
@@ -33016,8 +33546,8 @@ ${r}` : r;
33016
33546
  this.recordEcho(res2);
33017
33547
  return;
33018
33548
  }
33019
- const tmpDir = path30.join(this.stateDir, "whatsapp-media-tmp");
33020
- const dst = path30.join(tmpDir, `${randomUUID18()}.ogg`);
33549
+ const tmpDir = path31.join(this.stateDir, "whatsapp-media-tmp");
33550
+ const dst = path31.join(tmpDir, `${randomUUID18()}.ogg`);
33021
33551
  try {
33022
33552
  await (this.cfg.ffmpegTranscode ?? defaultFfmpegTranscode)(attachment.path, dst);
33023
33553
  assertExternalEffectCurrent();
@@ -33132,9 +33662,9 @@ function quotedTextOf(content) {
33132
33662
  }
33133
33663
 
33134
33664
  // src/channels/dingtalk.ts
33135
- import fs23 from "node:fs";
33136
- import path31 from "node:path";
33137
- import { createHash as createHash33, randomUUID as randomUUID19 } from "node:crypto";
33665
+ import fs24 from "node:fs";
33666
+ import path32 from "node:path";
33667
+ import { createHash as createHash34, randomUUID as randomUUID19 } from "node:crypto";
33138
33668
 
33139
33669
  // src/channels/dingtalk-stream.ts
33140
33670
  import { EventEmitter } from "node:events";
@@ -33606,11 +34136,10 @@ var DingTalkAdapter = class _DingTalkAdapter {
33606
34136
  throw new Error("dingtalk clientId/clientSecret \u672A\u914D\u7F6E\uFF08\u5F00\u53D1\u8005\u540E\u53F0 \u2192 \u5E94\u7528 \u2192 \u51ED\u8BC1\uFF09");
33607
34137
  }
33608
34138
  if (this.cfg.proxy) {
33609
- const { getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_withRetry(), withRetry_exports));
34139
+ const { createProxySocketAgent: createProxySocketAgent2, getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_adaptive_proxy(), adaptive_proxy_exports));
33610
34140
  const dispatcher = getProxyDispatcher2(this.cfg.proxy);
33611
34141
  this.baseFetch = (url, init) => this.fetchImpl(url, { ...init, dispatcher });
33612
- const { HttpsProxyAgent: HttpsProxyAgent3 } = await import("https-proxy-agent");
33613
- this.wsAgent = new HttpsProxyAgent3(this.cfg.proxy);
34142
+ this.wsAgent = createProxySocketAgent2(this.cfg.proxy);
33614
34143
  this.token = new DingTalkTokenManager(this.cfg.clientId, this.cfg.clientSecret, (u, i) => this.baseFetch(u, i), this.now);
33615
34144
  console.log(`[dingtalk] outbound via proxy ${this.cfg.proxy}`);
33616
34145
  }
@@ -33727,13 +34256,13 @@ var DingTalkAdapter = class _DingTalkAdapter {
33727
34256
  const res = await this.baseFetch(url, { signal: AbortSignal.timeout(3e4) });
33728
34257
  if (!res.ok) throw new Error(`media download HTTP ${res.status}`);
33729
34258
  const buf = Buffer.from(await res.arrayBuffer());
33730
- const dir = path31.join(this.cfg.stateDir, "media", "dingtalk");
33731
- fs23.mkdirSync(dir, { recursive: true });
34259
+ const dir = path32.join(this.cfg.stateDir, "media", "dingtalk");
34260
+ fs24.mkdirSync(dir, { recursive: true });
33732
34261
  const ext = m.kind === "image" ? "png" : m.kind === "video" ? "mp4" : "bin";
33733
- const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash33("sha1").update(m.code).digest("hex").slice(0, 12);
34262
+ const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash34("sha1").update(m.code).digest("hex").slice(0, 12);
33734
34263
  const safeCode = raw.replace(/[^a-zA-Z0-9_-]/g, "_");
33735
- const local = path31.join(dir, `${safeCode}.${ext}`);
33736
- fs23.writeFileSync(local, buf);
34264
+ const local = path32.join(dir, `${safeCode}.${ext}`);
34265
+ fs24.writeFileSync(local, buf);
33737
34266
  out.push({
33738
34267
  url: `file://${local}`,
33739
34268
  filename: m.filename ?? `${safeCode}.${ext}`,
@@ -33806,8 +34335,8 @@ var DingTalkAdapter = class _DingTalkAdapter {
33806
34335
  async sendFileNow(target, message, attachment) {
33807
34336
  const entry = this.registry.get(target);
33808
34337
  const robotCode = this.cfg.robotCode ?? this.cfg.clientId;
33809
- const buf = fs23.readFileSync(attachment.path);
33810
- const filename = (attachment.filename ?? path31.basename(attachment.path)).slice(0, 100);
34338
+ const buf = fs24.readFileSync(attachment.path);
34339
+ const filename = (attachment.filename ?? path32.basename(attachment.path)).slice(0, 100);
33811
34340
  const isImage = (attachment.mimeType ?? "").startsWith("image/") || /\.(png|jpe?g|gif|webp|bmp)$/i.test(filename);
33812
34341
  const mediaId = await this.uploadMedia(buf, filename, isImage ? "image" : "file");
33813
34342
  const msgKey = isImage ? "sampleImageMsg" : "sampleFileMsg";
@@ -34171,8 +34700,8 @@ var DING_EDIT_INTERVAL_MS = 300;
34171
34700
 
34172
34701
  // src/channels/wecom-stream.ts
34173
34702
  import { EventEmitter as EventEmitter2 } from "node:events";
34174
- import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
34175
- import { createHash as createHash34 } from "node:crypto";
34703
+ import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
34704
+ import { createHash as createHash35 } from "node:crypto";
34176
34705
  var WECOM_WS_URL = "wss://openws.work.weixin.qq.com";
34177
34706
  var HEARTBEAT_MS2 = 3e4;
34178
34707
  var ACK_TIMEOUT_MS = 15e3;
@@ -34497,7 +35026,7 @@ var WecomStreamClient = class extends EventEmitter2 {
34497
35026
  const item = {
34498
35027
  frame,
34499
35028
  // The ack event which pumps this queue has another async context. Keep the sender's guards.
34500
- send: AsyncLocalStorage8.bind((ws) => {
35029
+ send: AsyncLocalStorage9.bind((ws) => {
34501
35030
  assertExternalEffectCurrent();
34502
35031
  ws.send(JSON.stringify(frame));
34503
35032
  }),
@@ -34524,7 +35053,7 @@ var WecomStreamClient = class extends EventEmitter2 {
34524
35053
  if (!data.length) throw new Error("wecom uploadMedia: empty buffer");
34525
35054
  const totalChunks = Math.ceil(data.length / UPLOAD_CHUNK_BYTES);
34526
35055
  if (totalChunks > MAX_UPLOAD_CHUNKS) throw new Error(`wecom uploadMedia: too large (${totalChunks} chunks > ${MAX_UPLOAD_CHUNKS})`);
34527
- const md5 = createHash34("md5").update(data).digest("hex");
35056
+ const md5 = createHash35("md5").update(data).digest("hex");
34528
35057
  const initRes = await this.sendCommand("aibot_upload_media_init", {
34529
35058
  type,
34530
35059
  filename,
@@ -34552,8 +35081,8 @@ var WecomStreamClient = class extends EventEmitter2 {
34552
35081
  // src/channels/wecom.ts
34553
35082
  import { createDecipheriv as createDecipheriv3, randomUUID as randomUUID20 } from "node:crypto";
34554
35083
  import { readFileSync as readFileSync17 } from "node:fs";
34555
- import { mkdir as mkdir3, readFile, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
34556
- import path32 from "node:path";
35084
+ import { mkdir as mkdir4, readFile, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
35085
+ import path33 from "node:path";
34557
35086
  var WECOM_CONTENT_BYTES = 20480;
34558
35087
  var DEFAULT_MERGE_WINDOW_MS = 600;
34559
35088
  var REPLY_WINDOW_MS = 24 * 60 * 60 * 1e3;
@@ -34739,7 +35268,7 @@ var WecomAdapter = class {
34739
35268
  this.now = cfg.now ?? Date.now;
34740
35269
  this.sleepImpl = cfg.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
34741
35270
  this.fetchImpl = cfg.fetchImpl ?? fetch;
34742
- this.routesFile = path32.join(cfg.stateDir, "state", ROUTES_FILE);
35271
+ this.routesFile = path33.join(cfg.stateDir, "state", ROUTES_FILE);
34743
35272
  }
34744
35273
  /**
34745
35274
  * 载入落盘会话路由(1007:真机事故——注册表原本只存内存,引擎一重启"谁跟我说过话"全丢,
@@ -34783,7 +35312,7 @@ var WecomAdapter = class {
34783
35312
  try {
34784
35313
  const routes = {};
34785
35314
  for (const [chatId, e] of this.registry) routes[chatId] = { chatType: e.chatType, userId: e.userId };
34786
- await mkdir3(path32.dirname(this.routesFile), { recursive: true });
35315
+ await mkdir4(path33.dirname(this.routesFile), { recursive: true });
34787
35316
  await writeFile4(this.routesFile, JSON.stringify({ version: 1, routes }, null, 2) + "\n", "utf8");
34788
35317
  } catch (e) {
34789
35318
  console.warn(`[wecom] \u8DEF\u7531\u8868\u843D\u76D8\u5931\u8D25\uFF08\u672C\u8FDB\u7A0B\u5185\u51FA\u7AD9\u4E0D\u53D7\u5F71\u54CD\uFF09\uFF1A${e?.message ?? e}`);
@@ -34807,12 +35336,11 @@ var WecomAdapter = class {
34807
35336
  this.loadRoutes();
34808
35337
  let wsAgent;
34809
35338
  if (this.cfg.proxy) {
34810
- const { getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_withRetry(), withRetry_exports));
35339
+ const { createProxySocketAgent: createProxySocketAgent2, getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_adaptive_proxy(), adaptive_proxy_exports));
34811
35340
  const dispatcher = getProxyDispatcher2(this.cfg.proxy);
34812
35341
  const base = this.fetchImpl;
34813
35342
  this.fetchImpl = (url, init) => base(url, { ...init, dispatcher });
34814
- const { HttpsProxyAgent: HttpsProxyAgent3 } = await import("https-proxy-agent");
34815
- wsAgent = new HttpsProxyAgent3(this.cfg.proxy);
35343
+ wsAgent = createProxySocketAgent2(this.cfg.proxy);
34816
35344
  }
34817
35345
  let wsCtor = this.cfg.wsCtor;
34818
35346
  if (!wsCtor) {
@@ -35070,19 +35598,19 @@ ${parsed.inbound.content}`;
35070
35598
  /** 入站媒体:下载 → aeskey 解密 → 落盘 → 附件(单条失败不拖垮整条消息;全部失败给 content 加标记)。
35071
35599
  * 本地文件名一律由 msgid 派生(远端 filename 只做显示名)——防同名互相覆盖/超长(钉钉 1004 同款纪律)。 */
35072
35600
  async resolveInboundMedia(parsed) {
35073
- const dir = path32.join(this.cfg.stateDir, "media", "wecom");
35601
+ const dir = path33.join(this.cfg.stateDir, "media", "wecom");
35074
35602
  const attachments = [];
35075
35603
  let failed = 0;
35076
35604
  for (const [i, ref] of parsed.media.entries()) {
35077
35605
  try {
35078
- await mkdir3(dir, { recursive: true });
35606
+ await mkdir4(dir, { recursive: true });
35079
35607
  const res = await this.fetchImpl(ref.url, { signal: AbortSignal.timeout(3e4) });
35080
35608
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
35081
35609
  const raw = Buffer.from(await res.arrayBuffer());
35082
35610
  const data = ref.aeskey ? decryptWecomMedia(raw, ref.aeskey) : raw;
35083
35611
  const ext = ref.filename?.includes(".") ? ref.filename.split(".").pop().toLowerCase().slice(0, 8) : ref.kind === "image" ? "jpg" : ref.kind === "video" ? "mp4" : "bin";
35084
35612
  const localName = `wecom-${(parsed.msgId || String(this.now())).replace(/[^0-9A-Za-z_-]/g, "").slice(0, 32)}-${i}.${ext}`;
35085
- const file2 = path32.join(dir, localName);
35613
+ const file2 = path33.join(dir, localName);
35086
35614
  await writeFile4(file2, data);
35087
35615
  const displayName = (ref.filename || localName).slice(0, 120);
35088
35616
  attachments.push({
@@ -35113,7 +35641,7 @@ ${parsed.inbound.content}`;
35113
35641
  const entry = this.registry.get(target);
35114
35642
  if (!entry) throw new Error(`[wecom] \u65E0\u6CD5\u8DEF\u7531\u5A92\u4F53\u5230 ${target}\uFF08\u65E0\u4F1A\u8BDD\u6CE8\u518C\u8BB0\u5F55\uFF09`);
35115
35643
  await this.takeToken(target, false);
35116
- const filename = attachment.filename ?? path32.basename(attachment.path);
35644
+ const filename = attachment.filename ?? path33.basename(attachment.path);
35117
35645
  const { mediaId } = await this.requireStream().uploadMedia(data, type, filename);
35118
35646
  const body = type === "video" ? { msgtype: "video", video: { media_id: mediaId, title: filename } } : { msgtype: type, [type]: { media_id: mediaId } };
35119
35647
  await this.respondOrSend(entry, target, body);
@@ -35447,7 +35975,7 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
35447
35975
  // src/continuity/gateway-feishu.ts
35448
35976
  init_gateway_media();
35449
35977
  import * as lark2 from "@larksuiteoapi/node-sdk";
35450
- import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
35978
+ import { AsyncLocalStorage as AsyncLocalStorage10 } from "node:async_hooks";
35451
35979
  import { basename as basename6 } from "node:path";
35452
35980
 
35453
35981
  // src/continuity/gateway-feishu-render.ts
@@ -35480,7 +36008,7 @@ var quiet = { error: () => {
35480
36008
  }, debug: () => {
35481
36009
  }, trace: () => {
35482
36010
  } };
35483
- var dispatchContext = new AsyncLocalStorage9();
36011
+ var dispatchContext = new AsyncLocalStorage10();
35484
36012
  var format = "engine7-feishu-gateway-inbound-v1";
35485
36013
  function createFeishuGatewayDispatcher(options) {
35486
36014
  return new lark2.EventDispatcher({ verificationToken: options.verificationToken, encryptKey: options.encryptKey, logger: quiet }).register({
@@ -35666,9 +36194,9 @@ import { basename as basename7 } from "node:path";
35666
36194
  function createRemoteTravelChannel(block, stateDir, channel = "feishu") {
35667
36195
  if (!stateDir || !runtimeAuthorityFor(stateDir)) throw new Error("TRAVEL_GATEWAY_RUNTIME_REQUIRED");
35668
36196
  validateTravelChannels(stateDir, { [channel]: block });
35669
- const tls2 = block.gatewayTls;
35670
- if (!tls2 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls2[key4] !== "string" || !tls2[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35671
- const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls2.caFile, 1024 * 1024), cert: readPrivateFile(tls2.certFile, 1024 * 1024), key: readPrivateFile(tls2.keyFile, 16384) });
36197
+ const tls3 = block.gatewayTls;
36198
+ if (!tls3 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls3[key4] !== "string" || !tls3[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
36199
+ const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls3.caFile, 1024 * 1024), cert: readPrivateFile(tls3.certFile, 1024 * 1024), key: readPrivateFile(tls3.keyFile, 16384) });
35672
36200
  return new RemoteTravelChannel({ client, channel, permit: () => runtimeAuthorityFor(stateDir).assert("INPUT"), pollIntervalMs: block.gatewayPollIntervalMs });
35673
36201
  }
35674
36202
  var RemoteTravelChannel = class {
@@ -35858,9 +36386,9 @@ var RemoteTravelChannel = class {
35858
36386
  };
35859
36387
 
35860
36388
  // src/channels/private-library.ts
35861
- import fs24 from "node:fs/promises";
35862
- import path33 from "node:path";
35863
- import { createHash as createHash35 } from "node:crypto";
36389
+ import fs25 from "node:fs/promises";
36390
+ import path34 from "node:path";
36391
+ import { createHash as createHash36 } from "node:crypto";
35864
36392
 
35865
36393
  // src/channels/chan7-content.ts
35866
36394
  function fileMime(name) {
@@ -35872,8 +36400,8 @@ function fileMime(name) {
35872
36400
  function archive(manager, name, mime, bytes2, role, caption, identity) {
35873
36401
  const adapter = manager.getAdapter("chan7");
35874
36402
  if (!adapter?.files || bytes2.length > 16 * 1024 * 1024) return;
35875
- const safeName = path33.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
35876
- const key4 = createHash35("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
36403
+ const safeName = path34.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
36404
+ const key4 = createHash36("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
35877
36405
  try {
35878
36406
  adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key4);
35879
36407
  } catch (e) {
@@ -35883,9 +36411,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
35883
36411
  async function archivePrivateOutbound(manager, channel, target, text2, attachment, origin) {
35884
36412
  if (channel === "chan7" || origin?.channelType !== "dm" || origin.inboundIsBot || origin.channel !== channel || origin.channelTarget !== target || !manager.getAdapter("chan7")?.files) return;
35885
36413
  try {
35886
- const stat3 = await fs24.stat(attachment.path);
36414
+ const stat3 = await fs25.stat(attachment.path);
35887
36415
  if (!stat3.isFile() || stat3.size > 16 * 1024 * 1024) return;
35888
- const bytes2 = await fs24.readFile(attachment.path), name = attachment.filename ?? path33.basename(attachment.path);
36416
+ const bytes2 = await fs25.readFile(attachment.path), name = attachment.filename ?? path34.basename(attachment.path);
35889
36417
  archive(
35890
36418
  manager,
35891
36419
  name,
@@ -36083,6 +36611,16 @@ var ChannelManager = class {
36083
36611
  this.adapters.push(adapter);
36084
36612
  console.log(`[channels] Adapter registered: ${adapter.name}`);
36085
36613
  }
36614
+ /**
36615
+ * 当前可上报的聊天通道:只取 config 管起来、且建成了的那批(热加载后跟着变)。
36616
+ *
36617
+ * registerAdapter 注进来的不算——chan7 / console 终端是引擎自己的输入输出面,
36618
+ * 不是「用户拿什么聊」;取全部 adapters 的话每台新引擎至少会报 {"chan7":0,"console":0}。
36619
+ * 口径是「已启用」而不是「已连上」:connect 失败的通道也在这里(显示 0 条),装机列表列头有说明。
36620
+ */
36621
+ channelNames() {
36622
+ return [...this.managed.keys()];
36623
+ }
36086
36624
  /** 注册全局消息过滤器(所有通道生效) */
36087
36625
  addFilter(filter) {
36088
36626
  this.filters.push(filter);
@@ -36255,8 +36793,8 @@ var ChannelManager = class {
36255
36793
  /** 停止所有 adapter */
36256
36794
  async stopAll() {
36257
36795
  const results = await Promise.allSettled(this.adapters.map(async (adapter) => adapter.disconnect()));
36258
- const errors2 = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
36259
- if (errors2.length) throw new AggregateError(errors2, "CHANNEL_STOP_FAILED");
36796
+ const errors3 = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
36797
+ if (errors3.length) throw new AggregateError(errors3, "CHANNEL_STOP_FAILED");
36260
36798
  }
36261
36799
  /** 通道是否有已注册 adapter(投递前置判断用;1105 inbox-poller route 白名单替代硬编码) */
36262
36800
  hasChannel(channelName) {
@@ -36326,11 +36864,11 @@ var ChannelManager = class {
36326
36864
  }
36327
36865
  // === Streaming preview — 对齐 cc-connect 的 PreviewStarter/MessageUpdater/PreviewCleaner ===
36328
36866
  /** 发送初始 preview 消息 */
36329
- async sendPreview(channelName, channelId, content, agentName) {
36867
+ async sendPreview(channelName, channelId, content, agentName, presentation) {
36330
36868
  const adapter = this.adapters.find((a) => a.name === channelName);
36331
36869
  if (!adapter?.sendPreview) return null;
36332
36870
  if (hasMemoryEffectContext() && (!adapter.memoryGuardedSends || hasAutomaticMemoryEffectContext() && adapter.memoryGuardedAutomation === false)) throw new Error(`MEMORY_EXECUTION_BLOCKED: adapter ${channelName} has no final send guard`);
36333
- return guardedExternalEffect(() => adapter.sendPreview(channelId, content, agentName));
36871
+ return guardedExternalEffect(() => adapter.sendPreview(channelId, content, agentName, presentation));
36334
36872
  }
36335
36873
  /** 编辑已有的 preview 消息 */
36336
36874
  async editPreview(channelName, handle, content, agentName, isFinal) {
@@ -36365,12 +36903,12 @@ var quiet2 = { error: () => {
36365
36903
  }, debug: () => {
36366
36904
  }, trace: () => {
36367
36905
  } };
36368
- function path34(value) {
36906
+ function path35(value) {
36369
36907
  if (typeof value !== "string" || !isAbsolute5(value)) throw new Error("TRAVEL_GATEWAY_ABSOLUTE_PATH_REQUIRED");
36370
36908
  return resolve11(value);
36371
36909
  }
36372
- function tls(config) {
36373
- return { ca: readPrivateFile(path34(config?.caFile), 1024 * 1024), cert: readPrivateFile(path34(config?.certFile), 1024 * 1024), key: readPrivateFile(path34(config?.keyFile), 16384) };
36910
+ function tls2(config) {
36911
+ return { ca: readPrivateFile(path35(config?.caFile), 1024 * 1024), cert: readPrivateFile(path35(config?.certFile), 1024 * 1024), key: readPrivateFile(path35(config?.keyFile), 16384) };
36374
36912
  }
36375
36913
  async function startTravelGateway(config) {
36376
36914
  if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key4) => config.identity[key4] !== config.keyService.identity[key4])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
@@ -36378,9 +36916,9 @@ async function startTravelGateway(config) {
36378
36916
  for (const [name, value] of Object.entries(config.channels ?? {})) if (value?.enabled && !["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
36379
36917
  const feishuIngress = config.ingressEnabled !== false && config.feishu?.ingressEnabled !== false && config.channels?.feishu?.enabled !== false;
36380
36918
  if (feishuIngress && !/^cli_[0-9a-fA-F]{16}$/.test(config.feishu?.appId)) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
36381
- const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls(config.keyService.tls), timeoutMs: 1e4 };
36919
+ const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls2(config.keyService.tls), timeoutMs: 1e4 };
36382
36920
  const material = await fetchTravelKey(keyConfig);
36383
- const keyDigest = createHash36("sha256").update(material.key).digest("hex");
36921
+ const keyDigest = createHash37("sha256").update(material.key).digest("hex");
36384
36922
  let keyWatermark = material.deletionWatermark;
36385
36923
  const refreshInterval = config.keyRefreshIntervalMs ?? 1e4, maxKeyAge = config.keyMaxAgeMs ?? 3e4;
36386
36924
  if (!Number.isSafeInteger(refreshInterval) || refreshInterval < 100 || refreshInterval > 1e4 || !Number.isSafeInteger(maxKeyAge) || maxKeyAge < 2 * refreshInterval || maxKeyAge > 3e4) {
@@ -36421,18 +36959,18 @@ async function startTravelGateway(config) {
36421
36959
  }
36422
36960
  };
36423
36961
  try {
36424
- objects = await PublicationObjects.open({ directory: path34(config.objectsDir), identity: config.identity, key: material.key });
36425
- authority = new TravelAuthority({ directory: path34(config.authorityDir), leaseMs: config.leaseMs });
36962
+ objects = await PublicationObjects.open({ directory: path35(config.objectsDir), identity: config.identity, key: material.key });
36963
+ authority = new TravelAuthority({ directory: path35(config.authorityDir), leaseMs: config.leaseMs });
36426
36964
  if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
36427
36965
  for (const credential of Object.values(config.allowedPeers)) {
36428
36966
  const principal = authority.authenticate(String(credential));
36429
36967
  if (["tenantId", "companionId", "seatId"].some((key4) => principal[key4] !== config.identity[key4]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36430
36968
  }
36431
- store = new TravelGatewayStore({ directory: path34(config.gatewayDir), identity: config.identity, objects, authority });
36969
+ store = new TravelGatewayStore({ directory: path35(config.gatewayDir), identity: config.identity, objects, authority });
36432
36970
  await store.migrateStoredInputs();
36433
36971
  if (config.previouslyProcessedPlatformIds) store.importProcessedInputs(config.previouslyProcessedPlatformIds);
36434
36972
  platform = createFeishuGatewayPlatform(config.feishu);
36435
- server = createTravelGatewayServer({ ...tls(config.tls), store, authority, allowedPeers: config.allowedPeers, recoveryPeers: config.recoveryPeers, assertReady: assertKey, platform: { deliver: async (effect, body, assertCurrent) => {
36973
+ server = createTravelGatewayServer({ ...tls2(config.tls), store, authority, allowedPeers: config.allowedPeers, recoveryPeers: config.recoveryPeers, assertReady: assertKey, platform: { deliver: async (effect, body, assertCurrent) => {
36436
36974
  const packet = effect.kind === "MEDIA" ? (await Promise.resolve().then(() => (init_gateway_media(), gateway_media_exports))).decodeGatewayMedia(body).metadata : JSON.parse(body.toString());
36437
36975
  const channel = packet.channel ?? "feishu";
36438
36976
  if (channel === "feishu") return platform.deliver(effect, body, () => {
@@ -36453,7 +36991,7 @@ async function startTravelGateway(config) {
36453
36991
  if (config.control) {
36454
36992
  if (!Number.isSafeInteger(config.control.port) || config.control.port < 0 || config.control.port > 65535 || typeof config.control.host !== "string" || !config.control.host) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
36455
36993
  controlServer = createTravelAuthorityServer({
36456
- ...tls(config.control.tls ?? config.tls),
36994
+ ...tls2(config.control.tls ?? config.tls),
36457
36995
  authority,
36458
36996
  proxyFingerprints: config.control.proxyFingerprints,
36459
36997
  allowedPeers: config.control.allowedPeers,
@@ -36482,7 +37020,7 @@ async function startTravelGateway(config) {
36482
37020
  }
36483
37021
  });
36484
37022
  if (config.channels && config.ingressEnabled !== false) {
36485
- adapters.setFactoryContext({ stateDir: path34(config.platformStateDir) });
37023
+ adapters.setFactoryContext({ stateDir: path35(config.platformStateDir) });
36486
37024
  adapters.loadFromConfig(Object.fromEntries(Object.entries(config.channels).filter(([name, value]) => name !== "feishu" && value.enabled)));
36487
37025
  for (const channel of ["discord", "wechat"]) {
36488
37026
  const adapter = adapters.getAdapter(channel);
@@ -36545,7 +37083,7 @@ async function startTravelGateway(config) {
36545
37083
  checking = true;
36546
37084
  void fetchTravelKey(keyConfig).then((current2) => {
36547
37085
  try {
36548
- if (!objects || createHash36("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
37086
+ if (!objects || createHash37("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
36549
37087
  keyWatermark = current2.deletionWatermark;
36550
37088
  lastKeyCheck = Number(process.hrtime.bigint() / 1000000n);
36551
37089
  } finally {
@@ -36568,7 +37106,7 @@ async function startTravelGateway(config) {
36568
37106
  async function runTravelGatewayCli(args) {
36569
37107
  if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-gateway serve --config /absolute/private-config.json" };
36570
37108
  if (args.length !== 3 || args[0] !== "serve" || args[1] !== "--config") throw new Error("TRAVEL_GATEWAY_INVALID_COMMAND");
36571
- const config = JSON.parse(readPrivateFile(path34(args[2]), 65536).toString());
37109
+ const config = JSON.parse(readPrivateFile(path35(args[2]), 65536).toString());
36572
37110
  const gateway = await startTravelGateway(config);
36573
37111
  let closing = false;
36574
37112
  const stop = () => {
@@ -36590,7 +37128,7 @@ if (process.argv[1] && /[\\/](gateway-main\.ts|travel-gateway\.mjs)$/.test(proce
36590
37128
  // src/continuity/pairing-control.ts
36591
37129
  async function startPairingControl(config) {
36592
37130
  const directory2 = resolve12(config.directory), file2 = join32(directory2, "pairing.json"), read2 = (name) => readPrivateFile(join32(directory2, name), 65536);
36593
- const tls2 = { ca: read2("ca.pem"), cert: read2("server.pem"), key: read2("server.key") };
37131
+ const tls3 = { ca: read2("ca.pem"), cert: read2("server.pem"), key: read2("server.key") };
36594
37132
  const authority = new TravelAuthority({ directory: join32(directory2, "authority") });
36595
37133
  let binding;
36596
37134
  try {
@@ -36609,7 +37147,7 @@ async function startPairingControl(config) {
36609
37147
  const keys = new KeyServiceStore(join32(directory2, "keys"));
36610
37148
  const key4 = read2("data.key");
36611
37149
  try {
36612
- if (createHash37("sha256").update(key4).digest("hex") !== config.keySha256) throw new Error("TRAVEL_PAIRING_KEY");
37150
+ if (createHash38("sha256").update(key4).digest("hex") !== config.keySha256) throw new Error("TRAVEL_PAIRING_KEY");
36613
37151
  try {
36614
37152
  keys.assertIdentity(binding.keyIdentity);
36615
37153
  } catch {
@@ -36622,7 +37160,7 @@ async function startPairingControl(config) {
36622
37160
  } finally {
36623
37161
  key4.fill(0);
36624
37162
  }
36625
- const keyServer = createKeyServiceServer({ ...tls2, store: keys });
37163
+ const keyServer = createKeyServiceServer({ ...tls3, store: keys });
36626
37164
  await new Promise((done, reject) => {
36627
37165
  keyServer.once("error", reject);
36628
37166
  keyServer.listen(config.ports.key, "127.0.0.1", done);
@@ -36652,7 +37190,7 @@ async function startPairingControl(config) {
36652
37190
  let ingress = existsSync15(join32(directory2, "ingress-enabled.json"));
36653
37191
  let gateway = await startTravelGateway({ ...gatewayConfig, ingressEnabled: ingress, feishu: { ...gatewayConfig.feishu, ingressEnabled: ingress && config.channels?.feishu?.enabled === true } });
36654
37192
  let changing = false, closed = false;
36655
- const pairServer = createServer4({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
37193
+ const pairServer = createServer4({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
36656
37194
  res.setHeader("Content-Type", "application/json");
36657
37195
  res.setHeader("Cache-Control", "no-store");
36658
37196
  try {
@@ -36713,7 +37251,7 @@ async function startPairingControl(config) {
36713
37251
  keyServer.closeAllConnections();
36714
37252
  await new Promise((done) => keyServer.close(() => done()));
36715
37253
  keys.close();
36716
- tls2.key.fill(0);
37254
+ tls3.key.fill(0);
36717
37255
  };
36718
37256
  return { binding, keyServer, pairServer, get gateway() {
36719
37257
  return gateway;