engine7 7.1.151 → 7.1.153
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bg-worker.mjs +978 -424
- package/dist/cli.mjs +1209 -728
- package/dist/engine-startup.mjs +1775 -1169
- package/dist/main.mjs +1729 -1123
- package/dist/recall-worker.mjs +162 -52
- package/dist/sqlite-maintenance-worker.mjs +1 -1
- package/dist/topics-worker.mjs +144 -45
- package/dist/travel-data.mjs +1 -1
- package/dist/travel-gateway.mjs +608 -255
- package/dist/travel-host.mjs +659 -404
- package/dist/travel-initial-baseline.mjs +1 -1
- package/dist/travel-node-data.mjs +1 -1
- package/dist/travel-node.mjs +124 -41
- package/dist/travel-pairing.mjs +637 -284
- package/package.json +1 -1
- package/templates/skills/sop/SKILL.md +42 -150
package/dist/travel-gateway.mjs
CHANGED
|
@@ -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(
|
|
49
|
-
const info = lstatSync(
|
|
50
|
-
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(
|
|
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(
|
|
53
|
+
function syncDir(path37) {
|
|
54
54
|
if (process.platform === "win32") return;
|
|
55
|
-
const fd = openSync(
|
|
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(
|
|
62
|
+
function preparePrivateDirectory(path37) {
|
|
63
63
|
const missing = [];
|
|
64
|
-
let parent = resolve(
|
|
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(
|
|
85
|
+
assertPrivateDirectory(path37);
|
|
86
86
|
}
|
|
87
|
-
function preparePrivateDatabase(
|
|
88
|
-
for (const file2 of [
|
|
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(
|
|
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(
|
|
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(
|
|
106
|
+
syncDir(dirname(path37));
|
|
107
107
|
}
|
|
108
|
-
async function syncDirAsync(
|
|
108
|
+
async function syncDirAsync(path37) {
|
|
109
109
|
if (process.platform === "win32") return;
|
|
110
|
-
const fd = await open(
|
|
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(
|
|
118
|
-
const temp = join(dirname(
|
|
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,
|
|
122
|
-
if (!deferDirectorySync) await syncDirAsync(dirname(
|
|
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
|
|
342
|
-
const file2 = await open(
|
|
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 }),
|
|
465
|
-
if (
|
|
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(
|
|
547
|
-
assertPrivateStat(lstatSync2(
|
|
548
|
-
const fd = openSync2(
|
|
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(
|
|
569
|
-
const stat3 = lstatSync3(
|
|
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(
|
|
573
|
-
const before = lstatSync3(
|
|
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(
|
|
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(
|
|
584
|
-
const temporary =
|
|
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,
|
|
586
|
+
renameSync(temporary, path37);
|
|
587
587
|
if (process.platform !== "win32") {
|
|
588
|
-
const fd = openSync3(dirname2(
|
|
588
|
+
const fd = openSync3(dirname2(path37), "r");
|
|
589
589
|
try {
|
|
590
590
|
fsyncSync3(fd);
|
|
591
591
|
} finally {
|
|
@@ -1610,7 +1610,29 @@ function tokenize(text2) {
|
|
|
1610
1610
|
function tokenizeToField(text2) {
|
|
1611
1611
|
return tokenize(text2).join(" ");
|
|
1612
1612
|
}
|
|
1613
|
-
|
|
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
|
+
}
|
|
1620
|
+
function invisibleCjkNeedles(candidates2) {
|
|
1621
|
+
return [...new Set(candidates2.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
|
|
1622
|
+
}
|
|
1623
|
+
function literalQueryNeedles(text2) {
|
|
1624
|
+
const chars = shortCjkCharCount(text2);
|
|
1625
|
+
if (!chars || chars > 6) return null;
|
|
1626
|
+
const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
|
|
1627
|
+
return names.length ? names : queryBigramNeedles(text2);
|
|
1628
|
+
}
|
|
1629
|
+
function queryBigramNeedles(text2) {
|
|
1630
|
+
const chars = shortCjkCharCount(text2);
|
|
1631
|
+
if (!chars || chars > 6) return null;
|
|
1632
|
+
const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
|
|
1633
|
+
return grams.length ? grams : null;
|
|
1634
|
+
}
|
|
1635
|
+
var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
|
|
1614
1636
|
var init_tokenizer = __esm({
|
|
1615
1637
|
"src/mem7/core/tokenizer.ts"() {
|
|
1616
1638
|
"use strict";
|
|
@@ -1683,6 +1705,7 @@ var init_tokenizer = __esm({
|
|
|
1683
1705
|
]);
|
|
1684
1706
|
MIN_TOKEN_LENGTH = 2;
|
|
1685
1707
|
jieba = null;
|
|
1708
|
+
shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
|
|
1686
1709
|
}
|
|
1687
1710
|
});
|
|
1688
1711
|
|
|
@@ -1896,14 +1919,14 @@ var init_live = __esm({
|
|
|
1896
1919
|
}
|
|
1897
1920
|
/** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
|
|
1898
1921
|
async persistToFile(dotPath, val, atomic = false) {
|
|
1899
|
-
const
|
|
1922
|
+
const fs27 = await import("node:fs");
|
|
1900
1923
|
const cfgPath = this.current?._configFilePath;
|
|
1901
|
-
if (!cfgPath || !
|
|
1924
|
+
if (!cfgPath || !fs27.existsSync(cfgPath)) {
|
|
1902
1925
|
console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
|
|
1903
1926
|
return false;
|
|
1904
1927
|
}
|
|
1905
1928
|
try {
|
|
1906
|
-
const raw = JSON.parse(
|
|
1929
|
+
const raw = JSON.parse(fs27.readFileSync(cfgPath, "utf-8"));
|
|
1907
1930
|
const keys = dotPath.split(".");
|
|
1908
1931
|
let o = raw;
|
|
1909
1932
|
for (let i = 0; i < keys.length - 1; i++) {
|
|
@@ -1913,7 +1936,7 @@ var init_live = __esm({
|
|
|
1913
1936
|
o[keys[keys.length - 1]] = val;
|
|
1914
1937
|
if (atomic) {
|
|
1915
1938
|
writeConfigAtomic(cfgPath, raw);
|
|
1916
|
-
} else
|
|
1939
|
+
} else fs27.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
|
|
1917
1940
|
const lastKey = keys[keys.length - 1].toLowerCase();
|
|
1918
1941
|
const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
|
|
1919
1942
|
const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
|
|
@@ -2251,12 +2274,12 @@ function overlaps(a, b) {
|
|
|
2251
2274
|
return (a.validTo === null || b.validFrom === null || b.validFrom < a.validTo) && (b.validTo === null || a.validFrom === null || a.validFrom < b.validTo);
|
|
2252
2275
|
}
|
|
2253
2276
|
function canonicalJson(value) {
|
|
2254
|
-
const
|
|
2255
|
-
if (Array.isArray(input)) return input.map(
|
|
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,
|
|
2277
|
+
const normalize7 = (input) => {
|
|
2278
|
+
if (Array.isArray(input)) return input.map(normalize7);
|
|
2279
|
+
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
2280
|
return input;
|
|
2258
2281
|
};
|
|
2259
|
-
const json = JSON.stringify(
|
|
2282
|
+
const json = JSON.stringify(normalize7(value));
|
|
2260
2283
|
if (json === void 0) throw new Error("INVALID_JSON_VALUE");
|
|
2261
2284
|
return json;
|
|
2262
2285
|
}
|
|
@@ -2780,8 +2803,9 @@ function invalidateDerivedDependencies(db2, event2) {
|
|
|
2780
2803
|
}
|
|
2781
2804
|
return invalidateChildren(db2, event2.scopeId, pending, event2.kind);
|
|
2782
2805
|
}
|
|
2783
|
-
function invalidateScopeDependencies(db2, scope, parent, reason) {
|
|
2784
|
-
|
|
2806
|
+
function invalidateScopeDependencies(db2, scope, parent, reason, options = {}) {
|
|
2807
|
+
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);
|
|
2808
|
+
if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
|
|
2785
2809
|
invalidateChildren(db2, scope, children, reason);
|
|
2786
2810
|
}
|
|
2787
2811
|
function invalidateChildren(db2, scope, pending, reason) {
|
|
@@ -2801,7 +2825,7 @@ function invalidateChildren(db2, scope, pending, reason) {
|
|
|
2801
2825
|
}
|
|
2802
2826
|
const state = child.deleted ? "deleted" : "needs_revalidation";
|
|
2803
2827
|
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'
|
|
2828
|
+
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
2829
|
result.push(child.child_id);
|
|
2806
2830
|
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
2831
|
}
|
|
@@ -2896,7 +2920,7 @@ var init_dependencies = __esm({
|
|
|
2896
2920
|
if (previous && previous.version === version && previous.state !== "current") throw new Error("DERIVATION_REQUIRES_NEW_VERSION");
|
|
2897
2921
|
this.assertReferences(scope, dependencies);
|
|
2898
2922
|
if (previous?.version === version) {
|
|
2899
|
-
const
|
|
2923
|
+
const normalize7 = (refs) => JSON.stringify(refs.map((ref) => [
|
|
2900
2924
|
ref.parentKind,
|
|
2901
2925
|
ref.parentId,
|
|
2902
2926
|
ref.parentVersion,
|
|
@@ -2904,7 +2928,7 @@ var init_dependencies = __esm({
|
|
|
2904
2928
|
ref.slotRevision ?? null,
|
|
2905
2929
|
ref.role
|
|
2906
2930
|
]).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))));
|
|
2907
|
-
if (
|
|
2931
|
+
if (normalize7(this.refs(scope, kind, id3)) !== normalize7(dependencies)) throw new Error("DERIVATION_VERSION_CONFLICT");
|
|
2908
2932
|
return;
|
|
2909
2933
|
}
|
|
2910
2934
|
this.db.prepare(`INSERT INTO memory_derivations VALUES (?,?,?,?,'current',NULL,?)
|
|
@@ -3351,7 +3375,7 @@ function textColumnOf(kind) {
|
|
|
3351
3375
|
return "fact";
|
|
3352
3376
|
}
|
|
3353
3377
|
}
|
|
3354
|
-
var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
|
|
3378
|
+
var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
|
|
3355
3379
|
var init_vector_store = __esm({
|
|
3356
3380
|
"src/mem7/core/vector-store.ts"() {
|
|
3357
3381
|
"use strict";
|
|
@@ -3382,6 +3406,14 @@ var init_vector_store = __esm({
|
|
|
3382
3406
|
agent_case: ["task_intent_tokens", "approach_tokens"],
|
|
3383
3407
|
agent_skill: ["description_tokens", "content_tokens"]
|
|
3384
3408
|
};
|
|
3409
|
+
BM25_TEXT_FIELDS = {
|
|
3410
|
+
foresight: ["foresight", "evidence"],
|
|
3411
|
+
episode: ["episode"],
|
|
3412
|
+
atomic_fact: ["fact"],
|
|
3413
|
+
agent_case: ["task_intent", "approach"],
|
|
3414
|
+
agent_skill: ["description", "content"]
|
|
3415
|
+
};
|
|
3416
|
+
sqlLiteral = (value) => value.replace(/'/g, "''");
|
|
3385
3417
|
RRF_K = 60;
|
|
3386
3418
|
warnedFts = /* @__PURE__ */ new Set();
|
|
3387
3419
|
warnedVecIdx = /* @__PURE__ */ new Set();
|
|
@@ -3979,6 +4011,47 @@ var init_vector_store = __esm({
|
|
|
3979
4011
|
if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
|
|
3980
4012
|
}
|
|
3981
4013
|
}
|
|
4014
|
+
const textCols = BM25_TEXT_FIELDS[kind];
|
|
4015
|
+
const scan = async (terms, op, limit2) => {
|
|
4016
|
+
const expr = op === "AND" ? terms.map((g) => `(${textCols.map((col) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" AND ") : textCols.map((col) => `(${terms.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
|
|
4017
|
+
const where2 = compileFilter(opts.filter);
|
|
4018
|
+
return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit2).toArray();
|
|
4019
|
+
};
|
|
4020
|
+
const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
|
|
4021
|
+
const scoreLiteral = (needles2, rows) => {
|
|
4022
|
+
const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
|
|
4023
|
+
const occurrences2 = (text2, term) => text2.split(term).length - 1;
|
|
4024
|
+
for (const r of rows) {
|
|
4025
|
+
const rid = String(r.id ?? "");
|
|
4026
|
+
if (!rid) continue;
|
|
4027
|
+
const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
|
|
4028
|
+
const matched = terms.filter((term) => text2.includes(term));
|
|
4029
|
+
if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
|
|
4030
|
+
const full = matched.length === terms.length;
|
|
4031
|
+
const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
|
|
4032
|
+
const score = full ? maxScore + 1 + Math.min(0.99, density / 10) : maxScore > 0 ? maxScore * (0.5 + 0.5 * matched.length / terms.length) : matched.length / terms.length;
|
|
4033
|
+
const cur = best.get(rid);
|
|
4034
|
+
if (cur) {
|
|
4035
|
+
if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
|
|
4036
|
+
} else best.set(rid, { ...r, _score: score });
|
|
4037
|
+
}
|
|
4038
|
+
};
|
|
4039
|
+
const needles = literalQueryNeedles(queryText);
|
|
4040
|
+
if (needles) {
|
|
4041
|
+
try {
|
|
4042
|
+
const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
|
|
4043
|
+
const [all, any] = await Promise.all([
|
|
4044
|
+
terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
|
|
4045
|
+
scan(needles, "OR", topK * 3)
|
|
4046
|
+
]);
|
|
4047
|
+
scoreLiteral(needles, [...all, ...any]);
|
|
4048
|
+
if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
|
|
4049
|
+
const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
|
|
4050
|
+
if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
|
|
4051
|
+
}
|
|
4052
|
+
} catch {
|
|
4053
|
+
}
|
|
4054
|
+
}
|
|
3982
4055
|
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
4056
|
} catch (err) {
|
|
3984
4057
|
const msg2 = String(err?.message ?? err);
|
|
@@ -4504,7 +4577,7 @@ import { createHash as createHash9 } from "node:crypto";
|
|
|
4504
4577
|
function projectedSourceIdFromScopeId(id3, originKey, sourceVersion) {
|
|
4505
4578
|
return "src_" + digest([id3, originKey, sourceVersion]);
|
|
4506
4579
|
}
|
|
4507
|
-
var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
|
|
4580
|
+
var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
|
|
4508
4581
|
var init_source_store = __esm({
|
|
4509
4582
|
"src/mem7/core/source-store.ts"() {
|
|
4510
4583
|
"use strict";
|
|
@@ -4516,6 +4589,7 @@ var init_source_store = __esm({
|
|
|
4516
4589
|
init_watermarks();
|
|
4517
4590
|
init_interpretation_impact();
|
|
4518
4591
|
init_conversation_text();
|
|
4592
|
+
RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
|
|
4519
4593
|
SOURCE_SCHEMA = `
|
|
4520
4594
|
CREATE TABLE memory_scopes (
|
|
4521
4595
|
scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
|
|
@@ -4697,8 +4771,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
|
|
|
4697
4771
|
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
4772
|
if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
|
|
4699
4773
|
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");
|
|
4774
|
+
invalidateScopeDependencies(this.db, id3, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
|
|
4775
|
+
invalidateScopeDependencies(this.db, id3, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
|
|
4702
4776
|
const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id3).source_seq);
|
|
4703
4777
|
const sourceId = projectedSourceIdFromScopeId(id3, input.originKey, version);
|
|
4704
4778
|
const receiptId = "rcpt_" + digest([id3, sourceId]);
|
|
@@ -4868,10 +4942,10 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
|
|
|
4868
4942
|
AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)
|
|
4869
4943
|
ORDER BY source_seq DESC LIMIT ?`).all(scopeId(scope), source.sessionId, source.sourceSeq, limit2).map((row) => this.source(row)).reverse();
|
|
4870
4944
|
}
|
|
4871
|
-
pendingInterpretations(scope, sessionId, limit2 = 50, cutoff, newestFirst = false,
|
|
4872
|
-
if (
|
|
4945
|
+
pendingInterpretations(scope, sessionId, limit2 = 50, cutoff, newestFirst = false, states2, textTerms, roles) {
|
|
4946
|
+
if (states2?.some((state) => !["received", "applied", "needs_review", "failed"].includes(state))) throw new Error("INVALID_SOURCE_STATE");
|
|
4873
4947
|
if (roles?.some((role) => !["user", "assistant", "tool"].includes(role))) throw new Error("INVALID_SOURCE_ROLE");
|
|
4874
|
-
if (
|
|
4948
|
+
if (states2?.length === 0) return [];
|
|
4875
4949
|
if (roles?.length === 0) return [];
|
|
4876
4950
|
const terms = textTerms ? [...new Set(textTerms.map((term) => term.trim().toLowerCase()).filter(Boolean))] : void 0;
|
|
4877
4951
|
if (terms?.length === 0) return [];
|
|
@@ -4879,7 +4953,7 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
|
|
|
4879
4953
|
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
4954
|
if (cutoff) return historicalRows(this.db, scope, "source", cutoff).filter((row) => !["applied", "deleted"].includes(row.state)).flatMap((row) => {
|
|
4881
4955
|
const source = this.get(scope, row.targetId, cutoff);
|
|
4882
|
-
if (!source || !this.isCurrent(scope, source.sourceId, cutoff) || sessionId && source.sessionId !== sessionId ||
|
|
4956
|
+
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
4957
|
return [{
|
|
4884
4958
|
...source,
|
|
4885
4959
|
state: row.state,
|
|
@@ -4891,13 +4965,13 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
|
|
|
4891
4965
|
const rows = this.db.prepare(`SELECT * FROM memory_sources s WHERE scope_id=? AND interpretation_status<>'applied'
|
|
4892
4966
|
AND interpretation_status<>'deleted' AND NOT EXISTS (SELECT 1 FROM memory_sources newer
|
|
4893
4967
|
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=?" : ""} ${
|
|
4968
|
+
${this.recoveryClause("s")} ${sessionId ? "AND session_id=?" : ""} ${states2 ? `AND interpretation_status IN (${states2.map(() => "?").join(",")})` : ""}
|
|
4895
4969
|
${terms ? `AND (${terms.map((term) => latinTerm(term) ? "(' ' || lower(s.text) || ' ') GLOB ?" : "instr(lower(s.text), ?) > 0").join(" OR ")})` : ""}
|
|
4896
4970
|
${roles ? `AND role IN (${roles.map(() => "?").join(",")})` : ""}
|
|
4897
4971
|
ORDER BY source_seq ${newestFirst ? "DESC" : "ASC"} LIMIT ?`).all(
|
|
4898
4972
|
scopeId(scope),
|
|
4899
4973
|
...sessionId ? [sessionId] : [],
|
|
4900
|
-
...
|
|
4974
|
+
...states2 ?? [],
|
|
4901
4975
|
...terms?.map((term) => latinTerm(term) ? `*[^a-z0-9_]${term}[^a-z0-9_]*` : term) ?? [],
|
|
4902
4976
|
...roles ?? [],
|
|
4903
4977
|
limit2
|
|
@@ -5390,8 +5464,8 @@ var init_recovery_deletion = __esm({
|
|
|
5390
5464
|
const { owners, parents } = this.links(table, row);
|
|
5391
5465
|
for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
|
|
5392
5466
|
if (table === "memory_artifact_publications") {
|
|
5393
|
-
const medium = text(row, "medium"),
|
|
5394
|
-
const identity = medium === "markdown" &&
|
|
5467
|
+
const medium = text(row, "medium"), path37 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
|
|
5468
|
+
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
5469
|
if (identity) {
|
|
5396
5470
|
const rows = this.artifactPaths.get(identity) ?? [];
|
|
5397
5471
|
rows.push(row);
|
|
@@ -5399,8 +5473,8 @@ var init_recovery_deletion = __esm({
|
|
|
5399
5473
|
}
|
|
5400
5474
|
}
|
|
5401
5475
|
}
|
|
5402
|
-
blocksArtifactPath(kind,
|
|
5403
|
-
const rows = this.artifactPaths.get(kind + ":" +
|
|
5476
|
+
blocksArtifactPath(kind, path37) {
|
|
5477
|
+
const rows = this.artifactPaths.get(kind + ":" + path37);
|
|
5404
5478
|
return rows?.some((row) => this.blocks("memory_artifact_publications", row));
|
|
5405
5479
|
}
|
|
5406
5480
|
blocks(table, row) {
|
|
@@ -6419,7 +6493,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
|
|
|
6419
6493
|
};
|
|
6420
6494
|
const candidates2 = [];
|
|
6421
6495
|
const duplicateIds = /* @__PURE__ */ new Set();
|
|
6422
|
-
const inside = (
|
|
6496
|
+
const inside = (path37) => path37 && !isAbsolute2(path37) && path37 !== ".." && !path37.startsWith(`..${sep2}`);
|
|
6423
6497
|
for (const relativePath of input.files) {
|
|
6424
6498
|
const logical = resolve4(root, relativePath);
|
|
6425
6499
|
let canonical4;
|
|
@@ -6433,10 +6507,10 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
|
|
|
6433
6507
|
gap("projection_path_unverified");
|
|
6434
6508
|
continue;
|
|
6435
6509
|
}
|
|
6436
|
-
const
|
|
6510
|
+
const path37 = relative2(root, canonical4).replace(/\\/g, "/");
|
|
6437
6511
|
const user = `users/${input.scope.ownerId}/`;
|
|
6438
6512
|
const agent = store.ownerProjectionPath("agents", input.scope.ownerId, input.scope).replace(/\\/g, "/") + "/";
|
|
6439
|
-
const kind =
|
|
6513
|
+
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
6514
|
if (!kind) {
|
|
6441
6515
|
gap("projection_kind_or_owner_unverified");
|
|
6442
6516
|
continue;
|
|
@@ -6473,9 +6547,9 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
|
|
|
6473
6547
|
continue;
|
|
6474
6548
|
}
|
|
6475
6549
|
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(),
|
|
6550
|
+
const target = join8(store.mem7RootPath(), path37);
|
|
6477
6551
|
if (previous) {
|
|
6478
|
-
if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !==
|
|
6552
|
+
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
6553
|
gap("projection_mapping_conflict");
|
|
6480
6554
|
continue;
|
|
6481
6555
|
}
|
|
@@ -6491,7 +6565,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
|
|
|
6491
6565
|
candidates2.push({
|
|
6492
6566
|
file: canonical4,
|
|
6493
6567
|
fileHash,
|
|
6494
|
-
relativePath:
|
|
6568
|
+
relativePath: path37,
|
|
6495
6569
|
id: match[1],
|
|
6496
6570
|
kind,
|
|
6497
6571
|
parent,
|
|
@@ -7973,9 +8047,9 @@ function normalize3(input) {
|
|
|
7973
8047
|
if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
7974
8048
|
return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
|
|
7975
8049
|
}
|
|
7976
|
-
function directory(
|
|
7977
|
-
const info = lstatSync6(
|
|
7978
|
-
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(
|
|
8050
|
+
function directory(path37) {
|
|
8051
|
+
const info = lstatSync6(path37);
|
|
8052
|
+
if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path37) !== resolve5(path37) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
|
|
7979
8053
|
throw new Error("REPLICATION_REGISTRATION_INVALID");
|
|
7980
8054
|
}
|
|
7981
8055
|
function readRuntimeReplicationRegistration(stateDir, component, key4) {
|
|
@@ -8079,10 +8153,10 @@ var init_runtime_replication = __esm({
|
|
|
8079
8153
|
|
|
8080
8154
|
// src/memory/topics-history/index.ts
|
|
8081
8155
|
import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
|
|
8082
|
-
function parseTopicHistoryPath(
|
|
8083
|
-
if (!
|
|
8156
|
+
function parseTopicHistoryPath(path37) {
|
|
8157
|
+
if (!path37.startsWith("topics-history://") || path37.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
|
|
8084
8158
|
try {
|
|
8085
|
-
return JSON.parse(Buffer.from(
|
|
8159
|
+
return JSON.parse(Buffer.from(path37.slice(17), "base64url").toString("utf8"));
|
|
8086
8160
|
} catch {
|
|
8087
8161
|
throw new Error("INVALID_HISTORY_REFERENCE");
|
|
8088
8162
|
}
|
|
@@ -10027,23 +10101,23 @@ var init_facts = __esm({
|
|
|
10027
10101
|
if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
|
|
10028
10102
|
}
|
|
10029
10103
|
for (const [index, evidence] of proposal.evidence.entries()) {
|
|
10030
|
-
const
|
|
10031
|
-
if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${
|
|
10104
|
+
const path37 = `evidence[${index}]`;
|
|
10105
|
+
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
10106
|
const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
|
|
10033
10107
|
AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
|
|
10034
10108
|
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: ${
|
|
10036
|
-
if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${
|
|
10109
|
+
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`);
|
|
10110
|
+
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
10111
|
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
10112
|
const count = occurrences(source.text, evidence.quote);
|
|
10039
|
-
throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${
|
|
10113
|
+
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
10114
|
}
|
|
10041
|
-
if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${
|
|
10115
|
+
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
10116
|
const relationValue = proposal.value;
|
|
10043
10117
|
if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
|
|
10044
10118
|
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
10119
|
}
|
|
10046
|
-
const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${
|
|
10120
|
+
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
10121
|
if (proposal.claimKind !== "inference") {
|
|
10048
10122
|
if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
|
|
10049
10123
|
if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
|
|
@@ -10403,7 +10477,7 @@ function contentHash(text2) {
|
|
|
10403
10477
|
function mem7Root(stateDir) {
|
|
10404
10478
|
return join11(stateDir, "mem7");
|
|
10405
10479
|
}
|
|
10406
|
-
var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
|
|
10480
|
+
var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
|
|
10407
10481
|
var init_store = __esm({
|
|
10408
10482
|
"src/mem7/core/store.ts"() {
|
|
10409
10483
|
"use strict";
|
|
@@ -10441,6 +10515,7 @@ var init_store = __esm({
|
|
|
10441
10515
|
init_job_retention();
|
|
10442
10516
|
init_retire_graph_audits();
|
|
10443
10517
|
STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
|
|
10518
|
+
STARVATION_GRACE_MS = 36e5;
|
|
10444
10519
|
SCHEMA = `
|
|
10445
10520
|
CREATE TABLE IF NOT EXISTS memcells (
|
|
10446
10521
|
id TEXT PRIMARY KEY,
|
|
@@ -11034,13 +11109,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
|
|
|
11034
11109
|
const version = expectedVersion ?? this.dependencies.version(scope, kind, id3);
|
|
11035
11110
|
this.dependencies.assertCurrent(scope, kind, id3, version);
|
|
11036
11111
|
const digest7 = createHash20("sha256").update(content.trim()).digest("hex");
|
|
11037
|
-
const
|
|
11112
|
+
const path37 = relative3(this.root, file2).replace(/\\/g, "/");
|
|
11038
11113
|
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 !==
|
|
11114
|
+
if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path37)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
|
|
11040
11115
|
this.db.prepare(`INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)
|
|
11041
11116
|
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,
|
|
11043
|
-
this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path:
|
|
11117
|
+
WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id3, path37, version, digest7);
|
|
11118
|
+
this.artifacts.publish(scope, { ...body, kind, id: id3, version, medium: "markdown", path: path37, markdown: content.trim() });
|
|
11044
11119
|
});
|
|
11045
11120
|
}
|
|
11046
11121
|
projectionMatches(scope, kind, id3, file2, content) {
|
|
@@ -11237,8 +11312,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
|
|
|
11237
11312
|
};
|
|
11238
11313
|
}
|
|
11239
11314
|
unscopedProjectionMatches(ownerId, kind, id3, file2, content) {
|
|
11240
|
-
const
|
|
11241
|
-
const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3,
|
|
11315
|
+
const path37 = relative3(this.root, file2).replace(/\\/g, "/");
|
|
11316
|
+
const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id3, path37);
|
|
11242
11317
|
if (mappings.length) {
|
|
11243
11318
|
if (mappings.length !== 1) return false;
|
|
11244
11319
|
const scope = this.sources.scope(mappings[0].scope_id);
|
|
@@ -11531,7 +11606,7 @@ ${e.outcome}
|
|
|
11531
11606
|
return this.transaction(() => {
|
|
11532
11607
|
const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
|
|
11533
11608
|
const scopeFilter = options.scopeId !== void 0 ? " AND scope_id=?" : "";
|
|
11534
|
-
const
|
|
11609
|
+
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
11610
|
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
11611
|
AND ((status='pending' AND next_run_at<=?)
|
|
11537
11612
|
OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
|
|
@@ -11551,40 +11626,48 @@ ${e.outcome}
|
|
|
11551
11626
|
-- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
|
|
11552
11627
|
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
11628
|
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
|
-
|
|
11556
|
-
|
|
11557
|
-
|
|
11558
|
-
|
|
11559
|
-
|
|
11560
|
-
|
|
11561
|
-
|
|
11562
|
-
|
|
11563
|
-
|
|
11564
|
-
|
|
11565
|
-
|
|
11566
|
-
if (
|
|
11567
|
-
|
|
11568
|
-
|
|
11569
|
-
|
|
11570
|
-
|
|
11571
|
-
|
|
11572
|
-
|
|
11573
|
-
|
|
11574
|
-
|
|
11575
|
-
|
|
11576
|
-
|
|
11577
|
-
|
|
11578
|
-
|
|
11579
|
-
|
|
11580
|
-
|
|
11581
|
-
|
|
11582
|
-
|
|
11583
|
-
|
|
11584
|
-
|
|
11585
|
-
|
|
11586
|
-
|
|
11587
|
-
|
|
11629
|
+
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)`;
|
|
11630
|
+
const select = (starved2) => {
|
|
11631
|
+
const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
|
|
11632
|
+
ORDER BY priority,next_run_at,id LIMIT ?`;
|
|
11633
|
+
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];
|
|
11634
|
+
return this.db.prepare(sql).all(...args);
|
|
11635
|
+
};
|
|
11636
|
+
const claim = (rows) => {
|
|
11637
|
+
const claimedScopes = /* @__PURE__ */ new Set();
|
|
11638
|
+
return rows.flatMap((row) => {
|
|
11639
|
+
if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
|
|
11640
|
+
const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
|
|
11641
|
+
if (updated.scope_id !== row.scope_id && updated.scope_id) {
|
|
11642
|
+
const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
|
|
11643
|
+
AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
|
|
11644
|
+
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);
|
|
11645
|
+
if (conflict) return [];
|
|
11646
|
+
}
|
|
11647
|
+
return [updated];
|
|
11648
|
+
}).filter((row) => {
|
|
11649
|
+
if (!row.scope_id) return true;
|
|
11650
|
+
if (claimedScopes.has(row.scope_id)) return false;
|
|
11651
|
+
claimedScopes.add(row.scope_id);
|
|
11652
|
+
return true;
|
|
11653
|
+
}).map((row) => {
|
|
11654
|
+
const leaseToken = randomUUID9();
|
|
11655
|
+
this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
|
|
11656
|
+
return {
|
|
11657
|
+
id: row.id,
|
|
11658
|
+
kind: row.kind,
|
|
11659
|
+
payload: JSON.parse(row.payload),
|
|
11660
|
+
attempts: row.attempts,
|
|
11661
|
+
leaseToken,
|
|
11662
|
+
inputVersion: row.input_version,
|
|
11663
|
+
scopeId: row.scope_id ?? void 0,
|
|
11664
|
+
result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
|
|
11665
|
+
};
|
|
11666
|
+
});
|
|
11667
|
+
};
|
|
11668
|
+
if (options.staleOnly) return claim(select(true));
|
|
11669
|
+
const starved = claim(select(true));
|
|
11670
|
+
return starved.length ? starved : claim(select(false));
|
|
11588
11671
|
});
|
|
11589
11672
|
}
|
|
11590
11673
|
/** Compatibility entry point: only expired leases can be recovered. */
|
|
@@ -17962,9 +18045,9 @@ function isAutoMemPath(absolutePath, workspace) {
|
|
|
17962
18045
|
return normalizedPath.startsWith(getAutoMemPath(workspace));
|
|
17963
18046
|
}
|
|
17964
18047
|
async function ensureMemoryDirExists(memoryDir) {
|
|
17965
|
-
const
|
|
18048
|
+
const fs27 = await import("node:fs");
|
|
17966
18049
|
try {
|
|
17967
|
-
await
|
|
18050
|
+
await fs27.promises.mkdir(memoryDir, { recursive: true });
|
|
17968
18051
|
} catch (e) {
|
|
17969
18052
|
const code = e?.code;
|
|
17970
18053
|
if (code !== "EEXIST") {
|
|
@@ -18145,8 +18228,8 @@ __export(memdir_exports, {
|
|
|
18145
18228
|
loadMemoryPrompt: () => loadMemoryPrompt,
|
|
18146
18229
|
truncateEntrypointContent: () => truncateEntrypointContent
|
|
18147
18230
|
});
|
|
18148
|
-
import { readFileSync as
|
|
18149
|
-
import { join as
|
|
18231
|
+
import { readFileSync as readFileSync16 } from "node:fs";
|
|
18232
|
+
import { join as join29 } from "node:path";
|
|
18150
18233
|
function truncateEntrypointContent(raw) {
|
|
18151
18234
|
const trimmed = raw.trim();
|
|
18152
18235
|
const contentLines = trimmed.split("\n");
|
|
@@ -18239,11 +18322,11 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
|
|
|
18239
18322
|
}
|
|
18240
18323
|
function buildMemoryPrompt(params) {
|
|
18241
18324
|
const { displayName, memoryDir, extraGuidelines } = params;
|
|
18242
|
-
const entrypoint =
|
|
18325
|
+
const entrypoint = join29(memoryDir, ENTRYPOINT_NAME);
|
|
18243
18326
|
let entrypointContent = params.entrypointContent ?? "";
|
|
18244
18327
|
if (params.entrypointContent === void 0) {
|
|
18245
18328
|
try {
|
|
18246
|
-
entrypointContent =
|
|
18329
|
+
entrypointContent = readFileSync16(entrypoint, "utf-8");
|
|
18247
18330
|
} catch {
|
|
18248
18331
|
}
|
|
18249
18332
|
}
|
|
@@ -18289,8 +18372,8 @@ __export(context_analyzer_exports, {
|
|
|
18289
18372
|
formatContextReport: () => formatContextReport,
|
|
18290
18373
|
scanMemoryFiles: () => scanMemoryFiles
|
|
18291
18374
|
});
|
|
18292
|
-
import * as
|
|
18293
|
-
import * as
|
|
18375
|
+
import * as fs23 from "node:fs";
|
|
18376
|
+
import * as path30 from "node:path";
|
|
18294
18377
|
function estimateMessageTokens2(m) {
|
|
18295
18378
|
let tokens = 0;
|
|
18296
18379
|
if (typeof m.content === "string") {
|
|
@@ -18400,9 +18483,9 @@ function breakdownMessages(messages) {
|
|
|
18400
18483
|
}
|
|
18401
18484
|
async function scanMemoryFiles(workspace) {
|
|
18402
18485
|
const files = [];
|
|
18403
|
-
const soul = readFileIfExists(
|
|
18486
|
+
const soul = readFileIfExists(path30.join(workspace, "SOUL.md"));
|
|
18404
18487
|
if (soul) files.push({ path: "SOUL.md", tokens: roughTokenCountEstimation(soul), stable: true });
|
|
18405
|
-
const agents = readFileIfExists(
|
|
18488
|
+
const agents = readFileIfExists(path30.join(workspace, "AGENTS.md"));
|
|
18406
18489
|
if (agents) files.push({ path: "AGENTS.md", tokens: roughTokenCountEstimation(agents), stable: true });
|
|
18407
18490
|
try {
|
|
18408
18491
|
const { buildMemoryPrompt: buildMemoryPrompt2 } = await Promise.resolve().then(() => (init_memdir(), memdir_exports));
|
|
@@ -18418,7 +18501,7 @@ async function scanMemoryFiles(workspace) {
|
|
|
18418
18501
|
}
|
|
18419
18502
|
function readFileIfExists(filePath2) {
|
|
18420
18503
|
try {
|
|
18421
|
-
if (
|
|
18504
|
+
if (fs23.existsSync(filePath2)) return fs23.readFileSync(filePath2, "utf-8");
|
|
18422
18505
|
} catch {
|
|
18423
18506
|
}
|
|
18424
18507
|
return null;
|
|
@@ -18642,7 +18725,7 @@ var init_gateway_media = __esm({
|
|
|
18642
18725
|
// src/continuity/gateway-main.ts
|
|
18643
18726
|
import { isAbsolute as isAbsolute5, resolve as resolve11 } from "node:path";
|
|
18644
18727
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
18645
|
-
import { createHash as
|
|
18728
|
+
import { createHash as createHash38 } from "node:crypto";
|
|
18646
18729
|
import * as lark3 from "@larksuiteoapi/node-sdk";
|
|
18647
18730
|
|
|
18648
18731
|
// src/continuity/authority.ts
|
|
@@ -18708,9 +18791,9 @@ var TravelAuthority = class {
|
|
|
18708
18791
|
this.owner.close();
|
|
18709
18792
|
throw new Error("TRAVEL_AUTHORITY_BUSY", { cause: error });
|
|
18710
18793
|
}
|
|
18711
|
-
const
|
|
18794
|
+
const path37 = join2(options.directory, "authority.sqlite"), keyFile = join2(options.directory, "authority-signing.pem");
|
|
18712
18795
|
try {
|
|
18713
|
-
const present = existsSync(
|
|
18796
|
+
const present = existsSync(path37), keyPresent = existsSync(keyFile);
|
|
18714
18797
|
if (present !== keyPresent) throw new Error("TRAVEL_AUTHORITY_RECOVERY_REQUIRED");
|
|
18715
18798
|
if (!keyPresent) {
|
|
18716
18799
|
const keys = generateKeyPairSync("ed25519");
|
|
@@ -18718,8 +18801,8 @@ var TravelAuthority = class {
|
|
|
18718
18801
|
}
|
|
18719
18802
|
this.signingKey = readPrivateFile(keyFile).toString();
|
|
18720
18803
|
this.publicKey = createPublicKey(this.signingKey).export({ format: "pem", type: "spki" }).toString();
|
|
18721
|
-
preparePrivateDatabase(
|
|
18722
|
-
this.db = new DatabaseSync3(
|
|
18804
|
+
preparePrivateDatabase(path37);
|
|
18805
|
+
this.db = new DatabaseSync3(path37);
|
|
18723
18806
|
this.db.exec(`PRAGMA busy_timeout=1000; PRAGMA synchronous=FULL;
|
|
18724
18807
|
CREATE TABLE IF NOT EXISTS seats(identity TEXT PRIMARY KEY,epoch INTEGER NOT NULL,active_node TEXT,active_boot TEXT,
|
|
18725
18808
|
floor INTEGER NOT NULL,checkpoint TEXT NOT NULL,build TEXT NOT NULL,retired TEXT,frozen INTEGER NOT NULL DEFAULT 0);
|
|
@@ -19181,9 +19264,9 @@ import { isAbsolute, join as join3, relative, resolve as resolve2, sep } from "n
|
|
|
19181
19264
|
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
19265
|
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
19266
|
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(
|
|
19185
|
-
if (typeof
|
|
19186
|
-
for (const part of
|
|
19267
|
+
function validateRelativePath(path37) {
|
|
19268
|
+
if (typeof path37 !== "string" || !path37 || path37.length > 2048 || isAbsolute(path37)) throw new Error("INVALID_ARTIFACT_PATH");
|
|
19269
|
+
for (const part of path37.split("/")) {
|
|
19187
19270
|
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
19271
|
throw new Error("INVALID_ARTIFACT_PATH");
|
|
19189
19272
|
}
|
|
@@ -19231,10 +19314,10 @@ function normalizePublicationProfile(value) {
|
|
|
19231
19314
|
Object.freeze(profile.trees);
|
|
19232
19315
|
return Object.freeze(profile);
|
|
19233
19316
|
}
|
|
19234
|
-
function validatePublicationPath(
|
|
19235
|
-
if (typeof
|
|
19317
|
+
function validatePublicationPath(path37) {
|
|
19318
|
+
if (typeof path37 !== "string" || path37.normalize("NFC") !== path37) throw new Error("PUBLICATION_INVALID_PATH");
|
|
19236
19319
|
try {
|
|
19237
|
-
validateRelativePath(
|
|
19320
|
+
validateRelativePath(path37);
|
|
19238
19321
|
} catch {
|
|
19239
19322
|
throw new Error("PUBLICATION_INVALID_PATH");
|
|
19240
19323
|
}
|
|
@@ -19253,15 +19336,15 @@ function normalizePublication(value) {
|
|
|
19253
19336
|
if (!Array.isArray(tree.files) || !Array.isArray(tree.directories) || (paths += tree.files.length + tree.directories.length) > 1e5)
|
|
19254
19337
|
throw new Error("PUBLICATION_INVALID_TREE");
|
|
19255
19338
|
const occupied = /* @__PURE__ */ new Map();
|
|
19256
|
-
const claim = (
|
|
19257
|
-
validatePublicationPath(
|
|
19258
|
-
const folded =
|
|
19339
|
+
const claim = (path37, kind) => {
|
|
19340
|
+
validatePublicationPath(path37);
|
|
19341
|
+
const folded = path37.toLowerCase();
|
|
19259
19342
|
if (occupied.has(folded)) throw new Error("PUBLICATION_PATH_COLLISION");
|
|
19260
19343
|
occupied.set(folded, kind);
|
|
19261
19344
|
};
|
|
19262
|
-
const directories = tree.directories.map((
|
|
19263
|
-
claim(
|
|
19264
|
-
return
|
|
19345
|
+
const directories = tree.directories.map((path37) => {
|
|
19346
|
+
claim(path37, "directory");
|
|
19347
|
+
return path37;
|
|
19265
19348
|
}).sort();
|
|
19266
19349
|
const files = tree.files.map((file2) => {
|
|
19267
19350
|
claim(file2?.path, "file");
|
|
@@ -19273,8 +19356,8 @@ function normalizePublication(value) {
|
|
|
19273
19356
|
chunks: file2.content.chunks.map((r) => ({ sha256: r.sha256, bytes: r.bytes }))
|
|
19274
19357
|
} };
|
|
19275
19358
|
}).sort((a, b) => a.path.localeCompare(b.path, "en"));
|
|
19276
|
-
for (const
|
|
19277
|
-
const parts =
|
|
19359
|
+
for (const path37 of occupied.keys()) {
|
|
19360
|
+
const parts = path37.split("/");
|
|
19278
19361
|
for (let i = 1; i < parts.length; i++) if (occupied.get(parts.slice(0, i).join("/")) === "file") throw new Error("PUBLICATION_PATH_COLLISION");
|
|
19279
19362
|
}
|
|
19280
19363
|
return { id: tree.id, directories, files };
|
|
@@ -19705,9 +19788,9 @@ var TravelGatewayStore = class {
|
|
|
19705
19788
|
throw new Error("TRAVEL_GATEWAY_BUSY");
|
|
19706
19789
|
}
|
|
19707
19790
|
try {
|
|
19708
|
-
const
|
|
19709
|
-
preparePrivateDatabase(
|
|
19710
|
-
this.db = new DatabaseSync10(
|
|
19791
|
+
const path37 = join12(options.directory, "gateway.sqlite"), present = existsSync6(path37);
|
|
19792
|
+
preparePrivateDatabase(path37);
|
|
19793
|
+
this.db = new DatabaseSync10(path37);
|
|
19711
19794
|
this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000");
|
|
19712
19795
|
if (!present) this.db.exec([
|
|
19713
19796
|
"CREATE TABLE binding(identity TEXT NOT NULL,format TEXT NOT NULL);",
|
|
@@ -21392,13 +21475,13 @@ var DiscordAdapter = class _DiscordAdapter {
|
|
|
21392
21475
|
}
|
|
21393
21476
|
/** 发送媒体附件(图片/文件/音频)— discord.js channel.send({ files }) */
|
|
21394
21477
|
async sendFile(target, message, attachment) {
|
|
21395
|
-
const
|
|
21396
|
-
const
|
|
21397
|
-
if (!
|
|
21478
|
+
const fs27 = await import("node:fs");
|
|
21479
|
+
const path37 = await import("node:path");
|
|
21480
|
+
if (!fs27.existsSync(attachment.path)) {
|
|
21398
21481
|
throw new Error(`File not found: ${attachment.path}`);
|
|
21399
21482
|
}
|
|
21400
|
-
const filename = attachment.filename ||
|
|
21401
|
-
const fileBuffer =
|
|
21483
|
+
const filename = attachment.filename || path37.basename(attachment.path);
|
|
21484
|
+
const fileBuffer = fs27.readFileSync(attachment.path);
|
|
21402
21485
|
const filePayload = {
|
|
21403
21486
|
attachment: fileBuffer,
|
|
21404
21487
|
name: filename
|
|
@@ -22012,13 +22095,13 @@ var FeishuAdapter = class _FeishuAdapter {
|
|
|
22012
22095
|
}
|
|
22013
22096
|
/** 发送媒体附件(图片/文件) */
|
|
22014
22097
|
async sendFile(target, message, attachment) {
|
|
22015
|
-
const
|
|
22016
|
-
const
|
|
22017
|
-
if (!
|
|
22098
|
+
const fs27 = await import("node:fs");
|
|
22099
|
+
const path37 = await import("node:path");
|
|
22100
|
+
if (!fs27.existsSync(attachment.path)) {
|
|
22018
22101
|
throw new Error(`File not found: ${attachment.path}`);
|
|
22019
22102
|
}
|
|
22020
|
-
const filename = attachment.filename ||
|
|
22021
|
-
const fileBuffer =
|
|
22103
|
+
const filename = attachment.filename || path37.basename(attachment.path);
|
|
22104
|
+
const fileBuffer = fs27.readFileSync(attachment.path);
|
|
22022
22105
|
const safeTarget = target || this.config.defaultTarget || "";
|
|
22023
22106
|
if (!safeTarget) throw new Error("Feishu sendFile: no target (\u4E3B\u52A8\u53D1\u9001\u9700\u914D\u7F6E defaultTarget \u6216\u4F20\u5165 target)");
|
|
22024
22107
|
const receiveIdType = safeTarget.startsWith("ou_") ? "open_id" : "chat_id";
|
|
@@ -24148,22 +24231,22 @@ var DeskBuddyAdapter = class {
|
|
|
24148
24231
|
try {
|
|
24149
24232
|
if (!this.historyFile) {
|
|
24150
24233
|
const os7 = __require("os");
|
|
24151
|
-
const
|
|
24152
|
-
const
|
|
24153
|
-
const dir =
|
|
24154
|
-
|
|
24155
|
-
this.historyFile =
|
|
24156
|
-
this._fs =
|
|
24157
|
-
}
|
|
24158
|
-
const
|
|
24234
|
+
const fs28 = __require("fs");
|
|
24235
|
+
const path37 = __require("path");
|
|
24236
|
+
const dir = path37.join(os7.homedir(), "xiaowen", "workspace", ".desktopBuddy");
|
|
24237
|
+
fs28.mkdirSync(dir, { recursive: true });
|
|
24238
|
+
this.historyFile = path37.join(dir, "history.json");
|
|
24239
|
+
this._fs = fs28;
|
|
24240
|
+
}
|
|
24241
|
+
const fs27 = this._fs;
|
|
24159
24242
|
let arr = [];
|
|
24160
24243
|
try {
|
|
24161
|
-
arr = JSON.parse(
|
|
24244
|
+
arr = JSON.parse(fs27.readFileSync(this.historyFile, "utf-8")) || [];
|
|
24162
24245
|
} catch {
|
|
24163
24246
|
}
|
|
24164
24247
|
arr.push({ ...entry, ts: (/* @__PURE__ */ new Date()).toLocaleString("zh-CN", { hour12: false }) });
|
|
24165
24248
|
if (arr.length > 500) arr = arr.slice(-500);
|
|
24166
|
-
|
|
24249
|
+
fs27.writeFileSync(this.historyFile, JSON.stringify(arr, null, 1));
|
|
24167
24250
|
} catch (e) {
|
|
24168
24251
|
console.warn("[deskBuddy] history write fail", e);
|
|
24169
24252
|
}
|
|
@@ -25788,7 +25871,7 @@ var TelegramAdapter = class {
|
|
|
25788
25871
|
|
|
25789
25872
|
// src/channels/whatsapp/adapter.ts
|
|
25790
25873
|
import fsSync4 from "node:fs";
|
|
25791
|
-
import
|
|
25874
|
+
import path32 from "node:path";
|
|
25792
25875
|
import { spawn as spawn5 } from "node:child_process";
|
|
25793
25876
|
import { randomUUID as randomUUID17 } from "node:crypto";
|
|
25794
25877
|
|
|
@@ -26716,7 +26799,7 @@ function headerOf(groupJid) {
|
|
|
26716
26799
|
|
|
26717
26800
|
// src/channels/whatsapp/patrol.ts
|
|
26718
26801
|
import fsSync3 from "node:fs";
|
|
26719
|
-
import
|
|
26802
|
+
import path31 from "node:path";
|
|
26720
26803
|
import { randomBytes as randomBytes7 } from "node:crypto";
|
|
26721
26804
|
|
|
26722
26805
|
// src/models/model-capabilities.ts
|
|
@@ -27767,8 +27850,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
|
|
|
27767
27850
|
hookEvent,
|
|
27768
27851
|
durationMs: durationMs2
|
|
27769
27852
|
});
|
|
27853
|
+
const output = syncOutput.hookSpecificOutput;
|
|
27770
27854
|
return {
|
|
27771
27855
|
...processed,
|
|
27856
|
+
...hook.id === "skill-gate-prompt" && output?.hookEventName === "UserPromptSubmit" && output.selectSkill === true ? { selectSkill: true } : {},
|
|
27772
27857
|
outcome: processed.blockingError ? "blocking" : "success",
|
|
27773
27858
|
hook
|
|
27774
27859
|
};
|
|
@@ -27870,6 +27955,7 @@ function aggregateResults(results) {
|
|
|
27870
27955
|
if (result.permissionBehavior) {
|
|
27871
27956
|
aggregated.permissionBehavior = result.permissionBehavior;
|
|
27872
27957
|
}
|
|
27958
|
+
if (result.selectSkill) aggregated.selectSkill = true;
|
|
27873
27959
|
if (result.additionalContext) {
|
|
27874
27960
|
aggregated.additionalContexts.push(result.additionalContext);
|
|
27875
27961
|
}
|
|
@@ -30301,8 +30387,8 @@ var contextIdentity = (context) => canonicalJson({
|
|
|
30301
30387
|
function createNotificationStateReader() {
|
|
30302
30388
|
const databases = /* @__PURE__ */ new Map();
|
|
30303
30389
|
const checkers = /* @__PURE__ */ new Map();
|
|
30304
|
-
const open3 = (
|
|
30305
|
-
const key4 = resolve9(
|
|
30390
|
+
const open3 = (path37) => {
|
|
30391
|
+
const key4 = resolve9(path37);
|
|
30306
30392
|
let db2 = databases.get(key4);
|
|
30307
30393
|
if (!db2) {
|
|
30308
30394
|
db2 = new DatabaseSync11(key4, { readOnly: true });
|
|
@@ -30912,6 +30998,174 @@ function killTask(taskId) {
|
|
|
30912
30998
|
return true;
|
|
30913
30999
|
}
|
|
30914
31000
|
|
|
31001
|
+
// src/core/query-skill-selection.ts
|
|
31002
|
+
init_types();
|
|
31003
|
+
|
|
31004
|
+
// src/skills/recent-user-texts.ts
|
|
31005
|
+
init_strip_injected();
|
|
31006
|
+
|
|
31007
|
+
// src/core/query-skill-selection.ts
|
|
31008
|
+
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";
|
|
31009
|
+
var SKILL_SELECTION_MAX_TOKENS = 64;
|
|
31010
|
+
async function selectSkillCall(provider, params, allowedNames, recordUsage) {
|
|
31011
|
+
const timeout = AbortSignal.timeout(5e3);
|
|
31012
|
+
const signal = AbortSignal.any([params.signal, timeout]);
|
|
31013
|
+
const chunks = [];
|
|
31014
|
+
let calledSkill = false;
|
|
31015
|
+
let skillName = "";
|
|
31016
|
+
let requestComplete = false;
|
|
31017
|
+
let otherCut = false;
|
|
31018
|
+
try {
|
|
31019
|
+
for await (const chunk of provider.streamChat({
|
|
31020
|
+
...params,
|
|
31021
|
+
signal,
|
|
31022
|
+
httpRetry: { maxRetries: 0 }
|
|
31023
|
+
})) {
|
|
31024
|
+
signal.throwIfAborted();
|
|
31025
|
+
if (chunk.type === "error") return { outcome: "upstream-error" };
|
|
31026
|
+
if (chunk.type === "tool_call") {
|
|
31027
|
+
if (calledSkill || !chunk.tool_call?.id || chunk.tool_call.function?.name !== SKILL_TOOL_NAME) return { outcome: "invalid" };
|
|
31028
|
+
let args;
|
|
31029
|
+
try {
|
|
31030
|
+
args = JSON.parse(chunk.tool_call.function.arguments);
|
|
31031
|
+
} catch {
|
|
31032
|
+
return { outcome: "invalid" };
|
|
31033
|
+
}
|
|
31034
|
+
if (typeof args?.skill !== "string" || !allowedNames.has(args.skill.trim().replace(/^\//, ""))) return { outcome: "invalid" };
|
|
31035
|
+
calledSkill = true;
|
|
31036
|
+
skillName = args.skill.trim().replace(/^\//, "");
|
|
31037
|
+
chunks.push(chunk);
|
|
31038
|
+
}
|
|
31039
|
+
if (chunk.type === "done") {
|
|
31040
|
+
if (chunk.usage) recordUsage(chunk.usage);
|
|
31041
|
+
requestComplete ||= chunk.requestComplete === true;
|
|
31042
|
+
otherCut ||= ["incomplete", "content_filter"].includes(chunk.stopReason ?? "");
|
|
31043
|
+
}
|
|
31044
|
+
}
|
|
31045
|
+
} catch (error) {
|
|
31046
|
+
params.signal.throwIfAborted();
|
|
31047
|
+
if (error instanceof Error && /^TRAVEL_/.test(error.message)) throw error;
|
|
31048
|
+
return { outcome: timeout.aborted ? "timeout" : "upstream-error" };
|
|
31049
|
+
}
|
|
31050
|
+
params.signal.throwIfAborted();
|
|
31051
|
+
if (timeout.aborted) return { outcome: "timeout" };
|
|
31052
|
+
if (!requestComplete || otherCut) return { outcome: "incomplete" };
|
|
31053
|
+
return calledSkill ? { outcome: "selected", skill: skillName, chunks } : { outcome: "no-skill" };
|
|
31054
|
+
}
|
|
31055
|
+
|
|
31056
|
+
// src/skills/scanner.ts
|
|
31057
|
+
function parseFrontmatter(content) {
|
|
31058
|
+
const result = {};
|
|
31059
|
+
const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
|
|
31060
|
+
if (!match) return result;
|
|
31061
|
+
const lines = match[1].split("\n");
|
|
31062
|
+
let i = 0;
|
|
31063
|
+
while (i < lines.length) {
|
|
31064
|
+
const line = lines[i];
|
|
31065
|
+
const colonIdx = line.indexOf(":");
|
|
31066
|
+
if (colonIdx === -1) {
|
|
31067
|
+
i++;
|
|
31068
|
+
continue;
|
|
31069
|
+
}
|
|
31070
|
+
const key4 = line.slice(0, colonIdx).trim();
|
|
31071
|
+
let value = line.slice(colonIdx + 1).trim();
|
|
31072
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
31073
|
+
value = value.slice(1, -1);
|
|
31074
|
+
result[key4] = value;
|
|
31075
|
+
i++;
|
|
31076
|
+
continue;
|
|
31077
|
+
} else if (value === "|" || value === ">") {
|
|
31078
|
+
const blockLines = [];
|
|
31079
|
+
i++;
|
|
31080
|
+
while (i < lines.length && lines[i].startsWith(" ")) {
|
|
31081
|
+
blockLines.push(lines[i].slice(2));
|
|
31082
|
+
i++;
|
|
31083
|
+
}
|
|
31084
|
+
result[key4] = blockLines.join("\n").trim();
|
|
31085
|
+
continue;
|
|
31086
|
+
} else if (value.startsWith("[") && value.endsWith("]")) {
|
|
31087
|
+
result[key4] = value.slice(1, -1).split(",").map((s) => s.trim());
|
|
31088
|
+
i++;
|
|
31089
|
+
continue;
|
|
31090
|
+
} else if (value.includes(" ") && !value.startsWith('"')) {
|
|
31091
|
+
result[key4] = value;
|
|
31092
|
+
} else {
|
|
31093
|
+
result[key4] = value;
|
|
31094
|
+
}
|
|
31095
|
+
i++;
|
|
31096
|
+
}
|
|
31097
|
+
return result;
|
|
31098
|
+
}
|
|
31099
|
+
|
|
31100
|
+
// src/tools/SkillTool/SkillTool.ts
|
|
31101
|
+
init_tokenEstimate();
|
|
31102
|
+
import { createHash as createHash34 } from "node:crypto";
|
|
31103
|
+
import * as fs22 from "node:fs";
|
|
31104
|
+
import * as path29 from "node:path";
|
|
31105
|
+
var skillsDirPath = "";
|
|
31106
|
+
var selectionCatalog = { entries: [], allowedNames: /* @__PURE__ */ new Set() };
|
|
31107
|
+
function getSkillSelectionCatalog() {
|
|
31108
|
+
return selectionCatalog;
|
|
31109
|
+
}
|
|
31110
|
+
var resolveSkillFn;
|
|
31111
|
+
function loadSkillContent(skillsDir, skill) {
|
|
31112
|
+
const skillMdPath = skill.location ? path29.join(skillsDir, skill.location.slice("skills/".length)) : path29.join(skillsDir, skill.name, "SKILL.md");
|
|
31113
|
+
if (!fs22.existsSync(skillMdPath)) return null;
|
|
31114
|
+
const content = fs22.readFileSync(skillMdPath, "utf-8");
|
|
31115
|
+
const dependencies = parseFrontmatter(content)["requires-tools"];
|
|
31116
|
+
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))];
|
|
31117
|
+
const bodyMatch = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)/);
|
|
31118
|
+
const body = bodyMatch ? bodyMatch[1] : content;
|
|
31119
|
+
const skillDir = path29.dirname(skillMdPath);
|
|
31120
|
+
const normalizedDir = process.platform === "win32" ? skillDir.replace(/\\/g, "/") : skillDir;
|
|
31121
|
+
let finalContent = `Base directory for this skill: ${normalizedDir}
|
|
31122
|
+
|
|
31123
|
+
${body}`;
|
|
31124
|
+
finalContent = finalContent.replace(/\$\{CLAUDE_SKILL_DIR\}/g, normalizedDir);
|
|
31125
|
+
finalContent = finalContent.replace(/\$\{CLAUDE_SESSION_ID\}/g, getSessionId());
|
|
31126
|
+
return { content: finalContent, requiredTools };
|
|
31127
|
+
}
|
|
31128
|
+
function getSessionId() {
|
|
31129
|
+
return String(process.pid);
|
|
31130
|
+
}
|
|
31131
|
+
var SKILL_FINGERPRINT_PREFIX = "[fingerprint ";
|
|
31132
|
+
var SKILL_RELOAD_DISTANCE_TOKENS = 16e3;
|
|
31133
|
+
function skillFingerprint(skill, body) {
|
|
31134
|
+
return createHash34("sha256").update(skill.location ?? skill.name).update("\0").update(body).digest("hex").slice(0, 16);
|
|
31135
|
+
}
|
|
31136
|
+
function findLoadedSkill(history, skill, fingerprint, resolve12) {
|
|
31137
|
+
if (!history) return void 0;
|
|
31138
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
31139
|
+
const message = history[i];
|
|
31140
|
+
if (!("role" in message) || message.role !== "tool" || message.is_error || typeof message.content !== "string") continue;
|
|
31141
|
+
let call;
|
|
31142
|
+
for (let j = i - 1; j >= 0 && !call; j--) {
|
|
31143
|
+
const previous = history[j];
|
|
31144
|
+
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);
|
|
31145
|
+
}
|
|
31146
|
+
if (!call) continue;
|
|
31147
|
+
let args = {};
|
|
31148
|
+
try {
|
|
31149
|
+
args = JSON.parse(call.function.arguments);
|
|
31150
|
+
} catch {
|
|
31151
|
+
continue;
|
|
31152
|
+
}
|
|
31153
|
+
if (typeof args?.skill !== "string" || resolve12(args.skill.trim().replace(/^\//, "")) !== skill) continue;
|
|
31154
|
+
if (!message.content.includes(SKILL_FINGERPRINT_PREFIX + fingerprint + "]")) return void 0;
|
|
31155
|
+
return estimateMessageTokens(history.slice(i + 1)) <= SKILL_RELOAD_DISTANCE_TOKENS ? call.id : void 0;
|
|
31156
|
+
}
|
|
31157
|
+
return void 0;
|
|
31158
|
+
}
|
|
31159
|
+
function findLoadedSkillCall(history, skillName) {
|
|
31160
|
+
const resolve12 = resolveSkillFn;
|
|
31161
|
+
if (!history || !resolve12) return void 0;
|
|
31162
|
+
const skill = resolve12(skillName.trim().replace(/^\//, ""));
|
|
31163
|
+
if (!skill) return void 0;
|
|
31164
|
+
const content = loadSkillContent(skillsDirPath, skill);
|
|
31165
|
+
if (!content) return void 0;
|
|
31166
|
+
return findLoadedSkill(history, skill, skillFingerprint(skill, content.content), resolve12);
|
|
31167
|
+
}
|
|
31168
|
+
|
|
30915
31169
|
// src/core/query.ts
|
|
30916
31170
|
function blockedToolCallsForOverride(calls, override2) {
|
|
30917
31171
|
if (!override2) return [];
|
|
@@ -31309,6 +31563,7 @@ var QueryEngine = class _QueryEngine {
|
|
|
31309
31563
|
turnCount++;
|
|
31310
31564
|
const steers = this.pendingSteers.splice(0);
|
|
31311
31565
|
let steerConsumedThisTurn = false;
|
|
31566
|
+
let userSteerConsumedThisTurn = false;
|
|
31312
31567
|
if (steers.length > 0) {
|
|
31313
31568
|
for (const input of steers) {
|
|
31314
31569
|
if (this.steerHistoryIds.has(input.id)) {
|
|
@@ -31340,6 +31595,7 @@ var QueryEngine = class _QueryEngine {
|
|
|
31340
31595
|
if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
|
|
31341
31596
|
this.steerHistoryIds.add(input.id);
|
|
31342
31597
|
steerConsumedThisTurn = true;
|
|
31598
|
+
userSteerConsumedThisTurn = true;
|
|
31343
31599
|
yield {
|
|
31344
31600
|
type: "user_input",
|
|
31345
31601
|
message: steerMsg,
|
|
@@ -31595,7 +31851,53 @@ var QueryEngine = class _QueryEngine {
|
|
|
31595
31851
|
let turnAborted = false;
|
|
31596
31852
|
try {
|
|
31597
31853
|
wholeQueryAbort.signal.throwIfAborted();
|
|
31598
|
-
const
|
|
31854
|
+
const beforeRequest = () => {
|
|
31855
|
+
wholeQueryAbort.signal.throwIfAborted();
|
|
31856
|
+
ac.signal.throwIfAborted();
|
|
31857
|
+
};
|
|
31858
|
+
const startRequest = () => {
|
|
31859
|
+
this.phase = "streaming";
|
|
31860
|
+
assertRuntimeAuthority(void 0, "INPUT");
|
|
31861
|
+
if (perTurnOptions?.onRequestStarted) {
|
|
31862
|
+
const start = perTurnOptions.onRequestStarted;
|
|
31863
|
+
setImmediate(() => {
|
|
31864
|
+
if (!wholeQueryAbort.signal.aborted) start();
|
|
31865
|
+
});
|
|
31866
|
+
}
|
|
31867
|
+
};
|
|
31868
|
+
let selected;
|
|
31869
|
+
const selectionInput = perTurnOptions?.skillSelectionInput;
|
|
31870
|
+
const skill = turnCount === 1 && maxTurns >= 2 && !userSteerConsumedThisTurn && !hasPendingUserInput() && selectionInput ? allToolDefs.find((tool) => tool.function.name === SKILL_TOOL_NAME) : void 0;
|
|
31871
|
+
const catalog = skill ? getSkillSelectionCatalog() : void 0;
|
|
31872
|
+
if (skill && selectionInput && catalog?.entries.length) {
|
|
31873
|
+
const input = normalizeMessagesForAPI([selectionInput]);
|
|
31874
|
+
const started = performance.now();
|
|
31875
|
+
startRequest();
|
|
31876
|
+
const selection = await selectSkillCall(queryProvider, {
|
|
31877
|
+
preferFastFallback,
|
|
31878
|
+
model: queryModel,
|
|
31879
|
+
messages: input,
|
|
31880
|
+
tools: [skill],
|
|
31881
|
+
systemStable: SKILL_SELECTION_PROMPT + "\n\n" + JSON.stringify(catalog.entries),
|
|
31882
|
+
maxTokens: SKILL_SELECTION_MAX_TOKENS,
|
|
31883
|
+
signal: ac.signal,
|
|
31884
|
+
beforeRequest: () => {
|
|
31885
|
+
assertHostTurnCurrent();
|
|
31886
|
+
beforeRequest();
|
|
31887
|
+
},
|
|
31888
|
+
disableThinking: true
|
|
31889
|
+
}, catalog.allowedNames, recordUsage);
|
|
31890
|
+
assertHostTurnCurrent();
|
|
31891
|
+
beforeRequest();
|
|
31892
|
+
console.log(`${this.logPrefix} [skill-selection] ${selection.outcome} ms=${Math.round(performance.now() - started)}`);
|
|
31893
|
+
if (hasPendingUserInput()) continue;
|
|
31894
|
+
if (selection.outcome === "selected") {
|
|
31895
|
+
if (findLoadedSkillCall(currentMessages, selection.skill)) {
|
|
31896
|
+
console.log(`${this.logPrefix} [skill-selection] already-loaded ${selection.skill}`);
|
|
31897
|
+
} else selected = selection.chunks;
|
|
31898
|
+
}
|
|
31899
|
+
}
|
|
31900
|
+
const view = (selected ? [] : normalizeMessagesForAPI(currentMessages)).map((m) => {
|
|
31599
31901
|
if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
|
|
31600
31902
|
const blocks = m.content.filter((b) => {
|
|
31601
31903
|
if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
|
|
@@ -31630,7 +31932,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
|
|
|
31630
31932
|
const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
|
|
31631
31933
|
|
|
31632
31934
|
${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
|
|
31633
|
-
if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
|
|
31935
|
+
if (!selected && (!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
|
|
31634
31936
|
try {
|
|
31635
31937
|
const ws = process.env.ENGINE7_WORKSPACE;
|
|
31636
31938
|
if (ws) {
|
|
@@ -31646,15 +31948,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
|
|
|
31646
31948
|
} catch {
|
|
31647
31949
|
}
|
|
31648
31950
|
}
|
|
31649
|
-
|
|
31650
|
-
|
|
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({
|
|
31951
|
+
if (!selected) startRequest();
|
|
31952
|
+
for await (const chunk of selected ?? queryProvider.streamChat({
|
|
31658
31953
|
preferFastFallback,
|
|
31659
31954
|
model: queryModel,
|
|
31660
31955
|
messages: apiMessages,
|
|
@@ -31667,10 +31962,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
|
|
|
31667
31962
|
maxTokens: this.resolveRequestMaxTokens(apiMessages, maxTokensOverride),
|
|
31668
31963
|
temperature: this.options.temperature,
|
|
31669
31964
|
signal: ac.signal,
|
|
31670
|
-
beforeRequest
|
|
31671
|
-
wholeQueryAbort.signal.throwIfAborted();
|
|
31672
|
-
ac.signal.throwIfAborted();
|
|
31673
|
-
},
|
|
31965
|
+
beforeRequest,
|
|
31674
31966
|
disableThinking: this.options.disableThinking || !!perTurnEmotion
|
|
31675
31967
|
// 情感模式关 thinking(对齐 deskBuddy)
|
|
31676
31968
|
})) {
|
|
@@ -32031,6 +32323,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
|
|
|
32031
32323
|
if (vcDelivery) await vcDelivery;
|
|
32032
32324
|
}
|
|
32033
32325
|
const { messages: toolResults, summaries } = toolRes;
|
|
32326
|
+
if (selected) console.log(`${this.logPrefix} [skill-selection] ${summaries.length === 1 && !summaries[0].isError ? "loaded" : "load-failed"}`);
|
|
32034
32327
|
if (collectStopEvidence) stopToolResults.push(...summaries);
|
|
32035
32328
|
for (const s of summaries) {
|
|
32036
32329
|
try {
|
|
@@ -32328,9 +32621,9 @@ function readState(stateFile) {
|
|
|
32328
32621
|
return { lastPatrolAt: 0, lastLineCounts: {} };
|
|
32329
32622
|
}
|
|
32330
32623
|
function writeState(stateFile, state) {
|
|
32331
|
-
const dir =
|
|
32624
|
+
const dir = path31.dirname(stateFile);
|
|
32332
32625
|
fsSync3.mkdirSync(dir, { recursive: true });
|
|
32333
|
-
const tmp =
|
|
32626
|
+
const tmp = path31.join(dir, `.${path31.basename(stateFile)}.tmp-${process.pid}-${randomBytes7(4).toString("hex")}`);
|
|
32334
32627
|
try {
|
|
32335
32628
|
fsSync3.writeFileSync(tmp, JSON.stringify(state), "utf-8");
|
|
32336
32629
|
fsSync3.renameSync(tmp, stateFile);
|
|
@@ -32359,7 +32652,7 @@ function buildPatrolPrompt(materials) {
|
|
|
32359
32652
|
].join("\n");
|
|
32360
32653
|
}
|
|
32361
32654
|
function defaultWriteMemoryNote(workspace) {
|
|
32362
|
-
const dir =
|
|
32655
|
+
const dir = path31.join(getAutoMemPath(workspace), "whatsapp-patrol");
|
|
32363
32656
|
return (note) => {
|
|
32364
32657
|
fsSync3.mkdirSync(dir, { recursive: true });
|
|
32365
32658
|
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
@@ -32373,7 +32666,7 @@ function defaultWriteMemoryNote(workspace) {
|
|
|
32373
32666
|
note,
|
|
32374
32667
|
""
|
|
32375
32668
|
].join("\n");
|
|
32376
|
-
fsSync3.writeFileSync(
|
|
32669
|
+
fsSync3.writeFileSync(path31.join(dir, `patrol-${stamp}.md`), body, "utf-8");
|
|
32377
32670
|
};
|
|
32378
32671
|
}
|
|
32379
32672
|
function makeSubmitToMain(engineDeps) {
|
|
@@ -32518,15 +32811,15 @@ ${quoted}`);
|
|
|
32518
32811
|
|
|
32519
32812
|
// src/utils/ffmpeg-path.ts
|
|
32520
32813
|
init_dep_downloader();
|
|
32521
|
-
import * as
|
|
32814
|
+
import * as fs24 from "node:fs";
|
|
32522
32815
|
function resolveFfmpegPath() {
|
|
32523
32816
|
const env = (process.env.E7_FFMPEG_PATH || "").trim();
|
|
32524
|
-
if (env &&
|
|
32817
|
+
if (env && fs24.existsSync(env)) return env;
|
|
32525
32818
|
const downloaded = optionalFfmpegPath();
|
|
32526
32819
|
if (downloaded) return downloaded;
|
|
32527
32820
|
try {
|
|
32528
32821
|
const p = __require("@ffmpeg-installer/ffmpeg")?.path;
|
|
32529
|
-
if (p &&
|
|
32822
|
+
if (p && fs24.existsSync(p)) return p;
|
|
32530
32823
|
} catch {
|
|
32531
32824
|
}
|
|
32532
32825
|
return "ffmpeg";
|
|
@@ -32612,10 +32905,10 @@ function normalizeAllowEntry(entry) {
|
|
|
32612
32905
|
}
|
|
32613
32906
|
function atomicWriteFile(dir, fileName, content) {
|
|
32614
32907
|
fsSync4.mkdirSync(dir, { recursive: true });
|
|
32615
|
-
const tmp =
|
|
32908
|
+
const tmp = path32.join(dir, `.${fileName}.tmp-${process.pid}-${randomUUID17().slice(0, 8)}`);
|
|
32616
32909
|
try {
|
|
32617
32910
|
fsSync4.writeFileSync(tmp, content, "utf-8");
|
|
32618
|
-
fsSync4.renameSync(tmp,
|
|
32911
|
+
fsSync4.renameSync(tmp, path32.join(dir, fileName));
|
|
32619
32912
|
} catch (e) {
|
|
32620
32913
|
try {
|
|
32621
32914
|
fsSync4.rmSync(tmp, { force: true });
|
|
@@ -32730,13 +33023,13 @@ var WhatsAppAdapter = class {
|
|
|
32730
33023
|
constructor(cfg, opts = {}) {
|
|
32731
33024
|
this.cfg = cfg;
|
|
32732
33025
|
this.stateDir = cfg.stateDir;
|
|
32733
|
-
this.authDir =
|
|
32734
|
-
this.qrFilePath =
|
|
33026
|
+
this.authDir = path32.join(cfg.stateDir, "whatsapp-auth");
|
|
33027
|
+
this.qrFilePath = path32.join(cfg.stateDir, "whatsapp-qr.txt");
|
|
32735
33028
|
this.opts = opts;
|
|
32736
33029
|
this.credsStore = opts.credsStoreOverride ?? makeCredsStore(this.authDir);
|
|
32737
33030
|
this.loginTtlMs = opts.loginTtlMs ?? LOGIN_TTL_MS;
|
|
32738
33031
|
this.digestEnabled = cfg.groupDigest?.enabled !== false;
|
|
32739
|
-
this.digest = this.digestEnabled ? new GroupDigestStore(
|
|
33032
|
+
this.digest = this.digestEnabled ? new GroupDigestStore(path32.join(cfg.stateDir, "whatsapp-digest"), cfg.groupDigest?.maxLinesPerGroup ?? 500) : null;
|
|
32740
33033
|
this.typing = new PresenceTypingCoalescer(async (jid) => {
|
|
32741
33034
|
const sock = this.sock;
|
|
32742
33035
|
if (!sock || typeof sock.sendPresenceUpdate !== "function") return;
|
|
@@ -32871,7 +33164,7 @@ var WhatsAppAdapter = class {
|
|
|
32871
33164
|
this.patrol = startPatrolLoop({
|
|
32872
33165
|
digest: this.digest,
|
|
32873
33166
|
intervalMin: this.cfg.groupDigest?.patrolIntervalMin ?? 60,
|
|
32874
|
-
stateFile:
|
|
33167
|
+
stateFile: path32.join(this.stateDir, "whatsapp-patrol-state.json"),
|
|
32875
33168
|
runReadOnlyAgent: makeReadOnlyAgentRunner(this.opts.patrolDeps),
|
|
32876
33169
|
// ⚠️ 升级接线(终审 C1,1003):摘要含 ⚠️ 行时宿主经主 session 投递(spec §4)——
|
|
32877
33170
|
// makeSubmitToMain 吃的正是 patrolDeps {dispatcher, deps}(patrol.ts)形状。漏接这行 =
|
|
@@ -33168,11 +33461,11 @@ ${r}` : r;
|
|
|
33168
33461
|
const idRaw = typeof raw?.key?.id === "string" && raw.key.id ? raw.key.id : "";
|
|
33169
33462
|
const idSafe = idRaw.replace(/[^\w.-]/g, "_");
|
|
33170
33463
|
const id3 = !idRaw || idSafe !== idRaw || !idSafe ? randomUUID17() : idSafe;
|
|
33171
|
-
const dir =
|
|
33464
|
+
const dir = path32.join(this.stateDir, "media", "whatsapp");
|
|
33172
33465
|
fsSync4.mkdirSync(dir, { recursive: true });
|
|
33173
|
-
const abs =
|
|
33174
|
-
const resolved =
|
|
33175
|
-
if (!resolved.startsWith(
|
|
33466
|
+
const abs = path32.join(dir, `${id3}.${ext}`);
|
|
33467
|
+
const resolved = path32.resolve(abs);
|
|
33468
|
+
if (!resolved.startsWith(path32.resolve(dir) + path32.sep)) {
|
|
33176
33469
|
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
33470
|
return `${placeholder}\uFF08\u4E0B\u8F7D\u5931\u8D25\uFF09`;
|
|
33178
33471
|
}
|
|
@@ -33206,7 +33499,7 @@ ${r}` : r;
|
|
|
33206
33499
|
const lids = [jid, participant].filter((j) => j.endsWith("@lid"));
|
|
33207
33500
|
if (lids.length === 0) return;
|
|
33208
33501
|
try {
|
|
33209
|
-
const filePath2 =
|
|
33502
|
+
const filePath2 = path32.join(this.authDir, "lid-mapping.json");
|
|
33210
33503
|
let arr = [];
|
|
33211
33504
|
try {
|
|
33212
33505
|
const parsed = JSON.parse(fsSync4.readFileSync(filePath2, "utf-8"));
|
|
@@ -33316,7 +33609,7 @@ ${r}` : r;
|
|
|
33316
33609
|
if (isGroupJid(jid)) throw new Error(`WhatsApp \u7FA4\u53D1\u9001\u7269\u7406\u4E0D\u5B58\u5728\uFF08\u7EA2\u7EBF\uFF09\uFF1Atarget=${jid}`);
|
|
33317
33610
|
const sock = this.requireSock();
|
|
33318
33611
|
const mime = attachment.mimeType ?? "";
|
|
33319
|
-
const filename = attachment.filename ??
|
|
33612
|
+
const filename = attachment.filename ?? path32.basename(attachment.path);
|
|
33320
33613
|
if (mime.startsWith("image/")) {
|
|
33321
33614
|
assertExternalEffectCurrent();
|
|
33322
33615
|
const res2 = await sock.sendMessage(jid, { image: { url: attachment.path }, caption: message });
|
|
@@ -33345,8 +33638,8 @@ ${r}` : r;
|
|
|
33345
33638
|
this.recordEcho(res2);
|
|
33346
33639
|
return;
|
|
33347
33640
|
}
|
|
33348
|
-
const tmpDir =
|
|
33349
|
-
const dst =
|
|
33641
|
+
const tmpDir = path32.join(this.stateDir, "whatsapp-media-tmp");
|
|
33642
|
+
const dst = path32.join(tmpDir, `${randomUUID17()}.ogg`);
|
|
33350
33643
|
try {
|
|
33351
33644
|
await (this.cfg.ffmpegTranscode ?? defaultFfmpegTranscode)(attachment.path, dst);
|
|
33352
33645
|
assertExternalEffectCurrent();
|
|
@@ -33461,9 +33754,9 @@ function quotedTextOf(content) {
|
|
|
33461
33754
|
}
|
|
33462
33755
|
|
|
33463
33756
|
// src/channels/dingtalk.ts
|
|
33464
|
-
import
|
|
33465
|
-
import
|
|
33466
|
-
import { createHash as
|
|
33757
|
+
import fs25 from "node:fs";
|
|
33758
|
+
import path33 from "node:path";
|
|
33759
|
+
import { createHash as createHash35, randomUUID as randomUUID18 } from "node:crypto";
|
|
33467
33760
|
|
|
33468
33761
|
// src/channels/dingtalk-stream.ts
|
|
33469
33762
|
import { EventEmitter } from "node:events";
|
|
@@ -34055,13 +34348,13 @@ var DingTalkAdapter = class _DingTalkAdapter {
|
|
|
34055
34348
|
const res = await this.baseFetch(url, { signal: AbortSignal.timeout(3e4) });
|
|
34056
34349
|
if (!res.ok) throw new Error(`media download HTTP ${res.status}`);
|
|
34057
34350
|
const buf = Buffer.from(await res.arrayBuffer());
|
|
34058
|
-
const dir =
|
|
34059
|
-
|
|
34351
|
+
const dir = path33.join(this.cfg.stateDir, "media", "dingtalk");
|
|
34352
|
+
fs25.mkdirSync(dir, { recursive: true });
|
|
34060
34353
|
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) + "-" +
|
|
34354
|
+
const raw = m.code.length <= 40 ? m.code : m.code.slice(0, 16) + "-" + createHash35("sha1").update(m.code).digest("hex").slice(0, 12);
|
|
34062
34355
|
const safeCode = raw.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
34063
|
-
const local =
|
|
34064
|
-
|
|
34356
|
+
const local = path33.join(dir, `${safeCode}.${ext}`);
|
|
34357
|
+
fs25.writeFileSync(local, buf);
|
|
34065
34358
|
out.push({
|
|
34066
34359
|
url: `file://${local}`,
|
|
34067
34360
|
filename: m.filename ?? `${safeCode}.${ext}`,
|
|
@@ -34134,8 +34427,8 @@ var DingTalkAdapter = class _DingTalkAdapter {
|
|
|
34134
34427
|
async sendFileNow(target, message, attachment) {
|
|
34135
34428
|
const entry = this.registry.get(target);
|
|
34136
34429
|
const robotCode = this.cfg.robotCode ?? this.cfg.clientId;
|
|
34137
|
-
const buf =
|
|
34138
|
-
const filename = (attachment.filename ??
|
|
34430
|
+
const buf = fs25.readFileSync(attachment.path);
|
|
34431
|
+
const filename = (attachment.filename ?? path33.basename(attachment.path)).slice(0, 100);
|
|
34139
34432
|
const isImage = (attachment.mimeType ?? "").startsWith("image/") || /\.(png|jpe?g|gif|webp|bmp)$/i.test(filename);
|
|
34140
34433
|
const mediaId = await this.uploadMedia(buf, filename, isImage ? "image" : "file");
|
|
34141
34434
|
const msgKey = isImage ? "sampleImageMsg" : "sampleFileMsg";
|
|
@@ -34500,7 +34793,7 @@ var DING_EDIT_INTERVAL_MS = 300;
|
|
|
34500
34793
|
// src/channels/wecom-stream.ts
|
|
34501
34794
|
import { EventEmitter as EventEmitter2 } from "node:events";
|
|
34502
34795
|
import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
|
|
34503
|
-
import { createHash as
|
|
34796
|
+
import { createHash as createHash36 } from "node:crypto";
|
|
34504
34797
|
var WECOM_WS_URL = "wss://openws.work.weixin.qq.com";
|
|
34505
34798
|
var HEARTBEAT_MS2 = 3e4;
|
|
34506
34799
|
var ACK_TIMEOUT_MS = 15e3;
|
|
@@ -34852,7 +35145,7 @@ var WecomStreamClient = class extends EventEmitter2 {
|
|
|
34852
35145
|
if (!data.length) throw new Error("wecom uploadMedia: empty buffer");
|
|
34853
35146
|
const totalChunks = Math.ceil(data.length / UPLOAD_CHUNK_BYTES);
|
|
34854
35147
|
if (totalChunks > MAX_UPLOAD_CHUNKS) throw new Error(`wecom uploadMedia: too large (${totalChunks} chunks > ${MAX_UPLOAD_CHUNKS})`);
|
|
34855
|
-
const md5 =
|
|
35148
|
+
const md5 = createHash36("md5").update(data).digest("hex");
|
|
34856
35149
|
const initRes = await this.sendCommand("aibot_upload_media_init", {
|
|
34857
35150
|
type,
|
|
34858
35151
|
filename,
|
|
@@ -34879,9 +35172,9 @@ var WecomStreamClient = class extends EventEmitter2 {
|
|
|
34879
35172
|
|
|
34880
35173
|
// src/channels/wecom.ts
|
|
34881
35174
|
import { createDecipheriv as createDecipheriv3, randomUUID as randomUUID19 } from "node:crypto";
|
|
34882
|
-
import { readFileSync as
|
|
35175
|
+
import { readFileSync as readFileSync18 } from "node:fs";
|
|
34883
35176
|
import { mkdir as mkdir4, readFile, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
|
|
34884
|
-
import
|
|
35177
|
+
import path34 from "node:path";
|
|
34885
35178
|
var WECOM_CONTENT_BYTES = 20480;
|
|
34886
35179
|
var DEFAULT_MERGE_WINDOW_MS = 600;
|
|
34887
35180
|
var REPLY_WINDOW_MS = 24 * 60 * 60 * 1e3;
|
|
@@ -35067,7 +35360,7 @@ var WecomAdapter = class {
|
|
|
35067
35360
|
this.now = cfg.now ?? Date.now;
|
|
35068
35361
|
this.sleepImpl = cfg.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
35069
35362
|
this.fetchImpl = cfg.fetchImpl ?? fetch;
|
|
35070
|
-
this.routesFile =
|
|
35363
|
+
this.routesFile = path34.join(cfg.stateDir, "state", ROUTES_FILE);
|
|
35071
35364
|
}
|
|
35072
35365
|
/**
|
|
35073
35366
|
* 载入落盘会话路由(1007:真机事故——注册表原本只存内存,引擎一重启"谁跟我说过话"全丢,
|
|
@@ -35083,7 +35376,7 @@ var WecomAdapter = class {
|
|
|
35083
35376
|
this.routesLoaded = true;
|
|
35084
35377
|
let raw;
|
|
35085
35378
|
try {
|
|
35086
|
-
raw = JSON.parse(
|
|
35379
|
+
raw = JSON.parse(readFileSync18(this.routesFile, "utf8"));
|
|
35087
35380
|
} catch (e) {
|
|
35088
35381
|
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
35382
|
return;
|
|
@@ -35111,7 +35404,7 @@ var WecomAdapter = class {
|
|
|
35111
35404
|
try {
|
|
35112
35405
|
const routes = {};
|
|
35113
35406
|
for (const [chatId, e] of this.registry) routes[chatId] = { chatType: e.chatType, userId: e.userId };
|
|
35114
|
-
await mkdir4(
|
|
35407
|
+
await mkdir4(path34.dirname(this.routesFile), { recursive: true });
|
|
35115
35408
|
await writeFile4(this.routesFile, JSON.stringify({ version: 1, routes }, null, 2) + "\n", "utf8");
|
|
35116
35409
|
} catch (e) {
|
|
35117
35410
|
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 +35690,7 @@ ${parsed.inbound.content}`;
|
|
|
35397
35690
|
/** 入站媒体:下载 → aeskey 解密 → 落盘 → 附件(单条失败不拖垮整条消息;全部失败给 content 加标记)。
|
|
35398
35691
|
* 本地文件名一律由 msgid 派生(远端 filename 只做显示名)——防同名互相覆盖/超长(钉钉 1004 同款纪律)。 */
|
|
35399
35692
|
async resolveInboundMedia(parsed) {
|
|
35400
|
-
const dir =
|
|
35693
|
+
const dir = path34.join(this.cfg.stateDir, "media", "wecom");
|
|
35401
35694
|
const attachments = [];
|
|
35402
35695
|
let failed = 0;
|
|
35403
35696
|
for (const [i, ref] of parsed.media.entries()) {
|
|
@@ -35409,7 +35702,7 @@ ${parsed.inbound.content}`;
|
|
|
35409
35702
|
const data = ref.aeskey ? decryptWecomMedia(raw, ref.aeskey) : raw;
|
|
35410
35703
|
const ext = ref.filename?.includes(".") ? ref.filename.split(".").pop().toLowerCase().slice(0, 8) : ref.kind === "image" ? "jpg" : ref.kind === "video" ? "mp4" : "bin";
|
|
35411
35704
|
const localName = `wecom-${(parsed.msgId || String(this.now())).replace(/[^0-9A-Za-z_-]/g, "").slice(0, 32)}-${i}.${ext}`;
|
|
35412
|
-
const file2 =
|
|
35705
|
+
const file2 = path34.join(dir, localName);
|
|
35413
35706
|
await writeFile4(file2, data);
|
|
35414
35707
|
const displayName = (ref.filename || localName).slice(0, 120);
|
|
35415
35708
|
attachments.push({
|
|
@@ -35440,7 +35733,7 @@ ${parsed.inbound.content}`;
|
|
|
35440
35733
|
const entry = this.registry.get(target);
|
|
35441
35734
|
if (!entry) throw new Error(`[wecom] \u65E0\u6CD5\u8DEF\u7531\u5A92\u4F53\u5230 ${target}\uFF08\u65E0\u4F1A\u8BDD\u6CE8\u518C\u8BB0\u5F55\uFF09`);
|
|
35442
35735
|
await this.takeToken(target, false);
|
|
35443
|
-
const filename = attachment.filename ??
|
|
35736
|
+
const filename = attachment.filename ?? path34.basename(attachment.path);
|
|
35444
35737
|
const { mediaId } = await this.requireStream().uploadMedia(data, type, filename);
|
|
35445
35738
|
const body = type === "video" ? { msgtype: "video", video: { media_id: mediaId, title: filename } } : { msgtype: type, [type]: { media_id: mediaId } };
|
|
35446
35739
|
await this.respondOrSend(entry, target, body);
|
|
@@ -35704,7 +35997,7 @@ import { randomUUID as randomUUID20 } from "node:crypto";
|
|
|
35704
35997
|
// src/continuity/gateway-channel.ts
|
|
35705
35998
|
init_gateway_media();
|
|
35706
35999
|
import { mkdtempSync, writeFileSync as writeFileSync14, rmSync as rmSync2, realpathSync as realpathSync5 } from "node:fs";
|
|
35707
|
-
import { join as
|
|
36000
|
+
import { join as join31 } from "node:path";
|
|
35708
36001
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
35709
36002
|
function splitChannelGatewayText(text2, channel) {
|
|
35710
36003
|
if (typeof text2 !== "string" || Buffer.byteLength(text2) > 1024 * 1024) throw new Error("TRAVEL_GATEWAY_REPLY_LIMIT");
|
|
@@ -35759,7 +36052,7 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
|
|
|
35759
36052
|
if (!media) await adapter.send(packet.target, packet.text, { replyTo: packet.replyTo });
|
|
35760
36053
|
else {
|
|
35761
36054
|
if (!adapter.sendFile) throw new Error("TRAVEL_GATEWAY_MEDIA_UNAVAILABLE");
|
|
35762
|
-
const directory2 = realpathSync5(mkdtempSync(
|
|
36055
|
+
const directory2 = realpathSync5(mkdtempSync(join31(tmpdir3(), "e7-gateway-media-"))), file2 = join31(directory2, packet.filename);
|
|
35763
36056
|
try {
|
|
35764
36057
|
writeFileSync14(file2, media.bytes, { mode: 384 });
|
|
35765
36058
|
await adapter.sendFile(packet.target, packet.text, { path: file2, filename: packet.filename, mimeType: packet.mimeType, voiceDurationSec: packet.voiceDurationSec });
|
|
@@ -36185,9 +36478,9 @@ var RemoteTravelChannel = class {
|
|
|
36185
36478
|
};
|
|
36186
36479
|
|
|
36187
36480
|
// src/channels/private-library.ts
|
|
36188
|
-
import
|
|
36189
|
-
import
|
|
36190
|
-
import { createHash as
|
|
36481
|
+
import fs26 from "node:fs/promises";
|
|
36482
|
+
import path35 from "node:path";
|
|
36483
|
+
import { createHash as createHash37 } from "node:crypto";
|
|
36191
36484
|
|
|
36192
36485
|
// src/channels/chan7-content.ts
|
|
36193
36486
|
function fileMime(name) {
|
|
@@ -36199,8 +36492,8 @@ function fileMime(name) {
|
|
|
36199
36492
|
function archive(manager, name, mime, bytes2, role, caption, identity) {
|
|
36200
36493
|
const adapter = manager.getAdapter("chan7");
|
|
36201
36494
|
if (!adapter?.files || bytes2.length > 16 * 1024 * 1024) return;
|
|
36202
|
-
const safeName =
|
|
36203
|
-
const key4 =
|
|
36495
|
+
const safeName = path35.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
|
|
36496
|
+
const key4 = createHash37("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
|
|
36204
36497
|
try {
|
|
36205
36498
|
adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key4);
|
|
36206
36499
|
} catch (e) {
|
|
@@ -36210,9 +36503,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
|
|
|
36210
36503
|
async function archivePrivateOutbound(manager, channel, target, text2, attachment, origin) {
|
|
36211
36504
|
if (channel === "chan7" || origin?.channelType !== "dm" || origin.inboundIsBot || origin.channel !== channel || origin.channelTarget !== target || !manager.getAdapter("chan7")?.files) return;
|
|
36212
36505
|
try {
|
|
36213
|
-
const stat3 = await
|
|
36506
|
+
const stat3 = await fs26.stat(attachment.path);
|
|
36214
36507
|
if (!stat3.isFile() || stat3.size > 16 * 1024 * 1024) return;
|
|
36215
|
-
const bytes2 = await
|
|
36508
|
+
const bytes2 = await fs26.readFile(attachment.path), name = attachment.filename ?? path35.basename(attachment.path);
|
|
36216
36509
|
archive(
|
|
36217
36510
|
manager,
|
|
36218
36511
|
name,
|
|
@@ -36227,6 +36520,63 @@ async function archivePrivateOutbound(manager, channel, target, text2, attachmen
|
|
|
36227
36520
|
}
|
|
36228
36521
|
}
|
|
36229
36522
|
|
|
36523
|
+
// src/channels/loop-guard.ts
|
|
36524
|
+
var MAX_COMPARE_LEN = 60;
|
|
36525
|
+
var MAX_REPEAT = 3;
|
|
36526
|
+
var SIMILARITY_THRESHOLD = 0.8;
|
|
36527
|
+
var HISTORY_SIZE = 5;
|
|
36528
|
+
var LoopBlockedError = class extends Error {
|
|
36529
|
+
constructor(target, repeated) {
|
|
36530
|
+
super(`loop-guard blocked: \u5411 ${target} \u8FDE\u7EED ${repeated} \u6761\u540C\u8D28\u6D88\u606F`);
|
|
36531
|
+
this.target = target;
|
|
36532
|
+
this.repeated = repeated;
|
|
36533
|
+
this.name = "LoopBlockedError";
|
|
36534
|
+
}
|
|
36535
|
+
};
|
|
36536
|
+
var states = /* @__PURE__ */ new Map();
|
|
36537
|
+
function normalize6(text2) {
|
|
36538
|
+
return text2.replace(/[\s\u3000]/g, "").replace(/[。,、!?;:""''()()\[\]【】…~~\-—.,!?;:'"]/g, "").toLowerCase();
|
|
36539
|
+
}
|
|
36540
|
+
function similarity(a, b) {
|
|
36541
|
+
if (!a && !b) return 1;
|
|
36542
|
+
if (!a || !b) return 0;
|
|
36543
|
+
const setA = new Set(a);
|
|
36544
|
+
const setB = new Set(b);
|
|
36545
|
+
let inter = 0;
|
|
36546
|
+
for (const ch of setA) if (setB.has(ch)) inter++;
|
|
36547
|
+
const union = setA.size + setB.size - inter;
|
|
36548
|
+
return union === 0 ? 1 : inter / union;
|
|
36549
|
+
}
|
|
36550
|
+
function isSameKind(a, b) {
|
|
36551
|
+
if (a === b) return true;
|
|
36552
|
+
return similarity(a, b) >= SIMILARITY_THRESHOLD;
|
|
36553
|
+
}
|
|
36554
|
+
function checkOutbound(channelName, target, message) {
|
|
36555
|
+
const text2 = message.trim();
|
|
36556
|
+
if (!text2 || text2.length > MAX_COMPARE_LEN) {
|
|
36557
|
+
if (text2) states.delete(`${channelName}:${target}`);
|
|
36558
|
+
return true;
|
|
36559
|
+
}
|
|
36560
|
+
const key4 = `${channelName}:${target}`;
|
|
36561
|
+
const norm = normalize6(text2);
|
|
36562
|
+
const state = states.get(key4) ?? { recent: [] };
|
|
36563
|
+
let repeated = 1;
|
|
36564
|
+
for (let i = state.recent.length - 1; i >= 0; i--) {
|
|
36565
|
+
if (isSameKind(state.recent[i], norm)) repeated++;
|
|
36566
|
+
else break;
|
|
36567
|
+
}
|
|
36568
|
+
if (repeated >= MAX_REPEAT) {
|
|
36569
|
+
console.warn(
|
|
36570
|
+
`[loop-guard] BLOCKED channel=${channelName} target=${target} repeated=${repeated} text=${text2.slice(0, 40)}`
|
|
36571
|
+
);
|
|
36572
|
+
return false;
|
|
36573
|
+
}
|
|
36574
|
+
state.recent.push(norm);
|
|
36575
|
+
if (state.recent.length > HISTORY_SIZE) state.recent.shift();
|
|
36576
|
+
states.set(key4, state);
|
|
36577
|
+
return true;
|
|
36578
|
+
}
|
|
36579
|
+
|
|
36230
36580
|
// src/channels/manager.ts
|
|
36231
36581
|
var MANAGED_CHANNEL_NAMES = ["discord", "feishu", "wechat", "deskBuddy", "ccBridge", "telegram", "whatsapp", "dingtalk", "wecom"];
|
|
36232
36582
|
var defaultFactories = {
|
|
@@ -36605,6 +36955,9 @@ var ChannelManager = class {
|
|
|
36605
36955
|
if (!adapter) {
|
|
36606
36956
|
throw new Error(`No adapter for ${channelName}`);
|
|
36607
36957
|
}
|
|
36958
|
+
if (!checkOutbound(channelName, target, message)) {
|
|
36959
|
+
throw new LoopBlockedError(target, 3);
|
|
36960
|
+
}
|
|
36608
36961
|
try {
|
|
36609
36962
|
if (hasMemoryEffectContext() && (!adapter.memoryGuardedSends || hasAutomaticMemoryEffectContext() && adapter.memoryGuardedAutomation === false)) throw new Error(`MEMORY_EXECUTION_BLOCKED: adapter ${channelName} has no final send guard`);
|
|
36610
36963
|
await guardedExternalEffect(() => adapter.send(target, message, options));
|
|
@@ -36702,12 +37055,12 @@ var quiet2 = { error: () => {
|
|
|
36702
37055
|
}, debug: () => {
|
|
36703
37056
|
}, trace: () => {
|
|
36704
37057
|
} };
|
|
36705
|
-
function
|
|
37058
|
+
function path36(value) {
|
|
36706
37059
|
if (typeof value !== "string" || !isAbsolute5(value)) throw new Error("TRAVEL_GATEWAY_ABSOLUTE_PATH_REQUIRED");
|
|
36707
37060
|
return resolve11(value);
|
|
36708
37061
|
}
|
|
36709
37062
|
function tls2(config) {
|
|
36710
|
-
return { ca: readPrivateFile(
|
|
37063
|
+
return { ca: readPrivateFile(path36(config?.caFile), 1024 * 1024), cert: readPrivateFile(path36(config?.certFile), 1024 * 1024), key: readPrivateFile(path36(config?.keyFile), 16384) };
|
|
36711
37064
|
}
|
|
36712
37065
|
async function startTravelGateway(config) {
|
|
36713
37066
|
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 +37070,7 @@ async function startTravelGateway(config) {
|
|
|
36717
37070
|
if (feishuIngress && !/^cli_[0-9a-fA-F]{16}$/.test(config.feishu?.appId)) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
|
|
36718
37071
|
const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls2(config.keyService.tls), timeoutMs: 1e4 };
|
|
36719
37072
|
const material = await fetchTravelKey(keyConfig);
|
|
36720
|
-
const keyDigest =
|
|
37073
|
+
const keyDigest = createHash38("sha256").update(material.key).digest("hex");
|
|
36721
37074
|
let keyWatermark = material.deletionWatermark;
|
|
36722
37075
|
const refreshInterval = config.keyRefreshIntervalMs ?? 1e4, maxKeyAge = config.keyMaxAgeMs ?? 3e4;
|
|
36723
37076
|
if (!Number.isSafeInteger(refreshInterval) || refreshInterval < 100 || refreshInterval > 1e4 || !Number.isSafeInteger(maxKeyAge) || maxKeyAge < 2 * refreshInterval || maxKeyAge > 3e4) {
|
|
@@ -36758,14 +37111,14 @@ async function startTravelGateway(config) {
|
|
|
36758
37111
|
}
|
|
36759
37112
|
};
|
|
36760
37113
|
try {
|
|
36761
|
-
objects = await PublicationObjects.open({ directory:
|
|
36762
|
-
authority = new TravelAuthority({ directory:
|
|
37114
|
+
objects = await PublicationObjects.open({ directory: path36(config.objectsDir), identity: config.identity, key: material.key });
|
|
37115
|
+
authority = new TravelAuthority({ directory: path36(config.authorityDir), leaseMs: config.leaseMs });
|
|
36763
37116
|
if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
|
|
36764
37117
|
for (const credential of Object.values(config.allowedPeers)) {
|
|
36765
37118
|
const principal = authority.authenticate(String(credential));
|
|
36766
37119
|
if (["tenantId", "companionId", "seatId"].some((key4) => principal[key4] !== config.identity[key4]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
|
|
36767
37120
|
}
|
|
36768
|
-
store = new TravelGatewayStore({ directory:
|
|
37121
|
+
store = new TravelGatewayStore({ directory: path36(config.gatewayDir), identity: config.identity, objects, authority });
|
|
36769
37122
|
await store.migrateStoredInputs();
|
|
36770
37123
|
if (config.previouslyProcessedPlatformIds) store.importProcessedInputs(config.previouslyProcessedPlatformIds);
|
|
36771
37124
|
platform = createFeishuGatewayPlatform(config.feishu);
|
|
@@ -36819,7 +37172,7 @@ async function startTravelGateway(config) {
|
|
|
36819
37172
|
}
|
|
36820
37173
|
});
|
|
36821
37174
|
if (config.channels && config.ingressEnabled !== false) {
|
|
36822
|
-
adapters.setFactoryContext({ stateDir:
|
|
37175
|
+
adapters.setFactoryContext({ stateDir: path36(config.platformStateDir) });
|
|
36823
37176
|
adapters.loadFromConfig(Object.fromEntries(Object.entries(config.channels).filter(([name, value]) => name !== "feishu" && value.enabled)));
|
|
36824
37177
|
for (const channel of ["discord", "wechat"]) {
|
|
36825
37178
|
const adapter = adapters.getAdapter(channel);
|
|
@@ -36882,7 +37235,7 @@ async function startTravelGateway(config) {
|
|
|
36882
37235
|
checking = true;
|
|
36883
37236
|
void fetchTravelKey(keyConfig).then((current2) => {
|
|
36884
37237
|
try {
|
|
36885
|
-
if (!objects ||
|
|
37238
|
+
if (!objects || createHash38("sha256").update(current2.key).digest("hex") !== keyDigest) throw new Error("TRAVEL_GATEWAY_KEY_CHANGED");
|
|
36886
37239
|
keyWatermark = current2.deletionWatermark;
|
|
36887
37240
|
lastKeyCheck = Number(process.hrtime.bigint() / 1000000n);
|
|
36888
37241
|
} finally {
|
|
@@ -36905,7 +37258,7 @@ async function startTravelGateway(config) {
|
|
|
36905
37258
|
async function runTravelGatewayCli(args) {
|
|
36906
37259
|
if (!args.length || args.length === 1 && args[0] === "--help") return { usage: "travel-gateway serve --config /absolute/private-config.json" };
|
|
36907
37260
|
if (args.length !== 3 || args[0] !== "serve" || args[1] !== "--config") throw new Error("TRAVEL_GATEWAY_INVALID_COMMAND");
|
|
36908
|
-
const config = JSON.parse(readPrivateFile(
|
|
37261
|
+
const config = JSON.parse(readPrivateFile(path36(args[2]), 65536).toString());
|
|
36909
37262
|
const gateway = await startTravelGateway(config);
|
|
36910
37263
|
let closing = false;
|
|
36911
37264
|
const stop = () => {
|