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);
@@ -543,9 +543,9 @@ function assertPrivateStat(stat3, directory2) {
543
543
  if ((directory2 ? !stat3.isDirectory() : !stat3.isFile()) || process.platform !== "win32" && ((stat3.mode & 63) !== 0 || stat3.uid !== process.getuid?.()))
544
544
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
545
545
  }
546
- function readPrivateFile(path35, maximumBytes = 65536) {
547
- assertPrivateStat(lstatSync2(path35), false);
548
- const fd = openSync2(path35, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
546
+ function readPrivateFile(path36, maximumBytes = 65536) {
547
+ assertPrivateStat(lstatSync2(path36), false);
548
+ const fd = openSync2(path36, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
549
549
  try {
550
550
  const stat3 = fstatSync2(fd);
551
551
  assertPrivateStat(stat3, false);
@@ -565,14 +565,14 @@ var init_key_service_store = __esm({
565
565
  import { randomUUID as randomUUID3, verify as verify2 } from "node:crypto";
566
566
  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";
567
567
  import { basename, dirname as dirname2, join as join4, resolve as resolve3 } from "node:path";
568
- function assertPrivateDirectory2(path35) {
569
- const stat3 = lstatSync3(path35);
568
+ function assertPrivateDirectory2(path36) {
569
+ const stat3 = lstatSync3(path36);
570
570
  if (!stat3.isDirectory() || stat3.isSymbolicLink() || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
571
571
  }
572
- function readPrivateFile2(path35, maximum) {
573
- const before = lstatSync3(path35);
572
+ function readPrivateFile2(path36, maximum) {
573
+ const before = lstatSync3(path36);
574
574
  if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
575
- const fd = openSync3(path35, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
575
+ const fd = openSync3(path36, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
576
576
  try {
577
577
  if (fstatSync3(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
578
578
  return readFileSync2(fd);
@@ -580,12 +580,12 @@ function readPrivateFile2(path35, maximum) {
580
580
  closeSync3(fd);
581
581
  }
582
582
  }
583
- function writeControl(path35, value) {
584
- const temporary = path35 + "." + randomUUID3() + ".tmp";
583
+ function writeControl(path36, value) {
584
+ const temporary = path36 + "." + randomUUID3() + ".tmp";
585
585
  writeFileSync2(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
586
- renameSync(temporary, path35);
586
+ renameSync(temporary, path36);
587
587
  if (process.platform !== "win32") {
588
- const fd = openSync3(dirname2(path35), "r");
588
+ const fd = openSync3(dirname2(path36), "r");
589
589
  try {
590
590
  fsyncSync3(fd);
591
591
  } finally {
@@ -1896,14 +1896,14 @@ var init_live = __esm({
1896
1896
  }
1897
1897
  /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
1898
1898
  async persistToFile(dotPath, val, atomic = false) {
1899
- const fs25 = await import("node:fs");
1899
+ const fs26 = await import("node:fs");
1900
1900
  const cfgPath = this.current?._configFilePath;
1901
- if (!cfgPath || !fs25.existsSync(cfgPath)) {
1901
+ if (!cfgPath || !fs26.existsSync(cfgPath)) {
1902
1902
  console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
1903
1903
  return false;
1904
1904
  }
1905
1905
  try {
1906
- const raw = JSON.parse(fs25.readFileSync(cfgPath, "utf-8"));
1906
+ const raw = JSON.parse(fs26.readFileSync(cfgPath, "utf-8"));
1907
1907
  const keys = dotPath.split(".");
1908
1908
  let o = raw;
1909
1909
  for (let i = 0; i < keys.length - 1; i++) {
@@ -1913,7 +1913,7 @@ var init_live = __esm({
1913
1913
  o[keys[keys.length - 1]] = val;
1914
1914
  if (atomic) {
1915
1915
  writeConfigAtomic(cfgPath, raw);
1916
- } else fs25.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
1916
+ } else fs26.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
1917
1917
  const lastKey = keys[keys.length - 1].toLowerCase();
1918
1918
  const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
1919
1919
  const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
@@ -3351,7 +3351,7 @@ function textColumnOf(kind) {
3351
3351
  return "fact";
3352
3352
  }
3353
3353
  }
3354
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, bootAt, schemasCache, Mem7VectorStore;
3354
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3355
3355
  var init_vector_store = __esm({
3356
3356
  "src/mem7/core/vector-store.ts"() {
3357
3357
  "use strict";
@@ -3385,6 +3385,7 @@ var init_vector_store = __esm({
3385
3385
  RRF_K = 60;
3386
3386
  warnedFts = /* @__PURE__ */ new Set();
3387
3387
  warnedVecIdx = /* @__PURE__ */ new Set();
3388
+ incompatibleIndexSegments = (error) => error instanceof Error && error.message.includes("Index type URL should be present and identical across all segments");
3388
3389
  bootAt = Date.now();
3389
3390
  schemasCache = null;
3390
3391
  Mem7VectorStore = class {
@@ -3554,18 +3555,18 @@ var init_vector_store = __esm({
3554
3555
  * 快照版本——18:46 实测:香港相关 episode 在库、探针 BM25 可召回,线上 hybrid 却
3555
3556
  * 0 命中,时序与连续 3 次 conflict 吻合)。
3556
3557
  */
3557
- async ensureFtsIndexes(kind, tbl) {
3558
+ async ensureFtsIndexes(kind, tbl, indices) {
3558
3559
  const lance = await loadLance();
3559
3560
  if (!lance) return;
3560
- let existing = null;
3561
+ let existing;
3562
+ try {
3563
+ existing = new Set((indices ?? await tbl.listIndices()).filter((index) => index.indexType === "FTS").flatMap((index) => index.columns));
3564
+ } catch (err) {
3565
+ console.warn(`[mem7] FTS index check failed for ${kind}: ${err instanceof Error ? err.message : err}`);
3566
+ return;
3567
+ }
3561
3568
  for (const col of BM25_FIELDS[kind]) {
3562
3569
  try {
3563
- if (existing === null) {
3564
- existing = /* @__PURE__ */ new Set();
3565
- for (const idx of await tbl.listIndices()) {
3566
- if (idx.indexType === "FTS") for (const c of idx.columns) existing.add(c);
3567
- }
3568
- }
3569
3570
  if (existing.has(col)) continue;
3570
3571
  assertRuntimeAuthority(this.stateDir, "WRITE");
3571
3572
  await tbl.createIndex(col, {
@@ -3584,6 +3585,34 @@ var init_vector_store = __esm({
3584
3585
  }
3585
3586
  }
3586
3587
  }
3588
+ /** Called by the idle writer. Intel's all-in-one optimize can append an unreadable ANN delta
3589
+ * to a returned table, even with no new rows. Keep the existing ANN and let queries scan its tail. */
3590
+ async maintainIndexes(kind, canStart) {
3591
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
3592
+ const tbl = await this.table(kind);
3593
+ if (!canStart()) return;
3594
+ let indices;
3595
+ try {
3596
+ indices = await tbl.listIndices();
3597
+ } catch (error) {
3598
+ if (isIntelMac || !incompatibleIndexSegments(error)) throw error;
3599
+ const statsError = await tbl.indexStats("vector_idx").then(() => void 0, (failure2) => failure2);
3600
+ if (!incompatibleIndexSegments(statsError)) throw error;
3601
+ const lance = await loadLance();
3602
+ if (!lance || typeof lance.Index?.hnswSq !== "function") throw error;
3603
+ if (!canStart()) return;
3604
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3605
+ await tbl.createIndex("vector", { config: lance.Index.hnswSq({ distanceType: "cosine" }), replace: true });
3606
+ if (this.tables.get(kind) === tbl) this.vectorIndexesReady.add(kind);
3607
+ await this.ensureFtsIndexes(kind, tbl, await tbl.listIndices());
3608
+ console.log(`[mem7] ANN \u7D22\u5F15\u517C\u5BB9\u4FEE\u590D\u5B8C\u6210\uFF08${kind}.vector\uFF09`);
3609
+ return "repaired";
3610
+ }
3611
+ if (isIntelMac && indices.some((index) => index.columns.includes("vector"))) return "preserved";
3612
+ if (!canStart()) return;
3613
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3614
+ return tbl.optimize();
3615
+ }
3587
3616
  /**
3588
3617
  * ANN 向量索引(1004 妹妹 review 版):
3589
3618
  * - ★ **HNSW_SQ + distanceType:'cosine'**——距离必须配 cosine,不传默认 L2 与查询不兼容会
@@ -4332,6 +4361,45 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4332
4361
  }
4333
4362
  });
4334
4363
 
4364
+ // src/mem7/core/state/watermarks.ts
4365
+ function readRetractionSeq(db2, scope) {
4366
+ return Number(db2.prepare(`SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED}`).get(scope)?.seq ?? 0);
4367
+ }
4368
+ function readRetractionsSince(db2, scope, sinceSeq) {
4369
+ 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) => {
4370
+ const payload = JSON.parse(row.payload_json);
4371
+ const aggregate = !payload.targetKind || payload.targetKind === "source" ? [payload.aggregateId] : [];
4372
+ return { eventSeq: Number(row.event_seq), sourceIds: [.../* @__PURE__ */ new Set([...payload.sourceIds ?? [], ...aggregate])].filter((id3) => Boolean(id3)) };
4373
+ });
4374
+ }
4375
+ function readSourceSeq(db2, scope, sourceId) {
4376
+ const row = db2.prepare("SELECT source_seq FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, sourceId);
4377
+ return row && Number.isSafeInteger(row.source_seq) ? Number(row.source_seq) : null;
4378
+ }
4379
+ function deletionHits(db2, scope, events, sourceWatermark, sourceSeqs) {
4380
+ return events.some((event2) => event2.sourceIds.some((id3) => {
4381
+ const key4 = JSON.stringify([scope, id3]);
4382
+ if (!sourceSeqs.has(key4)) sourceSeqs.set(key4, readSourceSeq(db2, scope, id3));
4383
+ const seq = sourceSeqs.get(key4);
4384
+ return seq === null || seq <= sourceWatermark;
4385
+ }));
4386
+ }
4387
+ function deletedWithinView(db2, scope, sinceSeq, sourceWatermark, cache) {
4388
+ if (!cache.latest.has(scope)) cache.latest.set(scope, readRetractionSeq(db2, scope));
4389
+ if (cache.latest.get(scope) <= sinceSeq) return false;
4390
+ const key4 = JSON.stringify([scope, sinceSeq]);
4391
+ if (!cache.events.has(key4)) cache.events.set(key4, readRetractionsSince(db2, scope, sinceSeq));
4392
+ return deletionHits(db2, scope, cache.events.get(key4), sourceWatermark, cache.sourceSeqs);
4393
+ }
4394
+ var emptyRetractionCache, RETRACTED;
4395
+ var init_watermarks = __esm({
4396
+ "src/mem7/core/state/watermarks.ts"() {
4397
+ "use strict";
4398
+ emptyRetractionCache = () => ({ latest: /* @__PURE__ */ new Map(), events: /* @__PURE__ */ new Map(), sourceSeqs: /* @__PURE__ */ new Map() });
4399
+ RETRACTED = `kind IN ('evidence.retracted','memory.deleted')`;
4400
+ }
4401
+ });
4402
+
4335
4403
  // src/mem7/core/state/predicates.ts
4336
4404
  function hasReportedAttribution(text2, value, mentions) {
4337
4405
  const ref = value.attributionQuote;
@@ -4445,6 +4513,7 @@ var init_source_store = __esm({
4445
4513
  init_dependencies();
4446
4514
  init_knowledge_history();
4447
4515
  init_read_budget();
4516
+ init_watermarks();
4448
4517
  init_interpretation_impact();
4449
4518
  init_conversation_text();
4450
4519
  SOURCE_SCHEMA = `
@@ -4775,6 +4844,20 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4775
4844
  const row = this.db.prepare("SELECT fact_revision,source_seq,interpreted_seq FROM memory_scopes WHERE scope_id=?").get(scopeId(scope));
4776
4845
  return { factRevision: Number(row?.fact_revision ?? 0), sourceSeq: Number(row?.source_seq ?? 0), interpretedSeq: Number(row?.interpreted_seq ?? 0) };
4777
4846
  }
4847
+ /** Latest deletion or retraction event of the scope; 0 when none ever happened. */
4848
+ retractionSeq(scope) {
4849
+ return readRetractionSeq(this.db, scopeId(scope));
4850
+ }
4851
+ /** Sequence of a source whatever its status. get() hides deleted sources; this does not. */
4852
+ sourceSeqOf(scope, sourceId) {
4853
+ return readSourceSeq(this.db, scopeId(scope), sourceId);
4854
+ }
4855
+ /** A deletion after `sinceSeq` removed a source the node could have seen. One indexed lookup per scope
4856
+ * for the latest deletion, then one event query per (scope, watermark) per cache. */
4857
+ deletedWithinView(scope, sinceSeq, sourceWatermark, cache) {
4858
+ checkMemoryReadBudget();
4859
+ return deletedWithinView(this.db, scopeId(scope), sinceSeq, sourceWatermark, cache);
4860
+ }
4778
4861
  contextRevision(scope) {
4779
4862
  return Number(this.db.prepare("SELECT context_revision FROM memory_scopes WHERE scope_id=?").get(scopeId(scope))?.context_revision ?? 0);
4780
4863
  }
@@ -5307,8 +5390,8 @@ var init_recovery_deletion = __esm({
5307
5390
  const { owners, parents } = this.links(table, row);
5308
5391
  for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
5309
5392
  if (table === "memory_artifact_publications") {
5310
- const medium = text(row, "medium"), path35 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5311
- const identity = medium === "markdown" && path35 ? "file:mem7/" + path35 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash11("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5393
+ const medium = text(row, "medium"), path36 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5394
+ const identity = medium === "markdown" && path36 ? "file:mem7/" + path36 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash11("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5312
5395
  if (identity) {
5313
5396
  const rows = this.artifactPaths.get(identity) ?? [];
5314
5397
  rows.push(row);
@@ -5316,8 +5399,8 @@ var init_recovery_deletion = __esm({
5316
5399
  }
5317
5400
  }
5318
5401
  }
5319
- blocksArtifactPath(kind, path35) {
5320
- const rows = this.artifactPaths.get(kind + ":" + path35);
5402
+ blocksArtifactPath(kind, path36) {
5403
+ const rows = this.artifactPaths.get(kind + ":" + path36);
5321
5404
  return rows?.some((row) => this.blocks("memory_artifact_publications", row));
5322
5405
  }
5323
5406
  blocks(table, row) {
@@ -5994,16 +6077,15 @@ function stripInjectedContext(text2) {
5994
6077
  function escapeRegExp(s) {
5995
6078
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5996
6079
  }
5997
- var SKILL_GATE_HINT_PREFIX, SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
6080
+ var SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
5998
6081
  var init_strip_injected = __esm({
5999
6082
  "src/messages/strip-injected.ts"() {
6000
6083
  "use strict";
6001
- SKILL_GATE_HINT_PREFIX = "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1";
6002
6084
  SYSTEM_REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
6003
6085
  INJECT_SECTION_HEADS = /^(本轮对话|当前情绪状态|当前模式)/;
6004
6086
  KNOWN_INJECTED_TEXT = [
6005
- SKILL_GATE_HINT_PREFIX,
6006
- // skill-gate hint 默认/自定义前缀(1007 现行)
6087
+ "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1",
6088
+ // 旧版 skill-gate 提示前缀,兼容未打标签的历史
6007
6089
  "\u5F00\u53D1\u4EFB\u52A1\u8DEF\u6807\uFF0C\u6309\u573A\u666F\u5BF9\u53F7\u5165\u5EA7",
6008
6090
  // skill-gate hint(0912 老文案,历史 JSONL 兼容)
6009
6091
  "\u3010\u5B9A\u65F6\u5FC3\u8DF3\u3011\u8BF7 read HEARTBEAT.md"
@@ -6337,7 +6419,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6337
6419
  };
6338
6420
  const candidates2 = [];
6339
6421
  const duplicateIds = /* @__PURE__ */ new Set();
6340
- const inside = (path35) => path35 && !isAbsolute2(path35) && path35 !== ".." && !path35.startsWith(`..${sep2}`);
6422
+ const inside = (path36) => path36 && !isAbsolute2(path36) && path36 !== ".." && !path36.startsWith(`..${sep2}`);
6341
6423
  for (const relativePath of input.files) {
6342
6424
  const logical = resolve4(root, relativePath);
6343
6425
  let canonical4;
@@ -6351,10 +6433,10 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6351
6433
  gap("projection_path_unverified");
6352
6434
  continue;
6353
6435
  }
6354
- const path35 = relative2(root, canonical4).replace(/\\/g, "/");
6436
+ const path36 = relative2(root, canonical4).replace(/\\/g, "/");
6355
6437
  const user = `users/${input.scope.ownerId}/`;
6356
6438
  const agent = store.ownerProjectionPath("agents", input.scope.ownerId, input.scope).replace(/\\/g, "/") + "/";
6357
- 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;
6439
+ 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;
6358
6440
  if (!kind) {
6359
6441
  gap("projection_kind_or_owner_unverified");
6360
6442
  continue;
@@ -6391,9 +6473,9 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6391
6473
  continue;
6392
6474
  }
6393
6475
  const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key4, kind, match[1]);
6394
- const target = join8(store.mem7RootPath(), path35);
6476
+ const target = join8(store.mem7RootPath(), path36);
6395
6477
  if (previous) {
6396
- if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path35 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6478
+ if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path36 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6397
6479
  gap("projection_mapping_conflict");
6398
6480
  continue;
6399
6481
  }
@@ -6409,7 +6491,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6409
6491
  candidates2.push({
6410
6492
  file: canonical4,
6411
6493
  fileHash,
6412
- relativePath: path35,
6494
+ relativePath: path36,
6413
6495
  id: match[1],
6414
6496
  kind,
6415
6497
  parent,
@@ -7891,9 +7973,9 @@ function normalize3(input) {
7891
7973
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
7892
7974
  return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
7893
7975
  }
7894
- function directory(path35) {
7895
- const info = lstatSync6(path35);
7896
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path35) !== resolve5(path35) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
7976
+ function directory(path36) {
7977
+ const info = lstatSync6(path36);
7978
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path36) !== resolve5(path36) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
7897
7979
  throw new Error("REPLICATION_REGISTRATION_INVALID");
7898
7980
  }
7899
7981
  function readRuntimeReplicationRegistration(stateDir, component, key4) {
@@ -7997,10 +8079,10 @@ var init_runtime_replication = __esm({
7997
8079
 
7998
8080
  // src/memory/topics-history/index.ts
7999
8081
  import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
8000
- function parseTopicHistoryPath(path35) {
8001
- if (!path35.startsWith("topics-history://") || path35.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8082
+ function parseTopicHistoryPath(path36) {
8083
+ if (!path36.startsWith("topics-history://") || path36.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8002
8084
  try {
8003
- return JSON.parse(Buffer.from(path35.slice(17), "base64url").toString("utf8"));
8085
+ return JSON.parse(Buffer.from(path36.slice(17), "base64url").toString("utf8"));
8004
8086
  } catch {
8005
8087
  throw new Error("INVALID_HISTORY_REFERENCE");
8006
8088
  }
@@ -9692,11 +9774,13 @@ var init_facts = __esm({
9692
9774
  if (subjectIds?.length === 0) return [];
9693
9775
  const placeholders = subjectIds?.map(() => "?").join(",");
9694
9776
  const relations = relationshipPredicates.map((predicate) => `'${predicate}'`).join(",");
9777
+ const key4 = scopeId(scope);
9778
+ const incomingIds = includeIncoming ? subjectIds : void 0;
9695
9779
  return this.readTransaction(() => {
9696
- 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 (
9697
- 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 ?? [] : []);
9698
- const assertionsBySlot = this.versionsBySlot(scopeId(scope), knownAtRevision);
9699
- const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(scopeId(scope), knownAtRevision);
9780
+ 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 (
9781
+ 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] : []);
9782
+ const assertionsBySlot = this.versionsBySlot(key4, knownAtRevision);
9783
+ const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(key4, knownAtRevision);
9700
9784
  return slots.map((slot) => ({
9701
9785
  subjectId: slot.subject_id,
9702
9786
  predicate: slot.predicate,
@@ -9941,23 +10025,23 @@ var init_facts = __esm({
9941
10025
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
9942
10026
  }
9943
10027
  for (const [index, evidence] of proposal.evidence.entries()) {
9944
- const path35 = `evidence[${index}]`;
9945
- if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path35} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
10028
+ const path36 = `evidence[${index}]`;
10029
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path36} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
9946
10030
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
9947
10031
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
9948
10032
  AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
9949
- 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`);
9950
- 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`);
10033
+ 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`);
10034
+ 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`);
9951
10035
  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) {
9952
10036
  const count = occurrences(source.text, evidence.quote);
9953
- 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`);
10037
+ 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`);
9954
10038
  }
9955
- 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`);
10039
+ 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`);
9956
10040
  const relationValue = proposal.value;
9957
10041
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
9958
10042
  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");
9959
10043
  }
9960
- 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`);
10044
+ 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`);
9961
10045
  if (proposal.claimKind !== "inference") {
9962
10046
  if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
9963
10047
  if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
@@ -10338,6 +10422,7 @@ var init_store = __esm({
10338
10422
  init_change_feed();
10339
10423
  init_dependencies();
10340
10424
  init_tombstones();
10425
+ init_watermarks();
10341
10426
  init_scope();
10342
10427
  init_knowledge_history();
10343
10428
  init_host_turns();
@@ -10625,32 +10710,32 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10625
10710
  return { built: !hasStats, ms: Date.now() - started };
10626
10711
  }
10627
10712
  async close() {
10628
- const errors2 = [];
10713
+ const errors3 = [];
10629
10714
  try {
10630
10715
  this.capture?.close();
10631
10716
  } catch (error) {
10632
- errors2.push(error);
10717
+ errors3.push(error);
10633
10718
  }
10634
10719
  try {
10635
10720
  this.db.close();
10636
10721
  } catch (error) {
10637
- errors2.push(error);
10722
+ errors3.push(error);
10638
10723
  }
10639
10724
  try {
10640
10725
  await this.vectors?.close();
10641
10726
  } catch (error) {
10642
- errors2.push(error);
10727
+ errors3.push(error);
10643
10728
  } finally {
10644
10729
  this.vectors = null;
10645
10730
  }
10646
10731
  try {
10647
10732
  this.releaseRuntimeWriter?.();
10648
10733
  } catch (error) {
10649
- errors2.push(error);
10734
+ errors3.push(error);
10650
10735
  } finally {
10651
10736
  this.releaseRuntimeWriter = void 0;
10652
10737
  }
10653
- if (errors2.length) throw new AggregateError(errors2, "MEM7_CLOSE_FAILED");
10738
+ if (errors3.length) throw new AggregateError(errors3, "MEM7_CLOSE_FAILED");
10654
10739
  }
10655
10740
  // ── memcell 账本 ──────────────────────────────────────────
10656
10741
  insertMemcell(cell) {
@@ -10947,13 +11032,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10947
11032
  const version = expectedVersion ?? this.dependencies.version(scope, kind, id3);
10948
11033
  this.dependencies.assertCurrent(scope, kind, id3, version);
10949
11034
  const digest7 = createHash20("sha256").update(content.trim()).digest("hex");
10950
- const path35 = relative3(this.root, file2).replace(/\\/g, "/");
11035
+ const path36 = relative3(this.root, file2).replace(/\\/g, "/");
10951
11036
  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);
10952
- if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path35)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
11037
+ if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path36)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
10953
11038
  this.db.prepare(`INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)
10954
11039
  ON CONFLICT(scope_id,kind,entry_id) DO UPDATE SET path=excluded.path,version=excluded.version,digest=excluded.digest
10955
- WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path35, version, digest7);
10956
- this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path35, markdown: content.trim() });
11040
+ WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path36, version, digest7);
11041
+ this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path36, markdown: content.trim() });
10957
11042
  });
10958
11043
  }
10959
11044
  projectionMatches(scope, kind, id3, file2, content) {
@@ -11046,13 +11131,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11046
11131
  /** Interpretation reads entities, facts and confirmed mentions, independently of later chat intake. */
11047
11132
  interpretationReadStamp(scope, sourceIds, excludedPredicates = []) {
11048
11133
  return this.readTransaction(() => {
11049
- 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));
11134
+ const retractions = readRetractionSeq(this.db, scopeId(scope));
11050
11135
  const factRevision = excludedPredicates.length ? this.db.prepare(`SELECT slot_id,revision FROM fact_slots
11051
11136
  WHERE scope_id=? AND predicate NOT IN (${excludedPredicates.map(() => "?").join(",")}) ORDER BY slot_id`).all(scopeId(scope), ...excludedPredicates) : this.facts.revision(scope);
11052
11137
  return JSON.stringify([
11053
11138
  this.entities.revision(scope),
11054
11139
  factRevision,
11055
- retractions.seq,
11140
+ retractions,
11056
11141
  sourceIds.map((id3) => this.entities.sourceMentions(scope, id3))
11057
11142
  ]);
11058
11143
  });
@@ -11069,7 +11154,7 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11069
11154
  }
11070
11155
  /** History retrieval validates each publication; unrelated received/interpreted prose is not its basis. */
11071
11156
  captureHistoricalReadGuard(scope) {
11072
- 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;
11157
+ const stamp = () => readRetractionSeq(this.db, scopeId(scope));
11073
11158
  const captured = stamp();
11074
11159
  return () => {
11075
11160
  if (stamp() !== captured) throw new MemoryReadSupersededError();
@@ -11150,8 +11235,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11150
11235
  };
11151
11236
  }
11152
11237
  unscopedProjectionMatches(ownerId, kind, id3, file2, content) {
11153
- const path35 = relative3(this.root, file2).replace(/\\/g, "/");
11154
- const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path35);
11238
+ const path36 = relative3(this.root, file2).replace(/\\/g, "/");
11239
+ const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path36);
11155
11240
  if (mappings.length) {
11156
11241
  if (mappings.length !== 1) return false;
11157
11242
  const scope = this.sources.scope(mappings[0].scope_id);
@@ -14555,6 +14640,159 @@ var init_router = __esm({
14555
14640
  }
14556
14641
  });
14557
14642
 
14643
+ // src/services/adaptive-proxy.ts
14644
+ var adaptive_proxy_exports = {};
14645
+ __export(adaptive_proxy_exports, {
14646
+ createProxySocketAgent: () => createProxySocketAgent,
14647
+ getProxyDispatcher: () => getProxyDispatcher,
14648
+ isAdaptiveProxy: () => isAdaptiveProxy
14649
+ });
14650
+ import net from "node:net";
14651
+ import tls from "node:tls";
14652
+ import { HttpsProxyAgent } from "https-proxy-agent";
14653
+ import { Agent as Agent2, Client, ProxyAgent, errors as errors2 } from "undici";
14654
+ function proxyAddress(value) {
14655
+ const bareLoopback = /^(?:localhost\.?|127(?:\.\d{1,3}){3}|\[::1\]):\d+$/i;
14656
+ return new URL(bareLoopback.test(value) ? `http://${value}` : value);
14657
+ }
14658
+ function localProxyKey(url) {
14659
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
14660
+ const host = url.hostname.replace(/\.$/, "");
14661
+ if (host !== "localhost" && host !== "[::1]" && !/^127\./.test(host)) return;
14662
+ return `${host}:${url.port || (url.protocol === "https:" ? 443 : 80)}`;
14663
+ }
14664
+ function isAdaptiveProxy(proxy) {
14665
+ return localProxyKey(proxyAddress(proxy.trim())) !== void 0;
14666
+ }
14667
+ function proxyUnavailable(key4) {
14668
+ return (unreachableUntil.get(key4) ?? -Infinity) > Date.now();
14669
+ }
14670
+ function markUnavailable(key4) {
14671
+ unreachableUntil.set(key4, Date.now() + RETRY_PROXY_AFTER_MS);
14672
+ }
14673
+ function isTcpDialFailure(error) {
14674
+ if (error instanceof AggregateError) {
14675
+ return error.errors.length > 0 && error.errors.every(isTcpDialFailure);
14676
+ }
14677
+ const err = error;
14678
+ return err?.syscall === "connect" && dialFailureCodes.has(err.code ?? "");
14679
+ }
14680
+ function getProxyDispatcher(value) {
14681
+ const raw = value?.trim();
14682
+ if (!raw) return;
14683
+ const cached2 = dispatchers.get(raw);
14684
+ if (cached2) return cached2;
14685
+ const url = proxyAddress(raw);
14686
+ const key4 = localProxyKey(url);
14687
+ const dispatcher = key4 ? new AdaptiveProxyDispatcher(url.href, key4) : new ProxyAgent({ uri: url.href });
14688
+ dispatchers.set(raw, dispatcher);
14689
+ return dispatcher;
14690
+ }
14691
+ function createProxySocketAgent(value) {
14692
+ const url = proxyAddress(value.trim());
14693
+ const key4 = localProxyKey(url);
14694
+ return key4 ? new AdaptiveProxySocketAgent(url, key4) : new HttpsProxyAgent(url);
14695
+ }
14696
+ var RETRY_PROXY_AFTER_MS, LOCAL_CONNECT_TIMEOUT_MS, unreachableUntil, failedProxyDials, dispatchers, direct, dialFailureCodes, AdaptiveProxyDispatcher, AdaptiveProxySocketAgent;
14697
+ var init_adaptive_proxy = __esm({
14698
+ "src/services/adaptive-proxy.ts"() {
14699
+ "use strict";
14700
+ RETRY_PROXY_AFTER_MS = 5e3;
14701
+ LOCAL_CONNECT_TIMEOUT_MS = 1e3;
14702
+ unreachableUntil = /* @__PURE__ */ new Map();
14703
+ failedProxyDials = /* @__PURE__ */ new WeakSet();
14704
+ dispatchers = /* @__PURE__ */ new Map();
14705
+ direct = new Agent2();
14706
+ dialFailureCodes = /* @__PURE__ */ new Set(["ECONNREFUSED", "ETIMEDOUT", "ENETUNREACH", "EHOSTUNREACH", "EADDRNOTAVAIL"]);
14707
+ AdaptiveProxyDispatcher = class extends ProxyAgent {
14708
+ constructor(uri, key4) {
14709
+ super({
14710
+ uri,
14711
+ proxyTls: { timeout: LOCAL_CONNECT_TIMEOUT_MS },
14712
+ clientFactory(origin, opts) {
14713
+ const { connect } = opts;
14714
+ return new Client(origin, {
14715
+ connect(options, callback) {
14716
+ let tcpConnected = false;
14717
+ const socket = connect(options, (...result) => {
14718
+ const [error] = result;
14719
+ if (error && !tcpConnected && (isTcpDialFailure(error) || error.code === "UND_ERR_CONNECT_TIMEOUT")) {
14720
+ markUnavailable(key4);
14721
+ failedProxyDials.add(error);
14722
+ }
14723
+ callback(...result);
14724
+ });
14725
+ socket.once("connect", () => {
14726
+ tcpConnected = true;
14727
+ });
14728
+ return socket;
14729
+ }
14730
+ });
14731
+ }
14732
+ });
14733
+ this.key = key4;
14734
+ }
14735
+ dispatch(options, handler) {
14736
+ if (!this.closed && !this.destroyed && proxyUnavailable(this.key)) {
14737
+ const headers = options.headers;
14738
+ const keys = !headers ? [] : Array.isArray(headers) ? headers.filter((_, index) => index % 2 === 0) : Symbol.iterator in headers ? Array.from(headers, ([name]) => name) : Object.keys(headers);
14739
+ if (keys.some((name) => name.toLowerCase() === "proxy-authorization")) {
14740
+ throw new errors2.InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
14741
+ }
14742
+ return direct.dispatch(options, handler);
14743
+ }
14744
+ let connected = false;
14745
+ const extended = handler;
14746
+ const guarded = {
14747
+ onConnect: (abort) => {
14748
+ connected = true;
14749
+ handler.onConnect?.(abort);
14750
+ },
14751
+ onError: (error) => {
14752
+ if (!connected && failedProxyDials.has(error)) {
14753
+ direct.dispatch(options, handler);
14754
+ } else {
14755
+ handler.onError?.(error);
14756
+ }
14757
+ },
14758
+ onHeaders: handler.onHeaders?.bind(handler),
14759
+ onData: handler.onData?.bind(handler),
14760
+ onComplete: handler.onComplete?.bind(handler),
14761
+ onUpgrade: handler.onUpgrade?.bind(handler),
14762
+ onResponseStarted: handler.onResponseStarted?.bind(handler),
14763
+ onBodySent: handler.onBodySent?.bind(handler),
14764
+ onRequestSent: extended.onRequestSent?.bind(handler)
14765
+ };
14766
+ return super.dispatch(options, guarded);
14767
+ }
14768
+ };
14769
+ AdaptiveProxySocketAgent = class extends HttpsProxyAgent {
14770
+ constructor(url, key4) {
14771
+ super(url);
14772
+ this.key = key4;
14773
+ }
14774
+ async connect(req, opts) {
14775
+ if (!proxyUnavailable(this.key)) {
14776
+ try {
14777
+ return await super.connect(req, opts);
14778
+ } catch (error) {
14779
+ if (!isTcpDialFailure(error)) throw error;
14780
+ markUnavailable(this.key);
14781
+ if (req.destroyed) throw error;
14782
+ }
14783
+ }
14784
+ if (!opts.secureEndpoint) return net.connect({ ...opts, path: void 0 });
14785
+ const { host, servername } = opts;
14786
+ return tls.connect({
14787
+ ...opts,
14788
+ path: void 0,
14789
+ servername: servername ?? (host && !net.isIP(host) ? host : void 0)
14790
+ });
14791
+ }
14792
+ };
14793
+ }
14794
+ });
14795
+
14558
14796
  // src/calendar/dispatches.ts
14559
14797
  var dispatches_exports = {};
14560
14798
  __export(dispatches_exports, {
@@ -14615,10 +14853,10 @@ function installSQLiteWriteCapture(db2, source) {
14615
14853
  if (db2.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
14616
14854
  const exec = db2.exec, prepare = db2.prepare;
14617
14855
  let active, failed = false, closed = false, reading = false;
14618
- let direct;
14856
+ let direct2;
14619
14857
  const check = () => {
14620
14858
  if (closed) throw new Error("REPLICATION_TRANSACTION_CLOSED");
14621
- direct?.assertOpen();
14859
+ direct2?.assertOpen();
14622
14860
  };
14623
14861
  const wrappedExec = function(sql) {
14624
14862
  check();
@@ -14689,10 +14927,10 @@ function installSQLiteWriteCapture(db2, source) {
14689
14927
  db2.prepare = checkedPrepare;
14690
14928
  const transaction = (operation) => {
14691
14929
  check();
14692
- if (db2.isTransaction) return direct.scope(operation);
14930
+ if (db2.isTransaction) return direct2.scope(operation);
14693
14931
  db2.exec("BEGIN IMMEDIATE");
14694
14932
  try {
14695
- const result = direct.scope(operation);
14933
+ const result = direct2.scope(operation);
14696
14934
  if (result && typeof result.then === "function") throw new Error("REPLICATION_ASYNC_TRANSACTION");
14697
14935
  db2.exec("COMMIT");
14698
14936
  return result;
@@ -14701,10 +14939,10 @@ function installSQLiteWriteCapture(db2, source) {
14701
14939
  throw error;
14702
14940
  }
14703
14941
  };
14704
- direct = installAutocommitCapture(db2, transaction);
14942
+ direct2 = installAutocommitCapture(db2, transaction);
14705
14943
  return {
14706
14944
  assertOpen: check,
14707
- scope: (operation) => direct.scope(operation),
14945
+ scope: (operation) => direct2.scope(operation),
14708
14946
  transaction,
14709
14947
  close() {
14710
14948
  if (closed) return;
@@ -14713,7 +14951,7 @@ function installSQLiteWriteCapture(db2, source) {
14713
14951
  source.endCapture(active);
14714
14952
  active = void 0;
14715
14953
  }
14716
- direct.close();
14954
+ direct2.close();
14717
14955
  db2.prepare = prepare;
14718
14956
  db2.exec = exec;
14719
14957
  closed = true;
@@ -15212,8 +15450,8 @@ var init_graph_store = __esm({
15212
15450
  function graphNodeReadable(node, scope, allowGuarded = true) {
15213
15451
  return graphScopeId(node) === scope && !["needs_revalidation", "deleted"].includes(String(node.data.evidenceState)) && (allowGuarded || node.data.automationState !== "pending_execution_guard");
15214
15452
  }
15215
- function graphMemoryReferences(node) {
15216
- const refs = Array.isArray(node.data.memoryDependencies) ? structuredClone(node.data.memoryDependencies) : [];
15453
+ function graphOwnEvidence(node) {
15454
+ const refs = [];
15217
15455
  if (Array.isArray(node.data.sourceRefs)) for (const source of node.data.sourceRefs) refs.push({
15218
15456
  parentKind: "source",
15219
15457
  parentId: source.sourceId,
@@ -15233,6 +15471,9 @@ function graphMemoryReferences(node) {
15233
15471
  });
15234
15472
  return refs;
15235
15473
  }
15474
+ function graphMemoryReferences(node) {
15475
+ return [...Array.isArray(node.data.memoryDependencies) ? structuredClone(node.data.memoryDependencies) : [], ...graphOwnEvidence(node)];
15476
+ }
15236
15477
  function assertGraphMemoryReferences(memory, nodes, forGeneration = false) {
15237
15478
  const validate = createGraphMemoryValidator(memory);
15238
15479
  if (memory) memory.readTransaction(() => validate(nodes, forGeneration));
@@ -15240,6 +15481,8 @@ function assertGraphMemoryReferences(memory, nodes, forGeneration = false) {
15240
15481
  }
15241
15482
  function createGraphMemoryValidator(memory) {
15242
15483
  const checkedRefs = /* @__PURE__ */ new Set(), checkedSources = /* @__PURE__ */ new Set(), checkedRelations = /* @__PURE__ */ new Set();
15484
+ const scopes = /* @__PURE__ */ new Map();
15485
+ const retractions = emptyRetractionCache();
15243
15486
  return (nodes, forGeneration = false) => {
15244
15487
  const checkedScopes = /* @__PURE__ */ new Set();
15245
15488
  for (const node of nodes) {
@@ -15249,7 +15492,11 @@ function createGraphMemoryValidator(memory) {
15249
15492
  if (refs.length) throw new Error("GRAPH_MEMORY_SCOPE_REQUIRED");
15250
15493
  continue;
15251
15494
  }
15252
- const scope = memory?.sources.scope(scopeKey);
15495
+ let scope = scopes.get(scopeKey);
15496
+ if (scope === void 0) {
15497
+ scope = memory?.sources.scope(scopeKey) ?? null;
15498
+ scopes.set(scopeKey, scope);
15499
+ }
15253
15500
  if (!memory || !scope) throw new Error("GRAPH_MEMORY_READ_GUARD_REQUIRED");
15254
15501
  const unseen = [...new Map(refs.map((ref) => [JSON.stringify([scopeKey, ref]), ref])).entries()].filter(([key4]) => !checkedRefs.has(key4));
15255
15502
  memory.dependencies.assertReferences(scope, unseen.map(([, ref]) => ref));
@@ -15271,6 +15518,9 @@ function createGraphMemoryValidator(memory) {
15271
15518
  if (!record2 || record2.groundingState !== "current" || record2.recordVersion !== relation.recordVersion || record2.current !== relation.current) throw new Error("STALE_GRAPH_RELATIONSHIP");
15272
15519
  checkedRelations.add(relationshipKey);
15273
15520
  }
15521
+ if (typeof node.data.retractionWatermark === "number" && typeof node.data.sourceWatermark === "number" && memory.sources.deletedWithinView(scope, node.data.retractionWatermark, node.data.sourceWatermark, retractions)) {
15522
+ throw new Error("STALE_GRAPH_RETRACTION");
15523
+ }
15274
15524
  if (forGeneration && !checkedScopes.has(scopeKey)) {
15275
15525
  const snapshot = memory.sources.snapshot(scope);
15276
15526
  if (snapshot.interpretedSeq < snapshot.sourceSeq) throw new Error("SOURCE_INTERPRETATION_PENDING");
@@ -15284,6 +15534,7 @@ var init_graph_reads = __esm({
15284
15534
  "src/memory/proactive/graph-reads.ts"() {
15285
15535
  "use strict";
15286
15536
  init_graph_store();
15537
+ init_watermarks();
15287
15538
  graphScopeId = (node) => String(node.data.scopeId || "legacy");
15288
15539
  }
15289
15540
  });
@@ -15599,21 +15850,15 @@ CREATE TABLE graph_redirects (
15599
15850
  }
15600
15851
  }
15601
15852
  }
15602
- replace(node) {
15603
- const scope = String(node.data.scopeId ?? "legacy");
15604
- this.db.prepare("DELETE FROM graph_dependencies WHERE child_id=?").run(node.id);
15605
- const insert = this.db.prepare("INSERT OR IGNORE INTO graph_dependencies VALUES (?,?,?,?,?,?,?,?)");
15853
+ /** Rows the node must own. A repeated key keeps its first entry, as INSERT OR IGNORE did. */
15854
+ desiredRows(node, scope) {
15855
+ const rows = /* @__PURE__ */ new Map();
15856
+ const add = (kind, parentId, version, slotId, slotRevision, role) => {
15857
+ const key4 = JSON.stringify([scope, kind, parentId, role]);
15858
+ if (!rows.has(key4)) rows.set(key4, [scope, node.id, kind, parentId, version, slotId, slotRevision, role]);
15859
+ };
15606
15860
  const memoryRefs = Array.isArray(node.data.memoryDependencies) ? node.data.memoryDependencies : [];
15607
- for (const ref of memoryRefs) insert.run(
15608
- scope,
15609
- node.id,
15610
- ref.parentKind,
15611
- ref.parentId,
15612
- ref.parentVersion,
15613
- ref.slotId ?? null,
15614
- ref.slotRevision ?? null,
15615
- ref.role
15616
- );
15861
+ for (const ref of memoryRefs) add(ref.parentKind, ref.parentId, ref.parentVersion, ref.slotId ?? null, ref.slotRevision ?? null, ref.role);
15617
15862
  for (const parent of node.groundedIn) {
15618
15863
  let parentId = parent;
15619
15864
  let row = this.db.prepare("SELECT semantic_revision,data FROM nodes WHERE id=?").get(parentId);
@@ -15636,12 +15881,10 @@ CREATE TABLE graph_redirects (
15636
15881
  }
15637
15882
  const parentScope = String(JSON.parse(row.data).scopeId ?? "legacy");
15638
15883
  if (parentScope !== scope) throw new Error("GRAPH_DEPENDENCY_SCOPE_MISMATCH");
15639
- insert.run(scope, node.id, "node", parentId, row.semantic_revision, null, null, "supports");
15884
+ add("node", parentId, Number(row.semantic_revision), null, null, "supports");
15640
15885
  }
15641
15886
  const sources = Array.isArray(node.data.sourceRefs) ? node.data.sourceRefs : [];
15642
- for (const source of sources) insert.run(
15643
- scope,
15644
- node.id,
15887
+ for (const source of sources) add(
15645
15888
  "source",
15646
15889
  source.sourceId,
15647
15890
  source.sourceVersion,
@@ -15652,9 +15895,36 @@ CREATE TABLE graph_redirects (
15652
15895
  const facts = Array.isArray(node.data.basisRefs) ? node.data.basisRefs : [];
15653
15896
  for (const fact of facts) {
15654
15897
  if (fact.scopeId !== scope) throw new Error("GRAPH_FACT_SCOPE_MISMATCH");
15655
- insert.run(scope, node.id, "fact", fact.assertionId, fact.assertionVersion, fact.slotId, fact.slotRevision, "supports");
15656
- insert.run(scope, node.id, "entity", fact.subjectId, fact.subjectVersion ?? 1, null, null, "supports");
15898
+ add("fact", fact.assertionId, fact.assertionVersion, fact.slotId, fact.slotRevision, "supports");
15899
+ add("entity", fact.subjectId, fact.subjectVersion ?? 1, null, null, "supports");
15900
+ }
15901
+ return rows;
15902
+ }
15903
+ /** Brings the node's rows in line with its data. Unchanged rows are not written. */
15904
+ replace(node, options = {}) {
15905
+ const scope = String(node.data.scopeId ?? "legacy");
15906
+ const rows = this.desiredRows(node, scope);
15907
+ const insert = this.db.prepare("INSERT OR IGNORE INTO graph_dependencies VALUES (?,?,?,?,?,?,?,?)");
15908
+ if (options.fresh) {
15909
+ for (const row of rows.values()) insert.run(...row);
15910
+ return;
15911
+ }
15912
+ const remove = this.db.prepare("DELETE FROM graph_dependencies WHERE rowid=?");
15913
+ const update = this.db.prepare("UPDATE graph_dependencies SET parent_version=?, slot_id=?, slot_revision=? WHERE rowid=?");
15914
+ const present = /* @__PURE__ */ new Set();
15915
+ for (const row of this.db.prepare(`SELECT rowid rid, scope_id, parent_kind, parent_id, role, parent_version, slot_id, slot_revision
15916
+ FROM graph_dependencies WHERE child_id=?`).all(node.id)) {
15917
+ const key4 = JSON.stringify([row.scope_id, row.parent_kind, row.parent_id, row.role]);
15918
+ const want = rows.get(key4);
15919
+ if (!want) {
15920
+ remove.run(row.rid);
15921
+ continue;
15922
+ }
15923
+ present.add(key4);
15924
+ if (want[4] !== row.parent_version || want[5] !== row.slot_id || want[6] !== row.slot_revision)
15925
+ update.run(want[4], want[5], want[6], row.rid);
15657
15926
  }
15927
+ for (const [key4, row] of rows) if (!present.has(key4)) insert.run(...row);
15658
15928
  }
15659
15929
  /** parent_id 的全部失效别名:graph_redirects 图上与它同属一个重定向分量的全部 id
15660
15930
  * (双向多跳——按存活目标查要够到记旧 id 的存量行,按旧 id 查也要够到解析
@@ -15818,11 +16088,27 @@ var persistence_exports = {};
15818
16088
  __export(persistence_exports, {
15819
16089
  PROACTIVE_SCHEMA_VERSION: () => PROACTIVE_SCHEMA_VERSION,
15820
16090
  Persistence: () => Persistence,
15821
- normalizeToUtcIso: () => normalizeToUtcIso
16091
+ normalizeToUtcIso: () => normalizeToUtcIso,
16092
+ readableNodesSql: () => readableNodesSql
15822
16093
  });
15823
16094
  import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
15824
16095
  import { mkdirSync as mkdirSync11 } from "node:fs";
15825
16096
  import { basename as basename3, dirname as dirname7, resolve as resolve6 } from "node:path";
16097
+ function graphNodeFromRow(row) {
16098
+ return {
16099
+ id: row.id,
16100
+ type: row.type,
16101
+ data: JSON.parse(row.data),
16102
+ reasoning: row.reasoning ?? void 0,
16103
+ groundedIn: JSON.parse(row.grounded_in ?? "[]"),
16104
+ createdAt: row.created_at,
16105
+ lastAccessed: row.last_accessed,
16106
+ accessCount: row.access_count
16107
+ };
16108
+ }
16109
+ function readableNodesSql(allowGuarded) {
16110
+ return `SELECT * FROM nodes WHERE ${NODE_SCOPE}=? AND ${NODE_READABLE}=1${allowGuarded ? "" : ` AND ${NODE_UNGUARDED}=0`} ORDER BY rowid`;
16111
+ }
15826
16112
  function rowToAction(r) {
15827
16113
  return {
15828
16114
  id: r.id,
@@ -15856,7 +16142,7 @@ function normalizeToUtcIso(s) {
15856
16142
  if (!s) return s;
15857
16143
  return parseWall(s);
15858
16144
  }
15859
- var PROACTIVE_SCHEMA_VERSION, graphSubscribers, SCHEMA2, Persistence;
16145
+ var PROACTIVE_SCHEMA_VERSION, graphSubscribers, NODE_SCOPE, NODE_READABLE, NODE_UNGUARDED, SCHEMA2, Persistence;
15860
16146
  var init_persistence = __esm({
15861
16147
  "src/memory/proactive/persistence.ts"() {
15862
16148
  "use strict";
@@ -15879,6 +16165,9 @@ var init_persistence = __esm({
15879
16165
  init_runtime_lock();
15880
16166
  PROACTIVE_SCHEMA_VERSION = 12;
15881
16167
  graphSubscribers = /* @__PURE__ */ new Map();
16168
+ NODE_SCOPE = "COALESCE(NULLIF(json_extract(data,'$.scopeId'),''),'legacy')";
16169
+ NODE_READABLE = `CASE WHEN COALESCE(json_extract(data,'$.evidenceState'),'undefined') IN ('needs_revalidation','deleted') THEN 0 ELSE 1 END`;
16170
+ NODE_UNGUARDED = "CASE WHEN json_extract(data,'$.automationState')='pending_execution_guard' THEN 1 ELSE 0 END";
15882
16171
  SCHEMA2 = `
15883
16172
  CREATE TABLE IF NOT EXISTS nodes (
15884
16173
  id TEXT PRIMARY KEY,
@@ -16035,6 +16324,13 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16035
16324
  name: "rebuildable-person-node-index",
16036
16325
  apply: (db2) => db2.exec(PERSON_INDEX_SCHEMA)
16037
16326
  }]);
16327
+ if (!registration && !options.replication) {
16328
+ try {
16329
+ this.db.exec(`CREATE INDEX IF NOT EXISTS idx_nodes_readable ON nodes(${NODE_SCOPE}, ${NODE_READABLE}, ${NODE_UNGUARDED})`);
16330
+ } catch (error) {
16331
+ console.warn(`[proactive] readable-node index not built, reads fall back to a scan: ${error.message}`);
16332
+ }
16333
+ }
16038
16334
  this.db.exec("PRAGMA journal_mode=WAL");
16039
16335
  this.intentRuns = new IntentRunStore(this.db, (fn) => this.withMemoryTransaction(fn), () => this.loadNodes(), () => this.loadEdges(), memory);
16040
16336
  this.projection = new ProjectionInbox(this.db);
@@ -16195,6 +16491,10 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16195
16491
  ownsIntentRun(run, now2 = Date.now()) {
16196
16492
  return this.intentRuns.owns(run, now2);
16197
16493
  }
16494
+ /** A worker opens its graph before its memory store exists; the first store to arrive stays for the life of the handle. */
16495
+ attachMemory(memory) {
16496
+ if (!this.memory) this.memory = memory;
16497
+ }
16198
16498
  withMemoryTransaction(operation) {
16199
16499
  return this.memory ? this.memory.transaction(() => this.transaction(operation)) : this.transaction(operation);
16200
16500
  }
@@ -16240,15 +16540,21 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16240
16540
  loadGraphSnapshot(ids) {
16241
16541
  const read2 = () => {
16242
16542
  if (!ids) return { nodes: this.loadNodes(), edges: this.loadEdges(), revision: this.graphRevision() };
16243
- const keys = [...new Set(ids)];
16244
- const nodes = keys.map((id3) => this.loadNodeById(id3)).filter((node) => node !== void 0);
16245
- const edges = new Map(keys.flatMap((id3) => this.loadIncidentEdges(id3)).map((edge) => [edgeKey(edge.source, edge.target, edge.edgeType), edge]));
16246
- return { nodes, edges: [...edges.values()], revision: this.graphRevision() };
16543
+ const keys = new Set(ids);
16544
+ if (!keys.size) return { nodes: [], edges: [], revision: this.graphRevision() };
16545
+ const rows = this.db.prepare(`SELECT n.* FROM json_each(?) AS requested
16546
+ JOIN nodes n ON n.id=requested.value ORDER BY requested.key`).iterate(JSON.stringify([...keys]));
16547
+ const nodes = Array.from(rows, graphNodeFromRow);
16548
+ let edges = this.loadIncidentEdgesFor(keys);
16549
+ if (new Set(edges.map((edge) => edgeKey(edge.source, edge.target, edge.edgeType))).size !== edges.length) {
16550
+ edges = [...new Map([...keys].flatMap((id3) => this.loadIncidentEdges(id3)).map((edge) => [edgeKey(edge.source, edge.target, edge.edgeType), edge])).values()];
16551
+ }
16552
+ return { nodes, edges, revision: this.graphRevision() };
16247
16553
  };
16248
16554
  return this.readGraphTransaction(read2);
16249
16555
  }
16250
16556
  readGraphTransaction(read2) {
16251
- if (this.inTransaction) return read2();
16557
+ if (this.db.isTransaction) return read2();
16252
16558
  this.db.exec("BEGIN");
16253
16559
  try {
16254
16560
  const snapshot = read2();
@@ -16266,36 +16572,23 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16266
16572
  values.push(type);
16267
16573
  }
16268
16574
  if (scope !== void 0) {
16269
- clauses.push("COALESCE(NULLIF(json_extract(data,'$.scopeId'),''),'legacy')=?");
16575
+ clauses.push(`${NODE_SCOPE}=?`);
16270
16576
  values.push(scope);
16271
16577
  }
16272
- const rows = this.db.prepare("SELECT * FROM nodes" + (clauses.length ? " WHERE " + clauses.join(" AND ") : "")).iterate(...values);
16273
- return Array.from(rows, (r) => ({
16274
- id: r.id,
16275
- type: r.type,
16276
- data: JSON.parse(r.data),
16277
- reasoning: r.reasoning ?? void 0,
16278
- groundedIn: JSON.parse(r.grounded_in ?? "[]"),
16279
- createdAt: r.created_at,
16280
- lastAccessed: r.last_accessed,
16281
- accessCount: r.access_count
16282
- }));
16578
+ const rows = this.db.prepare("SELECT * FROM nodes" + (clauses.length ? " WHERE " + clauses.join(" AND ") : "") + (scope === void 0 ? "" : " ORDER BY rowid")).iterate(...values);
16579
+ return Array.from(rows, graphNodeFromRow);
16283
16580
  }
16284
16581
  /** 单行读(1016:touched-row 校验用——旧 updateNodeRow 为找前像整表 loadNodes(),
16285
16582
  * 每次 touch/更新都全库扫一遍,是图写路径的隐藏大头) */
16286
16583
  loadNodeById(id3) {
16287
- const r = this.db.prepare("SELECT * FROM nodes WHERE id=?").get(id3);
16288
- if (!r) return void 0;
16289
- return {
16290
- id: r.id,
16291
- type: r.type,
16292
- data: JSON.parse(r.data),
16293
- reasoning: r.reasoning ?? void 0,
16294
- groundedIn: JSON.parse(r.grounded_in ?? "[]"),
16295
- createdAt: r.created_at,
16296
- lastAccessed: r.last_accessed,
16297
- accessCount: r.access_count
16298
- };
16584
+ const row = this.db.prepare("SELECT * FROM nodes WHERE id=?").get(id3);
16585
+ return row ? graphNodeFromRow(row) : void 0;
16586
+ }
16587
+ /** The scope's nodes whose state is readable, in the order a full scope read has. With the index only those
16588
+ * rows are touched; without it the same conditions scan the table. */
16589
+ loadReadableNodes(scope, allowGuarded) {
16590
+ const rows = this.db.prepare(readableNodesSql(allowGuarded)).iterate(scope);
16591
+ return Array.from(rows, graphNodeFromRow);
16299
16592
  }
16300
16593
  /** 定向邻接边读(1016:basis/删除校验用,替代全表 loadEdges) */
16301
16594
  loadIncidentEdges(id3) {
@@ -16322,8 +16615,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16322
16615
  loadEdgesAmong(ids) {
16323
16616
  if (!ids.size) return [];
16324
16617
  const keys = JSON.stringify([...ids]);
16325
- const rows = this.db.prepare(`SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?))
16326
- AND target IN (SELECT value FROM json_each(?))`).iterate(keys, keys);
16618
+ const rows = this.db.prepare(`WITH visible(value) AS MATERIALIZED (SELECT value FROM json_each(?))
16619
+ SELECT e.* FROM edges e JOIN visible s ON e.source = s.value JOIN visible t ON e.target = t.value
16620
+ ORDER BY e.source,e.target,e.edge_type`).iterate(keys);
16327
16621
  return Array.from(rows, (row) => ({
16328
16622
  source: row.source,
16329
16623
  target: row.target,
@@ -16332,6 +16626,29 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16332
16626
  createdAt: row.created_at
16333
16627
  }));
16334
16628
  }
16629
+ /** Every edge with an end in the set, in one query; one lookup per node costs one round trip each. */
16630
+ loadIncidentEdgesFor(ids) {
16631
+ if (!ids.size) return [];
16632
+ const keys = JSON.stringify([...ids]);
16633
+ const rows = this.db.prepare(`WITH members(value) AS MATERIALIZED (SELECT value FROM json_each(?))
16634
+ SELECT source, target, edge_type, weight, created_at FROM edges WHERE source IN (SELECT value FROM members)
16635
+ UNION
16636
+ SELECT source, target, edge_type, weight, created_at FROM edges WHERE target IN (SELECT value FROM members)`).all(keys);
16637
+ return rows.map((r) => ({
16638
+ source: r.source,
16639
+ target: r.target,
16640
+ edgeType: r.edge_type,
16641
+ weight: r.weight,
16642
+ createdAt: r.created_at
16643
+ }));
16644
+ }
16645
+ /** Nodes of these types in the scope with no edge at either end, named by the indexes alone. */
16646
+ isolatedNodeIds(types, scope) {
16647
+ return this.db.prepare(`SELECT n.id FROM nodes n WHERE n.type IN (SELECT value FROM json_each(?))
16648
+ ${scope === void 0 ? "" : `AND (${NODE_SCOPE}=? OR json_type(n.data,'$.scopeId') NOT IN ('text','null'))`}
16649
+ AND NOT EXISTS (SELECT 1 FROM edges e WHERE e.source = n.id)
16650
+ 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));
16651
+ }
16335
16652
  // === 图:写(GraphStore 镜像调用) ===
16336
16653
  insertNode(node) {
16337
16654
  this.transaction(() => {
@@ -16515,7 +16832,7 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16515
16832
  "INSERT INTO edges (source, target, edge_type, weight, created_at) VALUES (?,?,?,?,?)"
16516
16833
  );
16517
16834
  for (const e of edges) insEdge.run(e.source, e.target, e.edgeType, e.weight, e.createdAt);
16518
- for (const node of nodes) this.dependencies.replace(node);
16835
+ for (const node of nodes) this.dependencies.replace(node, { fresh: true });
16519
16836
  this.personNodes.rebuild(nodes);
16520
16837
  this.noteGraphChange();
16521
16838
  });
@@ -17001,8 +17318,22 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
17001
17318
  /** Fast invalidation runs before any model work and commits with the consumer receipt. */
17002
17319
  invalidateMemoryEvent(event2) {
17003
17320
  const affected = new Set(this.dependencies.affected(event2));
17004
- const updated = [];
17005
17321
  const scope = this.memory?.sources.scope(event2.scopeId);
17322
+ if (event2.kind === "evidence.retracted" || event2.kind === "memory.deleted") {
17323
+ if (!this.memory) {
17324
+ 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.`);
17325
+ } else if (scope) {
17326
+ const deleted = [...new Set(event2.targetKind && event2.targetKind !== "source" ? event2.sourceIds : [...event2.sourceIds, event2.aggregateId])].filter(Boolean);
17327
+ if (deleted.length) {
17328
+ const seqs = deleted.map((id3) => this.memory.sources.sourceSeqOf(scope, id3));
17329
+ const known = seqs.filter((seq) => seq !== null);
17330
+ const oldest = known.length < seqs.length ? 0 : Math.min(...known);
17331
+ for (const row of this.db.prepare(`SELECT id FROM nodes WHERE json_extract(data,'$.scopeId')=? AND json_extract(data,'$.sourceWatermark')>=?
17332
+ AND COALESCE(json_extract(data,'$.retractionWatermark'),0)<?`).all(event2.scopeId, oldest, event2.eventSeq)) affected.add(row.id);
17333
+ }
17334
+ }
17335
+ }
17336
+ const updated = [];
17006
17337
  if (event2.kind === "memory.deleted" && scope && this.memory) {
17007
17338
  this.memory.readTransaction(() => {
17008
17339
  for (const node of this.loadNodes().filter((node2) => node2.data.scopeId === event2.scopeId)) {
@@ -17150,7 +17481,7 @@ __export(voice_chat_tts_daemon_exports, {
17150
17481
  stopTtsDaemon: () => stopTtsDaemon
17151
17482
  });
17152
17483
  import { spawn } from "child_process";
17153
- import net from "net";
17484
+ import net2 from "net";
17154
17485
  import path13 from "path";
17155
17486
  import fs10 from "fs";
17156
17487
  function _log(msg2) {
@@ -17158,7 +17489,7 @@ function _log(msg2) {
17158
17489
  }
17159
17490
  function _healthOnce() {
17160
17491
  return new Promise((resolve12) => {
17161
- const sock = net.connect(SOCK_PATH);
17492
+ const sock = net2.connect(SOCK_PATH);
17162
17493
  sock.setTimeout(2e3);
17163
17494
  sock.on("connect", () => {
17164
17495
  sock.write(JSON.stringify({ action: "health" }) + "\n");
@@ -17211,9 +17542,6 @@ async function startTtsDaemon(warmupCfg) {
17211
17542
  _log(`spawning ${script}`);
17212
17543
  const env = {
17213
17544
  ...process.env,
17214
- // 显式注入代理(dashscope SDK 不自动读系统代理)
17215
- HTTP_PROXY: process.env.HTTP_PROXY || "http://127.0.0.1:7892",
17216
- HTTPS_PROXY: process.env.HTTPS_PROXY || "http://127.0.0.1:7892",
17217
17545
  TTS_DAEMON_SOCK: SOCK_PATH,
17218
17546
  ...warmupCfg?.apiKey ? { ALIYUN_API_KEY: warmupCfg.apiKey } : {},
17219
17547
  ...warmupCfg?.model ? { TTS_MODEL: warmupCfg.model } : {},
@@ -17283,7 +17611,6 @@ __export(withRetry_exports, {
17283
17611
  getRetryDelay: () => getRetryDelay,
17284
17612
  readWithTimeout: () => readWithTimeout
17285
17613
  });
17286
- import { ProxyAgent } from "undici";
17287
17614
  function sleep2(ms, signal) {
17288
17615
  return new Promise((resolve12, reject) => {
17289
17616
  if (signal?.aborted) {
@@ -17351,15 +17678,6 @@ function shouldRetry(status, errorBody) {
17351
17678
  if (errorBody?.includes('"type":"overloaded_error"')) return true;
17352
17679
  return false;
17353
17680
  }
17354
- function getProxyDispatcher(proxyUrl) {
17355
- if (!proxyUrl) return void 0;
17356
- let agent = proxyAgentCache.get(proxyUrl);
17357
- if (!agent) {
17358
- agent = new ProxyAgent({ uri: proxyUrl });
17359
- proxyAgentCache.set(proxyUrl, agent);
17360
- }
17361
- return agent;
17362
- }
17363
17681
  async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, retryPolicy) {
17364
17682
  const configuredRetries = getMaxRetries();
17365
17683
  const maxRetries = retryPolicy?.maxRetries === void 0 ? configuredRetries : Math.min(configuredRetries, Math.max(0, Math.floor(retryPolicy.maxRetries)));
@@ -17409,17 +17727,17 @@ async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, r
17409
17727
  }
17410
17728
  if (attempt <= maxRetries && shouldRetry(status, errorBody)) {
17411
17729
  const retryAfter = response.headers.get("retry-after");
17412
- let delay = getRetryDelay(attempt, retryAfter);
17730
+ let delay2 = getRetryDelay(attempt, retryAfter);
17413
17731
  if (retryPolicy?.maxDelayMs !== void 0) {
17414
17732
  const retryAt = retryAfter && !/^\d+$/.test(retryAfter.trim()) ? Date.parse(retryAfter) : NaN;
17415
- if (Number.isFinite(retryAt)) delay = Math.max(0, retryAt - Date.now());
17416
- if (delay > retryPolicy.maxDelayMs) return response;
17733
+ if (Number.isFinite(retryAt)) delay2 = Math.max(0, retryAt - Date.now());
17734
+ if (delay2 > retryPolicy.maxDelayMs) return response;
17417
17735
  }
17418
17736
  console.log(
17419
- `[${label}] Retry ${attempt}/${maxRetries} after HTTP ${status}, delay=${delay}ms, url=${url}` + (retryAfter ? `, retry-after=${retryAfter}` : "") + (errorBody ? `, body=${errorBody}` : "")
17737
+ `[${label}] Retry ${attempt}/${maxRetries} after HTTP ${status}, delay=${delay2}ms, url=${url}` + (retryAfter ? `, retry-after=${retryAfter}` : "") + (errorBody ? `, body=${errorBody}` : "")
17420
17738
  );
17421
- yield { type: "api_retry", reason: `HTTP ${status}`, attempt, maxRetries, delayMs: delay, status };
17422
- await sleep2(delay, userSignal);
17739
+ yield { type: "api_retry", reason: `HTTP ${status}`, attempt, maxRetries, delayMs: delay2, status };
17740
+ await sleep2(delay2, userSignal);
17423
17741
  continue;
17424
17742
  }
17425
17743
  return response;
@@ -17436,10 +17754,10 @@ async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, r
17436
17754
  console.log(
17437
17755
  `[${label}] Timeout retry ${attempt}/${maxRetries} (${timeout}ms)`
17438
17756
  );
17439
- const delay = getRetryDelay(attempt);
17440
- if (retryPolicy?.maxDelayMs !== void 0 && delay > retryPolicy.maxDelayMs) throw err;
17441
- yield { type: "api_retry", reason: "timeout", attempt, maxRetries, delayMs: delay };
17442
- await sleep2(delay, init.signal ?? void 0);
17757
+ const delay2 = getRetryDelay(attempt);
17758
+ if (retryPolicy?.maxDelayMs !== void 0 && delay2 > retryPolicy.maxDelayMs) throw err;
17759
+ yield { type: "api_retry", reason: "timeout", attempt, maxRetries, delayMs: delay2 };
17760
+ await sleep2(delay2, init.signal ?? void 0);
17443
17761
  continue;
17444
17762
  }
17445
17763
  throw new Error(
@@ -17448,14 +17766,14 @@ async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, r
17448
17766
  }
17449
17767
  lastError = err;
17450
17768
  if (isConnectionError(err) && attempt <= maxRetries) {
17451
- const delay = getRetryDelay(attempt);
17452
- if (retryPolicy?.maxDelayMs !== void 0 && delay > retryPolicy.maxDelayMs) throw err;
17769
+ const delay2 = getRetryDelay(attempt);
17770
+ if (retryPolicy?.maxDelayMs !== void 0 && delay2 > retryPolicy.maxDelayMs) throw err;
17453
17771
  const cause = err?.cause ? ` cause=${err.cause.code ?? err.cause.message}` : "";
17454
17772
  console.log(
17455
- `[${label}] Connection error retry ${attempt}/${maxRetries}: ${err.message}${cause}, delay=${delay}ms`
17773
+ `[${label}] Connection error retry ${attempt}/${maxRetries}: ${err.message}${cause}, delay=${delay2}ms`
17456
17774
  );
17457
- yield { type: "api_retry", reason: `connection: ${err.message}`, attempt, maxRetries, delayMs: delay };
17458
- await sleep2(delay, init.signal ?? void 0);
17775
+ yield { type: "api_retry", reason: `connection: ${err.message}`, attempt, maxRetries, delayMs: delay2 };
17776
+ await sleep2(delay2, init.signal ?? void 0);
17459
17777
  continue;
17460
17778
  }
17461
17779
  throw err;
@@ -17497,10 +17815,11 @@ function readWithTimeout(reader, timeoutMs, signal) {
17497
17815
  if (onAbort) signal?.removeEventListener("abort", onAbort);
17498
17816
  });
17499
17817
  }
17500
- 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;
17818
+ var DEFAULT_MAX_RETRIES, BASE_DELAY_MS, MAX_DELAY_MS, DEFAULT_TIMEOUT_MS, READ_TIMEOUT_MS, FIRST_READ_TIMEOUT_MS, NO_PROGRESS_TIMEOUT_MS;
17501
17819
  var init_withRetry = __esm({
17502
17820
  "src/services/withRetry.ts"() {
17503
17821
  "use strict";
17822
+ init_adaptive_proxy();
17504
17823
  DEFAULT_MAX_RETRIES = 10;
17505
17824
  BASE_DELAY_MS = 500;
17506
17825
  MAX_DELAY_MS = 32e3;
@@ -17508,7 +17827,6 @@ var init_withRetry = __esm({
17508
17827
  READ_TIMEOUT_MS = 6e4;
17509
17828
  FIRST_READ_TIMEOUT_MS = parseInt(process.env.API_TIMEOUT_MS || "", 10) || 6e5;
17510
17829
  NO_PROGRESS_TIMEOUT_MS = parseInt(process.env.STREAM_NO_PROGRESS_TIMEOUT_MS || "", 10) || 3e5;
17511
- proxyAgentCache = /* @__PURE__ */ new Map();
17512
17830
  }
17513
17831
  });
17514
17832
 
@@ -17545,26 +17863,26 @@ __export(paths_exports, {
17545
17863
  isAutoMemPath: () => isAutoMemPath,
17546
17864
  setMemoryDirOverride: () => setMemoryDirOverride
17547
17865
  });
17548
- import { join as join27, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve10 } from "node:path";
17866
+ import { join as join22, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve8 } from "node:path";
17549
17867
  function setMemoryDirOverride(dir) {
17550
17868
  _overrideMemoryDir = dir;
17551
17869
  }
17552
17870
  function getAutoMemPath(workspace) {
17553
- const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve10(workspace, _overrideMemoryDir) : join27(workspace, AUTO_MEM_DIRNAME);
17871
+ const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve8(workspace, _overrideMemoryDir) : join22(workspace, AUTO_MEM_DIRNAME);
17554
17872
  const normalized = normalize5(dir);
17555
17873
  return (normalized + sep4).normalize("NFC");
17556
17874
  }
17557
17875
  function getAutoMemEntrypoint(workspace) {
17558
- return join27(getAutoMemPath(workspace), ENTRYPOINT_NAME);
17876
+ return join22(getAutoMemPath(workspace), ENTRYPOINT_NAME);
17559
17877
  }
17560
17878
  function isAutoMemPath(absolutePath, workspace) {
17561
17879
  const normalizedPath = normalize5(absolutePath);
17562
17880
  return normalizedPath.startsWith(getAutoMemPath(workspace));
17563
17881
  }
17564
17882
  async function ensureMemoryDirExists(memoryDir) {
17565
- const fs25 = await import("node:fs");
17883
+ const fs26 = await import("node:fs");
17566
17884
  try {
17567
- await fs25.promises.mkdir(memoryDir, { recursive: true });
17885
+ await fs26.promises.mkdir(memoryDir, { recursive: true });
17568
17886
  } catch (e) {
17569
17887
  const code = e?.code;
17570
17888
  if (code !== "EEXIST") {
@@ -17840,10 +18158,12 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
17840
18158
  function buildMemoryPrompt(params) {
17841
18159
  const { displayName, memoryDir, extraGuidelines } = params;
17842
18160
  const entrypoint = join28(memoryDir, ENTRYPOINT_NAME);
17843
- let entrypointContent = "";
17844
- try {
17845
- entrypointContent = readFileSync15(entrypoint, { encoding: "utf-8" });
17846
- } catch {
18161
+ let entrypointContent = params.entrypointContent ?? "";
18162
+ if (params.entrypointContent === void 0) {
18163
+ try {
18164
+ entrypointContent = readFileSync15(entrypoint, "utf-8");
18165
+ } catch {
18166
+ }
17847
18167
  }
17848
18168
  const lines = buildMemoryLines(displayName, memoryDir, extraGuidelines);
17849
18169
  if (entrypointContent.trim()) {
@@ -17887,8 +18207,8 @@ __export(context_analyzer_exports, {
17887
18207
  formatContextReport: () => formatContextReport,
17888
18208
  scanMemoryFiles: () => scanMemoryFiles
17889
18209
  });
17890
- import * as fs21 from "node:fs";
17891
- import * as path28 from "node:path";
18210
+ import * as fs22 from "node:fs";
18211
+ import * as path29 from "node:path";
17892
18212
  function estimateMessageTokens2(m) {
17893
18213
  let tokens = 0;
17894
18214
  if (typeof m.content === "string") {
@@ -17998,9 +18318,9 @@ function breakdownMessages(messages) {
17998
18318
  }
17999
18319
  async function scanMemoryFiles(workspace) {
18000
18320
  const files = [];
18001
- const soul = readFileIfExists(path28.join(workspace, "SOUL.md"));
18321
+ const soul = readFileIfExists(path29.join(workspace, "SOUL.md"));
18002
18322
  if (soul) files.push({ path: "SOUL.md", tokens: roughTokenCountEstimation(soul), stable: true });
18003
- const agents = readFileIfExists(path28.join(workspace, "AGENTS.md"));
18323
+ const agents = readFileIfExists(path29.join(workspace, "AGENTS.md"));
18004
18324
  if (agents) files.push({ path: "AGENTS.md", tokens: roughTokenCountEstimation(agents), stable: true });
18005
18325
  try {
18006
18326
  const { buildMemoryPrompt: buildMemoryPrompt2 } = await Promise.resolve().then(() => (init_memdir(), memdir_exports));
@@ -18016,7 +18336,7 @@ async function scanMemoryFiles(workspace) {
18016
18336
  }
18017
18337
  function readFileIfExists(filePath2) {
18018
18338
  try {
18019
- if (fs21.existsSync(filePath2)) return fs21.readFileSync(filePath2, "utf-8");
18339
+ if (fs22.existsSync(filePath2)) return fs22.readFileSync(filePath2, "utf-8");
18020
18340
  } catch {
18021
18341
  }
18022
18342
  return null;
@@ -18240,7 +18560,7 @@ var init_gateway_media = __esm({
18240
18560
  // src/continuity/gateway-main.ts
18241
18561
  import { isAbsolute as isAbsolute5, resolve as resolve11 } from "node:path";
18242
18562
  import { fileURLToPath as fileURLToPath4 } from "node:url";
18243
- import { createHash as createHash36 } from "node:crypto";
18563
+ import { createHash as createHash37 } from "node:crypto";
18244
18564
  import * as lark3 from "@larksuiteoapi/node-sdk";
18245
18565
 
18246
18566
  // src/continuity/authority.ts
@@ -18306,9 +18626,9 @@ var TravelAuthority = class {
18306
18626
  this.owner.close();
18307
18627
  throw new Error("TRAVEL_AUTHORITY_BUSY", { cause: error });
18308
18628
  }
18309
- const path35 = join2(options.directory, "authority.sqlite"), keyFile = join2(options.directory, "authority-signing.pem");
18629
+ const path36 = join2(options.directory, "authority.sqlite"), keyFile = join2(options.directory, "authority-signing.pem");
18310
18630
  try {
18311
- const present = existsSync(path35), keyPresent = existsSync(keyFile);
18631
+ const present = existsSync(path36), keyPresent = existsSync(keyFile);
18312
18632
  if (present !== keyPresent) throw new Error("TRAVEL_AUTHORITY_RECOVERY_REQUIRED");
18313
18633
  if (!keyPresent) {
18314
18634
  const keys = generateKeyPairSync("ed25519");
@@ -18316,8 +18636,8 @@ var TravelAuthority = class {
18316
18636
  }
18317
18637
  this.signingKey = readPrivateFile(keyFile).toString();
18318
18638
  this.publicKey = createPublicKey(this.signingKey).export({ format: "pem", type: "spki" }).toString();
18319
- preparePrivateDatabase(path35);
18320
- this.db = new DatabaseSync3(path35);
18639
+ preparePrivateDatabase(path36);
18640
+ this.db = new DatabaseSync3(path36);
18321
18641
  this.db.exec(`PRAGMA busy_timeout=1000; PRAGMA synchronous=FULL;
18322
18642
  CREATE TABLE IF NOT EXISTS seats(identity TEXT PRIMARY KEY,epoch INTEGER NOT NULL,active_node TEXT,active_boot TEXT,
18323
18643
  floor INTEGER NOT NULL,checkpoint TEXT NOT NULL,build TEXT NOT NULL,retired TEXT,frozen INTEGER NOT NULL DEFAULT 0);
@@ -18779,9 +19099,9 @@ import { isAbsolute, join as join3, relative, resolve as resolve2, sep } from "n
18779
19099
  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(" "));
18780
19100
  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(" "));
18781
19101
  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(" "));
18782
- function validateRelativePath(path35) {
18783
- if (typeof path35 !== "string" || !path35 || path35.length > 2048 || isAbsolute(path35)) throw new Error("INVALID_ARTIFACT_PATH");
18784
- for (const part of path35.split("/")) {
19102
+ function validateRelativePath(path36) {
19103
+ if (typeof path36 !== "string" || !path36 || path36.length > 2048 || isAbsolute(path36)) throw new Error("INVALID_ARTIFACT_PATH");
19104
+ for (const part of path36.split("/")) {
18785
19105
  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)))
18786
19106
  throw new Error("INVALID_ARTIFACT_PATH");
18787
19107
  }
@@ -18829,10 +19149,10 @@ function normalizePublicationProfile(value) {
18829
19149
  Object.freeze(profile.trees);
18830
19150
  return Object.freeze(profile);
18831
19151
  }
18832
- function validatePublicationPath(path35) {
18833
- if (typeof path35 !== "string" || path35.normalize("NFC") !== path35) throw new Error("PUBLICATION_INVALID_PATH");
19152
+ function validatePublicationPath(path36) {
19153
+ if (typeof path36 !== "string" || path36.normalize("NFC") !== path36) throw new Error("PUBLICATION_INVALID_PATH");
18834
19154
  try {
18835
- validateRelativePath(path35);
19155
+ validateRelativePath(path36);
18836
19156
  } catch {
18837
19157
  throw new Error("PUBLICATION_INVALID_PATH");
18838
19158
  }
@@ -18851,15 +19171,15 @@ function normalizePublication(value) {
18851
19171
  if (!Array.isArray(tree.files) || !Array.isArray(tree.directories) || (paths += tree.files.length + tree.directories.length) > 1e5)
18852
19172
  throw new Error("PUBLICATION_INVALID_TREE");
18853
19173
  const occupied = /* @__PURE__ */ new Map();
18854
- const claim = (path35, kind) => {
18855
- validatePublicationPath(path35);
18856
- const folded = path35.toLowerCase();
19174
+ const claim = (path36, kind) => {
19175
+ validatePublicationPath(path36);
19176
+ const folded = path36.toLowerCase();
18857
19177
  if (occupied.has(folded)) throw new Error("PUBLICATION_PATH_COLLISION");
18858
19178
  occupied.set(folded, kind);
18859
19179
  };
18860
- const directories = tree.directories.map((path35) => {
18861
- claim(path35, "directory");
18862
- return path35;
19180
+ const directories = tree.directories.map((path36) => {
19181
+ claim(path36, "directory");
19182
+ return path36;
18863
19183
  }).sort();
18864
19184
  const files = tree.files.map((file2) => {
18865
19185
  claim(file2?.path, "file");
@@ -18871,8 +19191,8 @@ function normalizePublication(value) {
18871
19191
  chunks: file2.content.chunks.map((r) => ({ sha256: r.sha256, bytes: r.bytes }))
18872
19192
  } };
18873
19193
  }).sort((a, b) => a.path.localeCompare(b.path, "en"));
18874
- for (const path35 of occupied.keys()) {
18875
- const parts = path35.split("/");
19194
+ for (const path36 of occupied.keys()) {
19195
+ const parts = path36.split("/");
18876
19196
  for (let i = 1; i < parts.length; i++) if (occupied.get(parts.slice(0, i).join("/")) === "file") throw new Error("PUBLICATION_PATH_COLLISION");
18877
19197
  }
18878
19198
  return { id: tree.id, directories, files };
@@ -18959,7 +19279,7 @@ function validManagement(input) {
18959
19279
  return true;
18960
19280
  }
18961
19281
  function createTravelAuthorityServer(options) {
18962
- const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, bootstrapPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls2 } = options;
19282
+ const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, bootstrapPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls3 } = options;
18963
19283
  const proxies = /* @__PURE__ */ new Set(), peers = /* @__PURE__ */ new Map(), managers = /* @__PURE__ */ new Map();
18964
19284
  const fingerprint = (value) => {
18965
19285
  const normalized = value.replaceAll(":", "").toLowerCase();
@@ -19004,7 +19324,7 @@ function createTravelAuthorityServer(options) {
19004
19324
  retirees.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
19005
19325
  }
19006
19326
  const reports = /* @__PURE__ */ new Set(), management = /* @__PURE__ */ new Set();
19007
- const server = createServer({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19327
+ const server = createServer({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19008
19328
  res.setHeader("Content-Type", "application/json");
19009
19329
  res.setHeader("Cache-Control", "no-store");
19010
19330
  const reply = (status, value) => {
@@ -19303,9 +19623,9 @@ var TravelGatewayStore = class {
19303
19623
  throw new Error("TRAVEL_GATEWAY_BUSY");
19304
19624
  }
19305
19625
  try {
19306
- const path35 = join12(options.directory, "gateway.sqlite"), present = existsSync6(path35);
19307
- preparePrivateDatabase(path35);
19308
- this.db = new DatabaseSync10(path35);
19626
+ const path36 = join12(options.directory, "gateway.sqlite"), present = existsSync6(path36);
19627
+ preparePrivateDatabase(path36);
19628
+ this.db = new DatabaseSync10(path36);
19309
19629
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
19310
19630
  if (!present) this.db.exec([
19311
19631
  "CREATE TABLE binding(identity TEXT NOT NULL,format TEXT NOT NULL);",
@@ -19859,7 +20179,7 @@ function decodeBody(value, maximum = 16 * 1024 * 1024) {
19859
20179
  return body;
19860
20180
  }
19861
20181
  function createTravelGatewayServer(options) {
19862
- const { authority, store, allowedPeers, recoveryPeers = {}, platform, assertReady, ...tls2 } = options, peers = /* @__PURE__ */ new Map(), recovery = /* @__PURE__ */ new Map();
20182
+ const { authority, store, allowedPeers, recoveryPeers = {}, platform, assertReady, ...tls3 } = options, peers = /* @__PURE__ */ new Map(), recovery = /* @__PURE__ */ new Map();
19863
20183
  for (const [fingerprint, credential] of Object.entries(allowedPeers)) {
19864
20184
  const normalized = fingerprint.replaceAll(":", "").toLowerCase();
19865
20185
  if (!/^[a-f0-9]{64}$/.test(normalized) || peers.has(normalized)) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
@@ -19872,7 +20192,7 @@ function createTravelGatewayServer(options) {
19872
20192
  }
19873
20193
  if (!peers.size || typeof platform.deliver !== "function") throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
19874
20194
  let inFlight = 0;
19875
- const server = createServer2({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
20195
+ const server = createServer2({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19876
20196
  res.setHeader("Cache-Control", "no-store");
19877
20197
  res.setHeader("Content-Type", "application/json");
19878
20198
  const reply = (status, value) => {
@@ -20253,12 +20573,55 @@ var AgentRegistryImpl = class {
20253
20573
  var agentRegistry = new AgentRegistryImpl();
20254
20574
 
20255
20575
  // src/channels/discord.ts
20256
- import { Client, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20257
- import { ProxyAgent as UndiciProxyAgent } from "undici";
20258
- import { HttpsProxyAgent } from "https-proxy-agent";
20576
+ init_adaptive_proxy();
20577
+ import { Client as Client2, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20578
+
20579
+ // src/channels/discord-gateway-proxy.ts
20580
+ init_adaptive_proxy();
20581
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
20582
+ import https from "node:https";
20583
+ import { SimpleShardingStrategy } from "@discordjs/ws";
20584
+ var gatewayRoute = new AsyncLocalStorage4();
20585
+ function gatewayDestination(url) {
20586
+ const { hostname, port } = new URL(url);
20587
+ return `${hostname.replace(/^\[|\]$/g, "")}:${port || 443}`;
20588
+ }
20589
+ var installed = false;
20590
+ function discordGatewayProxy(proxy) {
20591
+ if (!installed) {
20592
+ installed = true;
20593
+ const request4 = https.request;
20594
+ https.request = (...args) => {
20595
+ const route = gatewayRoute.getStore();
20596
+ const [options] = args;
20597
+ 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}`)) {
20598
+ args[0] = { ...options, agent: route.agent };
20599
+ }
20600
+ return Reflect.apply(request4, https, args);
20601
+ };
20602
+ }
20603
+ const agent = createProxySocketAgent(proxy);
20604
+ return (manager) => {
20605
+ const strategy = new SimpleShardingStrategy(manager);
20606
+ const destinations = /* @__PURE__ */ new Set();
20607
+ const retrieveSession = manager.options.retrieveSessionInfo.bind(manager.options);
20608
+ manager.options.retrieveSessionInfo = async (shardId) => {
20609
+ const session = await retrieveSession(shardId);
20610
+ if (session?.resumeURL) destinations.add(gatewayDestination(session.resumeURL));
20611
+ return session;
20612
+ };
20613
+ const connect = strategy.connect.bind(strategy);
20614
+ strategy.connect = async () => {
20615
+ const { url } = await manager.fetchGatewayInformation();
20616
+ destinations.add(gatewayDestination(url));
20617
+ return gatewayRoute.run({ agent, destinations }, connect);
20618
+ };
20619
+ return strategy;
20620
+ };
20621
+ }
20259
20622
 
20260
20623
  // src/memory/external-effect.ts
20261
- import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
20624
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
20262
20625
  import { createHash as createHash25 } from "node:crypto";
20263
20626
  import { join as join17 } from "node:path";
20264
20627
 
@@ -20270,6 +20633,7 @@ init_migrations();
20270
20633
  init_context_time();
20271
20634
  init_relationship_notice_check();
20272
20635
  init_dependencies();
20636
+ init_watermarks();
20273
20637
  import { join as join16 } from "node:path";
20274
20638
  var MemoryExecutionBlockedError = class extends Error {
20275
20639
  constructor(reason) {
@@ -20318,6 +20682,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20318
20682
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
20319
20683
  proactive = new DatabaseSync11(join16(workspace, ".proactive", "proactive.db"), { readOnly: true });
20320
20684
  proactive.exec("PRAGMA query_only=ON; BEGIN");
20685
+ const retractions = emptyRetractionCache();
20321
20686
  for (const [id3, version] of Object.entries(context.actionVersions)) {
20322
20687
  const action = proactive.prepare("SELECT * FROM actions WHERE id=?").get(id3);
20323
20688
  if (action?.dispatch_state === "delivery_unknown" || action?.dispatch_state === "started" && action.dispatch_key !== activeDispatchKey) {
@@ -20353,6 +20718,9 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20353
20718
  }
20354
20719
  }
20355
20720
  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" };
20721
+ if (typeof data.sourceWatermark === "number" && typeof data.retractionWatermark === "number" && deletedWithinView(memory, context.scopeId, data.retractionWatermark, data.sourceWatermark, retractions)) {
20722
+ return { ok: false, reason: "INTENT_BASIS_INVALID" };
20723
+ }
20356
20724
  }
20357
20725
  }
20358
20726
  return { ok: true };
@@ -20373,8 +20741,8 @@ function assertMemoryExecution(stateDir, workspace, context) {
20373
20741
  // src/mem7/host-turn.ts
20374
20742
  init_store();
20375
20743
  init_host_turns();
20376
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
20377
- var turns = new AsyncLocalStorage4();
20744
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
20745
+ var turns = new AsyncLocalStorage5();
20378
20746
  function hasHostTurnContext() {
20379
20747
  return Boolean(turns.getStore());
20380
20748
  }
@@ -20418,8 +20786,8 @@ function beginHostTurnEffect() {
20418
20786
 
20419
20787
  // src/memory/external-effect.ts
20420
20788
  init_runtime_authority();
20421
- var effects = new AsyncLocalStorage5();
20422
- var externalFences = new AsyncLocalStorage5();
20789
+ var effects = new AsyncLocalStorage6();
20790
+ var externalFences = new AsyncLocalStorage6();
20423
20791
  function withExternalEffectFence(check, run) {
20424
20792
  return externalFences.run(check, run);
20425
20793
  }
@@ -20693,6 +21061,7 @@ var settled = (status) => status !== "run" && status !== "wait";
20693
21061
  var DISCORD_MSG_LIMIT = 2e3;
20694
21062
  var DiscordAdapter = class _DiscordAdapter {
20695
21063
  name = "discord";
21064
+ supportsQuietPreview = true;
20696
21065
  memoryGuardedSends = true;
20697
21066
  client;
20698
21067
  config;
@@ -20707,7 +21076,7 @@ var DiscordAdapter = class _DiscordAdapter {
20707
21076
  // 🔴 P0: 消息去重 — Discord RESUME 重连会重放 messageCreate
20708
21077
  recentMessageIds = /* @__PURE__ */ new Set();
20709
21078
  constructor(clientOrConfig, config) {
20710
- if (clientOrConfig instanceof Client) {
21079
+ if (clientOrConfig instanceof Client2) {
20711
21080
  this.client = clientOrConfig;
20712
21081
  this.config = config ?? {};
20713
21082
  this.ownsClient = false;
@@ -20725,24 +21094,10 @@ var DiscordAdapter = class _DiscordAdapter {
20725
21094
  partials: [Partials.Channel, Partials.Message]
20726
21095
  };
20727
21096
  if (this.config.proxy) {
20728
- const proxyUrl = this.config.proxy;
20729
- clientOptions.rest = { agent: new UndiciProxyAgent({ uri: proxyUrl }) };
20730
- const httpsAgent = new HttpsProxyAgent(proxyUrl);
20731
- const https = __require("https");
20732
- const origRequest = https.request;
20733
- if (!origRequest.__discordProxyPatched) {
20734
- https.request = function(opts, cb) {
20735
- const host = typeof opts === "string" ? "" : opts?.hostname || opts?.host || "";
20736
- if ((host.includes("discord") || host.includes("gateway")) && typeof opts === "object" && !opts.agent) {
20737
- opts.agent = httpsAgent;
20738
- }
20739
- return origRequest.call(this, opts, cb);
20740
- };
20741
- https.request.__discordProxyPatched = true;
20742
- console.log(`[discord] https.request patched for Discord gateway \u2192 ${proxyUrl}`);
20743
- }
21097
+ clientOptions.rest = { agent: getProxyDispatcher(this.config.proxy) };
21098
+ clientOptions.ws = { buildStrategy: discordGatewayProxy(this.config.proxy) };
20744
21099
  }
20745
- this.client = new Client(clientOptions);
21100
+ this.client = new Client2(clientOptions);
20746
21101
  this.ownsClient = true;
20747
21102
  }
20748
21103
  this.progressCards = new DiscordProgressCards({
@@ -20803,7 +21158,7 @@ var DiscordAdapter = class _DiscordAdapter {
20803
21158
  }
20804
21159
  try {
20805
21160
  const init = { signal: AbortSignal.timeout(HISTORY_ATTACH_TIMEOUT_MS) };
20806
- if (this.config.proxy) init.dispatcher = new UndiciProxyAgent({ uri: this.config.proxy });
21161
+ if (this.config.proxy) init.dispatcher = getProxyDispatcher(this.config.proxy);
20807
21162
  const res = await fetch(att.url, init);
20808
21163
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
20809
21164
  const buf = Buffer.from(await res.arrayBuffer());
@@ -20876,9 +21231,9 @@ var DiscordAdapter = class _DiscordAdapter {
20876
21231
  throw err;
20877
21232
  }
20878
21233
  if (attempt < MAX_RETRIES2) {
20879
- const delay = Math.min(5e3 * Math.pow(2, attempt - 1), 6e4);
20880
- console.warn(`[discord] Login attempt ${attempt}/${MAX_RETRIES2} failed (${code || err.message}): ${err.message} \u2014 retrying in ${delay / 1e3}s`);
20881
- await new Promise((r) => setTimeout(r, delay));
21234
+ const delay2 = Math.min(5e3 * Math.pow(2, attempt - 1), 6e4);
21235
+ console.warn(`[discord] Login attempt ${attempt}/${MAX_RETRIES2} failed (${code || err.message}): ${err.message} \u2014 retrying in ${delay2 / 1e3}s`);
21236
+ await new Promise((r) => setTimeout(r, delay2));
20882
21237
  }
20883
21238
  }
20884
21239
  }
@@ -20955,13 +21310,13 @@ var DiscordAdapter = class _DiscordAdapter {
20955
21310
  }
20956
21311
  /** 发送媒体附件(图片/文件/音频)— discord.js channel.send({ files }) */
20957
21312
  async sendFile(target, message, attachment) {
20958
- const fs25 = await import("node:fs");
20959
- const path35 = await import("node:path");
20960
- if (!fs25.existsSync(attachment.path)) {
21313
+ const fs26 = await import("node:fs");
21314
+ const path36 = await import("node:path");
21315
+ if (!fs26.existsSync(attachment.path)) {
20961
21316
  throw new Error(`File not found: ${attachment.path}`);
20962
21317
  }
20963
- const filename = attachment.filename || path35.basename(attachment.path);
20964
- const fileBuffer = fs25.readFileSync(attachment.path);
21318
+ const filename = attachment.filename || path36.basename(attachment.path);
21319
+ const fileBuffer = fs26.readFileSync(attachment.path);
20965
21320
  const filePayload = {
20966
21321
  attachment: fileBuffer,
20967
21322
  name: filename
@@ -21164,7 +21519,7 @@ var DiscordAdapter = class _DiscordAdapter {
21164
21519
  return this.config.previewColor ?? _DiscordAdapter.COLOR_RUNNING;
21165
21520
  }
21166
21521
  /** 发送初始 preview 消息(Embed),返回 handle */
21167
- async sendPreview(channelId, content, agentName) {
21522
+ async sendPreview(channelId, content, agentName, presentation) {
21168
21523
  const channel = this.client.channels.cache.get(channelId) ?? await this.client.channels.fetch(channelId);
21169
21524
  if (!channel?.isTextBased() || !("send" in channel)) {
21170
21525
  throw new Error(`discord: sendPreview: channel ${channelId} not found or not text-based`);
@@ -21174,7 +21529,7 @@ var DiscordAdapter = class _DiscordAdapter {
21174
21529
  assertExternalEffectCurrent();
21175
21530
  const sent = await channel.send({
21176
21531
  embeds: [{
21177
- title: `${agent} \xB7 \u5904\u7406\u4E2D`,
21532
+ ...presentation !== "quiet" && { title: `${agent} \xB7 \u5904\u7406\u4E2D` },
21178
21533
  description: text2,
21179
21534
  color: this.previewColor
21180
21535
  }]
@@ -21418,6 +21773,7 @@ var FEISHU_POST_BYTES = 3e4;
21418
21773
  var FEISHU_POST_BUDGET = FEISHU_POST_BYTES - 1024;
21419
21774
  var FeishuAdapter = class _FeishuAdapter {
21420
21775
  name = "feishu";
21776
+ supportsQuietPreview = true;
21421
21777
  memoryGuardedSends = true;
21422
21778
  client;
21423
21779
  wsClient;
@@ -21574,13 +21930,13 @@ var FeishuAdapter = class _FeishuAdapter {
21574
21930
  }
21575
21931
  /** 发送媒体附件(图片/文件) */
21576
21932
  async sendFile(target, message, attachment) {
21577
- const fs25 = await import("node:fs");
21578
- const path35 = await import("node:path");
21579
- if (!fs25.existsSync(attachment.path)) {
21933
+ const fs26 = await import("node:fs");
21934
+ const path36 = await import("node:path");
21935
+ if (!fs26.existsSync(attachment.path)) {
21580
21936
  throw new Error(`File not found: ${attachment.path}`);
21581
21937
  }
21582
- const filename = attachment.filename || path35.basename(attachment.path);
21583
- const fileBuffer = fs25.readFileSync(attachment.path);
21938
+ const filename = attachment.filename || path36.basename(attachment.path);
21939
+ const fileBuffer = fs26.readFileSync(attachment.path);
21584
21940
  const safeTarget = target || this.config.defaultTarget || "";
21585
21941
  if (!safeTarget) throw new Error("Feishu sendFile: no target (\u4E3B\u52A8\u53D1\u9001\u9700\u914D\u7F6E defaultTarget \u6216\u4F20\u5165 target)");
21586
21942
  const receiveIdType = safeTarget.startsWith("ou_") ? "open_id" : "chat_id";
@@ -22002,7 +22358,7 @@ var FeishuAdapter = class _FeishuAdapter {
22002
22358
  }
22003
22359
  }
22004
22360
  // === Streaming preview — 用飞书消息卡片实现"正在思考"效果 ===
22005
- async sendPreview(channelId, content, agentName) {
22361
+ async sendPreview(channelId, content, agentName, presentation) {
22006
22362
  const agent = agentName || "Agent";
22007
22363
  const text2 = content.length > 2e3 ? content.slice(0, 1999) + "\u2026" : content;
22008
22364
  assertExternalEffectCurrent();
@@ -22013,10 +22369,10 @@ var FeishuAdapter = class _FeishuAdapter {
22013
22369
  msg_type: "interactive",
22014
22370
  content: JSON.stringify({
22015
22371
  config: { wide_screen_mode: true },
22016
- header: {
22372
+ ...presentation !== "quiet" && { header: {
22017
22373
  title: { tag: "plain_text", content: `${agent} \xB7 \u5904\u7406\u4E2D` },
22018
22374
  template: this.config.previewTemplate || "yellow"
22019
- },
22375
+ } },
22020
22376
  elements: [
22021
22377
  // 1013:预览卡也用 lark_md —— 生成过程中粗体/斜体/删除线/链接就能渲染了。
22022
22378
  // 表格、列表、代码块、行内代码是 lark_md 的能力边界(卡片 1.0 的 div 文本就只有
@@ -23595,7 +23951,7 @@ import { promisify as promisify3 } from "node:util";
23595
23951
  init_voice_chat_tts_daemon();
23596
23952
  import * as path14 from "node:path";
23597
23953
  import * as os6 from "node:os";
23598
- import net2 from "net";
23954
+ import net3 from "net";
23599
23955
  var execFileAsync = promisify3(execFile);
23600
23956
  var VOICE_DIR = path14.join(os6.tmpdir(), "engine-voice");
23601
23957
  async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
@@ -23607,7 +23963,7 @@ async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
23607
23963
  }
23608
23964
  }
23609
23965
  return new Promise((resolve12, reject) => {
23610
- const sock = net2.connect(getSockPath());
23966
+ const sock = net3.connect(getSockPath());
23611
23967
  let buf = "";
23612
23968
  const finish = (err) => {
23613
23969
  try {
@@ -23706,22 +24062,22 @@ var DeskBuddyAdapter = class {
23706
24062
  try {
23707
24063
  if (!this.historyFile) {
23708
24064
  const os7 = __require("os");
23709
- const fs26 = __require("fs");
23710
- const path35 = __require("path");
23711
- const dir = path35.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
23712
- fs26.mkdirSync(dir, { recursive: true });
23713
- this.historyFile = path35.join(dir, "history.json");
23714
- this._fs = fs26;
23715
- }
23716
- const fs25 = this._fs;
24065
+ const fs27 = __require("fs");
24066
+ const path36 = __require("path");
24067
+ const dir = path36.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
24068
+ fs27.mkdirSync(dir, { recursive: true });
24069
+ this.historyFile = path36.join(dir, "history.json");
24070
+ this._fs = fs27;
24071
+ }
24072
+ const fs26 = this._fs;
23717
24073
  let arr = [];
23718
24074
  try {
23719
- arr = JSON.parse(fs25.readFileSync(this.historyFile, "utf-8")) || [];
24075
+ arr = JSON.parse(fs26.readFileSync(this.historyFile, "utf-8")) || [];
23720
24076
  } catch {
23721
24077
  }
23722
24078
  arr.push({ ...entry, ts: (/* @__PURE__ */ new Date()).toLocaleString("zh-CN", { hour12: false }) });
23723
24079
  if (arr.length > 500) arr = arr.slice(-500);
23724
- fs25.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
24080
+ fs26.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
23725
24081
  } catch (e) {
23726
24082
  console.warn("[deskBuddy] history write fail", e);
23727
24083
  }
@@ -23819,8 +24175,8 @@ var DeskBuddyAdapter = class {
23819
24175
  startAsr() {
23820
24176
  if (this.asrSock) return;
23821
24177
  const port = this.asrBackend === "sensevoice" ? 9790 : 9791;
23822
- const net3 = __require("node:net");
23823
- const sock = net3.connect(port, "127.0.0.1");
24178
+ const net4 = __require("node:net");
24179
+ const sock = net4.connect(port, "127.0.0.1");
23824
24180
  sock.setNoDelay(true);
23825
24181
  this.asrSock = sock;
23826
24182
  this.asrBuf = "";
@@ -24372,7 +24728,7 @@ var CcBridgeAdapter = class {
24372
24728
 
24373
24729
  // src/channels/telegram.ts
24374
24730
  import fs13 from "node:fs";
24375
- import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
24731
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
24376
24732
  import path17 from "node:path";
24377
24733
 
24378
24734
  // src/channels/telegram-offset.ts
@@ -24564,7 +24920,7 @@ var PreviewEditThrottle = class {
24564
24920
  /** 提交一次编辑;返回的 promise 在"该内容(或其后覆盖它的更新内容)真实落盘"后 settle,失败 reject */
24565
24921
  submit(key4, req, run) {
24566
24922
  const s = this.st.get(key4) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
24567
- const guardedRun = AsyncLocalStorage6.bind(run);
24923
+ const guardedRun = AsyncLocalStorage7.bind(run);
24568
24924
  this.st.set(key4, s);
24569
24925
  return new Promise((resolve12, reject) => {
24570
24926
  const waiter = { resolve: resolve12, reject };
@@ -25346,7 +25702,7 @@ var TelegramAdapter = class {
25346
25702
 
25347
25703
  // src/channels/whatsapp/adapter.ts
25348
25704
  import fsSync4 from "node:fs";
25349
- import path30 from "node:path";
25705
+ import path31 from "node:path";
25350
25706
  import { spawn as spawn5 } from "node:child_process";
25351
25707
  import { randomUUID as randomUUID17 } from "node:crypto";
25352
25708
 
@@ -25750,9 +26106,6 @@ var QrManager = class {
25750
26106
  }
25751
26107
  };
25752
26108
 
25753
- // src/channels/whatsapp/socket.ts
25754
- import { HttpsProxyAgent as HttpsProxyAgent2 } from "https-proxy-agent";
25755
-
25756
26109
  // src/version.ts
25757
26110
  import { readFileSync as readFileSync12 } from "node:fs";
25758
26111
  import { dirname as dirname10, join as join21 } from "node:path";
@@ -25779,7 +26132,7 @@ function readEngineVersion() {
25779
26132
  }
25780
26133
 
25781
26134
  // src/channels/whatsapp/socket.ts
25782
- init_withRetry();
26135
+ init_adaptive_proxy();
25783
26136
  var VERSION_SOURCE_URL = "https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts";
25784
26137
  var VERSION_FETCH_TIMEOUT_MS = 3e3;
25785
26138
  var VERSION_FALLBACK_TIMEOUT_MS = 5e3;
@@ -25873,7 +26226,7 @@ async function makeWaSocket(opts) {
25873
26226
  connectTimeoutMs: 6e4,
25874
26227
  defaultQueryTimeoutMs: 6e4,
25875
26228
  // ws 层代理(https-proxy-agent,baileys 原生支持)
25876
- agent: opts.proxy ? new HttpsProxyAgent2(opts.proxy) : void 0,
26229
+ agent: opts.proxy ? createProxySocketAgent(opts.proxy) : void 0,
25877
26230
  // 媒体上传/下载走 native fetch,只认 undici dispatcher(防线 4,见文件头)
25878
26231
  fetchAgent: opts.proxy ? getProxyDispatcher(opts.proxy) : void 0,
25879
26232
  auth: { creds: auth.state.creds, keys },
@@ -26277,7 +26630,7 @@ function headerOf(groupJid) {
26277
26630
 
26278
26631
  // src/channels/whatsapp/patrol.ts
26279
26632
  import fsSync3 from "node:fs";
26280
- import path29 from "node:path";
26633
+ import path30 from "node:path";
26281
26634
  import { randomBytes as randomBytes7 } from "node:crypto";
26282
26635
 
26283
26636
  // src/models/model-capabilities.ts
@@ -26601,6 +26954,185 @@ function isQuotaExhaustedError(message) {
26601
26954
  // src/core/query.ts
26602
26955
  import { setTimeout as waitForRetry } from "node:timers/promises";
26603
26956
 
26957
+ // src/utils/file-transaction.ts
26958
+ import { mkdir as mkdir3 } from "node:fs/promises";
26959
+ import { dirname as dirname11 } from "node:path";
26960
+ import { DatabaseSync as DatabaseSync14 } from "node:sqlite";
26961
+ import { setTimeout as delay } from "node:timers/promises";
26962
+ async function withFileTransaction(file2, action, signal, waitMs = 5e3) {
26963
+ await mkdir3(dirname11(file2), { recursive: true });
26964
+ const db2 = new DatabaseSync14(file2);
26965
+ try {
26966
+ const deadline = waitMs === null ? Infinity : Date.now() + waitMs;
26967
+ const retryMs = waitMs === null ? 50 : waitMs > 5e3 ? 200 : 15;
26968
+ for (; ; ) {
26969
+ signal?.throwIfAborted();
26970
+ try {
26971
+ db2.exec("BEGIN IMMEDIATE");
26972
+ break;
26973
+ } catch (error) {
26974
+ const code = error.errcode;
26975
+ if (code !== 5 || Date.now() >= deadline) throw error;
26976
+ await delay(retryMs, void 0, { signal });
26977
+ }
26978
+ }
26979
+ const result = await action();
26980
+ db2.exec("COMMIT");
26981
+ return result;
26982
+ } finally {
26983
+ db2.close();
26984
+ }
26985
+ }
26986
+
26987
+ // src/tools/file-path.ts
26988
+ import { createHash as createHash31 } from "node:crypto";
26989
+ import fs14 from "node:fs";
26990
+ import path21 from "node:path";
26991
+
26992
+ // src/utils/path.ts
26993
+ import * as path20 from "node:path";
26994
+ function isWithin(root, target) {
26995
+ const name = path20.relative(root, target);
26996
+ return !path20.isAbsolute(name) && name !== ".." && !name.startsWith(".." + path20.sep);
26997
+ }
26998
+ var extraAllowedPaths = [];
26999
+ var sandboxOff = false;
27000
+ function fixMsysPath(p) {
27001
+ let fixed = p.includes("\\") ? p.replace(/\\/g, "/") : p;
27002
+ if (process.platform === "win32") {
27003
+ fixed = fixed.replace(/^\/([a-zA-Z])\//, (_, letter) => `${letter.toUpperCase()}:/`);
27004
+ }
27005
+ return fixed;
27006
+ }
27007
+ function resolvePath(p, workspace) {
27008
+ const fixed = fixMsysPath(p);
27009
+ const resolved = path20.isAbsolute(fixed) ? path20.normalize(fixed) : path20.resolve(workspace, fixed);
27010
+ const normalized = path20.normalize(resolved);
27011
+ const normalizedWorkspace = path20.normalize(workspace);
27012
+ if (sandboxOff) return normalized;
27013
+ if (normalized === normalizedWorkspace || normalized.startsWith(normalizedWorkspace + path20.sep)) {
27014
+ return normalized;
27015
+ }
27016
+ for (const allowed of extraAllowedPaths) {
27017
+ if (normalized === allowed || normalized.startsWith(allowed + path20.sep)) {
27018
+ return normalized;
27019
+ }
27020
+ }
27021
+ throw new Error(`\u8DEF\u5F84\u8D85\u51FA workspace \u8303\u56F4: ${p} \u2192 ${normalized} (workspace: ${normalizedWorkspace})`);
27022
+ }
27023
+
27024
+ // src/tools/file-path.ts
27025
+ init_paths();
27026
+ function physicalPath(target) {
27027
+ let ancestor = target;
27028
+ for (; ; ) {
27029
+ try {
27030
+ fs14.lstatSync(ancestor);
27031
+ break;
27032
+ } catch (error) {
27033
+ if (error.code !== "ENOENT") throw error;
27034
+ const parent = path21.dirname(ancestor);
27035
+ if (parent === ancestor) throw error;
27036
+ ancestor = parent;
27037
+ }
27038
+ }
27039
+ return path21.resolve(fs14.realpathSync(ancestor), path21.relative(ancestor, target));
27040
+ }
27041
+ function withoutRepeatedDirectories(relative5) {
27042
+ const parts = relative5.split(path21.sep);
27043
+ while (parts.length > 1 && parts[0].toLowerCase() === AUTO_MEM_DIRNAME) parts.shift();
27044
+ return parts.filter((part, index) => index === parts.length - 1 || index === 0 || part.toLowerCase() !== parts[index - 1].toLowerCase()).join(path21.sep);
27045
+ }
27046
+ function resolveFilePath(requested, context, writing = false) {
27047
+ if (!context.memoryToolRoot) {
27048
+ if (!context.projectTask) return resolvePath(requested, context.workspace);
27049
+ const target = path21.resolve(context.workspace, requested.replaceAll("\\", "/"));
27050
+ const roots = [context.projectTask.topicsDir, ...!writing && context.taskSessionsDir ? [context.taskSessionsDir] : [], context.workspace];
27051
+ const root2 = roots.find((directory2) => isWithin(directory2, target));
27052
+ const physical = physicalPath(target);
27053
+ if (!root2 || !isWithin(physicalPath(root2), physical)) throw new Error("Path is outside this task workspace and project context");
27054
+ if (root2 === context.workspace && context.stateDir && isWithin(physicalPath(path21.join(context.stateDir, "agents")), physical)) {
27055
+ throw new Error("Path is outside this task\u2019s project storage");
27056
+ }
27057
+ if (root2 !== context.workspace && path21.relative(root2, target).split(path21.sep).some((part) => part.startsWith("."))) {
27058
+ throw new Error("Project task storage metadata is internal");
27059
+ }
27060
+ return target;
27061
+ }
27062
+ const root = path21.resolve(context.memoryToolRoot);
27063
+ const resolved = resolvePath(requested, root);
27064
+ if (!isWithin(root, resolved) || !isWithin(physicalPath(root), physicalPath(resolved))) {
27065
+ 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");
27066
+ }
27067
+ const relative5 = path21.relative(root, resolved);
27068
+ if (writing) {
27069
+ if (path21.basename(resolved).toUpperCase() === "MEMORY.MD") {
27070
+ const canonicalIndex = path21.join(root, "MEMORY.md");
27071
+ const indexNames = fs14.existsSync(root) ? fs14.readdirSync(root).filter((name) => name.toUpperCase() === "MEMORY.MD") : [];
27072
+ let sameIndex = false;
27073
+ if (path21.dirname(relative5) === "." && indexNames.length === 1 && fs14.existsSync(resolved) && fs14.existsSync(canonicalIndex)) {
27074
+ const requestedEntry = fs14.lstatSync(resolved);
27075
+ const canonicalEntry = fs14.lstatSync(canonicalIndex);
27076
+ sameIndex = requestedEntry.dev === canonicalEntry.dev && requestedEntry.ino === canonicalEntry.ino;
27077
+ }
27078
+ if (relative5 !== "MEMORY.md" && !sameIndex || relative5 === "MEMORY.md" && indexNames.length > 0 && !fs14.existsSync(canonicalIndex)) {
27079
+ 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");
27080
+ }
27081
+ }
27082
+ if (!fs14.existsSync(resolved)) {
27083
+ const parts = relative5.split(path21.sep);
27084
+ if (parts[0].toLowerCase() === AUTO_MEM_DIRNAME || parts.some((part, index) => index > 0 && index < parts.length - 1 && part.toLowerCase() === parts[index - 1].toLowerCase())) {
27085
+ 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");
27086
+ }
27087
+ if (fs14.existsSync(root)) {
27088
+ 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);
27089
+ if (existing.length > 0) {
27090
+ 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`);
27091
+ }
27092
+ }
27093
+ }
27094
+ }
27095
+ return resolved;
27096
+ }
27097
+ function indexVersion(file2) {
27098
+ try {
27099
+ return createHash31("sha256").update(fs14.readFileSync(file2)).digest("hex");
27100
+ } catch (error) {
27101
+ if (error.code !== "ENOENT" && error.code !== "EISDIR") throw error;
27102
+ }
27103
+ }
27104
+ async function runFileTool(tool, requested, context, action, signal) {
27105
+ const root = context.memoryToolRoot ?? context.projectTask?.topicsDir;
27106
+ if (!root || typeof requested !== "string" || !["read", "write", "edit"].includes(tool)) return action();
27107
+ let file2;
27108
+ try {
27109
+ file2 = resolveFilePath(requested, context);
27110
+ } catch {
27111
+ return action();
27112
+ }
27113
+ if (!isWithin(path21.resolve(root), file2)) return action();
27114
+ if (tool === "read") {
27115
+ return withFileTransaction(path21.join(root, ".write-lock.sqlite"), async () => {
27116
+ const result = await action();
27117
+ const version = indexVersion(file2);
27118
+ if (version !== void 0 && !result.isError) context.topicReads?.set(file2, version);
27119
+ return result;
27120
+ }, signal);
27121
+ }
27122
+ return withFileTransaction(path21.join(root, ".write-lock.sqlite"), async () => {
27123
+ const current2 = indexVersion(file2);
27124
+ if (current2 !== void 0 && context.topicReads?.get(file2) !== current2) {
27125
+ throw new Error("Project topic changed or has not been read. Read it again before updating.");
27126
+ }
27127
+ const result = await action();
27128
+ if (!result.isError) {
27129
+ const version = indexVersion(file2);
27130
+ if (version !== void 0) context.topicReads?.set(file2, version);
27131
+ }
27132
+ return result;
27133
+ }, signal);
27134
+ }
27135
+
26604
27136
  // src/tools/ToolSearchTool/constants.ts
26605
27137
  var TOOL_SEARCH_TOOL_NAME = "load_missing_tools";
26606
27138
 
@@ -26724,9 +27256,9 @@ function isPlanMode() {
26724
27256
  init_runtime_authority();
26725
27257
 
26726
27258
  // src/continuity/gateway-context.ts
26727
- import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
26728
- var contexts = new AsyncLocalStorage7();
26729
- var outputKinds = new AsyncLocalStorage7();
27259
+ import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
27260
+ var contexts = new AsyncLocalStorage8();
27261
+ var outputKinds = new AsyncLocalStorage8();
26730
27262
  var travelOutputKind = () => outputKinds.getStore() ?? "REPLY";
26731
27263
  function withTravelOutputKind(kind, run) {
26732
27264
  return outputKinds.run(kind, run);
@@ -26859,27 +27391,45 @@ function emitHookResponse(data) {
26859
27391
  emit({ type: "response", ...data });
26860
27392
  }
26861
27393
 
27394
+ // src/skills/skill-gate.ts
27395
+ init_strip_injected();
27396
+ init_writer();
27397
+ var USER_CHANNELS = /* @__PURE__ */ new Set(["discord", "feishu", "wechat", "telegram", "cli", "console", "voice-chat", "deskBuddy", "ccBridge"]);
27398
+ var SKILL_CHANNELS = /* @__PURE__ */ new Set([...USER_CHANNELS, "chan7", "webhook"]);
27399
+ var loadedBySession = /* @__PURE__ */ new Map();
27400
+ var MAX_TRACKED_SESSIONS = 100;
27401
+ function beginSkillGate(sessionId) {
27402
+ if (loadedBySession.size >= MAX_TRACKED_SESSIONS && !loadedBySession.has(sessionId)) {
27403
+ const oldest = loadedBySession.keys().next().value;
27404
+ if (oldest !== void 0) loadedBySession.delete(oldest);
27405
+ }
27406
+ loadedBySession.set(sessionId, /* @__PURE__ */ new Set());
27407
+ }
27408
+ function isUserChannel(ch) {
27409
+ return !!ch && USER_CHANNELS.has(ch);
27410
+ }
27411
+
26862
27412
  // src/hooks/executor.ts
26863
- init_runtime_authority();
26864
27413
  import { spawn as spawn2 } from "child_process";
26865
27414
  import { randomUUID as randomUUID14 } from "node:crypto";
27415
+ init_runtime_authority();
26866
27416
  import { basename as basename5 } from "node:path";
26867
27417
 
26868
27418
  // src/router/cpu-router.ts
26869
- import fs14 from "node:fs";
26870
- import path20 from "node:path";
27419
+ import fs15 from "node:fs";
27420
+ import path22 from "node:path";
26871
27421
  init_strip_injected();
26872
27422
  import { fileURLToPath as fileURLToPath3 } from "node:url";
26873
- 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")));
27423
+ 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")));
26874
27424
 
26875
27425
  // src/router/cpu-router-mode-hook.ts
26876
- import fs15 from "node:fs";
26877
- import path21 from "node:path";
27426
+ import fs16 from "node:fs";
27427
+ import path23 from "node:path";
26878
27428
  function isCpuModeHook(command) {
26879
27429
  if (!/^(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>]+)\s+(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>]+)\s*$/.test(command)) return false;
26880
27430
  const tokens = command.match(/"[^"\r\n]*"|'[^'\r\n]*'|[^\s]+/g).map((token) => token.replace(/^["']|["']$/g, ""));
26881
- const executable = path21.basename(tokens[0].replaceAll("\\", "/"));
26882
- const script = path21.basename(tokens[1].replaceAll("\\", "/"));
27431
+ const executable = path23.basename(tokens[0].replaceAll("\\", "/"));
27432
+ const script = path23.basename(tokens[1].replaceAll("\\", "/"));
26883
27433
  return (tokens[0] === process.execPath || /^(?:node|python[\d.]*|py)(?:\.exe)?$/i.test(executable)) && /^emotion(?:_state_machine\.(?:mjs|py)|-hook-gate\.js)$/i.test(script);
26884
27434
  }
26885
27435
  function cpuModeHookOutput(command, input, workspace) {
@@ -26894,7 +27444,7 @@ function cpuModeOutput(input, workspace) {
26894
27444
  let fixed = "auto";
26895
27445
  if (!input.source || input.source === "user") {
26896
27446
  try {
26897
- fixed = fs15.readFileSync(path21.join(workspace, ".work-mode"), "utf8").trim();
27447
+ fixed = fs16.readFileSync(path23.join(workspace, ".work-mode"), "utf8").trim();
26898
27448
  } catch {
26899
27449
  }
26900
27450
  }
@@ -27463,6 +28013,9 @@ async function executeOne(tc, ctx, signal) {
27463
28013
  if (ctx.yieldSignal?.aborted) {
27464
28014
  return { call: tc, result: { content: "[not executed: new user input received; reconsider this call after reading it]", isError: false }, summary: null };
27465
28015
  }
28016
+ if (ctx.projectTask && /^(?:memory_|calendar_memory_|calendar_delivery_|calendar_reconcile_|goal_|proactive_|chat_history$)/.test(tc.function.name)) {
28017
+ 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 };
28018
+ }
27466
28019
  const tool = registry.get(tc.function.name);
27467
28020
  if (!tool) {
27468
28021
  return { call: tc, result: { content: `Unknown tool: ${tc.function.name}`, isError: true }, summary: null };
@@ -27565,7 +28118,13 @@ async function executeOne(tc, ctx, signal) {
27565
28118
  workspace: ctx.workspace,
27566
28119
  executionContext: guardContext,
27567
28120
  effectId: `tool:${tc.id}`
27568
- }, () => tool.handler(args, { ...ctx, toolCallId: tc.id }, signal));
28121
+ }, () => runFileTool(
28122
+ tc.function.name,
28123
+ args.file_path ?? args.path,
28124
+ ctx,
28125
+ () => tool.handler(args, { ...ctx, toolCallId: tc.id }, signal),
28126
+ signal
28127
+ ));
27569
28128
  assertRuntimeTool(ctx.stateDir, tc.function.name);
27570
28129
  await executePostToolUseHooks(tc.function.name, args, result.content, hookCtx, signal);
27571
28130
  if (repeatN >= LOOP_SOFT_AT) {
@@ -27794,8 +28353,11 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27794
28353
  }
27795
28354
 
27796
28355
  // src/utils/context-dump.ts
27797
- import * as fs16 from "node:fs";
27798
- import * as path22 from "node:path";
28356
+ import * as fs17 from "node:fs";
28357
+ import * as path24 from "node:path";
28358
+ function isContextDumpEnabled() {
28359
+ return process.env.ENGINE7_DUMP_CONTEXT === "1" || process.env.ENGINE_DUMP_REQUEST === "1";
28360
+ }
27799
28361
  function dumpApiRequest(opts) {
27800
28362
  const lines = [
27801
28363
  "=== API Request Debug\uFF08\u53D1\u7ED9 LLM \u7684\u6700\u7EC8\u8BF7\u6C42\u4F53\uFF0C\u6BCF\u6B21\u8986\u76D6\u5199\uFF09===",
@@ -27828,7 +28390,7 @@ function dumpApiRequest(opts) {
27828
28390
  lines.push(`[${i}] ${m.role}: (empty)`);
27829
28391
  }
27830
28392
  }
27831
- fs16.writeFileSync(path22.join(opts.workspace, ".context-debug.txt"), lines.join("\n") + "\n", "utf-8");
28393
+ fs17.writeFileSync(path24.join(opts.workspace, ".context-debug.txt"), lines.join("\n") + "\n", "utf-8");
27832
28394
  }
27833
28395
 
27834
28396
  // src/core/query.ts
@@ -27836,24 +28398,24 @@ init_types();
27836
28398
  import { randomUUID as randomUUID16 } from "node:crypto";
27837
28399
 
27838
28400
  // src/core/steer-mailbox.ts
27839
- import * as fs17 from "node:fs";
27840
- import * as path23 from "node:path";
27841
- import { createHash as createHash31, randomUUID as randomUUID15 } from "node:crypto";
28401
+ import * as fs18 from "node:fs";
28402
+ import * as path25 from "node:path";
28403
+ import { createHash as createHash32, randomUUID as randomUUID15 } from "node:crypto";
27842
28404
  var MAX_FILE = 1024 * 1024;
27843
28405
  var MAX_PENDING = 128;
27844
28406
  var MAX_PENDING_BYTES = 512 * 1024;
27845
28407
  var SteerMailbox = class {
27846
28408
  constructor(stateDir, sessionId) {
27847
28409
  this.sessionId = sessionId;
27848
- const key4 = createHash31("sha256").update(sessionId).digest("hex");
27849
- this.path = path23.join(stateDir, "steer", `${key4}.json`);
28410
+ const key4 = createHash32("sha256").update(sessionId).digest("hex");
28411
+ this.path = path25.join(stateDir, "steer", `${key4}.json`);
27850
28412
  }
27851
28413
  path;
27852
28414
  list() {
27853
28415
  let raw;
27854
28416
  try {
27855
- if (fs17.statSync(this.path).size > MAX_FILE) throw new Error("Steer mailbox exceeds size limit");
27856
- raw = fs17.readFileSync(this.path, "utf8");
28417
+ if (fs18.statSync(this.path).size > MAX_FILE) throw new Error("Steer mailbox exceeds size limit");
28418
+ raw = fs18.readFileSync(this.path, "utf8");
27857
28419
  } catch (error) {
27858
28420
  if (error.code === "ENOENT") return [];
27859
28421
  throw error;
@@ -27879,7 +28441,7 @@ var SteerMailbox = class {
27879
28441
  if (input.attachment) this.assertAttachment(input);
27880
28442
  input.images?.forEach(assertImageAssetRef);
27881
28443
  const records = this.list();
27882
- const id3 = input.messageId ? createHash31("sha256").update(JSON.stringify([
28444
+ const id3 = input.messageId ? createHash32("sha256").update(JSON.stringify([
27883
28445
  this.sessionId,
27884
28446
  input.channel,
27885
28447
  input.channelTarget ?? "",
@@ -27956,20 +28518,20 @@ var SteerMailbox = class {
27956
28518
  data = serialize();
27957
28519
  }
27958
28520
  if (Buffer.byteLength(data) > MAX_FILE) throw new Error("Steer mailbox full");
27959
- fs17.mkdirSync(path23.dirname(this.path), { recursive: true });
28521
+ fs18.mkdirSync(path25.dirname(this.path), { recursive: true });
27960
28522
  const temporary = `${this.path}.${randomUUID15()}.tmp`;
27961
28523
  try {
27962
- const fd = fs17.openSync(temporary, "wx", 384);
28524
+ const fd = fs18.openSync(temporary, "wx", 384);
27963
28525
  try {
27964
- fs17.writeFileSync(fd, data);
27965
- fs17.fsyncSync(fd);
28526
+ fs18.writeFileSync(fd, data);
28527
+ fs18.fsyncSync(fd);
27966
28528
  } finally {
27967
- fs17.closeSync(fd);
28529
+ fs18.closeSync(fd);
27968
28530
  }
27969
- fs17.renameSync(temporary, this.path);
28531
+ fs18.renameSync(temporary, this.path);
27970
28532
  } finally {
27971
28533
  try {
27972
- fs17.unlinkSync(temporary);
28534
+ fs18.unlinkSync(temporary);
27973
28535
  } catch {
27974
28536
  }
27975
28537
  }
@@ -27978,7 +28540,7 @@ var SteerMailbox = class {
27978
28540
 
27979
28541
  // src/compact/recent-tail.ts
27980
28542
  init_tokenEstimate();
27981
- function splitRecentHistory(messages, keepRecentTokens, budget) {
28543
+ function splitRecentHistory(messages, keepRecentTokens, budget, activeQueryId) {
27982
28544
  const protectedHistory = splitProtectedCompactHistory(messages, budget);
27983
28545
  let start = protectedHistory.prefix.length;
27984
28546
  if (keepRecentTokens > 0) {
@@ -27991,6 +28553,10 @@ function splitRecentHistory(messages, keepRecentTokens, budget) {
27991
28553
  }
27992
28554
  start = Math.min(start, recentStart);
27993
28555
  }
28556
+ if (activeQueryId) {
28557
+ const activeStart = messages.findIndex((m) => "role" in m && m.role === "user" && (m.inputSource?.queryId === activeQueryId || m.steerInput?.queryId === activeQueryId));
28558
+ if (activeStart >= 0) start = Math.min(start, activeStart);
28559
+ }
27994
28560
  const suffix = messages.slice(start);
27995
28561
  if (estimateMessageTokens(suffix) > budget) {
27996
28562
  const fused = fitProtectedTail(suffix, budget);
@@ -28504,14 +29070,14 @@ function shouldAutoCompact(messages, config) {
28504
29070
  compactLog(TAG3, `tokens=${tokenCount} threshold=${threshold} triggered=${result}`);
28505
29071
  return result;
28506
29072
  }
28507
- async function autoCompactIfNeeded(messages, config, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact = false) {
29073
+ async function autoCompactIfNeeded(messages, config, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact = false, activeQueryId) {
28508
29074
  const starts = messages.filter((m) => isAttachmentMessage(m) && m.attachment.type === "session_start");
28509
29075
  if (starts.length) {
28510
29076
  const body = messages.filter((m) => !starts.includes(m));
28511
29077
  const result = await autoCompactIfNeeded(body, {
28512
29078
  ...config,
28513
29079
  systemOverheadTokens: (config.systemOverheadTokens ?? 0) + estimateMessageTokens(starts)
28514
- }, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact);
29080
+ }, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact, activeQueryId);
28515
29081
  const retained = result.wasCompacted ? [...starts, ...result.messages] : messages;
28516
29082
  return { ...result, messages: retained, ...result.compactionResult ? { compactionResult: {
28517
29083
  ...result.compactionResult,
@@ -28520,8 +29086,8 @@ async function autoCompactIfNeeded(messages, config, tracking, provider, model,
28520
29086
  postCompactTokenCount: estimateMessageTokens(retained)
28521
29087
  } } : {} };
28522
29088
  }
28523
- if ((config.keepRecentTokens ?? 0) > 0 && config.enabled !== false) {
28524
- const { prefix: prefix3, suffix: suffix2 } = splitRecentHistory(messages, config.keepRecentTokens, getAutoCompactThreshold(config));
29089
+ if (((config.keepRecentTokens ?? 0) > 0 || activeQueryId) && config.enabled !== false) {
29090
+ const { prefix: prefix3, suffix: suffix2 } = splitRecentHistory(messages, config.keepRecentTokens ?? 0, getAutoCompactThreshold(config), activeQueryId);
28525
29091
  if (suffix2.length) {
28526
29092
  if (!prefix3.length) return { wasCompacted: false, messages, consecutiveFailures: tracking.consecutiveFailures };
28527
29093
  const result = await autoCompactIfNeeded(prefix3, {
@@ -29002,9 +29568,9 @@ async function streamCompactSummary(messages, compactPrompt, provider, model, ma
29002
29568
  init_tokenEstimate();
29003
29569
 
29004
29570
  // src/compact/background.ts
29005
- import { createHash as createHash32 } from "node:crypto";
29571
+ import { createHash as createHash33 } from "node:crypto";
29006
29572
  init_tokenEstimate();
29007
- var historyFingerprint = (messages) => createHash32("sha256").update(JSON.stringify(messages)).digest("hex");
29573
+ var historyFingerprint = (messages) => createHash33("sha256").update(JSON.stringify(messages)).digest("hex");
29008
29574
 
29009
29575
  // src/models/contextOverflow.ts
29010
29576
  var CONTEXT_OVERFLOW_SAFETY_BUFFER = 1e3;
@@ -29095,8 +29661,8 @@ init_live();
29095
29661
  // src/goals/store.ts
29096
29662
  init_db();
29097
29663
  init_schema2();
29098
- import fs18 from "node:fs";
29099
- import path24 from "node:path";
29664
+ import fs19 from "node:fs";
29665
+ import path26 from "node:path";
29100
29666
  import crypto3 from "node:crypto";
29101
29667
 
29102
29668
  // src/goals/read-snapshot.ts
@@ -29104,10 +29670,10 @@ init_db();
29104
29670
 
29105
29671
  // src/goals/store.ts
29106
29672
  function file(stateDir) {
29107
- return path24.join(stateDir, "goals.json");
29673
+ return path26.join(stateDir, "goals.json");
29108
29674
  }
29109
29675
  function eventFile(stateDir) {
29110
- return path24.join(stateDir, "goal-events.jsonl");
29676
+ return path26.join(stateDir, "goal-events.jsonl");
29111
29677
  }
29112
29678
  function db(stateDir) {
29113
29679
  const d = openDb(stateDir);
@@ -29115,17 +29681,17 @@ function db(stateDir) {
29115
29681
  return d;
29116
29682
  }
29117
29683
  function event(stateDir, goalId, type, payload = {}) {
29118
- fs18.mkdirSync(stateDir, { recursive: true });
29684
+ fs19.mkdirSync(stateDir, { recursive: true });
29119
29685
  const id3 = `ge-${Date.now()}-${crypto3.randomBytes(3).toString("hex")}`;
29120
29686
  const at = (/* @__PURE__ */ new Date()).toISOString();
29121
- fs18.appendFileSync(eventFile(stateDir), JSON.stringify({ eventId: id3, goalId, type, at, ...payload }) + "\n", "utf8");
29687
+ fs19.appendFileSync(eventFile(stateDir), JSON.stringify({ eventId: id3, goalId, type, at, ...payload }) + "\n", "utf8");
29122
29688
  const d = db(stateDir);
29123
29689
  d.prepare("INSERT INTO goal_events (event_id, goal_id, type, payload_json, created_at) VALUES (?, ?, ?, ?, ?)").run(id3, goalId, type, JSON.stringify(payload), at);
29124
29690
  d.close?.();
29125
29691
  }
29126
29692
  function read(stateDir) {
29127
29693
  try {
29128
- const v = JSON.parse(fs18.readFileSync(file(stateDir), "utf8"));
29694
+ const v = JSON.parse(fs19.readFileSync(file(stateDir), "utf8"));
29129
29695
  return Array.isArray(v) ? v : [];
29130
29696
  } catch {
29131
29697
  return [];
@@ -29180,41 +29746,13 @@ function markGoalBudgetLimited(stateDir, id3) {
29180
29746
  // src/tools/task-manager.ts
29181
29747
  import { randomBytes as randomBytes6 } from "node:crypto";
29182
29748
  import { spawn as spawn4 } from "node:child_process";
29183
- import * as fs20 from "node:fs";
29184
- import * as path27 from "node:path";
29185
-
29186
- // src/utils/path.ts
29187
- import * as path25 from "node:path";
29188
- var extraAllowedPaths = [];
29189
- var sandboxOff = false;
29190
- function fixMsysPath(p) {
29191
- let fixed = p.includes("\\") ? p.replace(/\\/g, "/") : p;
29192
- if (process.platform === "win32") {
29193
- fixed = fixed.replace(/^\/([a-zA-Z])\//, (_, letter) => `${letter.toUpperCase()}:/`);
29194
- }
29195
- return fixed;
29196
- }
29197
- function resolvePath(p, workspace) {
29198
- const fixed = fixMsysPath(p);
29199
- const resolved = path25.isAbsolute(fixed) ? path25.normalize(fixed) : path25.resolve(workspace, fixed);
29200
- const normalized = path25.normalize(resolved);
29201
- const normalizedWorkspace = path25.normalize(workspace);
29202
- if (sandboxOff) return normalized;
29203
- if (normalized === normalizedWorkspace || normalized.startsWith(normalizedWorkspace + path25.sep)) {
29204
- return normalized;
29205
- }
29206
- for (const allowed of extraAllowedPaths) {
29207
- if (normalized === allowed || normalized.startsWith(allowed + path25.sep)) {
29208
- return normalized;
29209
- }
29210
- }
29211
- throw new Error(`\u8DEF\u5F84\u8D85\u51FA workspace \u8303\u56F4: ${p} \u2192 ${normalized} (workspace: ${normalizedWorkspace})`);
29212
- }
29749
+ import * as fs21 from "node:fs";
29750
+ import * as path28 from "node:path";
29213
29751
 
29214
29752
  // src/tools/BashTool/BashTool.ts
29215
29753
  import { spawn as spawn3, execSync } from "node:child_process";
29216
- import * as fs19 from "node:fs";
29217
- import * as path26 from "node:path";
29754
+ import * as fs20 from "node:fs";
29755
+ import * as path27 from "node:path";
29218
29756
 
29219
29757
  // src/tools/BashTool/prompt.ts
29220
29758
  var GLOB_TOOL_NAME = "glob";
@@ -29435,7 +29973,7 @@ function findShell() {
29435
29973
  });
29436
29974
  const candidates2 = result.trim().split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
29437
29975
  const nonWsl = candidates2.find((p) => !isWslBash(p));
29438
- if (nonWsl && fs19.existsSync(nonWsl)) {
29976
+ if (nonWsl && fs20.existsSync(nonWsl)) {
29439
29977
  cachedShell = { shell: nonWsl, args: ["-c"] };
29440
29978
  return cachedShell;
29441
29979
  }
@@ -29445,10 +29983,10 @@ function findShell() {
29445
29983
  "C:\\Program Files\\Git\\bin\\bash.exe",
29446
29984
  "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
29447
29985
  "C:\\Program Files\\Git\\usr\\bin\\bash.exe",
29448
- path26.join(process.env.LOCALAPPDATA || "", "Programs", "Git", "bin", "bash.exe")
29986
+ path27.join(process.env.LOCALAPPDATA || "", "Programs", "Git", "bin", "bash.exe")
29449
29987
  ];
29450
29988
  for (const p of knownPaths) {
29451
- if (p && fs19.existsSync(p)) {
29989
+ if (p && fs20.existsSync(p)) {
29452
29990
  cachedShell = { shell: p, args: ["-c"] };
29453
29991
  return cachedShell;
29454
29992
  }
@@ -29512,7 +30050,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29512
30050
  const runInBackground = args.run_in_background || false;
29513
30051
  let cwd;
29514
30052
  try {
29515
- cwd = args.cwd ? resolvePath(args.cwd, ctx.workspace) : ctx.workspace;
30053
+ cwd = args.cwd ? resolveFilePath(args.cwd, ctx, true) : ctx.workspace;
29516
30054
  } catch (e) {
29517
30055
  return { content: e.message, isError: true };
29518
30056
  }
@@ -29541,12 +30079,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29541
30079
  }
29542
30080
  const MAX_OUTPUT = 100 * 1024;
29543
30081
  const startTime = Date.now();
29544
- fs19.mkdirSync(getTaskOutputDir(), { recursive: true });
29545
- const outputFile = path26.join(getTaskOutputDir(), `exec-${startTime}-${Math.random().toString(36).slice(2)}.output`);
29546
- const outputHandle = await fs19.promises.open(outputFile, "w");
30082
+ fs20.mkdirSync(getTaskOutputDir(), { recursive: true });
30083
+ const outputFile = path27.join(getTaskOutputDir(), `exec-${startTime}-${Math.random().toString(36).slice(2)}.output`);
30084
+ const outputHandle = await fs20.promises.open(outputFile, "w");
29547
30085
  if (signal?.aborted || ctx.yieldSignal?.aborted) {
29548
30086
  await outputHandle.close();
29549
- await fs19.promises.unlink(outputFile);
30087
+ await fs20.promises.unlink(outputFile);
29550
30088
  return { content: "[not executed: new user input or stop received before command start]" };
29551
30089
  }
29552
30090
  return new Promise((resolve12) => {
@@ -29576,18 +30114,18 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29576
30114
  let output = "";
29577
30115
  let truncated = false;
29578
30116
  try {
29579
- const fd = fs19.openSync(outputFile, "r");
30117
+ const fd = fs20.openSync(outputFile, "r");
29580
30118
  try {
29581
- truncated = fs19.fstatSync(fd).size > MAX_OUTPUT;
30119
+ truncated = fs20.fstatSync(fd).size > MAX_OUTPUT;
29582
30120
  const buffer = Buffer.alloc(MAX_OUTPUT);
29583
- output = buffer.subarray(0, fs19.readSync(fd, buffer, 0, MAX_OUTPUT, 0)).toString("utf8");
30121
+ output = buffer.subarray(0, fs20.readSync(fd, buffer, 0, MAX_OUTPUT, 0)).toString("utf8");
29584
30122
  } finally {
29585
- fs19.closeSync(fd);
30123
+ fs20.closeSync(fd);
29586
30124
  }
29587
30125
  } catch {
29588
30126
  }
29589
30127
  try {
29590
- await fs19.promises.unlink(outputFile);
30128
+ await fs20.promises.unlink(outputFile);
29591
30129
  } catch {
29592
30130
  }
29593
30131
  const parts = [
@@ -29661,8 +30199,9 @@ init_temporal();
29661
30199
  init_dependencies();
29662
30200
  init_basis_check();
29663
30201
  init_relationship_notice_check();
30202
+ init_watermarks();
29664
30203
  init_scope();
29665
- import { join as join25, resolve as resolve8 } from "node:path";
30204
+ import { join as join26, resolve as resolve9 } from "node:path";
29666
30205
  var contextIdentity = (context) => canonicalJson({
29667
30206
  scopeId: context.scopeId,
29668
30207
  basisRefs: context.basisRefs,
@@ -29674,8 +30213,8 @@ var contextIdentity = (context) => canonicalJson({
29674
30213
  function createNotificationStateReader() {
29675
30214
  const databases = /* @__PURE__ */ new Map();
29676
30215
  const checkers = /* @__PURE__ */ new Map();
29677
- const open3 = (path35) => {
29678
- const key4 = resolve8(path35);
30216
+ const open3 = (path36) => {
30217
+ const key4 = resolve9(path36);
29679
30218
  let db2 = databases.get(key4);
29680
30219
  if (!db2) {
29681
30220
  db2 = new DatabaseSync11(key4, { readOnly: true });
@@ -29710,14 +30249,14 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29710
30249
  const context = route.executionContext;
29711
30250
  const runtime = route.memoryRuntime ?? (route.hostDelivery ? { workspace: route.hostDelivery.workspace, stateDir: queueStateDir } : void 0);
29712
30251
  if (!context || !runtime) return {};
29713
- if (route.hostDelivery && resolve8(route.hostDelivery.workspace) !== resolve8(runtime.workspace)) {
30252
+ if (route.hostDelivery && resolve9(route.hostDelivery.workspace) !== resolve9(runtime.workspace)) {
29714
30253
  return { state: "blocked", reason: "MEMORY_NOTIFICATION_RUNTIME_MISMATCH", redact: true };
29715
30254
  }
29716
30255
  let memory;
29717
30256
  let proactive;
29718
30257
  let calendar;
29719
30258
  try {
29720
- memory = open3(join25(runtime.stateDir, "mem7", "index", "mem7.db"));
30259
+ memory = open3(join26(runtime.stateDir, "mem7", "index", "mem7.db"));
29721
30260
  const scope = memory.prepare("SELECT * FROM memory_scopes WHERE scope_id=?").get(context.scopeId);
29722
30261
  if (!scope) {
29723
30262
  return { state: "blocked", reason: "MEMORY_NOTIFICATION_SCOPE_MISSING", redact: true };
@@ -29744,7 +30283,8 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29744
30283
  }
29745
30284
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
29746
30285
  const ledgerDependencies = new MemoryDependencies(memory, (operation) => operation());
29747
- proactive = open3(join25(runtime.workspace, ".proactive", "proactive.db"));
30286
+ const retractions = emptyRetractionCache();
30287
+ proactive = open3(join26(runtime.workspace, ".proactive", "proactive.db"));
29748
30288
  for (const id3 of Object.keys(context.actionVersions)) {
29749
30289
  const action = proactive.prepare("SELECT scope_id,intent_id FROM actions WHERE id=?").get(id3);
29750
30290
  if (!action || action.scope_id !== context.scopeId) return { state: "blocked", reason: "MEMORY_NOTIFICATION_ACTION_MISMATCH", redact: true };
@@ -29757,6 +30297,9 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29757
30297
  const row = proactive.prepare("SELECT data FROM nodes WHERE id=?").get(nodeId);
29758
30298
  const data = row && JSON.parse(row.data);
29759
30299
  if (!data || data.scopeId !== context.scopeId || data.evidenceState === "deleted") return { state: "blocked", reason: "memory_deleted", redact: true };
30300
+ if (typeof data.sourceWatermark === "number" && typeof data.retractionWatermark === "number" && deletedWithinView(memory, context.scopeId, data.retractionWatermark, data.sourceWatermark, retractions)) {
30301
+ return { state: "blocked", reason: "memory_deleted", redact: true };
30302
+ }
29760
30303
  for (const evidence of [...data.sourceRefs ?? [], ...data.sourceEvidence ?? []]) {
29761
30304
  if (evidence.sourceId && deletedSource(evidence.sourceId)) return { state: "blocked", reason: "memory_deleted", redact: true };
29762
30305
  if (evidence.sourceId && Number.isSafeInteger(evidence.sourceVersion)) {
@@ -29798,7 +30341,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29798
30341
  }
29799
30342
  if (route.hostDelivery) {
29800
30343
  if (!proactive) {
29801
- proactive = open3(join25(runtime.workspace, ".proactive", "proactive.db"));
30344
+ proactive = open3(join26(runtime.workspace, ".proactive", "proactive.db"));
29802
30345
  }
29803
30346
  const receipt = proactive.prepare("SELECT * FROM proactive_host_deliveries WHERE delivery_key=?").get(route.hostDelivery.key);
29804
30347
  if (!receipt || contextIdentity(JSON.parse(receipt.context_json)) !== contextIdentity(context)) {
@@ -29809,7 +30352,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29809
30352
  if (["blocked", "delivery_unknown"].includes(receipt.state)) return { state: receipt.state, reason: receipt.reason ?? receipt.state };
29810
30353
  }
29811
30354
  if (context.calendarBinding) {
29812
- calendar = open3(join25(runtime.workspace, ".calendar", "calendar.db"));
30355
+ calendar = open3(join26(runtime.workspace, ".calendar", "calendar.db"));
29813
30356
  const binding = context.calendarBinding;
29814
30357
  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);
29815
30358
  if (rows.some((row) => ["started", "delivery_unknown"].includes(row.state) && !row.closure)) {
@@ -29844,50 +30387,50 @@ var _taskOutputDir;
29844
30387
  function getTaskOutputDir() {
29845
30388
  if (_taskOutputDir === void 0) {
29846
30389
  const stateDir = process.env.ENGINE_STATE_DIR || process.cwd();
29847
- _taskOutputDir = path27.join(stateDir, "tasks");
30390
+ _taskOutputDir = path28.join(stateDir, "tasks");
29848
30391
  }
29849
30392
  return _taskOutputDir;
29850
30393
  }
29851
30394
  function getTaskOutputPath(taskId) {
29852
- return path27.join(getTaskOutputDir(), `${taskId}.output`);
30395
+ return path28.join(getTaskOutputDir(), `${taskId}.output`);
29853
30396
  }
29854
30397
  function ensureOutputDir() {
29855
30398
  const dir = getTaskOutputDir();
29856
- if (!fs20.existsSync(dir)) {
29857
- fs20.mkdirSync(dir, { recursive: true });
30399
+ if (!fs21.existsSync(dir)) {
30400
+ fs21.mkdirSync(dir, { recursive: true });
29858
30401
  }
29859
30402
  }
29860
30403
  function initTaskOutput(taskId) {
29861
30404
  ensureOutputDir();
29862
30405
  const outputPath = getTaskOutputPath(taskId);
29863
- fs20.writeFileSync(outputPath, "", "utf-8");
30406
+ fs21.writeFileSync(outputPath, "", "utf-8");
29864
30407
  return outputPath;
29865
30408
  }
29866
30409
  var tasks = /* @__PURE__ */ new Map();
29867
30410
  var processes = /* @__PURE__ */ new Map();
29868
- var taskIndexPath = () => path27.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "index.json");
30411
+ var taskIndexPath = () => path28.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "index.json");
29869
30412
  function persistTask(state) {
29870
30413
  try {
29871
30414
  ensureOutputDir();
29872
30415
  const p = taskIndexPath();
29873
- const existing = fs20.existsSync(p) ? JSON.parse(fs20.readFileSync(p, "utf8")) : [];
30416
+ const existing = fs21.existsSync(p) ? JSON.parse(fs21.readFileSync(p, "utf8")) : [];
29874
30417
  const next = existing.filter((t) => t.id !== state.id);
29875
30418
  next.push({ ...state });
29876
30419
  const tmp = `${p}.${process.pid}.tmp`;
29877
- fs20.writeFileSync(tmp, JSON.stringify(next, null, 2));
29878
- fs20.renameSync(tmp, p);
30420
+ fs21.writeFileSync(tmp, JSON.stringify(next, null, 2));
30421
+ fs21.renameSync(tmp, p);
29879
30422
  } catch (err) {
29880
30423
  console.warn(`[task-manager] persist failed: ${err.message}`);
29881
30424
  }
29882
30425
  }
29883
30426
  var pendingNotifications = [];
29884
30427
  var notificationsLoaded = false;
29885
- var notificationQueuePath = () => path27.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "notifications.json");
30428
+ var notificationQueuePath = () => path28.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "notifications.json");
29886
30429
  function loadNotificationQueue() {
29887
30430
  if (notificationsLoaded) return;
29888
30431
  notificationsLoaded = true;
29889
30432
  try {
29890
- const value = JSON.parse(fs20.readFileSync(notificationQueuePath(), "utf8"));
30433
+ const value = JSON.parse(fs21.readFileSync(notificationQueuePath(), "utf8"));
29891
30434
  if (Array.isArray(value)) pendingNotifications.push(...value.filter((x) => x && typeof x.notification === "string"));
29892
30435
  } catch {
29893
30436
  }
@@ -29897,8 +30440,8 @@ function persistNotificationQueue(strict = false) {
29897
30440
  ensureOutputDir();
29898
30441
  const p = notificationQueuePath();
29899
30442
  const tmp = `${p}.${process.pid}.tmp`;
29900
- fs20.writeFileSync(tmp, JSON.stringify(pendingNotifications, null, 2), "utf8");
29901
- fs20.renameSync(tmp, p);
30443
+ fs21.writeFileSync(tmp, JSON.stringify(pendingNotifications, null, 2), "utf8");
30444
+ fs21.renameSync(tmp, p);
29902
30445
  } catch (err) {
29903
30446
  if (strict) throw err;
29904
30447
  console.warn(`[task-manager] notification persist failed: ${err.message}`);
@@ -30052,7 +30595,7 @@ function syncPendingNotificationState(runtime) {
30052
30595
  try {
30053
30596
  for (const record2 of pendingNotifications) {
30054
30597
  const route = record2.route;
30055
- 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))) {
30598
+ 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))) {
30056
30599
  next.push(record2);
30057
30600
  continue;
30058
30601
  }
@@ -30093,7 +30636,7 @@ function spawnBackgroundTask(opts) {
30093
30636
  const taskId = generateTaskId("local_bash");
30094
30637
  const outputPath = initTaskOutput(taskId);
30095
30638
  const { shell, args: shellArgs } = findShell();
30096
- const outputFd = fs20.openSync(outputPath, "w");
30639
+ const outputFd = fs21.openSync(outputPath, "w");
30097
30640
  const child = spawn4(shell, [...shellArgs, opts.command], {
30098
30641
  cwd: opts.cwd,
30099
30642
  env: opts.env || process.env,
@@ -30104,7 +30647,7 @@ function spawnBackgroundTask(opts) {
30104
30647
  // 1011:GUI 宿主(Electron 装机版)下后台任务别闪黑窗,同 BashTool
30105
30648
  });
30106
30649
  try {
30107
- fs20.closeSync(outputFd);
30650
+ fs21.closeSync(outputFd);
30108
30651
  } catch {
30109
30652
  }
30110
30653
  return trackBackgroundTask(opts, child, outputPath, Date.now(), taskId);
@@ -30146,12 +30689,12 @@ function trackBackgroundTask(opts, child, outputPath, startTime, taskId) {
30146
30689
  let killedForSize = false;
30147
30690
  sizeWatchdog = setInterval(() => {
30148
30691
  if (tasks.get(taskId)?.status !== "running") return;
30149
- fs20.stat(outputPath, (err, st) => {
30692
+ fs21.stat(outputPath, (err, st) => {
30150
30693
  if (err || st.size <= MAX_TASK_OUTPUT_BYTES) return;
30151
30694
  killedForSize = true;
30152
30695
  if (sizeWatchdog) clearInterval(sizeWatchdog);
30153
30696
  try {
30154
- fs20.appendFileSync(outputPath, "\n[output truncated: exceeded 5GB disk cap]\n");
30697
+ fs21.appendFileSync(outputPath, "\n[output truncated: exceeded 5GB disk cap]\n");
30155
30698
  } catch {
30156
30699
  }
30157
30700
  killChild(child);
@@ -30281,22 +30824,6 @@ function killTask(taskId) {
30281
30824
  return true;
30282
30825
  }
30283
30826
 
30284
- // src/skills/skill-gate.ts
30285
- init_strip_injected();
30286
- var USER_CHANNELS = /* @__PURE__ */ new Set(["discord", "feishu", "wechat", "telegram", "cli", "console", "voice-chat", "deskBuddy", "ccBridge"]);
30287
- var loadedBySession = /* @__PURE__ */ new Map();
30288
- var MAX_TRACKED_SESSIONS = 100;
30289
- function beginSkillGate(sessionId) {
30290
- if (loadedBySession.size >= MAX_TRACKED_SESSIONS && !loadedBySession.has(sessionId)) {
30291
- const oldest = loadedBySession.keys().next().value;
30292
- if (oldest !== void 0) loadedBySession.delete(oldest);
30293
- }
30294
- loadedBySession.set(sessionId, /* @__PURE__ */ new Set());
30295
- }
30296
- function isUserChannel(ch) {
30297
- return !!ch && USER_CHANNELS.has(ch);
30298
- }
30299
-
30300
30827
  // src/core/query.ts
30301
30828
  function blockedToolCallsForOverride(calls, override2) {
30302
30829
  if (!override2) return [];
@@ -30368,12 +30895,12 @@ var QueryEngine = class _QueryEngine {
30368
30895
  try {
30369
30896
  const url = "https://localhost:8116/voice-reply";
30370
30897
  if (url.startsWith("https://")) {
30371
- const https = await import("node:https");
30898
+ const https2 = await import("node:https");
30372
30899
  const postData = JSON.stringify({ text: line, isPlaceholder: true });
30373
30900
  assertExternalEffectCurrent();
30374
30901
  beginHostTurnEffect();
30375
30902
  await new Promise((resolve12, reject) => {
30376
- const req = https.request(url, {
30903
+ const req = https2.request(url, {
30377
30904
  method: "POST",
30378
30905
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) },
30379
30906
  rejectUnauthorized: false
@@ -30582,7 +31109,7 @@ var QueryEngine = class _QueryEngine {
30582
31109
  let currentMessages = [...messages];
30583
31110
  const stopUserMessages = [];
30584
31111
  const stopToolResults = [];
30585
- const collectStopEvidence = !this.options.skipStopHook && !perTurnEmotion;
31112
+ const collectStopEvidence = !context?.projectTask && !this.options.skipStopHook && !perTurnEmotion;
30586
31113
  const currentUser = collectStopEvidence ? messages.findLast((m) => "role" in m && m.role === "user") : void 0;
30587
31114
  if (currentUser && "role" in currentUser) {
30588
31115
  stopUserMessages.push(currentUser.memoryOriginalText ?? (typeof currentUser.content === "string" ? currentUser.content : currentUser.content.filter((b) => b.type === "text").map((b) => b.text).join("\n")));
@@ -30876,6 +31403,7 @@ var QueryEngine = class _QueryEngine {
30876
31403
  provider: queryProvider,
30877
31404
  model: queryModel,
30878
31405
  identity,
31406
+ activeQueryId: queryId,
30879
31407
  hookContext: context ? {
30880
31408
  sessionId: compactSessionId,
30881
31409
  workspace: context.workspace || "",
@@ -30926,7 +31454,9 @@ var QueryEngine = class _QueryEngine {
30926
31454
  channel: context.channel || "console",
30927
31455
  cwd: context.workspace || process.env.ENGINE_WORKSPACE || ""
30928
31456
  } : void 0,
30929
- snapshotContext
31457
+ snapshotContext,
31458
+ false,
31459
+ queryId
30930
31460
  ).catch((error) => {
30931
31461
  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}`);
30932
31462
  });
@@ -31012,7 +31542,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
31012
31542
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
31013
31543
 
31014
31544
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31015
- if (process.env.ENGINE_DUMP_REQUEST === "1" && (!this.options.agentLabel || this.options.agentLabel === "main")) {
31545
+ if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
31016
31546
  try {
31017
31547
  const ws = process.env.ENGINE7_WORKSPACE;
31018
31548
  if (ws) {
@@ -31113,13 +31643,13 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31113
31643
  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` };
31114
31644
  return;
31115
31645
  }
31116
- const delay = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
31646
+ const delay2 = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
31117
31647
  if (streamRetries < MAX_STREAM_RETRIES && !ac.signal.aborted) {
31118
- console.log(`${this.logPrefix} Turn ${turnCount}: stream retry ${streamRetries + 1}/${MAX_STREAM_RETRIES}, delay=${delay}ms`);
31648
+ console.log(`${this.logPrefix} Turn ${turnCount}: stream retry ${streamRetries + 1}/${MAX_STREAM_RETRIES}, delay=${delay2}ms`);
31119
31649
  yield { type: "status", text: `\u26A0\uFE0F API error, retrying (${streamRetries + 1}/${MAX_STREAM_RETRIES})...` };
31120
31650
  this.phase = "tools";
31121
31651
  try {
31122
- await waitForRetry(delay, void 0, { signal: ac.signal });
31652
+ await waitForRetry(delay2, void 0, { signal: ac.signal });
31123
31653
  } catch (error) {
31124
31654
  if (!ac.signal.aborted) throw error;
31125
31655
  }
@@ -31256,7 +31786,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31256
31786
  completionReason = "output_limit";
31257
31787
  break;
31258
31788
  }
31259
- if (this.options.skipStopHook || perTurnEmotion) {
31789
+ if (context?.projectTask || this.options.skipStopHook || perTurnEmotion) {
31260
31790
  if (this.pendingSteers.length > 0) {
31261
31791
  const carried = carryReply();
31262
31792
  if (carried) yield* carried;
@@ -31565,8 +32095,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31565
32095
  return this.provider;
31566
32096
  }
31567
32097
  /** Share model configuration, but give concurrent sessions their own abort/steer/compact state. */
31568
- fork(agentLabel) {
31569
- const fork = new _QueryEngine(this.provider, { ...this.options, agentLabel });
32098
+ fork(agentLabel, prompts) {
32099
+ const fork = new _QueryEngine(this.provider, { ...this.options, ...prompts, agentLabel });
31570
32100
  fork.backgroundOwners = this.backgroundOwners;
31571
32101
  return fork;
31572
32102
  }
@@ -31710,9 +32240,9 @@ function readState(stateFile) {
31710
32240
  return { lastPatrolAt: 0, lastLineCounts: {} };
31711
32241
  }
31712
32242
  function writeState(stateFile, state) {
31713
- const dir = path29.dirname(stateFile);
32243
+ const dir = path30.dirname(stateFile);
31714
32244
  fsSync3.mkdirSync(dir, { recursive: true });
31715
- const tmp = path29.join(dir, `.${path29.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
32245
+ const tmp = path30.join(dir, `.${path30.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
31716
32246
  try {
31717
32247
  fsSync3.writeFileSync(tmp, JSON.stringify(state), "utf-8");
31718
32248
  fsSync3.renameSync(tmp, stateFile);
@@ -31741,7 +32271,7 @@ function buildPatrolPrompt(materials) {
31741
32271
  ].join("\n");
31742
32272
  }
31743
32273
  function defaultWriteMemoryNote(workspace) {
31744
- const dir = path29.join(getAutoMemPath(workspace), "whatsapp-patrol");
32274
+ const dir = path30.join(getAutoMemPath(workspace), "whatsapp-patrol");
31745
32275
  return (note) => {
31746
32276
  fsSync3.mkdirSync(dir, { recursive: true });
31747
32277
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
@@ -31755,7 +32285,7 @@ function defaultWriteMemoryNote(workspace) {
31755
32285
  note,
31756
32286
  ""
31757
32287
  ].join("\n");
31758
- fsSync3.writeFileSync(path29.join(dir, `patrol-${stamp}.md`), body, "utf-8");
32288
+ fsSync3.writeFileSync(path30.join(dir, `patrol-${stamp}.md`), body, "utf-8");
31759
32289
  };
31760
32290
  }
31761
32291
  function makeSubmitToMain(engineDeps) {
@@ -31900,15 +32430,15 @@ ${quoted}`);
31900
32430
 
31901
32431
  // src/utils/ffmpeg-path.ts
31902
32432
  init_dep_downloader();
31903
- import * as fs22 from "node:fs";
32433
+ import * as fs23 from "node:fs";
31904
32434
  function resolveFfmpegPath() {
31905
32435
  const env = (process.env.E7_FFMPEG_PATH || "").trim();
31906
- if (env && fs22.existsSync(env)) return env;
32436
+ if (env && fs23.existsSync(env)) return env;
31907
32437
  const downloaded = optionalFfmpegPath();
31908
32438
  if (downloaded) return downloaded;
31909
32439
  try {
31910
32440
  const p = __require("@ffmpeg-installer/ffmpeg")?.path;
31911
- if (p && fs22.existsSync(p)) return p;
32441
+ if (p && fs23.existsSync(p)) return p;
31912
32442
  } catch {
31913
32443
  }
31914
32444
  return "ffmpeg";
@@ -31994,10 +32524,10 @@ function normalizeAllowEntry(entry) {
31994
32524
  }
31995
32525
  function atomicWriteFile(dir, fileName, content) {
31996
32526
  fsSync4.mkdirSync(dir, { recursive: true });
31997
- const tmp = path30.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID17().slice(0, 8)}`);
32527
+ const tmp = path31.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID17().slice(0, 8)}`);
31998
32528
  try {
31999
32529
  fsSync4.writeFileSync(tmp, content, "utf-8");
32000
- fsSync4.renameSync(tmp, path30.join(dir, fileName));
32530
+ fsSync4.renameSync(tmp, path31.join(dir, fileName));
32001
32531
  } catch (e) {
32002
32532
  try {
32003
32533
  fsSync4.rmSync(tmp, { force: true });
@@ -32112,13 +32642,13 @@ var WhatsAppAdapter = class {
32112
32642
  constructor(cfg, opts = {}) {
32113
32643
  this.cfg = cfg;
32114
32644
  this.stateDir = cfg.stateDir;
32115
- this.authDir = path30.join(cfg.stateDir, "whatsapp-auth");
32116
- this.qrFilePath = path30.join(cfg.stateDir, "whatsapp-qr.txt");
32645
+ this.authDir = path31.join(cfg.stateDir, "whatsapp-auth");
32646
+ this.qrFilePath = path31.join(cfg.stateDir, "whatsapp-qr.txt");
32117
32647
  this.opts = opts;
32118
32648
  this.credsStore = opts.credsStoreOverride ?? makeCredsStore(this.authDir);
32119
32649
  this.loginTtlMs = opts.loginTtlMs ?? LOGIN_TTL_MS;
32120
32650
  this.digestEnabled = cfg.groupDigest?.enabled !== false;
32121
- this.digest = this.digestEnabled ? new GroupDigestStore(path30.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
32651
+ this.digest = this.digestEnabled ? new GroupDigestStore(path31.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
32122
32652
  this.typing = new PresenceTypingCoalescer(async (jid) => {
32123
32653
  const sock = this.sock;
32124
32654
  if (!sock || typeof sock.sendPresenceUpdate !== "function") return;
@@ -32253,7 +32783,7 @@ var WhatsAppAdapter = class {
32253
32783
  this.patrol = startPatrolLoop({
32254
32784
  digest: this.digest,
32255
32785
  intervalMin: this.cfg.groupDigest?.patrolIntervalMin ?? 60,
32256
- stateFile: path30.join(this.stateDir, "whatsapp-patrol-state.json"),
32786
+ stateFile: path31.join(this.stateDir, "whatsapp-patrol-state.json"),
32257
32787
  runReadOnlyAgent: makeReadOnlyAgentRunner(this.opts.patrolDeps),
32258
32788
  // ⚠️ 升级接线(终审 C1,1003):摘要含 ⚠️ 行时宿主经主 session 投递(spec §4)——
32259
32789
  // makeSubmitToMain 吃的正是 patrolDeps {dispatcher, deps}(patrol.ts)形状。漏接这行 =
@@ -32550,11 +33080,11 @@ ${r}` : r;
32550
33080
  const idRaw = typeof raw?.key?.id === "string" && raw.key.id ? raw.key.id : "";
32551
33081
  const idSafe = idRaw.replace(/[^\w.-]/g, "_");
32552
33082
  const id3 = !idRaw || idSafe !== idRaw || !idSafe ? randomUUID17() : idSafe;
32553
- const dir = path30.join(this.stateDir, "media", "whatsapp");
33083
+ const dir = path31.join(this.stateDir, "media", "whatsapp");
32554
33084
  fsSync4.mkdirSync(dir, { recursive: true });
32555
- const abs = path30.join(dir, `${id3}.${ext}`);
32556
- const resolved = path30.resolve(abs);
32557
- if (!resolved.startsWith(path30.resolve(dir) + path30.sep)) {
33085
+ const abs = path31.join(dir, `${id3}.${ext}`);
33086
+ const resolved = path31.resolve(abs);
33087
+ if (!resolved.startsWith(path31.resolve(dir) + path31.sep)) {
32558
33088
  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}`);
32559
33089
  return `${placeholder}\uFF08\u4E0B\u8F7D\u5931\u8D25\uFF09`;
32560
33090
  }
@@ -32588,7 +33118,7 @@ ${r}` : r;
32588
33118
  const lids = [jid, participant].filter((j) => j.endsWith("@lid"));
32589
33119
  if (lids.length === 0) return;
32590
33120
  try {
32591
- const filePath2 = path30.join(this.authDir, "lid-mapping.json");
33121
+ const filePath2 = path31.join(this.authDir, "lid-mapping.json");
32592
33122
  let arr = [];
32593
33123
  try {
32594
33124
  const parsed = JSON.parse(fsSync4.readFileSync(filePath2, "utf-8"));
@@ -32698,7 +33228,7 @@ ${r}` : r;
32698
33228
  if (isGroupJid(jid)) throw new Error(`WhatsApp \u7FA4\u53D1\u9001\u7269\u7406\u4E0D\u5B58\u5728\uFF08\u7EA2\u7EBF\uFF09\uFF1Atarget=${jid}`);
32699
33229
  const sock = this.requireSock();
32700
33230
  const mime = attachment.mimeType ?? "";
32701
- const filename = attachment.filename ?? path30.basename(attachment.path);
33231
+ const filename = attachment.filename ?? path31.basename(attachment.path);
32702
33232
  if (mime.startsWith("image/")) {
32703
33233
  assertExternalEffectCurrent();
32704
33234
  const res2 = await sock.sendMessage(jid, { image: { url: attachment.path }, caption: message });
@@ -32727,8 +33257,8 @@ ${r}` : r;
32727
33257
  this.recordEcho(res2);
32728
33258
  return;
32729
33259
  }
32730
- const tmpDir = path30.join(this.stateDir, "whatsapp-media-tmp");
32731
- const dst = path30.join(tmpDir, `${randomUUID17()}.ogg`);
33260
+ const tmpDir = path31.join(this.stateDir, "whatsapp-media-tmp");
33261
+ const dst = path31.join(tmpDir, `${randomUUID17()}.ogg`);
32732
33262
  try {
32733
33263
  await (this.cfg.ffmpegTranscode ?? defaultFfmpegTranscode)(attachment.path, dst);
32734
33264
  assertExternalEffectCurrent();
@@ -32843,9 +33373,9 @@ function quotedTextOf(content) {
32843
33373
  }
32844
33374
 
32845
33375
  // src/channels/dingtalk.ts
32846
- import fs23 from "node:fs";
32847
- import path31 from "node:path";
32848
- import { createHash as createHash33, randomUUID as randomUUID18 } from "node:crypto";
33376
+ import fs24 from "node:fs";
33377
+ import path32 from "node:path";
33378
+ import { createHash as createHash34, randomUUID as randomUUID18 } from "node:crypto";
32849
33379
 
32850
33380
  // src/channels/dingtalk-stream.ts
32851
33381
  import { EventEmitter } from "node:events";
@@ -33317,11 +33847,10 @@ var DingTalkAdapter = class _DingTalkAdapter {
33317
33847
  throw new Error("dingtalk clientId/clientSecret \u672A\u914D\u7F6E\uFF08\u5F00\u53D1\u8005\u540E\u53F0 \u2192 \u5E94\u7528 \u2192 \u51ED\u8BC1\uFF09");
33318
33848
  }
33319
33849
  if (this.cfg.proxy) {
33320
- const { getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_withRetry(), withRetry_exports));
33850
+ const { createProxySocketAgent: createProxySocketAgent2, getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_adaptive_proxy(), adaptive_proxy_exports));
33321
33851
  const dispatcher = getProxyDispatcher2(this.cfg.proxy);
33322
33852
  this.baseFetch = (url, init) => this.fetchImpl(url, { ...init, dispatcher });
33323
- const { HttpsProxyAgent: HttpsProxyAgent3 } = await import("https-proxy-agent");
33324
- this.wsAgent = new HttpsProxyAgent3(this.cfg.proxy);
33853
+ this.wsAgent = createProxySocketAgent2(this.cfg.proxy);
33325
33854
  this.token = new DingTalkTokenManager(this.cfg.clientId, this.cfg.clientSecret, (u, i) => this.baseFetch(u, i), this.now);
33326
33855
  console.log(`[dingtalk] outbound via proxy ${this.cfg.proxy}`);
33327
33856
  }
@@ -33438,13 +33967,13 @@ var DingTalkAdapter = class _DingTalkAdapter {
33438
33967
  const res = await this.baseFetch(url, { signal: AbortSignal.timeout(3e4) });
33439
33968
  if (!res.ok) throw new Error(`media download HTTP ${res.status}`);
33440
33969
  const buf = Buffer.from(await res.arrayBuffer());
33441
- const dir = path31.join(this.cfg.stateDir, "media", "dingtalk");
33442
- fs23.mkdirSync(dir, { recursive: true });
33970
+ const dir = path32.join(this.cfg.stateDir, "media", "dingtalk");
33971
+ fs24.mkdirSync(dir, { recursive: true });
33443
33972
  const ext = m.kind === "image" ? "png" : m.kind === "video" ? "mp4" : "bin";
33444
- const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash33("sha1").update(m.code).digest("hex").slice(0, 12);
33973
+ const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash34("sha1").update(m.code).digest("hex").slice(0, 12);
33445
33974
  const safeCode = raw.replace(/[^a-zA-Z0-9_-]/g, "_");
33446
- const local = path31.join(dir, `${safeCode}.${ext}`);
33447
- fs23.writeFileSync(local, buf);
33975
+ const local = path32.join(dir, `${safeCode}.${ext}`);
33976
+ fs24.writeFileSync(local, buf);
33448
33977
  out.push({
33449
33978
  url: `file://${local}`,
33450
33979
  filename: m.filename ?? `${safeCode}.${ext}`,
@@ -33517,8 +34046,8 @@ var DingTalkAdapter = class _DingTalkAdapter {
33517
34046
  async sendFileNow(target, message, attachment) {
33518
34047
  const entry = this.registry.get(target);
33519
34048
  const robotCode = this.cfg.robotCode ?? this.cfg.clientId;
33520
- const buf = fs23.readFileSync(attachment.path);
33521
- const filename = (attachment.filename ?? path31.basename(attachment.path)).slice(0, 100);
34049
+ const buf = fs24.readFileSync(attachment.path);
34050
+ const filename = (attachment.filename ?? path32.basename(attachment.path)).slice(0, 100);
33522
34051
  const isImage = (attachment.mimeType ?? "").startsWith("image/") || /\.(png|jpe?g|gif|webp|bmp)$/i.test(filename);
33523
34052
  const mediaId = await this.uploadMedia(buf, filename, isImage ? "image" : "file");
33524
34053
  const msgKey = isImage ? "sampleImageMsg" : "sampleFileMsg";
@@ -33882,8 +34411,8 @@ var DING_EDIT_INTERVAL_MS = 300;
33882
34411
 
33883
34412
  // src/channels/wecom-stream.ts
33884
34413
  import { EventEmitter as EventEmitter2 } from "node:events";
33885
- import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
33886
- import { createHash as createHash34 } from "node:crypto";
34414
+ import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
34415
+ import { createHash as createHash35 } from "node:crypto";
33887
34416
  var WECOM_WS_URL = "wss://openws.work.weixin.qq.com";
33888
34417
  var HEARTBEAT_MS2 = 3e4;
33889
34418
  var ACK_TIMEOUT_MS = 15e3;
@@ -34208,7 +34737,7 @@ var WecomStreamClient = class extends EventEmitter2 {
34208
34737
  const item = {
34209
34738
  frame,
34210
34739
  // The ack event which pumps this queue has another async context. Keep the sender's guards.
34211
- send: AsyncLocalStorage8.bind((ws) => {
34740
+ send: AsyncLocalStorage9.bind((ws) => {
34212
34741
  assertExternalEffectCurrent();
34213
34742
  ws.send(JSON.stringify(frame));
34214
34743
  }),
@@ -34235,7 +34764,7 @@ var WecomStreamClient = class extends EventEmitter2 {
34235
34764
  if (!data.length) throw new Error("wecom uploadMedia: empty buffer");
34236
34765
  const totalChunks = Math.ceil(data.length / UPLOAD_CHUNK_BYTES);
34237
34766
  if (totalChunks > MAX_UPLOAD_CHUNKS) throw new Error(`wecom uploadMedia: too large (${totalChunks} chunks > ${MAX_UPLOAD_CHUNKS})`);
34238
- const md5 = createHash34("md5").update(data).digest("hex");
34767
+ const md5 = createHash35("md5").update(data).digest("hex");
34239
34768
  const initRes = await this.sendCommand("aibot_upload_media_init", {
34240
34769
  type,
34241
34770
  filename,
@@ -34263,8 +34792,8 @@ var WecomStreamClient = class extends EventEmitter2 {
34263
34792
  // src/channels/wecom.ts
34264
34793
  import { createDecipheriv as createDecipheriv3, randomUUID as randomUUID19 } from "node:crypto";
34265
34794
  import { readFileSync as readFileSync17 } from "node:fs";
34266
- import { mkdir as mkdir3, readFile, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
34267
- import path32 from "node:path";
34795
+ import { mkdir as mkdir4, readFile, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
34796
+ import path33 from "node:path";
34268
34797
  var WECOM_CONTENT_BYTES = 20480;
34269
34798
  var DEFAULT_MERGE_WINDOW_MS = 600;
34270
34799
  var REPLY_WINDOW_MS = 24 * 60 * 60 * 1e3;
@@ -34450,7 +34979,7 @@ var WecomAdapter = class {
34450
34979
  this.now = cfg.now ?? Date.now;
34451
34980
  this.sleepImpl = cfg.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
34452
34981
  this.fetchImpl = cfg.fetchImpl ?? fetch;
34453
- this.routesFile = path32.join(cfg.stateDir, "state", ROUTES_FILE);
34982
+ this.routesFile = path33.join(cfg.stateDir, "state", ROUTES_FILE);
34454
34983
  }
34455
34984
  /**
34456
34985
  * 载入落盘会话路由(1007:真机事故——注册表原本只存内存,引擎一重启"谁跟我说过话"全丢,
@@ -34494,7 +35023,7 @@ var WecomAdapter = class {
34494
35023
  try {
34495
35024
  const routes = {};
34496
35025
  for (const [chatId, e] of this.registry) routes[chatId] = { chatType: e.chatType, userId: e.userId };
34497
- await mkdir3(path32.dirname(this.routesFile), { recursive: true });
35026
+ await mkdir4(path33.dirname(this.routesFile), { recursive: true });
34498
35027
  await writeFile4(this.routesFile, JSON.stringify({ version: 1, routes }, null, 2) + "\n", "utf8");
34499
35028
  } catch (e) {
34500
35029
  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}`);
@@ -34518,12 +35047,11 @@ var WecomAdapter = class {
34518
35047
  this.loadRoutes();
34519
35048
  let wsAgent;
34520
35049
  if (this.cfg.proxy) {
34521
- const { getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_withRetry(), withRetry_exports));
35050
+ const { createProxySocketAgent: createProxySocketAgent2, getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_adaptive_proxy(), adaptive_proxy_exports));
34522
35051
  const dispatcher = getProxyDispatcher2(this.cfg.proxy);
34523
35052
  const base = this.fetchImpl;
34524
35053
  this.fetchImpl = (url, init) => base(url, { ...init, dispatcher });
34525
- const { HttpsProxyAgent: HttpsProxyAgent3 } = await import("https-proxy-agent");
34526
- wsAgent = new HttpsProxyAgent3(this.cfg.proxy);
35054
+ wsAgent = createProxySocketAgent2(this.cfg.proxy);
34527
35055
  }
34528
35056
  let wsCtor = this.cfg.wsCtor;
34529
35057
  if (!wsCtor) {
@@ -34781,19 +35309,19 @@ ${parsed.inbound.content}`;
34781
35309
  /** 入站媒体:下载 → aeskey 解密 → 落盘 → 附件(单条失败不拖垮整条消息;全部失败给 content 加标记)。
34782
35310
  * 本地文件名一律由 msgid 派生(远端 filename 只做显示名)——防同名互相覆盖/超长(钉钉 1004 同款纪律)。 */
34783
35311
  async resolveInboundMedia(parsed) {
34784
- const dir = path32.join(this.cfg.stateDir, "media", "wecom");
35312
+ const dir = path33.join(this.cfg.stateDir, "media", "wecom");
34785
35313
  const attachments = [];
34786
35314
  let failed = 0;
34787
35315
  for (const [i, ref] of parsed.media.entries()) {
34788
35316
  try {
34789
- await mkdir3(dir, { recursive: true });
35317
+ await mkdir4(dir, { recursive: true });
34790
35318
  const res = await this.fetchImpl(ref.url, { signal: AbortSignal.timeout(3e4) });
34791
35319
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
34792
35320
  const raw = Buffer.from(await res.arrayBuffer());
34793
35321
  const data = ref.aeskey ? decryptWecomMedia(raw, ref.aeskey) : raw;
34794
35322
  const ext = ref.filename?.includes(".") ? ref.filename.split(".").pop().toLowerCase().slice(0, 8) : ref.kind === "image" ? "jpg" : ref.kind === "video" ? "mp4" : "bin";
34795
35323
  const localName = `wecom-${(parsed.msgId || String(this.now())).replace(/[^0-9A-Za-z_-]/g, "").slice(0, 32)}-${i}.${ext}`;
34796
- const file2 = path32.join(dir, localName);
35324
+ const file2 = path33.join(dir, localName);
34797
35325
  await writeFile4(file2, data);
34798
35326
  const displayName = (ref.filename || localName).slice(0, 120);
34799
35327
  attachments.push({
@@ -34824,7 +35352,7 @@ ${parsed.inbound.content}`;
34824
35352
  const entry = this.registry.get(target);
34825
35353
  if (!entry) throw new Error(`[wecom] \u65E0\u6CD5\u8DEF\u7531\u5A92\u4F53\u5230 ${target}\uFF08\u65E0\u4F1A\u8BDD\u6CE8\u518C\u8BB0\u5F55\uFF09`);
34826
35354
  await this.takeToken(target, false);
34827
- const filename = attachment.filename ?? path32.basename(attachment.path);
35355
+ const filename = attachment.filename ?? path33.basename(attachment.path);
34828
35356
  const { mediaId } = await this.requireStream().uploadMedia(data, type, filename);
34829
35357
  const body = type === "video" ? { msgtype: "video", video: { media_id: mediaId, title: filename } } : { msgtype: type, [type]: { media_id: mediaId } };
34830
35358
  await this.respondOrSend(entry, target, body);
@@ -35158,7 +35686,7 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
35158
35686
  // src/continuity/gateway-feishu.ts
35159
35687
  init_gateway_media();
35160
35688
  import * as lark2 from "@larksuiteoapi/node-sdk";
35161
- import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
35689
+ import { AsyncLocalStorage as AsyncLocalStorage10 } from "node:async_hooks";
35162
35690
  import { basename as basename6 } from "node:path";
35163
35691
 
35164
35692
  // src/continuity/gateway-feishu-render.ts
@@ -35191,7 +35719,7 @@ var quiet = { error: () => {
35191
35719
  }, debug: () => {
35192
35720
  }, trace: () => {
35193
35721
  } };
35194
- var dispatchContext = new AsyncLocalStorage9();
35722
+ var dispatchContext = new AsyncLocalStorage10();
35195
35723
  var format = "engine7-feishu-gateway-inbound-v1";
35196
35724
  function createFeishuGatewayDispatcher(options) {
35197
35725
  return new lark2.EventDispatcher({ verificationToken: options.verificationToken, encryptKey: options.encryptKey, logger: quiet }).register({
@@ -35377,9 +35905,9 @@ import { basename as basename7 } from "node:path";
35377
35905
  function createRemoteTravelChannel(block, stateDir, channel = "feishu") {
35378
35906
  if (!stateDir || !runtimeAuthorityFor(stateDir)) throw new Error("TRAVEL_GATEWAY_RUNTIME_REQUIRED");
35379
35907
  validateTravelChannels(stateDir, { [channel]: block });
35380
- const tls2 = block.gatewayTls;
35381
- if (!tls2 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls2[key4] !== "string" || !tls2[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35382
- const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls2.caFile, 1024 * 1024), cert: readPrivateFile(tls2.certFile, 1024 * 1024), key: readPrivateFile(tls2.keyFile, 16384) });
35908
+ const tls3 = block.gatewayTls;
35909
+ if (!tls3 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls3[key4] !== "string" || !tls3[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35910
+ const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls3.caFile, 1024 * 1024), cert: readPrivateFile(tls3.certFile, 1024 * 1024), key: readPrivateFile(tls3.keyFile, 16384) });
35383
35911
  return new RemoteTravelChannel({ client, channel, permit: () => runtimeAuthorityFor(stateDir).assert("INPUT"), pollIntervalMs: block.gatewayPollIntervalMs });
35384
35912
  }
35385
35913
  var RemoteTravelChannel = class {
@@ -35569,9 +36097,9 @@ var RemoteTravelChannel = class {
35569
36097
  };
35570
36098
 
35571
36099
  // src/channels/private-library.ts
35572
- import fs24 from "node:fs/promises";
35573
- import path33 from "node:path";
35574
- import { createHash as createHash35 } from "node:crypto";
36100
+ import fs25 from "node:fs/promises";
36101
+ import path34 from "node:path";
36102
+ import { createHash as createHash36 } from "node:crypto";
35575
36103
 
35576
36104
  // src/channels/chan7-content.ts
35577
36105
  function fileMime(name) {
@@ -35583,8 +36111,8 @@ function fileMime(name) {
35583
36111
  function archive(manager, name, mime, bytes2, role, caption, identity) {
35584
36112
  const adapter = manager.getAdapter("chan7");
35585
36113
  if (!adapter?.files || bytes2.length > 16 * 1024 * 1024) return;
35586
- const safeName = path33.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
35587
- const key4 = createHash35("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
36114
+ const safeName = path34.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
36115
+ const key4 = createHash36("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
35588
36116
  try {
35589
36117
  adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key4);
35590
36118
  } catch (e) {
@@ -35594,9 +36122,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
35594
36122
  async function archivePrivateOutbound(manager, channel, target, text2, attachment, origin) {
35595
36123
  if (channel === "chan7" || origin?.channelType !== "dm" || origin.inboundIsBot || origin.channel !== channel || origin.channelTarget !== target || !manager.getAdapter("chan7")?.files) return;
35596
36124
  try {
35597
- const stat3 = await fs24.stat(attachment.path);
36125
+ const stat3 = await fs25.stat(attachment.path);
35598
36126
  if (!stat3.isFile() || stat3.size > 16 * 1024 * 1024) return;
35599
- const bytes2 = await fs24.readFile(attachment.path), name = attachment.filename ?? path33.basename(attachment.path);
36127
+ const bytes2 = await fs25.readFile(attachment.path), name = attachment.filename ?? path34.basename(attachment.path);
35600
36128
  archive(
35601
36129
  manager,
35602
36130
  name,
@@ -35794,6 +36322,16 @@ var ChannelManager = class {
35794
36322
  this.adapters.push(adapter);
35795
36323
  console.log(`[channels] Adapter registered: ${adapter.name}`);
35796
36324
  }
36325
+ /**
36326
+ * 当前可上报的聊天通道:只取 config 管起来、且建成了的那批(热加载后跟着变)。
36327
+ *
36328
+ * registerAdapter 注进来的不算——chan7 / console 终端是引擎自己的输入输出面,
36329
+ * 不是「用户拿什么聊」;取全部 adapters 的话每台新引擎至少会报 {"chan7":0,"console":0}。
36330
+ * 口径是「已启用」而不是「已连上」:connect 失败的通道也在这里(显示 0 条),装机列表列头有说明。
36331
+ */
36332
+ channelNames() {
36333
+ return [...this.managed.keys()];
36334
+ }
35797
36335
  /** 注册全局消息过滤器(所有通道生效) */
35798
36336
  addFilter(filter) {
35799
36337
  this.filters.push(filter);
@@ -35966,8 +36504,8 @@ var ChannelManager = class {
35966
36504
  /** 停止所有 adapter */
35967
36505
  async stopAll() {
35968
36506
  const results = await Promise.allSettled(this.adapters.map(async (adapter) => adapter.disconnect()));
35969
- const errors2 = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
35970
- if (errors2.length) throw new AggregateError(errors2, "CHANNEL_STOP_FAILED");
36507
+ const errors3 = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
36508
+ if (errors3.length) throw new AggregateError(errors3, "CHANNEL_STOP_FAILED");
35971
36509
  }
35972
36510
  /** 通道是否有已注册 adapter(投递前置判断用;1105 inbox-poller route 白名单替代硬编码) */
35973
36511
  hasChannel(channelName) {
@@ -36037,11 +36575,11 @@ var ChannelManager = class {
36037
36575
  }
36038
36576
  // === Streaming preview — 对齐 cc-connect 的 PreviewStarter/MessageUpdater/PreviewCleaner ===
36039
36577
  /** 发送初始 preview 消息 */
36040
- async sendPreview(channelName, channelId, content, agentName) {
36578
+ async sendPreview(channelName, channelId, content, agentName, presentation) {
36041
36579
  const adapter = this.adapters.find((a) => a.name === channelName);
36042
36580
  if (!adapter?.sendPreview) return null;
36043
36581
  if (hasMemoryEffectContext() && (!adapter.memoryGuardedSends || hasAutomaticMemoryEffectContext() && adapter.memoryGuardedAutomation === false)) throw new Error(`MEMORY_EXECUTION_BLOCKED: adapter ${channelName} has no final send guard`);
36044
- return guardedExternalEffect(() => adapter.sendPreview(channelId, content, agentName));
36582
+ return guardedExternalEffect(() => adapter.sendPreview(channelId, content, agentName, presentation));
36045
36583
  }
36046
36584
  /** 编辑已有的 preview 消息 */
36047
36585
  async editPreview(channelName, handle, content, agentName, isFinal) {
@@ -36076,12 +36614,12 @@ var quiet2 = { error: () => {
36076
36614
  }, debug: () => {
36077
36615
  }, trace: () => {
36078
36616
  } };
36079
- function path34(value) {
36617
+ function path35(value) {
36080
36618
  if (typeof value !== "string" || !isAbsolute5(value)) throw new Error("TRAVEL_GATEWAY_ABSOLUTE_PATH_REQUIRED");
36081
36619
  return resolve11(value);
36082
36620
  }
36083
- function tls(config) {
36084
- return { ca: readPrivateFile(path34(config?.caFile), 1024 * 1024), cert: readPrivateFile(path34(config?.certFile), 1024 * 1024), key: readPrivateFile(path34(config?.keyFile), 16384) };
36621
+ function tls2(config) {
36622
+ return { ca: readPrivateFile(path35(config?.caFile), 1024 * 1024), cert: readPrivateFile(path35(config?.certFile), 1024 * 1024), key: readPrivateFile(path35(config?.keyFile), 16384) };
36085
36623
  }
36086
36624
  async function startTravelGateway(config) {
36087
36625
  if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key4) => config.identity[key4] !== config.keyService.identity[key4])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
@@ -36089,9 +36627,9 @@ async function startTravelGateway(config) {
36089
36627
  for (const [name, value] of Object.entries(config.channels ?? {})) if (value?.enabled && !["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
36090
36628
  const feishuIngress = config.ingressEnabled !== false && config.feishu?.ingressEnabled !== false && config.channels?.feishu?.enabled !== false;
36091
36629
  if (feishuIngress && !/^cli_[0-9a-fA-F]{16}$/.test(config.feishu?.appId)) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
36092
- const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls(config.keyService.tls), timeoutMs: 1e4 };
36630
+ const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls2(config.keyService.tls), timeoutMs: 1e4 };
36093
36631
  const material = await fetchTravelKey(keyConfig);
36094
- const keyDigest = createHash36("sha256").update(material.key).digest("hex");
36632
+ const keyDigest = createHash37("sha256").update(material.key).digest("hex");
36095
36633
  let keyWatermark = material.deletionWatermark;
36096
36634
  const refreshInterval = config.keyRefreshIntervalMs ?? 1e4, maxKeyAge = config.keyMaxAgeMs ?? 3e4;
36097
36635
  if (!Number.isSafeInteger(refreshInterval) || refreshInterval < 100 || refreshInterval > 1e4 || !Number.isSafeInteger(maxKeyAge) || maxKeyAge < 2 * refreshInterval || maxKeyAge > 3e4) {
@@ -36132,18 +36670,18 @@ async function startTravelGateway(config) {
36132
36670
  }
36133
36671
  };
36134
36672
  try {
36135
- objects = await PublicationObjects.open({ directory: path34(config.objectsDir), identity: config.identity, key: material.key });
36136
- authority = new TravelAuthority({ directory: path34(config.authorityDir), leaseMs: config.leaseMs });
36673
+ objects = await PublicationObjects.open({ directory: path35(config.objectsDir), identity: config.identity, key: material.key });
36674
+ authority = new TravelAuthority({ directory: path35(config.authorityDir), leaseMs: config.leaseMs });
36137
36675
  if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
36138
36676
  for (const credential of Object.values(config.allowedPeers)) {
36139
36677
  const principal = authority.authenticate(String(credential));
36140
36678
  if (["tenantId", "companionId", "seatId"].some((key4) => principal[key4] !== config.identity[key4]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36141
36679
  }
36142
- store = new TravelGatewayStore({ directory: path34(config.gatewayDir), identity: config.identity, objects, authority });
36680
+ store = new TravelGatewayStore({ directory: path35(config.gatewayDir), identity: config.identity, objects, authority });
36143
36681
  await store.migrateStoredInputs();
36144
36682
  if (config.previouslyProcessedPlatformIds) store.importProcessedInputs(config.previouslyProcessedPlatformIds);
36145
36683
  platform = createFeishuGatewayPlatform(config.feishu);
36146
- server = createTravelGatewayServer({ ...tls(config.tls), store, authority, allowedPeers: config.allowedPeers, recoveryPeers: config.recoveryPeers, assertReady: assertKey, platform: { deliver: async (effect, body, assertCurrent) => {
36684
+ server = createTravelGatewayServer({ ...tls2(config.tls), store, authority, allowedPeers: config.allowedPeers, recoveryPeers: config.recoveryPeers, assertReady: assertKey, platform: { deliver: async (effect, body, assertCurrent) => {
36147
36685
  const packet = effect.kind === "MEDIA" ? (await Promise.resolve().then(() => (init_gateway_media(), gateway_media_exports))).decodeGatewayMedia(body).metadata : JSON.parse(body.toString());
36148
36686
  const channel = packet.channel ?? "feishu";
36149
36687
  if (channel === "feishu") return platform.deliver(effect, body, () => {
@@ -36164,7 +36702,7 @@ async function startTravelGateway(config) {
36164
36702
  if (config.control) {
36165
36703
  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");
36166
36704
  controlServer = createTravelAuthorityServer({
36167
- ...tls(config.control.tls ?? config.tls),
36705
+ ...tls2(config.control.tls ?? config.tls),
36168
36706
  authority,
36169
36707
  proxyFingerprints: config.control.proxyFingerprints,
36170
36708
  allowedPeers: config.control.allowedPeers,
@@ -36193,7 +36731,7 @@ async function startTravelGateway(config) {
36193
36731
  }
36194
36732
  });
36195
36733
  if (config.channels && config.ingressEnabled !== false) {
36196
- adapters.setFactoryContext({ stateDir: path34(config.platformStateDir) });
36734
+ adapters.setFactoryContext({ stateDir: path35(config.platformStateDir) });
36197
36735
  adapters.loadFromConfig(Object.fromEntries(Object.entries(config.channels).filter(([name, value]) => name !== "feishu" && value.enabled)));
36198
36736
  for (const channel of ["discord", "wechat"]) {
36199
36737
  const adapter = adapters.getAdapter(channel);
@@ -36256,7 +36794,7 @@ async function startTravelGateway(config) {
36256
36794
  checking = true;
36257
36795
  void fetchTravelKey(keyConfig).then((current2) => {
36258
36796
  try {
36259
- if (!objects || createHash36("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
36797
+ if (!objects || createHash37("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
36260
36798
  keyWatermark = current2.deletionWatermark;
36261
36799
  lastKeyCheck = Number(process.hrtime.bigint() / 1000000n);
36262
36800
  } finally {
@@ -36279,7 +36817,7 @@ async function startTravelGateway(config) {
36279
36817
  async function runTravelGatewayCli(args) {
36280
36818
  if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-gateway serve --config /absolute/private-config.json" };
36281
36819
  if (args.length !== 3 || args[0] !== "serve" || args[1] !== "--config") throw new Error("TRAVEL_GATEWAY_INVALID_COMMAND");
36282
- const config = JSON.parse(readPrivateFile(path34(args[2]), 65536).toString());
36820
+ const config = JSON.parse(readPrivateFile(path35(args[2]), 65536).toString());
36283
36821
  const gateway = await startTravelGateway(config);
36284
36822
  let closing = false;
36285
36823
  const stop = () => {