engine7 7.1.151 → 7.1.153

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(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()))
48
+ function assertPrivateDirectory(path37) {
49
+ const info = lstatSync(path37);
50
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path37) !== resolve(path37) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
51
51
  throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
52
52
  }
53
- function syncDir(path36) {
53
+ function syncDir(path37) {
54
54
  if (process.platform === "win32") return;
55
- const fd = openSync(path36, constants.O_RDONLY);
55
+ const fd = openSync(path37, constants.O_RDONLY);
56
56
  try {
57
57
  fsyncSync(fd);
58
58
  } finally {
59
59
  closeSync(fd);
60
60
  }
61
61
  }
62
- function preparePrivateDirectory(path36) {
62
+ function preparePrivateDirectory(path37) {
63
63
  const missing = [];
64
- let parent = resolve(path36);
64
+ let parent = resolve(path37);
65
65
  for (; ; ) {
66
66
  try {
67
67
  lstatSync(parent);
@@ -82,10 +82,10 @@ function preparePrivateDirectory(path36) {
82
82
  assertPrivateDirectory(directory2);
83
83
  syncDir(dirname(directory2));
84
84
  }
85
- assertPrivateDirectory(path36);
85
+ assertPrivateDirectory(path37);
86
86
  }
87
- function preparePrivateDatabase(path36) {
88
- for (const file2 of [path36, path36 + "-journal", path36 + "-wal", path36 + "-shm"]) {
87
+ function preparePrivateDatabase(path37) {
88
+ for (const file2 of [path37, path37 + "-journal", path37 + "-wal", path37 + "-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(path36) {
95
95
  }
96
96
  }
97
97
  try {
98
- const fd = openSync(path36, "wx", 384);
98
+ const fd = openSync(path37, "wx", 384);
99
99
  closeSync(fd);
100
100
  } catch (error) {
101
101
  if (error.code !== "EEXIST") throw error;
102
102
  }
103
- const info = lstatSync(path36);
103
+ const info = lstatSync(path37);
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(path36));
106
+ syncDir(dirname(path37));
107
107
  }
108
- async function syncDirAsync(path36) {
108
+ async function syncDirAsync(path37) {
109
109
  if (process.platform === "win32") return;
110
- const fd = await open(path36, constants.O_RDONLY);
110
+ const fd = await open(path37, 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(path36, body, deferDirectorySync = false) {
118
- const temp = join(dirname(path36), "." + randomUUID() + ".partial");
117
+ async function exclusivePublish(path37, body, deferDirectorySync = false) {
118
+ const temp = join(dirname(path37), "." + randomUUID() + ".partial");
119
119
  try {
120
120
  await writeFile(temp, body, { flag: "wx", mode: 384, flush: true });
121
- await link(temp, path36);
122
- if (!deferDirectorySync) await syncDirAsync(dirname(path36));
121
+ await link(temp, path37);
122
+ if (!deferDirectorySync) await syncDirAsync(dirname(path37));
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 path36 = join(this.directory, "chunks", ref.sha256);
342
- const file2 = await open(path36, constants.O_RDONLY | noFollow);
341
+ const path37 = join(this.directory, "chunks", ref.sha256);
342
+ const file2 = await open(path37, 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 }), 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");
464
+ const after = fstatSync(fd, { bigint: true }), path37 = lstatSync(source, { bigint: true });
465
+ if (path37.isSymbolicLink() || [after, path37].some((s) => ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((k) => s[k] !== before[k])) || BigInt(bytes2) !== before.size) throw new Error("PUBLICATION_SOURCE_CHANGED");
466
466
  return { bytes: bytes2, sha256: digest7.digest("hex"), chunks };
467
467
  } finally {
468
468
  closeSync(fd);
@@ -555,17 +555,17 @@ function assertPrivateStat(stat3, directory2) {
555
555
  if ((directory2 ? !stat3.isDirectory() : !stat3.isFile()) || process.platform !== "win32" && ((stat3.mode & 63) !== 0 || stat3.uid !== process.getuid?.()))
556
556
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
557
557
  }
558
- function privateDirectory(path36) {
558
+ function privateDirectory(path37) {
559
559
  try {
560
- mkdirSync2(path36, { mode: 448 });
560
+ mkdirSync2(path37, { mode: 448 });
561
561
  } catch (error) {
562
562
  if (error.code !== "EEXIST") throw error;
563
563
  }
564
- assertPrivateStat(lstatSync2(path36), true);
564
+ assertPrivateStat(lstatSync2(path37), true);
565
565
  }
566
- function readPrivateFile(path36, maximumBytes = 65536) {
567
- assertPrivateStat(lstatSync2(path36), false);
568
- const fd = openSync2(path36, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
566
+ function readPrivateFile(path37, maximumBytes = 65536) {
567
+ assertPrivateStat(lstatSync2(path37), false);
568
+ const fd = openSync2(path37, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
569
569
  try {
570
570
  const stat3 = fstatSync2(fd);
571
571
  assertPrivateStat(stat3, false);
@@ -585,21 +585,21 @@ var init_key_service_store = __esm({
585
585
  privateDirectory(directory2);
586
586
  this.secrets = join2(directory2, "secrets");
587
587
  privateDirectory(this.secrets);
588
- const path36 = join2(directory2, "control.sqlite");
588
+ const path37 = join2(directory2, "control.sqlite");
589
589
  try {
590
- closeSync2(openSync2(path36, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384));
590
+ closeSync2(openSync2(path37, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384));
591
591
  } catch (error) {
592
592
  if (error.code !== "EEXIST") throw error;
593
593
  }
594
- assertPrivateStat(lstatSync2(path36), false);
594
+ assertPrivateStat(lstatSync2(path37), false);
595
595
  for (const suffix of ["-wal", "-shm", "-journal"]) {
596
596
  try {
597
- assertPrivateStat(lstatSync2(path36 + suffix), false);
597
+ assertPrivateStat(lstatSync2(path37 + suffix), false);
598
598
  } catch (error) {
599
599
  if (error.code !== "ENOENT") throw error;
600
600
  }
601
601
  }
602
- this.db = new DatabaseSync2(path36);
602
+ this.db = new DatabaseSync2(path37);
603
603
  try {
604
604
  this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
605
605
  CREATE TABLE IF NOT EXISTS seat_keys (
@@ -633,16 +633,16 @@ var init_key_service_store = __esm({
633
633
  this.transaction(() => {
634
634
  if (this.db.prepare("SELECT key_id FROM seat_keys WHERE key_id=?").get(identity.keyId))
635
635
  throw new Error("KEY_SERVICE_KEY_EXISTS");
636
- const filename = `${randomUUID2()}.key`, path36 = join2(this.secrets, filename);
636
+ const filename = `${randomUUID2()}.key`, path37 = join2(this.secrets, filename);
637
637
  assertPrivateStat(lstatSync2(this.secrets), true);
638
- const fd = openSync2(path36, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384);
638
+ const fd = openSync2(path37, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384);
639
639
  try {
640
640
  let written = 0;
641
641
  while (written < key4.byteLength) written += writeSync(fd, key4, written, key4.byteLength - written);
642
642
  fsyncSync2(fd);
643
643
  } catch (error) {
644
644
  closeSync2(fd);
645
- unlinkSync(path36);
645
+ unlinkSync(path37);
646
646
  throw error;
647
647
  }
648
648
  closeSync2(fd);
@@ -657,7 +657,7 @@ var init_key_service_store = __esm({
657
657
  try {
658
658
  this.db.prepare("INSERT INTO seat_keys(key_id,identity,secret_file,state) VALUES(?,?,?,'active')").run(identity.keyId, text2, filename);
659
659
  } catch (error) {
660
- unlinkSync(path36);
660
+ unlinkSync(path37);
661
661
  throw error;
662
662
  }
663
663
  });
@@ -770,14 +770,14 @@ var init_key_service_store = __esm({
770
770
  import { randomUUID as randomUUID4, verify as verify2 } from "node:crypto";
771
771
  import { constants as constants3, closeSync as closeSync3, existsSync as existsSync2, fstatSync as fstatSync3, fsyncSync as fsyncSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
772
772
  import { basename, dirname as dirname2, join as join5, resolve as resolve3 } from "node:path";
773
- function assertPrivateDirectory2(path36) {
774
- const stat3 = lstatSync3(path36);
773
+ function assertPrivateDirectory2(path37) {
774
+ const stat3 = lstatSync3(path37);
775
775
  if (!stat3.isDirectory() || stat3.isSymbolicLink() || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
776
776
  }
777
- function readPrivateFile2(path36, maximum) {
778
- const before = lstatSync3(path36);
777
+ function readPrivateFile2(path37, maximum) {
778
+ const before = lstatSync3(path37);
779
779
  if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
780
- const fd = openSync3(path36, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
780
+ const fd = openSync3(path37, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
781
781
  try {
782
782
  if (fstatSync3(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
783
783
  return readFileSync2(fd);
@@ -785,12 +785,12 @@ function readPrivateFile2(path36, maximum) {
785
785
  closeSync3(fd);
786
786
  }
787
787
  }
788
- function writeControl(path36, value) {
789
- const temporary = path36 + "." + randomUUID4() + ".tmp";
788
+ function writeControl(path37, value) {
789
+ const temporary = path37 + "." + randomUUID4() + ".tmp";
790
790
  writeFileSync2(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
791
- renameSync(temporary, path36);
791
+ renameSync(temporary, path37);
792
792
  if (process.platform !== "win32") {
793
- const fd = openSync3(dirname2(path36), "r");
793
+ const fd = openSync3(dirname2(path37), "r");
794
794
  try {
795
795
  fsyncSync3(fd);
796
796
  } finally {
@@ -1815,7 +1815,29 @@ function tokenize(text2) {
1815
1815
  function tokenizeToField(text2) {
1816
1816
  return tokenize(text2).join(" ");
1817
1817
  }
1818
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1818
+ function cjkBigrams(text2) {
1819
+ const out = [];
1820
+ for (const seg of String(text2 ?? "").match(/[\u4e00-\u9fff]{2,}/g) ?? []) {
1821
+ for (let i = 0; i + 1 < seg.length; i++) out.push(seg.slice(i, i + 2));
1822
+ }
1823
+ return out;
1824
+ }
1825
+ function invisibleCjkNeedles(candidates2) {
1826
+ return [...new Set(candidates2.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
1827
+ }
1828
+ function literalQueryNeedles(text2) {
1829
+ const chars = shortCjkCharCount(text2);
1830
+ if (!chars || chars > 6) return null;
1831
+ const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
1832
+ return names.length ? names : queryBigramNeedles(text2);
1833
+ }
1834
+ function queryBigramNeedles(text2) {
1835
+ const chars = shortCjkCharCount(text2);
1836
+ if (!chars || chars > 6) return null;
1837
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
1838
+ return grams.length ? grams : null;
1839
+ }
1840
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
1819
1841
  var init_tokenizer = __esm({
1820
1842
  "src/mem7/core/tokenizer.ts"() {
1821
1843
  "use strict";
@@ -1888,6 +1910,7 @@ var init_tokenizer = __esm({
1888
1910
  ]);
1889
1911
  MIN_TOKEN_LENGTH = 2;
1890
1912
  jieba = null;
1913
+ shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
1891
1914
  }
1892
1915
  });
1893
1916
 
@@ -2101,14 +2124,14 @@ var init_live = __esm({
2101
2124
  }
2102
2125
  /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
2103
2126
  async persistToFile(dotPath, val, atomic = false) {
2104
- const fs26 = await import("node:fs");
2127
+ const fs27 = await import("node:fs");
2105
2128
  const cfgPath = this.current?._configFilePath;
2106
- if (!cfgPath || !fs26.existsSync(cfgPath)) {
2129
+ if (!cfgPath || !fs27.existsSync(cfgPath)) {
2107
2130
  console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
2108
2131
  return false;
2109
2132
  }
2110
2133
  try {
2111
- const raw = JSON.parse(fs26.readFileSync(cfgPath, "utf-8"));
2134
+ const raw = JSON.parse(fs27.readFileSync(cfgPath, "utf-8"));
2112
2135
  const keys = dotPath.split(".");
2113
2136
  let o = raw;
2114
2137
  for (let i = 0; i < keys.length - 1; i++) {
@@ -2118,7 +2141,7 @@ var init_live = __esm({
2118
2141
  o[keys[keys.length - 1]] = val;
2119
2142
  if (atomic) {
2120
2143
  writeConfigAtomic(cfgPath, raw);
2121
- } else fs26.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
2144
+ } else fs27.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
2122
2145
  const lastKey = keys[keys.length - 1].toLowerCase();
2123
2146
  const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
2124
2147
  const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
@@ -2456,12 +2479,12 @@ function overlaps(a, b) {
2456
2479
  return (a.validTo === null || b.validFrom === null || b.validFrom < a.validTo) && (b.validTo === null || a.validFrom === null || a.validFrom < b.validTo);
2457
2480
  }
2458
2481
  function canonicalJson(value) {
2459
- const normalize6 = (input) => {
2460
- if (Array.isArray(input)) return input.map(normalize6);
2461
- if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key4, entry]) => [key4, normalize6(entry)]));
2482
+ const normalize7 = (input) => {
2483
+ if (Array.isArray(input)) return input.map(normalize7);
2484
+ if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key4, entry]) => [key4, normalize7(entry)]));
2462
2485
  return input;
2463
2486
  };
2464
- const json = JSON.stringify(normalize6(value));
2487
+ const json = JSON.stringify(normalize7(value));
2465
2488
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
2466
2489
  return json;
2467
2490
  }
@@ -2985,8 +3008,9 @@ function invalidateDerivedDependencies(db2, event2) {
2985
3008
  }
2986
3009
  return invalidateChildren(db2, event2.scopeId, pending, event2.kind);
2987
3010
  }
2988
- function invalidateScopeDependencies(db2, scope, parent, reason) {
2989
- const children = db2.prepare("SELECT child_kind,child_id FROM memory_dependencies WHERE scope_id=? AND parent_kind='scope' AND parent_id=?").all(scope, parent);
3011
+ function invalidateScopeDependencies(db2, scope, parent, reason, options = {}) {
3012
+ let children = db2.prepare("SELECT child_kind,child_id FROM memory_dependencies WHERE scope_id=? AND parent_kind='scope' AND parent_id=?").all(scope, parent);
3013
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
2990
3014
  invalidateChildren(db2, scope, children, reason);
2991
3015
  }
2992
3016
  function invalidateChildren(db2, scope, pending, reason) {
@@ -3006,7 +3030,7 @@ function invalidateChildren(db2, scope, pending, reason) {
3006
3030
  }
3007
3031
  const state = child.deleted ? "deleted" : "needs_revalidation";
3008
3032
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3009
- WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation','invalid') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
3033
+ WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
3010
3034
  result.push(child.child_id);
3011
3035
  pending.push(...db2.prepare("SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?").all(scope, child.child_id).map((row) => ({ ...row, deleted: child.deleted && row.role === "supports" })));
3012
3036
  }
@@ -3101,7 +3125,7 @@ var init_dependencies = __esm({
3101
3125
  if (previous && previous.version === version && previous.state !== "current") throw new Error("DERIVATION_REQUIRES_NEW_VERSION");
3102
3126
  this.assertReferences(scope, dependencies);
3103
3127
  if (previous?.version === version) {
3104
- const normalize6 = (refs) => JSON.stringify(refs.map((ref) => [
3128
+ const normalize7 = (refs) => JSON.stringify(refs.map((ref) => [
3105
3129
  ref.parentKind,
3106
3130
  ref.parentId,
3107
3131
  ref.parentVersion,
@@ -3109,7 +3133,7 @@ var init_dependencies = __esm({
3109
3133
  ref.slotRevision ?? null,
3110
3134
  ref.role
3111
3135
  ]).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
3112
- if (normalize6(this.refs(scope, kind, id3)) !== normalize6(dependencies)) throw new Error("DERIVATION_VERSION_CONFLICT");
3136
+ if (normalize7(this.refs(scope, kind, id3)) !== normalize7(dependencies)) throw new Error("DERIVATION_VERSION_CONFLICT");
3113
3137
  return;
3114
3138
  }
3115
3139
  this.db.prepare(`INSERT INTO memory_derivations VALUES (?,?,?,?,'current',NULL,?)
@@ -3556,7 +3580,7 @@ function textColumnOf(kind) {
3556
3580
  return "fact";
3557
3581
  }
3558
3582
  }
3559
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3583
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3560
3584
  var init_vector_store = __esm({
3561
3585
  "src/mem7/core/vector-store.ts"() {
3562
3586
  "use strict";
@@ -3587,6 +3611,14 @@ var init_vector_store = __esm({
3587
3611
  agent_case: ["task_intent_tokens", "approach_tokens"],
3588
3612
  agent_skill: ["description_tokens", "content_tokens"]
3589
3613
  };
3614
+ BM25_TEXT_FIELDS = {
3615
+ foresight: ["foresight", "evidence"],
3616
+ episode: ["episode"],
3617
+ atomic_fact: ["fact"],
3618
+ agent_case: ["task_intent", "approach"],
3619
+ agent_skill: ["description", "content"]
3620
+ };
3621
+ sqlLiteral = (value) => value.replace(/'/g, "''");
3590
3622
  RRF_K = 60;
3591
3623
  warnedFts = /* @__PURE__ */ new Set();
3592
3624
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -4184,6 +4216,47 @@ var init_vector_store = __esm({
4184
4216
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
4185
4217
  }
4186
4218
  }
4219
+ const textCols = BM25_TEXT_FIELDS[kind];
4220
+ const scan = async (terms, op, limit2) => {
4221
+ const expr = op === "AND" ? terms.map((g) => `(${textCols.map((col) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" AND ") : textCols.map((col) => `(${terms.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4222
+ const where2 = compileFilter(opts.filter);
4223
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit2).toArray();
4224
+ };
4225
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4226
+ const scoreLiteral = (needles2, rows) => {
4227
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4228
+ const occurrences2 = (text2, term) => text2.split(term).length - 1;
4229
+ for (const r of rows) {
4230
+ const rid = String(r.id ?? "");
4231
+ if (!rid) continue;
4232
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4233
+ const matched = terms.filter((term) => text2.includes(term));
4234
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
4235
+ const full = matched.length === terms.length;
4236
+ const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
4237
+ const score = full ? maxScore + 1 + Math.min(0.99, density / 10) : maxScore > 0 ? maxScore * (0.5 + 0.5 * matched.length / terms.length) : matched.length / terms.length;
4238
+ const cur = best.get(rid);
4239
+ if (cur) {
4240
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
4241
+ } else best.set(rid, { ...r, _score: score });
4242
+ }
4243
+ };
4244
+ const needles = literalQueryNeedles(queryText);
4245
+ if (needles) {
4246
+ try {
4247
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4248
+ const [all, any] = await Promise.all([
4249
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
4250
+ scan(needles, "OR", topK * 3)
4251
+ ]);
4252
+ scoreLiteral(needles, [...all, ...any]);
4253
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
4254
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
4255
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
4256
+ }
4257
+ } catch {
4258
+ }
4259
+ }
4187
4260
  return this.visibleRows(kind, [...best.values()]).filter((r) => Number(r._score ?? 0) > 0).sort((a, b) => Number(b._score ?? 0) - Number(a._score ?? 0)).slice(0, topK).map((r) => ({ ...this.toHit(kind, r), distance: 0, score: Number(r._score ?? 0) }));
4188
4261
  } catch (err) {
4189
4262
  const msg2 = String(err?.message ?? err);
@@ -4709,7 +4782,7 @@ import { createHash as createHash9 } from "node:crypto";
4709
4782
  function projectedSourceIdFromScopeId(id3, originKey, sourceVersion) {
4710
4783
  return "src_" + digest([id3, originKey, sourceVersion]);
4711
4784
  }
4712
- var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4785
+ var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4713
4786
  var init_source_store = __esm({
4714
4787
  "src/mem7/core/source-store.ts"() {
4715
4788
  "use strict";
@@ -4721,6 +4794,7 @@ var init_source_store = __esm({
4721
4794
  init_watermarks();
4722
4795
  init_interpretation_impact();
4723
4796
  init_conversation_text();
4797
+ RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
4724
4798
  SOURCE_SCHEMA = `
4725
4799
  CREATE TABLE memory_scopes (
4726
4800
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -4902,8 +4976,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4902
4976
  if (this.db.prepare("SELECT 1 FROM memory_sources WHERE scope_id=? AND origin_key=? AND interpretation_status='deleted'").get(id3, input.originKey)) throw new Error("DELETED_EVIDENCE");
4903
4977
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
4904
4978
  this.db.prepare("UPDATE memory_scopes SET source_seq=source_seq+1,context_revision=context_revision+1 WHERE scope_id=?").run(id3);
4905
- invalidateScopeDependencies(this.db, id3, "sources", "source.received");
4906
- invalidateScopeDependencies(this.db, id3, "context", "source.received");
4979
+ invalidateScopeDependencies(this.db, id3, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4980
+ invalidateScopeDependencies(this.db, id3, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4907
4981
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id3).source_seq);
4908
4982
  const sourceId = projectedSourceIdFromScopeId(id3, input.originKey, version);
4909
4983
  const receiptId = "rcpt_" + digest([id3, sourceId]);
@@ -5073,10 +5147,10 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5073
5147
  AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)
5074
5148
  ORDER BY source_seq DESC LIMIT ?`).all(scopeId(scope), source.sessionId, source.sourceSeq, limit2).map((row) => this.source(row)).reverse();
5075
5149
  }
5076
- pendingInterpretations(scope, sessionId, limit2 = 50, cutoff, newestFirst = false, states, textTerms, roles) {
5077
- if (states?.some((state) => !["received", "applied", "needs_review", "failed"].includes(state))) throw new Error("INVALID_SOURCE_STATE");
5150
+ pendingInterpretations(scope, sessionId, limit2 = 50, cutoff, newestFirst = false, states2, textTerms, roles) {
5151
+ if (states2?.some((state) => !["received", "applied", "needs_review", "failed"].includes(state))) throw new Error("INVALID_SOURCE_STATE");
5078
5152
  if (roles?.some((role) => !["user", "assistant", "tool"].includes(role))) throw new Error("INVALID_SOURCE_ROLE");
5079
- if (states?.length === 0) return [];
5153
+ if (states2?.length === 0) return [];
5080
5154
  if (roles?.length === 0) return [];
5081
5155
  const terms = textTerms ? [...new Set(textTerms.map((term) => term.trim().toLowerCase()).filter(Boolean))] : void 0;
5082
5156
  if (terms?.length === 0) return [];
@@ -5084,7 +5158,7 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5084
5158
  const matchesText = (text2) => !terms || terms.some((term) => latinTerm(term) ? new RegExp(`(^|[^a-z0-9_])${term}($|[^a-z0-9_])`).test(text2.toLowerCase()) : text2.toLowerCase().includes(term));
5085
5159
  if (cutoff) return historicalRows(this.db, scope, "source", cutoff).filter((row) => !["applied", "deleted"].includes(row.state)).flatMap((row) => {
5086
5160
  const source = this.get(scope, row.targetId, cutoff);
5087
- if (!source || !this.isCurrent(scope, source.sourceId, cutoff) || sessionId && source.sessionId !== sessionId || states && !states.includes(row.state) || roles && !roles.includes(source.role) || !matchesText(source.text)) return [];
5161
+ if (!source || !this.isCurrent(scope, source.sourceId, cutoff) || sessionId && source.sessionId !== sessionId || states2 && !states2.includes(row.state) || roles && !roles.includes(source.role) || !matchesText(source.text)) return [];
5088
5162
  return [{
5089
5163
  ...source,
5090
5164
  state: row.state,
@@ -5096,13 +5170,13 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5096
5170
  const rows = this.db.prepare(`SELECT * FROM memory_sources s WHERE scope_id=? AND interpretation_status<>'applied'
5097
5171
  AND interpretation_status<>'deleted' AND NOT EXISTS (SELECT 1 FROM memory_sources newer
5098
5172
  WHERE newer.scope_id=s.scope_id AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)
5099
- ${this.recoveryClause("s")} ${sessionId ? "AND session_id=?" : ""} ${states ? `AND interpretation_status IN (${states.map(() => "?").join(",")})` : ""}
5173
+ ${this.recoveryClause("s")} ${sessionId ? "AND session_id=?" : ""} ${states2 ? `AND interpretation_status IN (${states2.map(() => "?").join(",")})` : ""}
5100
5174
  ${terms ? `AND (${terms.map((term) => latinTerm(term) ? "(' ' || lower(s.text) || ' ') GLOB ?" : "instr(lower(s.text), ?) > 0").join(" OR ")})` : ""}
5101
5175
  ${roles ? `AND role IN (${roles.map(() => "?").join(",")})` : ""}
5102
5176
  ORDER BY source_seq ${newestFirst ? "DESC" : "ASC"} LIMIT ?`).all(
5103
5177
  scopeId(scope),
5104
5178
  ...sessionId ? [sessionId] : [],
5105
- ...states ?? [],
5179
+ ...states2 ?? [],
5106
5180
  ...terms?.map((term) => latinTerm(term) ? `*[^a-z0-9_]${term}[^a-z0-9_]*` : term) ?? [],
5107
5181
  ...roles ?? [],
5108
5182
  limit2
@@ -5595,8 +5669,8 @@ var init_recovery_deletion = __esm({
5595
5669
  const { owners, parents } = this.links(table, row);
5596
5670
  for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
5597
5671
  if (table === "memory_artifact_publications") {
5598
- const medium = text(row, "medium"), path36 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5599
- const identity = medium === "markdown" && path36 ? "file:mem7/" + path36 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash11("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5672
+ const medium = text(row, "medium"), path37 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5673
+ const identity = medium === "markdown" && path37 ? "file:mem7/" + path37 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash11("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5600
5674
  if (identity) {
5601
5675
  const rows = this.artifactPaths.get(identity) ?? [];
5602
5676
  rows.push(row);
@@ -5604,8 +5678,8 @@ var init_recovery_deletion = __esm({
5604
5678
  }
5605
5679
  }
5606
5680
  }
5607
- blocksArtifactPath(kind, path36) {
5608
- const rows = this.artifactPaths.get(kind + ":" + path36);
5681
+ blocksArtifactPath(kind, path37) {
5682
+ const rows = this.artifactPaths.get(kind + ":" + path37);
5609
5683
  return rows?.some((row) => this.blocks("memory_artifact_publications", row));
5610
5684
  }
5611
5685
  blocks(table, row) {
@@ -6624,7 +6698,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6624
6698
  };
6625
6699
  const candidates2 = [];
6626
6700
  const duplicateIds = /* @__PURE__ */ new Set();
6627
- const inside = (path36) => path36 && !isAbsolute2(path36) && path36 !== ".." && !path36.startsWith(`..${sep2}`);
6701
+ const inside = (path37) => path37 && !isAbsolute2(path37) && path37 !== ".." && !path37.startsWith(`..${sep2}`);
6628
6702
  for (const relativePath of input.files) {
6629
6703
  const logical = resolve4(root, relativePath);
6630
6704
  let canonical4;
@@ -6638,10 +6712,10 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6638
6712
  gap("projection_path_unverified");
6639
6713
  continue;
6640
6714
  }
6641
- const path36 = relative2(root, canonical4).replace(/\\/g, "/");
6715
+ const path37 = relative2(root, canonical4).replace(/\\/g, "/");
6642
6716
  const user = `users/${input.scope.ownerId}/`;
6643
6717
  const agent = store.ownerProjectionPath("agents", input.scope.ownerId, input.scope).replace(/\\/g, "/") + "/";
6644
- const kind = path36.startsWith(`${user}episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "episode" : path36.startsWith(`${user}.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "atomic_fact" : path36.startsWith(`${user}.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "foresight" : path36.startsWith(`${agent}.cases/`) && /\/agent_case-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "agent_case" : void 0;
6718
+ const kind = path37.startsWith(`${user}episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(path37) ? "episode" : path37.startsWith(`${user}.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(path37) ? "atomic_fact" : path37.startsWith(`${user}.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(path37) ? "foresight" : path37.startsWith(`${agent}.cases/`) && /\/agent_case-\d{4}-\d{2}-\d{2}\.md$/.test(path37) ? "agent_case" : void 0;
6645
6719
  if (!kind) {
6646
6720
  gap("projection_kind_or_owner_unverified");
6647
6721
  continue;
@@ -6678,9 +6752,9 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6678
6752
  continue;
6679
6753
  }
6680
6754
  const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key4, kind, match[1]);
6681
- const target = join9(store.mem7RootPath(), path36);
6755
+ const target = join9(store.mem7RootPath(), path37);
6682
6756
  if (previous) {
6683
- if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path36 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6757
+ if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path37 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6684
6758
  gap("projection_mapping_conflict");
6685
6759
  continue;
6686
6760
  }
@@ -6696,7 +6770,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6696
6770
  candidates2.push({
6697
6771
  file: canonical4,
6698
6772
  fileHash,
6699
- relativePath: path36,
6773
+ relativePath: path37,
6700
6774
  id: match[1],
6701
6775
  kind,
6702
6776
  parent,
@@ -8178,9 +8252,9 @@ function normalize3(input) {
8178
8252
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
8179
8253
  return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
8180
8254
  }
8181
- function directory(path36) {
8182
- const info = lstatSync6(path36);
8183
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path36) !== resolve5(path36) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
8255
+ function directory(path37) {
8256
+ const info = lstatSync6(path37);
8257
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path37) !== resolve5(path37) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
8184
8258
  throw new Error("REPLICATION_REGISTRATION_INVALID");
8185
8259
  }
8186
8260
  function readRuntimeReplicationRegistration(stateDir, component, key4) {
@@ -8284,10 +8358,10 @@ var init_runtime_replication = __esm({
8284
8358
 
8285
8359
  // src/memory/topics-history/index.ts
8286
8360
  import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
8287
- function parseTopicHistoryPath(path36) {
8288
- if (!path36.startsWith("topics-history://") || path36.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8361
+ function parseTopicHistoryPath(path37) {
8362
+ if (!path37.startsWith("topics-history://") || path37.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8289
8363
  try {
8290
- return JSON.parse(Buffer.from(path36.slice(17), "base64url").toString("utf8"));
8364
+ return JSON.parse(Buffer.from(path37.slice(17), "base64url").toString("utf8"));
8291
8365
  } catch {
8292
8366
  throw new Error("INVALID_HISTORY_REFERENCE");
8293
8367
  }
@@ -10232,23 +10306,23 @@ var init_facts = __esm({
10232
10306
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
10233
10307
  }
10234
10308
  for (const [index, evidence] of proposal.evidence.entries()) {
10235
- const path36 = `evidence[${index}]`;
10236
- if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path36} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
10309
+ const path37 = `evidence[${index}]`;
10310
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path37} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
10237
10311
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
10238
10312
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
10239
10313
  AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
10240
- 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`);
10241
- 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`);
10314
+ if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path37}.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`);
10315
+ if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path37}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
10242
10316
  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) {
10243
10317
  const count = occurrences(source.text, evidence.quote);
10244
- 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`);
10318
+ throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path37}.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: ${path37} \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`);
10245
10319
  }
10246
- 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`);
10320
+ if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path37}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
10247
10321
  const relationValue = proposal.value;
10248
10322
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
10249
10323
  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");
10250
10324
  }
10251
- 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`);
10325
+ const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path37} \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`);
10252
10326
  if (proposal.claimKind !== "inference") {
10253
10327
  if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
10254
10328
  if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
@@ -10608,7 +10682,7 @@ function contentHash(text2) {
10608
10682
  function mem7Root(stateDir) {
10609
10683
  return join12(stateDir, "mem7");
10610
10684
  }
10611
- var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
10685
+ var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
10612
10686
  var init_store = __esm({
10613
10687
  "src/mem7/core/store.ts"() {
10614
10688
  "use strict";
@@ -10646,6 +10720,7 @@ var init_store = __esm({
10646
10720
  init_job_retention();
10647
10721
  init_retire_graph_audits();
10648
10722
  STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
10723
+ STARVATION_GRACE_MS = 36e5;
10649
10724
  SCHEMA = `
10650
10725
  CREATE TABLE IF NOT EXISTS memcells (
10651
10726
  id TEXT PRIMARY KEY,
@@ -11239,13 +11314,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11239
11314
  const version = expectedVersion ?? this.dependencies.version(scope, kind, id3);
11240
11315
  this.dependencies.assertCurrent(scope, kind, id3, version);
11241
11316
  const digest7 = createHash20("sha256").update(content.trim()).digest("hex");
11242
- const path36 = relative3(this.root, file2).replace(/\\/g, "/");
11317
+ const path37 = relative3(this.root, file2).replace(/\\/g, "/");
11243
11318
  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);
11244
- if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path36)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
11319
+ if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path37)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
11245
11320
  this.db.prepare(`INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)
11246
11321
  ON CONFLICT(scope_id,kind,entry_id) DO UPDATE SET path=excluded.path,version=excluded.version,digest=excluded.digest
11247
- WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path36, version, digest7);
11248
- this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path36, markdown: content.trim() });
11322
+ WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path37, version, digest7);
11323
+ this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path37, markdown: content.trim() });
11249
11324
  });
11250
11325
  }
11251
11326
  projectionMatches(scope, kind, id3, file2, content) {
@@ -11442,8 +11517,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11442
11517
  };
11443
11518
  }
11444
11519
  unscopedProjectionMatches(ownerId, kind, id3, file2, content) {
11445
- const path36 = relative3(this.root, file2).replace(/\\/g, "/");
11446
- const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path36);
11520
+ const path37 = relative3(this.root, file2).replace(/\\/g, "/");
11521
+ const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path37);
11447
11522
  if (mappings.length) {
11448
11523
  if (mappings.length !== 1) return false;
11449
11524
  const scope = this.sources.scope(mappings[0].scope_id);
@@ -11736,7 +11811,7 @@ ${e.outcome}
11736
11811
  return this.transaction(() => {
11737
11812
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
11738
11813
  const scopeFilter = options.scopeId !== void 0 ? " AND scope_id=?" : "";
11739
- const rows = this.db.prepare(`SELECT * FROM ome_jobs j INDEXED BY ${options.scopeId !== void 0 && options.kinds?.length === 1 ? "idx_jobs_scope_priority" : "idx_jobs_runnable_priority"}
11814
+ const base = `SELECT * FROM ome_jobs j INDEXED BY ${options.scopeId !== void 0 && options.kinds?.length === 1 ? "idx_jobs_scope_priority" : "idx_jobs_runnable_priority"}
11740
11815
  WHERE status IN ('pending','running') AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=j.id AND h.released_at IS NULL)
11741
11816
  AND ((status='pending' AND next_run_at<=?)
11742
11817
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -11756,40 +11831,48 @@ ${e.outcome}
11756
11831
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
11757
11832
  AND (kind IN ('social.interpret','source.interpret','relationship.cognition') OR scope_id NOT LIKE 'resource:%' OR NOT EXISTS (SELECT 1 FROM ome_jobs prior
11758
11833
  WHERE prior.scope_id=j.scope_id AND prior.id<j.id AND prior.status IN ('pending','running')
11759
- AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=prior.id AND h.released_at IS NULL)) OR scope_id IS NULL)
11760
- -- Retrying an old deferred job must not reserve the next stage budget.
11761
- -- Boundary/resource predecessor predicates above still enforce ordering.
11762
- ORDER BY priority,next_run_at,id LIMIT ?`).all(now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit2);
11763
- const claimedScopes = /* @__PURE__ */ new Set();
11764
- return rows.flatMap((row) => {
11765
- if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
11766
- const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
11767
- if (updated.scope_id !== row.scope_id && updated.scope_id) {
11768
- const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
11769
- AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
11770
- AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=j.id AND h.released_at IS NULL))`).get(updated.scope_id, updated.id, now2, updated.scope_id, updated.id);
11771
- if (conflict) return [];
11772
- }
11773
- return [updated];
11774
- }).filter((row) => {
11775
- if (!row.scope_id) return true;
11776
- if (claimedScopes.has(row.scope_id)) return false;
11777
- claimedScopes.add(row.scope_id);
11778
- return true;
11779
- }).map((row) => {
11780
- const leaseToken = randomUUID10();
11781
- this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
11782
- return {
11783
- id: row.id,
11784
- kind: row.kind,
11785
- payload: JSON.parse(row.payload),
11786
- attempts: row.attempts,
11787
- leaseToken,
11788
- inputVersion: row.input_version,
11789
- scopeId: row.scope_id ?? void 0,
11790
- result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
11791
- };
11792
- });
11834
+ AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=prior.id AND h.released_at IS NULL)) OR scope_id IS NULL)`;
11835
+ const select = (starved2) => {
11836
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
11837
+ ORDER BY priority,next_run_at,id LIMIT ?`;
11838
+ const args = starved2 ? [now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, now2 - STARVATION_GRACE_MS, limit2] : [now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit2];
11839
+ return this.db.prepare(sql).all(...args);
11840
+ };
11841
+ const claim = (rows) => {
11842
+ const claimedScopes = /* @__PURE__ */ new Set();
11843
+ return rows.flatMap((row) => {
11844
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
11845
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
11846
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
11847
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
11848
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
11849
+ AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=j.id AND h.released_at IS NULL))`).get(updated.scope_id, updated.id, now2, updated.scope_id, updated.id);
11850
+ if (conflict) return [];
11851
+ }
11852
+ return [updated];
11853
+ }).filter((row) => {
11854
+ if (!row.scope_id) return true;
11855
+ if (claimedScopes.has(row.scope_id)) return false;
11856
+ claimedScopes.add(row.scope_id);
11857
+ return true;
11858
+ }).map((row) => {
11859
+ const leaseToken = randomUUID10();
11860
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
11861
+ return {
11862
+ id: row.id,
11863
+ kind: row.kind,
11864
+ payload: JSON.parse(row.payload),
11865
+ attempts: row.attempts,
11866
+ leaseToken,
11867
+ inputVersion: row.input_version,
11868
+ scopeId: row.scope_id ?? void 0,
11869
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
11870
+ };
11871
+ });
11872
+ };
11873
+ if (options.staleOnly) return claim(select(true));
11874
+ const starved = claim(select(true));
11875
+ return starved.length ? starved : claim(select(false));
11793
11876
  });
11794
11877
  }
11795
11878
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -18167,9 +18250,9 @@ function isAutoMemPath(absolutePath, workspace) {
18167
18250
  return normalizedPath.startsWith(getAutoMemPath(workspace));
18168
18251
  }
18169
18252
  async function ensureMemoryDirExists(memoryDir) {
18170
- const fs26 = await import("node:fs");
18253
+ const fs27 = await import("node:fs");
18171
18254
  try {
18172
- await fs26.promises.mkdir(memoryDir, { recursive: true });
18255
+ await fs27.promises.mkdir(memoryDir, { recursive: true });
18173
18256
  } catch (e) {
18174
18257
  const code = e?.code;
18175
18258
  if (code !== "EEXIST") {
@@ -18350,8 +18433,8 @@ __export(memdir_exports, {
18350
18433
  loadMemoryPrompt: () => loadMemoryPrompt,
18351
18434
  truncateEntrypointContent: () => truncateEntrypointContent
18352
18435
  });
18353
- import { readFileSync as readFileSync15 } from "node:fs";
18354
- import { join as join29 } from "node:path";
18436
+ import { readFileSync as readFileSync16 } from "node:fs";
18437
+ import { join as join30 } from "node:path";
18355
18438
  function truncateEntrypointContent(raw) {
18356
18439
  const trimmed = raw.trim();
18357
18440
  const contentLines = trimmed.split("\n");
@@ -18444,11 +18527,11 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
18444
18527
  }
18445
18528
  function buildMemoryPrompt(params) {
18446
18529
  const { displayName, memoryDir, extraGuidelines } = params;
18447
- const entrypoint = join29(memoryDir, ENTRYPOINT_NAME);
18530
+ const entrypoint = join30(memoryDir, ENTRYPOINT_NAME);
18448
18531
  let entrypointContent = params.entrypointContent ?? "";
18449
18532
  if (params.entrypointContent === void 0) {
18450
18533
  try {
18451
- entrypointContent = readFileSync15(entrypoint, "utf-8");
18534
+ entrypointContent = readFileSync16(entrypoint, "utf-8");
18452
18535
  } catch {
18453
18536
  }
18454
18537
  }
@@ -18494,8 +18577,8 @@ __export(context_analyzer_exports, {
18494
18577
  formatContextReport: () => formatContextReport,
18495
18578
  scanMemoryFiles: () => scanMemoryFiles
18496
18579
  });
18497
- import * as fs22 from "node:fs";
18498
- import * as path29 from "node:path";
18580
+ import * as fs23 from "node:fs";
18581
+ import * as path30 from "node:path";
18499
18582
  function estimateMessageTokens2(m) {
18500
18583
  let tokens = 0;
18501
18584
  if (typeof m.content === "string") {
@@ -18605,9 +18688,9 @@ function breakdownMessages(messages) {
18605
18688
  }
18606
18689
  async function scanMemoryFiles(workspace) {
18607
18690
  const files = [];
18608
- const soul = readFileIfExists(path29.join(workspace, "SOUL.md"));
18691
+ const soul = readFileIfExists(path30.join(workspace, "SOUL.md"));
18609
18692
  if (soul) files.push({ path: "SOUL.md", tokens: roughTokenCountEstimation(soul), stable: true });
18610
- const agents = readFileIfExists(path29.join(workspace, "AGENTS.md"));
18693
+ const agents = readFileIfExists(path30.join(workspace, "AGENTS.md"));
18611
18694
  if (agents) files.push({ path: "AGENTS.md", tokens: roughTokenCountEstimation(agents), stable: true });
18612
18695
  try {
18613
18696
  const { buildMemoryPrompt: buildMemoryPrompt2 } = await Promise.resolve().then(() => (init_memdir(), memdir_exports));
@@ -18623,7 +18706,7 @@ async function scanMemoryFiles(workspace) {
18623
18706
  }
18624
18707
  function readFileIfExists(filePath2) {
18625
18708
  try {
18626
- if (fs22.existsSync(filePath2)) return fs22.readFileSync(filePath2, "utf-8");
18709
+ if (fs23.existsSync(filePath2)) return fs23.readFileSync(filePath2, "utf-8");
18627
18710
  } catch {
18628
18711
  }
18629
18712
  return null;
@@ -18845,11 +18928,11 @@ var init_gateway_media = __esm({
18845
18928
  });
18846
18929
 
18847
18930
  // src/continuity/pairing-control.ts
18848
- import { writeFileSync as writeFileSync15, existsSync as existsSync15, rmSync as rmSync3 } from "node:fs";
18849
- import { join as join32, resolve as resolve12 } from "node:path";
18931
+ import { writeFileSync as writeFileSync15, existsSync as existsSync16, rmSync as rmSync3 } from "node:fs";
18932
+ import { join as join33, resolve as resolve12 } from "node:path";
18850
18933
  import { fileURLToPath as fileURLToPath5 } from "node:url";
18851
18934
  import { createServer as createServer4 } from "node:https";
18852
- import { timingSafeEqual, X509Certificate, createHash as createHash38 } from "node:crypto";
18935
+ import { timingSafeEqual, X509Certificate, createHash as createHash39 } from "node:crypto";
18853
18936
 
18854
18937
  // src/continuity/authority.ts
18855
18938
  init_publication_objects();
@@ -18914,9 +18997,9 @@ var TravelAuthority = class {
18914
18997
  this.owner.close();
18915
18998
  throw new Error("TRAVEL_AUTHORITY_BUSY", { cause: error });
18916
18999
  }
18917
- const path36 = join3(options.directory, "authority.sqlite"), keyFile = join3(options.directory, "authority-signing.pem");
19000
+ const path37 = join3(options.directory, "authority.sqlite"), keyFile = join3(options.directory, "authority-signing.pem");
18918
19001
  try {
18919
- const present = existsSync(path36), keyPresent = existsSync(keyFile);
19002
+ const present = existsSync(path37), keyPresent = existsSync(keyFile);
18920
19003
  if (present !== keyPresent) throw new Error("TRAVEL_AUTHORITY_RECOVERY_REQUIRED");
18921
19004
  if (!keyPresent) {
18922
19005
  const keys = generateKeyPairSync("ed25519");
@@ -18924,8 +19007,8 @@ var TravelAuthority = class {
18924
19007
  }
18925
19008
  this.signingKey = readPrivateFile(keyFile).toString();
18926
19009
  this.publicKey = createPublicKey(this.signingKey).export({ format: "pem", type: "spki" }).toString();
18927
- preparePrivateDatabase(path36);
18928
- this.db = new DatabaseSync3(path36);
19010
+ preparePrivateDatabase(path37);
19011
+ this.db = new DatabaseSync3(path37);
18929
19012
  this.db.exec(`PRAGMA busy_timeout=1000; PRAGMA synchronous=FULL;
18930
19013
  CREATE TABLE IF NOT EXISTS seats(identity TEXT PRIMARY KEY,epoch INTEGER NOT NULL,active_node TEXT,active_boot TEXT,
18931
19014
  floor INTEGER NOT NULL,checkpoint TEXT NOT NULL,build TEXT NOT NULL,retired TEXT,frozen INTEGER NOT NULL DEFAULT 0);
@@ -19458,7 +19541,7 @@ function createKeyServiceServer(options) {
19458
19541
  // src/continuity/gateway-main.ts
19459
19542
  import { isAbsolute as isAbsolute5, resolve as resolve11 } from "node:path";
19460
19543
  import { fileURLToPath as fileURLToPath4 } from "node:url";
19461
- import { createHash as createHash37 } from "node:crypto";
19544
+ import { createHash as createHash38 } from "node:crypto";
19462
19545
  import * as lark3 from "@larksuiteoapi/node-sdk";
19463
19546
 
19464
19547
  // src/continuity/publication.ts
@@ -19470,9 +19553,9 @@ import { isAbsolute, join as join4, relative, resolve as resolve2, sep } from "n
19470
19553
  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(" "));
19471
19554
  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(" "));
19472
19555
  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(" "));
19473
- function validateRelativePath(path36) {
19474
- if (typeof path36 !== "string" || !path36 || path36.length > 2048 || isAbsolute(path36)) throw new Error("INVALID_ARTIFACT_PATH");
19475
- for (const part of path36.split("/")) {
19556
+ function validateRelativePath(path37) {
19557
+ if (typeof path37 !== "string" || !path37 || path37.length > 2048 || isAbsolute(path37)) throw new Error("INVALID_ARTIFACT_PATH");
19558
+ for (const part of path37.split("/")) {
19476
19559
  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)))
19477
19560
  throw new Error("INVALID_ARTIFACT_PATH");
19478
19561
  }
@@ -19520,10 +19603,10 @@ function normalizePublicationProfile(value) {
19520
19603
  Object.freeze(profile.trees);
19521
19604
  return Object.freeze(profile);
19522
19605
  }
19523
- function validatePublicationPath(path36) {
19524
- if (typeof path36 !== "string" || path36.normalize("NFC") !== path36) throw new Error("PUBLICATION_INVALID_PATH");
19606
+ function validatePublicationPath(path37) {
19607
+ if (typeof path37 !== "string" || path37.normalize("NFC") !== path37) throw new Error("PUBLICATION_INVALID_PATH");
19525
19608
  try {
19526
- validateRelativePath(path36);
19609
+ validateRelativePath(path37);
19527
19610
  } catch {
19528
19611
  throw new Error("PUBLICATION_INVALID_PATH");
19529
19612
  }
@@ -19542,15 +19625,15 @@ function normalizePublication(value) {
19542
19625
  if (!Array.isArray(tree.files) || !Array.isArray(tree.directories) || (paths += tree.files.length + tree.directories.length) > 1e5)
19543
19626
  throw new Error("PUBLICATION_INVALID_TREE");
19544
19627
  const occupied = /* @__PURE__ */ new Map();
19545
- const claim = (path36, kind) => {
19546
- validatePublicationPath(path36);
19547
- const folded = path36.toLowerCase();
19628
+ const claim = (path37, kind) => {
19629
+ validatePublicationPath(path37);
19630
+ const folded = path37.toLowerCase();
19548
19631
  if (occupied.has(folded)) throw new Error("PUBLICATION_PATH_COLLISION");
19549
19632
  occupied.set(folded, kind);
19550
19633
  };
19551
- const directories = tree.directories.map((path36) => {
19552
- claim(path36, "directory");
19553
- return path36;
19634
+ const directories = tree.directories.map((path37) => {
19635
+ claim(path37, "directory");
19636
+ return path37;
19554
19637
  }).sort();
19555
19638
  const files = tree.files.map((file2) => {
19556
19639
  claim(file2?.path, "file");
@@ -19562,8 +19645,8 @@ function normalizePublication(value) {
19562
19645
  chunks: file2.content.chunks.map((r) => ({ sha256: r.sha256, bytes: r.bytes }))
19563
19646
  } };
19564
19647
  }).sort((a, b) => a.path.localeCompare(b.path, "en"));
19565
- for (const path36 of occupied.keys()) {
19566
- const parts = path36.split("/");
19648
+ for (const path37 of occupied.keys()) {
19649
+ const parts = path37.split("/");
19567
19650
  for (let i = 1; i < parts.length; i++) if (occupied.get(parts.slice(0, i).join("/")) === "file") throw new Error("PUBLICATION_PATH_COLLISION");
19568
19651
  }
19569
19652
  return { id: tree.id, directories, files };
@@ -19994,9 +20077,9 @@ var TravelGatewayStore = class {
19994
20077
  throw new Error("TRAVEL_GATEWAY_BUSY");
19995
20078
  }
19996
20079
  try {
19997
- const path36 = join13(options.directory, "gateway.sqlite"), present = existsSync6(path36);
19998
- preparePrivateDatabase(path36);
19999
- this.db = new DatabaseSync10(path36);
20080
+ const path37 = join13(options.directory, "gateway.sqlite"), present = existsSync6(path37);
20081
+ preparePrivateDatabase(path37);
20082
+ this.db = new DatabaseSync10(path37);
20000
20083
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
20001
20084
  if (!present) this.db.exec([
20002
20085
  "CREATE TABLE binding(identity TEXT NOT NULL,format TEXT NOT NULL);",
@@ -21681,13 +21764,13 @@ var DiscordAdapter = class _DiscordAdapter {
21681
21764
  }
21682
21765
  /** 发送媒体附件(图片/文件/音频)— discord.js channel.send({ files }) */
21683
21766
  async sendFile(target, message, attachment) {
21684
- const fs26 = await import("node:fs");
21685
- const path36 = await import("node:path");
21686
- if (!fs26.existsSync(attachment.path)) {
21767
+ const fs27 = await import("node:fs");
21768
+ const path37 = await import("node:path");
21769
+ if (!fs27.existsSync(attachment.path)) {
21687
21770
  throw new Error(`File not found: ${attachment.path}`);
21688
21771
  }
21689
- const filename = attachment.filename || path36.basename(attachment.path);
21690
- const fileBuffer = fs26.readFileSync(attachment.path);
21772
+ const filename = attachment.filename || path37.basename(attachment.path);
21773
+ const fileBuffer = fs27.readFileSync(attachment.path);
21691
21774
  const filePayload = {
21692
21775
  attachment: fileBuffer,
21693
21776
  name: filename
@@ -22301,13 +22384,13 @@ var FeishuAdapter = class _FeishuAdapter {
22301
22384
  }
22302
22385
  /** 发送媒体附件(图片/文件) */
22303
22386
  async sendFile(target, message, attachment) {
22304
- const fs26 = await import("node:fs");
22305
- const path36 = await import("node:path");
22306
- if (!fs26.existsSync(attachment.path)) {
22387
+ const fs27 = await import("node:fs");
22388
+ const path37 = await import("node:path");
22389
+ if (!fs27.existsSync(attachment.path)) {
22307
22390
  throw new Error(`File not found: ${attachment.path}`);
22308
22391
  }
22309
- const filename = attachment.filename || path36.basename(attachment.path);
22310
- const fileBuffer = fs26.readFileSync(attachment.path);
22392
+ const filename = attachment.filename || path37.basename(attachment.path);
22393
+ const fileBuffer = fs27.readFileSync(attachment.path);
22311
22394
  const safeTarget = target || this.config.defaultTarget || "";
22312
22395
  if (!safeTarget) throw new Error("Feishu sendFile: no target (\u4E3B\u52A8\u53D1\u9001\u9700\u914D\u7F6E defaultTarget \u6216\u4F20\u5165 target)");
22313
22396
  const receiveIdType = safeTarget.startsWith("ou_") ? "open_id" : "chat_id";
@@ -24437,22 +24520,22 @@ var DeskBuddyAdapter = class {
24437
24520
  try {
24438
24521
  if (!this.historyFile) {
24439
24522
  const os7 = __require("os");
24440
- const fs27 = __require("fs");
24441
- const path36 = __require("path");
24442
- const dir = path36.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
24443
- fs27.mkdirSync(dir, { recursive: true });
24444
- this.historyFile = path36.join(dir, "history.json");
24445
- this._fs = fs27;
24446
- }
24447
- const fs26 = this._fs;
24523
+ const fs28 = __require("fs");
24524
+ const path37 = __require("path");
24525
+ const dir = path37.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
24526
+ fs28.mkdirSync(dir, { recursive: true });
24527
+ this.historyFile = path37.join(dir, "history.json");
24528
+ this._fs = fs28;
24529
+ }
24530
+ const fs27 = this._fs;
24448
24531
  let arr = [];
24449
24532
  try {
24450
- arr = JSON.parse(fs26.readFileSync(this.historyFile, "utf-8")) || [];
24533
+ arr = JSON.parse(fs27.readFileSync(this.historyFile, "utf-8")) || [];
24451
24534
  } catch {
24452
24535
  }
24453
24536
  arr.push({ ...entry, ts: (/* @__PURE__ */ new Date()).toLocaleString("zh-CN", { hour12: false }) });
24454
24537
  if (arr.length > 500) arr = arr.slice(-500);
24455
- fs26.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
24538
+ fs27.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
24456
24539
  } catch (e) {
24457
24540
  console.warn("[deskBuddy] history write fail", e);
24458
24541
  }
@@ -26077,7 +26160,7 @@ var TelegramAdapter = class {
26077
26160
 
26078
26161
  // src/channels/whatsapp/adapter.ts
26079
26162
  import fsSync4 from "node:fs";
26080
- import path31 from "node:path";
26163
+ import path32 from "node:path";
26081
26164
  import { spawn as spawn5 } from "node:child_process";
26082
26165
  import { randomUUID as randomUUID18 } from "node:crypto";
26083
26166
 
@@ -27005,7 +27088,7 @@ function headerOf(groupJid) {
27005
27088
 
27006
27089
  // src/channels/whatsapp/patrol.ts
27007
27090
  import fsSync3 from "node:fs";
27008
- import path30 from "node:path";
27091
+ import path31 from "node:path";
27009
27092
  import { randomBytes as randomBytes7 } from "node:crypto";
27010
27093
 
27011
27094
  // src/models/model-capabilities.ts
@@ -28056,8 +28139,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
28056
28139
  hookEvent,
28057
28140
  durationMs: durationMs2
28058
28141
  });
28142
+ const output = syncOutput.hookSpecificOutput;
28059
28143
  return {
28060
28144
  ...processed,
28145
+ ...hook.id === "skill-gate-prompt" && output?.hookEventName === "UserPromptSubmit" && output.selectSkill === true ? { selectSkill: true } : {},
28061
28146
  outcome: processed.blockingError ? "blocking" : "success",
28062
28147
  hook
28063
28148
  };
@@ -28159,6 +28244,7 @@ function aggregateResults(results) {
28159
28244
  if (result.permissionBehavior) {
28160
28245
  aggregated.permissionBehavior = result.permissionBehavior;
28161
28246
  }
28247
+ if (result.selectSkill) aggregated.selectSkill = true;
28162
28248
  if (result.additionalContext) {
28163
28249
  aggregated.additionalContexts.push(result.additionalContext);
28164
28250
  }
@@ -30590,8 +30676,8 @@ var contextIdentity = (context) => canonicalJson({
30590
30676
  function createNotificationStateReader() {
30591
30677
  const databases = /* @__PURE__ */ new Map();
30592
30678
  const checkers = /* @__PURE__ */ new Map();
30593
- const open3 = (path36) => {
30594
- const key4 = resolve9(path36);
30679
+ const open3 = (path37) => {
30680
+ const key4 = resolve9(path37);
30595
30681
  let db2 = databases.get(key4);
30596
30682
  if (!db2) {
30597
30683
  db2 = new DatabaseSync11(key4, { readOnly: true });
@@ -31201,6 +31287,174 @@ function killTask(taskId) {
31201
31287
  return true;
31202
31288
  }
31203
31289
 
31290
+ // src/core/query-skill-selection.ts
31291
+ init_types();
31292
+
31293
+ // src/skills/recent-user-texts.ts
31294
+ init_strip_injected();
31295
+
31296
+ // src/core/query-skill-selection.ts
31297
+ var SKILL_SELECTION_PROMPT = "\u6309 currentTask \u7684\u76EE\u6807\u548C\u6240\u5904\u9636\u6BB5\uFF0C\u5224\u65AD\u54EA\u9879\u5DF2\u5B89\u88C5\u6280\u80FD\u80FD\u5207\u5B9E\u5E2E\u52A9\u5B8C\u6210\u8FD9\u8F6E\u4EFB\u52A1\uFF0C\u6D41\u7A0B\u7C7B\u6280\u80FD\u7EA6\u675F\u505A\u6CD5\uFF0C\u6587\u6863\u3001\u8868\u683C\u3001\u53D1\u5E03\u7B49\u9886\u57DF\u7C7B\u6280\u80FD\u63D0\u4F9B\u4E13\u95E8\u80FD\u529B\u3002recentDialogue \u53EA\u7528\u4E8E\u7406\u89E3\u6307\u4EE3\u3002\u4E0B\u9762\u662F\u5DF2\u5B89\u88C5\u6280\u80FD\u7684\u540D\u79F0\u548C\u7528\u9014\u3002\u4F60\u53EA\u8D1F\u8D23\u6311\u9009\u6280\u80FD\uFF0C\u4E0D\u8D1F\u8D23\u56DE\u7B54\u4EFB\u52A1\u672C\u8EAB\uFF1A\u6B63\u5F0F\u56DE\u7B54\u7531\u540E\u7EED\u9636\u6BB5\u5B8C\u6210\uFF0C\u8FD9\u91CC\u4E0D\u8981\u5199\u4EFB\u4F55\u56DE\u7B54\u3002\u9002\u7528\u65F6\u76F4\u63A5\u8C03\u7528\u4E00\u9879\u6700\u5408\u9002\u7684 Skill\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u8BF4\u660E\u6587\u5B57\u3002\u7528\u666E\u901A\u5DE5\u5177\u6216\u53EA\u8BFB\u64CD\u4F5C\u4E5F\u53EF\u4EE5\u9075\u5FAA\u6D41\u7A0B\u3002\u5982\u679C\u5BF9\u65B9\u660E\u786E\u8981\u6C42\u8DF3\u8FC7\u3001\u5F53\u524D\u4EFB\u52A1\u6CA1\u6709\u9002\u7528\u7684\u6280\u80FD\uFF0C\u6216\u7F3A\u5C11\u9009\u51C6\u6240\u9700\u7684\u4FE1\u606F\uFF0C\u4E0D\u8C03\u7528\u4EFB\u4F55\u5DE5\u5177\uFF0C\u4E5F\u4E0D\u5199\u4EFB\u4F55\u5B57\uFF0C\u7ACB\u5373\u7ED3\u675F\u3002\u6B63\u5E38\u5DE5\u4F5C\u9636\u6BB5\u4F1A\u63D0\u4F9B\u5B8C\u6574\u5BF9\u8BDD\u548C\u9879\u76EE\u5DE5\u5177\u3002";
31298
+ var SKILL_SELECTION_MAX_TOKENS = 64;
31299
+ async function selectSkillCall(provider, params, allowedNames, recordUsage) {
31300
+ const timeout = AbortSignal.timeout(5e3);
31301
+ const signal = AbortSignal.any([params.signal, timeout]);
31302
+ const chunks = [];
31303
+ let calledSkill = false;
31304
+ let skillName = "";
31305
+ let requestComplete = false;
31306
+ let otherCut = false;
31307
+ try {
31308
+ for await (const chunk of provider.streamChat({
31309
+ ...params,
31310
+ signal,
31311
+ httpRetry: { maxRetries: 0 }
31312
+ })) {
31313
+ signal.throwIfAborted();
31314
+ if (chunk.type === "error") return { outcome: "upstream-error" };
31315
+ if (chunk.type === "tool_call") {
31316
+ if (calledSkill || !chunk.tool_call?.id || chunk.tool_call.function?.name !== SKILL_TOOL_NAME) return { outcome: "invalid" };
31317
+ let args;
31318
+ try {
31319
+ args = JSON.parse(chunk.tool_call.function.arguments);
31320
+ } catch {
31321
+ return { outcome: "invalid" };
31322
+ }
31323
+ if (typeof args?.skill !== "string" || !allowedNames.has(args.skill.trim().replace(/^\//, ""))) return { outcome: "invalid" };
31324
+ calledSkill = true;
31325
+ skillName = args.skill.trim().replace(/^\//, "");
31326
+ chunks.push(chunk);
31327
+ }
31328
+ if (chunk.type === "done") {
31329
+ if (chunk.usage) recordUsage(chunk.usage);
31330
+ requestComplete ||= chunk.requestComplete === true;
31331
+ otherCut ||= ["incomplete", "content_filter"].includes(chunk.stopReason ?? "");
31332
+ }
31333
+ }
31334
+ } catch (error) {
31335
+ params.signal.throwIfAborted();
31336
+ if (error instanceof Error && /^TRAVEL_/.test(error.message)) throw error;
31337
+ return { outcome: timeout.aborted ? "timeout" : "upstream-error" };
31338
+ }
31339
+ params.signal.throwIfAborted();
31340
+ if (timeout.aborted) return { outcome: "timeout" };
31341
+ if (!requestComplete || otherCut) return { outcome: "incomplete" };
31342
+ return calledSkill ? { outcome: "selected", skill: skillName, chunks } : { outcome: "no-skill" };
31343
+ }
31344
+
31345
+ // src/skills/scanner.ts
31346
+ function parseFrontmatter(content) {
31347
+ const result = {};
31348
+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
31349
+ if (!match) return result;
31350
+ const lines = match[1].split("\n");
31351
+ let i = 0;
31352
+ while (i < lines.length) {
31353
+ const line = lines[i];
31354
+ const colonIdx = line.indexOf(":");
31355
+ if (colonIdx === -1) {
31356
+ i++;
31357
+ continue;
31358
+ }
31359
+ const key4 = line.slice(0, colonIdx).trim();
31360
+ let value = line.slice(colonIdx + 1).trim();
31361
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
31362
+ value = value.slice(1, -1);
31363
+ result[key4] = value;
31364
+ i++;
31365
+ continue;
31366
+ } else if (value === "|" || value === ">") {
31367
+ const blockLines = [];
31368
+ i++;
31369
+ while (i < lines.length && lines[i].startsWith(" ")) {
31370
+ blockLines.push(lines[i].slice(2));
31371
+ i++;
31372
+ }
31373
+ result[key4] = blockLines.join("\n").trim();
31374
+ continue;
31375
+ } else if (value.startsWith("[") && value.endsWith("]")) {
31376
+ result[key4] = value.slice(1, -1).split(",").map((s) => s.trim());
31377
+ i++;
31378
+ continue;
31379
+ } else if (value.includes(" ") && !value.startsWith('"')) {
31380
+ result[key4] = value;
31381
+ } else {
31382
+ result[key4] = value;
31383
+ }
31384
+ i++;
31385
+ }
31386
+ return result;
31387
+ }
31388
+
31389
+ // src/tools/SkillTool/SkillTool.ts
31390
+ init_tokenEstimate();
31391
+ import { createHash as createHash34 } from "node:crypto";
31392
+ import * as fs22 from "node:fs";
31393
+ import * as path29 from "node:path";
31394
+ var skillsDirPath = "";
31395
+ var selectionCatalog = { entries: [], allowedNames: /* @__PURE__ */ new Set() };
31396
+ function getSkillSelectionCatalog() {
31397
+ return selectionCatalog;
31398
+ }
31399
+ var resolveSkillFn;
31400
+ function loadSkillContent(skillsDir, skill) {
31401
+ const skillMdPath = skill.location ? path29.join(skillsDir, skill.location.slice("skills/".length)) : path29.join(skillsDir, skill.name, "SKILL.md");
31402
+ if (!fs22.existsSync(skillMdPath)) return null;
31403
+ const content = fs22.readFileSync(skillMdPath, "utf-8");
31404
+ const dependencies = parseFrontmatter(content)["requires-tools"];
31405
+ const requiredTools = [...new Set((Array.isArray(dependencies) ? dependencies : typeof dependencies === "string" ? dependencies.split(/[\s,]+/) : []).filter((n) => typeof n === "string").map((n) => n.trim().replace(/^(['"])(.*)\1$/, "$2")).filter(Boolean))];
31406
+ const bodyMatch = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)/);
31407
+ const body = bodyMatch ? bodyMatch[1] : content;
31408
+ const skillDir = path29.dirname(skillMdPath);
31409
+ const normalizedDir = process.platform === "win32" ? skillDir.replace(/\\/g, "/") : skillDir;
31410
+ let finalContent = `Base directory for this skill: ${normalizedDir}
31411
+
31412
+ ${body}`;
31413
+ finalContent = finalContent.replace(/\$\{CLAUDE_SKILL_DIR\}/g, normalizedDir);
31414
+ finalContent = finalContent.replace(/\$\{CLAUDE_SESSION_ID\}/g, getSessionId());
31415
+ return { content: finalContent, requiredTools };
31416
+ }
31417
+ function getSessionId() {
31418
+ return String(process.pid);
31419
+ }
31420
+ var SKILL_FINGERPRINT_PREFIX = "[fingerprint ";
31421
+ var SKILL_RELOAD_DISTANCE_TOKENS = 16e3;
31422
+ function skillFingerprint(skill, body) {
31423
+ return createHash34("sha256").update(skill.location ?? skill.name).update("\0").update(body).digest("hex").slice(0, 16);
31424
+ }
31425
+ function findLoadedSkill(history, skill, fingerprint2, resolve13) {
31426
+ if (!history) return void 0;
31427
+ for (let i = history.length - 1; i >= 0; i--) {
31428
+ const message = history[i];
31429
+ if (!("role" in message) || message.role !== "tool" || message.is_error || typeof message.content !== "string") continue;
31430
+ let call;
31431
+ for (let j = i - 1; j >= 0 && !call; j--) {
31432
+ const previous = history[j];
31433
+ if ("role" in previous && previous.role === "assistant") call = (previous.tool_calls ?? []).find((c) => c.id === message.tool_call_id && c.function.name === SKILL_TOOL_NAME);
31434
+ }
31435
+ if (!call) continue;
31436
+ let args = {};
31437
+ try {
31438
+ args = JSON.parse(call.function.arguments);
31439
+ } catch {
31440
+ continue;
31441
+ }
31442
+ if (typeof args?.skill !== "string" || resolve13(args.skill.trim().replace(/^\//, "")) !== skill) continue;
31443
+ if (!message.content.includes(SKILL_FINGERPRINT_PREFIX + fingerprint2 + "]")) return void 0;
31444
+ return estimateMessageTokens(history.slice(i + 1)) <= SKILL_RELOAD_DISTANCE_TOKENS ? call.id : void 0;
31445
+ }
31446
+ return void 0;
31447
+ }
31448
+ function findLoadedSkillCall(history, skillName) {
31449
+ const resolve13 = resolveSkillFn;
31450
+ if (!history || !resolve13) return void 0;
31451
+ const skill = resolve13(skillName.trim().replace(/^\//, ""));
31452
+ if (!skill) return void 0;
31453
+ const content = loadSkillContent(skillsDirPath, skill);
31454
+ if (!content) return void 0;
31455
+ return findLoadedSkill(history, skill, skillFingerprint(skill, content.content), resolve13);
31456
+ }
31457
+
31204
31458
  // src/core/query.ts
31205
31459
  function blockedToolCallsForOverride(calls, override2) {
31206
31460
  if (!override2) return [];
@@ -31598,6 +31852,7 @@ var QueryEngine = class _QueryEngine {
31598
31852
  turnCount++;
31599
31853
  const steers = this.pendingSteers.splice(0);
31600
31854
  let steerConsumedThisTurn = false;
31855
+ let userSteerConsumedThisTurn = false;
31601
31856
  if (steers.length > 0) {
31602
31857
  for (const input of steers) {
31603
31858
  if (this.steerHistoryIds.has(input.id)) {
@@ -31629,6 +31884,7 @@ var QueryEngine = class _QueryEngine {
31629
31884
  if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
31630
31885
  this.steerHistoryIds.add(input.id);
31631
31886
  steerConsumedThisTurn = true;
31887
+ userSteerConsumedThisTurn = true;
31632
31888
  yield {
31633
31889
  type: "user_input",
31634
31890
  message: steerMsg,
@@ -31884,7 +32140,53 @@ var QueryEngine = class _QueryEngine {
31884
32140
  let turnAborted = false;
31885
32141
  try {
31886
32142
  wholeQueryAbort.signal.throwIfAborted();
31887
- const view = normalizeMessagesForAPI(currentMessages).map((m) => {
32143
+ const beforeRequest = () => {
32144
+ wholeQueryAbort.signal.throwIfAborted();
32145
+ ac.signal.throwIfAborted();
32146
+ };
32147
+ const startRequest = () => {
32148
+ this.phase = "streaming";
32149
+ assertRuntimeAuthority(void 0, "INPUT");
32150
+ if (perTurnOptions?.onRequestStarted) {
32151
+ const start = perTurnOptions.onRequestStarted;
32152
+ setImmediate(() => {
32153
+ if (!wholeQueryAbort.signal.aborted) start();
32154
+ });
32155
+ }
32156
+ };
32157
+ let selected;
32158
+ const selectionInput = perTurnOptions?.skillSelectionInput;
32159
+ const skill = turnCount === 1 && maxTurns >= 2 && !userSteerConsumedThisTurn && !hasPendingUserInput() && selectionInput ? allToolDefs.find((tool) => tool.function.name === SKILL_TOOL_NAME) : void 0;
32160
+ const catalog = skill ? getSkillSelectionCatalog() : void 0;
32161
+ if (skill && selectionInput && catalog?.entries.length) {
32162
+ const input = normalizeMessagesForAPI([selectionInput]);
32163
+ const started = performance.now();
32164
+ startRequest();
32165
+ const selection = await selectSkillCall(queryProvider, {
32166
+ preferFastFallback,
32167
+ model: queryModel,
32168
+ messages: input,
32169
+ tools: [skill],
32170
+ systemStable: SKILL_SELECTION_PROMPT + "\n\n" + JSON.stringify(catalog.entries),
32171
+ maxTokens: SKILL_SELECTION_MAX_TOKENS,
32172
+ signal: ac.signal,
32173
+ beforeRequest: () => {
32174
+ assertHostTurnCurrent();
32175
+ beforeRequest();
32176
+ },
32177
+ disableThinking: true
32178
+ }, catalog.allowedNames, recordUsage);
32179
+ assertHostTurnCurrent();
32180
+ beforeRequest();
32181
+ console.log(`${this.logPrefix} [skill-selection] ${selection.outcome} ms=${Math.round(performance.now() - started)}`);
32182
+ if (hasPendingUserInput()) continue;
32183
+ if (selection.outcome === "selected") {
32184
+ if (findLoadedSkillCall(currentMessages, selection.skill)) {
32185
+ console.log(`${this.logPrefix} [skill-selection] already-loaded ${selection.skill}`);
32186
+ } else selected = selection.chunks;
32187
+ }
32188
+ }
32189
+ const view = (selected ? [] : normalizeMessagesForAPI(currentMessages)).map((m) => {
31888
32190
  if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
31889
32191
  const blocks = m.content.filter((b) => {
31890
32192
  if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
@@ -31919,7 +32221,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
31919
32221
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
31920
32222
 
31921
32223
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31922
- if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
32224
+ if (!selected && (!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
31923
32225
  try {
31924
32226
  const ws = process.env.ENGINE7_WORKSPACE;
31925
32227
  if (ws) {
@@ -31935,15 +32237,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31935
32237
  } catch {
31936
32238
  }
31937
32239
  }
31938
- this.phase = "streaming";
31939
- assertRuntimeAuthority(void 0, "INPUT");
31940
- if (perTurnOptions?.onRequestStarted) {
31941
- const start = perTurnOptions.onRequestStarted;
31942
- setImmediate(() => {
31943
- if (!wholeQueryAbort.signal.aborted) start();
31944
- });
31945
- }
31946
- for await (const chunk of queryProvider.streamChat({
32240
+ if (!selected) startRequest();
32241
+ for await (const chunk of selected ?? queryProvider.streamChat({
31947
32242
  preferFastFallback,
31948
32243
  model: queryModel,
31949
32244
  messages: apiMessages,
@@ -31956,10 +32251,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31956
32251
  maxTokens: this.resolveRequestMaxTokens(apiMessages, maxTokensOverride),
31957
32252
  temperature: this.options.temperature,
31958
32253
  signal: ac.signal,
31959
- beforeRequest: () => {
31960
- wholeQueryAbort.signal.throwIfAborted();
31961
- ac.signal.throwIfAborted();
31962
- },
32254
+ beforeRequest,
31963
32255
  disableThinking: this.options.disableThinking || !!perTurnEmotion
31964
32256
  // 情感模式关 thinking(对齐 deskBuddy)
31965
32257
  })) {
@@ -32320,6 +32612,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
32320
32612
  if (vcDelivery) await vcDelivery;
32321
32613
  }
32322
32614
  const { messages: toolResults, summaries } = toolRes;
32615
+ if (selected) console.log(`${this.logPrefix} [skill-selection] ${summaries.length === 1 && !summaries[0].isError ? "loaded" : "load-failed"}`);
32323
32616
  if (collectStopEvidence) stopToolResults.push(...summaries);
32324
32617
  for (const s of summaries) {
32325
32618
  try {
@@ -32617,9 +32910,9 @@ function readState(stateFile) {
32617
32910
  return { lastPatrolAt: 0, lastLineCounts: {} };
32618
32911
  }
32619
32912
  function writeState(stateFile, state) {
32620
- const dir = path30.dirname(stateFile);
32913
+ const dir = path31.dirname(stateFile);
32621
32914
  fsSync3.mkdirSync(dir, { recursive: true });
32622
- const tmp = path30.join(dir, `.${path30.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
32915
+ const tmp = path31.join(dir, `.${path31.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
32623
32916
  try {
32624
32917
  fsSync3.writeFileSync(tmp, JSON.stringify(state), "utf-8");
32625
32918
  fsSync3.renameSync(tmp, stateFile);
@@ -32648,7 +32941,7 @@ function buildPatrolPrompt(materials) {
32648
32941
  ].join("\n");
32649
32942
  }
32650
32943
  function defaultWriteMemoryNote(workspace) {
32651
- const dir = path30.join(getAutoMemPath(workspace), "whatsapp-patrol");
32944
+ const dir = path31.join(getAutoMemPath(workspace), "whatsapp-patrol");
32652
32945
  return (note) => {
32653
32946
  fsSync3.mkdirSync(dir, { recursive: true });
32654
32947
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
@@ -32662,7 +32955,7 @@ function defaultWriteMemoryNote(workspace) {
32662
32955
  note,
32663
32956
  ""
32664
32957
  ].join("\n");
32665
- fsSync3.writeFileSync(path30.join(dir, `patrol-${stamp}.md`), body, "utf-8");
32958
+ fsSync3.writeFileSync(path31.join(dir, `patrol-${stamp}.md`), body, "utf-8");
32666
32959
  };
32667
32960
  }
32668
32961
  function makeSubmitToMain(engineDeps) {
@@ -32807,15 +33100,15 @@ ${quoted}`);
32807
33100
 
32808
33101
  // src/utils/ffmpeg-path.ts
32809
33102
  init_dep_downloader();
32810
- import * as fs23 from "node:fs";
33103
+ import * as fs24 from "node:fs";
32811
33104
  function resolveFfmpegPath() {
32812
33105
  const env = (process.env.E7_FFMPEG_PATH || "").trim();
32813
- if (env && fs23.existsSync(env)) return env;
33106
+ if (env && fs24.existsSync(env)) return env;
32814
33107
  const downloaded = optionalFfmpegPath();
32815
33108
  if (downloaded) return downloaded;
32816
33109
  try {
32817
33110
  const p = __require("@ffmpeg-installer/ffmpeg")?.path;
32818
- if (p && fs23.existsSync(p)) return p;
33111
+ if (p && fs24.existsSync(p)) return p;
32819
33112
  } catch {
32820
33113
  }
32821
33114
  return "ffmpeg";
@@ -32901,10 +33194,10 @@ function normalizeAllowEntry(entry) {
32901
33194
  }
32902
33195
  function atomicWriteFile(dir, fileName, content) {
32903
33196
  fsSync4.mkdirSync(dir, { recursive: true });
32904
- const tmp = path31.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID18().slice(0, 8)}`);
33197
+ const tmp = path32.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID18().slice(0, 8)}`);
32905
33198
  try {
32906
33199
  fsSync4.writeFileSync(tmp, content, "utf-8");
32907
- fsSync4.renameSync(tmp, path31.join(dir, fileName));
33200
+ fsSync4.renameSync(tmp, path32.join(dir, fileName));
32908
33201
  } catch (e) {
32909
33202
  try {
32910
33203
  fsSync4.rmSync(tmp, { force: true });
@@ -33019,13 +33312,13 @@ var WhatsAppAdapter = class {
33019
33312
  constructor(cfg, opts = {}) {
33020
33313
  this.cfg = cfg;
33021
33314
  this.stateDir = cfg.stateDir;
33022
- this.authDir = path31.join(cfg.stateDir, "whatsapp-auth");
33023
- this.qrFilePath = path31.join(cfg.stateDir, "whatsapp-qr.txt");
33315
+ this.authDir = path32.join(cfg.stateDir, "whatsapp-auth");
33316
+ this.qrFilePath = path32.join(cfg.stateDir, "whatsapp-qr.txt");
33024
33317
  this.opts = opts;
33025
33318
  this.credsStore = opts.credsStoreOverride ?? makeCredsStore(this.authDir);
33026
33319
  this.loginTtlMs = opts.loginTtlMs ?? LOGIN_TTL_MS;
33027
33320
  this.digestEnabled = cfg.groupDigest?.enabled !== false;
33028
- this.digest = this.digestEnabled ? new GroupDigestStore(path31.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
33321
+ this.digest = this.digestEnabled ? new GroupDigestStore(path32.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
33029
33322
  this.typing = new PresenceTypingCoalescer(async (jid) => {
33030
33323
  const sock = this.sock;
33031
33324
  if (!sock || typeof sock.sendPresenceUpdate !== "function") return;
@@ -33160,7 +33453,7 @@ var WhatsAppAdapter = class {
33160
33453
  this.patrol = startPatrolLoop({
33161
33454
  digest: this.digest,
33162
33455
  intervalMin: this.cfg.groupDigest?.patrolIntervalMin ?? 60,
33163
- stateFile: path31.join(this.stateDir, "whatsapp-patrol-state.json"),
33456
+ stateFile: path32.join(this.stateDir, "whatsapp-patrol-state.json"),
33164
33457
  runReadOnlyAgent: makeReadOnlyAgentRunner(this.opts.patrolDeps),
33165
33458
  // ⚠️ 升级接线(终审 C1,1003):摘要含 ⚠️ 行时宿主经主 session 投递(spec §4)——
33166
33459
  // makeSubmitToMain 吃的正是 patrolDeps {dispatcher, deps}(patrol.ts)形状。漏接这行 =
@@ -33457,11 +33750,11 @@ ${r}` : r;
33457
33750
  const idRaw = typeof raw?.key?.id === "string" && raw.key.id ? raw.key.id : "";
33458
33751
  const idSafe = idRaw.replace(/[^\w.-]/g, "_");
33459
33752
  const id3 = !idRaw || idSafe !== idRaw || !idSafe ? randomUUID18() : idSafe;
33460
- const dir = path31.join(this.stateDir, "media", "whatsapp");
33753
+ const dir = path32.join(this.stateDir, "media", "whatsapp");
33461
33754
  fsSync4.mkdirSync(dir, { recursive: true });
33462
- const abs = path31.join(dir, `${id3}.${ext}`);
33463
- const resolved = path31.resolve(abs);
33464
- if (!resolved.startsWith(path31.resolve(dir) + path31.sep)) {
33755
+ const abs = path32.join(dir, `${id3}.${ext}`);
33756
+ const resolved = path32.resolve(abs);
33757
+ if (!resolved.startsWith(path32.resolve(dir) + path32.sep)) {
33465
33758
  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}`);
33466
33759
  return `${placeholder}\uFF08\u4E0B\u8F7D\u5931\u8D25\uFF09`;
33467
33760
  }
@@ -33495,7 +33788,7 @@ ${r}` : r;
33495
33788
  const lids = [jid, participant].filter((j) => j.endsWith("@lid"));
33496
33789
  if (lids.length === 0) return;
33497
33790
  try {
33498
- const filePath2 = path31.join(this.authDir, "lid-mapping.json");
33791
+ const filePath2 = path32.join(this.authDir, "lid-mapping.json");
33499
33792
  let arr = [];
33500
33793
  try {
33501
33794
  const parsed = JSON.parse(fsSync4.readFileSync(filePath2, "utf-8"));
@@ -33605,7 +33898,7 @@ ${r}` : r;
33605
33898
  if (isGroupJid(jid)) throw new Error(`WhatsApp \u7FA4\u53D1\u9001\u7269\u7406\u4E0D\u5B58\u5728\uFF08\u7EA2\u7EBF\uFF09\uFF1Atarget=${jid}`);
33606
33899
  const sock = this.requireSock();
33607
33900
  const mime = attachment.mimeType ?? "";
33608
- const filename = attachment.filename ?? path31.basename(attachment.path);
33901
+ const filename = attachment.filename ?? path32.basename(attachment.path);
33609
33902
  if (mime.startsWith("image/")) {
33610
33903
  assertExternalEffectCurrent();
33611
33904
  const res2 = await sock.sendMessage(jid, { image: { url: attachment.path }, caption: message });
@@ -33634,8 +33927,8 @@ ${r}` : r;
33634
33927
  this.recordEcho(res2);
33635
33928
  return;
33636
33929
  }
33637
- const tmpDir = path31.join(this.stateDir, "whatsapp-media-tmp");
33638
- const dst = path31.join(tmpDir, `${randomUUID18()}.ogg`);
33930
+ const tmpDir = path32.join(this.stateDir, "whatsapp-media-tmp");
33931
+ const dst = path32.join(tmpDir, `${randomUUID18()}.ogg`);
33639
33932
  try {
33640
33933
  await (this.cfg.ffmpegTranscode ?? defaultFfmpegTranscode)(attachment.path, dst);
33641
33934
  assertExternalEffectCurrent();
@@ -33750,9 +34043,9 @@ function quotedTextOf(content) {
33750
34043
  }
33751
34044
 
33752
34045
  // src/channels/dingtalk.ts
33753
- import fs24 from "node:fs";
33754
- import path32 from "node:path";
33755
- import { createHash as createHash34, randomUUID as randomUUID19 } from "node:crypto";
34046
+ import fs25 from "node:fs";
34047
+ import path33 from "node:path";
34048
+ import { createHash as createHash35, randomUUID as randomUUID19 } from "node:crypto";
33756
34049
 
33757
34050
  // src/channels/dingtalk-stream.ts
33758
34051
  import { EventEmitter } from "node:events";
@@ -34344,13 +34637,13 @@ var DingTalkAdapter = class _DingTalkAdapter {
34344
34637
  const res = await this.baseFetch(url, { signal: AbortSignal.timeout(3e4) });
34345
34638
  if (!res.ok) throw new Error(`media download HTTP ${res.status}`);
34346
34639
  const buf = Buffer.from(await res.arrayBuffer());
34347
- const dir = path32.join(this.cfg.stateDir, "media", "dingtalk");
34348
- fs24.mkdirSync(dir, { recursive: true });
34640
+ const dir = path33.join(this.cfg.stateDir, "media", "dingtalk");
34641
+ fs25.mkdirSync(dir, { recursive: true });
34349
34642
  const ext = m.kind === "image" ? "png" : m.kind === "video" ? "mp4" : "bin";
34350
- const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash34("sha1").update(m.code).digest("hex").slice(0, 12);
34643
+ const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash35("sha1").update(m.code).digest("hex").slice(0, 12);
34351
34644
  const safeCode = raw.replace(/[^a-zA-Z0-9_-]/g, "_");
34352
- const local = path32.join(dir, `${safeCode}.${ext}`);
34353
- fs24.writeFileSync(local, buf);
34645
+ const local = path33.join(dir, `${safeCode}.${ext}`);
34646
+ fs25.writeFileSync(local, buf);
34354
34647
  out.push({
34355
34648
  url: `file://${local}`,
34356
34649
  filename: m.filename ?? `${safeCode}.${ext}`,
@@ -34423,8 +34716,8 @@ var DingTalkAdapter = class _DingTalkAdapter {
34423
34716
  async sendFileNow(target, message, attachment) {
34424
34717
  const entry = this.registry.get(target);
34425
34718
  const robotCode = this.cfg.robotCode ?? this.cfg.clientId;
34426
- const buf = fs24.readFileSync(attachment.path);
34427
- const filename = (attachment.filename ?? path32.basename(attachment.path)).slice(0, 100);
34719
+ const buf = fs25.readFileSync(attachment.path);
34720
+ const filename = (attachment.filename ?? path33.basename(attachment.path)).slice(0, 100);
34428
34721
  const isImage = (attachment.mimeType ?? "").startsWith("image/") || /\.(png|jpe?g|gif|webp|bmp)$/i.test(filename);
34429
34722
  const mediaId = await this.uploadMedia(buf, filename, isImage ? "image" : "file");
34430
34723
  const msgKey = isImage ? "sampleImageMsg" : "sampleFileMsg";
@@ -34789,7 +35082,7 @@ var DING_EDIT_INTERVAL_MS = 300;
34789
35082
  // src/channels/wecom-stream.ts
34790
35083
  import { EventEmitter as EventEmitter2 } from "node:events";
34791
35084
  import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
34792
- import { createHash as createHash35 } from "node:crypto";
35085
+ import { createHash as createHash36 } from "node:crypto";
34793
35086
  var WECOM_WS_URL = "wss://openws.work.weixin.qq.com";
34794
35087
  var HEARTBEAT_MS2 = 3e4;
34795
35088
  var ACK_TIMEOUT_MS = 15e3;
@@ -35141,7 +35434,7 @@ var WecomStreamClient = class extends EventEmitter2 {
35141
35434
  if (!data.length) throw new Error("wecom uploadMedia: empty buffer");
35142
35435
  const totalChunks = Math.ceil(data.length / UPLOAD_CHUNK_BYTES);
35143
35436
  if (totalChunks > MAX_UPLOAD_CHUNKS) throw new Error(`wecom uploadMedia: too large (${totalChunks} chunks > ${MAX_UPLOAD_CHUNKS})`);
35144
- const md5 = createHash35("md5").update(data).digest("hex");
35437
+ const md5 = createHash36("md5").update(data).digest("hex");
35145
35438
  const initRes = await this.sendCommand("aibot_upload_media_init", {
35146
35439
  type,
35147
35440
  filename,
@@ -35168,9 +35461,9 @@ var WecomStreamClient = class extends EventEmitter2 {
35168
35461
 
35169
35462
  // src/channels/wecom.ts
35170
35463
  import { createDecipheriv as createDecipheriv3, randomUUID as randomUUID20 } from "node:crypto";
35171
- import { readFileSync as readFileSync17 } from "node:fs";
35464
+ import { readFileSync as readFileSync18 } from "node:fs";
35172
35465
  import { mkdir as mkdir4, readFile, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
35173
- import path33 from "node:path";
35466
+ import path34 from "node:path";
35174
35467
  var WECOM_CONTENT_BYTES = 20480;
35175
35468
  var DEFAULT_MERGE_WINDOW_MS = 600;
35176
35469
  var REPLY_WINDOW_MS = 24 * 60 * 60 * 1e3;
@@ -35356,7 +35649,7 @@ var WecomAdapter = class {
35356
35649
  this.now = cfg.now ?? Date.now;
35357
35650
  this.sleepImpl = cfg.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
35358
35651
  this.fetchImpl = cfg.fetchImpl ?? fetch;
35359
- this.routesFile = path33.join(cfg.stateDir, "state", ROUTES_FILE);
35652
+ this.routesFile = path34.join(cfg.stateDir, "state", ROUTES_FILE);
35360
35653
  }
35361
35654
  /**
35362
35655
  * 载入落盘会话路由(1007:真机事故——注册表原本只存内存,引擎一重启"谁跟我说过话"全丢,
@@ -35372,7 +35665,7 @@ var WecomAdapter = class {
35372
35665
  this.routesLoaded = true;
35373
35666
  let raw;
35374
35667
  try {
35375
- raw = JSON.parse(readFileSync17(this.routesFile, "utf8"));
35668
+ raw = JSON.parse(readFileSync18(this.routesFile, "utf8"));
35376
35669
  } catch (e) {
35377
35670
  if (e?.code !== "ENOENT") console.warn(`[wecom] \u8DEF\u7531\u8868\u8BFB\u53D6\u5931\u8D25\uFF08\u6309\u7A7A\u8868\u542F\u52A8\uFF0C\u4E0D\u5F71\u54CD\u88AB\u52A8\u56DE\u590D\uFF09\uFF1A${e?.message ?? e}`);
35378
35671
  return;
@@ -35400,7 +35693,7 @@ var WecomAdapter = class {
35400
35693
  try {
35401
35694
  const routes = {};
35402
35695
  for (const [chatId, e] of this.registry) routes[chatId] = { chatType: e.chatType, userId: e.userId };
35403
- await mkdir4(path33.dirname(this.routesFile), { recursive: true });
35696
+ await mkdir4(path34.dirname(this.routesFile), { recursive: true });
35404
35697
  await writeFile4(this.routesFile, JSON.stringify({ version: 1, routes }, null, 2) + "\n", "utf8");
35405
35698
  } catch (e) {
35406
35699
  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}`);
@@ -35686,7 +35979,7 @@ ${parsed.inbound.content}`;
35686
35979
  /** 入站媒体:下载 → aeskey 解密 → 落盘 → 附件(单条失败不拖垮整条消息;全部失败给 content 加标记)。
35687
35980
  * 本地文件名一律由 msgid 派生(远端 filename 只做显示名)——防同名互相覆盖/超长(钉钉 1004 同款纪律)。 */
35688
35981
  async resolveInboundMedia(parsed) {
35689
- const dir = path33.join(this.cfg.stateDir, "media", "wecom");
35982
+ const dir = path34.join(this.cfg.stateDir, "media", "wecom");
35690
35983
  const attachments = [];
35691
35984
  let failed = 0;
35692
35985
  for (const [i, ref] of parsed.media.entries()) {
@@ -35698,7 +35991,7 @@ ${parsed.inbound.content}`;
35698
35991
  const data = ref.aeskey ? decryptWecomMedia(raw, ref.aeskey) : raw;
35699
35992
  const ext = ref.filename?.includes(".") ? ref.filename.split(".").pop().toLowerCase().slice(0, 8) : ref.kind === "image" ? "jpg" : ref.kind === "video" ? "mp4" : "bin";
35700
35993
  const localName = `wecom-${(parsed.msgId || String(this.now())).replace(/[^0-9A-Za-z_-]/g, "").slice(0, 32)}-${i}.${ext}`;
35701
- const file2 = path33.join(dir, localName);
35994
+ const file2 = path34.join(dir, localName);
35702
35995
  await writeFile4(file2, data);
35703
35996
  const displayName = (ref.filename || localName).slice(0, 120);
35704
35997
  attachments.push({
@@ -35729,7 +36022,7 @@ ${parsed.inbound.content}`;
35729
36022
  const entry = this.registry.get(target);
35730
36023
  if (!entry) throw new Error(`[wecom] \u65E0\u6CD5\u8DEF\u7531\u5A92\u4F53\u5230 ${target}\uFF08\u65E0\u4F1A\u8BDD\u6CE8\u518C\u8BB0\u5F55\uFF09`);
35731
36024
  await this.takeToken(target, false);
35732
- const filename = attachment.filename ?? path33.basename(attachment.path);
36025
+ const filename = attachment.filename ?? path34.basename(attachment.path);
35733
36026
  const { mediaId } = await this.requireStream().uploadMedia(data, type, filename);
35734
36027
  const body = type === "video" ? { msgtype: "video", video: { media_id: mediaId, title: filename } } : { msgtype: type, [type]: { media_id: mediaId } };
35735
36028
  await this.respondOrSend(entry, target, body);
@@ -35993,7 +36286,7 @@ import { randomUUID as randomUUID21 } from "node:crypto";
35993
36286
  // src/continuity/gateway-channel.ts
35994
36287
  init_gateway_media();
35995
36288
  import { mkdtempSync, writeFileSync as writeFileSync14, rmSync as rmSync2, realpathSync as realpathSync5 } from "node:fs";
35996
- import { join as join31 } from "node:path";
36289
+ import { join as join32 } from "node:path";
35997
36290
  import { tmpdir as tmpdir3 } from "node:os";
35998
36291
  function splitChannelGatewayText(text2, channel) {
35999
36292
  if (typeof text2 !== "string" || Buffer.byteLength(text2) > 1024 * 1024) throw new Error("TRAVEL_GATEWAY_REPLY_LIMIT");
@@ -36048,7 +36341,7 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
36048
36341
  if (!media) await adapter.send(packet.target, packet.text, { replyTo: packet.replyTo });
36049
36342
  else {
36050
36343
  if (!adapter.sendFile) throw new Error("TRAVEL_GATEWAY_MEDIA_UNAVAILABLE");
36051
- const directory2 = realpathSync5(mkdtempSync(join31(tmpdir3(), "e7-gateway-media-"))), file2 = join31(directory2, packet.filename);
36344
+ const directory2 = realpathSync5(mkdtempSync(join32(tmpdir3(), "e7-gateway-media-"))), file2 = join32(directory2, packet.filename);
36052
36345
  try {
36053
36346
  writeFileSync14(file2, media.bytes, { mode: 384 });
36054
36347
  await adapter.sendFile(packet.target, packet.text, { path: file2, filename: packet.filename, mimeType: packet.mimeType, voiceDurationSec: packet.voiceDurationSec });
@@ -36474,9 +36767,9 @@ var RemoteTravelChannel = class {
36474
36767
  };
36475
36768
 
36476
36769
  // src/channels/private-library.ts
36477
- import fs25 from "node:fs/promises";
36478
- import path34 from "node:path";
36479
- import { createHash as createHash36 } from "node:crypto";
36770
+ import fs26 from "node:fs/promises";
36771
+ import path35 from "node:path";
36772
+ import { createHash as createHash37 } from "node:crypto";
36480
36773
 
36481
36774
  // src/channels/chan7-content.ts
36482
36775
  function fileMime(name) {
@@ -36488,8 +36781,8 @@ function fileMime(name) {
36488
36781
  function archive(manager, name, mime, bytes2, role, caption, identity) {
36489
36782
  const adapter = manager.getAdapter("chan7");
36490
36783
  if (!adapter?.files || bytes2.length > 16 * 1024 * 1024) return;
36491
- const safeName = path34.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
36492
- const key4 = createHash36("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
36784
+ const safeName = path35.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
36785
+ const key4 = createHash37("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
36493
36786
  try {
36494
36787
  adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key4);
36495
36788
  } catch (e) {
@@ -36499,9 +36792,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
36499
36792
  async function archivePrivateOutbound(manager, channel, target, text2, attachment, origin) {
36500
36793
  if (channel === "chan7" || origin?.channelType !== "dm" || origin.inboundIsBot || origin.channel !== channel || origin.channelTarget !== target || !manager.getAdapter("chan7")?.files) return;
36501
36794
  try {
36502
- const stat3 = await fs25.stat(attachment.path);
36795
+ const stat3 = await fs26.stat(attachment.path);
36503
36796
  if (!stat3.isFile() || stat3.size > 16 * 1024 * 1024) return;
36504
- const bytes2 = await fs25.readFile(attachment.path), name = attachment.filename ?? path34.basename(attachment.path);
36797
+ const bytes2 = await fs26.readFile(attachment.path), name = attachment.filename ?? path35.basename(attachment.path);
36505
36798
  archive(
36506
36799
  manager,
36507
36800
  name,
@@ -36516,6 +36809,63 @@ async function archivePrivateOutbound(manager, channel, target, text2, attachmen
36516
36809
  }
36517
36810
  }
36518
36811
 
36812
+ // src/channels/loop-guard.ts
36813
+ var MAX_COMPARE_LEN = 60;
36814
+ var MAX_REPEAT = 3;
36815
+ var SIMILARITY_THRESHOLD = 0.8;
36816
+ var HISTORY_SIZE = 5;
36817
+ var LoopBlockedError = class extends Error {
36818
+ constructor(target, repeated) {
36819
+ super(`loop-guard blocked: \u5411 ${target} \u8FDE\u7EED ${repeated} \u6761\u540C\u8D28\u6D88\u606F`);
36820
+ this.target = target;
36821
+ this.repeated = repeated;
36822
+ this.name = "LoopBlockedError";
36823
+ }
36824
+ };
36825
+ var states = /* @__PURE__ */ new Map();
36826
+ function normalize6(text2) {
36827
+ return text2.replace(/[\s\u3000]/g, "").replace(/[。,、!?;:""''()()\[\]【】…~~\-—.,!?;:'"]/g, "").toLowerCase();
36828
+ }
36829
+ function similarity(a, b) {
36830
+ if (!a && !b) return 1;
36831
+ if (!a || !b) return 0;
36832
+ const setA = new Set(a);
36833
+ const setB = new Set(b);
36834
+ let inter = 0;
36835
+ for (const ch of setA) if (setB.has(ch)) inter++;
36836
+ const union = setA.size + setB.size - inter;
36837
+ return union === 0 ? 1 : inter / union;
36838
+ }
36839
+ function isSameKind(a, b) {
36840
+ if (a === b) return true;
36841
+ return similarity(a, b) >= SIMILARITY_THRESHOLD;
36842
+ }
36843
+ function checkOutbound(channelName, target, message) {
36844
+ const text2 = message.trim();
36845
+ if (!text2 || text2.length > MAX_COMPARE_LEN) {
36846
+ if (text2) states.delete(`${channelName}:${target}`);
36847
+ return true;
36848
+ }
36849
+ const key4 = `${channelName}:${target}`;
36850
+ const norm = normalize6(text2);
36851
+ const state = states.get(key4) ?? { recent: [] };
36852
+ let repeated = 1;
36853
+ for (let i = state.recent.length - 1; i >= 0; i--) {
36854
+ if (isSameKind(state.recent[i], norm)) repeated++;
36855
+ else break;
36856
+ }
36857
+ if (repeated >= MAX_REPEAT) {
36858
+ console.warn(
36859
+ `[loop-guard] BLOCKED channel=${channelName} target=${target} repeated=${repeated} text=${text2.slice(0, 40)}`
36860
+ );
36861
+ return false;
36862
+ }
36863
+ state.recent.push(norm);
36864
+ if (state.recent.length > HISTORY_SIZE) state.recent.shift();
36865
+ states.set(key4, state);
36866
+ return true;
36867
+ }
36868
+
36519
36869
  // src/channels/manager.ts
36520
36870
  var MANAGED_CHANNEL_NAMES = ["discord", "feishu", "wechat", "deskBuddy", "ccBridge", "telegram", "whatsapp", "dingtalk", "wecom"];
36521
36871
  var defaultFactories = {
@@ -36894,6 +37244,9 @@ var ChannelManager = class {
36894
37244
  if (!adapter) {
36895
37245
  throw new Error(`No adapter for ${channelName}`);
36896
37246
  }
37247
+ if (!checkOutbound(channelName, target, message)) {
37248
+ throw new LoopBlockedError(target, 3);
37249
+ }
36897
37250
  try {
36898
37251
  if (hasMemoryEffectContext() && (!adapter.memoryGuardedSends || hasAutomaticMemoryEffectContext() && adapter.memoryGuardedAutomation === false)) throw new Error(`MEMORY_EXECUTION_BLOCKED: adapter ${channelName} has no final send guard`);
36899
37252
  await guardedExternalEffect(() => adapter.send(target, message, options));
@@ -36991,12 +37344,12 @@ var quiet2 = { error: () => {
36991
37344
  }, debug: () => {
36992
37345
  }, trace: () => {
36993
37346
  } };
36994
- function path35(value) {
37347
+ function path36(value) {
36995
37348
  if (typeof value !== "string" || !isAbsolute5(value)) throw new Error("TRAVEL_GATEWAY_ABSOLUTE_PATH_REQUIRED");
36996
37349
  return resolve11(value);
36997
37350
  }
36998
37351
  function tls2(config) {
36999
- return { ca: readPrivateFile(path35(config?.caFile), 1024 * 1024), cert: readPrivateFile(path35(config?.certFile), 1024 * 1024), key: readPrivateFile(path35(config?.keyFile), 16384) };
37352
+ return { ca: readPrivateFile(path36(config?.caFile), 1024 * 1024), cert: readPrivateFile(path36(config?.certFile), 1024 * 1024), key: readPrivateFile(path36(config?.keyFile), 16384) };
37000
37353
  }
37001
37354
  async function startTravelGateway(config) {
37002
37355
  if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key4) => config.identity[key4] !== config.keyService.identity[key4])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
@@ -37006,7 +37359,7 @@ async function startTravelGateway(config) {
37006
37359
  if (feishuIngress && !/^cli_[0-9a-fA-F]{16}$/.test(config.feishu?.appId)) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
37007
37360
  const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls2(config.keyService.tls), timeoutMs: 1e4 };
37008
37361
  const material = await fetchTravelKey(keyConfig);
37009
- const keyDigest = createHash37("sha256").update(material.key).digest("hex");
37362
+ const keyDigest = createHash38("sha256").update(material.key).digest("hex");
37010
37363
  let keyWatermark = material.deletionWatermark;
37011
37364
  const refreshInterval = config.keyRefreshIntervalMs ?? 1e4, maxKeyAge = config.keyMaxAgeMs ?? 3e4;
37012
37365
  if (!Number.isSafeInteger(refreshInterval) || refreshInterval < 100 || refreshInterval > 1e4 || !Number.isSafeInteger(maxKeyAge) || maxKeyAge < 2 * refreshInterval || maxKeyAge > 3e4) {
@@ -37047,14 +37400,14 @@ async function startTravelGateway(config) {
37047
37400
  }
37048
37401
  };
37049
37402
  try {
37050
- objects = await PublicationObjects.open({ directory: path35(config.objectsDir), identity: config.identity, key: material.key });
37051
- authority = new TravelAuthority({ directory: path35(config.authorityDir), leaseMs: config.leaseMs });
37403
+ objects = await PublicationObjects.open({ directory: path36(config.objectsDir), identity: config.identity, key: material.key });
37404
+ authority = new TravelAuthority({ directory: path36(config.authorityDir), leaseMs: config.leaseMs });
37052
37405
  if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
37053
37406
  for (const credential of Object.values(config.allowedPeers)) {
37054
37407
  const principal = authority.authenticate(String(credential));
37055
37408
  if (["tenantId", "companionId", "seatId"].some((key4) => principal[key4] !== config.identity[key4]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
37056
37409
  }
37057
- store = new TravelGatewayStore({ directory: path35(config.gatewayDir), identity: config.identity, objects, authority });
37410
+ store = new TravelGatewayStore({ directory: path36(config.gatewayDir), identity: config.identity, objects, authority });
37058
37411
  await store.migrateStoredInputs();
37059
37412
  if (config.previouslyProcessedPlatformIds) store.importProcessedInputs(config.previouslyProcessedPlatformIds);
37060
37413
  platform = createFeishuGatewayPlatform(config.feishu);
@@ -37108,7 +37461,7 @@ async function startTravelGateway(config) {
37108
37461
  }
37109
37462
  });
37110
37463
  if (config.channels && config.ingressEnabled !== false) {
37111
- adapters.setFactoryContext({ stateDir: path35(config.platformStateDir) });
37464
+ adapters.setFactoryContext({ stateDir: path36(config.platformStateDir) });
37112
37465
  adapters.loadFromConfig(Object.fromEntries(Object.entries(config.channels).filter(([name, value]) => name !== "feishu" && value.enabled)));
37113
37466
  for (const channel of ["discord", "wechat"]) {
37114
37467
  const adapter = adapters.getAdapter(channel);
@@ -37171,7 +37524,7 @@ async function startTravelGateway(config) {
37171
37524
  checking = true;
37172
37525
  void fetchTravelKey(keyConfig).then((current2) => {
37173
37526
  try {
37174
- if (!objects || createHash37("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
37527
+ if (!objects || createHash38("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
37175
37528
  keyWatermark = current2.deletionWatermark;
37176
37529
  lastKeyCheck = Number(process.hrtime.bigint() / 1000000n);
37177
37530
  } finally {
@@ -37194,7 +37547,7 @@ async function startTravelGateway(config) {
37194
37547
  async function runTravelGatewayCli(args) {
37195
37548
  if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-gateway serve --config /absolute/private-config.json" };
37196
37549
  if (args.length !== 3 || args[0] !== "serve" || args[1] !== "--config") throw new Error("TRAVEL_GATEWAY_INVALID_COMMAND");
37197
- const config = JSON.parse(readPrivateFile(path35(args[2]), 65536).toString());
37550
+ const config = JSON.parse(readPrivateFile(path36(args[2]), 65536).toString());
37198
37551
  const gateway = await startTravelGateway(config);
37199
37552
  let closing = false;
37200
37553
  const stop = () => {
@@ -37215,12 +37568,12 @@ if (process.argv[1] && /[\\/](gateway-main\.ts|travel-gateway\.mjs)$/.test(proce
37215
37568
 
37216
37569
  // src/continuity/pairing-control.ts
37217
37570
  async function startPairingControl(config) {
37218
- const directory2 = resolve12(config.directory), file2 = join32(directory2, "pairing.json"), read2 = (name) => readPrivateFile(join32(directory2, name), 65536);
37571
+ const directory2 = resolve12(config.directory), file2 = join33(directory2, "pairing.json"), read2 = (name) => readPrivateFile(join33(directory2, name), 65536);
37219
37572
  const tls3 = { ca: read2("ca.pem"), cert: read2("server.pem"), key: read2("server.key") };
37220
- const authority = new TravelAuthority({ directory: join32(directory2, "authority") });
37573
+ const authority = new TravelAuthority({ directory: join33(directory2, "authority") });
37221
37574
  let binding;
37222
37575
  try {
37223
- if (existsSync15(file2)) {
37576
+ if (existsSync16(file2)) {
37224
37577
  binding = JSON.parse(readPrivateFile(file2, 65536).toString());
37225
37578
  if (JSON.stringify(binding.identity) !== JSON.stringify(config.identity) || binding.buildManifestId !== config.buildManifestId || binding.keySha256 !== config.keySha256) throw new Error("TRAVEL_PAIRING_IDENTITY");
37226
37579
  for (const name of ["local", "cloud"]) if (JSON.stringify(authority.authenticate(binding.tokens[name])) !== JSON.stringify(binding[name])) throw new Error("TRAVEL_PAIRING_IDENTITY");
@@ -37232,10 +37585,10 @@ async function startPairingControl(config) {
37232
37585
  } finally {
37233
37586
  authority.close();
37234
37587
  }
37235
- const keys = new KeyServiceStore(join32(directory2, "keys"));
37588
+ const keys = new KeyServiceStore(join33(directory2, "keys"));
37236
37589
  const key4 = read2("data.key");
37237
37590
  try {
37238
- if (createHash38("sha256").update(key4).digest("hex") !== config.keySha256) throw new Error("TRAVEL_PAIRING_KEY");
37591
+ if (createHash39("sha256").update(key4).digest("hex") !== config.keySha256) throw new Error("TRAVEL_PAIRING_KEY");
37239
37592
  try {
37240
37593
  keys.assertIdentity(binding.keyIdentity);
37241
37594
  } catch {
@@ -37256,13 +37609,13 @@ async function startPairingControl(config) {
37256
37609
  const fp = (name) => new X509Certificate(read2(name + ".pem")).fingerprint256.replaceAll(":", "").toLowerCase();
37257
37610
  const peers = { [fp("local")]: binding.tokens.local, [fp("cloud")]: binding.tokens.cloud };
37258
37611
  const managers = { [fp("manager")]: [binding.tokens.local, binding.tokens.cloud], [fp("local")]: [binding.tokens.local, binding.tokens.cloud], [fp("cloud")]: [binding.tokens.cloud, binding.tokens.local] };
37259
- const tlsFiles = { caFile: join32(directory2, "ca.pem"), certFile: join32(directory2, "server.pem"), keyFile: join32(directory2, "server.key") };
37260
- const managerTls = { ...tlsFiles, certFile: join32(directory2, "manager.pem"), keyFile: join32(directory2, "manager.key") };
37612
+ const tlsFiles = { caFile: join33(directory2, "ca.pem"), certFile: join33(directory2, "server.pem"), keyFile: join33(directory2, "server.key") };
37613
+ const managerTls = { ...tlsFiles, certFile: join33(directory2, "manager.pem"), keyFile: join33(directory2, "manager.key") };
37261
37614
  const gatewayConfig = {
37262
37615
  identity: config.identity,
37263
- authorityDir: join32(directory2, "authority"),
37264
- gatewayDir: join32(directory2, "gateway"),
37265
- objectsDir: join32(directory2, "objects"),
37616
+ authorityDir: join33(directory2, "authority"),
37617
+ gatewayDir: join33(directory2, "gateway"),
37618
+ objectsDir: join33(directory2, "objects"),
37266
37619
  tls: tlsFiles,
37267
37620
  host: "127.0.0.1",
37268
37621
  port: config.ports.gateway,
@@ -37270,12 +37623,12 @@ async function startPairingControl(config) {
37270
37623
  control: { host: "127.0.0.1", port: config.ports.authority, tls: tlsFiles, allowedPeers: peers, managementPeers: managers, recoveryPeers: managers, retirementPeers: { [fp("manager")]: [binding.tokens.local] } },
37271
37624
  allowedPeers: peers,
37272
37625
  recoveryPeers: { [fp("manager")]: binding.tokens.local },
37273
- platformStateDir: join32(directory2, "platform"),
37626
+ platformStateDir: join33(directory2, "platform"),
37274
37627
  channels: config.channels,
37275
37628
  feishu: { ...config.feishu, ingressEnabled: false },
37276
37629
  ingressEnabled: false
37277
37630
  };
37278
- let ingress = existsSync15(join32(directory2, "ingress-enabled.json"));
37631
+ let ingress = existsSync16(join33(directory2, "ingress-enabled.json"));
37279
37632
  let gateway = await startTravelGateway({ ...gatewayConfig, ingressEnabled: ingress, feishu: { ...gatewayConfig.feishu, ingressEnabled: ingress && config.channels?.feishu?.enabled === true } });
37280
37633
  let changing = false, closed = false;
37281
37634
  const pairServer = createServer4({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
@@ -37304,12 +37657,12 @@ async function startPairingControl(config) {
37304
37657
  if (input.action === "enable_ingress" && !ingress) {
37305
37658
  await gateway.close();
37306
37659
  gateway = await startTravelGateway({ ...gatewayConfig, ingressEnabled: true, feishu: { ...gatewayConfig.feishu, ingressEnabled: config.channels?.feishu?.enabled === true } });
37307
- writeFileSync15(join32(directory2, "ingress-enabled.json"), JSON.stringify({ identity: config.identity }), { mode: 384, flush: true });
37660
+ writeFileSync15(join33(directory2, "ingress-enabled.json"), JSON.stringify({ identity: config.identity }), { mode: 384, flush: true });
37308
37661
  ingress = true;
37309
37662
  }
37310
37663
  if (input.action === "disable_ingress" && ingress) {
37311
37664
  if (gateway.authority.status(binding.local).activeNodeId !== null) throw new Error("TRAVEL_INITIAL_SOURCE_RUNNING");
37312
- rmSync3(join32(directory2, "ingress-enabled.json"), { force: true });
37665
+ rmSync3(join33(directory2, "ingress-enabled.json"), { force: true });
37313
37666
  await gateway.close();
37314
37667
  gateway = await startTravelGateway(gatewayConfig);
37315
37668
  ingress = false;