engine7 7.1.151 → 7.1.152

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,6 +1815,13 @@ function tokenize(text2) {
1815
1815
  function tokenizeToField(text2) {
1816
1816
  return tokenize(text2).join(" ");
1817
1817
  }
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
+ }
1818
1825
  var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1819
1826
  var init_tokenizer = __esm({
1820
1827
  "src/mem7/core/tokenizer.ts"() {
@@ -2101,14 +2108,14 @@ var init_live = __esm({
2101
2108
  }
2102
2109
  /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
2103
2110
  async persistToFile(dotPath, val, atomic = false) {
2104
- const fs26 = await import("node:fs");
2111
+ const fs27 = await import("node:fs");
2105
2112
  const cfgPath = this.current?._configFilePath;
2106
- if (!cfgPath || !fs26.existsSync(cfgPath)) {
2113
+ if (!cfgPath || !fs27.existsSync(cfgPath)) {
2107
2114
  console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
2108
2115
  return false;
2109
2116
  }
2110
2117
  try {
2111
- const raw = JSON.parse(fs26.readFileSync(cfgPath, "utf-8"));
2118
+ const raw = JSON.parse(fs27.readFileSync(cfgPath, "utf-8"));
2112
2119
  const keys = dotPath.split(".");
2113
2120
  let o = raw;
2114
2121
  for (let i = 0; i < keys.length - 1; i++) {
@@ -2118,7 +2125,7 @@ var init_live = __esm({
2118
2125
  o[keys[keys.length - 1]] = val;
2119
2126
  if (atomic) {
2120
2127
  writeConfigAtomic(cfgPath, raw);
2121
- } else fs26.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
2128
+ } else fs27.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
2122
2129
  const lastKey = keys[keys.length - 1].toLowerCase();
2123
2130
  const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
2124
2131
  const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
@@ -2456,12 +2463,12 @@ function overlaps(a, b) {
2456
2463
  return (a.validTo === null || b.validFrom === null || b.validFrom < a.validTo) && (b.validTo === null || a.validFrom === null || a.validFrom < b.validTo);
2457
2464
  }
2458
2465
  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)]));
2466
+ const normalize7 = (input) => {
2467
+ if (Array.isArray(input)) return input.map(normalize7);
2468
+ 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
2469
  return input;
2463
2470
  };
2464
- const json = JSON.stringify(normalize6(value));
2471
+ const json = JSON.stringify(normalize7(value));
2465
2472
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
2466
2473
  return json;
2467
2474
  }
@@ -2985,8 +2992,9 @@ function invalidateDerivedDependencies(db2, event2) {
2985
2992
  }
2986
2993
  return invalidateChildren(db2, event2.scopeId, pending, event2.kind);
2987
2994
  }
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);
2995
+ function invalidateScopeDependencies(db2, scope, parent, reason, options = {}) {
2996
+ 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);
2997
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
2990
2998
  invalidateChildren(db2, scope, children, reason);
2991
2999
  }
2992
3000
  function invalidateChildren(db2, scope, pending, reason) {
@@ -3006,7 +3014,7 @@ function invalidateChildren(db2, scope, pending, reason) {
3006
3014
  }
3007
3015
  const state = child.deleted ? "deleted" : "needs_revalidation";
3008
3016
  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);
3017
+ 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
3018
  result.push(child.child_id);
3011
3019
  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
3020
  }
@@ -3101,7 +3109,7 @@ var init_dependencies = __esm({
3101
3109
  if (previous && previous.version === version && previous.state !== "current") throw new Error("DERIVATION_REQUIRES_NEW_VERSION");
3102
3110
  this.assertReferences(scope, dependencies);
3103
3111
  if (previous?.version === version) {
3104
- const normalize6 = (refs) => JSON.stringify(refs.map((ref) => [
3112
+ const normalize7 = (refs) => JSON.stringify(refs.map((ref) => [
3105
3113
  ref.parentKind,
3106
3114
  ref.parentId,
3107
3115
  ref.parentVersion,
@@ -3109,7 +3117,7 @@ var init_dependencies = __esm({
3109
3117
  ref.slotRevision ?? null,
3110
3118
  ref.role
3111
3119
  ]).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");
3120
+ if (normalize7(this.refs(scope, kind, id3)) !== normalize7(dependencies)) throw new Error("DERIVATION_VERSION_CONFLICT");
3113
3121
  return;
3114
3122
  }
3115
3123
  this.db.prepare(`INSERT INTO memory_derivations VALUES (?,?,?,?,'current',NULL,?)
@@ -3460,6 +3468,12 @@ function loadArrow() {
3460
3468
  }
3461
3469
  return arrowPromise;
3462
3470
  }
3471
+ function shortCjkQueryBigrams(text2) {
3472
+ const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
3473
+ if (!chars || chars > 6) return null;
3474
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
3475
+ return grams.length ? grams : null;
3476
+ }
3463
3477
  function buildSchemas(arrow) {
3464
3478
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
3465
3479
  const commonFields = () => [
@@ -3556,7 +3570,7 @@ function textColumnOf(kind) {
3556
3570
  return "fact";
3557
3571
  }
3558
3572
  }
3559
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3573
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3560
3574
  var init_vector_store = __esm({
3561
3575
  "src/mem7/core/vector-store.ts"() {
3562
3576
  "use strict";
@@ -3587,6 +3601,14 @@ var init_vector_store = __esm({
3587
3601
  agent_case: ["task_intent_tokens", "approach_tokens"],
3588
3602
  agent_skill: ["description_tokens", "content_tokens"]
3589
3603
  };
3604
+ BM25_TEXT_FIELDS = {
3605
+ foresight: ["foresight", "evidence"],
3606
+ episode: ["episode"],
3607
+ atomic_fact: ["fact"],
3608
+ agent_case: ["task_intent", "approach"],
3609
+ agent_skill: ["description", "content"]
3610
+ };
3611
+ sqlLiteral = (value) => value.replace(/'/g, "''");
3590
3612
  RRF_K = 60;
3591
3613
  warnedFts = /* @__PURE__ */ new Set();
3592
3614
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -4184,6 +4206,28 @@ var init_vector_store = __esm({
4184
4206
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
4185
4207
  }
4186
4208
  }
4209
+ const grams = shortCjkQueryBigrams(queryText);
4210
+ if (grams) {
4211
+ try {
4212
+ const textCols = BM25_TEXT_FIELDS[kind];
4213
+ const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4214
+ const where2 = compileFilter(opts.filter);
4215
+ const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
4216
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4217
+ for (const r of extra) {
4218
+ const rid = String(r.id ?? "");
4219
+ if (!rid) continue;
4220
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4221
+ const matched = grams.filter((gram) => text2.includes(gram)).length;
4222
+ if (!matched) continue;
4223
+ const score = maxScore + matched / grams.length;
4224
+ const cur = best.get(rid);
4225
+ if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
4226
+ else best.set(rid, { ...r, _score: score });
4227
+ }
4228
+ } catch {
4229
+ }
4230
+ }
4187
4231
  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
4232
  } catch (err) {
4189
4233
  const msg2 = String(err?.message ?? err);
@@ -4709,7 +4753,7 @@ import { createHash as createHash9 } from "node:crypto";
4709
4753
  function projectedSourceIdFromScopeId(id3, originKey, sourceVersion) {
4710
4754
  return "src_" + digest([id3, originKey, sourceVersion]);
4711
4755
  }
4712
- var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4756
+ var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4713
4757
  var init_source_store = __esm({
4714
4758
  "src/mem7/core/source-store.ts"() {
4715
4759
  "use strict";
@@ -4721,6 +4765,7 @@ var init_source_store = __esm({
4721
4765
  init_watermarks();
4722
4766
  init_interpretation_impact();
4723
4767
  init_conversation_text();
4768
+ RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
4724
4769
  SOURCE_SCHEMA = `
4725
4770
  CREATE TABLE memory_scopes (
4726
4771
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -4902,8 +4947,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4902
4947
  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
4948
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
4904
4949
  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");
4950
+ invalidateScopeDependencies(this.db, id3, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4951
+ invalidateScopeDependencies(this.db, id3, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4907
4952
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id3).source_seq);
4908
4953
  const sourceId = projectedSourceIdFromScopeId(id3, input.originKey, version);
4909
4954
  const receiptId = "rcpt_" + digest([id3, sourceId]);
@@ -5073,10 +5118,10 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5073
5118
  AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)
5074
5119
  ORDER BY source_seq DESC LIMIT ?`).all(scopeId(scope), source.sessionId, source.sourceSeq, limit2).map((row) => this.source(row)).reverse();
5075
5120
  }
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");
5121
+ pendingInterpretations(scope, sessionId, limit2 = 50, cutoff, newestFirst = false, states2, textTerms, roles) {
5122
+ if (states2?.some((state) => !["received", "applied", "needs_review", "failed"].includes(state))) throw new Error("INVALID_SOURCE_STATE");
5078
5123
  if (roles?.some((role) => !["user", "assistant", "tool"].includes(role))) throw new Error("INVALID_SOURCE_ROLE");
5079
- if (states?.length === 0) return [];
5124
+ if (states2?.length === 0) return [];
5080
5125
  if (roles?.length === 0) return [];
5081
5126
  const terms = textTerms ? [...new Set(textTerms.map((term) => term.trim().toLowerCase()).filter(Boolean))] : void 0;
5082
5127
  if (terms?.length === 0) return [];
@@ -5084,7 +5129,7 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5084
5129
  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
5130
  if (cutoff) return historicalRows(this.db, scope, "source", cutoff).filter((row) => !["applied", "deleted"].includes(row.state)).flatMap((row) => {
5086
5131
  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 [];
5132
+ 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
5133
  return [{
5089
5134
  ...source,
5090
5135
  state: row.state,
@@ -5096,13 +5141,13 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5096
5141
  const rows = this.db.prepare(`SELECT * FROM memory_sources s WHERE scope_id=? AND interpretation_status<>'applied'
5097
5142
  AND interpretation_status<>'deleted' AND NOT EXISTS (SELECT 1 FROM memory_sources newer
5098
5143
  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(",")})` : ""}
5144
+ ${this.recoveryClause("s")} ${sessionId ? "AND session_id=?" : ""} ${states2 ? `AND interpretation_status IN (${states2.map(() => "?").join(",")})` : ""}
5100
5145
  ${terms ? `AND (${terms.map((term) => latinTerm(term) ? "(' ' || lower(s.text) || ' ') GLOB ?" : "instr(lower(s.text), ?) > 0").join(" OR ")})` : ""}
5101
5146
  ${roles ? `AND role IN (${roles.map(() => "?").join(",")})` : ""}
5102
5147
  ORDER BY source_seq ${newestFirst ? "DESC" : "ASC"} LIMIT ?`).all(
5103
5148
  scopeId(scope),
5104
5149
  ...sessionId ? [sessionId] : [],
5105
- ...states ?? [],
5150
+ ...states2 ?? [],
5106
5151
  ...terms?.map((term) => latinTerm(term) ? `*[^a-z0-9_]${term}[^a-z0-9_]*` : term) ?? [],
5107
5152
  ...roles ?? [],
5108
5153
  limit2
@@ -5595,8 +5640,8 @@ var init_recovery_deletion = __esm({
5595
5640
  const { owners, parents } = this.links(table, row);
5596
5641
  for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
5597
5642
  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;
5643
+ const medium = text(row, "medium"), path37 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5644
+ 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
5645
  if (identity) {
5601
5646
  const rows = this.artifactPaths.get(identity) ?? [];
5602
5647
  rows.push(row);
@@ -5604,8 +5649,8 @@ var init_recovery_deletion = __esm({
5604
5649
  }
5605
5650
  }
5606
5651
  }
5607
- blocksArtifactPath(kind, path36) {
5608
- const rows = this.artifactPaths.get(kind + ":" + path36);
5652
+ blocksArtifactPath(kind, path37) {
5653
+ const rows = this.artifactPaths.get(kind + ":" + path37);
5609
5654
  return rows?.some((row) => this.blocks("memory_artifact_publications", row));
5610
5655
  }
5611
5656
  blocks(table, row) {
@@ -6624,7 +6669,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6624
6669
  };
6625
6670
  const candidates2 = [];
6626
6671
  const duplicateIds = /* @__PURE__ */ new Set();
6627
- const inside = (path36) => path36 && !isAbsolute2(path36) && path36 !== ".." && !path36.startsWith(`..${sep2}`);
6672
+ const inside = (path37) => path37 && !isAbsolute2(path37) && path37 !== ".." && !path37.startsWith(`..${sep2}`);
6628
6673
  for (const relativePath of input.files) {
6629
6674
  const logical = resolve4(root, relativePath);
6630
6675
  let canonical4;
@@ -6638,10 +6683,10 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6638
6683
  gap("projection_path_unverified");
6639
6684
  continue;
6640
6685
  }
6641
- const path36 = relative2(root, canonical4).replace(/\\/g, "/");
6686
+ const path37 = relative2(root, canonical4).replace(/\\/g, "/");
6642
6687
  const user = `users/${input.scope.ownerId}/`;
6643
6688
  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;
6689
+ 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
6690
  if (!kind) {
6646
6691
  gap("projection_kind_or_owner_unverified");
6647
6692
  continue;
@@ -6678,9 +6723,9 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6678
6723
  continue;
6679
6724
  }
6680
6725
  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);
6726
+ const target = join9(store.mem7RootPath(), path37);
6682
6727
  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)) {
6728
+ 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
6729
  gap("projection_mapping_conflict");
6685
6730
  continue;
6686
6731
  }
@@ -6696,7 +6741,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6696
6741
  candidates2.push({
6697
6742
  file: canonical4,
6698
6743
  fileHash,
6699
- relativePath: path36,
6744
+ relativePath: path37,
6700
6745
  id: match[1],
6701
6746
  kind,
6702
6747
  parent,
@@ -8178,9 +8223,9 @@ function normalize3(input) {
8178
8223
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
8179
8224
  return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
8180
8225
  }
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()))
8226
+ function directory(path37) {
8227
+ const info = lstatSync6(path37);
8228
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path37) !== resolve5(path37) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
8184
8229
  throw new Error("REPLICATION_REGISTRATION_INVALID");
8185
8230
  }
8186
8231
  function readRuntimeReplicationRegistration(stateDir, component, key4) {
@@ -8284,10 +8329,10 @@ var init_runtime_replication = __esm({
8284
8329
 
8285
8330
  // src/memory/topics-history/index.ts
8286
8331
  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");
8332
+ function parseTopicHistoryPath(path37) {
8333
+ if (!path37.startsWith("topics-history://") || path37.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8289
8334
  try {
8290
- return JSON.parse(Buffer.from(path36.slice(17), "base64url").toString("utf8"));
8335
+ return JSON.parse(Buffer.from(path37.slice(17), "base64url").toString("utf8"));
8291
8336
  } catch {
8292
8337
  throw new Error("INVALID_HISTORY_REFERENCE");
8293
8338
  }
@@ -10232,23 +10277,23 @@ var init_facts = __esm({
10232
10277
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
10233
10278
  }
10234
10279
  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}`);
10280
+ const path37 = `evidence[${index}]`;
10281
+ 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
10282
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
10238
10283
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
10239
10284
  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`);
10285
+ 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`);
10286
+ 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
10287
  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
10288
  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`);
10289
+ 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
10290
  }
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`);
10291
+ 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
10292
  const relationValue = proposal.value;
10248
10293
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
10249
10294
  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
10295
  }
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`);
10296
+ 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
10297
  if (proposal.claimKind !== "inference") {
10253
10298
  if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
10254
10299
  if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
@@ -10608,7 +10653,7 @@ function contentHash(text2) {
10608
10653
  function mem7Root(stateDir) {
10609
10654
  return join12(stateDir, "mem7");
10610
10655
  }
10611
- var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
10656
+ var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
10612
10657
  var init_store = __esm({
10613
10658
  "src/mem7/core/store.ts"() {
10614
10659
  "use strict";
@@ -10646,6 +10691,7 @@ var init_store = __esm({
10646
10691
  init_job_retention();
10647
10692
  init_retire_graph_audits();
10648
10693
  STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
10694
+ STARVATION_GRACE_MS = 36e5;
10649
10695
  SCHEMA = `
10650
10696
  CREATE TABLE IF NOT EXISTS memcells (
10651
10697
  id TEXT PRIMARY KEY,
@@ -11239,13 +11285,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11239
11285
  const version = expectedVersion ?? this.dependencies.version(scope, kind, id3);
11240
11286
  this.dependencies.assertCurrent(scope, kind, id3, version);
11241
11287
  const digest7 = createHash20("sha256").update(content.trim()).digest("hex");
11242
- const path36 = relative3(this.root, file2).replace(/\\/g, "/");
11288
+ const path37 = relative3(this.root, file2).replace(/\\/g, "/");
11243
11289
  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");
11290
+ if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path37)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
11245
11291
  this.db.prepare(`INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)
11246
11292
  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() });
11293
+ WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path37, version, digest7);
11294
+ this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path37, markdown: content.trim() });
11249
11295
  });
11250
11296
  }
11251
11297
  projectionMatches(scope, kind, id3, file2, content) {
@@ -11442,8 +11488,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11442
11488
  };
11443
11489
  }
11444
11490
  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);
11491
+ const path37 = relative3(this.root, file2).replace(/\\/g, "/");
11492
+ const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path37);
11447
11493
  if (mappings.length) {
11448
11494
  if (mappings.length !== 1) return false;
11449
11495
  const scope = this.sources.scope(mappings[0].scope_id);
@@ -11736,7 +11782,7 @@ ${e.outcome}
11736
11782
  return this.transaction(() => {
11737
11783
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
11738
11784
  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"}
11785
+ 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
11786
  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
11787
  AND ((status='pending' AND next_run_at<=?)
11742
11788
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -11756,40 +11802,48 @@ ${e.outcome}
11756
11802
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
11757
11803
  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
11804
  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
- });
11805
+ 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)`;
11806
+ const select = (starved2) => {
11807
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
11808
+ ORDER BY priority,next_run_at,id LIMIT ?`;
11809
+ 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];
11810
+ return this.db.prepare(sql).all(...args);
11811
+ };
11812
+ const claim = (rows) => {
11813
+ const claimedScopes = /* @__PURE__ */ new Set();
11814
+ return rows.flatMap((row) => {
11815
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
11816
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
11817
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
11818
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
11819
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
11820
+ 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);
11821
+ if (conflict) return [];
11822
+ }
11823
+ return [updated];
11824
+ }).filter((row) => {
11825
+ if (!row.scope_id) return true;
11826
+ if (claimedScopes.has(row.scope_id)) return false;
11827
+ claimedScopes.add(row.scope_id);
11828
+ return true;
11829
+ }).map((row) => {
11830
+ const leaseToken = randomUUID10();
11831
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
11832
+ return {
11833
+ id: row.id,
11834
+ kind: row.kind,
11835
+ payload: JSON.parse(row.payload),
11836
+ attempts: row.attempts,
11837
+ leaseToken,
11838
+ inputVersion: row.input_version,
11839
+ scopeId: row.scope_id ?? void 0,
11840
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
11841
+ };
11842
+ });
11843
+ };
11844
+ if (options.staleOnly) return claim(select(true));
11845
+ const starved = claim(select(true));
11846
+ return starved.length ? starved : claim(select(false));
11793
11847
  });
11794
11848
  }
11795
11849
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -18167,9 +18221,9 @@ function isAutoMemPath(absolutePath, workspace) {
18167
18221
  return normalizedPath.startsWith(getAutoMemPath(workspace));
18168
18222
  }
18169
18223
  async function ensureMemoryDirExists(memoryDir) {
18170
- const fs26 = await import("node:fs");
18224
+ const fs27 = await import("node:fs");
18171
18225
  try {
18172
- await fs26.promises.mkdir(memoryDir, { recursive: true });
18226
+ await fs27.promises.mkdir(memoryDir, { recursive: true });
18173
18227
  } catch (e) {
18174
18228
  const code = e?.code;
18175
18229
  if (code !== "EEXIST") {
@@ -18350,8 +18404,8 @@ __export(memdir_exports, {
18350
18404
  loadMemoryPrompt: () => loadMemoryPrompt,
18351
18405
  truncateEntrypointContent: () => truncateEntrypointContent
18352
18406
  });
18353
- import { readFileSync as readFileSync15 } from "node:fs";
18354
- import { join as join29 } from "node:path";
18407
+ import { readFileSync as readFileSync16 } from "node:fs";
18408
+ import { join as join30 } from "node:path";
18355
18409
  function truncateEntrypointContent(raw) {
18356
18410
  const trimmed = raw.trim();
18357
18411
  const contentLines = trimmed.split("\n");
@@ -18444,11 +18498,11 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
18444
18498
  }
18445
18499
  function buildMemoryPrompt(params) {
18446
18500
  const { displayName, memoryDir, extraGuidelines } = params;
18447
- const entrypoint = join29(memoryDir, ENTRYPOINT_NAME);
18501
+ const entrypoint = join30(memoryDir, ENTRYPOINT_NAME);
18448
18502
  let entrypointContent = params.entrypointContent ?? "";
18449
18503
  if (params.entrypointContent === void 0) {
18450
18504
  try {
18451
- entrypointContent = readFileSync15(entrypoint, "utf-8");
18505
+ entrypointContent = readFileSync16(entrypoint, "utf-8");
18452
18506
  } catch {
18453
18507
  }
18454
18508
  }
@@ -18494,8 +18548,8 @@ __export(context_analyzer_exports, {
18494
18548
  formatContextReport: () => formatContextReport,
18495
18549
  scanMemoryFiles: () => scanMemoryFiles
18496
18550
  });
18497
- import * as fs22 from "node:fs";
18498
- import * as path29 from "node:path";
18551
+ import * as fs23 from "node:fs";
18552
+ import * as path30 from "node:path";
18499
18553
  function estimateMessageTokens2(m) {
18500
18554
  let tokens = 0;
18501
18555
  if (typeof m.content === "string") {
@@ -18605,9 +18659,9 @@ function breakdownMessages(messages) {
18605
18659
  }
18606
18660
  async function scanMemoryFiles(workspace) {
18607
18661
  const files = [];
18608
- const soul = readFileIfExists(path29.join(workspace, "SOUL.md"));
18662
+ const soul = readFileIfExists(path30.join(workspace, "SOUL.md"));
18609
18663
  if (soul) files.push({ path: "SOUL.md", tokens: roughTokenCountEstimation(soul), stable: true });
18610
- const agents = readFileIfExists(path29.join(workspace, "AGENTS.md"));
18664
+ const agents = readFileIfExists(path30.join(workspace, "AGENTS.md"));
18611
18665
  if (agents) files.push({ path: "AGENTS.md", tokens: roughTokenCountEstimation(agents), stable: true });
18612
18666
  try {
18613
18667
  const { buildMemoryPrompt: buildMemoryPrompt2 } = await Promise.resolve().then(() => (init_memdir(), memdir_exports));
@@ -18623,7 +18677,7 @@ async function scanMemoryFiles(workspace) {
18623
18677
  }
18624
18678
  function readFileIfExists(filePath2) {
18625
18679
  try {
18626
- if (fs22.existsSync(filePath2)) return fs22.readFileSync(filePath2, "utf-8");
18680
+ if (fs23.existsSync(filePath2)) return fs23.readFileSync(filePath2, "utf-8");
18627
18681
  } catch {
18628
18682
  }
18629
18683
  return null;
@@ -18845,11 +18899,11 @@ var init_gateway_media = __esm({
18845
18899
  });
18846
18900
 
18847
18901
  // 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";
18902
+ import { writeFileSync as writeFileSync15, existsSync as existsSync16, rmSync as rmSync3 } from "node:fs";
18903
+ import { join as join33, resolve as resolve12 } from "node:path";
18850
18904
  import { fileURLToPath as fileURLToPath5 } from "node:url";
18851
18905
  import { createServer as createServer4 } from "node:https";
18852
- import { timingSafeEqual, X509Certificate, createHash as createHash38 } from "node:crypto";
18906
+ import { timingSafeEqual, X509Certificate, createHash as createHash39 } from "node:crypto";
18853
18907
 
18854
18908
  // src/continuity/authority.ts
18855
18909
  init_publication_objects();
@@ -18914,9 +18968,9 @@ var TravelAuthority = class {
18914
18968
  this.owner.close();
18915
18969
  throw new Error("TRAVEL_AUTHORITY_BUSY", { cause: error });
18916
18970
  }
18917
- const path36 = join3(options.directory, "authority.sqlite"), keyFile = join3(options.directory, "authority-signing.pem");
18971
+ const path37 = join3(options.directory, "authority.sqlite"), keyFile = join3(options.directory, "authority-signing.pem");
18918
18972
  try {
18919
- const present = existsSync(path36), keyPresent = existsSync(keyFile);
18973
+ const present = existsSync(path37), keyPresent = existsSync(keyFile);
18920
18974
  if (present !== keyPresent) throw new Error("TRAVEL_AUTHORITY_RECOVERY_REQUIRED");
18921
18975
  if (!keyPresent) {
18922
18976
  const keys = generateKeyPairSync("ed25519");
@@ -18924,8 +18978,8 @@ var TravelAuthority = class {
18924
18978
  }
18925
18979
  this.signingKey = readPrivateFile(keyFile).toString();
18926
18980
  this.publicKey = createPublicKey(this.signingKey).export({ format: "pem", type: "spki" }).toString();
18927
- preparePrivateDatabase(path36);
18928
- this.db = new DatabaseSync3(path36);
18981
+ preparePrivateDatabase(path37);
18982
+ this.db = new DatabaseSync3(path37);
18929
18983
  this.db.exec(`PRAGMA busy_timeout=1000; PRAGMA synchronous=FULL;
18930
18984
  CREATE TABLE IF NOT EXISTS seats(identity TEXT PRIMARY KEY,epoch INTEGER NOT NULL,active_node TEXT,active_boot TEXT,
18931
18985
  floor INTEGER NOT NULL,checkpoint TEXT NOT NULL,build TEXT NOT NULL,retired TEXT,frozen INTEGER NOT NULL DEFAULT 0);
@@ -19458,7 +19512,7 @@ function createKeyServiceServer(options) {
19458
19512
  // src/continuity/gateway-main.ts
19459
19513
  import { isAbsolute as isAbsolute5, resolve as resolve11 } from "node:path";
19460
19514
  import { fileURLToPath as fileURLToPath4 } from "node:url";
19461
- import { createHash as createHash37 } from "node:crypto";
19515
+ import { createHash as createHash38 } from "node:crypto";
19462
19516
  import * as lark3 from "@larksuiteoapi/node-sdk";
19463
19517
 
19464
19518
  // src/continuity/publication.ts
@@ -19470,9 +19524,9 @@ import { isAbsolute, join as join4, relative, resolve as resolve2, sep } from "n
19470
19524
  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
19525
  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
19526
  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("/")) {
19527
+ function validateRelativePath(path37) {
19528
+ if (typeof path37 !== "string" || !path37 || path37.length > 2048 || isAbsolute(path37)) throw new Error("INVALID_ARTIFACT_PATH");
19529
+ for (const part of path37.split("/")) {
19476
19530
  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
19531
  throw new Error("INVALID_ARTIFACT_PATH");
19478
19532
  }
@@ -19520,10 +19574,10 @@ function normalizePublicationProfile(value) {
19520
19574
  Object.freeze(profile.trees);
19521
19575
  return Object.freeze(profile);
19522
19576
  }
19523
- function validatePublicationPath(path36) {
19524
- if (typeof path36 !== "string" || path36.normalize("NFC") !== path36) throw new Error("PUBLICATION_INVALID_PATH");
19577
+ function validatePublicationPath(path37) {
19578
+ if (typeof path37 !== "string" || path37.normalize("NFC") !== path37) throw new Error("PUBLICATION_INVALID_PATH");
19525
19579
  try {
19526
- validateRelativePath(path36);
19580
+ validateRelativePath(path37);
19527
19581
  } catch {
19528
19582
  throw new Error("PUBLICATION_INVALID_PATH");
19529
19583
  }
@@ -19542,15 +19596,15 @@ function normalizePublication(value) {
19542
19596
  if (!Array.isArray(tree.files) || !Array.isArray(tree.directories) || (paths += tree.files.length + tree.directories.length) > 1e5)
19543
19597
  throw new Error("PUBLICATION_INVALID_TREE");
19544
19598
  const occupied = /* @__PURE__ */ new Map();
19545
- const claim = (path36, kind) => {
19546
- validatePublicationPath(path36);
19547
- const folded = path36.toLowerCase();
19599
+ const claim = (path37, kind) => {
19600
+ validatePublicationPath(path37);
19601
+ const folded = path37.toLowerCase();
19548
19602
  if (occupied.has(folded)) throw new Error("PUBLICATION_PATH_COLLISION");
19549
19603
  occupied.set(folded, kind);
19550
19604
  };
19551
- const directories = tree.directories.map((path36) => {
19552
- claim(path36, "directory");
19553
- return path36;
19605
+ const directories = tree.directories.map((path37) => {
19606
+ claim(path37, "directory");
19607
+ return path37;
19554
19608
  }).sort();
19555
19609
  const files = tree.files.map((file2) => {
19556
19610
  claim(file2?.path, "file");
@@ -19562,8 +19616,8 @@ function normalizePublication(value) {
19562
19616
  chunks: file2.content.chunks.map((r) => ({ sha256: r.sha256, bytes: r.bytes }))
19563
19617
  } };
19564
19618
  }).sort((a, b) => a.path.localeCompare(b.path, "en"));
19565
- for (const path36 of occupied.keys()) {
19566
- const parts = path36.split("/");
19619
+ for (const path37 of occupied.keys()) {
19620
+ const parts = path37.split("/");
19567
19621
  for (let i = 1; i < parts.length; i++) if (occupied.get(parts.slice(0, i).join("/")) === "file") throw new Error("PUBLICATION_PATH_COLLISION");
19568
19622
  }
19569
19623
  return { id: tree.id, directories, files };
@@ -19994,9 +20048,9 @@ var TravelGatewayStore = class {
19994
20048
  throw new Error("TRAVEL_GATEWAY_BUSY");
19995
20049
  }
19996
20050
  try {
19997
- const path36 = join13(options.directory, "gateway.sqlite"), present = existsSync6(path36);
19998
- preparePrivateDatabase(path36);
19999
- this.db = new DatabaseSync10(path36);
20051
+ const path37 = join13(options.directory, "gateway.sqlite"), present = existsSync6(path37);
20052
+ preparePrivateDatabase(path37);
20053
+ this.db = new DatabaseSync10(path37);
20000
20054
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
20001
20055
  if (!present) this.db.exec([
20002
20056
  "CREATE TABLE binding(identity TEXT NOT NULL,format TEXT NOT NULL);",
@@ -21681,13 +21735,13 @@ var DiscordAdapter = class _DiscordAdapter {
21681
21735
  }
21682
21736
  /** 发送媒体附件(图片/文件/音频)— discord.js channel.send({ files }) */
21683
21737
  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)) {
21738
+ const fs27 = await import("node:fs");
21739
+ const path37 = await import("node:path");
21740
+ if (!fs27.existsSync(attachment.path)) {
21687
21741
  throw new Error(`File not found: ${attachment.path}`);
21688
21742
  }
21689
- const filename = attachment.filename || path36.basename(attachment.path);
21690
- const fileBuffer = fs26.readFileSync(attachment.path);
21743
+ const filename = attachment.filename || path37.basename(attachment.path);
21744
+ const fileBuffer = fs27.readFileSync(attachment.path);
21691
21745
  const filePayload = {
21692
21746
  attachment: fileBuffer,
21693
21747
  name: filename
@@ -22301,13 +22355,13 @@ var FeishuAdapter = class _FeishuAdapter {
22301
22355
  }
22302
22356
  /** 发送媒体附件(图片/文件) */
22303
22357
  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)) {
22358
+ const fs27 = await import("node:fs");
22359
+ const path37 = await import("node:path");
22360
+ if (!fs27.existsSync(attachment.path)) {
22307
22361
  throw new Error(`File not found: ${attachment.path}`);
22308
22362
  }
22309
- const filename = attachment.filename || path36.basename(attachment.path);
22310
- const fileBuffer = fs26.readFileSync(attachment.path);
22363
+ const filename = attachment.filename || path37.basename(attachment.path);
22364
+ const fileBuffer = fs27.readFileSync(attachment.path);
22311
22365
  const safeTarget = target || this.config.defaultTarget || "";
22312
22366
  if (!safeTarget) throw new Error("Feishu sendFile: no target (\u4E3B\u52A8\u53D1\u9001\u9700\u914D\u7F6E defaultTarget \u6216\u4F20\u5165 target)");
22313
22367
  const receiveIdType = safeTarget.startsWith("ou_") ? "open_id" : "chat_id";
@@ -24437,22 +24491,22 @@ var DeskBuddyAdapter = class {
24437
24491
  try {
24438
24492
  if (!this.historyFile) {
24439
24493
  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;
24494
+ const fs28 = __require("fs");
24495
+ const path37 = __require("path");
24496
+ const dir = path37.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
24497
+ fs28.mkdirSync(dir, { recursive: true });
24498
+ this.historyFile = path37.join(dir, "history.json");
24499
+ this._fs = fs28;
24500
+ }
24501
+ const fs27 = this._fs;
24448
24502
  let arr = [];
24449
24503
  try {
24450
- arr = JSON.parse(fs26.readFileSync(this.historyFile, "utf-8")) || [];
24504
+ arr = JSON.parse(fs27.readFileSync(this.historyFile, "utf-8")) || [];
24451
24505
  } catch {
24452
24506
  }
24453
24507
  arr.push({ ...entry, ts: (/* @__PURE__ */ new Date()).toLocaleString("zh-CN", { hour12: false }) });
24454
24508
  if (arr.length > 500) arr = arr.slice(-500);
24455
- fs26.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
24509
+ fs27.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
24456
24510
  } catch (e) {
24457
24511
  console.warn("[deskBuddy] history write fail", e);
24458
24512
  }
@@ -26077,7 +26131,7 @@ var TelegramAdapter = class {
26077
26131
 
26078
26132
  // src/channels/whatsapp/adapter.ts
26079
26133
  import fsSync4 from "node:fs";
26080
- import path31 from "node:path";
26134
+ import path32 from "node:path";
26081
26135
  import { spawn as spawn5 } from "node:child_process";
26082
26136
  import { randomUUID as randomUUID18 } from "node:crypto";
26083
26137
 
@@ -27005,7 +27059,7 @@ function headerOf(groupJid) {
27005
27059
 
27006
27060
  // src/channels/whatsapp/patrol.ts
27007
27061
  import fsSync3 from "node:fs";
27008
- import path30 from "node:path";
27062
+ import path31 from "node:path";
27009
27063
  import { randomBytes as randomBytes7 } from "node:crypto";
27010
27064
 
27011
27065
  // src/models/model-capabilities.ts
@@ -28056,8 +28110,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
28056
28110
  hookEvent,
28057
28111
  durationMs: durationMs2
28058
28112
  });
28113
+ const output = syncOutput.hookSpecificOutput;
28059
28114
  return {
28060
28115
  ...processed,
28116
+ ...hook.id === "skill-gate-prompt" && output?.hookEventName === "UserPromptSubmit" && output.selectSkill === true ? { selectSkill: true } : {},
28061
28117
  outcome: processed.blockingError ? "blocking" : "success",
28062
28118
  hook
28063
28119
  };
@@ -28159,6 +28215,7 @@ function aggregateResults(results) {
28159
28215
  if (result.permissionBehavior) {
28160
28216
  aggregated.permissionBehavior = result.permissionBehavior;
28161
28217
  }
28218
+ if (result.selectSkill) aggregated.selectSkill = true;
28162
28219
  if (result.additionalContext) {
28163
28220
  aggregated.additionalContexts.push(result.additionalContext);
28164
28221
  }
@@ -30590,8 +30647,8 @@ var contextIdentity = (context) => canonicalJson({
30590
30647
  function createNotificationStateReader() {
30591
30648
  const databases = /* @__PURE__ */ new Map();
30592
30649
  const checkers = /* @__PURE__ */ new Map();
30593
- const open3 = (path36) => {
30594
- const key4 = resolve9(path36);
30650
+ const open3 = (path37) => {
30651
+ const key4 = resolve9(path37);
30595
30652
  let db2 = databases.get(key4);
30596
30653
  if (!db2) {
30597
30654
  db2 = new DatabaseSync11(key4, { readOnly: true });
@@ -31201,6 +31258,174 @@ function killTask(taskId) {
31201
31258
  return true;
31202
31259
  }
31203
31260
 
31261
+ // src/core/query-skill-selection.ts
31262
+ init_types();
31263
+
31264
+ // src/skills/recent-user-texts.ts
31265
+ init_strip_injected();
31266
+
31267
+ // src/core/query-skill-selection.ts
31268
+ 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";
31269
+ var SKILL_SELECTION_MAX_TOKENS = 64;
31270
+ async function selectSkillCall(provider, params, allowedNames, recordUsage) {
31271
+ const timeout = AbortSignal.timeout(5e3);
31272
+ const signal = AbortSignal.any([params.signal, timeout]);
31273
+ const chunks = [];
31274
+ let calledSkill = false;
31275
+ let skillName = "";
31276
+ let requestComplete = false;
31277
+ let otherCut = false;
31278
+ try {
31279
+ for await (const chunk of provider.streamChat({
31280
+ ...params,
31281
+ signal,
31282
+ httpRetry: { maxRetries: 0 }
31283
+ })) {
31284
+ signal.throwIfAborted();
31285
+ if (chunk.type === "error") return { outcome: "upstream-error" };
31286
+ if (chunk.type === "tool_call") {
31287
+ if (calledSkill || !chunk.tool_call?.id || chunk.tool_call.function?.name !== SKILL_TOOL_NAME) return { outcome: "invalid" };
31288
+ let args;
31289
+ try {
31290
+ args = JSON.parse(chunk.tool_call.function.arguments);
31291
+ } catch {
31292
+ return { outcome: "invalid" };
31293
+ }
31294
+ if (typeof args?.skill !== "string" || !allowedNames.has(args.skill.trim().replace(/^\//, ""))) return { outcome: "invalid" };
31295
+ calledSkill = true;
31296
+ skillName = args.skill.trim().replace(/^\//, "");
31297
+ chunks.push(chunk);
31298
+ }
31299
+ if (chunk.type === "done") {
31300
+ if (chunk.usage) recordUsage(chunk.usage);
31301
+ requestComplete ||= chunk.requestComplete === true;
31302
+ otherCut ||= ["incomplete", "content_filter"].includes(chunk.stopReason ?? "");
31303
+ }
31304
+ }
31305
+ } catch (error) {
31306
+ params.signal.throwIfAborted();
31307
+ if (error instanceof Error && /^TRAVEL_/.test(error.message)) throw error;
31308
+ return { outcome: timeout.aborted ? "timeout" : "upstream-error" };
31309
+ }
31310
+ params.signal.throwIfAborted();
31311
+ if (timeout.aborted) return { outcome: "timeout" };
31312
+ if (!requestComplete || otherCut) return { outcome: "incomplete" };
31313
+ return calledSkill ? { outcome: "selected", skill: skillName, chunks } : { outcome: "no-skill" };
31314
+ }
31315
+
31316
+ // src/skills/scanner.ts
31317
+ function parseFrontmatter(content) {
31318
+ const result = {};
31319
+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
31320
+ if (!match) return result;
31321
+ const lines = match[1].split("\n");
31322
+ let i = 0;
31323
+ while (i < lines.length) {
31324
+ const line = lines[i];
31325
+ const colonIdx = line.indexOf(":");
31326
+ if (colonIdx === -1) {
31327
+ i++;
31328
+ continue;
31329
+ }
31330
+ const key4 = line.slice(0, colonIdx).trim();
31331
+ let value = line.slice(colonIdx + 1).trim();
31332
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
31333
+ value = value.slice(1, -1);
31334
+ result[key4] = value;
31335
+ i++;
31336
+ continue;
31337
+ } else if (value === "|" || value === ">") {
31338
+ const blockLines = [];
31339
+ i++;
31340
+ while (i < lines.length && lines[i].startsWith(" ")) {
31341
+ blockLines.push(lines[i].slice(2));
31342
+ i++;
31343
+ }
31344
+ result[key4] = blockLines.join("\n").trim();
31345
+ continue;
31346
+ } else if (value.startsWith("[") && value.endsWith("]")) {
31347
+ result[key4] = value.slice(1, -1).split(",").map((s) => s.trim());
31348
+ i++;
31349
+ continue;
31350
+ } else if (value.includes(" ") && !value.startsWith('"')) {
31351
+ result[key4] = value;
31352
+ } else {
31353
+ result[key4] = value;
31354
+ }
31355
+ i++;
31356
+ }
31357
+ return result;
31358
+ }
31359
+
31360
+ // src/tools/SkillTool/SkillTool.ts
31361
+ init_tokenEstimate();
31362
+ import { createHash as createHash34 } from "node:crypto";
31363
+ import * as fs22 from "node:fs";
31364
+ import * as path29 from "node:path";
31365
+ var skillsDirPath = "";
31366
+ var selectionCatalog = { entries: [], allowedNames: /* @__PURE__ */ new Set() };
31367
+ function getSkillSelectionCatalog() {
31368
+ return selectionCatalog;
31369
+ }
31370
+ var resolveSkillFn;
31371
+ function loadSkillContent(skillsDir, skill) {
31372
+ const skillMdPath = skill.location ? path29.join(skillsDir, skill.location.slice("skills/".length)) : path29.join(skillsDir, skill.name, "SKILL.md");
31373
+ if (!fs22.existsSync(skillMdPath)) return null;
31374
+ const content = fs22.readFileSync(skillMdPath, "utf-8");
31375
+ const dependencies = parseFrontmatter(content)["requires-tools"];
31376
+ 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))];
31377
+ const bodyMatch = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)/);
31378
+ const body = bodyMatch ? bodyMatch[1] : content;
31379
+ const skillDir = path29.dirname(skillMdPath);
31380
+ const normalizedDir = process.platform === "win32" ? skillDir.replace(/\\/g, "/") : skillDir;
31381
+ let finalContent = `Base directory for this skill: ${normalizedDir}
31382
+
31383
+ ${body}`;
31384
+ finalContent = finalContent.replace(/\$\{CLAUDE_SKILL_DIR\}/g, normalizedDir);
31385
+ finalContent = finalContent.replace(/\$\{CLAUDE_SESSION_ID\}/g, getSessionId());
31386
+ return { content: finalContent, requiredTools };
31387
+ }
31388
+ function getSessionId() {
31389
+ return String(process.pid);
31390
+ }
31391
+ var SKILL_FINGERPRINT_PREFIX = "[fingerprint ";
31392
+ var SKILL_RELOAD_DISTANCE_TOKENS = 16e3;
31393
+ function skillFingerprint(skill, body) {
31394
+ return createHash34("sha256").update(skill.location ?? skill.name).update("\0").update(body).digest("hex").slice(0, 16);
31395
+ }
31396
+ function findLoadedSkill(history, skill, fingerprint2, resolve13) {
31397
+ if (!history) return void 0;
31398
+ for (let i = history.length - 1; i >= 0; i--) {
31399
+ const message = history[i];
31400
+ if (!("role" in message) || message.role !== "tool" || message.is_error || typeof message.content !== "string") continue;
31401
+ let call;
31402
+ for (let j = i - 1; j >= 0 && !call; j--) {
31403
+ const previous = history[j];
31404
+ 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);
31405
+ }
31406
+ if (!call) continue;
31407
+ let args = {};
31408
+ try {
31409
+ args = JSON.parse(call.function.arguments);
31410
+ } catch {
31411
+ continue;
31412
+ }
31413
+ if (typeof args?.skill !== "string" || resolve13(args.skill.trim().replace(/^\//, "")) !== skill) continue;
31414
+ if (!message.content.includes(SKILL_FINGERPRINT_PREFIX + fingerprint2 + "]")) return void 0;
31415
+ return estimateMessageTokens(history.slice(i + 1)) <= SKILL_RELOAD_DISTANCE_TOKENS ? call.id : void 0;
31416
+ }
31417
+ return void 0;
31418
+ }
31419
+ function findLoadedSkillCall(history, skillName) {
31420
+ const resolve13 = resolveSkillFn;
31421
+ if (!history || !resolve13) return void 0;
31422
+ const skill = resolve13(skillName.trim().replace(/^\//, ""));
31423
+ if (!skill) return void 0;
31424
+ const content = loadSkillContent(skillsDirPath, skill);
31425
+ if (!content) return void 0;
31426
+ return findLoadedSkill(history, skill, skillFingerprint(skill, content.content), resolve13);
31427
+ }
31428
+
31204
31429
  // src/core/query.ts
31205
31430
  function blockedToolCallsForOverride(calls, override2) {
31206
31431
  if (!override2) return [];
@@ -31598,6 +31823,7 @@ var QueryEngine = class _QueryEngine {
31598
31823
  turnCount++;
31599
31824
  const steers = this.pendingSteers.splice(0);
31600
31825
  let steerConsumedThisTurn = false;
31826
+ let userSteerConsumedThisTurn = false;
31601
31827
  if (steers.length > 0) {
31602
31828
  for (const input of steers) {
31603
31829
  if (this.steerHistoryIds.has(input.id)) {
@@ -31629,6 +31855,7 @@ var QueryEngine = class _QueryEngine {
31629
31855
  if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
31630
31856
  this.steerHistoryIds.add(input.id);
31631
31857
  steerConsumedThisTurn = true;
31858
+ userSteerConsumedThisTurn = true;
31632
31859
  yield {
31633
31860
  type: "user_input",
31634
31861
  message: steerMsg,
@@ -31884,7 +32111,53 @@ var QueryEngine = class _QueryEngine {
31884
32111
  let turnAborted = false;
31885
32112
  try {
31886
32113
  wholeQueryAbort.signal.throwIfAborted();
31887
- const view = normalizeMessagesForAPI(currentMessages).map((m) => {
32114
+ const beforeRequest = () => {
32115
+ wholeQueryAbort.signal.throwIfAborted();
32116
+ ac.signal.throwIfAborted();
32117
+ };
32118
+ const startRequest = () => {
32119
+ this.phase = "streaming";
32120
+ assertRuntimeAuthority(void 0, "INPUT");
32121
+ if (perTurnOptions?.onRequestStarted) {
32122
+ const start = perTurnOptions.onRequestStarted;
32123
+ setImmediate(() => {
32124
+ if (!wholeQueryAbort.signal.aborted) start();
32125
+ });
32126
+ }
32127
+ };
32128
+ let selected;
32129
+ const selectionInput = perTurnOptions?.skillSelectionInput;
32130
+ const skill = turnCount === 1 && maxTurns >= 2 && !userSteerConsumedThisTurn && !hasPendingUserInput() && selectionInput ? allToolDefs.find((tool) => tool.function.name === SKILL_TOOL_NAME) : void 0;
32131
+ const catalog = skill ? getSkillSelectionCatalog() : void 0;
32132
+ if (skill && selectionInput && catalog?.entries.length) {
32133
+ const input = normalizeMessagesForAPI([selectionInput]);
32134
+ const started = performance.now();
32135
+ startRequest();
32136
+ const selection = await selectSkillCall(queryProvider, {
32137
+ preferFastFallback,
32138
+ model: queryModel,
32139
+ messages: input,
32140
+ tools: [skill],
32141
+ systemStable: SKILL_SELECTION_PROMPT + "\n\n" + JSON.stringify(catalog.entries),
32142
+ maxTokens: SKILL_SELECTION_MAX_TOKENS,
32143
+ signal: ac.signal,
32144
+ beforeRequest: () => {
32145
+ assertHostTurnCurrent();
32146
+ beforeRequest();
32147
+ },
32148
+ disableThinking: true
32149
+ }, catalog.allowedNames, recordUsage);
32150
+ assertHostTurnCurrent();
32151
+ beforeRequest();
32152
+ console.log(`${this.logPrefix} [skill-selection] ${selection.outcome} ms=${Math.round(performance.now() - started)}`);
32153
+ if (hasPendingUserInput()) continue;
32154
+ if (selection.outcome === "selected") {
32155
+ if (findLoadedSkillCall(currentMessages, selection.skill)) {
32156
+ console.log(`${this.logPrefix} [skill-selection] already-loaded ${selection.skill}`);
32157
+ } else selected = selection.chunks;
32158
+ }
32159
+ }
32160
+ const view = (selected ? [] : normalizeMessagesForAPI(currentMessages)).map((m) => {
31888
32161
  if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
31889
32162
  const blocks = m.content.filter((b) => {
31890
32163
  if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
@@ -31919,7 +32192,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
31919
32192
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
31920
32193
 
31921
32194
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31922
- if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
32195
+ if (!selected && (!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
31923
32196
  try {
31924
32197
  const ws = process.env.ENGINE7_WORKSPACE;
31925
32198
  if (ws) {
@@ -31935,15 +32208,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31935
32208
  } catch {
31936
32209
  }
31937
32210
  }
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({
32211
+ if (!selected) startRequest();
32212
+ for await (const chunk of selected ?? queryProvider.streamChat({
31947
32213
  preferFastFallback,
31948
32214
  model: queryModel,
31949
32215
  messages: apiMessages,
@@ -31956,10 +32222,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31956
32222
  maxTokens: this.resolveRequestMaxTokens(apiMessages, maxTokensOverride),
31957
32223
  temperature: this.options.temperature,
31958
32224
  signal: ac.signal,
31959
- beforeRequest: () => {
31960
- wholeQueryAbort.signal.throwIfAborted();
31961
- ac.signal.throwIfAborted();
31962
- },
32225
+ beforeRequest,
31963
32226
  disableThinking: this.options.disableThinking || !!perTurnEmotion
31964
32227
  // 情感模式关 thinking(对齐 deskBuddy)
31965
32228
  })) {
@@ -32320,6 +32583,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
32320
32583
  if (vcDelivery) await vcDelivery;
32321
32584
  }
32322
32585
  const { messages: toolResults, summaries } = toolRes;
32586
+ if (selected) console.log(`${this.logPrefix} [skill-selection] ${summaries.length === 1 && !summaries[0].isError ? "loaded" : "load-failed"}`);
32323
32587
  if (collectStopEvidence) stopToolResults.push(...summaries);
32324
32588
  for (const s of summaries) {
32325
32589
  try {
@@ -32617,9 +32881,9 @@ function readState(stateFile) {
32617
32881
  return { lastPatrolAt: 0, lastLineCounts: {} };
32618
32882
  }
32619
32883
  function writeState(stateFile, state) {
32620
- const dir = path30.dirname(stateFile);
32884
+ const dir = path31.dirname(stateFile);
32621
32885
  fsSync3.mkdirSync(dir, { recursive: true });
32622
- const tmp = path30.join(dir, `.${path30.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
32886
+ const tmp = path31.join(dir, `.${path31.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
32623
32887
  try {
32624
32888
  fsSync3.writeFileSync(tmp, JSON.stringify(state), "utf-8");
32625
32889
  fsSync3.renameSync(tmp, stateFile);
@@ -32648,7 +32912,7 @@ function buildPatrolPrompt(materials) {
32648
32912
  ].join("\n");
32649
32913
  }
32650
32914
  function defaultWriteMemoryNote(workspace) {
32651
- const dir = path30.join(getAutoMemPath(workspace), "whatsapp-patrol");
32915
+ const dir = path31.join(getAutoMemPath(workspace), "whatsapp-patrol");
32652
32916
  return (note) => {
32653
32917
  fsSync3.mkdirSync(dir, { recursive: true });
32654
32918
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
@@ -32662,7 +32926,7 @@ function defaultWriteMemoryNote(workspace) {
32662
32926
  note,
32663
32927
  ""
32664
32928
  ].join("\n");
32665
- fsSync3.writeFileSync(path30.join(dir, `patrol-${stamp}.md`), body, "utf-8");
32929
+ fsSync3.writeFileSync(path31.join(dir, `patrol-${stamp}.md`), body, "utf-8");
32666
32930
  };
32667
32931
  }
32668
32932
  function makeSubmitToMain(engineDeps) {
@@ -32807,15 +33071,15 @@ ${quoted}`);
32807
33071
 
32808
33072
  // src/utils/ffmpeg-path.ts
32809
33073
  init_dep_downloader();
32810
- import * as fs23 from "node:fs";
33074
+ import * as fs24 from "node:fs";
32811
33075
  function resolveFfmpegPath() {
32812
33076
  const env = (process.env.E7_FFMPEG_PATH || "").trim();
32813
- if (env && fs23.existsSync(env)) return env;
33077
+ if (env && fs24.existsSync(env)) return env;
32814
33078
  const downloaded = optionalFfmpegPath();
32815
33079
  if (downloaded) return downloaded;
32816
33080
  try {
32817
33081
  const p = __require("@ffmpeg-installer/ffmpeg")?.path;
32818
- if (p && fs23.existsSync(p)) return p;
33082
+ if (p && fs24.existsSync(p)) return p;
32819
33083
  } catch {
32820
33084
  }
32821
33085
  return "ffmpeg";
@@ -32901,10 +33165,10 @@ function normalizeAllowEntry(entry) {
32901
33165
  }
32902
33166
  function atomicWriteFile(dir, fileName, content) {
32903
33167
  fsSync4.mkdirSync(dir, { recursive: true });
32904
- const tmp = path31.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID18().slice(0, 8)}`);
33168
+ const tmp = path32.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID18().slice(0, 8)}`);
32905
33169
  try {
32906
33170
  fsSync4.writeFileSync(tmp, content, "utf-8");
32907
- fsSync4.renameSync(tmp, path31.join(dir, fileName));
33171
+ fsSync4.renameSync(tmp, path32.join(dir, fileName));
32908
33172
  } catch (e) {
32909
33173
  try {
32910
33174
  fsSync4.rmSync(tmp, { force: true });
@@ -33019,13 +33283,13 @@ var WhatsAppAdapter = class {
33019
33283
  constructor(cfg, opts = {}) {
33020
33284
  this.cfg = cfg;
33021
33285
  this.stateDir = cfg.stateDir;
33022
- this.authDir = path31.join(cfg.stateDir, "whatsapp-auth");
33023
- this.qrFilePath = path31.join(cfg.stateDir, "whatsapp-qr.txt");
33286
+ this.authDir = path32.join(cfg.stateDir, "whatsapp-auth");
33287
+ this.qrFilePath = path32.join(cfg.stateDir, "whatsapp-qr.txt");
33024
33288
  this.opts = opts;
33025
33289
  this.credsStore = opts.credsStoreOverride ?? makeCredsStore(this.authDir);
33026
33290
  this.loginTtlMs = opts.loginTtlMs ?? LOGIN_TTL_MS;
33027
33291
  this.digestEnabled = cfg.groupDigest?.enabled !== false;
33028
- this.digest = this.digestEnabled ? new GroupDigestStore(path31.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
33292
+ this.digest = this.digestEnabled ? new GroupDigestStore(path32.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
33029
33293
  this.typing = new PresenceTypingCoalescer(async (jid) => {
33030
33294
  const sock = this.sock;
33031
33295
  if (!sock || typeof sock.sendPresenceUpdate !== "function") return;
@@ -33160,7 +33424,7 @@ var WhatsAppAdapter = class {
33160
33424
  this.patrol = startPatrolLoop({
33161
33425
  digest: this.digest,
33162
33426
  intervalMin: this.cfg.groupDigest?.patrolIntervalMin ?? 60,
33163
- stateFile: path31.join(this.stateDir, "whatsapp-patrol-state.json"),
33427
+ stateFile: path32.join(this.stateDir, "whatsapp-patrol-state.json"),
33164
33428
  runReadOnlyAgent: makeReadOnlyAgentRunner(this.opts.patrolDeps),
33165
33429
  // ⚠️ 升级接线(终审 C1,1003):摘要含 ⚠️ 行时宿主经主 session 投递(spec §4)——
33166
33430
  // makeSubmitToMain 吃的正是 patrolDeps {dispatcher, deps}(patrol.ts)形状。漏接这行 =
@@ -33457,11 +33721,11 @@ ${r}` : r;
33457
33721
  const idRaw = typeof raw?.key?.id === "string" && raw.key.id ? raw.key.id : "";
33458
33722
  const idSafe = idRaw.replace(/[^\w.-]/g, "_");
33459
33723
  const id3 = !idRaw || idSafe !== idRaw || !idSafe ? randomUUID18() : idSafe;
33460
- const dir = path31.join(this.stateDir, "media", "whatsapp");
33724
+ const dir = path32.join(this.stateDir, "media", "whatsapp");
33461
33725
  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)) {
33726
+ const abs = path32.join(dir, `${id3}.${ext}`);
33727
+ const resolved = path32.resolve(abs);
33728
+ if (!resolved.startsWith(path32.resolve(dir) + path32.sep)) {
33465
33729
  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
33730
  return `${placeholder}\uFF08\u4E0B\u8F7D\u5931\u8D25\uFF09`;
33467
33731
  }
@@ -33495,7 +33759,7 @@ ${r}` : r;
33495
33759
  const lids = [jid, participant].filter((j) => j.endsWith("@lid"));
33496
33760
  if (lids.length === 0) return;
33497
33761
  try {
33498
- const filePath2 = path31.join(this.authDir, "lid-mapping.json");
33762
+ const filePath2 = path32.join(this.authDir, "lid-mapping.json");
33499
33763
  let arr = [];
33500
33764
  try {
33501
33765
  const parsed = JSON.parse(fsSync4.readFileSync(filePath2, "utf-8"));
@@ -33605,7 +33869,7 @@ ${r}` : r;
33605
33869
  if (isGroupJid(jid)) throw new Error(`WhatsApp \u7FA4\u53D1\u9001\u7269\u7406\u4E0D\u5B58\u5728\uFF08\u7EA2\u7EBF\uFF09\uFF1Atarget=${jid}`);
33606
33870
  const sock = this.requireSock();
33607
33871
  const mime = attachment.mimeType ?? "";
33608
- const filename = attachment.filename ?? path31.basename(attachment.path);
33872
+ const filename = attachment.filename ?? path32.basename(attachment.path);
33609
33873
  if (mime.startsWith("image/")) {
33610
33874
  assertExternalEffectCurrent();
33611
33875
  const res2 = await sock.sendMessage(jid, { image: { url: attachment.path }, caption: message });
@@ -33634,8 +33898,8 @@ ${r}` : r;
33634
33898
  this.recordEcho(res2);
33635
33899
  return;
33636
33900
  }
33637
- const tmpDir = path31.join(this.stateDir, "whatsapp-media-tmp");
33638
- const dst = path31.join(tmpDir, `${randomUUID18()}.ogg`);
33901
+ const tmpDir = path32.join(this.stateDir, "whatsapp-media-tmp");
33902
+ const dst = path32.join(tmpDir, `${randomUUID18()}.ogg`);
33639
33903
  try {
33640
33904
  await (this.cfg.ffmpegTranscode ?? defaultFfmpegTranscode)(attachment.path, dst);
33641
33905
  assertExternalEffectCurrent();
@@ -33750,9 +34014,9 @@ function quotedTextOf(content) {
33750
34014
  }
33751
34015
 
33752
34016
  // 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";
34017
+ import fs25 from "node:fs";
34018
+ import path33 from "node:path";
34019
+ import { createHash as createHash35, randomUUID as randomUUID19 } from "node:crypto";
33756
34020
 
33757
34021
  // src/channels/dingtalk-stream.ts
33758
34022
  import { EventEmitter } from "node:events";
@@ -34344,13 +34608,13 @@ var DingTalkAdapter = class _DingTalkAdapter {
34344
34608
  const res = await this.baseFetch(url, { signal: AbortSignal.timeout(3e4) });
34345
34609
  if (!res.ok) throw new Error(`media download HTTP ${res.status}`);
34346
34610
  const buf = Buffer.from(await res.arrayBuffer());
34347
- const dir = path32.join(this.cfg.stateDir, "media", "dingtalk");
34348
- fs24.mkdirSync(dir, { recursive: true });
34611
+ const dir = path33.join(this.cfg.stateDir, "media", "dingtalk");
34612
+ fs25.mkdirSync(dir, { recursive: true });
34349
34613
  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);
34614
+ const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash35("sha1").update(m.code).digest("hex").slice(0, 12);
34351
34615
  const safeCode = raw.replace(/[^a-zA-Z0-9_-]/g, "_");
34352
- const local = path32.join(dir, `${safeCode}.${ext}`);
34353
- fs24.writeFileSync(local, buf);
34616
+ const local = path33.join(dir, `${safeCode}.${ext}`);
34617
+ fs25.writeFileSync(local, buf);
34354
34618
  out.push({
34355
34619
  url: `file://${local}`,
34356
34620
  filename: m.filename ?? `${safeCode}.${ext}`,
@@ -34423,8 +34687,8 @@ var DingTalkAdapter = class _DingTalkAdapter {
34423
34687
  async sendFileNow(target, message, attachment) {
34424
34688
  const entry = this.registry.get(target);
34425
34689
  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);
34690
+ const buf = fs25.readFileSync(attachment.path);
34691
+ const filename = (attachment.filename ?? path33.basename(attachment.path)).slice(0, 100);
34428
34692
  const isImage = (attachment.mimeType ?? "").startsWith("image/") || /\.(png|jpe?g|gif|webp|bmp)$/i.test(filename);
34429
34693
  const mediaId = await this.uploadMedia(buf, filename, isImage ? "image" : "file");
34430
34694
  const msgKey = isImage ? "sampleImageMsg" : "sampleFileMsg";
@@ -34789,7 +35053,7 @@ var DING_EDIT_INTERVAL_MS = 300;
34789
35053
  // src/channels/wecom-stream.ts
34790
35054
  import { EventEmitter as EventEmitter2 } from "node:events";
34791
35055
  import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
34792
- import { createHash as createHash35 } from "node:crypto";
35056
+ import { createHash as createHash36 } from "node:crypto";
34793
35057
  var WECOM_WS_URL = "wss://openws.work.weixin.qq.com";
34794
35058
  var HEARTBEAT_MS2 = 3e4;
34795
35059
  var ACK_TIMEOUT_MS = 15e3;
@@ -35141,7 +35405,7 @@ var WecomStreamClient = class extends EventEmitter2 {
35141
35405
  if (!data.length) throw new Error("wecom uploadMedia: empty buffer");
35142
35406
  const totalChunks = Math.ceil(data.length / UPLOAD_CHUNK_BYTES);
35143
35407
  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");
35408
+ const md5 = createHash36("md5").update(data).digest("hex");
35145
35409
  const initRes = await this.sendCommand("aibot_upload_media_init", {
35146
35410
  type,
35147
35411
  filename,
@@ -35168,9 +35432,9 @@ var WecomStreamClient = class extends EventEmitter2 {
35168
35432
 
35169
35433
  // src/channels/wecom.ts
35170
35434
  import { createDecipheriv as createDecipheriv3, randomUUID as randomUUID20 } from "node:crypto";
35171
- import { readFileSync as readFileSync17 } from "node:fs";
35435
+ import { readFileSync as readFileSync18 } from "node:fs";
35172
35436
  import { mkdir as mkdir4, readFile, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
35173
- import path33 from "node:path";
35437
+ import path34 from "node:path";
35174
35438
  var WECOM_CONTENT_BYTES = 20480;
35175
35439
  var DEFAULT_MERGE_WINDOW_MS = 600;
35176
35440
  var REPLY_WINDOW_MS = 24 * 60 * 60 * 1e3;
@@ -35356,7 +35620,7 @@ var WecomAdapter = class {
35356
35620
  this.now = cfg.now ?? Date.now;
35357
35621
  this.sleepImpl = cfg.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
35358
35622
  this.fetchImpl = cfg.fetchImpl ?? fetch;
35359
- this.routesFile = path33.join(cfg.stateDir, "state", ROUTES_FILE);
35623
+ this.routesFile = path34.join(cfg.stateDir, "state", ROUTES_FILE);
35360
35624
  }
35361
35625
  /**
35362
35626
  * 载入落盘会话路由(1007:真机事故——注册表原本只存内存,引擎一重启"谁跟我说过话"全丢,
@@ -35372,7 +35636,7 @@ var WecomAdapter = class {
35372
35636
  this.routesLoaded = true;
35373
35637
  let raw;
35374
35638
  try {
35375
- raw = JSON.parse(readFileSync17(this.routesFile, "utf8"));
35639
+ raw = JSON.parse(readFileSync18(this.routesFile, "utf8"));
35376
35640
  } catch (e) {
35377
35641
  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
35642
  return;
@@ -35400,7 +35664,7 @@ var WecomAdapter = class {
35400
35664
  try {
35401
35665
  const routes = {};
35402
35666
  for (const [chatId, e] of this.registry) routes[chatId] = { chatType: e.chatType, userId: e.userId };
35403
- await mkdir4(path33.dirname(this.routesFile), { recursive: true });
35667
+ await mkdir4(path34.dirname(this.routesFile), { recursive: true });
35404
35668
  await writeFile4(this.routesFile, JSON.stringify({ version: 1, routes }, null, 2) + "\n", "utf8");
35405
35669
  } catch (e) {
35406
35670
  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 +35950,7 @@ ${parsed.inbound.content}`;
35686
35950
  /** 入站媒体:下载 → aeskey 解密 → 落盘 → 附件(单条失败不拖垮整条消息;全部失败给 content 加标记)。
35687
35951
  * 本地文件名一律由 msgid 派生(远端 filename 只做显示名)——防同名互相覆盖/超长(钉钉 1004 同款纪律)。 */
35688
35952
  async resolveInboundMedia(parsed) {
35689
- const dir = path33.join(this.cfg.stateDir, "media", "wecom");
35953
+ const dir = path34.join(this.cfg.stateDir, "media", "wecom");
35690
35954
  const attachments = [];
35691
35955
  let failed = 0;
35692
35956
  for (const [i, ref] of parsed.media.entries()) {
@@ -35698,7 +35962,7 @@ ${parsed.inbound.content}`;
35698
35962
  const data = ref.aeskey ? decryptWecomMedia(raw, ref.aeskey) : raw;
35699
35963
  const ext = ref.filename?.includes(".") ? ref.filename.split(".").pop().toLowerCase().slice(0, 8) : ref.kind === "image" ? "jpg" : ref.kind === "video" ? "mp4" : "bin";
35700
35964
  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);
35965
+ const file2 = path34.join(dir, localName);
35702
35966
  await writeFile4(file2, data);
35703
35967
  const displayName = (ref.filename || localName).slice(0, 120);
35704
35968
  attachments.push({
@@ -35729,7 +35993,7 @@ ${parsed.inbound.content}`;
35729
35993
  const entry = this.registry.get(target);
35730
35994
  if (!entry) throw new Error(`[wecom] \u65E0\u6CD5\u8DEF\u7531\u5A92\u4F53\u5230 ${target}\uFF08\u65E0\u4F1A\u8BDD\u6CE8\u518C\u8BB0\u5F55\uFF09`);
35731
35995
  await this.takeToken(target, false);
35732
- const filename = attachment.filename ?? path33.basename(attachment.path);
35996
+ const filename = attachment.filename ?? path34.basename(attachment.path);
35733
35997
  const { mediaId } = await this.requireStream().uploadMedia(data, type, filename);
35734
35998
  const body = type === "video" ? { msgtype: "video", video: { media_id: mediaId, title: filename } } : { msgtype: type, [type]: { media_id: mediaId } };
35735
35999
  await this.respondOrSend(entry, target, body);
@@ -35993,7 +36257,7 @@ import { randomUUID as randomUUID21 } from "node:crypto";
35993
36257
  // src/continuity/gateway-channel.ts
35994
36258
  init_gateway_media();
35995
36259
  import { mkdtempSync, writeFileSync as writeFileSync14, rmSync as rmSync2, realpathSync as realpathSync5 } from "node:fs";
35996
- import { join as join31 } from "node:path";
36260
+ import { join as join32 } from "node:path";
35997
36261
  import { tmpdir as tmpdir3 } from "node:os";
35998
36262
  function splitChannelGatewayText(text2, channel) {
35999
36263
  if (typeof text2 !== "string" || Buffer.byteLength(text2) > 1024 * 1024) throw new Error("TRAVEL_GATEWAY_REPLY_LIMIT");
@@ -36048,7 +36312,7 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
36048
36312
  if (!media) await adapter.send(packet.target, packet.text, { replyTo: packet.replyTo });
36049
36313
  else {
36050
36314
  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);
36315
+ const directory2 = realpathSync5(mkdtempSync(join32(tmpdir3(), "e7-gateway-media-"))), file2 = join32(directory2, packet.filename);
36052
36316
  try {
36053
36317
  writeFileSync14(file2, media.bytes, { mode: 384 });
36054
36318
  await adapter.sendFile(packet.target, packet.text, { path: file2, filename: packet.filename, mimeType: packet.mimeType, voiceDurationSec: packet.voiceDurationSec });
@@ -36474,9 +36738,9 @@ var RemoteTravelChannel = class {
36474
36738
  };
36475
36739
 
36476
36740
  // 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";
36741
+ import fs26 from "node:fs/promises";
36742
+ import path35 from "node:path";
36743
+ import { createHash as createHash37 } from "node:crypto";
36480
36744
 
36481
36745
  // src/channels/chan7-content.ts
36482
36746
  function fileMime(name) {
@@ -36488,8 +36752,8 @@ function fileMime(name) {
36488
36752
  function archive(manager, name, mime, bytes2, role, caption, identity) {
36489
36753
  const adapter = manager.getAdapter("chan7");
36490
36754
  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");
36755
+ const safeName = path35.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
36756
+ const key4 = createHash37("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
36493
36757
  try {
36494
36758
  adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key4);
36495
36759
  } catch (e) {
@@ -36499,9 +36763,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
36499
36763
  async function archivePrivateOutbound(manager, channel, target, text2, attachment, origin) {
36500
36764
  if (channel === "chan7" || origin?.channelType !== "dm" || origin.inboundIsBot || origin.channel !== channel || origin.channelTarget !== target || !manager.getAdapter("chan7")?.files) return;
36501
36765
  try {
36502
- const stat3 = await fs25.stat(attachment.path);
36766
+ const stat3 = await fs26.stat(attachment.path);
36503
36767
  if (!stat3.isFile() || stat3.size > 16 * 1024 * 1024) return;
36504
- const bytes2 = await fs25.readFile(attachment.path), name = attachment.filename ?? path34.basename(attachment.path);
36768
+ const bytes2 = await fs26.readFile(attachment.path), name = attachment.filename ?? path35.basename(attachment.path);
36505
36769
  archive(
36506
36770
  manager,
36507
36771
  name,
@@ -36516,6 +36780,63 @@ async function archivePrivateOutbound(manager, channel, target, text2, attachmen
36516
36780
  }
36517
36781
  }
36518
36782
 
36783
+ // src/channels/loop-guard.ts
36784
+ var MAX_COMPARE_LEN = 60;
36785
+ var MAX_REPEAT = 3;
36786
+ var SIMILARITY_THRESHOLD = 0.8;
36787
+ var HISTORY_SIZE = 5;
36788
+ var LoopBlockedError = class extends Error {
36789
+ constructor(target, repeated) {
36790
+ super(`loop-guard blocked: \u5411 ${target} \u8FDE\u7EED ${repeated} \u6761\u540C\u8D28\u6D88\u606F`);
36791
+ this.target = target;
36792
+ this.repeated = repeated;
36793
+ this.name = "LoopBlockedError";
36794
+ }
36795
+ };
36796
+ var states = /* @__PURE__ */ new Map();
36797
+ function normalize6(text2) {
36798
+ return text2.replace(/[\s\u3000]/g, "").replace(/[。,、!?;:""''()()\[\]【】…~~\-—.,!?;:'"]/g, "").toLowerCase();
36799
+ }
36800
+ function similarity(a, b) {
36801
+ if (!a && !b) return 1;
36802
+ if (!a || !b) return 0;
36803
+ const setA = new Set(a);
36804
+ const setB = new Set(b);
36805
+ let inter = 0;
36806
+ for (const ch of setA) if (setB.has(ch)) inter++;
36807
+ const union = setA.size + setB.size - inter;
36808
+ return union === 0 ? 1 : inter / union;
36809
+ }
36810
+ function isSameKind(a, b) {
36811
+ if (a === b) return true;
36812
+ return similarity(a, b) >= SIMILARITY_THRESHOLD;
36813
+ }
36814
+ function checkOutbound(channelName, target, message) {
36815
+ const text2 = message.trim();
36816
+ if (!text2 || text2.length > MAX_COMPARE_LEN) {
36817
+ if (text2) states.delete(`${channelName}:${target}`);
36818
+ return true;
36819
+ }
36820
+ const key4 = `${channelName}:${target}`;
36821
+ const norm = normalize6(text2);
36822
+ const state = states.get(key4) ?? { recent: [] };
36823
+ let repeated = 1;
36824
+ for (let i = state.recent.length - 1; i >= 0; i--) {
36825
+ if (isSameKind(state.recent[i], norm)) repeated++;
36826
+ else break;
36827
+ }
36828
+ if (repeated >= MAX_REPEAT) {
36829
+ console.warn(
36830
+ `[loop-guard] BLOCKED channel=${channelName} target=${target} repeated=${repeated} text=${text2.slice(0, 40)}`
36831
+ );
36832
+ return false;
36833
+ }
36834
+ state.recent.push(norm);
36835
+ if (state.recent.length > HISTORY_SIZE) state.recent.shift();
36836
+ states.set(key4, state);
36837
+ return true;
36838
+ }
36839
+
36519
36840
  // src/channels/manager.ts
36520
36841
  var MANAGED_CHANNEL_NAMES = ["discord", "feishu", "wechat", "deskBuddy", "ccBridge", "telegram", "whatsapp", "dingtalk", "wecom"];
36521
36842
  var defaultFactories = {
@@ -36894,6 +37215,9 @@ var ChannelManager = class {
36894
37215
  if (!adapter) {
36895
37216
  throw new Error(`No adapter for ${channelName}`);
36896
37217
  }
37218
+ if (!checkOutbound(channelName, target, message)) {
37219
+ throw new LoopBlockedError(target, 3);
37220
+ }
36897
37221
  try {
36898
37222
  if (hasMemoryEffectContext() && (!adapter.memoryGuardedSends || hasAutomaticMemoryEffectContext() && adapter.memoryGuardedAutomation === false)) throw new Error(`MEMORY_EXECUTION_BLOCKED: adapter ${channelName} has no final send guard`);
36899
37223
  await guardedExternalEffect(() => adapter.send(target, message, options));
@@ -36991,12 +37315,12 @@ var quiet2 = { error: () => {
36991
37315
  }, debug: () => {
36992
37316
  }, trace: () => {
36993
37317
  } };
36994
- function path35(value) {
37318
+ function path36(value) {
36995
37319
  if (typeof value !== "string" || !isAbsolute5(value)) throw new Error("TRAVEL_GATEWAY_ABSOLUTE_PATH_REQUIRED");
36996
37320
  return resolve11(value);
36997
37321
  }
36998
37322
  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) };
37323
+ return { ca: readPrivateFile(path36(config?.caFile), 1024 * 1024), cert: readPrivateFile(path36(config?.certFile), 1024 * 1024), key: readPrivateFile(path36(config?.keyFile), 16384) };
37000
37324
  }
37001
37325
  async function startTravelGateway(config) {
37002
37326
  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 +37330,7 @@ async function startTravelGateway(config) {
37006
37330
  if (feishuIngress && !/^cli_[0-9a-fA-F]{16}$/.test(config.feishu?.appId)) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
37007
37331
  const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls2(config.keyService.tls), timeoutMs: 1e4 };
37008
37332
  const material = await fetchTravelKey(keyConfig);
37009
- const keyDigest = createHash37("sha256").update(material.key).digest("hex");
37333
+ const keyDigest = createHash38("sha256").update(material.key).digest("hex");
37010
37334
  let keyWatermark = material.deletionWatermark;
37011
37335
  const refreshInterval = config.keyRefreshIntervalMs ?? 1e4, maxKeyAge = config.keyMaxAgeMs ?? 3e4;
37012
37336
  if (!Number.isSafeInteger(refreshInterval) || refreshInterval < 100 || refreshInterval > 1e4 || !Number.isSafeInteger(maxKeyAge) || maxKeyAge < 2 * refreshInterval || maxKeyAge > 3e4) {
@@ -37047,14 +37371,14 @@ async function startTravelGateway(config) {
37047
37371
  }
37048
37372
  };
37049
37373
  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 });
37374
+ objects = await PublicationObjects.open({ directory: path36(config.objectsDir), identity: config.identity, key: material.key });
37375
+ authority = new TravelAuthority({ directory: path36(config.authorityDir), leaseMs: config.leaseMs });
37052
37376
  if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
37053
37377
  for (const credential of Object.values(config.allowedPeers)) {
37054
37378
  const principal = authority.authenticate(String(credential));
37055
37379
  if (["tenantId", "companionId", "seatId"].some((key4) => principal[key4] !== config.identity[key4]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
37056
37380
  }
37057
- store = new TravelGatewayStore({ directory: path35(config.gatewayDir), identity: config.identity, objects, authority });
37381
+ store = new TravelGatewayStore({ directory: path36(config.gatewayDir), identity: config.identity, objects, authority });
37058
37382
  await store.migrateStoredInputs();
37059
37383
  if (config.previouslyProcessedPlatformIds) store.importProcessedInputs(config.previouslyProcessedPlatformIds);
37060
37384
  platform = createFeishuGatewayPlatform(config.feishu);
@@ -37108,7 +37432,7 @@ async function startTravelGateway(config) {
37108
37432
  }
37109
37433
  });
37110
37434
  if (config.channels && config.ingressEnabled !== false) {
37111
- adapters.setFactoryContext({ stateDir: path35(config.platformStateDir) });
37435
+ adapters.setFactoryContext({ stateDir: path36(config.platformStateDir) });
37112
37436
  adapters.loadFromConfig(Object.fromEntries(Object.entries(config.channels).filter(([name, value]) => name !== "feishu" && value.enabled)));
37113
37437
  for (const channel of ["discord", "wechat"]) {
37114
37438
  const adapter = adapters.getAdapter(channel);
@@ -37171,7 +37495,7 @@ async function startTravelGateway(config) {
37171
37495
  checking = true;
37172
37496
  void fetchTravelKey(keyConfig).then((current2) => {
37173
37497
  try {
37174
- if (!objects || createHash37("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
37498
+ if (!objects || createHash38("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
37175
37499
  keyWatermark = current2.deletionWatermark;
37176
37500
  lastKeyCheck = Number(process.hrtime.bigint() / 1000000n);
37177
37501
  } finally {
@@ -37194,7 +37518,7 @@ async function startTravelGateway(config) {
37194
37518
  async function runTravelGatewayCli(args) {
37195
37519
  if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-gateway serve --config /absolute/private-config.json" };
37196
37520
  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());
37521
+ const config = JSON.parse(readPrivateFile(path36(args[2]), 65536).toString());
37198
37522
  const gateway = await startTravelGateway(config);
37199
37523
  let closing = false;
37200
37524
  const stop = () => {
@@ -37215,12 +37539,12 @@ if (process.argv[1] && /[\\/](gateway-main\.ts|travel-gateway\.mjs)$/.test(proce
37215
37539
 
37216
37540
  // src/continuity/pairing-control.ts
37217
37541
  async function startPairingControl(config) {
37218
- const directory2 = resolve12(config.directory), file2 = join32(directory2, "pairing.json"), read2 = (name) => readPrivateFile(join32(directory2, name), 65536);
37542
+ const directory2 = resolve12(config.directory), file2 = join33(directory2, "pairing.json"), read2 = (name) => readPrivateFile(join33(directory2, name), 65536);
37219
37543
  const tls3 = { ca: read2("ca.pem"), cert: read2("server.pem"), key: read2("server.key") };
37220
- const authority = new TravelAuthority({ directory: join32(directory2, "authority") });
37544
+ const authority = new TravelAuthority({ directory: join33(directory2, "authority") });
37221
37545
  let binding;
37222
37546
  try {
37223
- if (existsSync15(file2)) {
37547
+ if (existsSync16(file2)) {
37224
37548
  binding = JSON.parse(readPrivateFile(file2, 65536).toString());
37225
37549
  if (JSON.stringify(binding.identity) !== JSON.stringify(config.identity) || binding.buildManifestId !== config.buildManifestId || binding.keySha256 !== config.keySha256) throw new Error("TRAVEL_PAIRING_IDENTITY");
37226
37550
  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 +37556,10 @@ async function startPairingControl(config) {
37232
37556
  } finally {
37233
37557
  authority.close();
37234
37558
  }
37235
- const keys = new KeyServiceStore(join32(directory2, "keys"));
37559
+ const keys = new KeyServiceStore(join33(directory2, "keys"));
37236
37560
  const key4 = read2("data.key");
37237
37561
  try {
37238
- if (createHash38("sha256").update(key4).digest("hex") !== config.keySha256) throw new Error("TRAVEL_PAIRING_KEY");
37562
+ if (createHash39("sha256").update(key4).digest("hex") !== config.keySha256) throw new Error("TRAVEL_PAIRING_KEY");
37239
37563
  try {
37240
37564
  keys.assertIdentity(binding.keyIdentity);
37241
37565
  } catch {
@@ -37256,13 +37580,13 @@ async function startPairingControl(config) {
37256
37580
  const fp = (name) => new X509Certificate(read2(name + ".pem")).fingerprint256.replaceAll(":", "").toLowerCase();
37257
37581
  const peers = { [fp("local")]: binding.tokens.local, [fp("cloud")]: binding.tokens.cloud };
37258
37582
  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") };
37583
+ const tlsFiles = { caFile: join33(directory2, "ca.pem"), certFile: join33(directory2, "server.pem"), keyFile: join33(directory2, "server.key") };
37584
+ const managerTls = { ...tlsFiles, certFile: join33(directory2, "manager.pem"), keyFile: join33(directory2, "manager.key") };
37261
37585
  const gatewayConfig = {
37262
37586
  identity: config.identity,
37263
- authorityDir: join32(directory2, "authority"),
37264
- gatewayDir: join32(directory2, "gateway"),
37265
- objectsDir: join32(directory2, "objects"),
37587
+ authorityDir: join33(directory2, "authority"),
37588
+ gatewayDir: join33(directory2, "gateway"),
37589
+ objectsDir: join33(directory2, "objects"),
37266
37590
  tls: tlsFiles,
37267
37591
  host: "127.0.0.1",
37268
37592
  port: config.ports.gateway,
@@ -37270,12 +37594,12 @@ async function startPairingControl(config) {
37270
37594
  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
37595
  allowedPeers: peers,
37272
37596
  recoveryPeers: { [fp("manager")]: binding.tokens.local },
37273
- platformStateDir: join32(directory2, "platform"),
37597
+ platformStateDir: join33(directory2, "platform"),
37274
37598
  channels: config.channels,
37275
37599
  feishu: { ...config.feishu, ingressEnabled: false },
37276
37600
  ingressEnabled: false
37277
37601
  };
37278
- let ingress = existsSync15(join32(directory2, "ingress-enabled.json"));
37602
+ let ingress = existsSync16(join33(directory2, "ingress-enabled.json"));
37279
37603
  let gateway = await startTravelGateway({ ...gatewayConfig, ingressEnabled: ingress, feishu: { ...gatewayConfig.feishu, ingressEnabled: ingress && config.channels?.feishu?.enabled === true } });
37280
37604
  let changing = false, closed = false;
37281
37605
  const pairServer = createServer4({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
@@ -37304,12 +37628,12 @@ async function startPairingControl(config) {
37304
37628
  if (input.action === "enable_ingress" && !ingress) {
37305
37629
  await gateway.close();
37306
37630
  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 });
37631
+ writeFileSync15(join33(directory2, "ingress-enabled.json"), JSON.stringify({ identity: config.identity }), { mode: 384, flush: true });
37308
37632
  ingress = true;
37309
37633
  }
37310
37634
  if (input.action === "disable_ingress" && ingress) {
37311
37635
  if (gateway.authority.status(binding.local).activeNodeId !== null) throw new Error("TRAVEL_INITIAL_SOURCE_RUNNING");
37312
- rmSync3(join32(directory2, "ingress-enabled.json"), { force: true });
37636
+ rmSync3(join33(directory2, "ingress-enabled.json"), { force: true });
37313
37637
  await gateway.close();
37314
37638
  gateway = await startTravelGateway(gatewayConfig);
37315
37639
  ingress = false;