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);
@@ -543,9 +543,9 @@ function assertPrivateStat(stat3, directory2) {
543
543
  if ((directory2 ? !stat3.isDirectory() : !stat3.isFile()) || process.platform !== "win32" && ((stat3.mode & 63) !== 0 || stat3.uid !== process.getuid?.()))
544
544
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
545
545
  }
546
- function readPrivateFile(path36, maximumBytes = 65536) {
547
- assertPrivateStat(lstatSync2(path36), false);
548
- const fd = openSync2(path36, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
546
+ function readPrivateFile(path37, maximumBytes = 65536) {
547
+ assertPrivateStat(lstatSync2(path37), false);
548
+ const fd = openSync2(path37, constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0));
549
549
  try {
550
550
  const stat3 = fstatSync2(fd);
551
551
  assertPrivateStat(stat3, false);
@@ -565,14 +565,14 @@ var init_key_service_store = __esm({
565
565
  import { randomUUID as randomUUID3, verify as verify2 } from "node:crypto";
566
566
  import { constants as constants3, closeSync as closeSync3, existsSync as existsSync2, fstatSync as fstatSync3, fsyncSync as fsyncSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, openSync as openSync3, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "node:fs";
567
567
  import { basename, dirname as dirname2, join as join4, resolve as resolve3 } from "node:path";
568
- function assertPrivateDirectory2(path36) {
569
- const stat3 = lstatSync3(path36);
568
+ function assertPrivateDirectory2(path37) {
569
+ const stat3 = lstatSync3(path37);
570
570
  if (!stat3.isDirectory() || stat3.isSymbolicLink() || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
571
571
  }
572
- function readPrivateFile2(path36, maximum) {
573
- const before = lstatSync3(path36);
572
+ function readPrivateFile2(path37, maximum) {
573
+ const before = lstatSync3(path37);
574
574
  if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
575
- const fd = openSync3(path36, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
575
+ const fd = openSync3(path37, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
576
576
  try {
577
577
  if (fstatSync3(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
578
578
  return readFileSync2(fd);
@@ -580,12 +580,12 @@ function readPrivateFile2(path36, maximum) {
580
580
  closeSync3(fd);
581
581
  }
582
582
  }
583
- function writeControl(path36, value) {
584
- const temporary = path36 + "." + randomUUID3() + ".tmp";
583
+ function writeControl(path37, value) {
584
+ const temporary = path37 + "." + randomUUID3() + ".tmp";
585
585
  writeFileSync2(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
586
- renameSync(temporary, path36);
586
+ renameSync(temporary, path37);
587
587
  if (process.platform !== "win32") {
588
- const fd = openSync3(dirname2(path36), "r");
588
+ const fd = openSync3(dirname2(path37), "r");
589
589
  try {
590
590
  fsyncSync3(fd);
591
591
  } finally {
@@ -1610,6 +1610,13 @@ function tokenize(text2) {
1610
1610
  function tokenizeToField(text2) {
1611
1611
  return tokenize(text2).join(" ");
1612
1612
  }
1613
+ function cjkBigrams(text2) {
1614
+ const out = [];
1615
+ for (const seg of String(text2 ?? "").match(/[\u4e00-\u9fff]{2,}/g) ?? []) {
1616
+ for (let i = 0; i + 1 < seg.length; i++) out.push(seg.slice(i, i + 2));
1617
+ }
1618
+ return out;
1619
+ }
1613
1620
  var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1614
1621
  var init_tokenizer = __esm({
1615
1622
  "src/mem7/core/tokenizer.ts"() {
@@ -1896,14 +1903,14 @@ var init_live = __esm({
1896
1903
  }
1897
1904
  /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
1898
1905
  async persistToFile(dotPath, val, atomic = false) {
1899
- const fs26 = await import("node:fs");
1906
+ const fs27 = await import("node:fs");
1900
1907
  const cfgPath = this.current?._configFilePath;
1901
- if (!cfgPath || !fs26.existsSync(cfgPath)) {
1908
+ if (!cfgPath || !fs27.existsSync(cfgPath)) {
1902
1909
  console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
1903
1910
  return false;
1904
1911
  }
1905
1912
  try {
1906
- const raw = JSON.parse(fs26.readFileSync(cfgPath, "utf-8"));
1913
+ const raw = JSON.parse(fs27.readFileSync(cfgPath, "utf-8"));
1907
1914
  const keys = dotPath.split(".");
1908
1915
  let o = raw;
1909
1916
  for (let i = 0; i < keys.length - 1; i++) {
@@ -1913,7 +1920,7 @@ var init_live = __esm({
1913
1920
  o[keys[keys.length - 1]] = val;
1914
1921
  if (atomic) {
1915
1922
  writeConfigAtomic(cfgPath, raw);
1916
- } else fs26.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
1923
+ } else fs27.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
1917
1924
  const lastKey = keys[keys.length - 1].toLowerCase();
1918
1925
  const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
1919
1926
  const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
@@ -2251,12 +2258,12 @@ function overlaps(a, b) {
2251
2258
  return (a.validTo === null || b.validFrom === null || b.validFrom < a.validTo) && (b.validTo === null || a.validFrom === null || a.validFrom < b.validTo);
2252
2259
  }
2253
2260
  function canonicalJson(value) {
2254
- const normalize6 = (input) => {
2255
- if (Array.isArray(input)) return input.map(normalize6);
2256
- 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)]));
2261
+ const normalize7 = (input) => {
2262
+ if (Array.isArray(input)) return input.map(normalize7);
2263
+ 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)]));
2257
2264
  return input;
2258
2265
  };
2259
- const json = JSON.stringify(normalize6(value));
2266
+ const json = JSON.stringify(normalize7(value));
2260
2267
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
2261
2268
  return json;
2262
2269
  }
@@ -2780,8 +2787,9 @@ function invalidateDerivedDependencies(db2, event2) {
2780
2787
  }
2781
2788
  return invalidateChildren(db2, event2.scopeId, pending, event2.kind);
2782
2789
  }
2783
- function invalidateScopeDependencies(db2, scope, parent, reason) {
2784
- 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);
2790
+ function invalidateScopeDependencies(db2, scope, parent, reason, options = {}) {
2791
+ 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);
2792
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
2785
2793
  invalidateChildren(db2, scope, children, reason);
2786
2794
  }
2787
2795
  function invalidateChildren(db2, scope, pending, reason) {
@@ -2801,7 +2809,7 @@ function invalidateChildren(db2, scope, pending, reason) {
2801
2809
  }
2802
2810
  const state = child.deleted ? "deleted" : "needs_revalidation";
2803
2811
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2804
- 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);
2812
+ 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);
2805
2813
  result.push(child.child_id);
2806
2814
  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" })));
2807
2815
  }
@@ -2896,7 +2904,7 @@ var init_dependencies = __esm({
2896
2904
  if (previous && previous.version === version && previous.state !== "current") throw new Error("DERIVATION_REQUIRES_NEW_VERSION");
2897
2905
  this.assertReferences(scope, dependencies);
2898
2906
  if (previous?.version === version) {
2899
- const normalize6 = (refs) => JSON.stringify(refs.map((ref) => [
2907
+ const normalize7 = (refs) => JSON.stringify(refs.map((ref) => [
2900
2908
  ref.parentKind,
2901
2909
  ref.parentId,
2902
2910
  ref.parentVersion,
@@ -2904,7 +2912,7 @@ var init_dependencies = __esm({
2904
2912
  ref.slotRevision ?? null,
2905
2913
  ref.role
2906
2914
  ]).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
2907
- if (normalize6(this.refs(scope, kind, id3)) !== normalize6(dependencies)) throw new Error("DERIVATION_VERSION_CONFLICT");
2915
+ if (normalize7(this.refs(scope, kind, id3)) !== normalize7(dependencies)) throw new Error("DERIVATION_VERSION_CONFLICT");
2908
2916
  return;
2909
2917
  }
2910
2918
  this.db.prepare(`INSERT INTO memory_derivations VALUES (?,?,?,?,'current',NULL,?)
@@ -3255,6 +3263,12 @@ function loadArrow() {
3255
3263
  }
3256
3264
  return arrowPromise;
3257
3265
  }
3266
+ function shortCjkQueryBigrams(text2) {
3267
+ const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
3268
+ if (!chars || chars > 6) return null;
3269
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
3270
+ return grams.length ? grams : null;
3271
+ }
3258
3272
  function buildSchemas(arrow) {
3259
3273
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
3260
3274
  const commonFields = () => [
@@ -3351,7 +3365,7 @@ function textColumnOf(kind) {
3351
3365
  return "fact";
3352
3366
  }
3353
3367
  }
3354
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3368
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3355
3369
  var init_vector_store = __esm({
3356
3370
  "src/mem7/core/vector-store.ts"() {
3357
3371
  "use strict";
@@ -3382,6 +3396,14 @@ var init_vector_store = __esm({
3382
3396
  agent_case: ["task_intent_tokens", "approach_tokens"],
3383
3397
  agent_skill: ["description_tokens", "content_tokens"]
3384
3398
  };
3399
+ BM25_TEXT_FIELDS = {
3400
+ foresight: ["foresight", "evidence"],
3401
+ episode: ["episode"],
3402
+ atomic_fact: ["fact"],
3403
+ agent_case: ["task_intent", "approach"],
3404
+ agent_skill: ["description", "content"]
3405
+ };
3406
+ sqlLiteral = (value) => value.replace(/'/g, "''");
3385
3407
  RRF_K = 60;
3386
3408
  warnedFts = /* @__PURE__ */ new Set();
3387
3409
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3979,6 +4001,28 @@ var init_vector_store = __esm({
3979
4001
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3980
4002
  }
3981
4003
  }
4004
+ const grams = shortCjkQueryBigrams(queryText);
4005
+ if (grams) {
4006
+ try {
4007
+ const textCols = BM25_TEXT_FIELDS[kind];
4008
+ const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4009
+ const where2 = compileFilter(opts.filter);
4010
+ const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
4011
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4012
+ for (const r of extra) {
4013
+ const rid = String(r.id ?? "");
4014
+ if (!rid) continue;
4015
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4016
+ const matched = grams.filter((gram) => text2.includes(gram)).length;
4017
+ if (!matched) continue;
4018
+ const score = maxScore + matched / grams.length;
4019
+ const cur = best.get(rid);
4020
+ if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
4021
+ else best.set(rid, { ...r, _score: score });
4022
+ }
4023
+ } catch {
4024
+ }
4025
+ }
3982
4026
  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) }));
3983
4027
  } catch (err) {
3984
4028
  const msg2 = String(err?.message ?? err);
@@ -4504,7 +4548,7 @@ import { createHash as createHash9 } from "node:crypto";
4504
4548
  function projectedSourceIdFromScopeId(id3, originKey, sourceVersion) {
4505
4549
  return "src_" + digest([id3, originKey, sourceVersion]);
4506
4550
  }
4507
- var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4551
+ var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4508
4552
  var init_source_store = __esm({
4509
4553
  "src/mem7/core/source-store.ts"() {
4510
4554
  "use strict";
@@ -4516,6 +4560,7 @@ var init_source_store = __esm({
4516
4560
  init_watermarks();
4517
4561
  init_interpretation_impact();
4518
4562
  init_conversation_text();
4563
+ RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
4519
4564
  SOURCE_SCHEMA = `
4520
4565
  CREATE TABLE memory_scopes (
4521
4566
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -4697,8 +4742,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4697
4742
  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");
4698
4743
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
4699
4744
  this.db.prepare("UPDATE memory_scopes SET source_seq=source_seq+1,context_revision=context_revision+1 WHERE scope_id=?").run(id3);
4700
- invalidateScopeDependencies(this.db, id3, "sources", "source.received");
4701
- invalidateScopeDependencies(this.db, id3, "context", "source.received");
4745
+ invalidateScopeDependencies(this.db, id3, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4746
+ invalidateScopeDependencies(this.db, id3, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4702
4747
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id3).source_seq);
4703
4748
  const sourceId = projectedSourceIdFromScopeId(id3, input.originKey, version);
4704
4749
  const receiptId = "rcpt_" + digest([id3, sourceId]);
@@ -4868,10 +4913,10 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4868
4913
  AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)
4869
4914
  ORDER BY source_seq DESC LIMIT ?`).all(scopeId(scope), source.sessionId, source.sourceSeq, limit2).map((row) => this.source(row)).reverse();
4870
4915
  }
4871
- pendingInterpretations(scope, sessionId, limit2 = 50, cutoff, newestFirst = false, states, textTerms, roles) {
4872
- if (states?.some((state) => !["received", "applied", "needs_review", "failed"].includes(state))) throw new Error("INVALID_SOURCE_STATE");
4916
+ pendingInterpretations(scope, sessionId, limit2 = 50, cutoff, newestFirst = false, states2, textTerms, roles) {
4917
+ if (states2?.some((state) => !["received", "applied", "needs_review", "failed"].includes(state))) throw new Error("INVALID_SOURCE_STATE");
4873
4918
  if (roles?.some((role) => !["user", "assistant", "tool"].includes(role))) throw new Error("INVALID_SOURCE_ROLE");
4874
- if (states?.length === 0) return [];
4919
+ if (states2?.length === 0) return [];
4875
4920
  if (roles?.length === 0) return [];
4876
4921
  const terms = textTerms ? [...new Set(textTerms.map((term) => term.trim().toLowerCase()).filter(Boolean))] : void 0;
4877
4922
  if (terms?.length === 0) return [];
@@ -4879,7 +4924,7 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4879
4924
  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));
4880
4925
  if (cutoff) return historicalRows(this.db, scope, "source", cutoff).filter((row) => !["applied", "deleted"].includes(row.state)).flatMap((row) => {
4881
4926
  const source = this.get(scope, row.targetId, cutoff);
4882
- 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 [];
4927
+ 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 [];
4883
4928
  return [{
4884
4929
  ...source,
4885
4930
  state: row.state,
@@ -4891,13 +4936,13 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4891
4936
  const rows = this.db.prepare(`SELECT * FROM memory_sources s WHERE scope_id=? AND interpretation_status<>'applied'
4892
4937
  AND interpretation_status<>'deleted' AND NOT EXISTS (SELECT 1 FROM memory_sources newer
4893
4938
  WHERE newer.scope_id=s.scope_id AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)
4894
- ${this.recoveryClause("s")} ${sessionId ? "AND session_id=?" : ""} ${states ? `AND interpretation_status IN (${states.map(() => "?").join(",")})` : ""}
4939
+ ${this.recoveryClause("s")} ${sessionId ? "AND session_id=?" : ""} ${states2 ? `AND interpretation_status IN (${states2.map(() => "?").join(",")})` : ""}
4895
4940
  ${terms ? `AND (${terms.map((term) => latinTerm(term) ? "(' ' || lower(s.text) || ' ') GLOB ?" : "instr(lower(s.text), ?) > 0").join(" OR ")})` : ""}
4896
4941
  ${roles ? `AND role IN (${roles.map(() => "?").join(",")})` : ""}
4897
4942
  ORDER BY source_seq ${newestFirst ? "DESC" : "ASC"} LIMIT ?`).all(
4898
4943
  scopeId(scope),
4899
4944
  ...sessionId ? [sessionId] : [],
4900
- ...states ?? [],
4945
+ ...states2 ?? [],
4901
4946
  ...terms?.map((term) => latinTerm(term) ? `*[^a-z0-9_]${term}[^a-z0-9_]*` : term) ?? [],
4902
4947
  ...roles ?? [],
4903
4948
  limit2
@@ -5390,8 +5435,8 @@ var init_recovery_deletion = __esm({
5390
5435
  const { owners, parents } = this.links(table, row);
5391
5436
  for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
5392
5437
  if (table === "memory_artifact_publications") {
5393
- const medium = text(row, "medium"), path36 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5394
- const identity = medium === "markdown" && path36 ? "file:mem7/" + path36 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash11("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5438
+ const medium = text(row, "medium"), path37 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5439
+ const identity = medium === "markdown" && path37 ? "file:mem7/" + path37 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash11("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5395
5440
  if (identity) {
5396
5441
  const rows = this.artifactPaths.get(identity) ?? [];
5397
5442
  rows.push(row);
@@ -5399,8 +5444,8 @@ var init_recovery_deletion = __esm({
5399
5444
  }
5400
5445
  }
5401
5446
  }
5402
- blocksArtifactPath(kind, path36) {
5403
- const rows = this.artifactPaths.get(kind + ":" + path36);
5447
+ blocksArtifactPath(kind, path37) {
5448
+ const rows = this.artifactPaths.get(kind + ":" + path37);
5404
5449
  return rows?.some((row) => this.blocks("memory_artifact_publications", row));
5405
5450
  }
5406
5451
  blocks(table, row) {
@@ -6419,7 +6464,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6419
6464
  };
6420
6465
  const candidates2 = [];
6421
6466
  const duplicateIds = /* @__PURE__ */ new Set();
6422
- const inside = (path36) => path36 && !isAbsolute2(path36) && path36 !== ".." && !path36.startsWith(`..${sep2}`);
6467
+ const inside = (path37) => path37 && !isAbsolute2(path37) && path37 !== ".." && !path37.startsWith(`..${sep2}`);
6423
6468
  for (const relativePath of input.files) {
6424
6469
  const logical = resolve4(root, relativePath);
6425
6470
  let canonical4;
@@ -6433,10 +6478,10 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6433
6478
  gap("projection_path_unverified");
6434
6479
  continue;
6435
6480
  }
6436
- const path36 = relative2(root, canonical4).replace(/\\/g, "/");
6481
+ const path37 = relative2(root, canonical4).replace(/\\/g, "/");
6437
6482
  const user = `users/${input.scope.ownerId}/`;
6438
6483
  const agent = store.ownerProjectionPath("agents", input.scope.ownerId, input.scope).replace(/\\/g, "/") + "/";
6439
- const kind = path36.startsWith(`${user}episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "episode" : path36.startsWith(`${user}.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "atomic_fact" : path36.startsWith(`${user}.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "foresight" : path36.startsWith(`${agent}.cases/`) && /\/agent_case-\d{4}-\d{2}-\d{2}\.md$/.test(path36) ? "agent_case" : void 0;
6484
+ 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;
6440
6485
  if (!kind) {
6441
6486
  gap("projection_kind_or_owner_unverified");
6442
6487
  continue;
@@ -6473,9 +6518,9 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6473
6518
  continue;
6474
6519
  }
6475
6520
  const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key4, kind, match[1]);
6476
- const target = join8(store.mem7RootPath(), path36);
6521
+ const target = join8(store.mem7RootPath(), path37);
6477
6522
  if (previous) {
6478
- if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path36 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6523
+ if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path37 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6479
6524
  gap("projection_mapping_conflict");
6480
6525
  continue;
6481
6526
  }
@@ -6491,7 +6536,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6491
6536
  candidates2.push({
6492
6537
  file: canonical4,
6493
6538
  fileHash,
6494
- relativePath: path36,
6539
+ relativePath: path37,
6495
6540
  id: match[1],
6496
6541
  kind,
6497
6542
  parent,
@@ -7973,9 +8018,9 @@ function normalize3(input) {
7973
8018
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
7974
8019
  return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
7975
8020
  }
7976
- function directory(path36) {
7977
- const info = lstatSync6(path36);
7978
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path36) !== resolve5(path36) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
8021
+ function directory(path37) {
8022
+ const info = lstatSync6(path37);
8023
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path37) !== resolve5(path37) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
7979
8024
  throw new Error("REPLICATION_REGISTRATION_INVALID");
7980
8025
  }
7981
8026
  function readRuntimeReplicationRegistration(stateDir, component, key4) {
@@ -8079,10 +8124,10 @@ var init_runtime_replication = __esm({
8079
8124
 
8080
8125
  // src/memory/topics-history/index.ts
8081
8126
  import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
8082
- function parseTopicHistoryPath(path36) {
8083
- if (!path36.startsWith("topics-history://") || path36.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8127
+ function parseTopicHistoryPath(path37) {
8128
+ if (!path37.startsWith("topics-history://") || path37.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8084
8129
  try {
8085
- return JSON.parse(Buffer.from(path36.slice(17), "base64url").toString("utf8"));
8130
+ return JSON.parse(Buffer.from(path37.slice(17), "base64url").toString("utf8"));
8086
8131
  } catch {
8087
8132
  throw new Error("INVALID_HISTORY_REFERENCE");
8088
8133
  }
@@ -10027,23 +10072,23 @@ var init_facts = __esm({
10027
10072
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
10028
10073
  }
10029
10074
  for (const [index, evidence] of proposal.evidence.entries()) {
10030
- const path36 = `evidence[${index}]`;
10031
- if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path36} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
10075
+ const path37 = `evidence[${index}]`;
10076
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path37} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
10032
10077
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
10033
10078
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
10034
10079
  AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
10035
- 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`);
10036
- 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`);
10080
+ 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`);
10081
+ 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`);
10037
10082
  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) {
10038
10083
  const count = occurrences(source.text, evidence.quote);
10039
- 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`);
10084
+ 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`);
10040
10085
  }
10041
- 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`);
10086
+ 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`);
10042
10087
  const relationValue = proposal.value;
10043
10088
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
10044
10089
  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");
10045
10090
  }
10046
- 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`);
10091
+ 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`);
10047
10092
  if (proposal.claimKind !== "inference") {
10048
10093
  if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
10049
10094
  if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
@@ -10403,7 +10448,7 @@ function contentHash(text2) {
10403
10448
  function mem7Root(stateDir) {
10404
10449
  return join11(stateDir, "mem7");
10405
10450
  }
10406
- var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
10451
+ var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
10407
10452
  var init_store = __esm({
10408
10453
  "src/mem7/core/store.ts"() {
10409
10454
  "use strict";
@@ -10441,6 +10486,7 @@ var init_store = __esm({
10441
10486
  init_job_retention();
10442
10487
  init_retire_graph_audits();
10443
10488
  STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
10489
+ STARVATION_GRACE_MS = 36e5;
10444
10490
  SCHEMA = `
10445
10491
  CREATE TABLE IF NOT EXISTS memcells (
10446
10492
  id TEXT PRIMARY KEY,
@@ -11034,13 +11080,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11034
11080
  const version = expectedVersion ?? this.dependencies.version(scope, kind, id3);
11035
11081
  this.dependencies.assertCurrent(scope, kind, id3, version);
11036
11082
  const digest7 = createHash20("sha256").update(content.trim()).digest("hex");
11037
- const path36 = relative3(this.root, file2).replace(/\\/g, "/");
11083
+ const path37 = relative3(this.root, file2).replace(/\\/g, "/");
11038
11084
  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);
11039
- if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path36)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
11085
+ if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path37)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
11040
11086
  this.db.prepare(`INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)
11041
11087
  ON CONFLICT(scope_id,kind,entry_id) DO UPDATE SET path=excluded.path,version=excluded.version,digest=excluded.digest
11042
- WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path36, version, digest7);
11043
- this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path36, markdown: content.trim() });
11088
+ WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path37, version, digest7);
11089
+ this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path37, markdown: content.trim() });
11044
11090
  });
11045
11091
  }
11046
11092
  projectionMatches(scope, kind, id3, file2, content) {
@@ -11237,8 +11283,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11237
11283
  };
11238
11284
  }
11239
11285
  unscopedProjectionMatches(ownerId, kind, id3, file2, content) {
11240
- const path36 = relative3(this.root, file2).replace(/\\/g, "/");
11241
- const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path36);
11286
+ const path37 = relative3(this.root, file2).replace(/\\/g, "/");
11287
+ const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path37);
11242
11288
  if (mappings.length) {
11243
11289
  if (mappings.length !== 1) return false;
11244
11290
  const scope = this.sources.scope(mappings[0].scope_id);
@@ -11531,7 +11577,7 @@ ${e.outcome}
11531
11577
  return this.transaction(() => {
11532
11578
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
11533
11579
  const scopeFilter = options.scopeId !== void 0 ? " AND scope_id=?" : "";
11534
- 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"}
11580
+ 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"}
11535
11581
  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)
11536
11582
  AND ((status='pending' AND next_run_at<=?)
11537
11583
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -11551,40 +11597,48 @@ ${e.outcome}
11551
11597
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
11552
11598
  AND (kind IN ('social.interpret','source.interpret','relationship.cognition') OR scope_id NOT LIKE 'resource:%' OR NOT EXISTS (SELECT 1 FROM ome_jobs prior
11553
11599
  WHERE prior.scope_id=j.scope_id AND prior.id<j.id AND prior.status IN ('pending','running')
11554
- 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)
11555
- -- Retrying an old deferred job must not reserve the next stage budget.
11556
- -- Boundary/resource predecessor predicates above still enforce ordering.
11557
- ORDER BY priority,next_run_at,id LIMIT ?`).all(now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit2);
11558
- const claimedScopes = /* @__PURE__ */ new Set();
11559
- return rows.flatMap((row) => {
11560
- if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
11561
- const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
11562
- if (updated.scope_id !== row.scope_id && updated.scope_id) {
11563
- const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
11564
- AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
11565
- 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);
11566
- if (conflict) return [];
11567
- }
11568
- return [updated];
11569
- }).filter((row) => {
11570
- if (!row.scope_id) return true;
11571
- if (claimedScopes.has(row.scope_id)) return false;
11572
- claimedScopes.add(row.scope_id);
11573
- return true;
11574
- }).map((row) => {
11575
- const leaseToken = randomUUID9();
11576
- this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
11577
- return {
11578
- id: row.id,
11579
- kind: row.kind,
11580
- payload: JSON.parse(row.payload),
11581
- attempts: row.attempts,
11582
- leaseToken,
11583
- inputVersion: row.input_version,
11584
- scopeId: row.scope_id ?? void 0,
11585
- result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
11586
- };
11587
- });
11600
+ 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)`;
11601
+ const select = (starved2) => {
11602
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
11603
+ ORDER BY priority,next_run_at,id LIMIT ?`;
11604
+ 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];
11605
+ return this.db.prepare(sql).all(...args);
11606
+ };
11607
+ const claim = (rows) => {
11608
+ const claimedScopes = /* @__PURE__ */ new Set();
11609
+ return rows.flatMap((row) => {
11610
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
11611
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
11612
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
11613
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
11614
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
11615
+ 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);
11616
+ if (conflict) return [];
11617
+ }
11618
+ return [updated];
11619
+ }).filter((row) => {
11620
+ if (!row.scope_id) return true;
11621
+ if (claimedScopes.has(row.scope_id)) return false;
11622
+ claimedScopes.add(row.scope_id);
11623
+ return true;
11624
+ }).map((row) => {
11625
+ const leaseToken = randomUUID9();
11626
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
11627
+ return {
11628
+ id: row.id,
11629
+ kind: row.kind,
11630
+ payload: JSON.parse(row.payload),
11631
+ attempts: row.attempts,
11632
+ leaseToken,
11633
+ inputVersion: row.input_version,
11634
+ scopeId: row.scope_id ?? void 0,
11635
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
11636
+ };
11637
+ });
11638
+ };
11639
+ if (options.staleOnly) return claim(select(true));
11640
+ const starved = claim(select(true));
11641
+ return starved.length ? starved : claim(select(false));
11588
11642
  });
11589
11643
  }
11590
11644
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -17962,9 +18016,9 @@ function isAutoMemPath(absolutePath, workspace) {
17962
18016
  return normalizedPath.startsWith(getAutoMemPath(workspace));
17963
18017
  }
17964
18018
  async function ensureMemoryDirExists(memoryDir) {
17965
- const fs26 = await import("node:fs");
18019
+ const fs27 = await import("node:fs");
17966
18020
  try {
17967
- await fs26.promises.mkdir(memoryDir, { recursive: true });
18021
+ await fs27.promises.mkdir(memoryDir, { recursive: true });
17968
18022
  } catch (e) {
17969
18023
  const code = e?.code;
17970
18024
  if (code !== "EEXIST") {
@@ -18145,8 +18199,8 @@ __export(memdir_exports, {
18145
18199
  loadMemoryPrompt: () => loadMemoryPrompt,
18146
18200
  truncateEntrypointContent: () => truncateEntrypointContent
18147
18201
  });
18148
- import { readFileSync as readFileSync15 } from "node:fs";
18149
- import { join as join28 } from "node:path";
18202
+ import { readFileSync as readFileSync16 } from "node:fs";
18203
+ import { join as join29 } from "node:path";
18150
18204
  function truncateEntrypointContent(raw) {
18151
18205
  const trimmed = raw.trim();
18152
18206
  const contentLines = trimmed.split("\n");
@@ -18239,11 +18293,11 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
18239
18293
  }
18240
18294
  function buildMemoryPrompt(params) {
18241
18295
  const { displayName, memoryDir, extraGuidelines } = params;
18242
- const entrypoint = join28(memoryDir, ENTRYPOINT_NAME);
18296
+ const entrypoint = join29(memoryDir, ENTRYPOINT_NAME);
18243
18297
  let entrypointContent = params.entrypointContent ?? "";
18244
18298
  if (params.entrypointContent === void 0) {
18245
18299
  try {
18246
- entrypointContent = readFileSync15(entrypoint, "utf-8");
18300
+ entrypointContent = readFileSync16(entrypoint, "utf-8");
18247
18301
  } catch {
18248
18302
  }
18249
18303
  }
@@ -18289,8 +18343,8 @@ __export(context_analyzer_exports, {
18289
18343
  formatContextReport: () => formatContextReport,
18290
18344
  scanMemoryFiles: () => scanMemoryFiles
18291
18345
  });
18292
- import * as fs22 from "node:fs";
18293
- import * as path29 from "node:path";
18346
+ import * as fs23 from "node:fs";
18347
+ import * as path30 from "node:path";
18294
18348
  function estimateMessageTokens2(m) {
18295
18349
  let tokens = 0;
18296
18350
  if (typeof m.content === "string") {
@@ -18400,9 +18454,9 @@ function breakdownMessages(messages) {
18400
18454
  }
18401
18455
  async function scanMemoryFiles(workspace) {
18402
18456
  const files = [];
18403
- const soul = readFileIfExists(path29.join(workspace, "SOUL.md"));
18457
+ const soul = readFileIfExists(path30.join(workspace, "SOUL.md"));
18404
18458
  if (soul) files.push({ path: "SOUL.md", tokens: roughTokenCountEstimation(soul), stable: true });
18405
- const agents = readFileIfExists(path29.join(workspace, "AGENTS.md"));
18459
+ const agents = readFileIfExists(path30.join(workspace, "AGENTS.md"));
18406
18460
  if (agents) files.push({ path: "AGENTS.md", tokens: roughTokenCountEstimation(agents), stable: true });
18407
18461
  try {
18408
18462
  const { buildMemoryPrompt: buildMemoryPrompt2 } = await Promise.resolve().then(() => (init_memdir(), memdir_exports));
@@ -18418,7 +18472,7 @@ async function scanMemoryFiles(workspace) {
18418
18472
  }
18419
18473
  function readFileIfExists(filePath2) {
18420
18474
  try {
18421
- if (fs22.existsSync(filePath2)) return fs22.readFileSync(filePath2, "utf-8");
18475
+ if (fs23.existsSync(filePath2)) return fs23.readFileSync(filePath2, "utf-8");
18422
18476
  } catch {
18423
18477
  }
18424
18478
  return null;
@@ -18642,7 +18696,7 @@ var init_gateway_media = __esm({
18642
18696
  // src/continuity/gateway-main.ts
18643
18697
  import { isAbsolute as isAbsolute5, resolve as resolve11 } from "node:path";
18644
18698
  import { fileURLToPath as fileURLToPath4 } from "node:url";
18645
- import { createHash as createHash37 } from "node:crypto";
18699
+ import { createHash as createHash38 } from "node:crypto";
18646
18700
  import * as lark3 from "@larksuiteoapi/node-sdk";
18647
18701
 
18648
18702
  // src/continuity/authority.ts
@@ -18708,9 +18762,9 @@ var TravelAuthority = class {
18708
18762
  this.owner.close();
18709
18763
  throw new Error("TRAVEL_AUTHORITY_BUSY", { cause: error });
18710
18764
  }
18711
- const path36 = join2(options.directory, "authority.sqlite"), keyFile = join2(options.directory, "authority-signing.pem");
18765
+ const path37 = join2(options.directory, "authority.sqlite"), keyFile = join2(options.directory, "authority-signing.pem");
18712
18766
  try {
18713
- const present = existsSync(path36), keyPresent = existsSync(keyFile);
18767
+ const present = existsSync(path37), keyPresent = existsSync(keyFile);
18714
18768
  if (present !== keyPresent) throw new Error("TRAVEL_AUTHORITY_RECOVERY_REQUIRED");
18715
18769
  if (!keyPresent) {
18716
18770
  const keys = generateKeyPairSync("ed25519");
@@ -18718,8 +18772,8 @@ var TravelAuthority = class {
18718
18772
  }
18719
18773
  this.signingKey = readPrivateFile(keyFile).toString();
18720
18774
  this.publicKey = createPublicKey(this.signingKey).export({ format: "pem", type: "spki" }).toString();
18721
- preparePrivateDatabase(path36);
18722
- this.db = new DatabaseSync3(path36);
18775
+ preparePrivateDatabase(path37);
18776
+ this.db = new DatabaseSync3(path37);
18723
18777
  this.db.exec(`PRAGMA busy_timeout=1000; PRAGMA synchronous=FULL;
18724
18778
  CREATE TABLE IF NOT EXISTS seats(identity TEXT PRIMARY KEY,epoch INTEGER NOT NULL,active_node TEXT,active_boot TEXT,
18725
18779
  floor INTEGER NOT NULL,checkpoint TEXT NOT NULL,build TEXT NOT NULL,retired TEXT,frozen INTEGER NOT NULL DEFAULT 0);
@@ -19181,9 +19235,9 @@ import { isAbsolute, join as join3, relative, resolve as resolve2, sep } from "n
19181
19235
  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(" "));
19182
19236
  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(" "));
19183
19237
  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(" "));
19184
- function validateRelativePath(path36) {
19185
- if (typeof path36 !== "string" || !path36 || path36.length > 2048 || isAbsolute(path36)) throw new Error("INVALID_ARTIFACT_PATH");
19186
- for (const part of path36.split("/")) {
19238
+ function validateRelativePath(path37) {
19239
+ if (typeof path37 !== "string" || !path37 || path37.length > 2048 || isAbsolute(path37)) throw new Error("INVALID_ARTIFACT_PATH");
19240
+ for (const part of path37.split("/")) {
19187
19241
  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)))
19188
19242
  throw new Error("INVALID_ARTIFACT_PATH");
19189
19243
  }
@@ -19231,10 +19285,10 @@ function normalizePublicationProfile(value) {
19231
19285
  Object.freeze(profile.trees);
19232
19286
  return Object.freeze(profile);
19233
19287
  }
19234
- function validatePublicationPath(path36) {
19235
- if (typeof path36 !== "string" || path36.normalize("NFC") !== path36) throw new Error("PUBLICATION_INVALID_PATH");
19288
+ function validatePublicationPath(path37) {
19289
+ if (typeof path37 !== "string" || path37.normalize("NFC") !== path37) throw new Error("PUBLICATION_INVALID_PATH");
19236
19290
  try {
19237
- validateRelativePath(path36);
19291
+ validateRelativePath(path37);
19238
19292
  } catch {
19239
19293
  throw new Error("PUBLICATION_INVALID_PATH");
19240
19294
  }
@@ -19253,15 +19307,15 @@ function normalizePublication(value) {
19253
19307
  if (!Array.isArray(tree.files) || !Array.isArray(tree.directories) || (paths += tree.files.length + tree.directories.length) > 1e5)
19254
19308
  throw new Error("PUBLICATION_INVALID_TREE");
19255
19309
  const occupied = /* @__PURE__ */ new Map();
19256
- const claim = (path36, kind) => {
19257
- validatePublicationPath(path36);
19258
- const folded = path36.toLowerCase();
19310
+ const claim = (path37, kind) => {
19311
+ validatePublicationPath(path37);
19312
+ const folded = path37.toLowerCase();
19259
19313
  if (occupied.has(folded)) throw new Error("PUBLICATION_PATH_COLLISION");
19260
19314
  occupied.set(folded, kind);
19261
19315
  };
19262
- const directories = tree.directories.map((path36) => {
19263
- claim(path36, "directory");
19264
- return path36;
19316
+ const directories = tree.directories.map((path37) => {
19317
+ claim(path37, "directory");
19318
+ return path37;
19265
19319
  }).sort();
19266
19320
  const files = tree.files.map((file2) => {
19267
19321
  claim(file2?.path, "file");
@@ -19273,8 +19327,8 @@ function normalizePublication(value) {
19273
19327
  chunks: file2.content.chunks.map((r) => ({ sha256: r.sha256, bytes: r.bytes }))
19274
19328
  } };
19275
19329
  }).sort((a, b) => a.path.localeCompare(b.path, "en"));
19276
- for (const path36 of occupied.keys()) {
19277
- const parts = path36.split("/");
19330
+ for (const path37 of occupied.keys()) {
19331
+ const parts = path37.split("/");
19278
19332
  for (let i = 1; i < parts.length; i++) if (occupied.get(parts.slice(0, i).join("/")) === "file") throw new Error("PUBLICATION_PATH_COLLISION");
19279
19333
  }
19280
19334
  return { id: tree.id, directories, files };
@@ -19705,9 +19759,9 @@ var TravelGatewayStore = class {
19705
19759
  throw new Error("TRAVEL_GATEWAY_BUSY");
19706
19760
  }
19707
19761
  try {
19708
- const path36 = join12(options.directory, "gateway.sqlite"), present = existsSync6(path36);
19709
- preparePrivateDatabase(path36);
19710
- this.db = new DatabaseSync10(path36);
19762
+ const path37 = join12(options.directory, "gateway.sqlite"), present = existsSync6(path37);
19763
+ preparePrivateDatabase(path37);
19764
+ this.db = new DatabaseSync10(path37);
19711
19765
  this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
19712
19766
  if (!present) this.db.exec([
19713
19767
  "CREATE TABLE binding(identity TEXT NOT NULL,format TEXT NOT NULL);",
@@ -21392,13 +21446,13 @@ var DiscordAdapter = class _DiscordAdapter {
21392
21446
  }
21393
21447
  /** 发送媒体附件(图片/文件/音频)— discord.js channel.send({ files }) */
21394
21448
  async sendFile(target, message, attachment) {
21395
- const fs26 = await import("node:fs");
21396
- const path36 = await import("node:path");
21397
- if (!fs26.existsSync(attachment.path)) {
21449
+ const fs27 = await import("node:fs");
21450
+ const path37 = await import("node:path");
21451
+ if (!fs27.existsSync(attachment.path)) {
21398
21452
  throw new Error(`File not found: ${attachment.path}`);
21399
21453
  }
21400
- const filename = attachment.filename || path36.basename(attachment.path);
21401
- const fileBuffer = fs26.readFileSync(attachment.path);
21454
+ const filename = attachment.filename || path37.basename(attachment.path);
21455
+ const fileBuffer = fs27.readFileSync(attachment.path);
21402
21456
  const filePayload = {
21403
21457
  attachment: fileBuffer,
21404
21458
  name: filename
@@ -22012,13 +22066,13 @@ var FeishuAdapter = class _FeishuAdapter {
22012
22066
  }
22013
22067
  /** 发送媒体附件(图片/文件) */
22014
22068
  async sendFile(target, message, attachment) {
22015
- const fs26 = await import("node:fs");
22016
- const path36 = await import("node:path");
22017
- if (!fs26.existsSync(attachment.path)) {
22069
+ const fs27 = await import("node:fs");
22070
+ const path37 = await import("node:path");
22071
+ if (!fs27.existsSync(attachment.path)) {
22018
22072
  throw new Error(`File not found: ${attachment.path}`);
22019
22073
  }
22020
- const filename = attachment.filename || path36.basename(attachment.path);
22021
- const fileBuffer = fs26.readFileSync(attachment.path);
22074
+ const filename = attachment.filename || path37.basename(attachment.path);
22075
+ const fileBuffer = fs27.readFileSync(attachment.path);
22022
22076
  const safeTarget = target || this.config.defaultTarget || "";
22023
22077
  if (!safeTarget) throw new Error("Feishu sendFile: no target (\u4E3B\u52A8\u53D1\u9001\u9700\u914D\u7F6E defaultTarget \u6216\u4F20\u5165 target)");
22024
22078
  const receiveIdType = safeTarget.startsWith("ou_") ? "open_id" : "chat_id";
@@ -24148,22 +24202,22 @@ var DeskBuddyAdapter = class {
24148
24202
  try {
24149
24203
  if (!this.historyFile) {
24150
24204
  const os7 = __require("os");
24151
- const fs27 = __require("fs");
24152
- const path36 = __require("path");
24153
- const dir = path36.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
24154
- fs27.mkdirSync(dir, { recursive: true });
24155
- this.historyFile = path36.join(dir, "history.json");
24156
- this._fs = fs27;
24157
- }
24158
- const fs26 = this._fs;
24205
+ const fs28 = __require("fs");
24206
+ const path37 = __require("path");
24207
+ const dir = path37.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
24208
+ fs28.mkdirSync(dir, { recursive: true });
24209
+ this.historyFile = path37.join(dir, "history.json");
24210
+ this._fs = fs28;
24211
+ }
24212
+ const fs27 = this._fs;
24159
24213
  let arr = [];
24160
24214
  try {
24161
- arr = JSON.parse(fs26.readFileSync(this.historyFile, "utf-8")) || [];
24215
+ arr = JSON.parse(fs27.readFileSync(this.historyFile, "utf-8")) || [];
24162
24216
  } catch {
24163
24217
  }
24164
24218
  arr.push({ ...entry, ts: (/* @__PURE__ */ new Date()).toLocaleString("zh-CN", { hour12: false }) });
24165
24219
  if (arr.length > 500) arr = arr.slice(-500);
24166
- fs26.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
24220
+ fs27.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
24167
24221
  } catch (e) {
24168
24222
  console.warn("[deskBuddy] history write fail", e);
24169
24223
  }
@@ -25788,7 +25842,7 @@ var TelegramAdapter = class {
25788
25842
 
25789
25843
  // src/channels/whatsapp/adapter.ts
25790
25844
  import fsSync4 from "node:fs";
25791
- import path31 from "node:path";
25845
+ import path32 from "node:path";
25792
25846
  import { spawn as spawn5 } from "node:child_process";
25793
25847
  import { randomUUID as randomUUID17 } from "node:crypto";
25794
25848
 
@@ -26716,7 +26770,7 @@ function headerOf(groupJid) {
26716
26770
 
26717
26771
  // src/channels/whatsapp/patrol.ts
26718
26772
  import fsSync3 from "node:fs";
26719
- import path30 from "node:path";
26773
+ import path31 from "node:path";
26720
26774
  import { randomBytes as randomBytes7 } from "node:crypto";
26721
26775
 
26722
26776
  // src/models/model-capabilities.ts
@@ -27767,8 +27821,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
27767
27821
  hookEvent,
27768
27822
  durationMs: durationMs2
27769
27823
  });
27824
+ const output = syncOutput.hookSpecificOutput;
27770
27825
  return {
27771
27826
  ...processed,
27827
+ ...hook.id === "skill-gate-prompt" && output?.hookEventName === "UserPromptSubmit" && output.selectSkill === true ? { selectSkill: true } : {},
27772
27828
  outcome: processed.blockingError ? "blocking" : "success",
27773
27829
  hook
27774
27830
  };
@@ -27870,6 +27926,7 @@ function aggregateResults(results) {
27870
27926
  if (result.permissionBehavior) {
27871
27927
  aggregated.permissionBehavior = result.permissionBehavior;
27872
27928
  }
27929
+ if (result.selectSkill) aggregated.selectSkill = true;
27873
27930
  if (result.additionalContext) {
27874
27931
  aggregated.additionalContexts.push(result.additionalContext);
27875
27932
  }
@@ -30301,8 +30358,8 @@ var contextIdentity = (context) => canonicalJson({
30301
30358
  function createNotificationStateReader() {
30302
30359
  const databases = /* @__PURE__ */ new Map();
30303
30360
  const checkers = /* @__PURE__ */ new Map();
30304
- const open3 = (path36) => {
30305
- const key4 = resolve9(path36);
30361
+ const open3 = (path37) => {
30362
+ const key4 = resolve9(path37);
30306
30363
  let db2 = databases.get(key4);
30307
30364
  if (!db2) {
30308
30365
  db2 = new DatabaseSync11(key4, { readOnly: true });
@@ -30912,6 +30969,174 @@ function killTask(taskId) {
30912
30969
  return true;
30913
30970
  }
30914
30971
 
30972
+ // src/core/query-skill-selection.ts
30973
+ init_types();
30974
+
30975
+ // src/skills/recent-user-texts.ts
30976
+ init_strip_injected();
30977
+
30978
+ // src/core/query-skill-selection.ts
30979
+ 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";
30980
+ var SKILL_SELECTION_MAX_TOKENS = 64;
30981
+ async function selectSkillCall(provider, params, allowedNames, recordUsage) {
30982
+ const timeout = AbortSignal.timeout(5e3);
30983
+ const signal = AbortSignal.any([params.signal, timeout]);
30984
+ const chunks = [];
30985
+ let calledSkill = false;
30986
+ let skillName = "";
30987
+ let requestComplete = false;
30988
+ let otherCut = false;
30989
+ try {
30990
+ for await (const chunk of provider.streamChat({
30991
+ ...params,
30992
+ signal,
30993
+ httpRetry: { maxRetries: 0 }
30994
+ })) {
30995
+ signal.throwIfAborted();
30996
+ if (chunk.type === "error") return { outcome: "upstream-error" };
30997
+ if (chunk.type === "tool_call") {
30998
+ if (calledSkill || !chunk.tool_call?.id || chunk.tool_call.function?.name !== SKILL_TOOL_NAME) return { outcome: "invalid" };
30999
+ let args;
31000
+ try {
31001
+ args = JSON.parse(chunk.tool_call.function.arguments);
31002
+ } catch {
31003
+ return { outcome: "invalid" };
31004
+ }
31005
+ if (typeof args?.skill !== "string" || !allowedNames.has(args.skill.trim().replace(/^\//, ""))) return { outcome: "invalid" };
31006
+ calledSkill = true;
31007
+ skillName = args.skill.trim().replace(/^\//, "");
31008
+ chunks.push(chunk);
31009
+ }
31010
+ if (chunk.type === "done") {
31011
+ if (chunk.usage) recordUsage(chunk.usage);
31012
+ requestComplete ||= chunk.requestComplete === true;
31013
+ otherCut ||= ["incomplete", "content_filter"].includes(chunk.stopReason ?? "");
31014
+ }
31015
+ }
31016
+ } catch (error) {
31017
+ params.signal.throwIfAborted();
31018
+ if (error instanceof Error && /^TRAVEL_/.test(error.message)) throw error;
31019
+ return { outcome: timeout.aborted ? "timeout" : "upstream-error" };
31020
+ }
31021
+ params.signal.throwIfAborted();
31022
+ if (timeout.aborted) return { outcome: "timeout" };
31023
+ if (!requestComplete || otherCut) return { outcome: "incomplete" };
31024
+ return calledSkill ? { outcome: "selected", skill: skillName, chunks } : { outcome: "no-skill" };
31025
+ }
31026
+
31027
+ // src/skills/scanner.ts
31028
+ function parseFrontmatter(content) {
31029
+ const result = {};
31030
+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
31031
+ if (!match) return result;
31032
+ const lines = match[1].split("\n");
31033
+ let i = 0;
31034
+ while (i < lines.length) {
31035
+ const line = lines[i];
31036
+ const colonIdx = line.indexOf(":");
31037
+ if (colonIdx === -1) {
31038
+ i++;
31039
+ continue;
31040
+ }
31041
+ const key4 = line.slice(0, colonIdx).trim();
31042
+ let value = line.slice(colonIdx + 1).trim();
31043
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
31044
+ value = value.slice(1, -1);
31045
+ result[key4] = value;
31046
+ i++;
31047
+ continue;
31048
+ } else if (value === "|" || value === ">") {
31049
+ const blockLines = [];
31050
+ i++;
31051
+ while (i < lines.length && lines[i].startsWith(" ")) {
31052
+ blockLines.push(lines[i].slice(2));
31053
+ i++;
31054
+ }
31055
+ result[key4] = blockLines.join("\n").trim();
31056
+ continue;
31057
+ } else if (value.startsWith("[") && value.endsWith("]")) {
31058
+ result[key4] = value.slice(1, -1).split(",").map((s) => s.trim());
31059
+ i++;
31060
+ continue;
31061
+ } else if (value.includes(" ") && !value.startsWith('"')) {
31062
+ result[key4] = value;
31063
+ } else {
31064
+ result[key4] = value;
31065
+ }
31066
+ i++;
31067
+ }
31068
+ return result;
31069
+ }
31070
+
31071
+ // src/tools/SkillTool/SkillTool.ts
31072
+ init_tokenEstimate();
31073
+ import { createHash as createHash34 } from "node:crypto";
31074
+ import * as fs22 from "node:fs";
31075
+ import * as path29 from "node:path";
31076
+ var skillsDirPath = "";
31077
+ var selectionCatalog = { entries: [], allowedNames: /* @__PURE__ */ new Set() };
31078
+ function getSkillSelectionCatalog() {
31079
+ return selectionCatalog;
31080
+ }
31081
+ var resolveSkillFn;
31082
+ function loadSkillContent(skillsDir, skill) {
31083
+ const skillMdPath = skill.location ? path29.join(skillsDir, skill.location.slice("skills/".length)) : path29.join(skillsDir, skill.name, "SKILL.md");
31084
+ if (!fs22.existsSync(skillMdPath)) return null;
31085
+ const content = fs22.readFileSync(skillMdPath, "utf-8");
31086
+ const dependencies = parseFrontmatter(content)["requires-tools"];
31087
+ 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))];
31088
+ const bodyMatch = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)/);
31089
+ const body = bodyMatch ? bodyMatch[1] : content;
31090
+ const skillDir = path29.dirname(skillMdPath);
31091
+ const normalizedDir = process.platform === "win32" ? skillDir.replace(/\\/g, "/") : skillDir;
31092
+ let finalContent = `Base directory for this skill: ${normalizedDir}
31093
+
31094
+ ${body}`;
31095
+ finalContent = finalContent.replace(/\$\{CLAUDE_SKILL_DIR\}/g, normalizedDir);
31096
+ finalContent = finalContent.replace(/\$\{CLAUDE_SESSION_ID\}/g, getSessionId());
31097
+ return { content: finalContent, requiredTools };
31098
+ }
31099
+ function getSessionId() {
31100
+ return String(process.pid);
31101
+ }
31102
+ var SKILL_FINGERPRINT_PREFIX = "[fingerprint ";
31103
+ var SKILL_RELOAD_DISTANCE_TOKENS = 16e3;
31104
+ function skillFingerprint(skill, body) {
31105
+ return createHash34("sha256").update(skill.location ?? skill.name).update("\0").update(body).digest("hex").slice(0, 16);
31106
+ }
31107
+ function findLoadedSkill(history, skill, fingerprint, resolve12) {
31108
+ if (!history) return void 0;
31109
+ for (let i = history.length - 1; i >= 0; i--) {
31110
+ const message = history[i];
31111
+ if (!("role" in message) || message.role !== "tool" || message.is_error || typeof message.content !== "string") continue;
31112
+ let call;
31113
+ for (let j = i - 1; j >= 0 && !call; j--) {
31114
+ const previous = history[j];
31115
+ 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);
31116
+ }
31117
+ if (!call) continue;
31118
+ let args = {};
31119
+ try {
31120
+ args = JSON.parse(call.function.arguments);
31121
+ } catch {
31122
+ continue;
31123
+ }
31124
+ if (typeof args?.skill !== "string" || resolve12(args.skill.trim().replace(/^\//, "")) !== skill) continue;
31125
+ if (!message.content.includes(SKILL_FINGERPRINT_PREFIX + fingerprint + "]")) return void 0;
31126
+ return estimateMessageTokens(history.slice(i + 1)) <= SKILL_RELOAD_DISTANCE_TOKENS ? call.id : void 0;
31127
+ }
31128
+ return void 0;
31129
+ }
31130
+ function findLoadedSkillCall(history, skillName) {
31131
+ const resolve12 = resolveSkillFn;
31132
+ if (!history || !resolve12) return void 0;
31133
+ const skill = resolve12(skillName.trim().replace(/^\//, ""));
31134
+ if (!skill) return void 0;
31135
+ const content = loadSkillContent(skillsDirPath, skill);
31136
+ if (!content) return void 0;
31137
+ return findLoadedSkill(history, skill, skillFingerprint(skill, content.content), resolve12);
31138
+ }
31139
+
30915
31140
  // src/core/query.ts
30916
31141
  function blockedToolCallsForOverride(calls, override2) {
30917
31142
  if (!override2) return [];
@@ -31309,6 +31534,7 @@ var QueryEngine = class _QueryEngine {
31309
31534
  turnCount++;
31310
31535
  const steers = this.pendingSteers.splice(0);
31311
31536
  let steerConsumedThisTurn = false;
31537
+ let userSteerConsumedThisTurn = false;
31312
31538
  if (steers.length > 0) {
31313
31539
  for (const input of steers) {
31314
31540
  if (this.steerHistoryIds.has(input.id)) {
@@ -31340,6 +31566,7 @@ var QueryEngine = class _QueryEngine {
31340
31566
  if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
31341
31567
  this.steerHistoryIds.add(input.id);
31342
31568
  steerConsumedThisTurn = true;
31569
+ userSteerConsumedThisTurn = true;
31343
31570
  yield {
31344
31571
  type: "user_input",
31345
31572
  message: steerMsg,
@@ -31595,7 +31822,53 @@ var QueryEngine = class _QueryEngine {
31595
31822
  let turnAborted = false;
31596
31823
  try {
31597
31824
  wholeQueryAbort.signal.throwIfAborted();
31598
- const view = normalizeMessagesForAPI(currentMessages).map((m) => {
31825
+ const beforeRequest = () => {
31826
+ wholeQueryAbort.signal.throwIfAborted();
31827
+ ac.signal.throwIfAborted();
31828
+ };
31829
+ const startRequest = () => {
31830
+ this.phase = "streaming";
31831
+ assertRuntimeAuthority(void 0, "INPUT");
31832
+ if (perTurnOptions?.onRequestStarted) {
31833
+ const start = perTurnOptions.onRequestStarted;
31834
+ setImmediate(() => {
31835
+ if (!wholeQueryAbort.signal.aborted) start();
31836
+ });
31837
+ }
31838
+ };
31839
+ let selected;
31840
+ const selectionInput = perTurnOptions?.skillSelectionInput;
31841
+ const skill = turnCount === 1 && maxTurns >= 2 && !userSteerConsumedThisTurn && !hasPendingUserInput() && selectionInput ? allToolDefs.find((tool) => tool.function.name === SKILL_TOOL_NAME) : void 0;
31842
+ const catalog = skill ? getSkillSelectionCatalog() : void 0;
31843
+ if (skill && selectionInput && catalog?.entries.length) {
31844
+ const input = normalizeMessagesForAPI([selectionInput]);
31845
+ const started = performance.now();
31846
+ startRequest();
31847
+ const selection = await selectSkillCall(queryProvider, {
31848
+ preferFastFallback,
31849
+ model: queryModel,
31850
+ messages: input,
31851
+ tools: [skill],
31852
+ systemStable: SKILL_SELECTION_PROMPT + "\n\n" + JSON.stringify(catalog.entries),
31853
+ maxTokens: SKILL_SELECTION_MAX_TOKENS,
31854
+ signal: ac.signal,
31855
+ beforeRequest: () => {
31856
+ assertHostTurnCurrent();
31857
+ beforeRequest();
31858
+ },
31859
+ disableThinking: true
31860
+ }, catalog.allowedNames, recordUsage);
31861
+ assertHostTurnCurrent();
31862
+ beforeRequest();
31863
+ console.log(`${this.logPrefix} [skill-selection] ${selection.outcome} ms=${Math.round(performance.now() - started)}`);
31864
+ if (hasPendingUserInput()) continue;
31865
+ if (selection.outcome === "selected") {
31866
+ if (findLoadedSkillCall(currentMessages, selection.skill)) {
31867
+ console.log(`${this.logPrefix} [skill-selection] already-loaded ${selection.skill}`);
31868
+ } else selected = selection.chunks;
31869
+ }
31870
+ }
31871
+ const view = (selected ? [] : normalizeMessagesForAPI(currentMessages)).map((m) => {
31599
31872
  if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
31600
31873
  const blocks = m.content.filter((b) => {
31601
31874
  if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
@@ -31630,7 +31903,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
31630
31903
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
31631
31904
 
31632
31905
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31633
- if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
31906
+ if (!selected && (!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
31634
31907
  try {
31635
31908
  const ws = process.env.ENGINE7_WORKSPACE;
31636
31909
  if (ws) {
@@ -31646,15 +31919,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31646
31919
  } catch {
31647
31920
  }
31648
31921
  }
31649
- this.phase = "streaming";
31650
- assertRuntimeAuthority(void 0, "INPUT");
31651
- if (perTurnOptions?.onRequestStarted) {
31652
- const start = perTurnOptions.onRequestStarted;
31653
- setImmediate(() => {
31654
- if (!wholeQueryAbort.signal.aborted) start();
31655
- });
31656
- }
31657
- for await (const chunk of queryProvider.streamChat({
31922
+ if (!selected) startRequest();
31923
+ for await (const chunk of selected ?? queryProvider.streamChat({
31658
31924
  preferFastFallback,
31659
31925
  model: queryModel,
31660
31926
  messages: apiMessages,
@@ -31667,10 +31933,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31667
31933
  maxTokens: this.resolveRequestMaxTokens(apiMessages, maxTokensOverride),
31668
31934
  temperature: this.options.temperature,
31669
31935
  signal: ac.signal,
31670
- beforeRequest: () => {
31671
- wholeQueryAbort.signal.throwIfAborted();
31672
- ac.signal.throwIfAborted();
31673
- },
31936
+ beforeRequest,
31674
31937
  disableThinking: this.options.disableThinking || !!perTurnEmotion
31675
31938
  // 情感模式关 thinking(对齐 deskBuddy)
31676
31939
  })) {
@@ -32031,6 +32294,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
32031
32294
  if (vcDelivery) await vcDelivery;
32032
32295
  }
32033
32296
  const { messages: toolResults, summaries } = toolRes;
32297
+ if (selected) console.log(`${this.logPrefix} [skill-selection] ${summaries.length === 1 && !summaries[0].isError ? "loaded" : "load-failed"}`);
32034
32298
  if (collectStopEvidence) stopToolResults.push(...summaries);
32035
32299
  for (const s of summaries) {
32036
32300
  try {
@@ -32328,9 +32592,9 @@ function readState(stateFile) {
32328
32592
  return { lastPatrolAt: 0, lastLineCounts: {} };
32329
32593
  }
32330
32594
  function writeState(stateFile, state) {
32331
- const dir = path30.dirname(stateFile);
32595
+ const dir = path31.dirname(stateFile);
32332
32596
  fsSync3.mkdirSync(dir, { recursive: true });
32333
- const tmp = path30.join(dir, `.${path30.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
32597
+ const tmp = path31.join(dir, `.${path31.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
32334
32598
  try {
32335
32599
  fsSync3.writeFileSync(tmp, JSON.stringify(state), "utf-8");
32336
32600
  fsSync3.renameSync(tmp, stateFile);
@@ -32359,7 +32623,7 @@ function buildPatrolPrompt(materials) {
32359
32623
  ].join("\n");
32360
32624
  }
32361
32625
  function defaultWriteMemoryNote(workspace) {
32362
- const dir = path30.join(getAutoMemPath(workspace), "whatsapp-patrol");
32626
+ const dir = path31.join(getAutoMemPath(workspace), "whatsapp-patrol");
32363
32627
  return (note) => {
32364
32628
  fsSync3.mkdirSync(dir, { recursive: true });
32365
32629
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
@@ -32373,7 +32637,7 @@ function defaultWriteMemoryNote(workspace) {
32373
32637
  note,
32374
32638
  ""
32375
32639
  ].join("\n");
32376
- fsSync3.writeFileSync(path30.join(dir, `patrol-${stamp}.md`), body, "utf-8");
32640
+ fsSync3.writeFileSync(path31.join(dir, `patrol-${stamp}.md`), body, "utf-8");
32377
32641
  };
32378
32642
  }
32379
32643
  function makeSubmitToMain(engineDeps) {
@@ -32518,15 +32782,15 @@ ${quoted}`);
32518
32782
 
32519
32783
  // src/utils/ffmpeg-path.ts
32520
32784
  init_dep_downloader();
32521
- import * as fs23 from "node:fs";
32785
+ import * as fs24 from "node:fs";
32522
32786
  function resolveFfmpegPath() {
32523
32787
  const env = (process.env.E7_FFMPEG_PATH || "").trim();
32524
- if (env && fs23.existsSync(env)) return env;
32788
+ if (env && fs24.existsSync(env)) return env;
32525
32789
  const downloaded = optionalFfmpegPath();
32526
32790
  if (downloaded) return downloaded;
32527
32791
  try {
32528
32792
  const p = __require("@ffmpeg-installer/ffmpeg")?.path;
32529
- if (p && fs23.existsSync(p)) return p;
32793
+ if (p && fs24.existsSync(p)) return p;
32530
32794
  } catch {
32531
32795
  }
32532
32796
  return "ffmpeg";
@@ -32612,10 +32876,10 @@ function normalizeAllowEntry(entry) {
32612
32876
  }
32613
32877
  function atomicWriteFile(dir, fileName, content) {
32614
32878
  fsSync4.mkdirSync(dir, { recursive: true });
32615
- const tmp = path31.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID17().slice(0, 8)}`);
32879
+ const tmp = path32.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID17().slice(0, 8)}`);
32616
32880
  try {
32617
32881
  fsSync4.writeFileSync(tmp, content, "utf-8");
32618
- fsSync4.renameSync(tmp, path31.join(dir, fileName));
32882
+ fsSync4.renameSync(tmp, path32.join(dir, fileName));
32619
32883
  } catch (e) {
32620
32884
  try {
32621
32885
  fsSync4.rmSync(tmp, { force: true });
@@ -32730,13 +32994,13 @@ var WhatsAppAdapter = class {
32730
32994
  constructor(cfg, opts = {}) {
32731
32995
  this.cfg = cfg;
32732
32996
  this.stateDir = cfg.stateDir;
32733
- this.authDir = path31.join(cfg.stateDir, "whatsapp-auth");
32734
- this.qrFilePath = path31.join(cfg.stateDir, "whatsapp-qr.txt");
32997
+ this.authDir = path32.join(cfg.stateDir, "whatsapp-auth");
32998
+ this.qrFilePath = path32.join(cfg.stateDir, "whatsapp-qr.txt");
32735
32999
  this.opts = opts;
32736
33000
  this.credsStore = opts.credsStoreOverride ?? makeCredsStore(this.authDir);
32737
33001
  this.loginTtlMs = opts.loginTtlMs ?? LOGIN_TTL_MS;
32738
33002
  this.digestEnabled = cfg.groupDigest?.enabled !== false;
32739
- this.digest = this.digestEnabled ? new GroupDigestStore(path31.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
33003
+ this.digest = this.digestEnabled ? new GroupDigestStore(path32.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
32740
33004
  this.typing = new PresenceTypingCoalescer(async (jid) => {
32741
33005
  const sock = this.sock;
32742
33006
  if (!sock || typeof sock.sendPresenceUpdate !== "function") return;
@@ -32871,7 +33135,7 @@ var WhatsAppAdapter = class {
32871
33135
  this.patrol = startPatrolLoop({
32872
33136
  digest: this.digest,
32873
33137
  intervalMin: this.cfg.groupDigest?.patrolIntervalMin ?? 60,
32874
- stateFile: path31.join(this.stateDir, "whatsapp-patrol-state.json"),
33138
+ stateFile: path32.join(this.stateDir, "whatsapp-patrol-state.json"),
32875
33139
  runReadOnlyAgent: makeReadOnlyAgentRunner(this.opts.patrolDeps),
32876
33140
  // ⚠️ 升级接线(终审 C1,1003):摘要含 ⚠️ 行时宿主经主 session 投递(spec §4)——
32877
33141
  // makeSubmitToMain 吃的正是 patrolDeps {dispatcher, deps}(patrol.ts)形状。漏接这行 =
@@ -33168,11 +33432,11 @@ ${r}` : r;
33168
33432
  const idRaw = typeof raw?.key?.id === "string" && raw.key.id ? raw.key.id : "";
33169
33433
  const idSafe = idRaw.replace(/[^\w.-]/g, "_");
33170
33434
  const id3 = !idRaw || idSafe !== idRaw || !idSafe ? randomUUID17() : idSafe;
33171
- const dir = path31.join(this.stateDir, "media", "whatsapp");
33435
+ const dir = path32.join(this.stateDir, "media", "whatsapp");
33172
33436
  fsSync4.mkdirSync(dir, { recursive: true });
33173
- const abs = path31.join(dir, `${id3}.${ext}`);
33174
- const resolved = path31.resolve(abs);
33175
- if (!resolved.startsWith(path31.resolve(dir) + path31.sep)) {
33437
+ const abs = path32.join(dir, `${id3}.${ext}`);
33438
+ const resolved = path32.resolve(abs);
33439
+ if (!resolved.startsWith(path32.resolve(dir) + path32.sep)) {
33176
33440
  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}`);
33177
33441
  return `${placeholder}\uFF08\u4E0B\u8F7D\u5931\u8D25\uFF09`;
33178
33442
  }
@@ -33206,7 +33470,7 @@ ${r}` : r;
33206
33470
  const lids = [jid, participant].filter((j) => j.endsWith("@lid"));
33207
33471
  if (lids.length === 0) return;
33208
33472
  try {
33209
- const filePath2 = path31.join(this.authDir, "lid-mapping.json");
33473
+ const filePath2 = path32.join(this.authDir, "lid-mapping.json");
33210
33474
  let arr = [];
33211
33475
  try {
33212
33476
  const parsed = JSON.parse(fsSync4.readFileSync(filePath2, "utf-8"));
@@ -33316,7 +33580,7 @@ ${r}` : r;
33316
33580
  if (isGroupJid(jid)) throw new Error(`WhatsApp \u7FA4\u53D1\u9001\u7269\u7406\u4E0D\u5B58\u5728\uFF08\u7EA2\u7EBF\uFF09\uFF1Atarget=${jid}`);
33317
33581
  const sock = this.requireSock();
33318
33582
  const mime = attachment.mimeType ?? "";
33319
- const filename = attachment.filename ?? path31.basename(attachment.path);
33583
+ const filename = attachment.filename ?? path32.basename(attachment.path);
33320
33584
  if (mime.startsWith("image/")) {
33321
33585
  assertExternalEffectCurrent();
33322
33586
  const res2 = await sock.sendMessage(jid, { image: { url: attachment.path }, caption: message });
@@ -33345,8 +33609,8 @@ ${r}` : r;
33345
33609
  this.recordEcho(res2);
33346
33610
  return;
33347
33611
  }
33348
- const tmpDir = path31.join(this.stateDir, "whatsapp-media-tmp");
33349
- const dst = path31.join(tmpDir, `${randomUUID17()}.ogg`);
33612
+ const tmpDir = path32.join(this.stateDir, "whatsapp-media-tmp");
33613
+ const dst = path32.join(tmpDir, `${randomUUID17()}.ogg`);
33350
33614
  try {
33351
33615
  await (this.cfg.ffmpegTranscode ?? defaultFfmpegTranscode)(attachment.path, dst);
33352
33616
  assertExternalEffectCurrent();
@@ -33461,9 +33725,9 @@ function quotedTextOf(content) {
33461
33725
  }
33462
33726
 
33463
33727
  // src/channels/dingtalk.ts
33464
- import fs24 from "node:fs";
33465
- import path32 from "node:path";
33466
- import { createHash as createHash34, randomUUID as randomUUID18 } from "node:crypto";
33728
+ import fs25 from "node:fs";
33729
+ import path33 from "node:path";
33730
+ import { createHash as createHash35, randomUUID as randomUUID18 } from "node:crypto";
33467
33731
 
33468
33732
  // src/channels/dingtalk-stream.ts
33469
33733
  import { EventEmitter } from "node:events";
@@ -34055,13 +34319,13 @@ var DingTalkAdapter = class _DingTalkAdapter {
34055
34319
  const res = await this.baseFetch(url, { signal: AbortSignal.timeout(3e4) });
34056
34320
  if (!res.ok) throw new Error(`media download HTTP ${res.status}`);
34057
34321
  const buf = Buffer.from(await res.arrayBuffer());
34058
- const dir = path32.join(this.cfg.stateDir, "media", "dingtalk");
34059
- fs24.mkdirSync(dir, { recursive: true });
34322
+ const dir = path33.join(this.cfg.stateDir, "media", "dingtalk");
34323
+ fs25.mkdirSync(dir, { recursive: true });
34060
34324
  const ext = m.kind === "image" ? "png" : m.kind === "video" ? "mp4" : "bin";
34061
- const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash34("sha1").update(m.code).digest("hex").slice(0, 12);
34325
+ const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash35("sha1").update(m.code).digest("hex").slice(0, 12);
34062
34326
  const safeCode = raw.replace(/[^a-zA-Z0-9_-]/g, "_");
34063
- const local = path32.join(dir, `${safeCode}.${ext}`);
34064
- fs24.writeFileSync(local, buf);
34327
+ const local = path33.join(dir, `${safeCode}.${ext}`);
34328
+ fs25.writeFileSync(local, buf);
34065
34329
  out.push({
34066
34330
  url: `file://${local}`,
34067
34331
  filename: m.filename ?? `${safeCode}.${ext}`,
@@ -34134,8 +34398,8 @@ var DingTalkAdapter = class _DingTalkAdapter {
34134
34398
  async sendFileNow(target, message, attachment) {
34135
34399
  const entry = this.registry.get(target);
34136
34400
  const robotCode = this.cfg.robotCode ?? this.cfg.clientId;
34137
- const buf = fs24.readFileSync(attachment.path);
34138
- const filename = (attachment.filename ?? path32.basename(attachment.path)).slice(0, 100);
34401
+ const buf = fs25.readFileSync(attachment.path);
34402
+ const filename = (attachment.filename ?? path33.basename(attachment.path)).slice(0, 100);
34139
34403
  const isImage = (attachment.mimeType ?? "").startsWith("image/") || /\.(png|jpe?g|gif|webp|bmp)$/i.test(filename);
34140
34404
  const mediaId = await this.uploadMedia(buf, filename, isImage ? "image" : "file");
34141
34405
  const msgKey = isImage ? "sampleImageMsg" : "sampleFileMsg";
@@ -34500,7 +34764,7 @@ var DING_EDIT_INTERVAL_MS = 300;
34500
34764
  // src/channels/wecom-stream.ts
34501
34765
  import { EventEmitter as EventEmitter2 } from "node:events";
34502
34766
  import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
34503
- import { createHash as createHash35 } from "node:crypto";
34767
+ import { createHash as createHash36 } from "node:crypto";
34504
34768
  var WECOM_WS_URL = "wss://openws.work.weixin.qq.com";
34505
34769
  var HEARTBEAT_MS2 = 3e4;
34506
34770
  var ACK_TIMEOUT_MS = 15e3;
@@ -34852,7 +35116,7 @@ var WecomStreamClient = class extends EventEmitter2 {
34852
35116
  if (!data.length) throw new Error("wecom uploadMedia: empty buffer");
34853
35117
  const totalChunks = Math.ceil(data.length / UPLOAD_CHUNK_BYTES);
34854
35118
  if (totalChunks > MAX_UPLOAD_CHUNKS) throw new Error(`wecom uploadMedia: too large (${totalChunks} chunks > ${MAX_UPLOAD_CHUNKS})`);
34855
- const md5 = createHash35("md5").update(data).digest("hex");
35119
+ const md5 = createHash36("md5").update(data).digest("hex");
34856
35120
  const initRes = await this.sendCommand("aibot_upload_media_init", {
34857
35121
  type,
34858
35122
  filename,
@@ -34879,9 +35143,9 @@ var WecomStreamClient = class extends EventEmitter2 {
34879
35143
 
34880
35144
  // src/channels/wecom.ts
34881
35145
  import { createDecipheriv as createDecipheriv3, randomUUID as randomUUID19 } from "node:crypto";
34882
- import { readFileSync as readFileSync17 } from "node:fs";
35146
+ import { readFileSync as readFileSync18 } from "node:fs";
34883
35147
  import { mkdir as mkdir4, readFile, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
34884
- import path33 from "node:path";
35148
+ import path34 from "node:path";
34885
35149
  var WECOM_CONTENT_BYTES = 20480;
34886
35150
  var DEFAULT_MERGE_WINDOW_MS = 600;
34887
35151
  var REPLY_WINDOW_MS = 24 * 60 * 60 * 1e3;
@@ -35067,7 +35331,7 @@ var WecomAdapter = class {
35067
35331
  this.now = cfg.now ?? Date.now;
35068
35332
  this.sleepImpl = cfg.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
35069
35333
  this.fetchImpl = cfg.fetchImpl ?? fetch;
35070
- this.routesFile = path33.join(cfg.stateDir, "state", ROUTES_FILE);
35334
+ this.routesFile = path34.join(cfg.stateDir, "state", ROUTES_FILE);
35071
35335
  }
35072
35336
  /**
35073
35337
  * 载入落盘会话路由(1007:真机事故——注册表原本只存内存,引擎一重启"谁跟我说过话"全丢,
@@ -35083,7 +35347,7 @@ var WecomAdapter = class {
35083
35347
  this.routesLoaded = true;
35084
35348
  let raw;
35085
35349
  try {
35086
- raw = JSON.parse(readFileSync17(this.routesFile, "utf8"));
35350
+ raw = JSON.parse(readFileSync18(this.routesFile, "utf8"));
35087
35351
  } catch (e) {
35088
35352
  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}`);
35089
35353
  return;
@@ -35111,7 +35375,7 @@ var WecomAdapter = class {
35111
35375
  try {
35112
35376
  const routes = {};
35113
35377
  for (const [chatId, e] of this.registry) routes[chatId] = { chatType: e.chatType, userId: e.userId };
35114
- await mkdir4(path33.dirname(this.routesFile), { recursive: true });
35378
+ await mkdir4(path34.dirname(this.routesFile), { recursive: true });
35115
35379
  await writeFile4(this.routesFile, JSON.stringify({ version: 1, routes }, null, 2) + "\n", "utf8");
35116
35380
  } catch (e) {
35117
35381
  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}`);
@@ -35397,7 +35661,7 @@ ${parsed.inbound.content}`;
35397
35661
  /** 入站媒体:下载 → aeskey 解密 → 落盘 → 附件(单条失败不拖垮整条消息;全部失败给 content 加标记)。
35398
35662
  * 本地文件名一律由 msgid 派生(远端 filename 只做显示名)——防同名互相覆盖/超长(钉钉 1004 同款纪律)。 */
35399
35663
  async resolveInboundMedia(parsed) {
35400
- const dir = path33.join(this.cfg.stateDir, "media", "wecom");
35664
+ const dir = path34.join(this.cfg.stateDir, "media", "wecom");
35401
35665
  const attachments = [];
35402
35666
  let failed = 0;
35403
35667
  for (const [i, ref] of parsed.media.entries()) {
@@ -35409,7 +35673,7 @@ ${parsed.inbound.content}`;
35409
35673
  const data = ref.aeskey ? decryptWecomMedia(raw, ref.aeskey) : raw;
35410
35674
  const ext = ref.filename?.includes(".") ? ref.filename.split(".").pop().toLowerCase().slice(0, 8) : ref.kind === "image" ? "jpg" : ref.kind === "video" ? "mp4" : "bin";
35411
35675
  const localName = `wecom-${(parsed.msgId || String(this.now())).replace(/[^0-9A-Za-z_-]/g, "").slice(0, 32)}-${i}.${ext}`;
35412
- const file2 = path33.join(dir, localName);
35676
+ const file2 = path34.join(dir, localName);
35413
35677
  await writeFile4(file2, data);
35414
35678
  const displayName = (ref.filename || localName).slice(0, 120);
35415
35679
  attachments.push({
@@ -35440,7 +35704,7 @@ ${parsed.inbound.content}`;
35440
35704
  const entry = this.registry.get(target);
35441
35705
  if (!entry) throw new Error(`[wecom] \u65E0\u6CD5\u8DEF\u7531\u5A92\u4F53\u5230 ${target}\uFF08\u65E0\u4F1A\u8BDD\u6CE8\u518C\u8BB0\u5F55\uFF09`);
35442
35706
  await this.takeToken(target, false);
35443
- const filename = attachment.filename ?? path33.basename(attachment.path);
35707
+ const filename = attachment.filename ?? path34.basename(attachment.path);
35444
35708
  const { mediaId } = await this.requireStream().uploadMedia(data, type, filename);
35445
35709
  const body = type === "video" ? { msgtype: "video", video: { media_id: mediaId, title: filename } } : { msgtype: type, [type]: { media_id: mediaId } };
35446
35710
  await this.respondOrSend(entry, target, body);
@@ -35704,7 +35968,7 @@ import { randomUUID as randomUUID20 } from "node:crypto";
35704
35968
  // src/continuity/gateway-channel.ts
35705
35969
  init_gateway_media();
35706
35970
  import { mkdtempSync, writeFileSync as writeFileSync14, rmSync as rmSync2, realpathSync as realpathSync5 } from "node:fs";
35707
- import { join as join30 } from "node:path";
35971
+ import { join as join31 } from "node:path";
35708
35972
  import { tmpdir as tmpdir3 } from "node:os";
35709
35973
  function splitChannelGatewayText(text2, channel) {
35710
35974
  if (typeof text2 !== "string" || Buffer.byteLength(text2) > 1024 * 1024) throw new Error("TRAVEL_GATEWAY_REPLY_LIMIT");
@@ -35759,7 +36023,7 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
35759
36023
  if (!media) await adapter.send(packet.target, packet.text, { replyTo: packet.replyTo });
35760
36024
  else {
35761
36025
  if (!adapter.sendFile) throw new Error("TRAVEL_GATEWAY_MEDIA_UNAVAILABLE");
35762
- const directory2 = realpathSync5(mkdtempSync(join30(tmpdir3(), "e7-gateway-media-"))), file2 = join30(directory2, packet.filename);
36026
+ const directory2 = realpathSync5(mkdtempSync(join31(tmpdir3(), "e7-gateway-media-"))), file2 = join31(directory2, packet.filename);
35763
36027
  try {
35764
36028
  writeFileSync14(file2, media.bytes, { mode: 384 });
35765
36029
  await adapter.sendFile(packet.target, packet.text, { path: file2, filename: packet.filename, mimeType: packet.mimeType, voiceDurationSec: packet.voiceDurationSec });
@@ -36185,9 +36449,9 @@ var RemoteTravelChannel = class {
36185
36449
  };
36186
36450
 
36187
36451
  // src/channels/private-library.ts
36188
- import fs25 from "node:fs/promises";
36189
- import path34 from "node:path";
36190
- import { createHash as createHash36 } from "node:crypto";
36452
+ import fs26 from "node:fs/promises";
36453
+ import path35 from "node:path";
36454
+ import { createHash as createHash37 } from "node:crypto";
36191
36455
 
36192
36456
  // src/channels/chan7-content.ts
36193
36457
  function fileMime(name) {
@@ -36199,8 +36463,8 @@ function fileMime(name) {
36199
36463
  function archive(manager, name, mime, bytes2, role, caption, identity) {
36200
36464
  const adapter = manager.getAdapter("chan7");
36201
36465
  if (!adapter?.files || bytes2.length > 16 * 1024 * 1024) return;
36202
- const safeName = path34.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
36203
- const key4 = createHash36("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
36466
+ const safeName = path35.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
36467
+ const key4 = createHash37("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
36204
36468
  try {
36205
36469
  adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key4);
36206
36470
  } catch (e) {
@@ -36210,9 +36474,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
36210
36474
  async function archivePrivateOutbound(manager, channel, target, text2, attachment, origin) {
36211
36475
  if (channel === "chan7" || origin?.channelType !== "dm" || origin.inboundIsBot || origin.channel !== channel || origin.channelTarget !== target || !manager.getAdapter("chan7")?.files) return;
36212
36476
  try {
36213
- const stat3 = await fs25.stat(attachment.path);
36477
+ const stat3 = await fs26.stat(attachment.path);
36214
36478
  if (!stat3.isFile() || stat3.size > 16 * 1024 * 1024) return;
36215
- const bytes2 = await fs25.readFile(attachment.path), name = attachment.filename ?? path34.basename(attachment.path);
36479
+ const bytes2 = await fs26.readFile(attachment.path), name = attachment.filename ?? path35.basename(attachment.path);
36216
36480
  archive(
36217
36481
  manager,
36218
36482
  name,
@@ -36227,6 +36491,63 @@ async function archivePrivateOutbound(manager, channel, target, text2, attachmen
36227
36491
  }
36228
36492
  }
36229
36493
 
36494
+ // src/channels/loop-guard.ts
36495
+ var MAX_COMPARE_LEN = 60;
36496
+ var MAX_REPEAT = 3;
36497
+ var SIMILARITY_THRESHOLD = 0.8;
36498
+ var HISTORY_SIZE = 5;
36499
+ var LoopBlockedError = class extends Error {
36500
+ constructor(target, repeated) {
36501
+ super(`loop-guard blocked: \u5411 ${target} \u8FDE\u7EED ${repeated} \u6761\u540C\u8D28\u6D88\u606F`);
36502
+ this.target = target;
36503
+ this.repeated = repeated;
36504
+ this.name = "LoopBlockedError";
36505
+ }
36506
+ };
36507
+ var states = /* @__PURE__ */ new Map();
36508
+ function normalize6(text2) {
36509
+ return text2.replace(/[\s\u3000]/g, "").replace(/[。,、!?;:""''()()\[\]【】…~~\-—.,!?;:'"]/g, "").toLowerCase();
36510
+ }
36511
+ function similarity(a, b) {
36512
+ if (!a && !b) return 1;
36513
+ if (!a || !b) return 0;
36514
+ const setA = new Set(a);
36515
+ const setB = new Set(b);
36516
+ let inter = 0;
36517
+ for (const ch of setA) if (setB.has(ch)) inter++;
36518
+ const union = setA.size + setB.size - inter;
36519
+ return union === 0 ? 1 : inter / union;
36520
+ }
36521
+ function isSameKind(a, b) {
36522
+ if (a === b) return true;
36523
+ return similarity(a, b) >= SIMILARITY_THRESHOLD;
36524
+ }
36525
+ function checkOutbound(channelName, target, message) {
36526
+ const text2 = message.trim();
36527
+ if (!text2 || text2.length > MAX_COMPARE_LEN) {
36528
+ if (text2) states.delete(`${channelName}:${target}`);
36529
+ return true;
36530
+ }
36531
+ const key4 = `${channelName}:${target}`;
36532
+ const norm = normalize6(text2);
36533
+ const state = states.get(key4) ?? { recent: [] };
36534
+ let repeated = 1;
36535
+ for (let i = state.recent.length - 1; i >= 0; i--) {
36536
+ if (isSameKind(state.recent[i], norm)) repeated++;
36537
+ else break;
36538
+ }
36539
+ if (repeated >= MAX_REPEAT) {
36540
+ console.warn(
36541
+ `[loop-guard] BLOCKED channel=${channelName} target=${target} repeated=${repeated} text=${text2.slice(0, 40)}`
36542
+ );
36543
+ return false;
36544
+ }
36545
+ state.recent.push(norm);
36546
+ if (state.recent.length > HISTORY_SIZE) state.recent.shift();
36547
+ states.set(key4, state);
36548
+ return true;
36549
+ }
36550
+
36230
36551
  // src/channels/manager.ts
36231
36552
  var MANAGED_CHANNEL_NAMES = ["discord", "feishu", "wechat", "deskBuddy", "ccBridge", "telegram", "whatsapp", "dingtalk", "wecom"];
36232
36553
  var defaultFactories = {
@@ -36605,6 +36926,9 @@ var ChannelManager = class {
36605
36926
  if (!adapter) {
36606
36927
  throw new Error(`No adapter for ${channelName}`);
36607
36928
  }
36929
+ if (!checkOutbound(channelName, target, message)) {
36930
+ throw new LoopBlockedError(target, 3);
36931
+ }
36608
36932
  try {
36609
36933
  if (hasMemoryEffectContext() && (!adapter.memoryGuardedSends || hasAutomaticMemoryEffectContext() && adapter.memoryGuardedAutomation === false)) throw new Error(`MEMORY_EXECUTION_BLOCKED: adapter ${channelName} has no final send guard`);
36610
36934
  await guardedExternalEffect(() => adapter.send(target, message, options));
@@ -36702,12 +37026,12 @@ var quiet2 = { error: () => {
36702
37026
  }, debug: () => {
36703
37027
  }, trace: () => {
36704
37028
  } };
36705
- function path35(value) {
37029
+ function path36(value) {
36706
37030
  if (typeof value !== "string" || !isAbsolute5(value)) throw new Error("TRAVEL_GATEWAY_ABSOLUTE_PATH_REQUIRED");
36707
37031
  return resolve11(value);
36708
37032
  }
36709
37033
  function tls2(config) {
36710
- return { ca: readPrivateFile(path35(config?.caFile), 1024 * 1024), cert: readPrivateFile(path35(config?.certFile), 1024 * 1024), key: readPrivateFile(path35(config?.keyFile), 16384) };
37034
+ return { ca: readPrivateFile(path36(config?.caFile), 1024 * 1024), cert: readPrivateFile(path36(config?.certFile), 1024 * 1024), key: readPrivateFile(path36(config?.keyFile), 16384) };
36711
37035
  }
36712
37036
  async function startTravelGateway(config) {
36713
37037
  if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key4) => config.identity[key4] !== config.keyService.identity[key4])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
@@ -36717,7 +37041,7 @@ async function startTravelGateway(config) {
36717
37041
  if (feishuIngress && !/^cli_[0-9a-fA-F]{16}$/.test(config.feishu?.appId)) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
36718
37042
  const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls2(config.keyService.tls), timeoutMs: 1e4 };
36719
37043
  const material = await fetchTravelKey(keyConfig);
36720
- const keyDigest = createHash37("sha256").update(material.key).digest("hex");
37044
+ const keyDigest = createHash38("sha256").update(material.key).digest("hex");
36721
37045
  let keyWatermark = material.deletionWatermark;
36722
37046
  const refreshInterval = config.keyRefreshIntervalMs ?? 1e4, maxKeyAge = config.keyMaxAgeMs ?? 3e4;
36723
37047
  if (!Number.isSafeInteger(refreshInterval) || refreshInterval < 100 || refreshInterval > 1e4 || !Number.isSafeInteger(maxKeyAge) || maxKeyAge < 2 * refreshInterval || maxKeyAge > 3e4) {
@@ -36758,14 +37082,14 @@ async function startTravelGateway(config) {
36758
37082
  }
36759
37083
  };
36760
37084
  try {
36761
- objects = await PublicationObjects.open({ directory: path35(config.objectsDir), identity: config.identity, key: material.key });
36762
- authority = new TravelAuthority({ directory: path35(config.authorityDir), leaseMs: config.leaseMs });
37085
+ objects = await PublicationObjects.open({ directory: path36(config.objectsDir), identity: config.identity, key: material.key });
37086
+ authority = new TravelAuthority({ directory: path36(config.authorityDir), leaseMs: config.leaseMs });
36763
37087
  if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
36764
37088
  for (const credential of Object.values(config.allowedPeers)) {
36765
37089
  const principal = authority.authenticate(String(credential));
36766
37090
  if (["tenantId", "companionId", "seatId"].some((key4) => principal[key4] !== config.identity[key4]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36767
37091
  }
36768
- store = new TravelGatewayStore({ directory: path35(config.gatewayDir), identity: config.identity, objects, authority });
37092
+ store = new TravelGatewayStore({ directory: path36(config.gatewayDir), identity: config.identity, objects, authority });
36769
37093
  await store.migrateStoredInputs();
36770
37094
  if (config.previouslyProcessedPlatformIds) store.importProcessedInputs(config.previouslyProcessedPlatformIds);
36771
37095
  platform = createFeishuGatewayPlatform(config.feishu);
@@ -36819,7 +37143,7 @@ async function startTravelGateway(config) {
36819
37143
  }
36820
37144
  });
36821
37145
  if (config.channels && config.ingressEnabled !== false) {
36822
- adapters.setFactoryContext({ stateDir: path35(config.platformStateDir) });
37146
+ adapters.setFactoryContext({ stateDir: path36(config.platformStateDir) });
36823
37147
  adapters.loadFromConfig(Object.fromEntries(Object.entries(config.channels).filter(([name, value]) => name !== "feishu" && value.enabled)));
36824
37148
  for (const channel of ["discord", "wechat"]) {
36825
37149
  const adapter = adapters.getAdapter(channel);
@@ -36882,7 +37206,7 @@ async function startTravelGateway(config) {
36882
37206
  checking = true;
36883
37207
  void fetchTravelKey(keyConfig).then((current2) => {
36884
37208
  try {
36885
- if (!objects || createHash37("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
37209
+ if (!objects || createHash38("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
36886
37210
  keyWatermark = current2.deletionWatermark;
36887
37211
  lastKeyCheck = Number(process.hrtime.bigint() / 1000000n);
36888
37212
  } finally {
@@ -36905,7 +37229,7 @@ async function startTravelGateway(config) {
36905
37229
  async function runTravelGatewayCli(args) {
36906
37230
  if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-gateway serve --config /absolute/private-config.json" };
36907
37231
  if (args.length !== 3 || args[0] !== "serve" || args[1] !== "--config") throw new Error("TRAVEL_GATEWAY_INVALID_COMMAND");
36908
- const config = JSON.parse(readPrivateFile(path35(args[2]), 65536).toString());
37232
+ const config = JSON.parse(readPrivateFile(path36(args[2]), 65536).toString());
36909
37233
  const gateway = await startTravelGateway(config);
36910
37234
  let closing = false;
36911
37235
  const stop = () => {