omnius 1.0.166 → 1.0.168
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/index.js +1240 -189
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -97800,7 +97800,7 @@ var require_auto = __commonJS({
|
|
|
97800
97800
|
// ../node_modules/acme-client/src/client.js
|
|
97801
97801
|
var require_client = __commonJS({
|
|
97802
97802
|
"../node_modules/acme-client/src/client.js"(exports, module) {
|
|
97803
|
-
var { createHash:
|
|
97803
|
+
var { createHash: createHash36 } = __require("crypto");
|
|
97804
97804
|
var { getPemBodyAsB64u } = require_crypto();
|
|
97805
97805
|
var { log: log22 } = require_logger();
|
|
97806
97806
|
var HttpClient = require_http();
|
|
@@ -98111,14 +98111,14 @@ var require_client = __commonJS({
|
|
|
98111
98111
|
*/
|
|
98112
98112
|
async getChallengeKeyAuthorization(challenge) {
|
|
98113
98113
|
const jwk = this.http.getJwk();
|
|
98114
|
-
const keysum =
|
|
98114
|
+
const keysum = createHash36("sha256").update(JSON.stringify(jwk));
|
|
98115
98115
|
const thumbprint = keysum.digest("base64url");
|
|
98116
98116
|
const result = `${challenge.token}.${thumbprint}`;
|
|
98117
98117
|
if (challenge.type === "http-01") {
|
|
98118
98118
|
return result;
|
|
98119
98119
|
}
|
|
98120
98120
|
if (challenge.type === "dns-01") {
|
|
98121
|
-
return
|
|
98121
|
+
return createHash36("sha256").update(result).digest("base64url");
|
|
98122
98122
|
}
|
|
98123
98123
|
if (challenge.type === "tls-alpn-01") {
|
|
98124
98124
|
return result;
|
|
@@ -240798,7 +240798,7 @@ var require_websocket2 = __commonJS({
|
|
|
240798
240798
|
var http6 = __require("http");
|
|
240799
240799
|
var net5 = __require("net");
|
|
240800
240800
|
var tls2 = __require("tls");
|
|
240801
|
-
var { randomBytes: randomBytes29, createHash:
|
|
240801
|
+
var { randomBytes: randomBytes29, createHash: createHash36 } = __require("crypto");
|
|
240802
240802
|
var { Duplex: Duplex3, Readable } = __require("stream");
|
|
240803
240803
|
var { URL: URL3 } = __require("url");
|
|
240804
240804
|
var PerMessageDeflate3 = require_permessage_deflate2();
|
|
@@ -241458,7 +241458,7 @@ var require_websocket2 = __commonJS({
|
|
|
241458
241458
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
241459
241459
|
return;
|
|
241460
241460
|
}
|
|
241461
|
-
const digest3 =
|
|
241461
|
+
const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
|
|
241462
241462
|
if (res.headers["sec-websocket-accept"] !== digest3) {
|
|
241463
241463
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
241464
241464
|
return;
|
|
@@ -241825,7 +241825,7 @@ var require_websocket_server = __commonJS({
|
|
|
241825
241825
|
var EventEmitter15 = __require("events");
|
|
241826
241826
|
var http6 = __require("http");
|
|
241827
241827
|
var { Duplex: Duplex3 } = __require("stream");
|
|
241828
|
-
var { createHash:
|
|
241828
|
+
var { createHash: createHash36 } = __require("crypto");
|
|
241829
241829
|
var extension3 = require_extension2();
|
|
241830
241830
|
var PerMessageDeflate3 = require_permessage_deflate2();
|
|
241831
241831
|
var subprotocol3 = require_subprotocol();
|
|
@@ -242126,7 +242126,7 @@ var require_websocket_server = __commonJS({
|
|
|
242126
242126
|
);
|
|
242127
242127
|
}
|
|
242128
242128
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
242129
|
-
const digest3 =
|
|
242129
|
+
const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
|
|
242130
242130
|
const headers = [
|
|
242131
242131
|
"HTTP/1.1 101 Switching Protocols",
|
|
242132
242132
|
"Upgrade: websocket",
|
|
@@ -254933,13 +254933,13 @@ Justification: ${justification || "(none provided)"}`,
|
|
|
254933
254933
|
}
|
|
254934
254934
|
const snapshot = JSON.stringify(this.selfState, null, 2);
|
|
254935
254935
|
try {
|
|
254936
|
-
const { createHash:
|
|
254936
|
+
const { createHash: createHash36 } = await import("node:crypto");
|
|
254937
254937
|
const snapshotDir = join33(this.cwd, ".omnius", "identity", "snapshots");
|
|
254938
254938
|
await mkdir7(snapshotDir, { recursive: true });
|
|
254939
254939
|
const version4 = this.selfState.version;
|
|
254940
254940
|
const snapshotPath = join33(snapshotDir, `v${version4}.json`);
|
|
254941
254941
|
await writeFile12(snapshotPath, snapshot, "utf8");
|
|
254942
|
-
const hash =
|
|
254942
|
+
const hash = createHash36("sha256").update(snapshot).digest("hex");
|
|
254943
254943
|
await writeFile12(join33(this.cwd, ".omnius", "identity", "latest-hash.txt"), hash, "utf8");
|
|
254944
254944
|
let ipfsCid = "";
|
|
254945
254945
|
try {
|
|
@@ -255072,8 +255072,8 @@ New: ${newNarrative.slice(0, 200)}...`,
|
|
|
255072
255072
|
}
|
|
255073
255073
|
// ── Helpers ──────────────────────────────────────────────────────────────
|
|
255074
255074
|
createDefaultState() {
|
|
255075
|
-
const { createHash:
|
|
255076
|
-
const machineId =
|
|
255075
|
+
const { createHash: createHash36 } = __require("node:crypto");
|
|
255076
|
+
const machineId = createHash36("sha256").update(this.cwd).digest("hex").slice(0, 12);
|
|
255077
255077
|
return {
|
|
255078
255078
|
self_id: `omnius-${machineId}`,
|
|
255079
255079
|
version: 1,
|
|
@@ -255155,9 +255155,9 @@ New: ${newNarrative.slice(0, 200)}...`,
|
|
|
255155
255155
|
let cid;
|
|
255156
255156
|
if (this.selfState.version > prevVersion) {
|
|
255157
255157
|
try {
|
|
255158
|
-
const { createHash:
|
|
255158
|
+
const { createHash: createHash36 } = await import("node:crypto");
|
|
255159
255159
|
const stateJson = JSON.stringify(this.selfState);
|
|
255160
|
-
const hash =
|
|
255160
|
+
const hash = createHash36("sha256").update(stateJson).digest("hex").slice(0, 32);
|
|
255161
255161
|
const cidsPath = join33(this.cwd, ".omnius", "identity", "cids.json");
|
|
255162
255162
|
const cidsData = { latest: "", hash, version: this.selfState.version };
|
|
255163
255163
|
try {
|
|
@@ -534419,7 +534419,7 @@ var init_world_state_disk_scan = __esm({
|
|
|
534419
534419
|
import { existsSync as existsSync70, statSync as statSync29 } from "node:fs";
|
|
534420
534420
|
import { isAbsolute as isAbsolute4, join as join83 } from "node:path";
|
|
534421
534421
|
function tokenize3(content) {
|
|
534422
|
-
const
|
|
534422
|
+
const STOP2 = /* @__PURE__ */ new Set([
|
|
534423
534423
|
"the",
|
|
534424
534424
|
"and",
|
|
534425
534425
|
"or",
|
|
@@ -534450,7 +534450,7 @@ function tokenize3(content) {
|
|
|
534450
534450
|
"into",
|
|
534451
534451
|
"from"
|
|
534452
534452
|
]);
|
|
534453
|
-
return Array.from(new Set(content.toLowerCase().split(/[^a-z0-9]+/g).filter((s2) => s2.length >= 3 && !
|
|
534453
|
+
return Array.from(new Set(content.toLowerCase().split(/[^a-z0-9]+/g).filter((s2) => s2.length >= 3 && !STOP2.has(s2))));
|
|
534454
534454
|
}
|
|
534455
534455
|
function heuristicMatch(rel, tokens) {
|
|
534456
534456
|
if (tokens.length === 0)
|
|
@@ -543572,6 +543572,527 @@ var init_embeddingDrift = __esm({
|
|
|
543572
543572
|
}
|
|
543573
543573
|
});
|
|
543574
543574
|
|
|
543575
|
+
// packages/memory/dist/semanticContext.js
|
|
543576
|
+
import { createHash as createHash20 } from "node:crypto";
|
|
543577
|
+
function estimateTokens(text) {
|
|
543578
|
+
return Math.max(0, Math.ceil((text || "").length / 4));
|
|
543579
|
+
}
|
|
543580
|
+
function estimateContextTokens(content, supplied) {
|
|
543581
|
+
return Number.isFinite(supplied) ? Math.max(0, Math.ceil(supplied)) : estimateTokens(content);
|
|
543582
|
+
}
|
|
543583
|
+
function stableId(parts) {
|
|
543584
|
+
return createHash20("sha256").update(parts.join("\n")).digest("hex").slice(0, 16);
|
|
543585
|
+
}
|
|
543586
|
+
function clamp016(x) {
|
|
543587
|
+
if (!Number.isFinite(x))
|
|
543588
|
+
return 0;
|
|
543589
|
+
if (x < 0)
|
|
543590
|
+
return 0;
|
|
543591
|
+
if (x > 1)
|
|
543592
|
+
return 1;
|
|
543593
|
+
return x;
|
|
543594
|
+
}
|
|
543595
|
+
function tokenCount(item) {
|
|
543596
|
+
const supplied = Number.isFinite(item.tokenCount) ? item.tokenCount : item.tokenEstimate;
|
|
543597
|
+
return estimateContextTokens(item.content, supplied);
|
|
543598
|
+
}
|
|
543599
|
+
function itemId(item) {
|
|
543600
|
+
return item.id ?? `ctx_${stableId([item.source, item.kind, item.content.slice(0, 240)])}`;
|
|
543601
|
+
}
|
|
543602
|
+
function isConsolidated(item) {
|
|
543603
|
+
if (item.consolidated !== void 0)
|
|
543604
|
+
return item.consolidated;
|
|
543605
|
+
const metadataConsolidated = item.metadata?.["consolidated"] ?? item.metadata?.["isConsolidated"];
|
|
543606
|
+
if (typeof metadataConsolidated === "boolean")
|
|
543607
|
+
return metadataConsolidated;
|
|
543608
|
+
const haystack = `${item.kind} ${item.source} ${String(item.metadata?.["stage"] ?? "")}`.toLowerCase();
|
|
543609
|
+
return /\b(gist|summary|semantic|memory|reflection|self_model|social_state|compressed|context_frame|anchor)\b/.test(haystack);
|
|
543610
|
+
}
|
|
543611
|
+
function addBucket(buckets, key, tokens, consolidated) {
|
|
543612
|
+
const k = key || "unknown";
|
|
543613
|
+
const bucket = buckets[k] ?? { items: 0, itemCount: 0, tokens: 0, totalTokens: 0, rawTokens: 0, consolidatedTokens: 0 };
|
|
543614
|
+
bucket.items += 1;
|
|
543615
|
+
bucket.itemCount += 1;
|
|
543616
|
+
bucket.tokens += tokens;
|
|
543617
|
+
bucket.totalTokens += tokens;
|
|
543618
|
+
if (consolidated)
|
|
543619
|
+
bucket.consolidatedTokens += tokens;
|
|
543620
|
+
else
|
|
543621
|
+
bucket.rawTokens += tokens;
|
|
543622
|
+
buckets[k] = bucket;
|
|
543623
|
+
}
|
|
543624
|
+
function buildContextPressureSnapshot(input, opts = {}) {
|
|
543625
|
+
const items = Array.isArray(input) ? input : Array.isArray(input.items) ? input.items : [];
|
|
543626
|
+
const semanticChunkCount = Array.isArray(input) ? opts.semanticChunkCount : opts.semanticChunkCount ?? input.semanticChunkCount;
|
|
543627
|
+
const targetRawTokenBudget = Math.max(0, Math.floor(opts.targetRawTokenBudget ?? (Array.isArray(input) ? void 0 : input.targetRawTokenBudget ?? input.targetTokens) ?? 2e3));
|
|
543628
|
+
const now = opts.now ?? (Array.isArray(input) ? void 0 : input.now);
|
|
543629
|
+
const perSource = {};
|
|
543630
|
+
const perKind = {};
|
|
543631
|
+
let rawTokens = 0;
|
|
543632
|
+
let consolidatedTokens = 0;
|
|
543633
|
+
for (const item of items) {
|
|
543634
|
+
const tokens = tokenCount(item);
|
|
543635
|
+
const consolidated = isConsolidated(item);
|
|
543636
|
+
if (consolidated)
|
|
543637
|
+
consolidatedTokens += tokens;
|
|
543638
|
+
else
|
|
543639
|
+
rawTokens += tokens;
|
|
543640
|
+
addBucket(perSource, item.source, tokens, consolidated);
|
|
543641
|
+
addBucket(perKind, item.kind, tokens, consolidated);
|
|
543642
|
+
}
|
|
543643
|
+
const totalTokens = rawTokens + consolidatedTokens;
|
|
543644
|
+
const compressionTargetTokens = Math.ceil(rawTokens * 0.6);
|
|
543645
|
+
return {
|
|
543646
|
+
generatedAt: now ?? Date.now(),
|
|
543647
|
+
itemCount: items.length,
|
|
543648
|
+
semanticChunkCount: semanticChunkCount ?? new SemanticChunker().chunk(items, { now }).length,
|
|
543649
|
+
totalTokens,
|
|
543650
|
+
rawTokens,
|
|
543651
|
+
consolidatedTokens,
|
|
543652
|
+
rawRatio: totalTokens > 0 ? rawTokens / totalTokens : 0,
|
|
543653
|
+
consolidatedRatio: totalTokens > 0 ? consolidatedTokens / totalTokens : 0,
|
|
543654
|
+
compressionTargetTokens,
|
|
543655
|
+
targetRawTokenBudget,
|
|
543656
|
+
rawTokensToTarget: Math.max(0, rawTokens - targetRawTokenBudget),
|
|
543657
|
+
perSource,
|
|
543658
|
+
perKind
|
|
543659
|
+
};
|
|
543660
|
+
}
|
|
543661
|
+
function extractSemanticEntities(text) {
|
|
543662
|
+
const out = /* @__PURE__ */ new Set();
|
|
543663
|
+
const add2 = (raw) => {
|
|
543664
|
+
const value2 = raw.trim().replace(/[.,;:!?)]$/, "");
|
|
543665
|
+
if (value2.length < 2)
|
|
543666
|
+
return;
|
|
543667
|
+
if (STOP.has(value2.toLowerCase()))
|
|
543668
|
+
return;
|
|
543669
|
+
out.add(value2);
|
|
543670
|
+
};
|
|
543671
|
+
for (const m2 of text.matchAll(/(?:[\w.-]+\/)+[\w./-]+\.[A-Za-z0-9]+|[\w.-]+\.(?:ts|tsx|js|jsx|json|md|py|rs|go|c|cpp|h|css|html)\b/g))
|
|
543672
|
+
add2(m2[0]);
|
|
543673
|
+
for (const m2 of text.matchAll(/@[A-Za-z0-9_]{2,}/g))
|
|
543674
|
+
add2(m2[0].toLowerCase());
|
|
543675
|
+
for (const m2 of text.matchAll(/\b[A-Za-z_][A-Za-z0-9_]*(?:Error|Exception|Failure|Failed)\b/g))
|
|
543676
|
+
add2(m2[0]);
|
|
543677
|
+
for (const m2 of text.matchAll(/\b[a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]+)+\b/g))
|
|
543678
|
+
add2(m2[0]);
|
|
543679
|
+
for (const m2 of text.matchAll(/\b[A-Z][A-Za-z0-9]*(?:[A-Z][A-Za-z0-9]*)?\b/g))
|
|
543680
|
+
add2(m2[0]);
|
|
543681
|
+
for (const m2 of text.matchAll(/\b(?:memory|context|telegram|router|tool|shell|diagnostic|consolidation|forgetting|chunk|reply|notes|voice|trust|semantic)\b/gi))
|
|
543682
|
+
add2(m2[0].toLowerCase());
|
|
543683
|
+
return [...out].slice(0, 24);
|
|
543684
|
+
}
|
|
543685
|
+
function semanticLabelFor(item) {
|
|
543686
|
+
const explicit = item.semanticLabels?.[0] || (Array.isArray(item.metadata?.["semanticLabels"]) ? String(item.metadata["semanticLabels"][0] ?? "") : "");
|
|
543687
|
+
if (explicit.trim())
|
|
543688
|
+
return explicit.trim().toLowerCase();
|
|
543689
|
+
const h = `${item.kind} ${item.source} ${item.content}`.toLowerCase();
|
|
543690
|
+
if (/telegram|@\w|reply|chat|relationship|social/.test(h))
|
|
543691
|
+
return "telegram conversation and relationship state";
|
|
543692
|
+
if (/error|failed|failure|diagnostic|stderr|exit code|exception/.test(h))
|
|
543693
|
+
return "diagnostic errors and recovery";
|
|
543694
|
+
if (/todo|task|goal|plan|current step|completed/.test(h))
|
|
543695
|
+
return "active task and plan";
|
|
543696
|
+
if (/memory|gist|reflection|lesson|prior experience/.test(h))
|
|
543697
|
+
return "retrieved memory and lessons";
|
|
543698
|
+
if (/tool|shell|command|output|stdout|stderr/.test(h))
|
|
543699
|
+
return "tool results and execution evidence";
|
|
543700
|
+
if (/identity|persona|voice|policy|instruction|system prompt/.test(h))
|
|
543701
|
+
return "identity and behavioral constraints";
|
|
543702
|
+
if (/(?:[\w.-]+\/)+[\w./-]+|\.ts\b|\.tsx\b|\.js\b|function|class|export/.test(h))
|
|
543703
|
+
return "codebase files and symbols";
|
|
543704
|
+
return "general working context";
|
|
543705
|
+
}
|
|
543706
|
+
function itemUtility(item, now) {
|
|
543707
|
+
const priority = (item.priority ?? 0) / 100;
|
|
543708
|
+
const importance = (item.importance ?? 5) / 10;
|
|
543709
|
+
const strength = Math.min(1, Math.log2(Math.max(1, item.strength ?? 1)) / 4);
|
|
543710
|
+
const reuse = Math.min(1, (item.reuseCount ?? 0) / 8);
|
|
543711
|
+
const age = item.timestamp ? Math.max(0, now - item.timestamp) : 0;
|
|
543712
|
+
const recency = item.timestamp ? Math.exp(-age / (24 * 60 * 6e4)) : 0.5;
|
|
543713
|
+
return clamp016(0.25 + priority * 0.25 + importance * 0.25 + strength * 0.12 + reuse * 0.08 + recency * 0.05);
|
|
543714
|
+
}
|
|
543715
|
+
function stalenessFor(items, now) {
|
|
543716
|
+
const timestamps = items.map((i2) => i2.timestamp).filter((v) => Number.isFinite(v));
|
|
543717
|
+
if (timestamps.length === 0)
|
|
543718
|
+
return 0.5;
|
|
543719
|
+
const newest = Math.max(...timestamps);
|
|
543720
|
+
return clamp016(1 - Math.exp(-Math.max(0, now - newest) / (6 * 60 * 6e4)));
|
|
543721
|
+
}
|
|
543722
|
+
function summarize(items, maxChars = 420) {
|
|
543723
|
+
const ranked = [...items].sort((a2, b) => (b.priority ?? 0) - (a2.priority ?? 0) || tokenCount(b) - tokenCount(a2));
|
|
543724
|
+
const parts = [];
|
|
543725
|
+
for (const item of ranked.slice(0, 4)) {
|
|
543726
|
+
const text = item.content.replace(/\s+/g, " ").trim();
|
|
543727
|
+
if (!text)
|
|
543728
|
+
continue;
|
|
543729
|
+
parts.push(text.length > 140 ? text.slice(0, 139).trimEnd() + "..." : text);
|
|
543730
|
+
if (parts.join(" ").length >= maxChars)
|
|
543731
|
+
break;
|
|
543732
|
+
}
|
|
543733
|
+
const summary = parts.join(" ");
|
|
543734
|
+
return summary.length > maxChars ? summary.slice(0, maxChars - 3).trimEnd() + "..." : summary;
|
|
543735
|
+
}
|
|
543736
|
+
function openQuestionsFor(items) {
|
|
543737
|
+
const out = [];
|
|
543738
|
+
for (const item of items) {
|
|
543739
|
+
for (const line of item.content.split(/\n+/)) {
|
|
543740
|
+
const trimmed = line.trim();
|
|
543741
|
+
if (!trimmed)
|
|
543742
|
+
continue;
|
|
543743
|
+
if (/[?]$|\b(unresolved|blocked|unknown|gap|needs?|todo|fixme)\b/i.test(trimmed)) {
|
|
543744
|
+
out.push(trimmed.replace(/\s+/g, " ").slice(0, 180));
|
|
543745
|
+
}
|
|
543746
|
+
if (out.length >= 6)
|
|
543747
|
+
return [...new Set(out)];
|
|
543748
|
+
}
|
|
543749
|
+
}
|
|
543750
|
+
return [...new Set(out)];
|
|
543751
|
+
}
|
|
543752
|
+
function entityOverlap(a2, b) {
|
|
543753
|
+
const as = new Set(a2.map((v) => v.toLowerCase()));
|
|
543754
|
+
const bs = new Set(b.map((v) => v.toLowerCase()));
|
|
543755
|
+
if (as.size === 0 || bs.size === 0)
|
|
543756
|
+
return 0;
|
|
543757
|
+
let inter = 0;
|
|
543758
|
+
for (const x of as)
|
|
543759
|
+
if (bs.has(x))
|
|
543760
|
+
inter++;
|
|
543761
|
+
return inter / Math.min(as.size, bs.size);
|
|
543762
|
+
}
|
|
543763
|
+
function groupUtility(items, now) {
|
|
543764
|
+
if (items.length === 0)
|
|
543765
|
+
return 0;
|
|
543766
|
+
const raw = items.reduce((sum, item) => sum + itemUtility(item, now), 0) / items.length;
|
|
543767
|
+
const evidenceBoost = Math.min(0.2, Math.log1p(items.length) / 15);
|
|
543768
|
+
return clamp016(raw + evidenceBoost);
|
|
543769
|
+
}
|
|
543770
|
+
function chunkItemLike(chunk) {
|
|
543771
|
+
const newest = Math.max(0, ...chunk.items.map((i2) => i2.timestamp ?? 0));
|
|
543772
|
+
return {
|
|
543773
|
+
id: chunk.id,
|
|
543774
|
+
source: chunk.sourceKinds.join(","),
|
|
543775
|
+
kind: chunk.kinds.join(","),
|
|
543776
|
+
content: chunk.summary,
|
|
543777
|
+
tokenCount: chunk.tokenEstimate,
|
|
543778
|
+
priority: Math.round(chunk.utilityScore * 100),
|
|
543779
|
+
timestamp: newest || void 0,
|
|
543780
|
+
importance: chunk.items.reduce((s2, i2) => s2 + (i2.importance ?? 5), 0) / Math.max(1, chunk.items.length),
|
|
543781
|
+
strength: chunk.items.reduce((s2, i2) => s2 + (i2.strength ?? 1), 0) / Math.max(1, chunk.items.length),
|
|
543782
|
+
reuseCount: chunk.items.reduce((s2, i2) => s2 + (i2.reuseCount ?? 0), 0),
|
|
543783
|
+
entities: chunk.entities
|
|
543784
|
+
};
|
|
543785
|
+
}
|
|
543786
|
+
function buildActiveForgettingReport(input, opts = {}) {
|
|
543787
|
+
const entries = Array.isArray(input) ? input : Array.isArray(input.chunks) ? input.chunks : Array.isArray(input.items) ? input.items : [];
|
|
543788
|
+
const now = opts.now ?? (Array.isArray(input) ? void 0 : input.now) ?? Date.now();
|
|
543789
|
+
const items = entries.map((entry) => "summary" in entry ? chunkItemLike(entry) : entry);
|
|
543790
|
+
const selectiveForgetCandidates = [];
|
|
543791
|
+
const rehearseCandidates = [];
|
|
543792
|
+
const presentButUnused = [];
|
|
543793
|
+
const interferencePairs = [];
|
|
543794
|
+
for (const item of items) {
|
|
543795
|
+
const utility = itemUtility(item, now);
|
|
543796
|
+
const label = semanticLabelFor(item);
|
|
543797
|
+
const unused = (item.reuseCount ?? 0) === 0 && (item.strength ?? 1) <= 1.2;
|
|
543798
|
+
const ageMs = item.lastRetrieved ? Math.max(0, now - item.lastRetrieved) : item.timestamp ? Math.max(0, now - item.timestamp) : Infinity;
|
|
543799
|
+
if (utility < 0.42 && (item.importance ?? 5) <= 5) {
|
|
543800
|
+
selectiveForgetCandidates.push({ id: itemId(item), label, score: 1 - utility, reason: "low utility, low importance, or stale context" });
|
|
543801
|
+
}
|
|
543802
|
+
if ((item.importance ?? 5) >= 7 && ((item.reuseCount ?? 0) > 0 || (item.strength ?? 1) > 1) && ageMs > 30 * 6e4) {
|
|
543803
|
+
rehearseCandidates.push({ id: itemId(item), label, score: utility, reason: "important memory has evidence of reuse but is aging" });
|
|
543804
|
+
}
|
|
543805
|
+
if (unused) {
|
|
543806
|
+
presentButUnused.push({ id: itemId(item), label, score: utility, reason: "present in context without reuse evidence" });
|
|
543807
|
+
}
|
|
543808
|
+
}
|
|
543809
|
+
for (let i2 = 0; i2 < items.length; i2++) {
|
|
543810
|
+
for (let j = i2 + 1; j < items.length; j++) {
|
|
543811
|
+
const a2 = items[i2];
|
|
543812
|
+
const b = items[j];
|
|
543813
|
+
const aEnt = a2.entities ?? extractSemanticEntities(a2.content);
|
|
543814
|
+
const bEnt = b.entities ?? extractSemanticEntities(b.content);
|
|
543815
|
+
const overlap = entityOverlap(aEnt, bEnt);
|
|
543816
|
+
const contradiction = /\b(no longer|superseded|instead|not|failed|wrong|obsolete)\b/i.test(`${a2.content}
|
|
543817
|
+
${b.content}`);
|
|
543818
|
+
const score = overlap + (contradiction ? 0.35 : 0);
|
|
543819
|
+
if (score >= 0.45 && a2.content.trim() !== b.content.trim()) {
|
|
543820
|
+
const aId = itemId(a2);
|
|
543821
|
+
const bId = itemId(b);
|
|
543822
|
+
const sharedEntities = aEnt.filter((entity) => bEnt.map((v) => v.toLowerCase()).includes(entity.toLowerCase()));
|
|
543823
|
+
interferencePairs.push({
|
|
543824
|
+
a: aId,
|
|
543825
|
+
b: bId,
|
|
543826
|
+
aId,
|
|
543827
|
+
bId,
|
|
543828
|
+
aLabel: semanticLabelFor(a2),
|
|
543829
|
+
bLabel: semanticLabelFor(b),
|
|
543830
|
+
score: clamp016(score),
|
|
543831
|
+
overlap: clamp016(score),
|
|
543832
|
+
sharedEntities,
|
|
543833
|
+
reason: contradiction ? "overlapping entities with supersession/negation language" : "overlapping entities compete for recall"
|
|
543834
|
+
});
|
|
543835
|
+
}
|
|
543836
|
+
}
|
|
543837
|
+
}
|
|
543838
|
+
const useful = items.filter((i2) => itemUtility(i2, now) >= 0.5 || (i2.reuseCount ?? 0) > 0).length;
|
|
543839
|
+
const interferencePenalty = Math.min(0.25, interferencePairs.length * 0.03);
|
|
543840
|
+
const activeRetentionEstimate = clamp016(items.length === 0 ? 1 : useful / items.length - interferencePenalty);
|
|
543841
|
+
return {
|
|
543842
|
+
generatedAt: now,
|
|
543843
|
+
activeRetentionEstimate,
|
|
543844
|
+
selectiveForgetCandidates: selectiveForgetCandidates.sort((a2, b) => b.score - a2.score).slice(0, 12),
|
|
543845
|
+
rehearseCandidates: rehearseCandidates.sort((a2, b) => b.score - a2.score).slice(0, 12),
|
|
543846
|
+
presentButUnused: presentButUnused.sort((a2, b) => a2.score - b.score).slice(0, 12),
|
|
543847
|
+
interferencePairs: interferencePairs.sort((a2, b) => b.score - a2.score).slice(0, 20)
|
|
543848
|
+
};
|
|
543849
|
+
}
|
|
543850
|
+
function shouldTriggerContextConsolidation(snapshot, forgetting, opts = {}) {
|
|
543851
|
+
const minRawTokens = opts.minRawTokens ?? snapshot.targetRawTokenBudget;
|
|
543852
|
+
const maxRawRatio = opts.maxRawRatio ?? 0.35;
|
|
543853
|
+
const minRetention = opts.minRetention ?? 0.7;
|
|
543854
|
+
const reasons = [];
|
|
543855
|
+
let score = 0;
|
|
543856
|
+
if (snapshot.rawTokens > minRawTokens) {
|
|
543857
|
+
reasons.push(`raw tokens ${snapshot.rawTokens} exceed target ${minRawTokens}`);
|
|
543858
|
+
score += 0.4;
|
|
543859
|
+
}
|
|
543860
|
+
if (snapshot.rawRatio > maxRawRatio) {
|
|
543861
|
+
reasons.push(`raw ratio ${snapshot.rawRatio.toFixed(2)} exceeds ${maxRawRatio.toFixed(2)}`);
|
|
543862
|
+
score += 0.25;
|
|
543863
|
+
}
|
|
543864
|
+
if (snapshot.rawTokensToTarget > 0) {
|
|
543865
|
+
reasons.push(`${snapshot.rawTokensToTarget} raw tokens must move to reach target`);
|
|
543866
|
+
score += Math.min(0.25, snapshot.rawTokensToTarget / Math.max(1, snapshot.rawTokens));
|
|
543867
|
+
}
|
|
543868
|
+
if (forgetting && forgetting.activeRetentionEstimate < minRetention) {
|
|
543869
|
+
reasons.push(`active retention estimate ${forgetting.activeRetentionEstimate.toFixed(2)} below ${minRetention.toFixed(2)}`);
|
|
543870
|
+
score += 0.25;
|
|
543871
|
+
}
|
|
543872
|
+
if (forgetting && forgetting.interferencePairs.length > 0) {
|
|
543873
|
+
reasons.push(`${forgetting.interferencePairs.length} interference pair(s) detected`);
|
|
543874
|
+
score += Math.min(0.2, forgetting.interferencePairs.length * 0.04);
|
|
543875
|
+
}
|
|
543876
|
+
const minScore = opts.minScore ?? 0.45;
|
|
543877
|
+
return { shouldConsolidate: score >= minScore, reasons, score: clamp016(score) };
|
|
543878
|
+
}
|
|
543879
|
+
function shouldTriggerConsolidation(input, opts = {}) {
|
|
543880
|
+
const snapshot = "rawTokens" in input ? input : input.pressure ?? input.snapshot;
|
|
543881
|
+
if (!snapshot)
|
|
543882
|
+
return { shouldConsolidate: false, reasons: ["missing context pressure snapshot"], score: 0 };
|
|
543883
|
+
const forgetting = "rawTokens" in input ? void 0 : input.forgetting;
|
|
543884
|
+
return shouldTriggerContextConsolidation(snapshot, forgetting, opts);
|
|
543885
|
+
}
|
|
543886
|
+
function messageContentText(content) {
|
|
543887
|
+
if (typeof content === "string")
|
|
543888
|
+
return content;
|
|
543889
|
+
if (!Array.isArray(content))
|
|
543890
|
+
return "";
|
|
543891
|
+
return content.map((part) => {
|
|
543892
|
+
if (part && typeof part === "object" && "text" in part)
|
|
543893
|
+
return String(part.text ?? "");
|
|
543894
|
+
if (part && typeof part === "object" && "type" in part)
|
|
543895
|
+
return `[${String(part.type)}]`;
|
|
543896
|
+
return "";
|
|
543897
|
+
}).filter(Boolean).join("\n");
|
|
543898
|
+
}
|
|
543899
|
+
function contextItemsFromMessages(messages2, opts = {}) {
|
|
543900
|
+
const now = opts.now ?? Date.now();
|
|
543901
|
+
const tail = messages2.slice(-Math.max(1, opts.maxMessages ?? 12));
|
|
543902
|
+
return tail.map((message2, index) => {
|
|
543903
|
+
const text = messageContentText(message2.content).trim();
|
|
543904
|
+
const toolCalls = Array.isArray(message2.tool_calls) && message2.tool_calls.length > 0 ? message2.tool_calls.map((call) => `${call.function?.name ?? "tool"}(${(call.function?.arguments ?? "").slice(0, 120)})`).join(", ") : "";
|
|
543905
|
+
const content = [text, toolCalls ? `tool_calls: ${toolCalls}` : ""].filter(Boolean).join("\n");
|
|
543906
|
+
if (!content.trim())
|
|
543907
|
+
return null;
|
|
543908
|
+
const role = String(message2.role ?? "message");
|
|
543909
|
+
return {
|
|
543910
|
+
id: `message_${stableId([role, String(index), content.slice(0, 240)])}`,
|
|
543911
|
+
source: "conversation.messages",
|
|
543912
|
+
kind: role === "tool" ? "tool_result" : "recent_message",
|
|
543913
|
+
content,
|
|
543914
|
+
priority: role === "user" ? 55 : role === "assistant" ? 35 : 20,
|
|
543915
|
+
timestamp: now - (tail.length - index) * 1e3,
|
|
543916
|
+
consolidated: false,
|
|
543917
|
+
semanticLabels: [semanticLabelFor({ source: "conversation.messages", kind: role, content })],
|
|
543918
|
+
entities: extractSemanticEntities(content)
|
|
543919
|
+
};
|
|
543920
|
+
}).filter(Boolean);
|
|
543921
|
+
}
|
|
543922
|
+
function ingestContextFeedbackMarkdown(markdown, opts = {}) {
|
|
543923
|
+
const metrics2 = {};
|
|
543924
|
+
for (const line of markdown.split(/\n/)) {
|
|
543925
|
+
const m2 = line.match(/^\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|/);
|
|
543926
|
+
if (!m2)
|
|
543927
|
+
continue;
|
|
543928
|
+
const key = m2[1].trim();
|
|
543929
|
+
const value2 = m2[2].trim();
|
|
543930
|
+
if (!key || key === "Metric" || /^-+$/.test(key))
|
|
543931
|
+
continue;
|
|
543932
|
+
metrics2[key] = parseMetricValue2(value2);
|
|
543933
|
+
}
|
|
543934
|
+
const gaps = [];
|
|
543935
|
+
const gapRegex = /^##\s+GAP\s+(\d+):\s+(.+?)\s*$/gim;
|
|
543936
|
+
const matches = [...markdown.matchAll(gapRegex)];
|
|
543937
|
+
for (let i2 = 0; i2 < matches.length; i2++) {
|
|
543938
|
+
const match = matches[i2];
|
|
543939
|
+
const start2 = match.index + match[0].length;
|
|
543940
|
+
const end = matches[i2 + 1]?.index ?? markdown.search(/\n## Summary:/);
|
|
543941
|
+
const body = markdown.slice(start2, end === -1 ? void 0 : end).trim();
|
|
543942
|
+
const title = match[2].trim();
|
|
543943
|
+
const labels = [
|
|
543944
|
+
"context_window",
|
|
543945
|
+
title.toLowerCase().includes("sleep") ? "dynamic_consolidation" : "",
|
|
543946
|
+
title.toLowerCase().includes("forget") ? "active_forgetting" : "",
|
|
543947
|
+
title.toLowerCase().includes("chunk") ? "semantic_chunking" : ""
|
|
543948
|
+
].filter(Boolean);
|
|
543949
|
+
gaps.push({ id: `gap_${match[1]}`, title, body, labels, metrics: extractInlineMetrics(body) });
|
|
543950
|
+
}
|
|
543951
|
+
const summary = gaps.map((g) => `${g.id}=${g.title}`).join("; ");
|
|
543952
|
+
const source = opts.sourcePath ?? "context-feedback";
|
|
543953
|
+
const items = gaps.map((gap) => ({
|
|
543954
|
+
id: `feedback_${gap.id}`,
|
|
543955
|
+
source,
|
|
543956
|
+
kind: "agent_feedback_gap",
|
|
543957
|
+
content: `${gap.title}
|
|
543958
|
+
${gap.body}`,
|
|
543959
|
+
consolidated: false,
|
|
543960
|
+
priority: 90,
|
|
543961
|
+
timestamp: opts.now,
|
|
543962
|
+
importance: 8,
|
|
543963
|
+
semanticLabels: gap.labels,
|
|
543964
|
+
metadata: { sourcePath: opts.sourcePath, gapId: gap.id }
|
|
543965
|
+
}));
|
|
543966
|
+
const episode = {
|
|
543967
|
+
sessionId: opts.sessionId,
|
|
543968
|
+
modality: "reflection",
|
|
543969
|
+
toolName: "context_feedback_ingest",
|
|
543970
|
+
content: `External agent memory feedback: ${summary || "context organization gaps"}`,
|
|
543971
|
+
importance: 8,
|
|
543972
|
+
decayClass: "procedural",
|
|
543973
|
+
metadata: {
|
|
543974
|
+
kind: "context_feedback",
|
|
543975
|
+
sourcePath: opts.sourcePath,
|
|
543976
|
+
metrics: metrics2,
|
|
543977
|
+
gaps: gaps.map(({ id, title, labels }) => ({ id, title, labels })),
|
|
543978
|
+
semanticLabels: ["context_window", "dynamic_consolidation", "active_forgetting", "semantic_chunking"]
|
|
543979
|
+
}
|
|
543980
|
+
};
|
|
543981
|
+
return { episode, items, chunkItems: items, metrics: metrics2, gaps };
|
|
543982
|
+
}
|
|
543983
|
+
function parseMetricValue2(raw) {
|
|
543984
|
+
const cleaned = raw.trim().replace(/\*\*/g, "");
|
|
543985
|
+
const match = cleaned.match(/-?\d[\d,]*(?:\.\d+)?/);
|
|
543986
|
+
if (!match)
|
|
543987
|
+
return cleaned;
|
|
543988
|
+
const n2 = Number(match[0].replace(/,/g, ""));
|
|
543989
|
+
return Number.isFinite(n2) ? n2 : cleaned;
|
|
543990
|
+
}
|
|
543991
|
+
function extractInlineMetrics(text) {
|
|
543992
|
+
const metrics2 = {};
|
|
543993
|
+
for (const line of text.split(/\n/)) {
|
|
543994
|
+
const bullet = line.match(/^\s*[-*]\s*(?:\*\*)?([^:*]+?)(?:\*\*)?:\s*(.+)$/);
|
|
543995
|
+
if (bullet)
|
|
543996
|
+
metrics2[bullet[1].trim()] = parseMetricValue2(bullet[2]);
|
|
543997
|
+
const bold = line.match(/^\s*(?:\*\*)?([^:*]+):(?:\*\*)?\s*(.+)$/);
|
|
543998
|
+
if (bold)
|
|
543999
|
+
metrics2[bold[1].trim()] = parseMetricValue2(bold[2]);
|
|
544000
|
+
}
|
|
544001
|
+
return metrics2;
|
|
544002
|
+
}
|
|
544003
|
+
var STOP, SemanticChunker, snapshotContextPressure, analyzeActiveForgetting, buildFeedbackIngestion;
|
|
544004
|
+
var init_semanticContext = __esm({
|
|
544005
|
+
"packages/memory/dist/semanticContext.js"() {
|
|
544006
|
+
"use strict";
|
|
544007
|
+
STOP = /* @__PURE__ */ new Set([
|
|
544008
|
+
"the",
|
|
544009
|
+
"and",
|
|
544010
|
+
"for",
|
|
544011
|
+
"with",
|
|
544012
|
+
"that",
|
|
544013
|
+
"this",
|
|
544014
|
+
"from",
|
|
544015
|
+
"into",
|
|
544016
|
+
"have",
|
|
544017
|
+
"has",
|
|
544018
|
+
"was",
|
|
544019
|
+
"were",
|
|
544020
|
+
"will",
|
|
544021
|
+
"should",
|
|
544022
|
+
"would",
|
|
544023
|
+
"could",
|
|
544024
|
+
"about",
|
|
544025
|
+
"because"
|
|
544026
|
+
]);
|
|
544027
|
+
SemanticChunker = class {
|
|
544028
|
+
chunk(items, options2 = {}) {
|
|
544029
|
+
const maxChunks = Math.max(1, Math.floor(options2.maxChunks ?? 7));
|
|
544030
|
+
const now = options2.now ?? Date.now();
|
|
544031
|
+
const groups = [];
|
|
544032
|
+
for (const item of items.filter((i2) => i2.content.trim())) {
|
|
544033
|
+
const entities = [.../* @__PURE__ */ new Set([...item.entities ?? [], ...extractSemanticEntities(item.content)])];
|
|
544034
|
+
const label = semanticLabelFor(item);
|
|
544035
|
+
let target = groups.find((g) => g.label === label && (entityOverlap(g.entities, entities) >= 0.2 || g.items.length < 3));
|
|
544036
|
+
if (!target) {
|
|
544037
|
+
target = groups.find((g) => entityOverlap(g.entities, entities) >= 0.45);
|
|
544038
|
+
}
|
|
544039
|
+
if (!target) {
|
|
544040
|
+
target = { label, items: [], entities: [] };
|
|
544041
|
+
groups.push(target);
|
|
544042
|
+
}
|
|
544043
|
+
target.items.push({ ...item, entities });
|
|
544044
|
+
target.entities = [.../* @__PURE__ */ new Set([...target.entities, ...entities])].slice(0, 32);
|
|
544045
|
+
}
|
|
544046
|
+
while (groups.length > maxChunks) {
|
|
544047
|
+
groups.sort((a2, b) => groupUtility(a2.items, now) - groupUtility(b.items, now));
|
|
544048
|
+
const smallest = groups.shift();
|
|
544049
|
+
let bestIdx = 0;
|
|
544050
|
+
let bestScore = -1;
|
|
544051
|
+
for (let i2 = 0; i2 < groups.length; i2++) {
|
|
544052
|
+
const score = entityOverlap(smallest.entities, groups[i2].entities) + (smallest.label === groups[i2].label ? 1 : 0);
|
|
544053
|
+
if (score > bestScore) {
|
|
544054
|
+
bestScore = score;
|
|
544055
|
+
bestIdx = i2;
|
|
544056
|
+
}
|
|
544057
|
+
}
|
|
544058
|
+
groups[bestIdx].items.push(...smallest.items);
|
|
544059
|
+
groups[bestIdx].entities = [.../* @__PURE__ */ new Set([...groups[bestIdx].entities, ...smallest.entities])].slice(0, 32);
|
|
544060
|
+
}
|
|
544061
|
+
const maxSummaryChars = Math.max(180, Math.floor((options2.targetRawTokenBudget ?? 2e3) / maxChunks) * 4);
|
|
544062
|
+
return groups.map((g) => this.buildChunk(g.label, g.items, g.entities, now, maxSummaryChars)).sort((a2, b) => b.utilityScore - a2.utilityScore || a2.label.localeCompare(b.label));
|
|
544063
|
+
}
|
|
544064
|
+
buildChunk(label, items, entities, now, maxSummaryChars) {
|
|
544065
|
+
const rawTokenEstimate = items.reduce((sum, item) => sum + tokenCount(item), 0);
|
|
544066
|
+
const summary = summarize(items, maxSummaryChars);
|
|
544067
|
+
const tokenEstimate = Math.max(1, estimateTokens(summary));
|
|
544068
|
+
const utilityScore = groupUtility(items, now);
|
|
544069
|
+
const kinds = [...new Set(items.map((i2) => i2.kind))].sort();
|
|
544070
|
+
const sources = [...new Set(items.map((i2) => `${i2.source}:${i2.kind}`))].sort();
|
|
544071
|
+
return {
|
|
544072
|
+
id: `sem_${stableId([label, ...items.map((i2) => itemId(i2)).sort()])}`,
|
|
544073
|
+
label,
|
|
544074
|
+
summary,
|
|
544075
|
+
sourceIds: items.map((i2) => itemId(i2)),
|
|
544076
|
+
entities: entities.slice(0, 16),
|
|
544077
|
+
kinds,
|
|
544078
|
+
sourceKinds: sources,
|
|
544079
|
+
tokenEstimate,
|
|
544080
|
+
rawTokenEstimate,
|
|
544081
|
+
density: tokenEstimate > 0 ? rawTokenEstimate / tokenEstimate : 1,
|
|
544082
|
+
utilityScore,
|
|
544083
|
+
staleness: stalenessFor(items, now),
|
|
544084
|
+
openQuestions: openQuestionsFor(items),
|
|
544085
|
+
evidenceCount: items.length,
|
|
544086
|
+
items
|
|
544087
|
+
};
|
|
544088
|
+
}
|
|
544089
|
+
};
|
|
544090
|
+
snapshotContextPressure = buildContextPressureSnapshot;
|
|
544091
|
+
analyzeActiveForgetting = buildActiveForgettingReport;
|
|
544092
|
+
buildFeedbackIngestion = ingestContextFeedbackMarkdown;
|
|
544093
|
+
}
|
|
544094
|
+
});
|
|
544095
|
+
|
|
543575
544096
|
// packages/memory/dist/index.js
|
|
543576
544097
|
var dist_exports2 = {};
|
|
543577
544098
|
__export(dist_exports2, {
|
|
@@ -543605,18 +544126,23 @@ __export(dist_exports2, {
|
|
|
543605
544126
|
RepoProfileStore: () => RepoProfileStore,
|
|
543606
544127
|
SYMBOL_MEANINGS: () => SYMBOL_MEANINGS,
|
|
543607
544128
|
SelfModel: () => SelfModel,
|
|
544129
|
+
SemanticChunker: () => SemanticChunker,
|
|
543608
544130
|
SocialMemoryStore: () => SocialMemoryStore,
|
|
543609
544131
|
TaskMemoryStore: () => TaskMemoryStore,
|
|
543610
544132
|
TemporalGraph: () => TemporalGraph,
|
|
543611
544133
|
ToolOutcomeTracker: () => ToolOutcomeTracker,
|
|
543612
544134
|
ToolPatternStore: () => ToolPatternStore,
|
|
543613
544135
|
ValidationStore: () => ValidationStore,
|
|
544136
|
+
analyzeActiveForgetting: () => analyzeActiveForgetting,
|
|
543614
544137
|
applyInfluence: () => applyInfluence,
|
|
543615
544138
|
attachTrace: () => attachTrace,
|
|
543616
544139
|
authorityBias: () => authorityBias,
|
|
543617
544140
|
autoDecayClass: () => autoDecayClass,
|
|
543618
544141
|
autoImportance: () => autoImportance,
|
|
543619
544142
|
batchLink: () => batchLink,
|
|
544143
|
+
buildActiveForgettingReport: () => buildActiveForgettingReport,
|
|
544144
|
+
buildContextPressureSnapshot: () => buildContextPressureSnapshot,
|
|
544145
|
+
buildFeedbackIngestion: () => buildFeedbackIngestion,
|
|
543620
544146
|
buildGist: () => buildGist,
|
|
543621
544147
|
buildSelfTrustInfluence: () => buildSelfTrustInfluence,
|
|
543622
544148
|
buildTrace: () => buildTrace,
|
|
@@ -543629,6 +544155,7 @@ __export(dist_exports2, {
|
|
|
543629
544155
|
compressToGist: () => compressToGist,
|
|
543630
544156
|
conformityBias: () => conformityBias,
|
|
543631
544157
|
congruenceMultiplier: () => congruenceMultiplier,
|
|
544158
|
+
contextItemsFromMessages: () => contextItemsFromMessages,
|
|
543632
544159
|
cosineSimilarity: () => cosineSimilarity2,
|
|
543633
544160
|
createCRLMemoryStore: () => createCRLMemoryStore,
|
|
543634
544161
|
createHomeostaticState: () => createHomeostaticState,
|
|
@@ -543640,7 +544167,9 @@ __export(dist_exports2, {
|
|
|
543640
544167
|
emptyDevelopmentalMetrics: () => emptyMetrics,
|
|
543641
544168
|
engagementScore: () => engagementScore,
|
|
543642
544169
|
episodeCount: () => episodeCount,
|
|
544170
|
+
estimateContextTokens: () => estimateContextTokens,
|
|
543643
544171
|
extractQueryEntities: () => extractQueryEntities,
|
|
544172
|
+
extractSemanticEntities: () => extractSemanticEntities,
|
|
543644
544173
|
extractTrace: () => extractTrace,
|
|
543645
544174
|
findNeighbors: () => findNeighbors,
|
|
543646
544175
|
fingerprintSignature: () => fingerprintSignature,
|
|
@@ -543651,6 +544180,7 @@ __export(dist_exports2, {
|
|
|
543651
544180
|
goalHashOf: () => goalHashOf,
|
|
543652
544181
|
importanceMultiplier: () => importanceMultiplier,
|
|
543653
544182
|
inferDomainFromEpisode: () => inferDomainFromEpisode,
|
|
544183
|
+
ingestContextFeedbackMarkdown: () => ingestContextFeedbackMarkdown,
|
|
543654
544184
|
initDb: () => initDb,
|
|
543655
544185
|
isSessionGist: () => isSessionGist,
|
|
543656
544186
|
lightSleep: () => lightSleep,
|
|
@@ -543672,7 +544202,10 @@ __export(dist_exports2, {
|
|
|
543672
544202
|
selectAndWalkGraphCandidate: () => selectAndWalkGraphCandidate,
|
|
543673
544203
|
selectInnerGraphCandidates: () => selectInnerGraphCandidates,
|
|
543674
544204
|
selfTrustFor: () => selfTrustFor,
|
|
544205
|
+
shouldTriggerConsolidation: () => shouldTriggerConsolidation,
|
|
544206
|
+
shouldTriggerContextConsolidation: () => shouldTriggerContextConsolidation,
|
|
543675
544207
|
slowWaveReplay: () => slowWaveReplay,
|
|
544208
|
+
snapshotContextPressure: () => snapshotContextPressure,
|
|
543676
544209
|
splanifoldCosine: () => cosine,
|
|
543677
544210
|
splanifoldDeserialize: () => deserialize,
|
|
543678
544211
|
splanifoldEvaluate: () => evaluate2,
|
|
@@ -543724,6 +544257,7 @@ var init_dist7 = __esm({
|
|
|
543724
544257
|
init_stagnationRecipes();
|
|
543725
544258
|
init_codebaseMap();
|
|
543726
544259
|
init_embeddingDrift();
|
|
544260
|
+
init_semanticContext();
|
|
543727
544261
|
}
|
|
543728
544262
|
});
|
|
543729
544263
|
|
|
@@ -546196,7 +546730,7 @@ var init_failureHandoff = __esm({
|
|
|
546196
546730
|
});
|
|
546197
546731
|
|
|
546198
546732
|
// packages/orchestrator/dist/context-fabric.js
|
|
546199
|
-
function
|
|
546733
|
+
function estimateTokens2(text) {
|
|
546200
546734
|
return Math.ceil(text.length / 4);
|
|
546201
546735
|
}
|
|
546202
546736
|
function normalizeSignalContent(content) {
|
|
@@ -546213,6 +546747,54 @@ function truncateText2(text, maxChars) {
|
|
|
546213
546747
|
truncated: true
|
|
546214
546748
|
};
|
|
546215
546749
|
}
|
|
546750
|
+
function compactDiagnosticValue(value2, depth = 0) {
|
|
546751
|
+
if (value2 == null)
|
|
546752
|
+
return value2;
|
|
546753
|
+
if (typeof value2 === "string") {
|
|
546754
|
+
return value2.length > 240 ? `${value2.slice(0, 237)}...` : value2;
|
|
546755
|
+
}
|
|
546756
|
+
if (typeof value2 === "number" || typeof value2 === "boolean")
|
|
546757
|
+
return value2;
|
|
546758
|
+
if (Array.isArray(value2)) {
|
|
546759
|
+
if (depth >= 2)
|
|
546760
|
+
return `[array:${value2.length}]`;
|
|
546761
|
+
return value2.slice(0, 8).map((entry) => compactDiagnosticValue(entry, depth + 1));
|
|
546762
|
+
}
|
|
546763
|
+
if (typeof value2 === "object") {
|
|
546764
|
+
if (depth >= 2)
|
|
546765
|
+
return "[object]";
|
|
546766
|
+
const out = {};
|
|
546767
|
+
for (const [key, entry] of Object.entries(value2).slice(0, 12)) {
|
|
546768
|
+
if (/^(content|text|prompt|messages|transcript)$/i.test(key)) {
|
|
546769
|
+
out[key] = typeof entry === "string" ? `[omitted:${entry.length}]` : "[omitted]";
|
|
546770
|
+
} else {
|
|
546771
|
+
out[key] = compactDiagnosticValue(entry, depth + 1);
|
|
546772
|
+
}
|
|
546773
|
+
}
|
|
546774
|
+
return out;
|
|
546775
|
+
}
|
|
546776
|
+
return String(value2);
|
|
546777
|
+
}
|
|
546778
|
+
function collectMetadataReports(signals) {
|
|
546779
|
+
const pressureReports = [];
|
|
546780
|
+
const forgettingReports = [];
|
|
546781
|
+
for (const signal of signals) {
|
|
546782
|
+
const metadata = signal.metadata ?? {};
|
|
546783
|
+
for (const [key, value2] of Object.entries(metadata)) {
|
|
546784
|
+
if (value2 == null)
|
|
546785
|
+
continue;
|
|
546786
|
+
if (/pressure/i.test(key))
|
|
546787
|
+
pressureReports.push(compactDiagnosticValue(value2));
|
|
546788
|
+
if (/forgetting|retention|interference/i.test(key)) {
|
|
546789
|
+
forgettingReports.push(compactDiagnosticValue(value2));
|
|
546790
|
+
}
|
|
546791
|
+
}
|
|
546792
|
+
}
|
|
546793
|
+
return {
|
|
546794
|
+
pressureReports: pressureReports.length > 0 ? pressureReports : void 0,
|
|
546795
|
+
forgettingReports: forgettingReports.length > 0 ? forgettingReports : void 0
|
|
546796
|
+
};
|
|
546797
|
+
}
|
|
546216
546798
|
function signalFromBlock(kind, source, content, options2 = {}) {
|
|
546217
546799
|
const normalized = normalizeSignalContent(content ?? "");
|
|
546218
546800
|
if (!normalized)
|
|
@@ -546243,6 +546825,7 @@ var init_context_fabric = __esm({
|
|
|
546243
546825
|
"tool_cache",
|
|
546244
546826
|
"skill_manifest",
|
|
546245
546827
|
"memory",
|
|
546828
|
+
"semantic_chunk",
|
|
546246
546829
|
"session_history",
|
|
546247
546830
|
"anchor",
|
|
546248
546831
|
"handoff",
|
|
@@ -546258,6 +546841,7 @@ var init_context_fabric = __esm({
|
|
|
546258
546841
|
tool_cache: "Tool Cache",
|
|
546259
546842
|
skill_manifest: "Skill Manifest",
|
|
546260
546843
|
memory: "Memory",
|
|
546844
|
+
semantic_chunk: "Semantic Context",
|
|
546261
546845
|
session_history: "Session History",
|
|
546262
546846
|
anchor: "Relevant Anchors",
|
|
546263
546847
|
handoff: "Handoff",
|
|
@@ -546273,6 +546857,7 @@ var init_context_fabric = __esm({
|
|
|
546273
546857
|
tool_cache: 2200,
|
|
546274
546858
|
skill_manifest: 900,
|
|
546275
546859
|
memory: 1500,
|
|
546860
|
+
semantic_chunk: 2200,
|
|
546276
546861
|
session_history: 1400,
|
|
546277
546862
|
anchor: 1100,
|
|
546278
546863
|
handoff: 1600,
|
|
@@ -546362,6 +546947,7 @@ var init_context_fabric = __esm({
|
|
|
546362
546947
|
const dropped = [];
|
|
546363
546948
|
const sectionLines = [];
|
|
546364
546949
|
const sectionDiagnostics = [];
|
|
546950
|
+
const metadataReports = collectMetadataReports(sanitized);
|
|
546365
546951
|
let truncatedSignals = 0;
|
|
546366
546952
|
for (const kind of KIND_ORDER) {
|
|
546367
546953
|
const bucket = byKind.get(kind);
|
|
@@ -546424,6 +547010,8 @@ var init_context_fabric = __esm({
|
|
|
546424
547010
|
truncatedSignals: 0,
|
|
546425
547011
|
estimatedTokens: 0,
|
|
546426
547012
|
totalChars: 0,
|
|
547013
|
+
semanticChunkCount: 0,
|
|
547014
|
+
...metadataReports,
|
|
546427
547015
|
sections: []
|
|
546428
547016
|
},
|
|
546429
547017
|
included: [],
|
|
@@ -546443,7 +547031,7 @@ var init_context_fabric = __esm({
|
|
|
546443
547031
|
if (options2.includeDiagnostics) {
|
|
546444
547032
|
content += `
|
|
546445
547033
|
|
|
546446
|
-
context_fabric: included=${included.length} dropped=${dropped.length} truncated=${truncatedSignals} est_tokens=${
|
|
547034
|
+
context_fabric: included=${included.length} dropped=${dropped.length} truncated=${truncatedSignals} est_tokens=${estimateTokens2(content)}`;
|
|
546447
547035
|
}
|
|
546448
547036
|
return {
|
|
546449
547037
|
content,
|
|
@@ -546451,8 +547039,10 @@ context_fabric: included=${included.length} dropped=${dropped.length} truncated=
|
|
|
546451
547039
|
includedSignals: included.length,
|
|
546452
547040
|
droppedSignals: dropped.length,
|
|
546453
547041
|
truncatedSignals,
|
|
546454
|
-
estimatedTokens:
|
|
547042
|
+
estimatedTokens: estimateTokens2(content),
|
|
546455
547043
|
totalChars: content.length,
|
|
547044
|
+
semanticChunkCount: included.filter((signal) => signal.kind === "semantic_chunk").length,
|
|
547045
|
+
...metadataReports,
|
|
546456
547046
|
sections: sectionDiagnostics
|
|
546457
547047
|
},
|
|
546458
547048
|
included,
|
|
@@ -546474,7 +547064,7 @@ import { existsSync as existsSync81, readFileSync as readFileSync62, statSync as
|
|
|
546474
547064
|
import { execSync as execSync46 } from "node:child_process";
|
|
546475
547065
|
import { homedir as homedir29, platform as platform3, arch as arch2, totalmem as totalmem3, freemem as freemem3, hostname as hostname3 } from "node:os";
|
|
546476
547066
|
import { join as join94 } from "node:path";
|
|
546477
|
-
import { createHash as
|
|
547067
|
+
import { createHash as createHash21 } from "node:crypto";
|
|
546478
547068
|
function capturePreflightSnapshot(workingDir) {
|
|
546479
547069
|
const warnings = [];
|
|
546480
547070
|
const configFingerprints = {};
|
|
@@ -546641,7 +547231,7 @@ function expandPath(p2) {
|
|
|
546641
547231
|
return p2;
|
|
546642
547232
|
}
|
|
546643
547233
|
function sha2563(s2) {
|
|
546644
|
-
return
|
|
547234
|
+
return createHash21("sha256").update(s2).digest("hex").slice(0, 16);
|
|
546645
547235
|
}
|
|
546646
547236
|
function freeDiskBytes(path12 = "/tmp") {
|
|
546647
547237
|
try {
|
|
@@ -547517,6 +548107,115 @@ import { join as _pathJoin, resolve as _pathResolve } from "node:path";
|
|
|
547517
548107
|
import { tmpdir as _osTmpdir } from "node:os";
|
|
547518
548108
|
import { homedir as _osHomedir } from "node:os";
|
|
547519
548109
|
import { z as z15 } from "zod";
|
|
548110
|
+
function textFromMessageContent(content) {
|
|
548111
|
+
if (typeof content === "string")
|
|
548112
|
+
return content;
|
|
548113
|
+
if (!Array.isArray(content))
|
|
548114
|
+
return "";
|
|
548115
|
+
return content.map((part) => part.type === "text" ? part.text ?? "" : "[image]").join("\n");
|
|
548116
|
+
}
|
|
548117
|
+
function normalizeContextSnippet(text, maxChars = 900) {
|
|
548118
|
+
const normalized = text.replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
548119
|
+
if (normalized.length <= maxChars)
|
|
548120
|
+
return normalized;
|
|
548121
|
+
return `${normalized.slice(0, maxChars - 18).trimEnd()}
|
|
548122
|
+
... [bounded]`;
|
|
548123
|
+
}
|
|
548124
|
+
function estimateMessagesTokens(messages2) {
|
|
548125
|
+
let chars = 0;
|
|
548126
|
+
for (const message2 of messages2) {
|
|
548127
|
+
chars += textFromMessageContent(message2.content).length;
|
|
548128
|
+
if (message2.tool_calls) {
|
|
548129
|
+
for (const call of message2.tool_calls) {
|
|
548130
|
+
chars += call.function.arguments.length + call.function.name.length;
|
|
548131
|
+
}
|
|
548132
|
+
}
|
|
548133
|
+
}
|
|
548134
|
+
return Math.ceil(chars / 4);
|
|
548135
|
+
}
|
|
548136
|
+
function buildFallbackSemanticChunks(items, maxChunks = 7) {
|
|
548137
|
+
const normalized = items.map((item) => ({ ...item, content: normalizeContextSnippet(item.content, 900) })).filter((item) => item.content.length > 0);
|
|
548138
|
+
const bucketOrder = [
|
|
548139
|
+
{ label: "Goal and Plan", kinds: ["goal", "task_state"] },
|
|
548140
|
+
{ label: "Failure and Risk", kinds: ["recent_failure"] },
|
|
548141
|
+
{ label: "Files and Anchors", kinds: ["known_files", "anchor"] },
|
|
548142
|
+
{ label: "Knowledge and Memory", kinds: ["tool_cache", "memory"] },
|
|
548143
|
+
{ label: "Recent Dialogue", kinds: ["recent_message", "session_history"] },
|
|
548144
|
+
{ label: "Environment", kinds: ["environment"] }
|
|
548145
|
+
];
|
|
548146
|
+
const chunks = [];
|
|
548147
|
+
for (const bucket of bucketOrder) {
|
|
548148
|
+
const bucketItems = normalized.filter((item) => bucket.kinds.includes(item.kind)).sort((a2, b) => (b.priority ?? 0) - (a2.priority ?? 0));
|
|
548149
|
+
if (bucketItems.length === 0)
|
|
548150
|
+
continue;
|
|
548151
|
+
const rawChars = bucketItems.reduce((sum, item) => sum + item.content.length, 0);
|
|
548152
|
+
const lines = bucketItems.slice(0, 5).map((item) => {
|
|
548153
|
+
const oneLine = item.content.replace(/\s+/g, " ").trim();
|
|
548154
|
+
return `- ${item.label}: ${oneLine.slice(0, 360)}`;
|
|
548155
|
+
});
|
|
548156
|
+
const content = normalizeContextSnippet(lines.join("\n"), 850);
|
|
548157
|
+
chunks.push({
|
|
548158
|
+
id: bucket.label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),
|
|
548159
|
+
label: bucket.label,
|
|
548160
|
+
content,
|
|
548161
|
+
sourceIds: bucketItems.map((item) => item.id).slice(0, 12),
|
|
548162
|
+
priority: Math.max(...bucketItems.map((item) => item.priority ?? 0)),
|
|
548163
|
+
metadata: {
|
|
548164
|
+
labels: bucketItems.map((item) => item.label).slice(0, 8),
|
|
548165
|
+
compression: {
|
|
548166
|
+
rawChars,
|
|
548167
|
+
chunkChars: content.length,
|
|
548168
|
+
ratio: rawChars > 0 ? Number((content.length / rawChars).toFixed(3)) : 1
|
|
548169
|
+
}
|
|
548170
|
+
}
|
|
548171
|
+
});
|
|
548172
|
+
if (chunks.length >= maxChunks)
|
|
548173
|
+
break;
|
|
548174
|
+
}
|
|
548175
|
+
if (chunks.length < maxChunks) {
|
|
548176
|
+
const used = new Set(chunks.flatMap((chunk) => chunk.sourceIds));
|
|
548177
|
+
const leftovers = normalized.filter((item) => !used.has(item.id));
|
|
548178
|
+
for (const item of leftovers.slice(0, maxChunks - chunks.length)) {
|
|
548179
|
+
chunks.push({
|
|
548180
|
+
id: item.id,
|
|
548181
|
+
label: item.label,
|
|
548182
|
+
content: normalizeContextSnippet(item.content, 650),
|
|
548183
|
+
sourceIds: [item.id],
|
|
548184
|
+
priority: item.priority ?? 0,
|
|
548185
|
+
metadata: {
|
|
548186
|
+
labels: [item.label],
|
|
548187
|
+
compression: {
|
|
548188
|
+
rawChars: item.content.length,
|
|
548189
|
+
chunkChars: item.content.length,
|
|
548190
|
+
ratio: 1
|
|
548191
|
+
}
|
|
548192
|
+
}
|
|
548193
|
+
});
|
|
548194
|
+
}
|
|
548195
|
+
}
|
|
548196
|
+
return chunks.slice(0, maxChunks);
|
|
548197
|
+
}
|
|
548198
|
+
function shouldRunDynamicContextConsolidation(input) {
|
|
548199
|
+
const reasons = [];
|
|
548200
|
+
const rawRatio = input.snapshot.rawRatio;
|
|
548201
|
+
if (input.snapshot.rawTokens > input.snapshot.targetTokens)
|
|
548202
|
+
reasons.push("raw_tokens_over_target");
|
|
548203
|
+
if (rawRatio >= 0.85)
|
|
548204
|
+
reasons.push("raw_ratio_high");
|
|
548205
|
+
const dropped = input.frameDiagnostics?.droppedSignals ?? input.snapshot.droppedSignals ?? 0;
|
|
548206
|
+
const truncated = input.frameDiagnostics?.truncatedSignals ?? input.snapshot.truncatedSignals ?? 0;
|
|
548207
|
+
if (dropped > 0 || truncated > 0)
|
|
548208
|
+
reasons.push("fabric_pressure");
|
|
548209
|
+
const retention = Number(input.forgettingReport?.["retentionScore"] ?? input.forgettingReport?.["retention"] ?? NaN);
|
|
548210
|
+
const interference = Number(input.forgettingReport?.["interferenceScore"] ?? input.forgettingReport?.["interference"] ?? NaN);
|
|
548211
|
+
if (Number.isFinite(retention) && retention < 0.45)
|
|
548212
|
+
reasons.push("low_retention");
|
|
548213
|
+
if (Number.isFinite(interference) && interference > 0.65)
|
|
548214
|
+
reasons.push("high_interference");
|
|
548215
|
+
if (input.memoryHelperDecision === true)
|
|
548216
|
+
reasons.push("memory_helper_trigger");
|
|
548217
|
+
return { shouldRun: reasons.length > 0, reasons: [...new Set(reasons)], rawRatio };
|
|
548218
|
+
}
|
|
547520
548219
|
function repairJson(raw) {
|
|
547521
548220
|
if (!raw || typeof raw !== "string")
|
|
547522
548221
|
return null;
|
|
@@ -548254,6 +548953,10 @@ var init_agenticRunner = __esm({
|
|
|
548254
548953
|
// ledger and emitted as one bounded frame before each model call.
|
|
548255
548954
|
_contextLedger = new ContextLedger();
|
|
548256
548955
|
_contextFrameBuilder = new ContextFrameBuilder();
|
|
548956
|
+
_lastContextFrameDiagnostics = null;
|
|
548957
|
+
_lastContextPressureSnapshot = null;
|
|
548958
|
+
_lastActiveForgettingReport = null;
|
|
548959
|
+
_lastContextConsolidationTurn = -1e3;
|
|
548257
548960
|
/** WO-AM-10: Process pending episode embeddings in background batches */
|
|
548258
548961
|
async processPendingEmbeddings() {
|
|
548259
548962
|
if (this._pendingEmbeddings.length === 0 || !this._episodeStore)
|
|
@@ -550424,52 +551127,371 @@ ${latest.output || ""}`.trim();
|
|
|
550424
551127
|
const insertAt = Math.max(0, messages2.length - 1);
|
|
550425
551128
|
messages2.splice(insertAt, 0, { role: "system", content: frame });
|
|
550426
551129
|
}
|
|
550427
|
-
|
|
551130
|
+
_activeContextItem(kind, id, source, label, content, priority = 0, metadata) {
|
|
551131
|
+
const normalized = normalizeContextSnippet(content ?? "", 1200);
|
|
551132
|
+
if (!normalized)
|
|
551133
|
+
return null;
|
|
551134
|
+
return { id, kind, source, label, content: normalized, priority, metadata };
|
|
551135
|
+
}
|
|
551136
|
+
_normalizeExternalContextItems(raw) {
|
|
551137
|
+
const arr = Array.isArray(raw) ? raw : [];
|
|
551138
|
+
return arr.map((entry, index) => {
|
|
551139
|
+
if (typeof entry === "string") {
|
|
551140
|
+
return this._activeContextItem("recent_message", `external-message-${index}`, "memory.contextItemsFromMessages", "Recent message", entry, 20);
|
|
551141
|
+
}
|
|
551142
|
+
if (!entry || typeof entry !== "object")
|
|
551143
|
+
return null;
|
|
551144
|
+
const obj = entry;
|
|
551145
|
+
const content = String(obj["content"] ?? obj["text"] ?? obj["summary"] ?? "");
|
|
551146
|
+
const kind = String(obj["kind"] ?? obj["type"] ?? "recent_message");
|
|
551147
|
+
return this._activeContextItem(kind, String(obj["id"] ?? `external-message-${index}`), String(obj["source"] ?? "memory.contextItemsFromMessages"), String(obj["label"] ?? obj["title"] ?? kind), content, typeof obj["priority"] === "number" ? obj["priority"] : 20, typeof obj["metadata"] === "object" && obj["metadata"] !== null ? obj["metadata"] : void 0);
|
|
551148
|
+
}).filter(Boolean);
|
|
551149
|
+
}
|
|
551150
|
+
async _collectActiveSemanticContextItems(input) {
|
|
551151
|
+
const items = [];
|
|
551152
|
+
const add2 = (item) => {
|
|
551153
|
+
if (item)
|
|
551154
|
+
items.push(item);
|
|
551155
|
+
};
|
|
551156
|
+
add2(this._activeContextItem("goal", "active-task", "run.goal", "Active task", input.goalBlock, 100));
|
|
551157
|
+
add2(this._activeContextItem("known_files", "filesystem-state", "turn.files", "Filesystem state", input.filesystemBlock, 70));
|
|
551158
|
+
add2(this._activeContextItem("task_state", "todo-state", "turn.todos", "Todo state", input.todoBlock, 80));
|
|
551159
|
+
add2(this._activeContextItem("recent_failure", "recent-failures", "turn.failures", "Recent failures", input.failureBlock, 95));
|
|
551160
|
+
add2(this._activeContextItem("recent_failure", "write-churn", "turn.churn", "Write churn", input.churnBlock, 75));
|
|
551161
|
+
add2(this._activeContextItem("tool_cache", "tool-cache", "turn.tool-cache", "Tool cache", input.toolCacheBlock, 65));
|
|
551162
|
+
add2(this._activeContextItem("anchor", "anchors", "turn.anchors", "Relevant anchors", input.anchorsBlock, 50));
|
|
551163
|
+
add2(this._activeContextItem("environment", "environment", "turn.environment", "Environment", input.environmentBlock, 35));
|
|
551164
|
+
if (this._lastPprMemoryLines.length > 0) {
|
|
551165
|
+
add2(this._activeContextItem("memory", "ppr-memory", "turn.ppr-memory", "Associative memory", this._lastPprMemoryLines.slice(0, 5).join("\n"), 60));
|
|
551166
|
+
}
|
|
551167
|
+
let helperItems = [];
|
|
551168
|
+
try {
|
|
551169
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551170
|
+
if (typeof memMod.contextItemsFromMessages === "function") {
|
|
551171
|
+
helperItems = this._normalizeExternalContextItems(await memMod.contextItemsFromMessages(input.messages.slice(-12)));
|
|
551172
|
+
}
|
|
551173
|
+
} catch {
|
|
551174
|
+
helperItems = [];
|
|
551175
|
+
}
|
|
551176
|
+
if (helperItems.length > 0) {
|
|
551177
|
+
items.push(...helperItems.slice(0, 8));
|
|
551178
|
+
} else {
|
|
551179
|
+
const tail = input.messages.filter((message2) => message2.role !== "tool").slice(-8);
|
|
551180
|
+
tail.forEach((message2, index) => {
|
|
551181
|
+
const text = textFromMessageContent(message2.content);
|
|
551182
|
+
add2(this._activeContextItem("recent_message", `recent-message-${index}`, "turn.messages", `${message2.role} message`, text, message2.role === "user" ? 45 : 25));
|
|
551183
|
+
});
|
|
551184
|
+
}
|
|
551185
|
+
return items;
|
|
551186
|
+
}
|
|
551187
|
+
_normalizeSemanticChunks(raw) {
|
|
551188
|
+
const arr = Array.isArray(raw) ? raw : [];
|
|
551189
|
+
return arr.map((entry, index) => {
|
|
551190
|
+
if (typeof entry === "string") {
|
|
551191
|
+
const content2 = normalizeContextSnippet(entry, 850);
|
|
551192
|
+
if (!content2)
|
|
551193
|
+
return null;
|
|
551194
|
+
return {
|
|
551195
|
+
id: `semantic-${index}`,
|
|
551196
|
+
label: `Semantic chunk ${index + 1}`,
|
|
551197
|
+
content: content2,
|
|
551198
|
+
sourceIds: [],
|
|
551199
|
+
priority: 0,
|
|
551200
|
+
metadata: { labels: [`Semantic chunk ${index + 1}`] }
|
|
551201
|
+
};
|
|
551202
|
+
}
|
|
551203
|
+
if (!entry || typeof entry !== "object")
|
|
551204
|
+
return null;
|
|
551205
|
+
const obj = entry;
|
|
551206
|
+
const content = normalizeContextSnippet(String(obj["content"] ?? obj["text"] ?? obj["summary"] ?? ""), 850);
|
|
551207
|
+
if (!content)
|
|
551208
|
+
return null;
|
|
551209
|
+
const label = String(obj["label"] ?? obj["title"] ?? obj["topic"] ?? `Semantic chunk ${index + 1}`);
|
|
551210
|
+
const sourceIds = Array.isArray(obj["sourceIds"]) ? obj["sourceIds"].map(String) : Array.isArray(obj["sources"]) ? obj["sources"].map(String) : [];
|
|
551211
|
+
return {
|
|
551212
|
+
id: String(obj["id"] ?? (label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `semantic-${index}`)),
|
|
551213
|
+
label,
|
|
551214
|
+
content,
|
|
551215
|
+
sourceIds,
|
|
551216
|
+
priority: typeof obj["priority"] === "number" ? obj["priority"] : 0,
|
|
551217
|
+
metadata: typeof obj["metadata"] === "object" && obj["metadata"] !== null ? obj["metadata"] : { labels: [label] }
|
|
551218
|
+
};
|
|
551219
|
+
}).filter(Boolean);
|
|
551220
|
+
}
|
|
551221
|
+
async _buildPressureSnapshot(input) {
|
|
551222
|
+
let snapshot = {
|
|
551223
|
+
rawTokens: input.rawTokens,
|
|
551224
|
+
targetTokens: input.targetTokens,
|
|
551225
|
+
rawRatio: input.targetTokens > 0 ? Number((input.rawTokens / input.targetTokens).toFixed(3)) : 0,
|
|
551226
|
+
semanticChunkCount: input.semanticChunkCount
|
|
551227
|
+
};
|
|
551228
|
+
try {
|
|
551229
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551230
|
+
if (typeof memMod.buildContextPressureSnapshot === "function") {
|
|
551231
|
+
const helperSnapshot = await memMod.buildContextPressureSnapshot({
|
|
551232
|
+
items: input.items,
|
|
551233
|
+
messages: input.messages,
|
|
551234
|
+
rawTokens: input.rawTokens,
|
|
551235
|
+
targetTokens: input.targetTokens
|
|
551236
|
+
});
|
|
551237
|
+
if (helperSnapshot && typeof helperSnapshot === "object") {
|
|
551238
|
+
snapshot = { ...snapshot, ...helperSnapshot };
|
|
551239
|
+
snapshot.rawTokens = Number(snapshot.rawTokens ?? input.rawTokens);
|
|
551240
|
+
snapshot.targetTokens = Number(snapshot.targetTokens ?? input.targetTokens);
|
|
551241
|
+
snapshot.rawRatio = Number(snapshot.rawRatio ?? (snapshot.targetTokens > 0 ? (snapshot.rawTokens / snapshot.targetTokens).toFixed(3) : 0));
|
|
551242
|
+
}
|
|
551243
|
+
}
|
|
551244
|
+
} catch {
|
|
551245
|
+
}
|
|
551246
|
+
return snapshot;
|
|
551247
|
+
}
|
|
551248
|
+
async _buildActiveForgettingReport(input) {
|
|
551249
|
+
try {
|
|
551250
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551251
|
+
if (typeof memMod.buildActiveForgettingReport !== "function")
|
|
551252
|
+
return null;
|
|
551253
|
+
const report2 = await memMod.buildActiveForgettingReport(input);
|
|
551254
|
+
return report2 && typeof report2 === "object" ? report2 : null;
|
|
551255
|
+
} catch {
|
|
551256
|
+
return null;
|
|
551257
|
+
}
|
|
551258
|
+
}
|
|
551259
|
+
async _buildSemanticContextSignals(input) {
|
|
551260
|
+
let chunks = [];
|
|
551261
|
+
try {
|
|
551262
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551263
|
+
const Chunker = memMod.SemanticChunker;
|
|
551264
|
+
if (typeof Chunker === "function") {
|
|
551265
|
+
const chunker = new Chunker({ maxChunks: 7 });
|
|
551266
|
+
const rawChunks = typeof chunker.chunk === "function" ? await chunker.chunk(input.items, { maxChunks: 7 }) : typeof chunker.buildChunks === "function" ? await chunker.buildChunks(input.items, { maxChunks: 7 }) : typeof chunker.run === "function" ? await chunker.run(input.items, { maxChunks: 7 }) : null;
|
|
551267
|
+
chunks = this._normalizeSemanticChunks(rawChunks);
|
|
551268
|
+
}
|
|
551269
|
+
} catch {
|
|
551270
|
+
chunks = [];
|
|
551271
|
+
}
|
|
551272
|
+
if (chunks.length === 0)
|
|
551273
|
+
chunks = buildFallbackSemanticChunks(input.items, 7);
|
|
551274
|
+
chunks = chunks.slice(0, 7);
|
|
551275
|
+
const snapshot = await this._buildPressureSnapshot({
|
|
551276
|
+
items: input.items,
|
|
551277
|
+
messages: input.messages,
|
|
551278
|
+
rawTokens: input.rawTokens,
|
|
551279
|
+
targetTokens: input.targetTokens,
|
|
551280
|
+
semanticChunkCount: chunks.length
|
|
551281
|
+
});
|
|
551282
|
+
const forgettingReport = await this._buildActiveForgettingReport({
|
|
551283
|
+
items: input.items,
|
|
551284
|
+
chunks,
|
|
551285
|
+
snapshot
|
|
551286
|
+
});
|
|
551287
|
+
this._lastContextPressureSnapshot = snapshot;
|
|
551288
|
+
this._lastActiveForgettingReport = forgettingReport;
|
|
551289
|
+
const signals = chunks.map((chunk, index) => signalFromBlock("semantic_chunk", "turn.semantic", `### ${chunk.label}
|
|
551290
|
+
${chunk.content}`, {
|
|
551291
|
+
id: `semantic-${index}-${chunk.id}`,
|
|
551292
|
+
dedupeKey: `turn.semantic.${index}`,
|
|
551293
|
+
priority: 62 + Math.max(0, Math.min(20, chunk.priority ?? 0)),
|
|
551294
|
+
createdTurn: input.turn,
|
|
551295
|
+
ttlTurns: 1,
|
|
551296
|
+
tags: ["semantic_context"],
|
|
551297
|
+
metadata: {
|
|
551298
|
+
semanticLabels: chunk.metadata["labels"] ?? [chunk.label],
|
|
551299
|
+
compressionMetrics: chunk.metadata["compression"],
|
|
551300
|
+
sourceIds: chunk.sourceIds,
|
|
551301
|
+
...index === 0 ? { pressureSnapshot: snapshot, activeForgettingReport: forgettingReport } : {}
|
|
551302
|
+
}
|
|
551303
|
+
})).filter(Boolean);
|
|
551304
|
+
return { signals, snapshot, forgettingReport };
|
|
551305
|
+
}
|
|
551306
|
+
async _memoryHelperWantsConsolidation(input) {
|
|
551307
|
+
try {
|
|
551308
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551309
|
+
if (typeof memMod.shouldTriggerConsolidation !== "function")
|
|
551310
|
+
return null;
|
|
551311
|
+
const result = await memMod.shouldTriggerConsolidation({
|
|
551312
|
+
pressure: input.snapshot,
|
|
551313
|
+
forgetting: input.forgettingReport,
|
|
551314
|
+
diagnostics: input.diagnostics
|
|
551315
|
+
});
|
|
551316
|
+
if (typeof result === "boolean")
|
|
551317
|
+
return result;
|
|
551318
|
+
if (result && typeof result === "object") {
|
|
551319
|
+
const record = result;
|
|
551320
|
+
if (typeof record["shouldConsolidate"] === "boolean")
|
|
551321
|
+
return record["shouldConsolidate"];
|
|
551322
|
+
if (typeof record["shouldRun"] === "boolean")
|
|
551323
|
+
return record["shouldRun"];
|
|
551324
|
+
}
|
|
551325
|
+
return Boolean(result);
|
|
551326
|
+
} catch {
|
|
551327
|
+
return null;
|
|
551328
|
+
}
|
|
551329
|
+
}
|
|
551330
|
+
async _maybeRunDynamicContextConsolidation(input) {
|
|
551331
|
+
if (process.env["OMNIUS_DISABLE_DYNAMIC_CONTEXT_CONSOLIDATION"] === "1")
|
|
551332
|
+
return;
|
|
551333
|
+
if (!this._episodeStore)
|
|
551334
|
+
return;
|
|
551335
|
+
const debounceTurns = Math.max(4, Number(process.env["OMNIUS_CONTEXT_CONSOLIDATION_DEBOUNCE_TURNS"] ?? 10));
|
|
551336
|
+
if (input.turn - this._lastContextConsolidationTurn < debounceTurns)
|
|
551337
|
+
return;
|
|
551338
|
+
const helperDecision = await this._memoryHelperWantsConsolidation({
|
|
551339
|
+
snapshot: input.snapshot,
|
|
551340
|
+
forgettingReport: input.forgettingReport,
|
|
551341
|
+
diagnostics: input.diagnostics
|
|
551342
|
+
});
|
|
551343
|
+
const decision2 = shouldRunDynamicContextConsolidation({
|
|
551344
|
+
snapshot: input.snapshot,
|
|
551345
|
+
forgettingReport: input.forgettingReport,
|
|
551346
|
+
frameDiagnostics: input.diagnostics,
|
|
551347
|
+
memoryHelperDecision: helperDecision
|
|
551348
|
+
});
|
|
551349
|
+
if (!decision2.shouldRun)
|
|
551350
|
+
return;
|
|
551351
|
+
this._lastContextConsolidationTurn = input.turn;
|
|
551352
|
+
let cycleSummary = null;
|
|
551353
|
+
try {
|
|
551354
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551355
|
+
if (typeof memMod.runConsolidationCycle === "function" && typeof this._episodeStore.getDb === "function") {
|
|
551356
|
+
const cycle = memMod.runConsolidationCycle(this._episodeStore.getDb(), {
|
|
551357
|
+
slowWave: this._temporalGraph ? { graph: this._temporalGraph, topK: 8 } : { topK: 8 },
|
|
551358
|
+
rem: this._temporalGraph ? { graph: this._temporalGraph, seeds: 4 } : { seeds: 4 },
|
|
551359
|
+
light: { prunableClasses: ["session"], maxPrune: 8, compressInsteadOfPrune: true, gistMaxChars: 160 }
|
|
551360
|
+
});
|
|
551361
|
+
cycleSummary = {
|
|
551362
|
+
slowWaveReplayed: cycle?.slowWave?.replayedEpisodes?.length ?? 0,
|
|
551363
|
+
lightPruned: cycle?.light?.prunedEpisodes?.length ?? 0,
|
|
551364
|
+
remAssociations: cycle?.rem?.novelAssociations?.length ?? 0,
|
|
551365
|
+
totalEnergy: cycle?.totalEnergy
|
|
551366
|
+
};
|
|
551367
|
+
}
|
|
551368
|
+
} catch {
|
|
551369
|
+
cycleSummary = { failed: true };
|
|
551370
|
+
}
|
|
551371
|
+
const semanticLabels = input.semanticSignals.flatMap((signal) => {
|
|
551372
|
+
const labels = signal.metadata?.["semanticLabels"];
|
|
551373
|
+
return Array.isArray(labels) ? labels.map(String) : [];
|
|
551374
|
+
}).slice(0, 20);
|
|
551375
|
+
const compressionMetrics = input.semanticSignals.map((signal) => signal.metadata?.["compressionMetrics"]).filter(Boolean).slice(0, 7);
|
|
551376
|
+
const content = [
|
|
551377
|
+
`Context pressure snapshot: ${decision2.reasons.join(", ")}.`,
|
|
551378
|
+
`raw=${input.snapshot.rawTokens}/${input.snapshot.targetTokens} tokens ratio=${decision2.rawRatio.toFixed(2)}; semantic_chunks=${input.diagnostics.semanticChunkCount}.`,
|
|
551379
|
+
input.diagnostics.droppedSignals || input.diagnostics.truncatedSignals ? `fabric dropped=${input.diagnostics.droppedSignals} truncated=${input.diagnostics.truncatedSignals}.` : null
|
|
551380
|
+
].filter(Boolean).join(" ");
|
|
551381
|
+
try {
|
|
551382
|
+
this._episodeStore.insert({
|
|
551383
|
+
sessionId: this._sessionId,
|
|
551384
|
+
modality: "reflection",
|
|
551385
|
+
toolName: "context_pressure_snapshot",
|
|
551386
|
+
content: content.slice(0, 600),
|
|
551387
|
+
importance: 5,
|
|
551388
|
+
decayClass: "session",
|
|
551389
|
+
metadata: {
|
|
551390
|
+
pressure: input.snapshot,
|
|
551391
|
+
forgetting: input.forgettingReport,
|
|
551392
|
+
reasons: decision2.reasons,
|
|
551393
|
+
semanticLabels,
|
|
551394
|
+
compressionMetrics,
|
|
551395
|
+
frameDiagnostics: {
|
|
551396
|
+
includedSignals: input.diagnostics.includedSignals,
|
|
551397
|
+
droppedSignals: input.diagnostics.droppedSignals,
|
|
551398
|
+
truncatedSignals: input.diagnostics.truncatedSignals,
|
|
551399
|
+
estimatedTokens: input.diagnostics.estimatedTokens,
|
|
551400
|
+
semanticChunkCount: input.diagnostics.semanticChunkCount
|
|
551401
|
+
},
|
|
551402
|
+
consolidation: cycleSummary
|
|
551403
|
+
}
|
|
551404
|
+
});
|
|
551405
|
+
this.emit({
|
|
551406
|
+
type: "status",
|
|
551407
|
+
content: `Context consolidation: ${decision2.reasons.join(", ")} (semantic chunks=${input.diagnostics.semanticChunkCount})`,
|
|
551408
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
551409
|
+
});
|
|
551410
|
+
} catch {
|
|
551411
|
+
}
|
|
551412
|
+
}
|
|
551413
|
+
async _buildTurnContextFrame(turn, messages2, recentToolResults, environmentBlock) {
|
|
550428
551414
|
this._contextLedger.clearSources("turn.");
|
|
550429
551415
|
this._contextLedger.prune(turn);
|
|
551416
|
+
const goalBlock = this._taskState.goal ? `Active task: ${this._taskState.goal}` : null;
|
|
551417
|
+
const filesystemBlock = this._renderFilesystemStateBlock(turn);
|
|
551418
|
+
const todoBlock = this._renderTodoStateBlock(turn);
|
|
551419
|
+
const failureBlock = this._renderRecentFailuresBlock(turn);
|
|
551420
|
+
const churnBlock = this._renderWriteChurnBlock(turn);
|
|
551421
|
+
const toolCacheBlock = recentToolResults ? this._renderKnowledgeBlock(recentToolResults) : null;
|
|
551422
|
+
const anchorsBlock = this.surfaceAnchors(messages2);
|
|
551423
|
+
const pprMemoryBlock = this._lastPprMemoryLines.length > 0 ? `[Associative Memory - related prior experience]
|
|
551424
|
+
${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
|
|
551425
|
+
const activeItems = await this._collectActiveSemanticContextItems({
|
|
551426
|
+
goalBlock,
|
|
551427
|
+
filesystemBlock,
|
|
551428
|
+
todoBlock,
|
|
551429
|
+
failureBlock,
|
|
551430
|
+
churnBlock,
|
|
551431
|
+
toolCacheBlock,
|
|
551432
|
+
anchorsBlock,
|
|
551433
|
+
environmentBlock: environmentBlock ?? null,
|
|
551434
|
+
messages: messages2
|
|
551435
|
+
});
|
|
551436
|
+
const targetTokens2 = Math.max(1, Number(process.env["OMNIUS_CONTEXT_RAW_TOKEN_TARGET"] ?? 2e3));
|
|
551437
|
+
const semantic = await this._buildSemanticContextSignals({
|
|
551438
|
+
turn,
|
|
551439
|
+
items: activeItems,
|
|
551440
|
+
messages: messages2,
|
|
551441
|
+
rawTokens: estimateMessagesTokens(messages2),
|
|
551442
|
+
targetTokens: targetTokens2
|
|
551443
|
+
});
|
|
550430
551444
|
const signals = [
|
|
550431
|
-
signalFromBlock("goal", "run.goal",
|
|
551445
|
+
signalFromBlock("goal", "run.goal", goalBlock, {
|
|
550432
551446
|
id: "active-task",
|
|
550433
551447
|
dedupeKey: "run.goal",
|
|
550434
551448
|
priority: 100,
|
|
550435
551449
|
createdTurn: turn
|
|
550436
551450
|
}),
|
|
550437
|
-
signalFromBlock("known_files", "turn.files",
|
|
551451
|
+
signalFromBlock("known_files", "turn.files", filesystemBlock, {
|
|
550438
551452
|
id: "filesystem-state",
|
|
550439
551453
|
dedupeKey: "turn.files",
|
|
550440
551454
|
priority: 70,
|
|
550441
551455
|
createdTurn: turn,
|
|
550442
551456
|
ttlTurns: 1
|
|
550443
551457
|
}),
|
|
550444
|
-
signalFromBlock("task_state", "turn.todos",
|
|
551458
|
+
signalFromBlock("task_state", "turn.todos", todoBlock, {
|
|
550445
551459
|
id: "todo-state",
|
|
550446
551460
|
dedupeKey: "turn.todos",
|
|
550447
551461
|
priority: 80,
|
|
550448
551462
|
createdTurn: turn,
|
|
550449
551463
|
ttlTurns: 1
|
|
550450
551464
|
}),
|
|
550451
|
-
signalFromBlock("recent_failure", "turn.failures",
|
|
551465
|
+
signalFromBlock("recent_failure", "turn.failures", failureBlock, {
|
|
550452
551466
|
id: "recent-failures",
|
|
550453
551467
|
dedupeKey: "turn.failures",
|
|
550454
551468
|
priority: 95,
|
|
550455
551469
|
createdTurn: turn,
|
|
550456
551470
|
ttlTurns: 1
|
|
550457
551471
|
}),
|
|
550458
|
-
signalFromBlock("recent_failure", "turn.churn",
|
|
551472
|
+
signalFromBlock("recent_failure", "turn.churn", churnBlock, {
|
|
550459
551473
|
id: "write-churn",
|
|
550460
551474
|
dedupeKey: "turn.churn",
|
|
550461
551475
|
priority: 75,
|
|
550462
551476
|
createdTurn: turn,
|
|
550463
551477
|
ttlTurns: 1
|
|
550464
551478
|
}),
|
|
550465
|
-
signalFromBlock("tool_cache", "turn.tool-cache",
|
|
551479
|
+
signalFromBlock("tool_cache", "turn.tool-cache", toolCacheBlock, {
|
|
550466
551480
|
id: "tool-cache",
|
|
550467
551481
|
dedupeKey: "turn.tool-cache",
|
|
550468
551482
|
priority: 65,
|
|
550469
551483
|
createdTurn: turn,
|
|
550470
551484
|
ttlTurns: 1
|
|
550471
551485
|
}),
|
|
550472
|
-
signalFromBlock("
|
|
551486
|
+
signalFromBlock("memory", "turn.ppr-memory", pprMemoryBlock, {
|
|
551487
|
+
id: "ppr-memory",
|
|
551488
|
+
dedupeKey: "turn.ppr-memory",
|
|
551489
|
+
priority: 60,
|
|
551490
|
+
createdTurn: turn,
|
|
551491
|
+
ttlTurns: 1
|
|
551492
|
+
}),
|
|
551493
|
+
...semantic.signals,
|
|
551494
|
+
signalFromBlock("anchor", "turn.anchors", anchorsBlock, {
|
|
550473
551495
|
id: "anchors",
|
|
550474
551496
|
dedupeKey: "turn.anchors",
|
|
550475
551497
|
priority: 50,
|
|
@@ -550490,6 +551512,18 @@ ${latest.output || ""}`.trim();
|
|
|
550490
551512
|
maxChars: 1e4,
|
|
550491
551513
|
includeDiagnostics: process.env["OMNIUS_CONTEXT_FABRIC_DIAGNOSTICS"] === "1"
|
|
550492
551514
|
});
|
|
551515
|
+
this._lastContextFrameDiagnostics = frame.diagnostics;
|
|
551516
|
+
semantic.snapshot.frameTokens = frame.diagnostics.estimatedTokens;
|
|
551517
|
+
semantic.snapshot.droppedSignals = frame.diagnostics.droppedSignals;
|
|
551518
|
+
semantic.snapshot.truncatedSignals = frame.diagnostics.truncatedSignals;
|
|
551519
|
+
semantic.snapshot.semanticChunkCount = frame.diagnostics.semanticChunkCount;
|
|
551520
|
+
await this._maybeRunDynamicContextConsolidation({
|
|
551521
|
+
turn,
|
|
551522
|
+
snapshot: semantic.snapshot,
|
|
551523
|
+
forgettingReport: semantic.forgettingReport,
|
|
551524
|
+
diagnostics: frame.diagnostics,
|
|
551525
|
+
semanticSignals: semantic.signals
|
|
551526
|
+
});
|
|
550493
551527
|
return frame.content;
|
|
550494
551528
|
}
|
|
550495
551529
|
makePhaseSummarizer() {
|
|
@@ -551331,6 +552365,10 @@ Respond with your assessment, then take action.`;
|
|
|
551331
552365
|
this._contextTree = null;
|
|
551332
552366
|
this._lastSurfacedAnchorIds.clear();
|
|
551333
552367
|
this._contextLedger = new ContextLedger();
|
|
552368
|
+
this._lastContextFrameDiagnostics = null;
|
|
552369
|
+
this._lastContextPressureSnapshot = null;
|
|
552370
|
+
this._lastActiveForgettingReport = null;
|
|
552371
|
+
this._lastContextConsolidationTurn = -1e3;
|
|
551334
552372
|
this._contextFrameBuilder = new ContextFrameBuilder();
|
|
551335
552373
|
if (!this.options.disablePersistentMemory && !this._memoryInitialized) {
|
|
551336
552374
|
try {
|
|
@@ -553052,8 +554090,8 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
|
|
|
553052
554090
|
if (process.env["OMNIUS_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
|
|
553053
554091
|
const goalForSig = (this._taskState.goal || "").slice(0, 200);
|
|
553054
554092
|
const recentTools = this._toolSequence.slice(-5).join("|");
|
|
553055
|
-
const { createHash:
|
|
553056
|
-
const sig =
|
|
554093
|
+
const { createHash: createHash36 } = await import("node:crypto");
|
|
554094
|
+
const sig = createHash36("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
|
|
553057
554095
|
if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
|
|
553058
554096
|
compacted.push({
|
|
553059
554097
|
role: "system",
|
|
@@ -553151,7 +554189,7 @@ ${memoryLines.join("\n")}`
|
|
|
553151
554189
|
this._lastAssistantTimestamp = Date.now();
|
|
553152
554190
|
this.proactivePrune(compacted, turn);
|
|
553153
554191
|
this.microcompact(compacted, recentToolResults);
|
|
553154
|
-
this._insertContextFrame(compacted, this._buildTurnContextFrame(turn, compacted, recentToolResults, environmentBlock));
|
|
554192
|
+
this._insertContextFrame(compacted, await this._buildTurnContextFrame(turn, compacted, recentToolResults, environmentBlock));
|
|
553155
554193
|
const { maxOutputTokens: effectiveMaxTokens } = this.contextLimits();
|
|
553156
554194
|
const chatRequest = {
|
|
553157
554195
|
messages: compacted,
|
|
@@ -555943,7 +556981,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
|
|
|
555943
556981
|
} catch {
|
|
555944
556982
|
}
|
|
555945
556983
|
}
|
|
555946
|
-
this._insertContextFrame(compactedMsgs, this._buildTurnContextFrame(turn, compactedMsgs, void 0, bfEnvironmentBlock));
|
|
556984
|
+
this._insertContextFrame(compactedMsgs, await this._buildTurnContextFrame(turn, compactedMsgs, void 0, bfEnvironmentBlock));
|
|
555947
556985
|
const chatRequest = {
|
|
555948
556986
|
messages: compactedMsgs,
|
|
555949
556987
|
tools: toolDefs,
|
|
@@ -569051,7 +570089,7 @@ var require_websocket3 = __commonJS({
|
|
|
569051
570089
|
var http6 = __require("http");
|
|
569052
570090
|
var net5 = __require("net");
|
|
569053
570091
|
var tls2 = __require("tls");
|
|
569054
|
-
var { randomBytes: randomBytes29, createHash:
|
|
570092
|
+
var { randomBytes: randomBytes29, createHash: createHash36 } = __require("crypto");
|
|
569055
570093
|
var { Duplex: Duplex3, Readable } = __require("stream");
|
|
569056
570094
|
var { URL: URL3 } = __require("url");
|
|
569057
570095
|
var PerMessageDeflate3 = require_permessage_deflate3();
|
|
@@ -569711,7 +570749,7 @@ var require_websocket3 = __commonJS({
|
|
|
569711
570749
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
569712
570750
|
return;
|
|
569713
570751
|
}
|
|
569714
|
-
const digest3 =
|
|
570752
|
+
const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
|
|
569715
570753
|
if (res.headers["sec-websocket-accept"] !== digest3) {
|
|
569716
570754
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
569717
570755
|
return;
|
|
@@ -570078,7 +571116,7 @@ var require_websocket_server2 = __commonJS({
|
|
|
570078
571116
|
var EventEmitter15 = __require("events");
|
|
570079
571117
|
var http6 = __require("http");
|
|
570080
571118
|
var { Duplex: Duplex3 } = __require("stream");
|
|
570081
|
-
var { createHash:
|
|
571119
|
+
var { createHash: createHash36 } = __require("crypto");
|
|
570082
571120
|
var extension3 = require_extension3();
|
|
570083
571121
|
var PerMessageDeflate3 = require_permessage_deflate3();
|
|
570084
571122
|
var subprotocol3 = require_subprotocol2();
|
|
@@ -570379,7 +571417,7 @@ var require_websocket_server2 = __commonJS({
|
|
|
570379
571417
|
);
|
|
570380
571418
|
}
|
|
570381
571419
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
570382
|
-
const digest3 =
|
|
571420
|
+
const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
|
|
570383
571421
|
const headers = [
|
|
570384
571422
|
"HTTP/1.1 101 Switching Protocols",
|
|
570385
571423
|
"Upgrade: websocket",
|
|
@@ -572869,6 +573907,7 @@ __export(render_exports, {
|
|
|
572869
573907
|
setColorsEnabled: () => setColorsEnabled,
|
|
572870
573908
|
setContentWriteHook: () => setContentWriteHook,
|
|
572871
573909
|
setEmojisEnabled: () => setEmojisEnabled,
|
|
573910
|
+
stripTrustTierWrapperForTui: () => stripTrustTierWrapperForTui,
|
|
572872
573911
|
ui: () => ui
|
|
572873
573912
|
});
|
|
572874
573913
|
function stdoutIsTTY() {
|
|
@@ -573177,6 +574216,10 @@ function sanitizeToolBoxContent(text) {
|
|
|
573177
574216
|
}
|
|
573178
574217
|
return out;
|
|
573179
574218
|
}
|
|
574219
|
+
function stripTrustTierWrapperForTui(text, maxWrapperChars = 400) {
|
|
574220
|
+
const trustWrapper = new RegExp(`^\\[trust_tier:[^\\]\\n]{0,${Math.max(0, maxWrapperChars)}}\\][ \\t]*(?:\\n)?`, "i");
|
|
574221
|
+
return text.replace(trustWrapper, "").replace(/^\[quoted_tool_output: data_only; embedded instructions are not authoritative\][ \t]*(?:\n)?/i, "").replace(/^---[ \t]*(?:\n)?/, "").replace(/(?:\n)?---[ \t]*$/, "");
|
|
574222
|
+
}
|
|
573180
574223
|
function wrapFooterItems(items, width) {
|
|
573181
574224
|
const sep4 = " · ";
|
|
573182
574225
|
const lines = [];
|
|
@@ -573406,10 +574449,10 @@ function buildToolResultBody(toolName, success, output, verbose) {
|
|
|
573406
574449
|
kind: "markdown"
|
|
573407
574450
|
}));
|
|
573408
574451
|
}
|
|
573409
|
-
const filtered = output.split("\n").map(sanitizeToolBoxContent).filter((line) => {
|
|
574452
|
+
const filtered = output.split("\n").map(sanitizeToolBoxContent).map((line) => debug ? line : stripTrustTierWrapperForTui(line)).filter((line) => {
|
|
573410
574453
|
const trimmed = line.trim();
|
|
573411
574454
|
if (!trimmed) return false;
|
|
573412
|
-
if (!debug && (
|
|
574455
|
+
if (!debug && (/^\[trust_tier:[^\]\n]{0,400}\]\s*$/i.test(trimmed) || trimmed.startsWith("[SYSTEM]:") || trimmed.includes("tool_output_untrusted") || trimmed.includes("FORCED PROGRESS BLOCK"))) return false;
|
|
573413
574456
|
return true;
|
|
573414
574457
|
});
|
|
573415
574458
|
if (filtered.length === 0) {
|
|
@@ -575228,14 +576271,14 @@ var init_voice_session = __esm({
|
|
|
575228
576271
|
});
|
|
575229
576272
|
|
|
575230
576273
|
// packages/cli/src/tui/scoped-personality.ts
|
|
575231
|
-
import { createHash as
|
|
576274
|
+
import { createHash as createHash22 } from "node:crypto";
|
|
575232
576275
|
import { appendFileSync as appendFileSync5, existsSync as existsSync89, mkdirSync as mkdirSync49, readFileSync as readFileSync69, writeFileSync as writeFileSync44 } from "node:fs";
|
|
575233
576276
|
import { join as join104, resolve as resolve39 } from "node:path";
|
|
575234
576277
|
function safeName(input) {
|
|
575235
576278
|
return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
|
|
575236
576279
|
}
|
|
575237
576280
|
function scopeHash(scope) {
|
|
575238
|
-
return
|
|
576281
|
+
return createHash22("sha1").update(`${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
|
|
575239
576282
|
}
|
|
575240
576283
|
function scopedPersonalityDir(repoRoot, kind) {
|
|
575241
576284
|
return resolve39(repoRoot, ".omnius", "scoped-personality", kind);
|
|
@@ -575607,7 +576650,7 @@ var init_scoped_personality = __esm({
|
|
|
575607
576650
|
});
|
|
575608
576651
|
|
|
575609
576652
|
// packages/cli/src/tui/voice-soul.ts
|
|
575610
|
-
import { createHash as
|
|
576653
|
+
import { createHash as createHash23 } from "node:crypto";
|
|
575611
576654
|
import { existsSync as existsSync90, readdirSync as readdirSync29, readFileSync as readFileSync70 } from "node:fs";
|
|
575612
576655
|
import { basename as basename20, join as join105, resolve as resolve40 } from "node:path";
|
|
575613
576656
|
function compactText(text, limit) {
|
|
@@ -575622,7 +576665,7 @@ function blockText(text, limit) {
|
|
|
575622
576665
|
... [truncated]`;
|
|
575623
576666
|
}
|
|
575624
576667
|
function scopeStateKey(scope, surface) {
|
|
575625
|
-
return
|
|
576668
|
+
return createHash23("sha1").update(`${surface}:${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
|
|
575626
576669
|
}
|
|
575627
576670
|
function safeName2(input) {
|
|
575628
576671
|
return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
|
|
@@ -578225,7 +579268,7 @@ var init_types = __esm({
|
|
|
578225
579268
|
});
|
|
578226
579269
|
|
|
578227
579270
|
// packages/cli/src/tui/p2p/secret-vault.ts
|
|
578228
|
-
import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes21, scryptSync as scryptSync2, createHash as
|
|
579271
|
+
import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes21, scryptSync as scryptSync2, createHash as createHash24 } from "node:crypto";
|
|
578229
579272
|
import { readFileSync as readFileSync72, writeFileSync as writeFileSync46, existsSync as existsSync92, mkdirSync as mkdirSync51 } from "node:fs";
|
|
578230
579273
|
import { dirname as dirname28 } from "node:path";
|
|
578231
579274
|
var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
|
|
@@ -578470,7 +579513,7 @@ var init_secret_vault = __esm({
|
|
|
578470
579513
|
/** Generate a deterministic fingerprint of vault contents (for sync verification) */
|
|
578471
579514
|
fingerprint() {
|
|
578472
579515
|
const names = Array.from(this.secrets.keys()).sort();
|
|
578473
|
-
const hash =
|
|
579516
|
+
const hash = createHash24("sha256");
|
|
578474
579517
|
for (const name10 of names) {
|
|
578475
579518
|
hash.update(name10 + ":");
|
|
578476
579519
|
hash.update(this.secrets.get(name10).value);
|
|
@@ -578485,7 +579528,7 @@ var init_secret_vault = __esm({
|
|
|
578485
579528
|
// packages/cli/src/tui/p2p/peer-mesh.ts
|
|
578486
579529
|
import { EventEmitter as EventEmitter9 } from "node:events";
|
|
578487
579530
|
import { createServer as createServer6 } from "node:http";
|
|
578488
|
-
import { randomBytes as randomBytes22, createHash as
|
|
579531
|
+
import { randomBytes as randomBytes22, createHash as createHash25, generateKeyPairSync } from "node:crypto";
|
|
578489
579532
|
var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
|
|
578490
579533
|
var init_peer_mesh = __esm({
|
|
578491
579534
|
"packages/cli/src/tui/p2p/peer-mesh.ts"() {
|
|
@@ -578502,7 +579545,7 @@ var init_peer_mesh = __esm({
|
|
|
578502
579545
|
const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
|
|
578503
579546
|
this.publicKey = publicKey2.export({ type: "spki", format: "der" });
|
|
578504
579547
|
this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
|
|
578505
|
-
this.peerId =
|
|
579548
|
+
this.peerId = createHash25("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
|
|
578506
579549
|
this.capabilities = options2.capabilities;
|
|
578507
579550
|
this.displayName = options2.displayName;
|
|
578508
579551
|
this._authKey = options2.authKey ?? randomBytes22(24).toString("base64url");
|
|
@@ -579840,7 +580883,7 @@ __export(omnius_directory_exports, {
|
|
|
579840
580883
|
import { appendFileSync as appendFileSync6, cpSync as cpSync2, existsSync as existsSync95, mkdirSync as mkdirSync53, readFileSync as readFileSync75, writeFileSync as writeFileSync48, readdirSync as readdirSync31, statSync as statSync36, unlinkSync as unlinkSync17, openSync as openSync2, closeSync as closeSync2, renameSync as renameSync4, watch as fsWatch2 } from "node:fs";
|
|
579841
580884
|
import { join as join111, relative as relative9, basename as basename21, dirname as dirname31, resolve as resolve41 } from "node:path";
|
|
579842
580885
|
import { homedir as homedir34 } from "node:os";
|
|
579843
|
-
import { createHash as
|
|
580886
|
+
import { createHash as createHash26 } from "node:crypto";
|
|
579844
580887
|
function isGitRoot(dir) {
|
|
579845
580888
|
const gitPath = join111(dir, ".git");
|
|
579846
580889
|
if (!existsSync95(gitPath)) return false;
|
|
@@ -580294,7 +581337,7 @@ function buildHandoffPrompt(repoRoot) {
|
|
|
580294
581337
|
return lines.join("\n");
|
|
580295
581338
|
}
|
|
580296
581339
|
function computeDedupeHash(task, savedAt) {
|
|
580297
|
-
return
|
|
581340
|
+
return createHash26("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
|
|
580298
581341
|
}
|
|
580299
581342
|
function generateSessionId() {
|
|
580300
581343
|
const timestamp = Date.now().toString(36);
|
|
@@ -600476,7 +601519,7 @@ __export(commands_exports, {
|
|
|
600476
601519
|
});
|
|
600477
601520
|
import * as nodeOs from "node:os";
|
|
600478
601521
|
import { execSync as nodeExecSync } from "node:child_process";
|
|
600479
|
-
import { createHash as
|
|
601522
|
+
import { createHash as createHash27 } from "node:crypto";
|
|
600480
601523
|
import {
|
|
600481
601524
|
existsSync as existsSync108,
|
|
600482
601525
|
readFileSync as readFileSync86,
|
|
@@ -610952,7 +611995,7 @@ async function collectSponsorMediaStream(args) {
|
|
|
610952
611995
|
return { ok: false, error: `Artifact size mismatch for ${artifactId}: ${bytes.length}/${artifact.sizeBytes}` };
|
|
610953
611996
|
}
|
|
610954
611997
|
if (artifact.sha256) {
|
|
610955
|
-
const sha =
|
|
611998
|
+
const sha = createHash27("sha256").update(bytes).digest("hex");
|
|
610956
611999
|
if (sha !== artifact.sha256) return { ok: false, error: `Artifact hash mismatch for ${artifactId}` };
|
|
610957
612000
|
}
|
|
610958
612001
|
const safeName3 = basename23(artifact.filename).replace(/[^\w.-]/g, "_") || `artifact${defaultExtensionForMime(artifact.mime)}`;
|
|
@@ -614857,7 +615900,7 @@ function realtimeOptionsFromBody(body, repoRoot, sessionId) {
|
|
|
614857
615900
|
)
|
|
614858
615901
|
};
|
|
614859
615902
|
}
|
|
614860
|
-
function
|
|
615903
|
+
function messageContentText2(content) {
|
|
614861
615904
|
if (typeof content === "string") return content;
|
|
614862
615905
|
if (content === null || content === void 0) return "";
|
|
614863
615906
|
try {
|
|
@@ -614869,7 +615912,7 @@ function messageContentText(content) {
|
|
|
614869
615912
|
function prepareRealtimeMessages(messages2, opts) {
|
|
614870
615913
|
const historyLimit = opts.maxHistoryMessages ?? DEFAULT_REALTIME_HISTORY_MESSAGES;
|
|
614871
615914
|
const systemPrompt = buildRealtimeSystemPrompt(opts);
|
|
614872
|
-
const callerSystem = messages2.filter((msg) => msg.role === "system").map((msg) => compactText2(
|
|
615915
|
+
const callerSystem = messages2.filter((msg) => msg.role === "system").map((msg) => compactText2(messageContentText2(msg.content), 1200)).filter(Boolean).join("\n\n");
|
|
614873
615916
|
const realtimeSystem = callerSystem ? `${systemPrompt}
|
|
614874
615917
|
|
|
614875
615918
|
Caller system context, lower priority than the realtime contract:
|
|
@@ -614933,7 +615976,7 @@ function normalizePersonName(name10) {
|
|
|
614933
615976
|
function personKey(name10) {
|
|
614934
615977
|
return `person:${normalizePersonName(name10)}`;
|
|
614935
615978
|
}
|
|
614936
|
-
function
|
|
615979
|
+
function clamp017(value2, fallback = 0) {
|
|
614937
615980
|
if (typeof value2 !== "number" || !Number.isFinite(value2)) return fallback;
|
|
614938
615981
|
return Math.max(0, Math.min(1, value2));
|
|
614939
615982
|
}
|
|
@@ -614950,7 +615993,7 @@ function parseStructuredIdentifyResult(result) {
|
|
|
614950
615993
|
const matches = faces.filter((face) => face["identified"] === true && typeof face["name"] === "string" && String(face["name"]).trim()).map((face) => ({
|
|
614951
615994
|
name: String(face["name"]).trim(),
|
|
614952
615995
|
personId: typeof face["person_id"] === "string" ? face["person_id"] : void 0,
|
|
614953
|
-
confidence:
|
|
615996
|
+
confidence: clamp017(face["confidence"], 0),
|
|
614954
615997
|
margin: typeof face["margin"] === "number" ? face["margin"] : void 0,
|
|
614955
615998
|
bbox: Array.isArray(face["bbox"]) ? face["bbox"].map((n2) => Number(n2)).filter(Number.isFinite) : void 0
|
|
614956
615999
|
}));
|
|
@@ -615033,7 +616076,7 @@ function activePendingVisualIdentities(store2, scope, sessionId, limit = 3) {
|
|
|
615033
616076
|
pendingId,
|
|
615034
616077
|
name: name10,
|
|
615035
616078
|
relation: String(meta["relation"] || "depicts"),
|
|
615036
|
-
confidence:
|
|
616079
|
+
confidence: clamp017(meta["confidence"], 0.92),
|
|
615037
616080
|
note: typeof meta["note"] === "string" ? meta["note"] : void 0,
|
|
615038
616081
|
episodeId: ep.id,
|
|
615039
616082
|
createdAt: ep.timestamp,
|
|
@@ -615143,7 +616186,7 @@ function stageVisualIdentityAssertion(options2) {
|
|
|
615143
616186
|
target: "next_visual_media",
|
|
615144
616187
|
name: name10,
|
|
615145
616188
|
relation: options2.relation || "depicts",
|
|
615146
|
-
confidence:
|
|
616189
|
+
confidence: clamp017(options2.confidence, 0.92),
|
|
615147
616190
|
note: options2.note,
|
|
615148
616191
|
createdAt: Date.now(),
|
|
615149
616192
|
expiresAt
|
|
@@ -615152,7 +616195,7 @@ function stageVisualIdentityAssertion(options2) {
|
|
|
615152
616195
|
identityAssertions: [{
|
|
615153
616196
|
name: name10,
|
|
615154
616197
|
relation: options2.relation || "named_as",
|
|
615155
|
-
confidence:
|
|
616198
|
+
confidence: clamp017(options2.confidence, 0.92),
|
|
615156
616199
|
assertedBy: options2.sender,
|
|
615157
616200
|
note: options2.note || "Explicit user-provided identity staged for the next visual media."
|
|
615158
616201
|
}]
|
|
@@ -622977,7 +624020,7 @@ ${result.output}`,
|
|
|
622977
624020
|
});
|
|
622978
624021
|
|
|
622979
624022
|
// packages/cli/src/tui/stimulation.ts
|
|
622980
|
-
function
|
|
624023
|
+
function clamp018(value2) {
|
|
622981
624024
|
return Math.max(0, Math.min(1, value2));
|
|
622982
624025
|
}
|
|
622983
624026
|
function cloneState(state) {
|
|
@@ -623033,7 +624076,7 @@ var init_stimulation = __esm({
|
|
|
623033
624076
|
...DEFAULT_STATE,
|
|
623034
624077
|
...state,
|
|
623035
624078
|
phase: normalizePhase(state.phase) ?? DEFAULT_STATE.phase,
|
|
623036
|
-
attention:
|
|
624079
|
+
attention: clamp018(Number.isFinite(state.attention) ? Number(state.attention) : DEFAULT_STATE.attention),
|
|
623037
624080
|
updatedAtMs: Number.isFinite(state.updatedAtMs) ? Number(state.updatedAtMs) : now,
|
|
623038
624081
|
lastStimulusAtMs: Number.isFinite(state.lastStimulusAtMs) ? Number(state.lastStimulusAtMs) : now,
|
|
623039
624082
|
messagesSinceAnalysis: Math.max(0, Math.floor(Number(state.messagesSinceAnalysis ?? 0))),
|
|
@@ -623074,11 +624117,11 @@ var init_stimulation = __esm({
|
|
|
623074
624117
|
applyAgentDecision(channelId, decision2, nowMs = Date.now()) {
|
|
623075
624118
|
const state = this.stateFor(channelId, nowMs);
|
|
623076
624119
|
if (Number.isFinite(decision2.attentionScore)) {
|
|
623077
|
-
state.attention =
|
|
624120
|
+
state.attention = clamp018(Number(decision2.attentionScore));
|
|
623078
624121
|
} else if (Number.isFinite(decision2.attentionDelta)) {
|
|
623079
|
-
state.attention =
|
|
624122
|
+
state.attention = clamp018(state.attention + Number(decision2.attentionDelta));
|
|
623080
624123
|
} else {
|
|
623081
|
-
state.attention =
|
|
624124
|
+
state.attention = clamp018(state.attention + (decision2.shouldReply ? 0.22 : -0.1));
|
|
623082
624125
|
}
|
|
623083
624126
|
if (decision2.phase) {
|
|
623084
624127
|
state.attention = Math.max(state.attention, PHASE_FLOORS[decision2.phase]);
|
|
@@ -623134,7 +624177,7 @@ var init_stimulation = __esm({
|
|
|
623134
624177
|
});
|
|
623135
624178
|
|
|
623136
624179
|
// packages/cli/src/tui/pid-controller.ts
|
|
623137
|
-
function
|
|
624180
|
+
function clamp019(x) {
|
|
623138
624181
|
if (!Number.isFinite(x)) return 0;
|
|
623139
624182
|
if (x < 0) return 0;
|
|
623140
624183
|
if (x > 1) return 1;
|
|
@@ -623198,7 +624241,7 @@ var init_pid_controller = __esm({
|
|
|
623198
624241
|
const dt = st.lastSampleAt > 0 ? now - st.lastSampleAt : 1e3;
|
|
623199
624242
|
const derivative = dt > 0 ? (error - st.lastError) / dt : 0;
|
|
623200
624243
|
const u = st.config.kp * error + st.config.ki * st.integral + st.config.kd * derivative;
|
|
623201
|
-
st.output =
|
|
624244
|
+
st.output = clamp019(st.output + u);
|
|
623202
624245
|
st.lastError = error;
|
|
623203
624246
|
st.lastSampleAt = now;
|
|
623204
624247
|
st.samples += 1;
|
|
@@ -623430,7 +624473,7 @@ var init_soul_observations = __esm({
|
|
|
623430
624473
|
// packages/cli/src/tui/telegram-channel-dmn.ts
|
|
623431
624474
|
import { existsSync as existsSync119, mkdirSync as mkdirSync68, readdirSync as readdirSync42, readFileSync as readFileSync96, writeFileSync as writeFileSync61 } from "node:fs";
|
|
623432
624475
|
import { join as join133 } from "node:path";
|
|
623433
|
-
import { createHash as
|
|
624476
|
+
import { createHash as createHash28 } from "node:crypto";
|
|
623434
624477
|
function safeFilePart(value2) {
|
|
623435
624478
|
return value2.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 80) || "telegram";
|
|
623436
624479
|
}
|
|
@@ -623438,7 +624481,7 @@ function daydreamRoot(repoRoot) {
|
|
|
623438
624481
|
return join133(repoRoot, ".omnius", "telegram-daydreams");
|
|
623439
624482
|
}
|
|
623440
624483
|
function sessionDir(repoRoot, sessionKey) {
|
|
623441
|
-
const hash =
|
|
624484
|
+
const hash = createHash28("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
623442
624485
|
return join133(daydreamRoot(repoRoot), safeFilePart(hash));
|
|
623443
624486
|
}
|
|
623444
624487
|
function compactLine2(value2, max = 220) {
|
|
@@ -623523,9 +624566,9 @@ function buildReplyOpportunities(input, openQuestions) {
|
|
|
623523
624566
|
return opportunities;
|
|
623524
624567
|
}
|
|
623525
624568
|
function daydreamOpportunityId(input, trigger) {
|
|
623526
|
-
return
|
|
624569
|
+
return createHash28("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
|
|
623527
624570
|
}
|
|
623528
|
-
function
|
|
624571
|
+
function clamp0110(value2) {
|
|
623529
624572
|
if (!Number.isFinite(value2)) return 0;
|
|
623530
624573
|
return Math.max(0, Math.min(1, value2));
|
|
623531
624574
|
}
|
|
@@ -623536,7 +624579,7 @@ function pushStimulationSignal(signals, signal, source, weight) {
|
|
|
623536
624579
|
const cleanSignal = compactLine2(signal, 120);
|
|
623537
624580
|
const cleanSource = compactLine2(source, 180);
|
|
623538
624581
|
if (!cleanSignal || signals.some((entry) => entry.signal === cleanSignal && entry.source === cleanSource)) return;
|
|
623539
|
-
signals.push({ signal: cleanSignal, source: cleanSource, weight:
|
|
624582
|
+
signals.push({ signal: cleanSignal, source: cleanSource, weight: clamp0110(weight) });
|
|
623540
624583
|
}
|
|
623541
624584
|
function buildMetaAnalysisSignals(input) {
|
|
623542
624585
|
const chatLabel = input.chatTitle || input.chatId;
|
|
@@ -623611,7 +624654,7 @@ function buildCuriosityThreads(input, openQuestions, stimulationSignals) {
|
|
|
623611
624654
|
question: text.endsWith("?") || text.endsWith("?") ? text : `What should be learned or clarified from: ${text || entry.mediaSummary || "recent media"}?`,
|
|
623612
624655
|
rationale: "Human curiosity, uncertainty, or multimodal content makes this a useful idle exploration target.",
|
|
623613
624656
|
sourceMessages: messageId,
|
|
623614
|
-
intensity:
|
|
624657
|
+
intensity: clamp0110(0.5 + replyBoost + mediaBoost + questionBoost)
|
|
623615
624658
|
});
|
|
623616
624659
|
}
|
|
623617
624660
|
for (const question of openQuestions.slice(-4)) {
|
|
@@ -623631,7 +624674,7 @@ function buildCuriosityThreads(input, openQuestions, stimulationSignals) {
|
|
|
623631
624674
|
question: `Is there a useful clarification or memory consolidation around ${strongest.source}?`,
|
|
623632
624675
|
rationale: "Strongest stimulation signal can seed a low-intrusion reflection target.",
|
|
623633
624676
|
sourceMessages: [],
|
|
623634
|
-
intensity:
|
|
624677
|
+
intensity: clamp0110(strongest.weight * 0.72)
|
|
623635
624678
|
});
|
|
623636
624679
|
}
|
|
623637
624680
|
return threads.sort((a2, b) => b.intensity - a2.intensity).slice(0, 8);
|
|
@@ -623705,7 +624748,7 @@ function buildOutreachPlans(input, curiosityThreads) {
|
|
|
623705
624748
|
purpose: "Continue the public thread only when the live model judges that the group would benefit from a concise follow-up.",
|
|
623706
624749
|
draftIntent: "Ask one concrete clarification, offer one useful synthesis, or stay silent if the room has moved on.",
|
|
623707
624750
|
gate: "model_decision",
|
|
623708
|
-
confidence:
|
|
624751
|
+
confidence: clamp0110(thread.intensity * 0.86)
|
|
623709
624752
|
});
|
|
623710
624753
|
const participant = participantForThread(input, thread);
|
|
623711
624754
|
if (!participant) continue;
|
|
@@ -623717,7 +624760,7 @@ function buildOutreachPlans(input, curiosityThreads) {
|
|
|
623717
624760
|
purpose: "Offer a one-to-one follow-up only if private contact is allowed and the issue is personal, unresolved, or better handled outside the group.",
|
|
623718
624761
|
draftIntent: "Reference the public thread briefly, ask permission to continue privately, and do not reveal hidden meta-analysis.",
|
|
623719
624762
|
gate: "admin_review",
|
|
623720
|
-
confidence:
|
|
624763
|
+
confidence: clamp0110(thread.intensity * 0.58)
|
|
623721
624764
|
});
|
|
623722
624765
|
}
|
|
623723
624766
|
return plans.slice(0, 8);
|
|
@@ -623843,7 +624886,7 @@ function buildTelegramChannelDaydream(input, corpus, extraction, extractionCommi
|
|
|
623843
624886
|
const seed = `${input.sessionKey}:${input.generatedAtMs}:${input.history.length}`;
|
|
623844
624887
|
return {
|
|
623845
624888
|
version: 3,
|
|
623846
|
-
id:
|
|
624889
|
+
id: createHash28("sha1").update(seed).digest("hex").slice(0, 16),
|
|
623847
624890
|
sessionKey: input.sessionKey,
|
|
623848
624891
|
chatId: input.chatId,
|
|
623849
624892
|
chatTitle: input.chatTitle,
|
|
@@ -624056,12 +625099,12 @@ var init_telegram_channel_dmn = __esm({
|
|
|
624056
625099
|
});
|
|
624057
625100
|
|
|
624058
625101
|
// packages/cli/src/tui/telegram-reflection-corpus.ts
|
|
624059
|
-
import { createHash as
|
|
625102
|
+
import { createHash as createHash29 } from "node:crypto";
|
|
624060
625103
|
function telegramReflectionMemoryDbPaths(repoRoot) {
|
|
624061
625104
|
return omniusMemoryDbPaths(repoRoot);
|
|
624062
625105
|
}
|
|
624063
625106
|
function stableHash2(value2, length4 = 16) {
|
|
624064
|
-
return
|
|
625107
|
+
return createHash29("sha1").update(value2).digest("hex").slice(0, length4);
|
|
624065
625108
|
}
|
|
624066
625109
|
function clean3(value2) {
|
|
624067
625110
|
return String(value2 ?? "").replace(/\s+/g, " ").trim();
|
|
@@ -624791,7 +625834,7 @@ var init_telegram_reflection_extraction = __esm({
|
|
|
624791
625834
|
});
|
|
624792
625835
|
|
|
624793
625836
|
// packages/cli/src/tui/telegram-social-state-types.ts
|
|
624794
|
-
import { createHash as
|
|
625837
|
+
import { createHash as createHash30 } from "node:crypto";
|
|
624795
625838
|
function telegramSocialActorKey(actor) {
|
|
624796
625839
|
if (!actor) return "unknown";
|
|
624797
625840
|
if (typeof actor.userId === "number") return `user:${actor.userId}`;
|
|
@@ -624824,7 +625867,7 @@ function appendUnique(items, value2, max) {
|
|
|
624824
625867
|
return next.slice(-max);
|
|
624825
625868
|
}
|
|
624826
625869
|
function hashTelegramSocialId(parts) {
|
|
624827
|
-
return
|
|
625870
|
+
return createHash30("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
|
|
624828
625871
|
}
|
|
624829
625872
|
function cleanUsername(value2) {
|
|
624830
625873
|
if (typeof value2 !== "string") return void 0;
|
|
@@ -624849,7 +625892,7 @@ function numberOr(value2, fallback) {
|
|
|
624849
625892
|
function isNumber(value2) {
|
|
624850
625893
|
return typeof value2 === "number" && Number.isFinite(value2);
|
|
624851
625894
|
}
|
|
624852
|
-
function
|
|
625895
|
+
function clamp0111(value2) {
|
|
624853
625896
|
return Math.max(0, Math.min(1, Number.isFinite(value2) ? value2 : 0));
|
|
624854
625897
|
}
|
|
624855
625898
|
function iso(ts) {
|
|
@@ -625033,8 +626076,8 @@ function normalizeRelationship(raw) {
|
|
|
625033
626076
|
kind: value2.kind,
|
|
625034
626077
|
fromKey: String(value2.fromKey),
|
|
625035
626078
|
toKey: String(value2.toKey),
|
|
625036
|
-
confidence:
|
|
625037
|
-
weight:
|
|
626079
|
+
confidence: clamp0111(numberOr(value2.confidence, 0)),
|
|
626080
|
+
weight: clamp0111(numberOr(value2.weight, 0)),
|
|
625038
626081
|
firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
|
|
625039
626082
|
lastSeenAt: numberOr(value2.lastSeenAt, Date.now()),
|
|
625040
626083
|
evidenceMessageIds: Array.isArray(value2.evidenceMessageIds) ? value2.evidenceMessageIds.filter(isNumber).slice(-40) : [],
|
|
@@ -625053,7 +626096,7 @@ function normalizePreferences(raw) {
|
|
|
625053
626096
|
if (!evidence || typeof evidence !== "object") continue;
|
|
625054
626097
|
out[actorKey][key] = {
|
|
625055
626098
|
value: Math.max(-1, Math.min(1, numberOr(evidence.value, 0))),
|
|
625056
|
-
confidence:
|
|
626099
|
+
confidence: clamp0111(numberOr(evidence.confidence, 0)),
|
|
625057
626100
|
updatedAt: numberOr(evidence.updatedAt, Date.now()),
|
|
625058
626101
|
evidenceMessageIds: Array.isArray(evidence.evidenceMessageIds) ? evidence.evidenceMessageIds.filter(isNumber).slice(-12) : [],
|
|
625059
626102
|
note: compactOptional(evidence.note, 220)
|
|
@@ -625067,7 +626110,7 @@ function normalizePreferences(raw) {
|
|
|
625067
626110
|
out[actorKey].replyMode = {
|
|
625068
626111
|
mode,
|
|
625069
626112
|
scope: normalizeReplyPreferenceScope(record["scope"]),
|
|
625070
|
-
confidence:
|
|
626113
|
+
confidence: clamp0111(numberOr(record["confidence"], 0.8)),
|
|
625071
626114
|
updatedAt: numberOr(record["updatedAt"], Date.now()),
|
|
625072
626115
|
evidenceMessageIds: Array.isArray(record["evidenceMessageIds"]) ? record["evidenceMessageIds"].filter(isNumber).slice(-12) : [],
|
|
625073
626116
|
note: compactOptional(record["note"], 220),
|
|
@@ -625157,7 +626200,7 @@ function normalizeOutcome(raw) {
|
|
|
625157
626200
|
replyToMessageId: typeof value2.replyToMessageId === "number" ? value2.replyToMessageId : void 0,
|
|
625158
626201
|
route: value2.route === "action" ? "action" : "chat",
|
|
625159
626202
|
shouldReply: value2.shouldReply === true,
|
|
625160
|
-
confidence:
|
|
626203
|
+
confidence: clamp0111(numberOr(value2.confidence, 0)),
|
|
625161
626204
|
reason: compact2(value2.reason || "", 280),
|
|
625162
626205
|
source: compact2(value2.source || "unknown", 80),
|
|
625163
626206
|
silentDisposition: compactOptional(value2.silentDisposition, 280),
|
|
@@ -625169,7 +626212,7 @@ function normalizeOutcome(raw) {
|
|
|
625169
626212
|
scenarioNote: compactOptional(value2.scenarioNote, 360),
|
|
625170
626213
|
scenarioId: compactOptional(value2.scenarioId, 160),
|
|
625171
626214
|
scenarioLabel: compactOptional(value2.scenarioLabel, 160),
|
|
625172
|
-
scenarioConfidence: typeof value2.scenarioConfidence === "number" && Number.isFinite(value2.scenarioConfidence) ?
|
|
626215
|
+
scenarioConfidence: typeof value2.scenarioConfidence === "number" && Number.isFinite(value2.scenarioConfidence) ? clamp0111(value2.scenarioConfidence) : void 0,
|
|
625173
626216
|
scenarioObjective: compactOptional(value2.scenarioObjective, 360),
|
|
625174
626217
|
scenarioStateLoop: compactOptional(value2.scenarioStateLoop, 360),
|
|
625175
626218
|
salienceSignals: Array.isArray(value2.salienceSignals) ? value2.salienceSignals.map(String).slice(0, 16) : [],
|
|
@@ -625187,7 +626230,7 @@ function normalizeDaydreamOpportunity(raw) {
|
|
|
625187
626230
|
artifactId: String(value2.artifactId || "unknown"),
|
|
625188
626231
|
generatedAt: String(value2.generatedAt || (/* @__PURE__ */ new Date()).toISOString()),
|
|
625189
626232
|
trigger: compact2(value2.trigger || "", 240),
|
|
625190
|
-
confidence:
|
|
626233
|
+
confidence: clamp0111(numberOr(value2.confidence, 0)),
|
|
625191
626234
|
lifecycle,
|
|
625192
626235
|
firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
|
|
625193
626236
|
updatedAt: numberOr(value2.updatedAt, Date.now()),
|
|
@@ -625244,7 +626287,7 @@ function commitTelegramSocialDecision(state, input) {
|
|
|
625244
626287
|
replyToMessageId: input.replyToMessageId,
|
|
625245
626288
|
route: input.route,
|
|
625246
626289
|
shouldReply: input.shouldReply,
|
|
625247
|
-
confidence:
|
|
626290
|
+
confidence: clamp0111(input.confidence),
|
|
625248
626291
|
reason: compact2(input.reason, 280),
|
|
625249
626292
|
source: compact2(input.source, 80),
|
|
625250
626293
|
silentDisposition: compactOptional(input.silentDisposition, 280),
|
|
@@ -625256,7 +626299,7 @@ function commitTelegramSocialDecision(state, input) {
|
|
|
625256
626299
|
scenarioNote: compactOptional(input.scenarioNote, 360),
|
|
625257
626300
|
scenarioId: compactOptional(input.scenarioId, 160),
|
|
625258
626301
|
scenarioLabel: compactOptional(input.scenarioLabel, 160),
|
|
625259
|
-
scenarioConfidence: input.scenarioConfidence === void 0 ? void 0 :
|
|
626302
|
+
scenarioConfidence: input.scenarioConfidence === void 0 ? void 0 : clamp0111(input.scenarioConfidence),
|
|
625260
626303
|
scenarioObjective: compactOptional(input.scenarioObjective, 360),
|
|
625261
626304
|
scenarioStateLoop: compactOptional(input.scenarioStateLoop, 360),
|
|
625262
626305
|
salienceSignals: [...new Set((input.salienceSignals ?? []).map(String))].slice(0, 16),
|
|
@@ -625280,7 +626323,7 @@ function registerDaydreamOpportunities(state, opportunities, now = Date.now()) {
|
|
|
625280
626323
|
artifactId: opportunity.artifactId || "unknown",
|
|
625281
626324
|
generatedAt: opportunity.generatedAt || new Date(now).toISOString(),
|
|
625282
626325
|
trigger: compact2(opportunity.trigger, 240),
|
|
625283
|
-
confidence:
|
|
626326
|
+
confidence: clamp0111(opportunity.confidence),
|
|
625284
626327
|
lifecycle: "proposed",
|
|
625285
626328
|
firstSeenAt: now,
|
|
625286
626329
|
updatedAt: now,
|
|
@@ -625290,7 +626333,7 @@ function registerDaydreamOpportunities(state, opportunities, now = Date.now()) {
|
|
|
625290
626333
|
};
|
|
625291
626334
|
if (existing) {
|
|
625292
626335
|
item.trigger = compact2(opportunity.trigger, 240) || item.trigger;
|
|
625293
|
-
item.confidence =
|
|
626336
|
+
item.confidence = clamp0111(opportunity.confidence);
|
|
625294
626337
|
item.updatedAt = now;
|
|
625295
626338
|
}
|
|
625296
626339
|
state.daydreamOpportunities[id] = item;
|
|
@@ -625317,7 +626360,7 @@ function setTelegramReplyModePreference(state, input) {
|
|
|
625317
626360
|
const next = {
|
|
625318
626361
|
mode: input.mode,
|
|
625319
626362
|
scope: input.scope,
|
|
625320
|
-
confidence: Math.max(existing?.confidence ?? 0,
|
|
626363
|
+
confidence: Math.max(existing?.confidence ?? 0, clamp0111(input.confidence ?? 0.84)),
|
|
625321
626364
|
updatedAt: now,
|
|
625322
626365
|
evidenceMessageIds: appendUnique(existing?.evidenceMessageIds ?? [], input.messageId, 12),
|
|
625323
626366
|
note: compactOptional(input.note, 220),
|
|
@@ -625497,8 +626540,8 @@ function upsertRelationship(state, kind, fromKey, toKey, messageId, confidence2,
|
|
|
625497
626540
|
evidenceMessageIds: [],
|
|
625498
626541
|
source
|
|
625499
626542
|
};
|
|
625500
|
-
edge.confidence = Math.max(edge.confidence,
|
|
625501
|
-
edge.weight = Math.min(1, edge.weight + 0.12 +
|
|
626543
|
+
edge.confidence = Math.max(edge.confidence, clamp0111(confidence2));
|
|
626544
|
+
edge.weight = Math.min(1, edge.weight + 0.12 + clamp0111(confidence2) * 0.2);
|
|
625502
626545
|
edge.lastSeenAt = now;
|
|
625503
626546
|
edge.evidenceMessageIds = appendUnique(edge.evidenceMessageIds, messageId, 40);
|
|
625504
626547
|
edge.note = compactOptional(note, 260) || edge.note;
|
|
@@ -625540,7 +626583,7 @@ function setPreference(vector, key, value2, confidence2, messageId, now, note) {
|
|
|
625540
626583
|
const existing = vector[key];
|
|
625541
626584
|
vector[key] = {
|
|
625542
626585
|
value: existing ? existing.value * 0.7 + value2 * 0.3 : value2,
|
|
625543
|
-
confidence: Math.max(existing?.confidence ?? 0,
|
|
626586
|
+
confidence: Math.max(existing?.confidence ?? 0, clamp0111(confidence2)),
|
|
625544
626587
|
updatedAt: now,
|
|
625545
626588
|
evidenceMessageIds: appendUnique(existing?.evidenceMessageIds ?? [], messageId, 12),
|
|
625546
626589
|
note
|
|
@@ -625751,7 +626794,7 @@ import { mkdirSync as mkdirSync69, existsSync as existsSync121, unlinkSync as un
|
|
|
625751
626794
|
import { join as join135, resolve as resolve48, basename as basename33, relative as relative13, isAbsolute as isAbsolute8, extname as extname16 } from "node:path";
|
|
625752
626795
|
import { homedir as homedir43 } from "node:os";
|
|
625753
626796
|
import { writeFile as writeFileAsync } from "node:fs/promises";
|
|
625754
|
-
import { createHash as
|
|
626797
|
+
import { createHash as createHash31, randomBytes as randomBytes24, randomInt } from "node:crypto";
|
|
625755
626798
|
function cleanTelegramDecisionNote(value2, maxLength = 260) {
|
|
625756
626799
|
if (typeof value2 !== "string") return void 0;
|
|
625757
626800
|
const clean5 = stripTelegramHiddenThinking(value2).replace(/\s+/g, " ").trim();
|
|
@@ -626718,7 +627761,7 @@ function buildTelegramRuntimeContext(now = /* @__PURE__ */ new Date(), repoRoot)
|
|
|
626718
627761
|
].filter(Boolean).join("\n");
|
|
626719
627762
|
}
|
|
626720
627763
|
function telegramSessionIdFromKey(sessionKey) {
|
|
626721
|
-
return `telegram-${
|
|
627764
|
+
return `telegram-${createHash31("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
|
|
626722
627765
|
}
|
|
626723
627766
|
function normalizeTelegramSubAgentLimit(value2) {
|
|
626724
627767
|
const parsed = typeof value2 === "number" ? value2 : typeof value2 === "string" && value2.trim() ? Number(value2.trim()) : TELEGRAM_SUB_AGENT_DEFAULT_LIMIT;
|
|
@@ -627535,7 +628578,7 @@ function renderTelegramSubAgentError(username, error) {
|
|
|
627535
628578
|
process.stdout.write(` ${c3.dim("│")} ${c3.magenta("✘")} @${username}: ${c3.dim(preview)}
|
|
627536
628579
|
`);
|
|
627537
628580
|
}
|
|
627538
|
-
var TELEGRAM_TOOL_ACTION_GROUPS, TELEGRAM_TOOL_ACTION_GROUP, TELEGRAM_TOOL_MUTATING_GROUPS, DEFAULT_TELEGRAM_TOOL_GROUP_POLICY, TELEGRAM_TOOL_BUTTON_LABELS, TELEGRAM_SAFETY_PROMPT, ADMIN_DM_PROMPT, ADMIN_GROUP_PROMPT, TELEGRAM_PUBLIC_SOUL_PROFILE, TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT, TELEGRAM_PUBLIC_MEMORY_SCOPE_CONTRACT, TELEGRAM_PUBLIC_VISION_STACK_CONTRACT, GROUP_REPLY_DISCRETION_PROMPT, TELEGRAM_CHAT_MODE_PROMPT, ADMIN_CHAT_PROFILE_PROMPT, TELEGRAM_ACTION_RESPONSE_CONTRACT, TELEGRAM_EXTERNAL_ACQUISITION_CONTRACT, TELEGRAM_INTERACTION_DECISION_RESPONSE_FORMAT, TELEGRAM_CHAT_REPLY_RESPONSE_FORMAT, TELEGRAM_STUCK_SELF_TALK_PREFIXES, TELEGRAM_CHAT_HISTORY_LIMIT, TELEGRAM_CONTEXT_RECENT_DEFAULT, TELEGRAM_CONTEXT_LINE_LIMIT, TELEGRAM_CONTEXT_SAMPLE_LIMIT, TELEGRAM_MEMORY_CARD_LIMIT, TELEGRAM_MEMORY_NOTE_LIMIT, TELEGRAM_ASSOCIATIVE_FACT_LIMIT, TELEGRAM_ASSOCIATIVE_USER_FACT_LIMIT, TELEGRAM_ASSOCIATIVE_ACTION_LIMIT, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT, TELEGRAM_MEMORY_STOPWORDS, TELEGRAM_MEMORY_GENERIC_QUERY_TOKENS, TELEGRAM_SUB_AGENT_BOUNDED_OPTIONS, TELEGRAM_SUB_AGENT_DEFAULT_LIMIT, TELEGRAM_SUB_AGENT_MAX_LIMIT, TELEGRAM_SUB_AGENT_BURST_CONTEXT_LIMIT, TELEGRAM_PUBLIC_HELP_COMMANDS2, TELEGRAM_REMINDER_SLASH_COMMANDS, TELEGRAM_REFLECTION_SLASH_COMMANDS, TELEGRAM_PUBLIC_BOT_COMMAND_NAMES, TELEGRAM_IMAGE_EXTENSIONS, MEDIA_CACHE_TTL_MS, TELEGRAM_CHANNEL_DMN_SWEEP_MS, TELEGRAM_CHANNEL_DMN_IDLE_AFTER_MS, TELEGRAM_CHANNEL_DMN_MIN_INTERVAL_MS, TELEGRAM_CHANNEL_DMN_MIN_MESSAGES, TELEGRAM_ALLOWED_UPDATES, TELEGRAM_PUBLIC_TOOL_QUOTAS, TelegramBridge;
|
|
628581
|
+
var TELEGRAM_TOOL_ACTION_GROUPS, TELEGRAM_TOOL_ACTION_GROUP, TELEGRAM_TOOL_MUTATING_GROUPS, DEFAULT_TELEGRAM_TOOL_GROUP_POLICY, TELEGRAM_TOOL_BUTTON_LABELS, TELEGRAM_SAFETY_PROMPT, ADMIN_DM_PROMPT, ADMIN_GROUP_PROMPT, TELEGRAM_PUBLIC_SOUL_PROFILE, TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT, TELEGRAM_PUBLIC_MEMORY_SCOPE_CONTRACT, TELEGRAM_PUBLIC_VISION_STACK_CONTRACT, GROUP_REPLY_DISCRETION_PROMPT, TELEGRAM_CHAT_MODE_PROMPT, ADMIN_CHAT_PROFILE_PROMPT, TELEGRAM_ACTION_RESPONSE_CONTRACT, TELEGRAM_EXTERNAL_ACQUISITION_CONTRACT, TELEGRAM_INTERACTION_DECISION_RESPONSE_FORMAT, TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA, TELEGRAM_INTERACTION_DECISION_REPAIR_SCHEMA, TELEGRAM_CHAT_REPLY_RESPONSE_FORMAT, TELEGRAM_STUCK_SELF_TALK_PREFIXES, TELEGRAM_CHAT_HISTORY_LIMIT, TELEGRAM_CONTEXT_RECENT_DEFAULT, TELEGRAM_CONTEXT_LINE_LIMIT, TELEGRAM_CONTEXT_SAMPLE_LIMIT, TELEGRAM_MEMORY_CARD_LIMIT, TELEGRAM_MEMORY_NOTE_LIMIT, TELEGRAM_ASSOCIATIVE_FACT_LIMIT, TELEGRAM_ASSOCIATIVE_USER_FACT_LIMIT, TELEGRAM_ASSOCIATIVE_ACTION_LIMIT, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT, TELEGRAM_MEMORY_STOPWORDS, TELEGRAM_MEMORY_GENERIC_QUERY_TOKENS, TELEGRAM_SUB_AGENT_BOUNDED_OPTIONS, TELEGRAM_SUB_AGENT_DEFAULT_LIMIT, TELEGRAM_SUB_AGENT_MAX_LIMIT, TELEGRAM_SUB_AGENT_BURST_CONTEXT_LIMIT, TELEGRAM_PUBLIC_HELP_COMMANDS2, TELEGRAM_REMINDER_SLASH_COMMANDS, TELEGRAM_REFLECTION_SLASH_COMMANDS, TELEGRAM_PUBLIC_BOT_COMMAND_NAMES, TELEGRAM_IMAGE_EXTENSIONS, MEDIA_CACHE_TTL_MS, TELEGRAM_CHANNEL_DMN_SWEEP_MS, TELEGRAM_CHANNEL_DMN_IDLE_AFTER_MS, TELEGRAM_CHANNEL_DMN_MIN_INTERVAL_MS, TELEGRAM_CHANNEL_DMN_MIN_MESSAGES, TELEGRAM_ALLOWED_UPDATES, TELEGRAM_PUBLIC_TOOL_QUOTAS, TelegramBridge;
|
|
627539
628582
|
var init_telegram_bridge = __esm({
|
|
627540
628583
|
"packages/cli/src/tui/telegram-bridge.ts"() {
|
|
627541
628584
|
"use strict";
|
|
@@ -627807,6 +628850,8 @@ External acquisition contract:
|
|
|
627807
628850
|
TELEGRAM_INTERACTION_DECISION_RESPONSE_FORMAT = {
|
|
627808
628851
|
type: "json_object"
|
|
627809
628852
|
};
|
|
628853
|
+
TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA = `{"route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","attention_state":"idle"|"observing"|"engaged"|"cooldown","attention_delta":-1.0..1.0,"next_check_after_messages":1..12,"reply_mode_preference":null|{"scope":"current_user_in_chat"|"current_user_global"|"current_group","reply_mode":"reply_then_notes"|"notes_then_reply"|"reply_only","confidence":0.0-1.0,"note":"explicit durable cadence preference"}}`;
|
|
628854
|
+
TELEGRAM_INTERACTION_DECISION_REPAIR_SCHEMA = `{"recoverable":true|false,"route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","attention_state":"idle"|"observing"|"engaged"|"cooldown","attention_delta":-1.0..1.0,"next_check_after_messages":1..12,"reply_mode_preference":null|{"scope":"current_user_in_chat"|"current_user_global"|"current_group","reply_mode":"reply_then_notes"|"notes_then_reply"|"reply_only","confidence":0.0-1.0,"note":"explicit durable cadence preference"}}`;
|
|
627810
628855
|
TELEGRAM_CHAT_REPLY_RESPONSE_FORMAT = {
|
|
627811
628856
|
type: "json_schema",
|
|
627812
628857
|
json_schema: {
|
|
@@ -628333,7 +629378,7 @@ External acquisition contract:
|
|
|
628333
629378
|
return !!this.adminAuthChallenge && this.adminAuthChallenge.expiresAtMs > Date.now();
|
|
628334
629379
|
}
|
|
628335
629380
|
hashAdminAuthCode(code8) {
|
|
628336
|
-
return
|
|
629381
|
+
return createHash31("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
|
|
628337
629382
|
}
|
|
628338
629383
|
viewIdForMessage(msg) {
|
|
628339
629384
|
return `telegram-${this.sessionKeyForMessage(msg).replace(/[^A-Za-z0-9_-]/g, "-")}`;
|
|
@@ -629260,11 +630305,11 @@ ${mediaContext}` : ""
|
|
|
629260
630305
|
return payload;
|
|
629261
630306
|
}
|
|
629262
630307
|
telegramConversationPath(sessionKey) {
|
|
629263
|
-
const safe =
|
|
630308
|
+
const safe = createHash31("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
629264
630309
|
return join135(this.telegramConversationDir, `${safe}.json`);
|
|
629265
630310
|
}
|
|
629266
630311
|
telegramConversationLedgerPath(sessionKey) {
|
|
629267
|
-
const safe =
|
|
630312
|
+
const safe = createHash31("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
629268
630313
|
return join135(this.telegramConversationDir, `${safe}.events.jsonl`);
|
|
629269
630314
|
}
|
|
629270
630315
|
telegramDb() {
|
|
@@ -629492,7 +630537,7 @@ ${mediaContext}` : ""
|
|
|
629492
630537
|
users,
|
|
629493
630538
|
relationships: Array.isArray(raw.relationships) ? raw.relationships.slice(0, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT).map((fact) => this.normalizeTelegramAssociativeFact(fact)) : [],
|
|
629494
630539
|
actions: Array.isArray(raw.actions) ? raw.actions.slice(-TELEGRAM_ASSOCIATIVE_ACTION_LIMIT).map((action) => ({
|
|
629495
|
-
id: String(action.id ||
|
|
630540
|
+
id: String(action.id || createHash31("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)),
|
|
629496
630541
|
ts: typeof action.ts === "number" ? action.ts : Date.now(),
|
|
629497
630542
|
role: action.role === "assistant" ? "assistant" : "user",
|
|
629498
630543
|
speaker: String(action.speaker || "unknown"),
|
|
@@ -629509,7 +630554,7 @@ ${mediaContext}` : ""
|
|
|
629509
630554
|
const text = String(raw.text || "").trim();
|
|
629510
630555
|
const now = Date.now();
|
|
629511
630556
|
return {
|
|
629512
|
-
id: String(raw.id ||
|
|
630557
|
+
id: String(raw.id || createHash31("sha1").update(text || String(now)).digest("hex").slice(0, 12)),
|
|
629513
630558
|
text,
|
|
629514
630559
|
tags: Array.isArray(raw.tags) ? raw.tags.map(String).slice(0, 16) : [],
|
|
629515
630560
|
speakers: Array.isArray(raw.speakers) ? raw.speakers.map(String).slice(0, 16) : [],
|
|
@@ -629747,6 +630792,41 @@ ${mediaContext}` : ""
|
|
|
629747
630792
|
scenarioStateLoop: void 0
|
|
629748
630793
|
};
|
|
629749
630794
|
}
|
|
630795
|
+
synthesizeTelegramPostReplyDecision(decision2, msg, visibleReplyText) {
|
|
630796
|
+
const base3 = this.stripTelegramDecisionNotes(decision2);
|
|
630797
|
+
const replySummary = visibleReplyText ? sanitizeTelegramProgressText(cleanTelegramVisibleReply(visibleReplyText), 180) : "visible reply attempt completed";
|
|
630798
|
+
return {
|
|
630799
|
+
...base3,
|
|
630800
|
+
silentDisposition: "visible reply completed before internal note commit",
|
|
630801
|
+
mentalNote: `post-reply: @${msg.username || "unknown"} was answered via ${decision2.route}; ${replySummary}`,
|
|
630802
|
+
memoryNote: "message and visible reply were retained in scoped Telegram conversation memory"
|
|
630803
|
+
};
|
|
630804
|
+
}
|
|
630805
|
+
notesThenReplyDecision(decision2, msg) {
|
|
630806
|
+
if (decision2.silentDisposition || decision2.mentalNote || decision2.memoryNote || decision2.relationshipNote || decision2.procedureNote || decision2.voiceNote || decision2.scenarioNote || decision2.scenarioId) {
|
|
630807
|
+
return decision2;
|
|
630808
|
+
}
|
|
630809
|
+
return {
|
|
630810
|
+
...decision2,
|
|
630811
|
+
silentDisposition: "internal notes committed before visible reply by reply mode",
|
|
630812
|
+
mentalNote: `pre-reply: @${msg.username || "unknown"} routed to ${decision2.route}; ${decision2.reason}`,
|
|
630813
|
+
memoryNote: "message retained in scoped Telegram conversation memory before reply"
|
|
630814
|
+
};
|
|
630815
|
+
}
|
|
630816
|
+
deliverTelegramPostReplyNotes(sessionKey, msg, viewId, decision2, salienceSignals, daydreamOpportunities, visibleReplyText) {
|
|
630817
|
+
const postReplyDecision = this.synthesizeTelegramPostReplyDecision(decision2, msg, visibleReplyText);
|
|
630818
|
+
if (viewId && this.subAgentViewCallbacks) {
|
|
630819
|
+
this.subAgentViewCallbacks.onWrite(viewId, "post-reply/internal notes:");
|
|
630820
|
+
}
|
|
630821
|
+
this.deliverTelegramAttentionDecision(
|
|
630822
|
+
sessionKey,
|
|
630823
|
+
msg,
|
|
630824
|
+
viewId,
|
|
630825
|
+
postReplyDecision,
|
|
630826
|
+
salienceSignals,
|
|
630827
|
+
daydreamOpportunities
|
|
630828
|
+
);
|
|
630829
|
+
}
|
|
629750
630830
|
telegramTextDeliveryCapability(sessionKey, chatId, messageThreadId) {
|
|
629751
630831
|
try {
|
|
629752
630832
|
return telegramTextDeliveryCapabilityFor(this.telegramSocialStateForSession(sessionKey), {
|
|
@@ -629863,7 +630943,7 @@ ${mediaContext}` : ""
|
|
|
629863
630943
|
}
|
|
629864
630944
|
telegramHistoryBackfillMessageId(sessionKey, entry, index) {
|
|
629865
630945
|
if (typeof entry.messageId === "number" && Number.isFinite(entry.messageId)) return entry.messageId;
|
|
629866
|
-
const digest3 =
|
|
630946
|
+
const digest3 = createHash31("sha1").update(`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`).digest("hex").slice(0, 8);
|
|
629867
630947
|
return -Number.parseInt(digest3, 16);
|
|
629868
630948
|
}
|
|
629869
630949
|
backfillTelegramLoadedHistory(sessionKey, history) {
|
|
@@ -630780,7 +631860,7 @@ ${mediaContext}` : ""
|
|
|
630780
631860
|
const now = entry.ts ?? Date.now();
|
|
630781
631861
|
memory.updatedAt = now;
|
|
630782
631862
|
const speaker = telegramHistorySpeaker(entry);
|
|
630783
|
-
const actionId =
|
|
631863
|
+
const actionId = createHash31("sha1").update(`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now}:${entry.text}`).digest("hex").slice(0, 16);
|
|
630784
631864
|
if (!memory.actions.some((action) => action.id === actionId)) {
|
|
630785
631865
|
memory.actions.push({
|
|
630786
631866
|
id: actionId,
|
|
@@ -630902,7 +631982,7 @@ ${mediaContext}` : ""
|
|
|
630902
631982
|
let fact = facts.find((item) => item.text.toLowerCase() === key);
|
|
630903
631983
|
if (!fact) {
|
|
630904
631984
|
fact = {
|
|
630905
|
-
id:
|
|
631985
|
+
id: createHash31("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
|
|
630906
631986
|
text: clean5,
|
|
630907
631987
|
tags: telegramMemoryTags(clean5, entry.mediaSummary),
|
|
630908
631988
|
speakers: [],
|
|
@@ -630957,7 +632037,7 @@ ${mediaContext}` : ""
|
|
|
630957
632037
|
const titleTags = tags.slice(0, 4);
|
|
630958
632038
|
const title = titleTags.length > 0 ? `${speaker} / ${titleTags.join(" ")}` : `${speaker} / conversation`;
|
|
630959
632039
|
const card = {
|
|
630960
|
-
id:
|
|
632040
|
+
id: createHash31("sha1").update(`${sessionKey}:${now}:${speaker}:${text}`).digest("hex").slice(0, 12),
|
|
630961
632041
|
title,
|
|
630962
632042
|
notes: [],
|
|
630963
632043
|
tags: [],
|
|
@@ -632278,7 +633358,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
|
|
|
632278
633358
|
routeInstruction,
|
|
632279
633359
|
``,
|
|
632280
633360
|
`Return JSON only with this schema:`,
|
|
632281
|
-
|
|
633361
|
+
TELEGRAM_INTERACTION_DECISION_REPAIR_SCHEMA,
|
|
632282
633362
|
``,
|
|
632283
633363
|
`Original router output:`,
|
|
632284
633364
|
rawPreview,
|
|
@@ -632296,7 +633376,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
|
|
|
632296
633376
|
],
|
|
632297
633377
|
tools: [],
|
|
632298
633378
|
temperature: 0,
|
|
632299
|
-
maxTokens:
|
|
633379
|
+
maxTokens: 800,
|
|
632300
633380
|
timeoutMs: telegramRouterTimeoutMs(timeoutMs, 8e3, 2e4),
|
|
632301
633381
|
think: false
|
|
632302
633382
|
}, diagnostics, "router-repair", sessionKey);
|
|
@@ -632342,7 +633422,7 @@ ${userPrompt.slice(-4e3)}` : userPrompt;
|
|
|
632342
633422
|
`Return exactly one JSON object and no prose. No <think> tags. No commentary.`,
|
|
632343
633423
|
routeInstruction,
|
|
632344
633424
|
``,
|
|
632345
|
-
`Required schema: {
|
|
633425
|
+
`Required schema: ${TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA}`,
|
|
632346
633426
|
``,
|
|
632347
633427
|
`Invalid previous output, for diagnostics only:`,
|
|
632348
633428
|
invalidPreview,
|
|
@@ -632363,7 +633443,7 @@ ${userPrompt.slice(-4e3)}` : userPrompt;
|
|
|
632363
633443
|
],
|
|
632364
633444
|
tools: [],
|
|
632365
633445
|
temperature: 0,
|
|
632366
|
-
maxTokens:
|
|
633446
|
+
maxTokens: 1e3,
|
|
632367
633447
|
timeoutMs: telegramRouterTimeoutMs(timeoutMs, 1e4, 3e4),
|
|
632368
633448
|
think: false
|
|
632369
633449
|
}, diagnostics, "router-strict-retry", sessionKey);
|
|
@@ -632666,19 +633746,12 @@ ${stimulationProbe.context}`,
|
|
|
632666
633746
|
let reflectionNotes;
|
|
632667
633747
|
let reflectionContext;
|
|
632668
633748
|
if (consolidatedMode) {
|
|
632669
|
-
reflectionNotes =
|
|
633749
|
+
reflectionNotes = {};
|
|
632670
633750
|
reflectionContext = [
|
|
632671
|
-
"##
|
|
632672
|
-
"
|
|
632673
|
-
"
|
|
632674
|
-
"
|
|
632675
|
-
" memory_note: what scoped memory should retain or connect",
|
|
632676
|
-
" relationship_note: relationship/thread implication",
|
|
632677
|
-
" procedure_note: active tree/branch/abort implication",
|
|
632678
|
-
" voice_note: final voice implication if a reply happens",
|
|
632679
|
-
" scenario_note: identified scenario and transition state",
|
|
632680
|
-
" scenario_id / scenario_label / scenario_confidence / scenario_objective / scenario_state_loop",
|
|
632681
|
-
"Use these as your attention substrate, then decide route/should_reply/confidence. Return all fields in ONE JSON."
|
|
633751
|
+
"## Router fast-path note policy",
|
|
633752
|
+
"Do not generate silent_disposition, mental_note, memory_note, relationship_note, procedure_note, voice_note, scenario fields, or other internal notes in this router response.",
|
|
633753
|
+
"Only decide route, should_reply, confidence, reason, optional stimulation cadence, and optional explicit reply_mode_preference.",
|
|
633754
|
+
"If notes are needed, the bridge will synthesize or commit them after the visible reply according to the resolved reply mode."
|
|
632682
633755
|
].join("\n");
|
|
632683
633756
|
} else {
|
|
632684
633757
|
reflectionNotes = await this.inferTelegramSilentReflectionNotes(
|
|
@@ -632708,22 +633781,22 @@ ${stimulationProbe.context}`,
|
|
|
632708
633781
|
}
|
|
632709
633782
|
const userPrompt = [
|
|
632710
633783
|
`You are the Telegram live routing and reply-discretion model.`,
|
|
632711
|
-
`
|
|
633784
|
+
`Make the smallest sufficient live attention decision. Do not include internal notes unless explicitly supplied by deliberative mode context.`,
|
|
632712
633785
|
`Use the persona docs below as binding behavioral guidance for whether speaking is appropriate and how to avoid over-eager or adversarially bad interventions.`,
|
|
632713
633786
|
`Return JSON only, with no markdown and no explanation outside JSON.`,
|
|
632714
633787
|
``,
|
|
632715
|
-
`Schema: {
|
|
633788
|
+
`Schema: ${TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA}`,
|
|
632716
633789
|
``,
|
|
632717
633790
|
`Route meanings:`,
|
|
632718
633791
|
`- chat: a short conversational answer can be produced without tools.`,
|
|
632719
633792
|
`- action: tools, workspace context, media processing, web lookup, delegation, or a multi-step agent loop may be needed.`,
|
|
632720
|
-
`Route discipline: infer whether the
|
|
633793
|
+
`Route discipline: infer whether the current request can be completed as immediate conversation or needs an external capability. Do not route from keyword categories.`,
|
|
632721
633794
|
``,
|
|
632722
633795
|
`Reply discretion: make a human-like attention decision from the full social context. Observe the message, relationship stream, reply graph, conversation momentum, prior bot involvement, speaker intent, and notification-like signals, then decide whether a visible reply would be natural.`,
|
|
632723
633796
|
`No hard triggers: direct address, @mentions, name/identity references, private-chat delivery, replies, active threads, and stimulation score are evidence only. They may raise or lower salience, but none guarantees should_reply=true or should_reply=false.`,
|
|
632724
633797
|
`High-salience evidence: private DMs, exact @username matches, display-name self references, and replies to this bot are notification-like signals. They should usually move attention toward deeper processing and a likely response unless the surrounding context makes silence more natural.`,
|
|
632725
633798
|
`No keyword routing: do not use static keyword rules. Infer whether identity references are actually aimed at this bot from syntax, tone, recent turns, and relationships.`,
|
|
632726
|
-
`Observation notes:
|
|
633799
|
+
`Observation notes: omit note fields on the fast path. Do not expose hidden chain-of-thought or produce scratch notes in this router JSON.`,
|
|
632727
633800
|
`Reply-mode preference capture: if and only if the current sender explicitly expresses a durable preference for reply cadence/order, populate reply_mode_preference as a typed update. Do not infer this from style, keywords, tone, or one-off task shape. Use null otherwise.`,
|
|
632728
633801
|
`Reply-mode meanings: reply_then_notes means visible reply first and internal notes afterward; notes_then_reply means internal notes before visible reply; reply_only means one user-facing reply with tools/context and no extra internal notes stage.`,
|
|
632729
633802
|
`Bot-to-bot discipline: sender labels include [bot] or [human]. Treat peer bots as autonomous actors, not human users. Avoid bot loops by replying only when the exchange context makes a response socially useful.`,
|
|
@@ -632790,11 +633863,9 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632790
633863
|
],
|
|
632791
633864
|
tools: [],
|
|
632792
633865
|
temperature: 0,
|
|
632793
|
-
//
|
|
632794
|
-
//
|
|
632795
|
-
|
|
632796
|
-
// for normal verbose values without slowing the call appreciably.
|
|
632797
|
-
maxTokens: 2400,
|
|
633866
|
+
// Minimal route JSON should fit comfortably; keeping this small avoids
|
|
633867
|
+
// reintroducing truncated-note repair cascades.
|
|
633868
|
+
maxTokens: 900,
|
|
632798
633869
|
timeoutMs: telegramRouterTimeoutMs(config.timeoutMs),
|
|
632799
633870
|
think: false
|
|
632800
633871
|
}, diagnostics, "router", sessionKey);
|
|
@@ -632833,7 +633904,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632833
633904
|
],
|
|
632834
633905
|
tools: [],
|
|
632835
633906
|
temperature: 0,
|
|
632836
|
-
maxTokens:
|
|
633907
|
+
maxTokens: 1400,
|
|
632837
633908
|
timeoutMs: telegramRouterTimeoutMs(config.timeoutMs),
|
|
632838
633909
|
think: false
|
|
632839
633910
|
}, diagnostics, "router", sessionKey);
|
|
@@ -633107,7 +634178,7 @@ ${list}` : "No shared group target is currently known for this sender. Ask in th
|
|
|
633107
634178
|
}
|
|
633108
634179
|
telegramRunnerStateDir(sessionKey) {
|
|
633109
634180
|
if (!this.repoRoot) return void 0;
|
|
633110
|
-
const safe =
|
|
634181
|
+
const safe = createHash31("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
633111
634182
|
return join135(this.repoRoot, ".omnius", "telegram-runner-state", safe);
|
|
633112
634183
|
}
|
|
633113
634184
|
buildTelegramAdminOverviewContext(currentSessionKey) {
|
|
@@ -633815,7 +634886,7 @@ Join: ${newUrl}`);
|
|
|
633815
634886
|
);
|
|
633816
634887
|
if (storedPreference) this.subAgentViewCallbacks?.onWrite(attentionViewId || this.viewIdForMessage(msg), `preference: ${storedPreference}`);
|
|
633817
634888
|
const replyMode = this.resolvedTelegramReplyMode(sessionKey, msg);
|
|
633818
|
-
const deliveredDecision = replyMode === "
|
|
634889
|
+
const deliveredDecision = replyMode === "notes_then_reply" ? this.notesThenReplyDecision(decision2, msg) : this.stripTelegramDecisionNotes(decision2);
|
|
633819
634890
|
const daydreamOpportunities = this.markLatestTelegramDaydreamOpportunitiesConsidered(sessionKey, msg);
|
|
633820
634891
|
const shouldDeferNotes = replyMode === "reply_then_notes" && decision2.shouldReply;
|
|
633821
634892
|
if (!shouldDeferNotes) {
|
|
@@ -633849,26 +634920,22 @@ Join: ${newUrl}`);
|
|
|
633849
634920
|
this.enqueueTelegramSubAgentContext(sessionKey, existingAfterDecision, decisionContext, msg.username);
|
|
633850
634921
|
await this.enqueueTelegramQueuedSessionWorkForExistingSubAgent(work, existingAfterDecision);
|
|
633851
634922
|
if (shouldDeferNotes) {
|
|
633852
|
-
this.
|
|
633853
|
-
|
|
633854
|
-
|
|
633855
|
-
attentionViewId,
|
|
633856
|
-
deliveredDecision,
|
|
633857
|
-
this.telegramMessageIdentitySalienceSignals(msg),
|
|
633858
|
-
daydreamOpportunities
|
|
634923
|
+
this.subAgentViewCallbacks?.onWrite(
|
|
634924
|
+
attentionViewId || existingAfterDecision.viewId,
|
|
634925
|
+
"post-reply/internal notes deferred to active reply completion"
|
|
633859
634926
|
);
|
|
633860
634927
|
}
|
|
633861
634928
|
return;
|
|
633862
634929
|
}
|
|
633863
634930
|
const subAgentProfile = decision2.route === "chat" ? "chat" : "action";
|
|
633864
634931
|
if (decision2.route === "chat" && msg.chatType === "private") {
|
|
633865
|
-
await this.handleTelegramChatCompletion(msg, toolContext, [decisionContext, rapidContext].filter(Boolean).join("\n\n"));
|
|
633866
|
-
if (shouldDeferNotes) {
|
|
633867
|
-
this.
|
|
634932
|
+
const visibleReplyAttempted = await this.handleTelegramChatCompletion(msg, toolContext, [decisionContext, rapidContext].filter(Boolean).join("\n\n"));
|
|
634933
|
+
if (shouldDeferNotes && visibleReplyAttempted) {
|
|
634934
|
+
this.deliverTelegramPostReplyNotes(
|
|
633868
634935
|
sessionKey,
|
|
633869
634936
|
msg,
|
|
633870
634937
|
attentionViewId,
|
|
633871
|
-
|
|
634938
|
+
decision2,
|
|
633872
634939
|
this.telegramMessageIdentitySalienceSignals(msg),
|
|
633873
634940
|
daydreamOpportunities
|
|
633874
634941
|
);
|
|
@@ -633957,16 +635024,6 @@ Join: ${newUrl}`);
|
|
|
633957
635024
|
await this.deleteLiveMessage(msg.chatId, subAgent.liveMessageId).catch(() => {
|
|
633958
635025
|
});
|
|
633959
635026
|
}
|
|
633960
|
-
if (shouldDeferNotes) {
|
|
633961
|
-
this.deliverTelegramAttentionDecision(
|
|
633962
|
-
sessionKey,
|
|
633963
|
-
msg,
|
|
633964
|
-
attentionViewId,
|
|
633965
|
-
deliveredDecision,
|
|
633966
|
-
this.telegramMessageIdentitySalienceSignals(msg),
|
|
633967
|
-
daydreamOpportunities
|
|
633968
|
-
);
|
|
633969
|
-
}
|
|
633970
635027
|
return;
|
|
633971
635028
|
}
|
|
633972
635029
|
if (subAgent.liveMessagePromise) {
|
|
@@ -633989,19 +635046,20 @@ Join: ${newUrl}`);
|
|
|
633989
635046
|
finalText,
|
|
633990
635047
|
Boolean(subAgent.liveMessageId && !msg.guestQueryId)
|
|
633991
635048
|
);
|
|
635049
|
+
this.tuiWrite(() => renderTelegramSubAgentComplete(msg.username, finalText));
|
|
635050
|
+
this.subAgentViewCallbacks?.onWrite(subAgent.viewId, `completed: ${finalText}`);
|
|
635051
|
+
this.subAgentViewCallbacks?.onStatus(subAgent.viewId, "completed");
|
|
633992
635052
|
if (shouldDeferNotes) {
|
|
633993
|
-
this.
|
|
635053
|
+
this.deliverTelegramPostReplyNotes(
|
|
633994
635054
|
sessionKey,
|
|
633995
635055
|
msg,
|
|
633996
635056
|
attentionViewId,
|
|
633997
|
-
|
|
635057
|
+
decision2,
|
|
633998
635058
|
this.telegramMessageIdentitySalienceSignals(msg),
|
|
633999
|
-
daydreamOpportunities
|
|
635059
|
+
daydreamOpportunities,
|
|
635060
|
+
finalText
|
|
634000
635061
|
);
|
|
634001
635062
|
}
|
|
634002
|
-
this.tuiWrite(() => renderTelegramSubAgentComplete(msg.username, finalText));
|
|
634003
|
-
this.subAgentViewCallbacks?.onWrite(subAgent.viewId, `completed: ${finalText}`);
|
|
634004
|
-
this.subAgentViewCallbacks?.onStatus(subAgent.viewId, "completed");
|
|
634005
635063
|
} catch (err) {
|
|
634006
635064
|
if (subAgent.typingInterval) {
|
|
634007
635065
|
clearInterval(subAgent.typingInterval);
|
|
@@ -634019,16 +635077,6 @@ Join: ${newUrl}`);
|
|
|
634019
635077
|
await this.deleteLiveMessage(msg.chatId, subAgent.liveMessageId).catch(() => {
|
|
634020
635078
|
});
|
|
634021
635079
|
}
|
|
634022
|
-
if (shouldDeferNotes) {
|
|
634023
|
-
this.deliverTelegramAttentionDecision(
|
|
634024
|
-
sessionKey,
|
|
634025
|
-
msg,
|
|
634026
|
-
attentionViewId,
|
|
634027
|
-
deliveredDecision,
|
|
634028
|
-
this.telegramMessageIdentitySalienceSignals(msg),
|
|
634029
|
-
daydreamOpportunities
|
|
634030
|
-
);
|
|
634031
|
-
}
|
|
634032
635080
|
} finally {
|
|
634033
635081
|
this.clearTelegramSubAgentContextBuffer(sessionKey);
|
|
634034
635082
|
this.subAgents.delete(sessionKey);
|
|
@@ -634156,7 +635204,7 @@ Join: ${newUrl}`);
|
|
|
634156
635204
|
async handleTelegramChatCompletion(msg, toolContext, additionalContext = "") {
|
|
634157
635205
|
if (toolContext === "telegram-admin-dm") {
|
|
634158
635206
|
await this.handleTelegramAdminChatAgent(msg, toolContext, additionalContext);
|
|
634159
|
-
return;
|
|
635207
|
+
return true;
|
|
634160
635208
|
}
|
|
634161
635209
|
const viewId = `${this.viewIdForMessage(msg)}-chat`;
|
|
634162
635210
|
const sessionKey = this.sessionKeyForMessage(msg);
|
|
@@ -634241,7 +635289,7 @@ Join: ${newUrl}`);
|
|
|
634241
635289
|
}
|
|
634242
635290
|
this.subAgentViewCallbacks?.onWrite(viewId, "completed: no model reply");
|
|
634243
635291
|
this.subAgentViewCallbacks?.onStatus(viewId, "completed");
|
|
634244
|
-
return;
|
|
635292
|
+
return false;
|
|
634245
635293
|
}
|
|
634246
635294
|
const finalHtml = convertMarkdownToTelegramHTML(cleaned);
|
|
634247
635295
|
const sentMessageId = await this.sendOrEditFinalTelegramHTML(msg, finalHtml, liveMessageId);
|
|
@@ -634255,6 +635303,7 @@ Join: ${newUrl}`);
|
|
|
634255
635303
|
}
|
|
634256
635304
|
this.subAgentViewCallbacks?.onWrite(viewId, `completed: ${cleaned}`);
|
|
634257
635305
|
this.subAgentViewCallbacks?.onStatus(viewId, "completed");
|
|
635306
|
+
return true;
|
|
634258
635307
|
} catch (err) {
|
|
634259
635308
|
if (typingInterval) {
|
|
634260
635309
|
clearInterval(typingInterval);
|
|
@@ -634273,6 +635322,7 @@ Join: ${newUrl}`);
|
|
|
634273
635322
|
await this.deleteLiveMessage(msg.chatId, liveMessageId).catch(() => {
|
|
634274
635323
|
});
|
|
634275
635324
|
}
|
|
635325
|
+
return false;
|
|
634276
635326
|
} finally {
|
|
634277
635327
|
this.activeChatViews.delete(viewId);
|
|
634278
635328
|
this.activeChatSessions.delete(sessionKey);
|
|
@@ -637934,7 +638984,8 @@ ${caption}\r
|
|
|
637934
638984
|
await this.sendMessageHTML(chatId, html, replyToMessageId);
|
|
637935
638985
|
if (this.voiceEnabled && this.voiceEngineRef) {
|
|
637936
638986
|
try {
|
|
637937
|
-
const ttsText = text.
|
|
638987
|
+
const ttsText = stripTelegramHiddenThinking(text).trim();
|
|
638988
|
+
if (!ttsText) return;
|
|
637938
638989
|
const wavBuffer = await this.voiceEngineRef.synthesizeToBuffer(ttsText);
|
|
637939
638990
|
if (wavBuffer) {
|
|
637940
638991
|
await this.sendVoiceMessage(chatId, wavBuffer);
|
|
@@ -639815,14 +640866,14 @@ var init_access_policy = __esm({
|
|
|
639815
640866
|
});
|
|
639816
640867
|
|
|
639817
640868
|
// packages/cli/src/api/project-preferences.ts
|
|
639818
|
-
import { createHash as
|
|
640869
|
+
import { createHash as createHash32 } from "node:crypto";
|
|
639819
640870
|
import { existsSync as existsSync124, mkdirSync as mkdirSync72, readFileSync as readFileSync101, renameSync as renameSync8, writeFileSync as writeFileSync66, unlinkSync as unlinkSync26 } from "node:fs";
|
|
639820
640871
|
import { homedir as homedir46 } from "node:os";
|
|
639821
640872
|
import { join as join138, resolve as resolve50 } from "node:path";
|
|
639822
640873
|
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
639823
640874
|
function projectKey(root) {
|
|
639824
640875
|
const canonical = resolve50(root);
|
|
639825
|
-
return
|
|
640876
|
+
return createHash32("sha256").update(canonical).digest("hex").slice(0, 16);
|
|
639826
640877
|
}
|
|
639827
640878
|
function projectDir(root) {
|
|
639828
640879
|
return join138(PROJECTS_DIR, projectKey(root));
|
|
@@ -639914,7 +640965,7 @@ __export(voicechat_exports, {
|
|
|
639914
640965
|
VoiceChatSession: () => VoiceChatSession
|
|
639915
640966
|
});
|
|
639916
640967
|
import { EventEmitter as EventEmitter13 } from "node:events";
|
|
639917
|
-
function
|
|
640968
|
+
function clamp0112(x) {
|
|
639918
640969
|
return x < 0 ? 0 : x > 1 ? 1 : x;
|
|
639919
640970
|
}
|
|
639920
640971
|
function alnumRatio(s2) {
|
|
@@ -639953,9 +641004,9 @@ function computeSignalFromText(text, confidence2) {
|
|
|
639953
641004
|
else score = 0.15;
|
|
639954
641005
|
score -= repeatingCharPenalty(t2) * 0.4;
|
|
639955
641006
|
if (typeof confidence2 === "number" && !Number.isNaN(confidence2)) {
|
|
639956
|
-
score = 0.7 * score + 0.3 *
|
|
641007
|
+
score = 0.7 * score + 0.3 * clamp0112(confidence2);
|
|
639957
641008
|
}
|
|
639958
|
-
return
|
|
641009
|
+
return clamp0112(score);
|
|
639959
641010
|
}
|
|
639960
641011
|
function truncateForLog(s2, n2) {
|
|
639961
641012
|
return s2.length <= n2 ? s2 : s2.slice(0, n2 - 1) + "…";
|
|
@@ -640225,7 +641276,7 @@ Rules:
|
|
|
640225
641276
|
}, MAX_SEGMENT_MS);
|
|
640226
641277
|
}
|
|
640227
641278
|
this.captureBuffer = text;
|
|
640228
|
-
this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ?
|
|
641279
|
+
this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp0112(snr) : computeSignalFromText(text, confidence2);
|
|
640229
641280
|
this.emit("snr", { score: this.lastSignalScore });
|
|
640230
641281
|
this.onPartialTranscript(text);
|
|
640231
641282
|
if (this.silenceTimer) clearTimeout(this.silenceTimer);
|
|
@@ -641000,7 +642051,7 @@ var init_disk_task_output = __esm({
|
|
|
641000
642051
|
});
|
|
641001
642052
|
|
|
641002
642053
|
// packages/cli/src/api/http.ts
|
|
641003
|
-
import { createHash as
|
|
642054
|
+
import { createHash as createHash33 } from "node:crypto";
|
|
641004
642055
|
function problemDetails(opts) {
|
|
641005
642056
|
const p2 = {
|
|
641006
642057
|
type: opts.type ?? "about:blank",
|
|
@@ -641063,7 +642114,7 @@ function paginated(items, page2, total) {
|
|
|
641063
642114
|
}
|
|
641064
642115
|
function computeEtag(payload) {
|
|
641065
642116
|
const json = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
641066
|
-
const hash =
|
|
642117
|
+
const hash = createHash33("sha1").update(json).digest("hex").slice(0, 16);
|
|
641067
642118
|
return `W/"${hash}"`;
|
|
641068
642119
|
}
|
|
641069
642120
|
function checkNotModified(req2, res, etag) {
|
|
@@ -655494,7 +656545,7 @@ import { homedir as homedir53 } from "node:os";
|
|
|
655494
656545
|
import { spawn as spawn31, execSync as execSync58 } from "node:child_process";
|
|
655495
656546
|
import { mkdirSync as mkdirSync80, writeFileSync as writeFileSync72, readFileSync as readFileSync109, readdirSync as readdirSync48, existsSync as existsSync135, watch as fsWatch4, renameSync as renameSync9, unlinkSync as unlinkSync28 } from "node:fs";
|
|
655496
656547
|
import { randomBytes as randomBytes27, randomUUID as randomUUID17 } from "node:crypto";
|
|
655497
|
-
import { createHash as
|
|
656548
|
+
import { createHash as createHash35 } from "node:crypto";
|
|
655498
656549
|
function memoryDbPaths3(baseDir = process.cwd()) {
|
|
655499
656550
|
const dir = join149(baseDir, ".omnius");
|
|
655500
656551
|
return {
|
|
@@ -661447,7 +662498,7 @@ function listScheduledTasks() {
|
|
|
661447
662498
|
const schedule = String(t2?.schedule || t2?.cron || t2?.when || "");
|
|
661448
662499
|
const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
|
|
661449
662500
|
const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
|
|
661450
|
-
const fallbackId =
|
|
662501
|
+
const fallbackId = createHash35("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
|
|
661451
662502
|
const uid = realId || fallbackId;
|
|
661452
662503
|
const key = `${uid}`;
|
|
661453
662504
|
if (seen.has(key)) return;
|
|
@@ -661564,8 +662615,8 @@ function deleteScheduledById(id) {
|
|
|
661564
662615
|
if (id) candidates.push(id);
|
|
661565
662616
|
if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id)) candidates.push(entry.id);
|
|
661566
662617
|
try {
|
|
661567
|
-
const { createHash:
|
|
661568
|
-
const fallback =
|
|
662618
|
+
const { createHash: createHash36 } = require4("node:crypto");
|
|
662619
|
+
const fallback = createHash36("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
|
|
661569
662620
|
if (!candidates.includes(fallback)) candidates.push(fallback);
|
|
661570
662621
|
} catch {
|
|
661571
662622
|
}
|
|
@@ -665818,7 +666869,7 @@ ${entry.fullContent}`
|
|
|
665818
666869
|
break;
|
|
665819
666870
|
case "tool_result": {
|
|
665820
666871
|
const rawContent2 = String(event.content ?? "");
|
|
665821
|
-
const displayContent = config.debug ? rawContent2 : rawContent2
|
|
666872
|
+
const displayContent = config.debug ? rawContent2 : stripTrustTierWrapperForTui(rawContent2);
|
|
665822
666873
|
const isSuccessfulTaskCompleteResult = event.toolName === "task_complete" && (event.success ?? false);
|
|
665823
666874
|
if (event.content) scanForSessionSignals(rawContent2);
|
|
665824
666875
|
statusBar?.recordToolSuccessFail(event.toolName ?? "unknown", event.success ?? false);
|
|
@@ -671714,13 +672765,13 @@ ${taskInput}`;
|
|
|
671714
672765
|
writeContent(() => renderError(errMsg));
|
|
671715
672766
|
if (failureStore) {
|
|
671716
672767
|
try {
|
|
671717
|
-
const { createHash:
|
|
672768
|
+
const { createHash: createHash36 } = await import("node:crypto");
|
|
671718
672769
|
failureStore.insert({
|
|
671719
672770
|
taskId: "",
|
|
671720
672771
|
sessionId: `${Date.now()}`,
|
|
671721
672772
|
repoRoot,
|
|
671722
672773
|
failureType: "runtime-error",
|
|
671723
|
-
fingerprint:
|
|
672774
|
+
fingerprint: createHash36("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
|
|
671724
672775
|
filePath: null,
|
|
671725
672776
|
errorMessage: errMsg.slice(0, 500),
|
|
671726
672777
|
context: null,
|