omnius 1.0.165 → 1.0.167
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 +1216 -198
- 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,480 @@ 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(items, opts = {}) {
|
|
543625
|
+
const targetRawTokenBudget = Math.max(0, Math.floor(opts.targetRawTokenBudget ?? 2e3));
|
|
543626
|
+
const perSource = {};
|
|
543627
|
+
const perKind = {};
|
|
543628
|
+
let rawTokens = 0;
|
|
543629
|
+
let consolidatedTokens = 0;
|
|
543630
|
+
for (const item of items) {
|
|
543631
|
+
const tokens = tokenCount(item);
|
|
543632
|
+
const consolidated = isConsolidated(item);
|
|
543633
|
+
if (consolidated)
|
|
543634
|
+
consolidatedTokens += tokens;
|
|
543635
|
+
else
|
|
543636
|
+
rawTokens += tokens;
|
|
543637
|
+
addBucket(perSource, item.source, tokens, consolidated);
|
|
543638
|
+
addBucket(perKind, item.kind, tokens, consolidated);
|
|
543639
|
+
}
|
|
543640
|
+
const totalTokens = rawTokens + consolidatedTokens;
|
|
543641
|
+
const compressionTargetTokens = Math.ceil(rawTokens * 0.6);
|
|
543642
|
+
return {
|
|
543643
|
+
generatedAt: opts.now ?? Date.now(),
|
|
543644
|
+
itemCount: items.length,
|
|
543645
|
+
semanticChunkCount: opts.semanticChunkCount ?? new SemanticChunker().chunk(items, { now: opts.now }).length,
|
|
543646
|
+
totalTokens,
|
|
543647
|
+
rawTokens,
|
|
543648
|
+
consolidatedTokens,
|
|
543649
|
+
rawRatio: totalTokens > 0 ? rawTokens / totalTokens : 0,
|
|
543650
|
+
consolidatedRatio: totalTokens > 0 ? consolidatedTokens / totalTokens : 0,
|
|
543651
|
+
compressionTargetTokens,
|
|
543652
|
+
targetRawTokenBudget,
|
|
543653
|
+
rawTokensToTarget: Math.max(0, rawTokens - targetRawTokenBudget),
|
|
543654
|
+
perSource,
|
|
543655
|
+
perKind
|
|
543656
|
+
};
|
|
543657
|
+
}
|
|
543658
|
+
function extractSemanticEntities(text) {
|
|
543659
|
+
const out = /* @__PURE__ */ new Set();
|
|
543660
|
+
const add2 = (raw) => {
|
|
543661
|
+
const value2 = raw.trim().replace(/[.,;:!?)]$/, "");
|
|
543662
|
+
if (value2.length < 2)
|
|
543663
|
+
return;
|
|
543664
|
+
if (STOP.has(value2.toLowerCase()))
|
|
543665
|
+
return;
|
|
543666
|
+
out.add(value2);
|
|
543667
|
+
};
|
|
543668
|
+
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))
|
|
543669
|
+
add2(m2[0]);
|
|
543670
|
+
for (const m2 of text.matchAll(/@[A-Za-z0-9_]{2,}/g))
|
|
543671
|
+
add2(m2[0].toLowerCase());
|
|
543672
|
+
for (const m2 of text.matchAll(/\b[A-Za-z_][A-Za-z0-9_]*(?:Error|Exception|Failure|Failed)\b/g))
|
|
543673
|
+
add2(m2[0]);
|
|
543674
|
+
for (const m2 of text.matchAll(/\b[a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]+)+\b/g))
|
|
543675
|
+
add2(m2[0]);
|
|
543676
|
+
for (const m2 of text.matchAll(/\b[A-Z][A-Za-z0-9]*(?:[A-Z][A-Za-z0-9]*)?\b/g))
|
|
543677
|
+
add2(m2[0]);
|
|
543678
|
+
for (const m2 of text.matchAll(/\b(?:memory|context|telegram|router|tool|shell|diagnostic|consolidation|forgetting|chunk|reply|notes|voice|trust|semantic)\b/gi))
|
|
543679
|
+
add2(m2[0].toLowerCase());
|
|
543680
|
+
return [...out].slice(0, 24);
|
|
543681
|
+
}
|
|
543682
|
+
function semanticLabelFor(item) {
|
|
543683
|
+
const explicit = item.semanticLabels?.[0] || (Array.isArray(item.metadata?.["semanticLabels"]) ? String(item.metadata["semanticLabels"][0] ?? "") : "");
|
|
543684
|
+
if (explicit.trim())
|
|
543685
|
+
return explicit.trim().toLowerCase();
|
|
543686
|
+
const h = `${item.kind} ${item.source} ${item.content}`.toLowerCase();
|
|
543687
|
+
if (/telegram|@\w|reply|chat|relationship|social/.test(h))
|
|
543688
|
+
return "telegram conversation and relationship state";
|
|
543689
|
+
if (/error|failed|failure|diagnostic|stderr|exit code|exception/.test(h))
|
|
543690
|
+
return "diagnostic errors and recovery";
|
|
543691
|
+
if (/todo|task|goal|plan|current step|completed/.test(h))
|
|
543692
|
+
return "active task and plan";
|
|
543693
|
+
if (/memory|gist|reflection|lesson|prior experience/.test(h))
|
|
543694
|
+
return "retrieved memory and lessons";
|
|
543695
|
+
if (/tool|shell|command|output|stdout|stderr/.test(h))
|
|
543696
|
+
return "tool results and execution evidence";
|
|
543697
|
+
if (/identity|persona|voice|policy|instruction|system prompt/.test(h))
|
|
543698
|
+
return "identity and behavioral constraints";
|
|
543699
|
+
if (/(?:[\w.-]+\/)+[\w./-]+|\.ts\b|\.tsx\b|\.js\b|function|class|export/.test(h))
|
|
543700
|
+
return "codebase files and symbols";
|
|
543701
|
+
return "general working context";
|
|
543702
|
+
}
|
|
543703
|
+
function itemUtility(item, now) {
|
|
543704
|
+
const priority = (item.priority ?? 0) / 100;
|
|
543705
|
+
const importance = (item.importance ?? 5) / 10;
|
|
543706
|
+
const strength = Math.min(1, Math.log2(Math.max(1, item.strength ?? 1)) / 4);
|
|
543707
|
+
const reuse = Math.min(1, (item.reuseCount ?? 0) / 8);
|
|
543708
|
+
const age = item.timestamp ? Math.max(0, now - item.timestamp) : 0;
|
|
543709
|
+
const recency = item.timestamp ? Math.exp(-age / (24 * 60 * 6e4)) : 0.5;
|
|
543710
|
+
return clamp016(0.25 + priority * 0.25 + importance * 0.25 + strength * 0.12 + reuse * 0.08 + recency * 0.05);
|
|
543711
|
+
}
|
|
543712
|
+
function stalenessFor(items, now) {
|
|
543713
|
+
const timestamps = items.map((i2) => i2.timestamp).filter((v) => Number.isFinite(v));
|
|
543714
|
+
if (timestamps.length === 0)
|
|
543715
|
+
return 0.5;
|
|
543716
|
+
const newest = Math.max(...timestamps);
|
|
543717
|
+
return clamp016(1 - Math.exp(-Math.max(0, now - newest) / (6 * 60 * 6e4)));
|
|
543718
|
+
}
|
|
543719
|
+
function summarize(items, maxChars = 420) {
|
|
543720
|
+
const ranked = [...items].sort((a2, b) => (b.priority ?? 0) - (a2.priority ?? 0) || tokenCount(b) - tokenCount(a2));
|
|
543721
|
+
const parts = [];
|
|
543722
|
+
for (const item of ranked.slice(0, 4)) {
|
|
543723
|
+
const text = item.content.replace(/\s+/g, " ").trim();
|
|
543724
|
+
if (!text)
|
|
543725
|
+
continue;
|
|
543726
|
+
parts.push(text.length > 140 ? text.slice(0, 139).trimEnd() + "..." : text);
|
|
543727
|
+
if (parts.join(" ").length >= maxChars)
|
|
543728
|
+
break;
|
|
543729
|
+
}
|
|
543730
|
+
const summary = parts.join(" ");
|
|
543731
|
+
return summary.length > maxChars ? summary.slice(0, maxChars - 3).trimEnd() + "..." : summary;
|
|
543732
|
+
}
|
|
543733
|
+
function openQuestionsFor(items) {
|
|
543734
|
+
const out = [];
|
|
543735
|
+
for (const item of items) {
|
|
543736
|
+
for (const line of item.content.split(/\n+/)) {
|
|
543737
|
+
const trimmed = line.trim();
|
|
543738
|
+
if (!trimmed)
|
|
543739
|
+
continue;
|
|
543740
|
+
if (/[?]$|\b(unresolved|blocked|unknown|gap|needs?|todo|fixme)\b/i.test(trimmed)) {
|
|
543741
|
+
out.push(trimmed.replace(/\s+/g, " ").slice(0, 180));
|
|
543742
|
+
}
|
|
543743
|
+
if (out.length >= 6)
|
|
543744
|
+
return [...new Set(out)];
|
|
543745
|
+
}
|
|
543746
|
+
}
|
|
543747
|
+
return [...new Set(out)];
|
|
543748
|
+
}
|
|
543749
|
+
function entityOverlap(a2, b) {
|
|
543750
|
+
const as = new Set(a2.map((v) => v.toLowerCase()));
|
|
543751
|
+
const bs = new Set(b.map((v) => v.toLowerCase()));
|
|
543752
|
+
if (as.size === 0 || bs.size === 0)
|
|
543753
|
+
return 0;
|
|
543754
|
+
let inter = 0;
|
|
543755
|
+
for (const x of as)
|
|
543756
|
+
if (bs.has(x))
|
|
543757
|
+
inter++;
|
|
543758
|
+
return inter / Math.min(as.size, bs.size);
|
|
543759
|
+
}
|
|
543760
|
+
function groupUtility(items, now) {
|
|
543761
|
+
if (items.length === 0)
|
|
543762
|
+
return 0;
|
|
543763
|
+
const raw = items.reduce((sum, item) => sum + itemUtility(item, now), 0) / items.length;
|
|
543764
|
+
const evidenceBoost = Math.min(0.2, Math.log1p(items.length) / 15);
|
|
543765
|
+
return clamp016(raw + evidenceBoost);
|
|
543766
|
+
}
|
|
543767
|
+
function chunkItemLike(chunk) {
|
|
543768
|
+
const newest = Math.max(0, ...chunk.items.map((i2) => i2.timestamp ?? 0));
|
|
543769
|
+
return {
|
|
543770
|
+
id: chunk.id,
|
|
543771
|
+
source: chunk.sourceKinds.join(","),
|
|
543772
|
+
kind: chunk.kinds.join(","),
|
|
543773
|
+
content: chunk.summary,
|
|
543774
|
+
tokenCount: chunk.tokenEstimate,
|
|
543775
|
+
priority: Math.round(chunk.utilityScore * 100),
|
|
543776
|
+
timestamp: newest || void 0,
|
|
543777
|
+
importance: chunk.items.reduce((s2, i2) => s2 + (i2.importance ?? 5), 0) / Math.max(1, chunk.items.length),
|
|
543778
|
+
strength: chunk.items.reduce((s2, i2) => s2 + (i2.strength ?? 1), 0) / Math.max(1, chunk.items.length),
|
|
543779
|
+
reuseCount: chunk.items.reduce((s2, i2) => s2 + (i2.reuseCount ?? 0), 0),
|
|
543780
|
+
entities: chunk.entities
|
|
543781
|
+
};
|
|
543782
|
+
}
|
|
543783
|
+
function buildActiveForgettingReport(chunksOrItems, opts = {}) {
|
|
543784
|
+
const now = opts.now ?? Date.now();
|
|
543785
|
+
const items = chunksOrItems.map((entry) => "summary" in entry ? chunkItemLike(entry) : entry);
|
|
543786
|
+
const selectiveForgetCandidates = [];
|
|
543787
|
+
const rehearseCandidates = [];
|
|
543788
|
+
const presentButUnused = [];
|
|
543789
|
+
const interferencePairs = [];
|
|
543790
|
+
for (const item of items) {
|
|
543791
|
+
const utility = itemUtility(item, now);
|
|
543792
|
+
const label = semanticLabelFor(item);
|
|
543793
|
+
const unused = (item.reuseCount ?? 0) === 0 && (item.strength ?? 1) <= 1.2;
|
|
543794
|
+
const ageMs = item.lastRetrieved ? Math.max(0, now - item.lastRetrieved) : item.timestamp ? Math.max(0, now - item.timestamp) : Infinity;
|
|
543795
|
+
if (utility < 0.42 && (item.importance ?? 5) <= 5) {
|
|
543796
|
+
selectiveForgetCandidates.push({ id: itemId(item), label, score: 1 - utility, reason: "low utility, low importance, or stale context" });
|
|
543797
|
+
}
|
|
543798
|
+
if ((item.importance ?? 5) >= 7 && ((item.reuseCount ?? 0) > 0 || (item.strength ?? 1) > 1) && ageMs > 30 * 6e4) {
|
|
543799
|
+
rehearseCandidates.push({ id: itemId(item), label, score: utility, reason: "important memory has evidence of reuse but is aging" });
|
|
543800
|
+
}
|
|
543801
|
+
if (unused) {
|
|
543802
|
+
presentButUnused.push({ id: itemId(item), label, score: utility, reason: "present in context without reuse evidence" });
|
|
543803
|
+
}
|
|
543804
|
+
}
|
|
543805
|
+
for (let i2 = 0; i2 < items.length; i2++) {
|
|
543806
|
+
for (let j = i2 + 1; j < items.length; j++) {
|
|
543807
|
+
const a2 = items[i2];
|
|
543808
|
+
const b = items[j];
|
|
543809
|
+
const aEnt = a2.entities ?? extractSemanticEntities(a2.content);
|
|
543810
|
+
const bEnt = b.entities ?? extractSemanticEntities(b.content);
|
|
543811
|
+
const overlap = entityOverlap(aEnt, bEnt);
|
|
543812
|
+
const contradiction = /\b(no longer|superseded|instead|not|failed|wrong|obsolete)\b/i.test(`${a2.content}
|
|
543813
|
+
${b.content}`);
|
|
543814
|
+
const score = overlap + (contradiction ? 0.35 : 0);
|
|
543815
|
+
if (score >= 0.45 && a2.content.trim() !== b.content.trim()) {
|
|
543816
|
+
const aId = itemId(a2);
|
|
543817
|
+
const bId = itemId(b);
|
|
543818
|
+
const sharedEntities = aEnt.filter((entity) => bEnt.map((v) => v.toLowerCase()).includes(entity.toLowerCase()));
|
|
543819
|
+
interferencePairs.push({
|
|
543820
|
+
a: aId,
|
|
543821
|
+
b: bId,
|
|
543822
|
+
aId,
|
|
543823
|
+
bId,
|
|
543824
|
+
aLabel: semanticLabelFor(a2),
|
|
543825
|
+
bLabel: semanticLabelFor(b),
|
|
543826
|
+
score: clamp016(score),
|
|
543827
|
+
overlap: clamp016(score),
|
|
543828
|
+
sharedEntities,
|
|
543829
|
+
reason: contradiction ? "overlapping entities with supersession/negation language" : "overlapping entities compete for recall"
|
|
543830
|
+
});
|
|
543831
|
+
}
|
|
543832
|
+
}
|
|
543833
|
+
}
|
|
543834
|
+
const useful = items.filter((i2) => itemUtility(i2, now) >= 0.5 || (i2.reuseCount ?? 0) > 0).length;
|
|
543835
|
+
const interferencePenalty = Math.min(0.25, interferencePairs.length * 0.03);
|
|
543836
|
+
const activeRetentionEstimate = clamp016(items.length === 0 ? 1 : useful / items.length - interferencePenalty);
|
|
543837
|
+
return {
|
|
543838
|
+
generatedAt: now,
|
|
543839
|
+
activeRetentionEstimate,
|
|
543840
|
+
selectiveForgetCandidates: selectiveForgetCandidates.sort((a2, b) => b.score - a2.score).slice(0, 12),
|
|
543841
|
+
rehearseCandidates: rehearseCandidates.sort((a2, b) => b.score - a2.score).slice(0, 12),
|
|
543842
|
+
presentButUnused: presentButUnused.sort((a2, b) => a2.score - b.score).slice(0, 12),
|
|
543843
|
+
interferencePairs: interferencePairs.sort((a2, b) => b.score - a2.score).slice(0, 20)
|
|
543844
|
+
};
|
|
543845
|
+
}
|
|
543846
|
+
function shouldTriggerContextConsolidation(snapshot, forgetting, opts = {}) {
|
|
543847
|
+
const minRawTokens = opts.minRawTokens ?? snapshot.targetRawTokenBudget;
|
|
543848
|
+
const maxRawRatio = opts.maxRawRatio ?? 0.35;
|
|
543849
|
+
const minRetention = opts.minRetention ?? 0.7;
|
|
543850
|
+
const reasons = [];
|
|
543851
|
+
let score = 0;
|
|
543852
|
+
if (snapshot.rawTokens > minRawTokens) {
|
|
543853
|
+
reasons.push(`raw tokens ${snapshot.rawTokens} exceed target ${minRawTokens}`);
|
|
543854
|
+
score += 0.4;
|
|
543855
|
+
}
|
|
543856
|
+
if (snapshot.rawRatio > maxRawRatio) {
|
|
543857
|
+
reasons.push(`raw ratio ${snapshot.rawRatio.toFixed(2)} exceeds ${maxRawRatio.toFixed(2)}`);
|
|
543858
|
+
score += 0.25;
|
|
543859
|
+
}
|
|
543860
|
+
if (snapshot.rawTokensToTarget > 0) {
|
|
543861
|
+
reasons.push(`${snapshot.rawTokensToTarget} raw tokens must move to reach target`);
|
|
543862
|
+
score += Math.min(0.25, snapshot.rawTokensToTarget / Math.max(1, snapshot.rawTokens));
|
|
543863
|
+
}
|
|
543864
|
+
if (forgetting && forgetting.activeRetentionEstimate < minRetention) {
|
|
543865
|
+
reasons.push(`active retention estimate ${forgetting.activeRetentionEstimate.toFixed(2)} below ${minRetention.toFixed(2)}`);
|
|
543866
|
+
score += 0.25;
|
|
543867
|
+
}
|
|
543868
|
+
if (forgetting && forgetting.interferencePairs.length > 0) {
|
|
543869
|
+
reasons.push(`${forgetting.interferencePairs.length} interference pair(s) detected`);
|
|
543870
|
+
score += Math.min(0.2, forgetting.interferencePairs.length * 0.04);
|
|
543871
|
+
}
|
|
543872
|
+
const minScore = opts.minScore ?? 0.45;
|
|
543873
|
+
return { shouldConsolidate: score >= minScore, reasons, score: clamp016(score) };
|
|
543874
|
+
}
|
|
543875
|
+
function ingestContextFeedbackMarkdown(markdown, opts = {}) {
|
|
543876
|
+
const metrics2 = {};
|
|
543877
|
+
for (const line of markdown.split(/\n/)) {
|
|
543878
|
+
const m2 = line.match(/^\|\s*([^|]+?)\s*\|\s*([^|]+?)\s*\|/);
|
|
543879
|
+
if (!m2)
|
|
543880
|
+
continue;
|
|
543881
|
+
const key = m2[1].trim();
|
|
543882
|
+
const value2 = m2[2].trim();
|
|
543883
|
+
if (!key || key === "Metric" || /^-+$/.test(key))
|
|
543884
|
+
continue;
|
|
543885
|
+
metrics2[key] = parseMetricValue2(value2);
|
|
543886
|
+
}
|
|
543887
|
+
const gaps = [];
|
|
543888
|
+
const gapRegex = /^##\s+GAP\s+(\d+):\s+(.+?)\s*$/gim;
|
|
543889
|
+
const matches = [...markdown.matchAll(gapRegex)];
|
|
543890
|
+
for (let i2 = 0; i2 < matches.length; i2++) {
|
|
543891
|
+
const match = matches[i2];
|
|
543892
|
+
const start2 = match.index + match[0].length;
|
|
543893
|
+
const end = matches[i2 + 1]?.index ?? markdown.search(/\n## Summary:/);
|
|
543894
|
+
const body = markdown.slice(start2, end === -1 ? void 0 : end).trim();
|
|
543895
|
+
const title = match[2].trim();
|
|
543896
|
+
const labels = [
|
|
543897
|
+
"context_window",
|
|
543898
|
+
title.toLowerCase().includes("sleep") ? "dynamic_consolidation" : "",
|
|
543899
|
+
title.toLowerCase().includes("forget") ? "active_forgetting" : "",
|
|
543900
|
+
title.toLowerCase().includes("chunk") ? "semantic_chunking" : ""
|
|
543901
|
+
].filter(Boolean);
|
|
543902
|
+
gaps.push({ id: `gap_${match[1]}`, title, body, labels, metrics: extractInlineMetrics(body) });
|
|
543903
|
+
}
|
|
543904
|
+
const summary = gaps.map((g) => `${g.id}=${g.title}`).join("; ");
|
|
543905
|
+
const source = opts.sourcePath ?? "context-feedback";
|
|
543906
|
+
const items = gaps.map((gap) => ({
|
|
543907
|
+
id: `feedback_${gap.id}`,
|
|
543908
|
+
source,
|
|
543909
|
+
kind: "agent_feedback_gap",
|
|
543910
|
+
content: `${gap.title}
|
|
543911
|
+
${gap.body}`,
|
|
543912
|
+
consolidated: false,
|
|
543913
|
+
priority: 90,
|
|
543914
|
+
timestamp: opts.now,
|
|
543915
|
+
importance: 8,
|
|
543916
|
+
semanticLabels: gap.labels,
|
|
543917
|
+
metadata: { sourcePath: opts.sourcePath, gapId: gap.id }
|
|
543918
|
+
}));
|
|
543919
|
+
const episode = {
|
|
543920
|
+
sessionId: opts.sessionId,
|
|
543921
|
+
modality: "reflection",
|
|
543922
|
+
toolName: "context_feedback_ingest",
|
|
543923
|
+
content: `External agent memory feedback: ${summary || "context organization gaps"}`,
|
|
543924
|
+
importance: 8,
|
|
543925
|
+
decayClass: "procedural",
|
|
543926
|
+
metadata: {
|
|
543927
|
+
kind: "context_feedback",
|
|
543928
|
+
sourcePath: opts.sourcePath,
|
|
543929
|
+
metrics: metrics2,
|
|
543930
|
+
gaps: gaps.map(({ id, title, labels }) => ({ id, title, labels })),
|
|
543931
|
+
semanticLabels: ["context_window", "dynamic_consolidation", "active_forgetting", "semantic_chunking"]
|
|
543932
|
+
}
|
|
543933
|
+
};
|
|
543934
|
+
return { episode, items, chunkItems: items, metrics: metrics2, gaps };
|
|
543935
|
+
}
|
|
543936
|
+
function parseMetricValue2(raw) {
|
|
543937
|
+
const cleaned = raw.trim().replace(/\*\*/g, "");
|
|
543938
|
+
const match = cleaned.match(/-?\d[\d,]*(?:\.\d+)?/);
|
|
543939
|
+
if (!match)
|
|
543940
|
+
return cleaned;
|
|
543941
|
+
const n2 = Number(match[0].replace(/,/g, ""));
|
|
543942
|
+
return Number.isFinite(n2) ? n2 : cleaned;
|
|
543943
|
+
}
|
|
543944
|
+
function extractInlineMetrics(text) {
|
|
543945
|
+
const metrics2 = {};
|
|
543946
|
+
for (const line of text.split(/\n/)) {
|
|
543947
|
+
const bullet = line.match(/^\s*[-*]\s*(?:\*\*)?([^:*]+?)(?:\*\*)?:\s*(.+)$/);
|
|
543948
|
+
if (bullet)
|
|
543949
|
+
metrics2[bullet[1].trim()] = parseMetricValue2(bullet[2]);
|
|
543950
|
+
const bold = line.match(/^\s*(?:\*\*)?([^:*]+):(?:\*\*)?\s*(.+)$/);
|
|
543951
|
+
if (bold)
|
|
543952
|
+
metrics2[bold[1].trim()] = parseMetricValue2(bold[2]);
|
|
543953
|
+
}
|
|
543954
|
+
return metrics2;
|
|
543955
|
+
}
|
|
543956
|
+
var STOP, SemanticChunker, snapshotContextPressure, analyzeActiveForgetting, buildFeedbackIngestion;
|
|
543957
|
+
var init_semanticContext = __esm({
|
|
543958
|
+
"packages/memory/dist/semanticContext.js"() {
|
|
543959
|
+
"use strict";
|
|
543960
|
+
STOP = /* @__PURE__ */ new Set([
|
|
543961
|
+
"the",
|
|
543962
|
+
"and",
|
|
543963
|
+
"for",
|
|
543964
|
+
"with",
|
|
543965
|
+
"that",
|
|
543966
|
+
"this",
|
|
543967
|
+
"from",
|
|
543968
|
+
"into",
|
|
543969
|
+
"have",
|
|
543970
|
+
"has",
|
|
543971
|
+
"was",
|
|
543972
|
+
"were",
|
|
543973
|
+
"will",
|
|
543974
|
+
"should",
|
|
543975
|
+
"would",
|
|
543976
|
+
"could",
|
|
543977
|
+
"about",
|
|
543978
|
+
"because"
|
|
543979
|
+
]);
|
|
543980
|
+
SemanticChunker = class {
|
|
543981
|
+
chunk(items, options2 = {}) {
|
|
543982
|
+
const maxChunks = Math.max(1, Math.floor(options2.maxChunks ?? 7));
|
|
543983
|
+
const now = options2.now ?? Date.now();
|
|
543984
|
+
const groups = [];
|
|
543985
|
+
for (const item of items.filter((i2) => i2.content.trim())) {
|
|
543986
|
+
const entities = [.../* @__PURE__ */ new Set([...item.entities ?? [], ...extractSemanticEntities(item.content)])];
|
|
543987
|
+
const label = semanticLabelFor(item);
|
|
543988
|
+
let target = groups.find((g) => g.label === label && (entityOverlap(g.entities, entities) >= 0.2 || g.items.length < 3));
|
|
543989
|
+
if (!target) {
|
|
543990
|
+
target = groups.find((g) => entityOverlap(g.entities, entities) >= 0.45);
|
|
543991
|
+
}
|
|
543992
|
+
if (!target) {
|
|
543993
|
+
target = { label, items: [], entities: [] };
|
|
543994
|
+
groups.push(target);
|
|
543995
|
+
}
|
|
543996
|
+
target.items.push({ ...item, entities });
|
|
543997
|
+
target.entities = [.../* @__PURE__ */ new Set([...target.entities, ...entities])].slice(0, 32);
|
|
543998
|
+
}
|
|
543999
|
+
while (groups.length > maxChunks) {
|
|
544000
|
+
groups.sort((a2, b) => groupUtility(a2.items, now) - groupUtility(b.items, now));
|
|
544001
|
+
const smallest = groups.shift();
|
|
544002
|
+
let bestIdx = 0;
|
|
544003
|
+
let bestScore = -1;
|
|
544004
|
+
for (let i2 = 0; i2 < groups.length; i2++) {
|
|
544005
|
+
const score = entityOverlap(smallest.entities, groups[i2].entities) + (smallest.label === groups[i2].label ? 1 : 0);
|
|
544006
|
+
if (score > bestScore) {
|
|
544007
|
+
bestScore = score;
|
|
544008
|
+
bestIdx = i2;
|
|
544009
|
+
}
|
|
544010
|
+
}
|
|
544011
|
+
groups[bestIdx].items.push(...smallest.items);
|
|
544012
|
+
groups[bestIdx].entities = [.../* @__PURE__ */ new Set([...groups[bestIdx].entities, ...smallest.entities])].slice(0, 32);
|
|
544013
|
+
}
|
|
544014
|
+
const maxSummaryChars = Math.max(180, Math.floor((options2.targetRawTokenBudget ?? 2e3) / maxChunks) * 4);
|
|
544015
|
+
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));
|
|
544016
|
+
}
|
|
544017
|
+
buildChunk(label, items, entities, now, maxSummaryChars) {
|
|
544018
|
+
const rawTokenEstimate = items.reduce((sum, item) => sum + tokenCount(item), 0);
|
|
544019
|
+
const summary = summarize(items, maxSummaryChars);
|
|
544020
|
+
const tokenEstimate = Math.max(1, estimateTokens(summary));
|
|
544021
|
+
const utilityScore = groupUtility(items, now);
|
|
544022
|
+
const kinds = [...new Set(items.map((i2) => i2.kind))].sort();
|
|
544023
|
+
const sources = [...new Set(items.map((i2) => `${i2.source}:${i2.kind}`))].sort();
|
|
544024
|
+
return {
|
|
544025
|
+
id: `sem_${stableId([label, ...items.map((i2) => itemId(i2)).sort()])}`,
|
|
544026
|
+
label,
|
|
544027
|
+
summary,
|
|
544028
|
+
sourceIds: items.map((i2) => itemId(i2)),
|
|
544029
|
+
entities: entities.slice(0, 16),
|
|
544030
|
+
kinds,
|
|
544031
|
+
sourceKinds: sources,
|
|
544032
|
+
tokenEstimate,
|
|
544033
|
+
rawTokenEstimate,
|
|
544034
|
+
density: tokenEstimate > 0 ? rawTokenEstimate / tokenEstimate : 1,
|
|
544035
|
+
utilityScore,
|
|
544036
|
+
staleness: stalenessFor(items, now),
|
|
544037
|
+
openQuestions: openQuestionsFor(items),
|
|
544038
|
+
evidenceCount: items.length,
|
|
544039
|
+
items
|
|
544040
|
+
};
|
|
544041
|
+
}
|
|
544042
|
+
};
|
|
544043
|
+
snapshotContextPressure = buildContextPressureSnapshot;
|
|
544044
|
+
analyzeActiveForgetting = buildActiveForgettingReport;
|
|
544045
|
+
buildFeedbackIngestion = ingestContextFeedbackMarkdown;
|
|
544046
|
+
}
|
|
544047
|
+
});
|
|
544048
|
+
|
|
543575
544049
|
// packages/memory/dist/index.js
|
|
543576
544050
|
var dist_exports2 = {};
|
|
543577
544051
|
__export(dist_exports2, {
|
|
@@ -543605,18 +544079,23 @@ __export(dist_exports2, {
|
|
|
543605
544079
|
RepoProfileStore: () => RepoProfileStore,
|
|
543606
544080
|
SYMBOL_MEANINGS: () => SYMBOL_MEANINGS,
|
|
543607
544081
|
SelfModel: () => SelfModel,
|
|
544082
|
+
SemanticChunker: () => SemanticChunker,
|
|
543608
544083
|
SocialMemoryStore: () => SocialMemoryStore,
|
|
543609
544084
|
TaskMemoryStore: () => TaskMemoryStore,
|
|
543610
544085
|
TemporalGraph: () => TemporalGraph,
|
|
543611
544086
|
ToolOutcomeTracker: () => ToolOutcomeTracker,
|
|
543612
544087
|
ToolPatternStore: () => ToolPatternStore,
|
|
543613
544088
|
ValidationStore: () => ValidationStore,
|
|
544089
|
+
analyzeActiveForgetting: () => analyzeActiveForgetting,
|
|
543614
544090
|
applyInfluence: () => applyInfluence,
|
|
543615
544091
|
attachTrace: () => attachTrace,
|
|
543616
544092
|
authorityBias: () => authorityBias,
|
|
543617
544093
|
autoDecayClass: () => autoDecayClass,
|
|
543618
544094
|
autoImportance: () => autoImportance,
|
|
543619
544095
|
batchLink: () => batchLink,
|
|
544096
|
+
buildActiveForgettingReport: () => buildActiveForgettingReport,
|
|
544097
|
+
buildContextPressureSnapshot: () => buildContextPressureSnapshot,
|
|
544098
|
+
buildFeedbackIngestion: () => buildFeedbackIngestion,
|
|
543620
544099
|
buildGist: () => buildGist,
|
|
543621
544100
|
buildSelfTrustInfluence: () => buildSelfTrustInfluence,
|
|
543622
544101
|
buildTrace: () => buildTrace,
|
|
@@ -543640,7 +544119,9 @@ __export(dist_exports2, {
|
|
|
543640
544119
|
emptyDevelopmentalMetrics: () => emptyMetrics,
|
|
543641
544120
|
engagementScore: () => engagementScore,
|
|
543642
544121
|
episodeCount: () => episodeCount,
|
|
544122
|
+
estimateContextTokens: () => estimateContextTokens,
|
|
543643
544123
|
extractQueryEntities: () => extractQueryEntities,
|
|
544124
|
+
extractSemanticEntities: () => extractSemanticEntities,
|
|
543644
544125
|
extractTrace: () => extractTrace,
|
|
543645
544126
|
findNeighbors: () => findNeighbors,
|
|
543646
544127
|
fingerprintSignature: () => fingerprintSignature,
|
|
@@ -543651,6 +544132,7 @@ __export(dist_exports2, {
|
|
|
543651
544132
|
goalHashOf: () => goalHashOf,
|
|
543652
544133
|
importanceMultiplier: () => importanceMultiplier,
|
|
543653
544134
|
inferDomainFromEpisode: () => inferDomainFromEpisode,
|
|
544135
|
+
ingestContextFeedbackMarkdown: () => ingestContextFeedbackMarkdown,
|
|
543654
544136
|
initDb: () => initDb,
|
|
543655
544137
|
isSessionGist: () => isSessionGist,
|
|
543656
544138
|
lightSleep: () => lightSleep,
|
|
@@ -543672,7 +544154,9 @@ __export(dist_exports2, {
|
|
|
543672
544154
|
selectAndWalkGraphCandidate: () => selectAndWalkGraphCandidate,
|
|
543673
544155
|
selectInnerGraphCandidates: () => selectInnerGraphCandidates,
|
|
543674
544156
|
selfTrustFor: () => selfTrustFor,
|
|
544157
|
+
shouldTriggerContextConsolidation: () => shouldTriggerContextConsolidation,
|
|
543675
544158
|
slowWaveReplay: () => slowWaveReplay,
|
|
544159
|
+
snapshotContextPressure: () => snapshotContextPressure,
|
|
543676
544160
|
splanifoldCosine: () => cosine,
|
|
543677
544161
|
splanifoldDeserialize: () => deserialize,
|
|
543678
544162
|
splanifoldEvaluate: () => evaluate2,
|
|
@@ -543724,6 +544208,7 @@ var init_dist7 = __esm({
|
|
|
543724
544208
|
init_stagnationRecipes();
|
|
543725
544209
|
init_codebaseMap();
|
|
543726
544210
|
init_embeddingDrift();
|
|
544211
|
+
init_semanticContext();
|
|
543727
544212
|
}
|
|
543728
544213
|
});
|
|
543729
544214
|
|
|
@@ -546196,7 +546681,7 @@ var init_failureHandoff = __esm({
|
|
|
546196
546681
|
});
|
|
546197
546682
|
|
|
546198
546683
|
// packages/orchestrator/dist/context-fabric.js
|
|
546199
|
-
function
|
|
546684
|
+
function estimateTokens2(text) {
|
|
546200
546685
|
return Math.ceil(text.length / 4);
|
|
546201
546686
|
}
|
|
546202
546687
|
function normalizeSignalContent(content) {
|
|
@@ -546213,6 +546698,54 @@ function truncateText2(text, maxChars) {
|
|
|
546213
546698
|
truncated: true
|
|
546214
546699
|
};
|
|
546215
546700
|
}
|
|
546701
|
+
function compactDiagnosticValue(value2, depth = 0) {
|
|
546702
|
+
if (value2 == null)
|
|
546703
|
+
return value2;
|
|
546704
|
+
if (typeof value2 === "string") {
|
|
546705
|
+
return value2.length > 240 ? `${value2.slice(0, 237)}...` : value2;
|
|
546706
|
+
}
|
|
546707
|
+
if (typeof value2 === "number" || typeof value2 === "boolean")
|
|
546708
|
+
return value2;
|
|
546709
|
+
if (Array.isArray(value2)) {
|
|
546710
|
+
if (depth >= 2)
|
|
546711
|
+
return `[array:${value2.length}]`;
|
|
546712
|
+
return value2.slice(0, 8).map((entry) => compactDiagnosticValue(entry, depth + 1));
|
|
546713
|
+
}
|
|
546714
|
+
if (typeof value2 === "object") {
|
|
546715
|
+
if (depth >= 2)
|
|
546716
|
+
return "[object]";
|
|
546717
|
+
const out = {};
|
|
546718
|
+
for (const [key, entry] of Object.entries(value2).slice(0, 12)) {
|
|
546719
|
+
if (/^(content|text|prompt|messages|transcript)$/i.test(key)) {
|
|
546720
|
+
out[key] = typeof entry === "string" ? `[omitted:${entry.length}]` : "[omitted]";
|
|
546721
|
+
} else {
|
|
546722
|
+
out[key] = compactDiagnosticValue(entry, depth + 1);
|
|
546723
|
+
}
|
|
546724
|
+
}
|
|
546725
|
+
return out;
|
|
546726
|
+
}
|
|
546727
|
+
return String(value2);
|
|
546728
|
+
}
|
|
546729
|
+
function collectMetadataReports(signals) {
|
|
546730
|
+
const pressureReports = [];
|
|
546731
|
+
const forgettingReports = [];
|
|
546732
|
+
for (const signal of signals) {
|
|
546733
|
+
const metadata = signal.metadata ?? {};
|
|
546734
|
+
for (const [key, value2] of Object.entries(metadata)) {
|
|
546735
|
+
if (value2 == null)
|
|
546736
|
+
continue;
|
|
546737
|
+
if (/pressure/i.test(key))
|
|
546738
|
+
pressureReports.push(compactDiagnosticValue(value2));
|
|
546739
|
+
if (/forgetting|retention|interference/i.test(key)) {
|
|
546740
|
+
forgettingReports.push(compactDiagnosticValue(value2));
|
|
546741
|
+
}
|
|
546742
|
+
}
|
|
546743
|
+
}
|
|
546744
|
+
return {
|
|
546745
|
+
pressureReports: pressureReports.length > 0 ? pressureReports : void 0,
|
|
546746
|
+
forgettingReports: forgettingReports.length > 0 ? forgettingReports : void 0
|
|
546747
|
+
};
|
|
546748
|
+
}
|
|
546216
546749
|
function signalFromBlock(kind, source, content, options2 = {}) {
|
|
546217
546750
|
const normalized = normalizeSignalContent(content ?? "");
|
|
546218
546751
|
if (!normalized)
|
|
@@ -546243,6 +546776,7 @@ var init_context_fabric = __esm({
|
|
|
546243
546776
|
"tool_cache",
|
|
546244
546777
|
"skill_manifest",
|
|
546245
546778
|
"memory",
|
|
546779
|
+
"semantic_chunk",
|
|
546246
546780
|
"session_history",
|
|
546247
546781
|
"anchor",
|
|
546248
546782
|
"handoff",
|
|
@@ -546258,6 +546792,7 @@ var init_context_fabric = __esm({
|
|
|
546258
546792
|
tool_cache: "Tool Cache",
|
|
546259
546793
|
skill_manifest: "Skill Manifest",
|
|
546260
546794
|
memory: "Memory",
|
|
546795
|
+
semantic_chunk: "Semantic Context",
|
|
546261
546796
|
session_history: "Session History",
|
|
546262
546797
|
anchor: "Relevant Anchors",
|
|
546263
546798
|
handoff: "Handoff",
|
|
@@ -546273,6 +546808,7 @@ var init_context_fabric = __esm({
|
|
|
546273
546808
|
tool_cache: 2200,
|
|
546274
546809
|
skill_manifest: 900,
|
|
546275
546810
|
memory: 1500,
|
|
546811
|
+
semantic_chunk: 2200,
|
|
546276
546812
|
session_history: 1400,
|
|
546277
546813
|
anchor: 1100,
|
|
546278
546814
|
handoff: 1600,
|
|
@@ -546362,6 +546898,7 @@ var init_context_fabric = __esm({
|
|
|
546362
546898
|
const dropped = [];
|
|
546363
546899
|
const sectionLines = [];
|
|
546364
546900
|
const sectionDiagnostics = [];
|
|
546901
|
+
const metadataReports = collectMetadataReports(sanitized);
|
|
546365
546902
|
let truncatedSignals = 0;
|
|
546366
546903
|
for (const kind of KIND_ORDER) {
|
|
546367
546904
|
const bucket = byKind.get(kind);
|
|
@@ -546424,6 +546961,8 @@ var init_context_fabric = __esm({
|
|
|
546424
546961
|
truncatedSignals: 0,
|
|
546425
546962
|
estimatedTokens: 0,
|
|
546426
546963
|
totalChars: 0,
|
|
546964
|
+
semanticChunkCount: 0,
|
|
546965
|
+
...metadataReports,
|
|
546427
546966
|
sections: []
|
|
546428
546967
|
},
|
|
546429
546968
|
included: [],
|
|
@@ -546443,7 +546982,7 @@ var init_context_fabric = __esm({
|
|
|
546443
546982
|
if (options2.includeDiagnostics) {
|
|
546444
546983
|
content += `
|
|
546445
546984
|
|
|
546446
|
-
context_fabric: included=${included.length} dropped=${dropped.length} truncated=${truncatedSignals} est_tokens=${
|
|
546985
|
+
context_fabric: included=${included.length} dropped=${dropped.length} truncated=${truncatedSignals} est_tokens=${estimateTokens2(content)}`;
|
|
546447
546986
|
}
|
|
546448
546987
|
return {
|
|
546449
546988
|
content,
|
|
@@ -546451,8 +546990,10 @@ context_fabric: included=${included.length} dropped=${dropped.length} truncated=
|
|
|
546451
546990
|
includedSignals: included.length,
|
|
546452
546991
|
droppedSignals: dropped.length,
|
|
546453
546992
|
truncatedSignals,
|
|
546454
|
-
estimatedTokens:
|
|
546993
|
+
estimatedTokens: estimateTokens2(content),
|
|
546455
546994
|
totalChars: content.length,
|
|
546995
|
+
semanticChunkCount: included.filter((signal) => signal.kind === "semantic_chunk").length,
|
|
546996
|
+
...metadataReports,
|
|
546456
546997
|
sections: sectionDiagnostics
|
|
546457
546998
|
},
|
|
546458
546999
|
included,
|
|
@@ -546474,7 +547015,7 @@ import { existsSync as existsSync81, readFileSync as readFileSync62, statSync as
|
|
|
546474
547015
|
import { execSync as execSync46 } from "node:child_process";
|
|
546475
547016
|
import { homedir as homedir29, platform as platform3, arch as arch2, totalmem as totalmem3, freemem as freemem3, hostname as hostname3 } from "node:os";
|
|
546476
547017
|
import { join as join94 } from "node:path";
|
|
546477
|
-
import { createHash as
|
|
547018
|
+
import { createHash as createHash21 } from "node:crypto";
|
|
546478
547019
|
function capturePreflightSnapshot(workingDir) {
|
|
546479
547020
|
const warnings = [];
|
|
546480
547021
|
const configFingerprints = {};
|
|
@@ -546641,7 +547182,7 @@ function expandPath(p2) {
|
|
|
546641
547182
|
return p2;
|
|
546642
547183
|
}
|
|
546643
547184
|
function sha2563(s2) {
|
|
546644
|
-
return
|
|
547185
|
+
return createHash21("sha256").update(s2).digest("hex").slice(0, 16);
|
|
546645
547186
|
}
|
|
546646
547187
|
function freeDiskBytes(path12 = "/tmp") {
|
|
546647
547188
|
try {
|
|
@@ -547517,6 +548058,115 @@ import { join as _pathJoin, resolve as _pathResolve } from "node:path";
|
|
|
547517
548058
|
import { tmpdir as _osTmpdir } from "node:os";
|
|
547518
548059
|
import { homedir as _osHomedir } from "node:os";
|
|
547519
548060
|
import { z as z15 } from "zod";
|
|
548061
|
+
function textFromMessageContent(content) {
|
|
548062
|
+
if (typeof content === "string")
|
|
548063
|
+
return content;
|
|
548064
|
+
if (!Array.isArray(content))
|
|
548065
|
+
return "";
|
|
548066
|
+
return content.map((part) => part.type === "text" ? part.text ?? "" : "[image]").join("\n");
|
|
548067
|
+
}
|
|
548068
|
+
function normalizeContextSnippet(text, maxChars = 900) {
|
|
548069
|
+
const normalized = text.replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
548070
|
+
if (normalized.length <= maxChars)
|
|
548071
|
+
return normalized;
|
|
548072
|
+
return `${normalized.slice(0, maxChars - 18).trimEnd()}
|
|
548073
|
+
... [bounded]`;
|
|
548074
|
+
}
|
|
548075
|
+
function estimateMessagesTokens(messages2) {
|
|
548076
|
+
let chars = 0;
|
|
548077
|
+
for (const message2 of messages2) {
|
|
548078
|
+
chars += textFromMessageContent(message2.content).length;
|
|
548079
|
+
if (message2.tool_calls) {
|
|
548080
|
+
for (const call of message2.tool_calls) {
|
|
548081
|
+
chars += call.function.arguments.length + call.function.name.length;
|
|
548082
|
+
}
|
|
548083
|
+
}
|
|
548084
|
+
}
|
|
548085
|
+
return Math.ceil(chars / 4);
|
|
548086
|
+
}
|
|
548087
|
+
function buildFallbackSemanticChunks(items, maxChunks = 7) {
|
|
548088
|
+
const normalized = items.map((item) => ({ ...item, content: normalizeContextSnippet(item.content, 900) })).filter((item) => item.content.length > 0);
|
|
548089
|
+
const bucketOrder = [
|
|
548090
|
+
{ label: "Goal and Plan", kinds: ["goal", "task_state"] },
|
|
548091
|
+
{ label: "Failure and Risk", kinds: ["recent_failure"] },
|
|
548092
|
+
{ label: "Files and Anchors", kinds: ["known_files", "anchor"] },
|
|
548093
|
+
{ label: "Knowledge and Memory", kinds: ["tool_cache", "memory"] },
|
|
548094
|
+
{ label: "Recent Dialogue", kinds: ["recent_message", "session_history"] },
|
|
548095
|
+
{ label: "Environment", kinds: ["environment"] }
|
|
548096
|
+
];
|
|
548097
|
+
const chunks = [];
|
|
548098
|
+
for (const bucket of bucketOrder) {
|
|
548099
|
+
const bucketItems = normalized.filter((item) => bucket.kinds.includes(item.kind)).sort((a2, b) => (b.priority ?? 0) - (a2.priority ?? 0));
|
|
548100
|
+
if (bucketItems.length === 0)
|
|
548101
|
+
continue;
|
|
548102
|
+
const rawChars = bucketItems.reduce((sum, item) => sum + item.content.length, 0);
|
|
548103
|
+
const lines = bucketItems.slice(0, 5).map((item) => {
|
|
548104
|
+
const oneLine = item.content.replace(/\s+/g, " ").trim();
|
|
548105
|
+
return `- ${item.label}: ${oneLine.slice(0, 360)}`;
|
|
548106
|
+
});
|
|
548107
|
+
const content = normalizeContextSnippet(lines.join("\n"), 850);
|
|
548108
|
+
chunks.push({
|
|
548109
|
+
id: bucket.label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),
|
|
548110
|
+
label: bucket.label,
|
|
548111
|
+
content,
|
|
548112
|
+
sourceIds: bucketItems.map((item) => item.id).slice(0, 12),
|
|
548113
|
+
priority: Math.max(...bucketItems.map((item) => item.priority ?? 0)),
|
|
548114
|
+
metadata: {
|
|
548115
|
+
labels: bucketItems.map((item) => item.label).slice(0, 8),
|
|
548116
|
+
compression: {
|
|
548117
|
+
rawChars,
|
|
548118
|
+
chunkChars: content.length,
|
|
548119
|
+
ratio: rawChars > 0 ? Number((content.length / rawChars).toFixed(3)) : 1
|
|
548120
|
+
}
|
|
548121
|
+
}
|
|
548122
|
+
});
|
|
548123
|
+
if (chunks.length >= maxChunks)
|
|
548124
|
+
break;
|
|
548125
|
+
}
|
|
548126
|
+
if (chunks.length < maxChunks) {
|
|
548127
|
+
const used = new Set(chunks.flatMap((chunk) => chunk.sourceIds));
|
|
548128
|
+
const leftovers = normalized.filter((item) => !used.has(item.id));
|
|
548129
|
+
for (const item of leftovers.slice(0, maxChunks - chunks.length)) {
|
|
548130
|
+
chunks.push({
|
|
548131
|
+
id: item.id,
|
|
548132
|
+
label: item.label,
|
|
548133
|
+
content: normalizeContextSnippet(item.content, 650),
|
|
548134
|
+
sourceIds: [item.id],
|
|
548135
|
+
priority: item.priority ?? 0,
|
|
548136
|
+
metadata: {
|
|
548137
|
+
labels: [item.label],
|
|
548138
|
+
compression: {
|
|
548139
|
+
rawChars: item.content.length,
|
|
548140
|
+
chunkChars: item.content.length,
|
|
548141
|
+
ratio: 1
|
|
548142
|
+
}
|
|
548143
|
+
}
|
|
548144
|
+
});
|
|
548145
|
+
}
|
|
548146
|
+
}
|
|
548147
|
+
return chunks.slice(0, maxChunks);
|
|
548148
|
+
}
|
|
548149
|
+
function shouldRunDynamicContextConsolidation(input) {
|
|
548150
|
+
const reasons = [];
|
|
548151
|
+
const rawRatio = input.snapshot.rawRatio;
|
|
548152
|
+
if (input.snapshot.rawTokens > input.snapshot.targetTokens)
|
|
548153
|
+
reasons.push("raw_tokens_over_target");
|
|
548154
|
+
if (rawRatio >= 0.85)
|
|
548155
|
+
reasons.push("raw_ratio_high");
|
|
548156
|
+
const dropped = input.frameDiagnostics?.droppedSignals ?? input.snapshot.droppedSignals ?? 0;
|
|
548157
|
+
const truncated = input.frameDiagnostics?.truncatedSignals ?? input.snapshot.truncatedSignals ?? 0;
|
|
548158
|
+
if (dropped > 0 || truncated > 0)
|
|
548159
|
+
reasons.push("fabric_pressure");
|
|
548160
|
+
const retention = Number(input.forgettingReport?.["retentionScore"] ?? input.forgettingReport?.["retention"] ?? NaN);
|
|
548161
|
+
const interference = Number(input.forgettingReport?.["interferenceScore"] ?? input.forgettingReport?.["interference"] ?? NaN);
|
|
548162
|
+
if (Number.isFinite(retention) && retention < 0.45)
|
|
548163
|
+
reasons.push("low_retention");
|
|
548164
|
+
if (Number.isFinite(interference) && interference > 0.65)
|
|
548165
|
+
reasons.push("high_interference");
|
|
548166
|
+
if (input.memoryHelperDecision === true)
|
|
548167
|
+
reasons.push("memory_helper_trigger");
|
|
548168
|
+
return { shouldRun: reasons.length > 0, reasons: [...new Set(reasons)], rawRatio };
|
|
548169
|
+
}
|
|
547520
548170
|
function repairJson(raw) {
|
|
547521
548171
|
if (!raw || typeof raw !== "string")
|
|
547522
548172
|
return null;
|
|
@@ -548254,6 +548904,10 @@ var init_agenticRunner = __esm({
|
|
|
548254
548904
|
// ledger and emitted as one bounded frame before each model call.
|
|
548255
548905
|
_contextLedger = new ContextLedger();
|
|
548256
548906
|
_contextFrameBuilder = new ContextFrameBuilder();
|
|
548907
|
+
_lastContextFrameDiagnostics = null;
|
|
548908
|
+
_lastContextPressureSnapshot = null;
|
|
548909
|
+
_lastActiveForgettingReport = null;
|
|
548910
|
+
_lastContextConsolidationTurn = -1e3;
|
|
548257
548911
|
/** WO-AM-10: Process pending episode embeddings in background batches */
|
|
548258
548912
|
async processPendingEmbeddings() {
|
|
548259
548913
|
if (this._pendingEmbeddings.length === 0 || !this._episodeStore)
|
|
@@ -550424,52 +551078,361 @@ ${latest.output || ""}`.trim();
|
|
|
550424
551078
|
const insertAt = Math.max(0, messages2.length - 1);
|
|
550425
551079
|
messages2.splice(insertAt, 0, { role: "system", content: frame });
|
|
550426
551080
|
}
|
|
550427
|
-
|
|
551081
|
+
_activeContextItem(kind, id, source, label, content, priority = 0, metadata) {
|
|
551082
|
+
const normalized = normalizeContextSnippet(content ?? "", 1200);
|
|
551083
|
+
if (!normalized)
|
|
551084
|
+
return null;
|
|
551085
|
+
return { id, kind, source, label, content: normalized, priority, metadata };
|
|
551086
|
+
}
|
|
551087
|
+
_normalizeExternalContextItems(raw) {
|
|
551088
|
+
const arr = Array.isArray(raw) ? raw : [];
|
|
551089
|
+
return arr.map((entry, index) => {
|
|
551090
|
+
if (typeof entry === "string") {
|
|
551091
|
+
return this._activeContextItem("recent_message", `external-message-${index}`, "memory.contextItemsFromMessages", "Recent message", entry, 20);
|
|
551092
|
+
}
|
|
551093
|
+
if (!entry || typeof entry !== "object")
|
|
551094
|
+
return null;
|
|
551095
|
+
const obj = entry;
|
|
551096
|
+
const content = String(obj["content"] ?? obj["text"] ?? obj["summary"] ?? "");
|
|
551097
|
+
const kind = String(obj["kind"] ?? obj["type"] ?? "recent_message");
|
|
551098
|
+
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);
|
|
551099
|
+
}).filter(Boolean);
|
|
551100
|
+
}
|
|
551101
|
+
async _collectActiveSemanticContextItems(input) {
|
|
551102
|
+
const items = [];
|
|
551103
|
+
const add2 = (item) => {
|
|
551104
|
+
if (item)
|
|
551105
|
+
items.push(item);
|
|
551106
|
+
};
|
|
551107
|
+
add2(this._activeContextItem("goal", "active-task", "run.goal", "Active task", input.goalBlock, 100));
|
|
551108
|
+
add2(this._activeContextItem("known_files", "filesystem-state", "turn.files", "Filesystem state", input.filesystemBlock, 70));
|
|
551109
|
+
add2(this._activeContextItem("task_state", "todo-state", "turn.todos", "Todo state", input.todoBlock, 80));
|
|
551110
|
+
add2(this._activeContextItem("recent_failure", "recent-failures", "turn.failures", "Recent failures", input.failureBlock, 95));
|
|
551111
|
+
add2(this._activeContextItem("recent_failure", "write-churn", "turn.churn", "Write churn", input.churnBlock, 75));
|
|
551112
|
+
add2(this._activeContextItem("tool_cache", "tool-cache", "turn.tool-cache", "Tool cache", input.toolCacheBlock, 65));
|
|
551113
|
+
add2(this._activeContextItem("anchor", "anchors", "turn.anchors", "Relevant anchors", input.anchorsBlock, 50));
|
|
551114
|
+
add2(this._activeContextItem("environment", "environment", "turn.environment", "Environment", input.environmentBlock, 35));
|
|
551115
|
+
if (this._lastPprMemoryLines.length > 0) {
|
|
551116
|
+
add2(this._activeContextItem("memory", "ppr-memory", "turn.ppr-memory", "Associative memory", this._lastPprMemoryLines.slice(0, 5).join("\n"), 60));
|
|
551117
|
+
}
|
|
551118
|
+
let helperItems = [];
|
|
551119
|
+
try {
|
|
551120
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551121
|
+
if (typeof memMod.contextItemsFromMessages === "function") {
|
|
551122
|
+
helperItems = this._normalizeExternalContextItems(await memMod.contextItemsFromMessages(input.messages.slice(-12)));
|
|
551123
|
+
}
|
|
551124
|
+
} catch {
|
|
551125
|
+
helperItems = [];
|
|
551126
|
+
}
|
|
551127
|
+
if (helperItems.length > 0) {
|
|
551128
|
+
items.push(...helperItems.slice(0, 8));
|
|
551129
|
+
} else {
|
|
551130
|
+
const tail = input.messages.filter((message2) => message2.role !== "tool").slice(-8);
|
|
551131
|
+
tail.forEach((message2, index) => {
|
|
551132
|
+
const text = textFromMessageContent(message2.content);
|
|
551133
|
+
add2(this._activeContextItem("recent_message", `recent-message-${index}`, "turn.messages", `${message2.role} message`, text, message2.role === "user" ? 45 : 25));
|
|
551134
|
+
});
|
|
551135
|
+
}
|
|
551136
|
+
return items;
|
|
551137
|
+
}
|
|
551138
|
+
_normalizeSemanticChunks(raw) {
|
|
551139
|
+
const arr = Array.isArray(raw) ? raw : [];
|
|
551140
|
+
return arr.map((entry, index) => {
|
|
551141
|
+
if (typeof entry === "string") {
|
|
551142
|
+
const content2 = normalizeContextSnippet(entry, 850);
|
|
551143
|
+
if (!content2)
|
|
551144
|
+
return null;
|
|
551145
|
+
return {
|
|
551146
|
+
id: `semantic-${index}`,
|
|
551147
|
+
label: `Semantic chunk ${index + 1}`,
|
|
551148
|
+
content: content2,
|
|
551149
|
+
sourceIds: [],
|
|
551150
|
+
priority: 0,
|
|
551151
|
+
metadata: { labels: [`Semantic chunk ${index + 1}`] }
|
|
551152
|
+
};
|
|
551153
|
+
}
|
|
551154
|
+
if (!entry || typeof entry !== "object")
|
|
551155
|
+
return null;
|
|
551156
|
+
const obj = entry;
|
|
551157
|
+
const content = normalizeContextSnippet(String(obj["content"] ?? obj["text"] ?? obj["summary"] ?? ""), 850);
|
|
551158
|
+
if (!content)
|
|
551159
|
+
return null;
|
|
551160
|
+
const label = String(obj["label"] ?? obj["title"] ?? obj["topic"] ?? `Semantic chunk ${index + 1}`);
|
|
551161
|
+
const sourceIds = Array.isArray(obj["sourceIds"]) ? obj["sourceIds"].map(String) : Array.isArray(obj["sources"]) ? obj["sources"].map(String) : [];
|
|
551162
|
+
return {
|
|
551163
|
+
id: String(obj["id"] ?? (label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `semantic-${index}`)),
|
|
551164
|
+
label,
|
|
551165
|
+
content,
|
|
551166
|
+
sourceIds,
|
|
551167
|
+
priority: typeof obj["priority"] === "number" ? obj["priority"] : 0,
|
|
551168
|
+
metadata: typeof obj["metadata"] === "object" && obj["metadata"] !== null ? obj["metadata"] : { labels: [label] }
|
|
551169
|
+
};
|
|
551170
|
+
}).filter(Boolean);
|
|
551171
|
+
}
|
|
551172
|
+
async _buildPressureSnapshot(input) {
|
|
551173
|
+
let snapshot = {
|
|
551174
|
+
rawTokens: input.rawTokens,
|
|
551175
|
+
targetTokens: input.targetTokens,
|
|
551176
|
+
rawRatio: input.targetTokens > 0 ? Number((input.rawTokens / input.targetTokens).toFixed(3)) : 0,
|
|
551177
|
+
semanticChunkCount: input.semanticChunkCount
|
|
551178
|
+
};
|
|
551179
|
+
try {
|
|
551180
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551181
|
+
if (typeof memMod.buildContextPressureSnapshot === "function") {
|
|
551182
|
+
const helperSnapshot = await memMod.buildContextPressureSnapshot({
|
|
551183
|
+
items: input.items,
|
|
551184
|
+
messages: input.messages,
|
|
551185
|
+
rawTokens: input.rawTokens,
|
|
551186
|
+
targetTokens: input.targetTokens
|
|
551187
|
+
});
|
|
551188
|
+
if (helperSnapshot && typeof helperSnapshot === "object") {
|
|
551189
|
+
snapshot = { ...snapshot, ...helperSnapshot };
|
|
551190
|
+
snapshot.rawTokens = Number(snapshot.rawTokens ?? input.rawTokens);
|
|
551191
|
+
snapshot.targetTokens = Number(snapshot.targetTokens ?? input.targetTokens);
|
|
551192
|
+
snapshot.rawRatio = Number(snapshot.rawRatio ?? (snapshot.targetTokens > 0 ? (snapshot.rawTokens / snapshot.targetTokens).toFixed(3) : 0));
|
|
551193
|
+
}
|
|
551194
|
+
}
|
|
551195
|
+
} catch {
|
|
551196
|
+
}
|
|
551197
|
+
return snapshot;
|
|
551198
|
+
}
|
|
551199
|
+
async _buildActiveForgettingReport(input) {
|
|
551200
|
+
try {
|
|
551201
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551202
|
+
if (typeof memMod.buildActiveForgettingReport !== "function")
|
|
551203
|
+
return null;
|
|
551204
|
+
const report2 = await memMod.buildActiveForgettingReport(input);
|
|
551205
|
+
return report2 && typeof report2 === "object" ? report2 : null;
|
|
551206
|
+
} catch {
|
|
551207
|
+
return null;
|
|
551208
|
+
}
|
|
551209
|
+
}
|
|
551210
|
+
async _buildSemanticContextSignals(input) {
|
|
551211
|
+
let chunks = [];
|
|
551212
|
+
try {
|
|
551213
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551214
|
+
const Chunker = memMod.SemanticChunker;
|
|
551215
|
+
if (typeof Chunker === "function") {
|
|
551216
|
+
const chunker = new Chunker({ maxChunks: 7 });
|
|
551217
|
+
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;
|
|
551218
|
+
chunks = this._normalizeSemanticChunks(rawChunks);
|
|
551219
|
+
}
|
|
551220
|
+
} catch {
|
|
551221
|
+
chunks = [];
|
|
551222
|
+
}
|
|
551223
|
+
if (chunks.length === 0)
|
|
551224
|
+
chunks = buildFallbackSemanticChunks(input.items, 7);
|
|
551225
|
+
chunks = chunks.slice(0, 7);
|
|
551226
|
+
const snapshot = await this._buildPressureSnapshot({
|
|
551227
|
+
items: input.items,
|
|
551228
|
+
messages: input.messages,
|
|
551229
|
+
rawTokens: input.rawTokens,
|
|
551230
|
+
targetTokens: input.targetTokens,
|
|
551231
|
+
semanticChunkCount: chunks.length
|
|
551232
|
+
});
|
|
551233
|
+
const forgettingReport = await this._buildActiveForgettingReport({
|
|
551234
|
+
items: input.items,
|
|
551235
|
+
chunks,
|
|
551236
|
+
snapshot
|
|
551237
|
+
});
|
|
551238
|
+
this._lastContextPressureSnapshot = snapshot;
|
|
551239
|
+
this._lastActiveForgettingReport = forgettingReport;
|
|
551240
|
+
const signals = chunks.map((chunk, index) => signalFromBlock("semantic_chunk", "turn.semantic", `### ${chunk.label}
|
|
551241
|
+
${chunk.content}`, {
|
|
551242
|
+
id: `semantic-${index}-${chunk.id}`,
|
|
551243
|
+
dedupeKey: `turn.semantic.${index}`,
|
|
551244
|
+
priority: 62 + Math.max(0, Math.min(20, chunk.priority ?? 0)),
|
|
551245
|
+
createdTurn: input.turn,
|
|
551246
|
+
ttlTurns: 1,
|
|
551247
|
+
tags: ["semantic_context"],
|
|
551248
|
+
metadata: {
|
|
551249
|
+
semanticLabels: chunk.metadata["labels"] ?? [chunk.label],
|
|
551250
|
+
compressionMetrics: chunk.metadata["compression"],
|
|
551251
|
+
sourceIds: chunk.sourceIds,
|
|
551252
|
+
...index === 0 ? { pressureSnapshot: snapshot, activeForgettingReport: forgettingReport } : {}
|
|
551253
|
+
}
|
|
551254
|
+
})).filter(Boolean);
|
|
551255
|
+
return { signals, snapshot, forgettingReport };
|
|
551256
|
+
}
|
|
551257
|
+
async _memoryHelperWantsConsolidation(input) {
|
|
551258
|
+
try {
|
|
551259
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551260
|
+
if (typeof memMod.shouldTriggerConsolidation !== "function")
|
|
551261
|
+
return null;
|
|
551262
|
+
return Boolean(await memMod.shouldTriggerConsolidation({
|
|
551263
|
+
pressure: input.snapshot,
|
|
551264
|
+
forgetting: input.forgettingReport,
|
|
551265
|
+
diagnostics: input.diagnostics
|
|
551266
|
+
}));
|
|
551267
|
+
} catch {
|
|
551268
|
+
return null;
|
|
551269
|
+
}
|
|
551270
|
+
}
|
|
551271
|
+
async _maybeRunDynamicContextConsolidation(input) {
|
|
551272
|
+
if (process.env["OMNIUS_DISABLE_DYNAMIC_CONTEXT_CONSOLIDATION"] === "1")
|
|
551273
|
+
return;
|
|
551274
|
+
if (!this._episodeStore)
|
|
551275
|
+
return;
|
|
551276
|
+
const debounceTurns = Math.max(4, Number(process.env["OMNIUS_CONTEXT_CONSOLIDATION_DEBOUNCE_TURNS"] ?? 10));
|
|
551277
|
+
if (input.turn - this._lastContextConsolidationTurn < debounceTurns)
|
|
551278
|
+
return;
|
|
551279
|
+
const helperDecision = await this._memoryHelperWantsConsolidation({
|
|
551280
|
+
snapshot: input.snapshot,
|
|
551281
|
+
forgettingReport: input.forgettingReport,
|
|
551282
|
+
diagnostics: input.diagnostics
|
|
551283
|
+
});
|
|
551284
|
+
const decision2 = shouldRunDynamicContextConsolidation({
|
|
551285
|
+
snapshot: input.snapshot,
|
|
551286
|
+
forgettingReport: input.forgettingReport,
|
|
551287
|
+
frameDiagnostics: input.diagnostics,
|
|
551288
|
+
memoryHelperDecision: helperDecision
|
|
551289
|
+
});
|
|
551290
|
+
if (!decision2.shouldRun)
|
|
551291
|
+
return;
|
|
551292
|
+
this._lastContextConsolidationTurn = input.turn;
|
|
551293
|
+
let cycleSummary = null;
|
|
551294
|
+
try {
|
|
551295
|
+
const memMod = await Promise.resolve().then(() => (init_dist7(), dist_exports2));
|
|
551296
|
+
if (typeof memMod.runConsolidationCycle === "function" && typeof this._episodeStore.getDb === "function") {
|
|
551297
|
+
const cycle = memMod.runConsolidationCycle(this._episodeStore.getDb(), {
|
|
551298
|
+
slowWave: this._temporalGraph ? { graph: this._temporalGraph, maxReplay: 8 } : { maxReplay: 8 },
|
|
551299
|
+
rem: this._temporalGraph ? { graph: this._temporalGraph, maxAssociations: 4 } : { maxAssociations: 4 },
|
|
551300
|
+
light: { prunableClasses: ["session"], maxPrune: 8 }
|
|
551301
|
+
});
|
|
551302
|
+
cycleSummary = {
|
|
551303
|
+
slowWaveReplayed: cycle?.slowWave?.replayedEpisodes?.length ?? 0,
|
|
551304
|
+
lightPruned: cycle?.light?.prunedEpisodes?.length ?? 0,
|
|
551305
|
+
remAssociations: cycle?.rem?.novelAssociations?.length ?? 0,
|
|
551306
|
+
totalEnergy: cycle?.totalEnergy
|
|
551307
|
+
};
|
|
551308
|
+
}
|
|
551309
|
+
} catch {
|
|
551310
|
+
cycleSummary = { failed: true };
|
|
551311
|
+
}
|
|
551312
|
+
const semanticLabels = input.semanticSignals.flatMap((signal) => {
|
|
551313
|
+
const labels = signal.metadata?.["semanticLabels"];
|
|
551314
|
+
return Array.isArray(labels) ? labels.map(String) : [];
|
|
551315
|
+
}).slice(0, 20);
|
|
551316
|
+
const compressionMetrics = input.semanticSignals.map((signal) => signal.metadata?.["compressionMetrics"]).filter(Boolean).slice(0, 7);
|
|
551317
|
+
const content = [
|
|
551318
|
+
`Context pressure snapshot: ${decision2.reasons.join(", ")}.`,
|
|
551319
|
+
`raw=${input.snapshot.rawTokens}/${input.snapshot.targetTokens} tokens ratio=${decision2.rawRatio.toFixed(2)}; semantic_chunks=${input.diagnostics.semanticChunkCount}.`,
|
|
551320
|
+
input.diagnostics.droppedSignals || input.diagnostics.truncatedSignals ? `fabric dropped=${input.diagnostics.droppedSignals} truncated=${input.diagnostics.truncatedSignals}.` : null
|
|
551321
|
+
].filter(Boolean).join(" ");
|
|
551322
|
+
try {
|
|
551323
|
+
this._episodeStore.insert({
|
|
551324
|
+
sessionId: this._sessionId,
|
|
551325
|
+
modality: "reflection",
|
|
551326
|
+
toolName: "context_pressure_snapshot",
|
|
551327
|
+
content: content.slice(0, 600),
|
|
551328
|
+
importance: 5,
|
|
551329
|
+
decayClass: "session",
|
|
551330
|
+
metadata: {
|
|
551331
|
+
pressure: input.snapshot,
|
|
551332
|
+
forgetting: input.forgettingReport,
|
|
551333
|
+
reasons: decision2.reasons,
|
|
551334
|
+
semanticLabels,
|
|
551335
|
+
compressionMetrics,
|
|
551336
|
+
frameDiagnostics: {
|
|
551337
|
+
includedSignals: input.diagnostics.includedSignals,
|
|
551338
|
+
droppedSignals: input.diagnostics.droppedSignals,
|
|
551339
|
+
truncatedSignals: input.diagnostics.truncatedSignals,
|
|
551340
|
+
estimatedTokens: input.diagnostics.estimatedTokens,
|
|
551341
|
+
semanticChunkCount: input.diagnostics.semanticChunkCount
|
|
551342
|
+
},
|
|
551343
|
+
consolidation: cycleSummary
|
|
551344
|
+
}
|
|
551345
|
+
});
|
|
551346
|
+
this.emit({
|
|
551347
|
+
type: "status",
|
|
551348
|
+
content: `Context consolidation: ${decision2.reasons.join(", ")} (semantic chunks=${input.diagnostics.semanticChunkCount})`,
|
|
551349
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
551350
|
+
});
|
|
551351
|
+
} catch {
|
|
551352
|
+
}
|
|
551353
|
+
}
|
|
551354
|
+
async _buildTurnContextFrame(turn, messages2, recentToolResults, environmentBlock) {
|
|
550428
551355
|
this._contextLedger.clearSources("turn.");
|
|
550429
551356
|
this._contextLedger.prune(turn);
|
|
551357
|
+
const goalBlock = this._taskState.goal ? `Active task: ${this._taskState.goal}` : null;
|
|
551358
|
+
const filesystemBlock = this._renderFilesystemStateBlock(turn);
|
|
551359
|
+
const todoBlock = this._renderTodoStateBlock(turn);
|
|
551360
|
+
const failureBlock = this._renderRecentFailuresBlock(turn);
|
|
551361
|
+
const churnBlock = this._renderWriteChurnBlock(turn);
|
|
551362
|
+
const toolCacheBlock = recentToolResults ? this._renderKnowledgeBlock(recentToolResults) : null;
|
|
551363
|
+
const anchorsBlock = this.surfaceAnchors(messages2);
|
|
551364
|
+
const pprMemoryBlock = this._lastPprMemoryLines.length > 0 ? `[Associative Memory - related prior experience]
|
|
551365
|
+
${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
|
|
551366
|
+
const activeItems = await this._collectActiveSemanticContextItems({
|
|
551367
|
+
goalBlock,
|
|
551368
|
+
filesystemBlock,
|
|
551369
|
+
todoBlock,
|
|
551370
|
+
failureBlock,
|
|
551371
|
+
churnBlock,
|
|
551372
|
+
toolCacheBlock,
|
|
551373
|
+
anchorsBlock,
|
|
551374
|
+
environmentBlock: environmentBlock ?? null,
|
|
551375
|
+
messages: messages2
|
|
551376
|
+
});
|
|
551377
|
+
const targetTokens2 = this.contextLimits().compactionThreshold;
|
|
551378
|
+
const semantic = await this._buildSemanticContextSignals({
|
|
551379
|
+
turn,
|
|
551380
|
+
items: activeItems,
|
|
551381
|
+
messages: messages2,
|
|
551382
|
+
rawTokens: estimateMessagesTokens(messages2),
|
|
551383
|
+
targetTokens: targetTokens2
|
|
551384
|
+
});
|
|
550430
551385
|
const signals = [
|
|
550431
|
-
signalFromBlock("goal", "run.goal",
|
|
551386
|
+
signalFromBlock("goal", "run.goal", goalBlock, {
|
|
550432
551387
|
id: "active-task",
|
|
550433
551388
|
dedupeKey: "run.goal",
|
|
550434
551389
|
priority: 100,
|
|
550435
551390
|
createdTurn: turn
|
|
550436
551391
|
}),
|
|
550437
|
-
signalFromBlock("known_files", "turn.files",
|
|
551392
|
+
signalFromBlock("known_files", "turn.files", filesystemBlock, {
|
|
550438
551393
|
id: "filesystem-state",
|
|
550439
551394
|
dedupeKey: "turn.files",
|
|
550440
551395
|
priority: 70,
|
|
550441
551396
|
createdTurn: turn,
|
|
550442
551397
|
ttlTurns: 1
|
|
550443
551398
|
}),
|
|
550444
|
-
signalFromBlock("task_state", "turn.todos",
|
|
551399
|
+
signalFromBlock("task_state", "turn.todos", todoBlock, {
|
|
550445
551400
|
id: "todo-state",
|
|
550446
551401
|
dedupeKey: "turn.todos",
|
|
550447
551402
|
priority: 80,
|
|
550448
551403
|
createdTurn: turn,
|
|
550449
551404
|
ttlTurns: 1
|
|
550450
551405
|
}),
|
|
550451
|
-
signalFromBlock("recent_failure", "turn.failures",
|
|
551406
|
+
signalFromBlock("recent_failure", "turn.failures", failureBlock, {
|
|
550452
551407
|
id: "recent-failures",
|
|
550453
551408
|
dedupeKey: "turn.failures",
|
|
550454
551409
|
priority: 95,
|
|
550455
551410
|
createdTurn: turn,
|
|
550456
551411
|
ttlTurns: 1
|
|
550457
551412
|
}),
|
|
550458
|
-
signalFromBlock("recent_failure", "turn.churn",
|
|
551413
|
+
signalFromBlock("recent_failure", "turn.churn", churnBlock, {
|
|
550459
551414
|
id: "write-churn",
|
|
550460
551415
|
dedupeKey: "turn.churn",
|
|
550461
551416
|
priority: 75,
|
|
550462
551417
|
createdTurn: turn,
|
|
550463
551418
|
ttlTurns: 1
|
|
550464
551419
|
}),
|
|
550465
|
-
signalFromBlock("tool_cache", "turn.tool-cache",
|
|
551420
|
+
signalFromBlock("tool_cache", "turn.tool-cache", toolCacheBlock, {
|
|
550466
551421
|
id: "tool-cache",
|
|
550467
551422
|
dedupeKey: "turn.tool-cache",
|
|
550468
551423
|
priority: 65,
|
|
550469
551424
|
createdTurn: turn,
|
|
550470
551425
|
ttlTurns: 1
|
|
550471
551426
|
}),
|
|
550472
|
-
signalFromBlock("
|
|
551427
|
+
signalFromBlock("memory", "turn.ppr-memory", pprMemoryBlock, {
|
|
551428
|
+
id: "ppr-memory",
|
|
551429
|
+
dedupeKey: "turn.ppr-memory",
|
|
551430
|
+
priority: 60,
|
|
551431
|
+
createdTurn: turn,
|
|
551432
|
+
ttlTurns: 1
|
|
551433
|
+
}),
|
|
551434
|
+
...semantic.signals,
|
|
551435
|
+
signalFromBlock("anchor", "turn.anchors", anchorsBlock, {
|
|
550473
551436
|
id: "anchors",
|
|
550474
551437
|
dedupeKey: "turn.anchors",
|
|
550475
551438
|
priority: 50,
|
|
@@ -550490,6 +551453,18 @@ ${latest.output || ""}`.trim();
|
|
|
550490
551453
|
maxChars: 1e4,
|
|
550491
551454
|
includeDiagnostics: process.env["OMNIUS_CONTEXT_FABRIC_DIAGNOSTICS"] === "1"
|
|
550492
551455
|
});
|
|
551456
|
+
this._lastContextFrameDiagnostics = frame.diagnostics;
|
|
551457
|
+
semantic.snapshot.frameTokens = frame.diagnostics.estimatedTokens;
|
|
551458
|
+
semantic.snapshot.droppedSignals = frame.diagnostics.droppedSignals;
|
|
551459
|
+
semantic.snapshot.truncatedSignals = frame.diagnostics.truncatedSignals;
|
|
551460
|
+
semantic.snapshot.semanticChunkCount = frame.diagnostics.semanticChunkCount;
|
|
551461
|
+
await this._maybeRunDynamicContextConsolidation({
|
|
551462
|
+
turn,
|
|
551463
|
+
snapshot: semantic.snapshot,
|
|
551464
|
+
forgettingReport: semantic.forgettingReport,
|
|
551465
|
+
diagnostics: frame.diagnostics,
|
|
551466
|
+
semanticSignals: semantic.signals
|
|
551467
|
+
});
|
|
550493
551468
|
return frame.content;
|
|
550494
551469
|
}
|
|
550495
551470
|
makePhaseSummarizer() {
|
|
@@ -551331,7 +552306,14 @@ Respond with your assessment, then take action.`;
|
|
|
551331
552306
|
this._contextTree = null;
|
|
551332
552307
|
this._lastSurfacedAnchorIds.clear();
|
|
551333
552308
|
this._contextLedger = new ContextLedger();
|
|
552309
|
+
this._lastContextFrameDiagnostics = null;
|
|
552310
|
+
this._lastContextPressureSnapshot = null;
|
|
552311
|
+
this._lastActiveForgettingReport = null;
|
|
552312
|
+
this._lastContextConsolidationTurn = -1e3;
|
|
551334
552313
|
this._contextFrameBuilder = new ContextFrameBuilder();
|
|
552314
|
+
this._lastContextPressureSnapshot = null;
|
|
552315
|
+
this._lastActiveForgettingReport = null;
|
|
552316
|
+
this._lastContextConsolidationTurn = -1e3;
|
|
551335
552317
|
if (!this.options.disablePersistentMemory && !this._memoryInitialized) {
|
|
551336
552318
|
try {
|
|
551337
552319
|
const path12 = await import("node:path");
|
|
@@ -553052,8 +554034,8 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
|
|
|
553052
554034
|
if (process.env["OMNIUS_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
|
|
553053
554035
|
const goalForSig = (this._taskState.goal || "").slice(0, 200);
|
|
553054
554036
|
const recentTools = this._toolSequence.slice(-5).join("|");
|
|
553055
|
-
const { createHash:
|
|
553056
|
-
const sig =
|
|
554037
|
+
const { createHash: createHash36 } = await import("node:crypto");
|
|
554038
|
+
const sig = createHash36("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
|
|
553057
554039
|
if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
|
|
553058
554040
|
compacted.push({
|
|
553059
554041
|
role: "system",
|
|
@@ -553151,7 +554133,7 @@ ${memoryLines.join("\n")}`
|
|
|
553151
554133
|
this._lastAssistantTimestamp = Date.now();
|
|
553152
554134
|
this.proactivePrune(compacted, turn);
|
|
553153
554135
|
this.microcompact(compacted, recentToolResults);
|
|
553154
|
-
this._insertContextFrame(compacted, this._buildTurnContextFrame(turn, compacted, recentToolResults, environmentBlock));
|
|
554136
|
+
this._insertContextFrame(compacted, await this._buildTurnContextFrame(turn, compacted, recentToolResults, environmentBlock));
|
|
553155
554137
|
const { maxOutputTokens: effectiveMaxTokens } = this.contextLimits();
|
|
553156
554138
|
const chatRequest = {
|
|
553157
554139
|
messages: compacted,
|
|
@@ -555943,7 +556925,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
|
|
|
555943
556925
|
} catch {
|
|
555944
556926
|
}
|
|
555945
556927
|
}
|
|
555946
|
-
this._insertContextFrame(compactedMsgs, this._buildTurnContextFrame(turn, compactedMsgs, void 0, bfEnvironmentBlock));
|
|
556928
|
+
this._insertContextFrame(compactedMsgs, await this._buildTurnContextFrame(turn, compactedMsgs, void 0, bfEnvironmentBlock));
|
|
555947
556929
|
const chatRequest = {
|
|
555948
556930
|
messages: compactedMsgs,
|
|
555949
556931
|
tools: toolDefs,
|
|
@@ -569051,7 +570033,7 @@ var require_websocket3 = __commonJS({
|
|
|
569051
570033
|
var http6 = __require("http");
|
|
569052
570034
|
var net5 = __require("net");
|
|
569053
570035
|
var tls2 = __require("tls");
|
|
569054
|
-
var { randomBytes: randomBytes29, createHash:
|
|
570036
|
+
var { randomBytes: randomBytes29, createHash: createHash36 } = __require("crypto");
|
|
569055
570037
|
var { Duplex: Duplex3, Readable } = __require("stream");
|
|
569056
570038
|
var { URL: URL3 } = __require("url");
|
|
569057
570039
|
var PerMessageDeflate3 = require_permessage_deflate3();
|
|
@@ -569711,7 +570693,7 @@ var require_websocket3 = __commonJS({
|
|
|
569711
570693
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
569712
570694
|
return;
|
|
569713
570695
|
}
|
|
569714
|
-
const digest3 =
|
|
570696
|
+
const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
|
|
569715
570697
|
if (res.headers["sec-websocket-accept"] !== digest3) {
|
|
569716
570698
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
569717
570699
|
return;
|
|
@@ -570078,7 +571060,7 @@ var require_websocket_server2 = __commonJS({
|
|
|
570078
571060
|
var EventEmitter15 = __require("events");
|
|
570079
571061
|
var http6 = __require("http");
|
|
570080
571062
|
var { Duplex: Duplex3 } = __require("stream");
|
|
570081
|
-
var { createHash:
|
|
571063
|
+
var { createHash: createHash36 } = __require("crypto");
|
|
570082
571064
|
var extension3 = require_extension3();
|
|
570083
571065
|
var PerMessageDeflate3 = require_permessage_deflate3();
|
|
570084
571066
|
var subprotocol3 = require_subprotocol2();
|
|
@@ -570379,7 +571361,7 @@ var require_websocket_server2 = __commonJS({
|
|
|
570379
571361
|
);
|
|
570380
571362
|
}
|
|
570381
571363
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
570382
|
-
const digest3 =
|
|
571364
|
+
const digest3 = createHash36("sha1").update(key + GUID).digest("base64");
|
|
570383
571365
|
const headers = [
|
|
570384
571366
|
"HTTP/1.1 101 Switching Protocols",
|
|
570385
571367
|
"Upgrade: websocket",
|
|
@@ -575228,14 +576210,14 @@ var init_voice_session = __esm({
|
|
|
575228
576210
|
});
|
|
575229
576211
|
|
|
575230
576212
|
// packages/cli/src/tui/scoped-personality.ts
|
|
575231
|
-
import { createHash as
|
|
576213
|
+
import { createHash as createHash22 } from "node:crypto";
|
|
575232
576214
|
import { appendFileSync as appendFileSync5, existsSync as existsSync89, mkdirSync as mkdirSync49, readFileSync as readFileSync69, writeFileSync as writeFileSync44 } from "node:fs";
|
|
575233
576215
|
import { join as join104, resolve as resolve39 } from "node:path";
|
|
575234
576216
|
function safeName(input) {
|
|
575235
576217
|
return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
|
|
575236
576218
|
}
|
|
575237
576219
|
function scopeHash(scope) {
|
|
575238
|
-
return
|
|
576220
|
+
return createHash22("sha1").update(`${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
|
|
575239
576221
|
}
|
|
575240
576222
|
function scopedPersonalityDir(repoRoot, kind) {
|
|
575241
576223
|
return resolve39(repoRoot, ".omnius", "scoped-personality", kind);
|
|
@@ -575607,7 +576589,7 @@ var init_scoped_personality = __esm({
|
|
|
575607
576589
|
});
|
|
575608
576590
|
|
|
575609
576591
|
// packages/cli/src/tui/voice-soul.ts
|
|
575610
|
-
import { createHash as
|
|
576592
|
+
import { createHash as createHash23 } from "node:crypto";
|
|
575611
576593
|
import { existsSync as existsSync90, readdirSync as readdirSync29, readFileSync as readFileSync70 } from "node:fs";
|
|
575612
576594
|
import { basename as basename20, join as join105, resolve as resolve40 } from "node:path";
|
|
575613
576595
|
function compactText(text, limit) {
|
|
@@ -575622,7 +576604,7 @@ function blockText(text, limit) {
|
|
|
575622
576604
|
... [truncated]`;
|
|
575623
576605
|
}
|
|
575624
576606
|
function scopeStateKey(scope, surface) {
|
|
575625
|
-
return
|
|
576607
|
+
return createHash23("sha1").update(`${surface}:${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
|
|
575626
576608
|
}
|
|
575627
576609
|
function safeName2(input) {
|
|
575628
576610
|
return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
|
|
@@ -578225,7 +579207,7 @@ var init_types = __esm({
|
|
|
578225
579207
|
});
|
|
578226
579208
|
|
|
578227
579209
|
// packages/cli/src/tui/p2p/secret-vault.ts
|
|
578228
|
-
import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes21, scryptSync as scryptSync2, createHash as
|
|
579210
|
+
import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes21, scryptSync as scryptSync2, createHash as createHash24 } from "node:crypto";
|
|
578229
579211
|
import { readFileSync as readFileSync72, writeFileSync as writeFileSync46, existsSync as existsSync92, mkdirSync as mkdirSync51 } from "node:fs";
|
|
578230
579212
|
import { dirname as dirname28 } from "node:path";
|
|
578231
579213
|
var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
|
|
@@ -578470,7 +579452,7 @@ var init_secret_vault = __esm({
|
|
|
578470
579452
|
/** Generate a deterministic fingerprint of vault contents (for sync verification) */
|
|
578471
579453
|
fingerprint() {
|
|
578472
579454
|
const names = Array.from(this.secrets.keys()).sort();
|
|
578473
|
-
const hash =
|
|
579455
|
+
const hash = createHash24("sha256");
|
|
578474
579456
|
for (const name10 of names) {
|
|
578475
579457
|
hash.update(name10 + ":");
|
|
578476
579458
|
hash.update(this.secrets.get(name10).value);
|
|
@@ -578485,7 +579467,7 @@ var init_secret_vault = __esm({
|
|
|
578485
579467
|
// packages/cli/src/tui/p2p/peer-mesh.ts
|
|
578486
579468
|
import { EventEmitter as EventEmitter9 } from "node:events";
|
|
578487
579469
|
import { createServer as createServer6 } from "node:http";
|
|
578488
|
-
import { randomBytes as randomBytes22, createHash as
|
|
579470
|
+
import { randomBytes as randomBytes22, createHash as createHash25, generateKeyPairSync } from "node:crypto";
|
|
578489
579471
|
var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
|
|
578490
579472
|
var init_peer_mesh = __esm({
|
|
578491
579473
|
"packages/cli/src/tui/p2p/peer-mesh.ts"() {
|
|
@@ -578502,7 +579484,7 @@ var init_peer_mesh = __esm({
|
|
|
578502
579484
|
const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
|
|
578503
579485
|
this.publicKey = publicKey2.export({ type: "spki", format: "der" });
|
|
578504
579486
|
this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
|
|
578505
|
-
this.peerId =
|
|
579487
|
+
this.peerId = createHash25("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
|
|
578506
579488
|
this.capabilities = options2.capabilities;
|
|
578507
579489
|
this.displayName = options2.displayName;
|
|
578508
579490
|
this._authKey = options2.authKey ?? randomBytes22(24).toString("base64url");
|
|
@@ -579840,7 +580822,7 @@ __export(omnius_directory_exports, {
|
|
|
579840
580822
|
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
580823
|
import { join as join111, relative as relative9, basename as basename21, dirname as dirname31, resolve as resolve41 } from "node:path";
|
|
579842
580824
|
import { homedir as homedir34 } from "node:os";
|
|
579843
|
-
import { createHash as
|
|
580825
|
+
import { createHash as createHash26 } from "node:crypto";
|
|
579844
580826
|
function isGitRoot(dir) {
|
|
579845
580827
|
const gitPath = join111(dir, ".git");
|
|
579846
580828
|
if (!existsSync95(gitPath)) return false;
|
|
@@ -580294,7 +581276,7 @@ function buildHandoffPrompt(repoRoot) {
|
|
|
580294
581276
|
return lines.join("\n");
|
|
580295
581277
|
}
|
|
580296
581278
|
function computeDedupeHash(task, savedAt) {
|
|
580297
|
-
return
|
|
581279
|
+
return createHash26("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
|
|
580298
581280
|
}
|
|
580299
581281
|
function generateSessionId() {
|
|
580300
581282
|
const timestamp = Date.now().toString(36);
|
|
@@ -584502,6 +585484,17 @@ var init_status_bar = __esm({
|
|
|
584502
585484
|
this.repaintContent();
|
|
584503
585485
|
this.renderAgentTabs();
|
|
584504
585486
|
}
|
|
585487
|
+
cycleAgentView(direction) {
|
|
585488
|
+
if (this._agentViews.size <= 1) return;
|
|
585489
|
+
const ids = Array.from(this._agentViews.keys());
|
|
585490
|
+
const currentIdx = Math.max(0, ids.indexOf(this._activeViewId));
|
|
585491
|
+
const delta = direction === "next" ? 1 : -1;
|
|
585492
|
+
const nextIdx = (currentIdx + delta + ids.length) % ids.length;
|
|
585493
|
+
const nextId2 = ids[nextIdx];
|
|
585494
|
+
if (!nextId2 || nextId2 === this._activeViewId) return;
|
|
585495
|
+
this.switchToView(nextId2);
|
|
585496
|
+
this.refreshHeaderContent();
|
|
585497
|
+
}
|
|
584505
585498
|
/** Write content to a specific agent's buffer (called from sub-agent event handler) */
|
|
584506
585499
|
writeToAgentView(id, text) {
|
|
584507
585500
|
const view = this._agentViews.get(id);
|
|
@@ -586377,6 +587370,8 @@ ${CONTENT_BG_SEQ}`);
|
|
|
586377
587370
|
if (onCtrlO) di.on("ctrl-o", () => onCtrlO());
|
|
586378
587371
|
if (onCtrlL) di.on("ctrl-l", () => onCtrlL());
|
|
586379
587372
|
di.on("ctrl-i", () => self2.toggleFooterMetrics());
|
|
587373
|
+
di.on("ctrl-left", () => self2.cycleAgentView("prev"));
|
|
587374
|
+
di.on("ctrl-right", () => self2.cycleAgentView("next"));
|
|
586380
587375
|
di.on("pageup", () => self2.pageUpContent());
|
|
586381
587376
|
di.on("pagedown", () => self2.pageDownContent());
|
|
586382
587377
|
di.on("shiftup", () => self2.scrollContentUp(3));
|
|
@@ -600463,7 +601458,7 @@ __export(commands_exports, {
|
|
|
600463
601458
|
});
|
|
600464
601459
|
import * as nodeOs from "node:os";
|
|
600465
601460
|
import { execSync as nodeExecSync } from "node:child_process";
|
|
600466
|
-
import { createHash as
|
|
601461
|
+
import { createHash as createHash27 } from "node:crypto";
|
|
600467
601462
|
import {
|
|
600468
601463
|
existsSync as existsSync108,
|
|
600469
601464
|
readFileSync as readFileSync86,
|
|
@@ -610939,7 +611934,7 @@ async function collectSponsorMediaStream(args) {
|
|
|
610939
611934
|
return { ok: false, error: `Artifact size mismatch for ${artifactId}: ${bytes.length}/${artifact.sizeBytes}` };
|
|
610940
611935
|
}
|
|
610941
611936
|
if (artifact.sha256) {
|
|
610942
|
-
const sha =
|
|
611937
|
+
const sha = createHash27("sha256").update(bytes).digest("hex");
|
|
610943
611938
|
if (sha !== artifact.sha256) return { ok: false, error: `Artifact hash mismatch for ${artifactId}` };
|
|
610944
611939
|
}
|
|
610945
611940
|
const safeName3 = basename23(artifact.filename).replace(/[^\w.-]/g, "_") || `artifact${defaultExtensionForMime(artifact.mime)}`;
|
|
@@ -614920,7 +615915,7 @@ function normalizePersonName(name10) {
|
|
|
614920
615915
|
function personKey(name10) {
|
|
614921
615916
|
return `person:${normalizePersonName(name10)}`;
|
|
614922
615917
|
}
|
|
614923
|
-
function
|
|
615918
|
+
function clamp017(value2, fallback = 0) {
|
|
614924
615919
|
if (typeof value2 !== "number" || !Number.isFinite(value2)) return fallback;
|
|
614925
615920
|
return Math.max(0, Math.min(1, value2));
|
|
614926
615921
|
}
|
|
@@ -614937,7 +615932,7 @@ function parseStructuredIdentifyResult(result) {
|
|
|
614937
615932
|
const matches = faces.filter((face) => face["identified"] === true && typeof face["name"] === "string" && String(face["name"]).trim()).map((face) => ({
|
|
614938
615933
|
name: String(face["name"]).trim(),
|
|
614939
615934
|
personId: typeof face["person_id"] === "string" ? face["person_id"] : void 0,
|
|
614940
|
-
confidence:
|
|
615935
|
+
confidence: clamp017(face["confidence"], 0),
|
|
614941
615936
|
margin: typeof face["margin"] === "number" ? face["margin"] : void 0,
|
|
614942
615937
|
bbox: Array.isArray(face["bbox"]) ? face["bbox"].map((n2) => Number(n2)).filter(Number.isFinite) : void 0
|
|
614943
615938
|
}));
|
|
@@ -615020,7 +616015,7 @@ function activePendingVisualIdentities(store2, scope, sessionId, limit = 3) {
|
|
|
615020
616015
|
pendingId,
|
|
615021
616016
|
name: name10,
|
|
615022
616017
|
relation: String(meta["relation"] || "depicts"),
|
|
615023
|
-
confidence:
|
|
616018
|
+
confidence: clamp017(meta["confidence"], 0.92),
|
|
615024
616019
|
note: typeof meta["note"] === "string" ? meta["note"] : void 0,
|
|
615025
616020
|
episodeId: ep.id,
|
|
615026
616021
|
createdAt: ep.timestamp,
|
|
@@ -615130,7 +616125,7 @@ function stageVisualIdentityAssertion(options2) {
|
|
|
615130
616125
|
target: "next_visual_media",
|
|
615131
616126
|
name: name10,
|
|
615132
616127
|
relation: options2.relation || "depicts",
|
|
615133
|
-
confidence:
|
|
616128
|
+
confidence: clamp017(options2.confidence, 0.92),
|
|
615134
616129
|
note: options2.note,
|
|
615135
616130
|
createdAt: Date.now(),
|
|
615136
616131
|
expiresAt
|
|
@@ -615139,7 +616134,7 @@ function stageVisualIdentityAssertion(options2) {
|
|
|
615139
616134
|
identityAssertions: [{
|
|
615140
616135
|
name: name10,
|
|
615141
616136
|
relation: options2.relation || "named_as",
|
|
615142
|
-
confidence:
|
|
616137
|
+
confidence: clamp017(options2.confidence, 0.92),
|
|
615143
616138
|
assertedBy: options2.sender,
|
|
615144
616139
|
note: options2.note || "Explicit user-provided identity staged for the next visual media."
|
|
615145
616140
|
}]
|
|
@@ -622964,7 +623959,7 @@ ${result.output}`,
|
|
|
622964
623959
|
});
|
|
622965
623960
|
|
|
622966
623961
|
// packages/cli/src/tui/stimulation.ts
|
|
622967
|
-
function
|
|
623962
|
+
function clamp018(value2) {
|
|
622968
623963
|
return Math.max(0, Math.min(1, value2));
|
|
622969
623964
|
}
|
|
622970
623965
|
function cloneState(state) {
|
|
@@ -623020,7 +624015,7 @@ var init_stimulation = __esm({
|
|
|
623020
624015
|
...DEFAULT_STATE,
|
|
623021
624016
|
...state,
|
|
623022
624017
|
phase: normalizePhase(state.phase) ?? DEFAULT_STATE.phase,
|
|
623023
|
-
attention:
|
|
624018
|
+
attention: clamp018(Number.isFinite(state.attention) ? Number(state.attention) : DEFAULT_STATE.attention),
|
|
623024
624019
|
updatedAtMs: Number.isFinite(state.updatedAtMs) ? Number(state.updatedAtMs) : now,
|
|
623025
624020
|
lastStimulusAtMs: Number.isFinite(state.lastStimulusAtMs) ? Number(state.lastStimulusAtMs) : now,
|
|
623026
624021
|
messagesSinceAnalysis: Math.max(0, Math.floor(Number(state.messagesSinceAnalysis ?? 0))),
|
|
@@ -623061,11 +624056,11 @@ var init_stimulation = __esm({
|
|
|
623061
624056
|
applyAgentDecision(channelId, decision2, nowMs = Date.now()) {
|
|
623062
624057
|
const state = this.stateFor(channelId, nowMs);
|
|
623063
624058
|
if (Number.isFinite(decision2.attentionScore)) {
|
|
623064
|
-
state.attention =
|
|
624059
|
+
state.attention = clamp018(Number(decision2.attentionScore));
|
|
623065
624060
|
} else if (Number.isFinite(decision2.attentionDelta)) {
|
|
623066
|
-
state.attention =
|
|
624061
|
+
state.attention = clamp018(state.attention + Number(decision2.attentionDelta));
|
|
623067
624062
|
} else {
|
|
623068
|
-
state.attention =
|
|
624063
|
+
state.attention = clamp018(state.attention + (decision2.shouldReply ? 0.22 : -0.1));
|
|
623069
624064
|
}
|
|
623070
624065
|
if (decision2.phase) {
|
|
623071
624066
|
state.attention = Math.max(state.attention, PHASE_FLOORS[decision2.phase]);
|
|
@@ -623121,7 +624116,7 @@ var init_stimulation = __esm({
|
|
|
623121
624116
|
});
|
|
623122
624117
|
|
|
623123
624118
|
// packages/cli/src/tui/pid-controller.ts
|
|
623124
|
-
function
|
|
624119
|
+
function clamp019(x) {
|
|
623125
624120
|
if (!Number.isFinite(x)) return 0;
|
|
623126
624121
|
if (x < 0) return 0;
|
|
623127
624122
|
if (x > 1) return 1;
|
|
@@ -623185,7 +624180,7 @@ var init_pid_controller = __esm({
|
|
|
623185
624180
|
const dt = st.lastSampleAt > 0 ? now - st.lastSampleAt : 1e3;
|
|
623186
624181
|
const derivative = dt > 0 ? (error - st.lastError) / dt : 0;
|
|
623187
624182
|
const u = st.config.kp * error + st.config.ki * st.integral + st.config.kd * derivative;
|
|
623188
|
-
st.output =
|
|
624183
|
+
st.output = clamp019(st.output + u);
|
|
623189
624184
|
st.lastError = error;
|
|
623190
624185
|
st.lastSampleAt = now;
|
|
623191
624186
|
st.samples += 1;
|
|
@@ -623417,7 +624412,7 @@ var init_soul_observations = __esm({
|
|
|
623417
624412
|
// packages/cli/src/tui/telegram-channel-dmn.ts
|
|
623418
624413
|
import { existsSync as existsSync119, mkdirSync as mkdirSync68, readdirSync as readdirSync42, readFileSync as readFileSync96, writeFileSync as writeFileSync61 } from "node:fs";
|
|
623419
624414
|
import { join as join133 } from "node:path";
|
|
623420
|
-
import { createHash as
|
|
624415
|
+
import { createHash as createHash28 } from "node:crypto";
|
|
623421
624416
|
function safeFilePart(value2) {
|
|
623422
624417
|
return value2.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 80) || "telegram";
|
|
623423
624418
|
}
|
|
@@ -623425,7 +624420,7 @@ function daydreamRoot(repoRoot) {
|
|
|
623425
624420
|
return join133(repoRoot, ".omnius", "telegram-daydreams");
|
|
623426
624421
|
}
|
|
623427
624422
|
function sessionDir(repoRoot, sessionKey) {
|
|
623428
|
-
const hash =
|
|
624423
|
+
const hash = createHash28("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
623429
624424
|
return join133(daydreamRoot(repoRoot), safeFilePart(hash));
|
|
623430
624425
|
}
|
|
623431
624426
|
function compactLine2(value2, max = 220) {
|
|
@@ -623510,9 +624505,9 @@ function buildReplyOpportunities(input, openQuestions) {
|
|
|
623510
624505
|
return opportunities;
|
|
623511
624506
|
}
|
|
623512
624507
|
function daydreamOpportunityId(input, trigger) {
|
|
623513
|
-
return
|
|
624508
|
+
return createHash28("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
|
|
623514
624509
|
}
|
|
623515
|
-
function
|
|
624510
|
+
function clamp0110(value2) {
|
|
623516
624511
|
if (!Number.isFinite(value2)) return 0;
|
|
623517
624512
|
return Math.max(0, Math.min(1, value2));
|
|
623518
624513
|
}
|
|
@@ -623523,7 +624518,7 @@ function pushStimulationSignal(signals, signal, source, weight) {
|
|
|
623523
624518
|
const cleanSignal = compactLine2(signal, 120);
|
|
623524
624519
|
const cleanSource = compactLine2(source, 180);
|
|
623525
624520
|
if (!cleanSignal || signals.some((entry) => entry.signal === cleanSignal && entry.source === cleanSource)) return;
|
|
623526
|
-
signals.push({ signal: cleanSignal, source: cleanSource, weight:
|
|
624521
|
+
signals.push({ signal: cleanSignal, source: cleanSource, weight: clamp0110(weight) });
|
|
623527
624522
|
}
|
|
623528
624523
|
function buildMetaAnalysisSignals(input) {
|
|
623529
624524
|
const chatLabel = input.chatTitle || input.chatId;
|
|
@@ -623598,7 +624593,7 @@ function buildCuriosityThreads(input, openQuestions, stimulationSignals) {
|
|
|
623598
624593
|
question: text.endsWith("?") || text.endsWith("?") ? text : `What should be learned or clarified from: ${text || entry.mediaSummary || "recent media"}?`,
|
|
623599
624594
|
rationale: "Human curiosity, uncertainty, or multimodal content makes this a useful idle exploration target.",
|
|
623600
624595
|
sourceMessages: messageId,
|
|
623601
|
-
intensity:
|
|
624596
|
+
intensity: clamp0110(0.5 + replyBoost + mediaBoost + questionBoost)
|
|
623602
624597
|
});
|
|
623603
624598
|
}
|
|
623604
624599
|
for (const question of openQuestions.slice(-4)) {
|
|
@@ -623618,7 +624613,7 @@ function buildCuriosityThreads(input, openQuestions, stimulationSignals) {
|
|
|
623618
624613
|
question: `Is there a useful clarification or memory consolidation around ${strongest.source}?`,
|
|
623619
624614
|
rationale: "Strongest stimulation signal can seed a low-intrusion reflection target.",
|
|
623620
624615
|
sourceMessages: [],
|
|
623621
|
-
intensity:
|
|
624616
|
+
intensity: clamp0110(strongest.weight * 0.72)
|
|
623622
624617
|
});
|
|
623623
624618
|
}
|
|
623624
624619
|
return threads.sort((a2, b) => b.intensity - a2.intensity).slice(0, 8);
|
|
@@ -623692,7 +624687,7 @@ function buildOutreachPlans(input, curiosityThreads) {
|
|
|
623692
624687
|
purpose: "Continue the public thread only when the live model judges that the group would benefit from a concise follow-up.",
|
|
623693
624688
|
draftIntent: "Ask one concrete clarification, offer one useful synthesis, or stay silent if the room has moved on.",
|
|
623694
624689
|
gate: "model_decision",
|
|
623695
|
-
confidence:
|
|
624690
|
+
confidence: clamp0110(thread.intensity * 0.86)
|
|
623696
624691
|
});
|
|
623697
624692
|
const participant = participantForThread(input, thread);
|
|
623698
624693
|
if (!participant) continue;
|
|
@@ -623704,7 +624699,7 @@ function buildOutreachPlans(input, curiosityThreads) {
|
|
|
623704
624699
|
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.",
|
|
623705
624700
|
draftIntent: "Reference the public thread briefly, ask permission to continue privately, and do not reveal hidden meta-analysis.",
|
|
623706
624701
|
gate: "admin_review",
|
|
623707
|
-
confidence:
|
|
624702
|
+
confidence: clamp0110(thread.intensity * 0.58)
|
|
623708
624703
|
});
|
|
623709
624704
|
}
|
|
623710
624705
|
return plans.slice(0, 8);
|
|
@@ -623830,7 +624825,7 @@ function buildTelegramChannelDaydream(input, corpus, extraction, extractionCommi
|
|
|
623830
624825
|
const seed = `${input.sessionKey}:${input.generatedAtMs}:${input.history.length}`;
|
|
623831
624826
|
return {
|
|
623832
624827
|
version: 3,
|
|
623833
|
-
id:
|
|
624828
|
+
id: createHash28("sha1").update(seed).digest("hex").slice(0, 16),
|
|
623834
624829
|
sessionKey: input.sessionKey,
|
|
623835
624830
|
chatId: input.chatId,
|
|
623836
624831
|
chatTitle: input.chatTitle,
|
|
@@ -624043,12 +625038,12 @@ var init_telegram_channel_dmn = __esm({
|
|
|
624043
625038
|
});
|
|
624044
625039
|
|
|
624045
625040
|
// packages/cli/src/tui/telegram-reflection-corpus.ts
|
|
624046
|
-
import { createHash as
|
|
625041
|
+
import { createHash as createHash29 } from "node:crypto";
|
|
624047
625042
|
function telegramReflectionMemoryDbPaths(repoRoot) {
|
|
624048
625043
|
return omniusMemoryDbPaths(repoRoot);
|
|
624049
625044
|
}
|
|
624050
625045
|
function stableHash2(value2, length4 = 16) {
|
|
624051
|
-
return
|
|
625046
|
+
return createHash29("sha1").update(value2).digest("hex").slice(0, length4);
|
|
624052
625047
|
}
|
|
624053
625048
|
function clean3(value2) {
|
|
624054
625049
|
return String(value2 ?? "").replace(/\s+/g, " ").trim();
|
|
@@ -624778,7 +625773,7 @@ var init_telegram_reflection_extraction = __esm({
|
|
|
624778
625773
|
});
|
|
624779
625774
|
|
|
624780
625775
|
// packages/cli/src/tui/telegram-social-state-types.ts
|
|
624781
|
-
import { createHash as
|
|
625776
|
+
import { createHash as createHash30 } from "node:crypto";
|
|
624782
625777
|
function telegramSocialActorKey(actor) {
|
|
624783
625778
|
if (!actor) return "unknown";
|
|
624784
625779
|
if (typeof actor.userId === "number") return `user:${actor.userId}`;
|
|
@@ -624811,7 +625806,7 @@ function appendUnique(items, value2, max) {
|
|
|
624811
625806
|
return next.slice(-max);
|
|
624812
625807
|
}
|
|
624813
625808
|
function hashTelegramSocialId(parts) {
|
|
624814
|
-
return
|
|
625809
|
+
return createHash30("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
|
|
624815
625810
|
}
|
|
624816
625811
|
function cleanUsername(value2) {
|
|
624817
625812
|
if (typeof value2 !== "string") return void 0;
|
|
@@ -624836,7 +625831,7 @@ function numberOr(value2, fallback) {
|
|
|
624836
625831
|
function isNumber(value2) {
|
|
624837
625832
|
return typeof value2 === "number" && Number.isFinite(value2);
|
|
624838
625833
|
}
|
|
624839
|
-
function
|
|
625834
|
+
function clamp0111(value2) {
|
|
624840
625835
|
return Math.max(0, Math.min(1, Number.isFinite(value2) ? value2 : 0));
|
|
624841
625836
|
}
|
|
624842
625837
|
function iso(ts) {
|
|
@@ -624846,10 +625841,11 @@ function iso(ts) {
|
|
|
624846
625841
|
return "";
|
|
624847
625842
|
}
|
|
624848
625843
|
}
|
|
624849
|
-
var TELEGRAM_SOCIAL_LIMITS;
|
|
625844
|
+
var DEFAULT_TELEGRAM_REPLY_MODE, TELEGRAM_SOCIAL_LIMITS;
|
|
624850
625845
|
var init_telegram_social_state_types = __esm({
|
|
624851
625846
|
"packages/cli/src/tui/telegram-social-state-types.ts"() {
|
|
624852
625847
|
"use strict";
|
|
625848
|
+
DEFAULT_TELEGRAM_REPLY_MODE = "reply_then_notes";
|
|
624853
625849
|
TELEGRAM_SOCIAL_LIMITS = {
|
|
624854
625850
|
relationships: 240,
|
|
624855
625851
|
salience: 180,
|
|
@@ -624894,7 +625890,7 @@ function formatTelegramSocialStateContext(state, input) {
|
|
|
624894
625890
|
`Current actor node: ${senderKey3} [${participant?.actorKind || telegramSocialActorKind(input)}] messages=${participant?.messageCount ?? 0}${participant?.lastText ? ` last=${jsonLine(participant.lastText, 140)}` : ""}`,
|
|
624895
625891
|
thread ? `Active channel/thread: ${thread.key}; messages=${thread.messageCount}; participants=${thread.participantKeys.slice(-8).join(", ") || "none"}; last_outcomes=${thread.lastOutcomeIds.slice(-5).join(", ") || "none"}` : "",
|
|
624896
625892
|
delivery ? `Telegram text delivery raw warning stream: ${delivery.status}; key=${telegramTextDeliveryCapabilityKey({ chatId: input.chatId, messageThreadId: input.messageThreadId })}${delivery.reason ? `; raw=${jsonLine(delivery.reason, 180)}` : ""}` : "Telegram text delivery raw warning stream: none recorded",
|
|
624897
|
-
resolvedReplyMode ? `Resolved reply mode: ${resolvedReplyMode.item.mode} from ${resolvedReplyMode.item.scope} (${resolvedReplyMode.key}); confidence=${resolvedReplyMode.item.confidence.toFixed(2)}${resolvedReplyMode.item.note ? ` note=${jsonLine(resolvedReplyMode.item.note, 120)}` : ""}` :
|
|
625893
|
+
resolvedReplyMode ? `Resolved reply mode: ${resolvedReplyMode.item.mode} from ${resolvedReplyMode.item.scope} (${resolvedReplyMode.key}); confidence=${resolvedReplyMode.item.confidence.toFixed(2)}${resolvedReplyMode.item.note ? ` note=${jsonLine(resolvedReplyMode.item.note, 120)}` : ""}` : `Resolved reply mode: ${DEFAULT_TELEGRAM_REPLY_MODE} (system default)`,
|
|
624898
625894
|
preferences.length ? `Relevant preference vector for ${senderKey3}:
|
|
624899
625895
|
${preferences.join("\n")}` : `Relevant preference vector for ${senderKey3}: no durable preferences yet`,
|
|
624900
625896
|
scopedPreferences.length ? `Scoped reply preferences:
|
|
@@ -625019,8 +626015,8 @@ function normalizeRelationship(raw) {
|
|
|
625019
626015
|
kind: value2.kind,
|
|
625020
626016
|
fromKey: String(value2.fromKey),
|
|
625021
626017
|
toKey: String(value2.toKey),
|
|
625022
|
-
confidence:
|
|
625023
|
-
weight:
|
|
626018
|
+
confidence: clamp0111(numberOr(value2.confidence, 0)),
|
|
626019
|
+
weight: clamp0111(numberOr(value2.weight, 0)),
|
|
625024
626020
|
firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
|
|
625025
626021
|
lastSeenAt: numberOr(value2.lastSeenAt, Date.now()),
|
|
625026
626022
|
evidenceMessageIds: Array.isArray(value2.evidenceMessageIds) ? value2.evidenceMessageIds.filter(isNumber).slice(-40) : [],
|
|
@@ -625039,7 +626035,7 @@ function normalizePreferences(raw) {
|
|
|
625039
626035
|
if (!evidence || typeof evidence !== "object") continue;
|
|
625040
626036
|
out[actorKey][key] = {
|
|
625041
626037
|
value: Math.max(-1, Math.min(1, numberOr(evidence.value, 0))),
|
|
625042
|
-
confidence:
|
|
626038
|
+
confidence: clamp0111(numberOr(evidence.confidence, 0)),
|
|
625043
626039
|
updatedAt: numberOr(evidence.updatedAt, Date.now()),
|
|
625044
626040
|
evidenceMessageIds: Array.isArray(evidence.evidenceMessageIds) ? evidence.evidenceMessageIds.filter(isNumber).slice(-12) : [],
|
|
625045
626041
|
note: compactOptional(evidence.note, 220)
|
|
@@ -625053,7 +626049,7 @@ function normalizePreferences(raw) {
|
|
|
625053
626049
|
out[actorKey].replyMode = {
|
|
625054
626050
|
mode,
|
|
625055
626051
|
scope: normalizeReplyPreferenceScope(record["scope"]),
|
|
625056
|
-
confidence:
|
|
626052
|
+
confidence: clamp0111(numberOr(record["confidence"], 0.8)),
|
|
625057
626053
|
updatedAt: numberOr(record["updatedAt"], Date.now()),
|
|
625058
626054
|
evidenceMessageIds: Array.isArray(record["evidenceMessageIds"]) ? record["evidenceMessageIds"].filter(isNumber).slice(-12) : [],
|
|
625059
626055
|
note: compactOptional(record["note"], 220),
|
|
@@ -625143,7 +626139,7 @@ function normalizeOutcome(raw) {
|
|
|
625143
626139
|
replyToMessageId: typeof value2.replyToMessageId === "number" ? value2.replyToMessageId : void 0,
|
|
625144
626140
|
route: value2.route === "action" ? "action" : "chat",
|
|
625145
626141
|
shouldReply: value2.shouldReply === true,
|
|
625146
|
-
confidence:
|
|
626142
|
+
confidence: clamp0111(numberOr(value2.confidence, 0)),
|
|
625147
626143
|
reason: compact2(value2.reason || "", 280),
|
|
625148
626144
|
source: compact2(value2.source || "unknown", 80),
|
|
625149
626145
|
silentDisposition: compactOptional(value2.silentDisposition, 280),
|
|
@@ -625155,7 +626151,7 @@ function normalizeOutcome(raw) {
|
|
|
625155
626151
|
scenarioNote: compactOptional(value2.scenarioNote, 360),
|
|
625156
626152
|
scenarioId: compactOptional(value2.scenarioId, 160),
|
|
625157
626153
|
scenarioLabel: compactOptional(value2.scenarioLabel, 160),
|
|
625158
|
-
scenarioConfidence: typeof value2.scenarioConfidence === "number" && Number.isFinite(value2.scenarioConfidence) ?
|
|
626154
|
+
scenarioConfidence: typeof value2.scenarioConfidence === "number" && Number.isFinite(value2.scenarioConfidence) ? clamp0111(value2.scenarioConfidence) : void 0,
|
|
625159
626155
|
scenarioObjective: compactOptional(value2.scenarioObjective, 360),
|
|
625160
626156
|
scenarioStateLoop: compactOptional(value2.scenarioStateLoop, 360),
|
|
625161
626157
|
salienceSignals: Array.isArray(value2.salienceSignals) ? value2.salienceSignals.map(String).slice(0, 16) : [],
|
|
@@ -625173,7 +626169,7 @@ function normalizeDaydreamOpportunity(raw) {
|
|
|
625173
626169
|
artifactId: String(value2.artifactId || "unknown"),
|
|
625174
626170
|
generatedAt: String(value2.generatedAt || (/* @__PURE__ */ new Date()).toISOString()),
|
|
625175
626171
|
trigger: compact2(value2.trigger || "", 240),
|
|
625176
|
-
confidence:
|
|
626172
|
+
confidence: clamp0111(numberOr(value2.confidence, 0)),
|
|
625177
626173
|
lifecycle,
|
|
625178
626174
|
firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
|
|
625179
626175
|
updatedAt: numberOr(value2.updatedAt, Date.now()),
|
|
@@ -625230,7 +626226,7 @@ function commitTelegramSocialDecision(state, input) {
|
|
|
625230
626226
|
replyToMessageId: input.replyToMessageId,
|
|
625231
626227
|
route: input.route,
|
|
625232
626228
|
shouldReply: input.shouldReply,
|
|
625233
|
-
confidence:
|
|
626229
|
+
confidence: clamp0111(input.confidence),
|
|
625234
626230
|
reason: compact2(input.reason, 280),
|
|
625235
626231
|
source: compact2(input.source, 80),
|
|
625236
626232
|
silentDisposition: compactOptional(input.silentDisposition, 280),
|
|
@@ -625242,7 +626238,7 @@ function commitTelegramSocialDecision(state, input) {
|
|
|
625242
626238
|
scenarioNote: compactOptional(input.scenarioNote, 360),
|
|
625243
626239
|
scenarioId: compactOptional(input.scenarioId, 160),
|
|
625244
626240
|
scenarioLabel: compactOptional(input.scenarioLabel, 160),
|
|
625245
|
-
scenarioConfidence: input.scenarioConfidence === void 0 ? void 0 :
|
|
626241
|
+
scenarioConfidence: input.scenarioConfidence === void 0 ? void 0 : clamp0111(input.scenarioConfidence),
|
|
625246
626242
|
scenarioObjective: compactOptional(input.scenarioObjective, 360),
|
|
625247
626243
|
scenarioStateLoop: compactOptional(input.scenarioStateLoop, 360),
|
|
625248
626244
|
salienceSignals: [...new Set((input.salienceSignals ?? []).map(String))].slice(0, 16),
|
|
@@ -625266,7 +626262,7 @@ function registerDaydreamOpportunities(state, opportunities, now = Date.now()) {
|
|
|
625266
626262
|
artifactId: opportunity.artifactId || "unknown",
|
|
625267
626263
|
generatedAt: opportunity.generatedAt || new Date(now).toISOString(),
|
|
625268
626264
|
trigger: compact2(opportunity.trigger, 240),
|
|
625269
|
-
confidence:
|
|
626265
|
+
confidence: clamp0111(opportunity.confidence),
|
|
625270
626266
|
lifecycle: "proposed",
|
|
625271
626267
|
firstSeenAt: now,
|
|
625272
626268
|
updatedAt: now,
|
|
@@ -625276,7 +626272,7 @@ function registerDaydreamOpportunities(state, opportunities, now = Date.now()) {
|
|
|
625276
626272
|
};
|
|
625277
626273
|
if (existing) {
|
|
625278
626274
|
item.trigger = compact2(opportunity.trigger, 240) || item.trigger;
|
|
625279
|
-
item.confidence =
|
|
626275
|
+
item.confidence = clamp0111(opportunity.confidence);
|
|
625280
626276
|
item.updatedAt = now;
|
|
625281
626277
|
}
|
|
625282
626278
|
state.daydreamOpportunities[id] = item;
|
|
@@ -625303,7 +626299,7 @@ function setTelegramReplyModePreference(state, input) {
|
|
|
625303
626299
|
const next = {
|
|
625304
626300
|
mode: input.mode,
|
|
625305
626301
|
scope: input.scope,
|
|
625306
|
-
confidence: Math.max(existing?.confidence ?? 0,
|
|
626302
|
+
confidence: Math.max(existing?.confidence ?? 0, clamp0111(input.confidence ?? 0.84)),
|
|
625307
626303
|
updatedAt: now,
|
|
625308
626304
|
evidenceMessageIds: appendUnique(existing?.evidenceMessageIds ?? [], input.messageId, 12),
|
|
625309
626305
|
note: compactOptional(input.note, 220),
|
|
@@ -625483,8 +626479,8 @@ function upsertRelationship(state, kind, fromKey, toKey, messageId, confidence2,
|
|
|
625483
626479
|
evidenceMessageIds: [],
|
|
625484
626480
|
source
|
|
625485
626481
|
};
|
|
625486
|
-
edge.confidence = Math.max(edge.confidence,
|
|
625487
|
-
edge.weight = Math.min(1, edge.weight + 0.12 +
|
|
626482
|
+
edge.confidence = Math.max(edge.confidence, clamp0111(confidence2));
|
|
626483
|
+
edge.weight = Math.min(1, edge.weight + 0.12 + clamp0111(confidence2) * 0.2);
|
|
625488
626484
|
edge.lastSeenAt = now;
|
|
625489
626485
|
edge.evidenceMessageIds = appendUnique(edge.evidenceMessageIds, messageId, 40);
|
|
625490
626486
|
edge.note = compactOptional(note, 260) || edge.note;
|
|
@@ -625526,7 +626522,7 @@ function setPreference(vector, key, value2, confidence2, messageId, now, note) {
|
|
|
625526
626522
|
const existing = vector[key];
|
|
625527
626523
|
vector[key] = {
|
|
625528
626524
|
value: existing ? existing.value * 0.7 + value2 * 0.3 : value2,
|
|
625529
|
-
confidence: Math.max(existing?.confidence ?? 0,
|
|
626525
|
+
confidence: Math.max(existing?.confidence ?? 0, clamp0111(confidence2)),
|
|
625530
626526
|
updatedAt: now,
|
|
625531
626527
|
evidenceMessageIds: appendUnique(existing?.evidenceMessageIds ?? [], messageId, 12),
|
|
625532
626528
|
note
|
|
@@ -625737,7 +626733,7 @@ import { mkdirSync as mkdirSync69, existsSync as existsSync121, unlinkSync as un
|
|
|
625737
626733
|
import { join as join135, resolve as resolve48, basename as basename33, relative as relative13, isAbsolute as isAbsolute8, extname as extname16 } from "node:path";
|
|
625738
626734
|
import { homedir as homedir43 } from "node:os";
|
|
625739
626735
|
import { writeFile as writeFileAsync } from "node:fs/promises";
|
|
625740
|
-
import { createHash as
|
|
626736
|
+
import { createHash as createHash31, randomBytes as randomBytes24, randomInt } from "node:crypto";
|
|
625741
626737
|
function cleanTelegramDecisionNote(value2, maxLength = 260) {
|
|
625742
626738
|
if (typeof value2 !== "string") return void 0;
|
|
625743
626739
|
const clean5 = stripTelegramHiddenThinking(value2).replace(/\s+/g, " ").trim();
|
|
@@ -625779,6 +626775,11 @@ function telegramDecisionNumber(parsed, keys, nestedKeys = ["internal_notes", "i
|
|
|
625779
626775
|
function parseTelegramReplyMode(raw) {
|
|
625780
626776
|
return raw === "reply_then_notes" || raw === "notes_then_reply" || raw === "reply_only" ? raw : void 0;
|
|
625781
626777
|
}
|
|
626778
|
+
function formatTelegramPipelineDuration(ms) {
|
|
626779
|
+
if (!Number.isFinite(ms) || ms < 0) return "?";
|
|
626780
|
+
if (ms < 1e3) return `${Math.round(ms)}ms`;
|
|
626781
|
+
return `${(ms / 1e3).toFixed(1)}s`;
|
|
626782
|
+
}
|
|
625782
626783
|
function parseTelegramReplyPreferenceToolScope(raw) {
|
|
625783
626784
|
return raw === "current_user_in_chat" || raw === "current_user_global" || raw === "current_group" ? raw : void 0;
|
|
625784
626785
|
}
|
|
@@ -626699,7 +627700,7 @@ function buildTelegramRuntimeContext(now = /* @__PURE__ */ new Date(), repoRoot)
|
|
|
626699
627700
|
].filter(Boolean).join("\n");
|
|
626700
627701
|
}
|
|
626701
627702
|
function telegramSessionIdFromKey(sessionKey) {
|
|
626702
|
-
return `telegram-${
|
|
627703
|
+
return `telegram-${createHash31("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
|
|
626703
627704
|
}
|
|
626704
627705
|
function normalizeTelegramSubAgentLimit(value2) {
|
|
626705
627706
|
const parsed = typeof value2 === "number" ? value2 : typeof value2 === "string" && value2.trim() ? Number(value2.trim()) : TELEGRAM_SUB_AGENT_DEFAULT_LIMIT;
|
|
@@ -627516,7 +628517,7 @@ function renderTelegramSubAgentError(username, error) {
|
|
|
627516
628517
|
process.stdout.write(` ${c3.dim("│")} ${c3.magenta("✘")} @${username}: ${c3.dim(preview)}
|
|
627517
628518
|
`);
|
|
627518
628519
|
}
|
|
627519
|
-
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;
|
|
628520
|
+
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;
|
|
627520
628521
|
var init_telegram_bridge = __esm({
|
|
627521
628522
|
"packages/cli/src/tui/telegram-bridge.ts"() {
|
|
627522
628523
|
"use strict";
|
|
@@ -627788,6 +628789,8 @@ External acquisition contract:
|
|
|
627788
628789
|
TELEGRAM_INTERACTION_DECISION_RESPONSE_FORMAT = {
|
|
627789
628790
|
type: "json_object"
|
|
627790
628791
|
};
|
|
628792
|
+
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"}}`;
|
|
628793
|
+
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"}}`;
|
|
627791
628794
|
TELEGRAM_CHAT_REPLY_RESPONSE_FORMAT = {
|
|
627792
628795
|
type: "json_schema",
|
|
627793
628796
|
json_schema: {
|
|
@@ -628314,7 +629317,7 @@ External acquisition contract:
|
|
|
628314
629317
|
return !!this.adminAuthChallenge && this.adminAuthChallenge.expiresAtMs > Date.now();
|
|
628315
629318
|
}
|
|
628316
629319
|
hashAdminAuthCode(code8) {
|
|
628317
|
-
return
|
|
629320
|
+
return createHash31("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
|
|
628318
629321
|
}
|
|
628319
629322
|
viewIdForMessage(msg) {
|
|
628320
629323
|
return `telegram-${this.sessionKeyForMessage(msg).replace(/[^A-Za-z0-9_-]/g, "-")}`;
|
|
@@ -628355,6 +629358,7 @@ External acquisition contract:
|
|
|
628355
629358
|
].filter(Boolean).join(" or ");
|
|
628356
629359
|
const lines = [
|
|
628357
629360
|
`decision: ${route} (${decision2.source}, confidence ${decision2.confidence.toFixed(2)})`,
|
|
629361
|
+
decision2.routerLatencyMs !== void 0 ? `timing: ${decision2.routerMode ?? "router"} attention pipeline ${formatTelegramPipelineDuration(decision2.routerLatencyMs)}` : "",
|
|
628358
629362
|
attention ? `attention: ${attention}` : "",
|
|
628359
629363
|
`reason: ${decision2.reason}`,
|
|
628360
629364
|
decision2.diagnosticNote ? `router diagnostic: ${decision2.diagnosticNote}` : "",
|
|
@@ -629240,11 +630244,11 @@ ${mediaContext}` : ""
|
|
|
629240
630244
|
return payload;
|
|
629241
630245
|
}
|
|
629242
630246
|
telegramConversationPath(sessionKey) {
|
|
629243
|
-
const safe =
|
|
630247
|
+
const safe = createHash31("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
629244
630248
|
return join135(this.telegramConversationDir, `${safe}.json`);
|
|
629245
630249
|
}
|
|
629246
630250
|
telegramConversationLedgerPath(sessionKey) {
|
|
629247
|
-
const safe =
|
|
630251
|
+
const safe = createHash31("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
629248
630252
|
return join135(this.telegramConversationDir, `${safe}.events.jsonl`);
|
|
629249
630253
|
}
|
|
629250
630254
|
telegramDb() {
|
|
@@ -629472,7 +630476,7 @@ ${mediaContext}` : ""
|
|
|
629472
630476
|
users,
|
|
629473
630477
|
relationships: Array.isArray(raw.relationships) ? raw.relationships.slice(0, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT).map((fact) => this.normalizeTelegramAssociativeFact(fact)) : [],
|
|
629474
630478
|
actions: Array.isArray(raw.actions) ? raw.actions.slice(-TELEGRAM_ASSOCIATIVE_ACTION_LIMIT).map((action) => ({
|
|
629475
|
-
id: String(action.id ||
|
|
630479
|
+
id: String(action.id || createHash31("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)),
|
|
629476
630480
|
ts: typeof action.ts === "number" ? action.ts : Date.now(),
|
|
629477
630481
|
role: action.role === "assistant" ? "assistant" : "user",
|
|
629478
630482
|
speaker: String(action.speaker || "unknown"),
|
|
@@ -629489,7 +630493,7 @@ ${mediaContext}` : ""
|
|
|
629489
630493
|
const text = String(raw.text || "").trim();
|
|
629490
630494
|
const now = Date.now();
|
|
629491
630495
|
return {
|
|
629492
|
-
id: String(raw.id ||
|
|
630496
|
+
id: String(raw.id || createHash31("sha1").update(text || String(now)).digest("hex").slice(0, 12)),
|
|
629493
630497
|
text,
|
|
629494
630498
|
tags: Array.isArray(raw.tags) ? raw.tags.map(String).slice(0, 16) : [],
|
|
629495
630499
|
speakers: Array.isArray(raw.speakers) ? raw.speakers.map(String).slice(0, 16) : [],
|
|
@@ -629705,9 +630709,9 @@ ${mediaContext}` : ""
|
|
|
629705
630709
|
return resolveTelegramReplyModePreference(this.telegramSocialStateForSession(sessionKey), {
|
|
629706
630710
|
chatId: msg.chatId,
|
|
629707
630711
|
actor: this.telegramMessageSocialActorInput(msg)
|
|
629708
|
-
})?.mode ??
|
|
630712
|
+
})?.mode ?? DEFAULT_TELEGRAM_REPLY_MODE;
|
|
629709
630713
|
} catch {
|
|
629710
|
-
return
|
|
630714
|
+
return DEFAULT_TELEGRAM_REPLY_MODE;
|
|
629711
630715
|
}
|
|
629712
630716
|
}
|
|
629713
630717
|
stripTelegramDecisionNotes(decision2) {
|
|
@@ -629727,6 +630731,41 @@ ${mediaContext}` : ""
|
|
|
629727
630731
|
scenarioStateLoop: void 0
|
|
629728
630732
|
};
|
|
629729
630733
|
}
|
|
630734
|
+
synthesizeTelegramPostReplyDecision(decision2, msg, visibleReplyText) {
|
|
630735
|
+
const base3 = this.stripTelegramDecisionNotes(decision2);
|
|
630736
|
+
const replySummary = visibleReplyText ? sanitizeTelegramProgressText(cleanTelegramVisibleReply(visibleReplyText), 180) : "visible reply attempt completed";
|
|
630737
|
+
return {
|
|
630738
|
+
...base3,
|
|
630739
|
+
silentDisposition: "visible reply completed before internal note commit",
|
|
630740
|
+
mentalNote: `post-reply: @${msg.username || "unknown"} was answered via ${decision2.route}; ${replySummary}`,
|
|
630741
|
+
memoryNote: "message and visible reply were retained in scoped Telegram conversation memory"
|
|
630742
|
+
};
|
|
630743
|
+
}
|
|
630744
|
+
notesThenReplyDecision(decision2, msg) {
|
|
630745
|
+
if (decision2.silentDisposition || decision2.mentalNote || decision2.memoryNote || decision2.relationshipNote || decision2.procedureNote || decision2.voiceNote || decision2.scenarioNote || decision2.scenarioId) {
|
|
630746
|
+
return decision2;
|
|
630747
|
+
}
|
|
630748
|
+
return {
|
|
630749
|
+
...decision2,
|
|
630750
|
+
silentDisposition: "internal notes committed before visible reply by reply mode",
|
|
630751
|
+
mentalNote: `pre-reply: @${msg.username || "unknown"} routed to ${decision2.route}; ${decision2.reason}`,
|
|
630752
|
+
memoryNote: "message retained in scoped Telegram conversation memory before reply"
|
|
630753
|
+
};
|
|
630754
|
+
}
|
|
630755
|
+
deliverTelegramPostReplyNotes(sessionKey, msg, viewId, decision2, salienceSignals, daydreamOpportunities, visibleReplyText) {
|
|
630756
|
+
const postReplyDecision = this.synthesizeTelegramPostReplyDecision(decision2, msg, visibleReplyText);
|
|
630757
|
+
if (viewId && this.subAgentViewCallbacks) {
|
|
630758
|
+
this.subAgentViewCallbacks.onWrite(viewId, "post-reply/internal notes:");
|
|
630759
|
+
}
|
|
630760
|
+
this.deliverTelegramAttentionDecision(
|
|
630761
|
+
sessionKey,
|
|
630762
|
+
msg,
|
|
630763
|
+
viewId,
|
|
630764
|
+
postReplyDecision,
|
|
630765
|
+
salienceSignals,
|
|
630766
|
+
daydreamOpportunities
|
|
630767
|
+
);
|
|
630768
|
+
}
|
|
629730
630769
|
telegramTextDeliveryCapability(sessionKey, chatId, messageThreadId) {
|
|
629731
630770
|
try {
|
|
629732
630771
|
return telegramTextDeliveryCapabilityFor(this.telegramSocialStateForSession(sessionKey), {
|
|
@@ -629843,7 +630882,7 @@ ${mediaContext}` : ""
|
|
|
629843
630882
|
}
|
|
629844
630883
|
telegramHistoryBackfillMessageId(sessionKey, entry, index) {
|
|
629845
630884
|
if (typeof entry.messageId === "number" && Number.isFinite(entry.messageId)) return entry.messageId;
|
|
629846
|
-
const digest3 =
|
|
630885
|
+
const digest3 = createHash31("sha1").update(`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`).digest("hex").slice(0, 8);
|
|
629847
630886
|
return -Number.parseInt(digest3, 16);
|
|
629848
630887
|
}
|
|
629849
630888
|
backfillTelegramLoadedHistory(sessionKey, history) {
|
|
@@ -630760,7 +631799,7 @@ ${mediaContext}` : ""
|
|
|
630760
631799
|
const now = entry.ts ?? Date.now();
|
|
630761
631800
|
memory.updatedAt = now;
|
|
630762
631801
|
const speaker = telegramHistorySpeaker(entry);
|
|
630763
|
-
const actionId =
|
|
631802
|
+
const actionId = createHash31("sha1").update(`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now}:${entry.text}`).digest("hex").slice(0, 16);
|
|
630764
631803
|
if (!memory.actions.some((action) => action.id === actionId)) {
|
|
630765
631804
|
memory.actions.push({
|
|
630766
631805
|
id: actionId,
|
|
@@ -630882,7 +631921,7 @@ ${mediaContext}` : ""
|
|
|
630882
631921
|
let fact = facts.find((item) => item.text.toLowerCase() === key);
|
|
630883
631922
|
if (!fact) {
|
|
630884
631923
|
fact = {
|
|
630885
|
-
id:
|
|
631924
|
+
id: createHash31("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
|
|
630886
631925
|
text: clean5,
|
|
630887
631926
|
tags: telegramMemoryTags(clean5, entry.mediaSummary),
|
|
630888
631927
|
speakers: [],
|
|
@@ -630937,7 +631976,7 @@ ${mediaContext}` : ""
|
|
|
630937
631976
|
const titleTags = tags.slice(0, 4);
|
|
630938
631977
|
const title = titleTags.length > 0 ? `${speaker} / ${titleTags.join(" ")}` : `${speaker} / conversation`;
|
|
630939
631978
|
const card = {
|
|
630940
|
-
id:
|
|
631979
|
+
id: createHash31("sha1").update(`${sessionKey}:${now}:${speaker}:${text}`).digest("hex").slice(0, 12),
|
|
630941
631980
|
title,
|
|
630942
631981
|
notes: [],
|
|
630943
631982
|
tags: [],
|
|
@@ -632258,7 +633297,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
|
|
|
632258
633297
|
routeInstruction,
|
|
632259
633298
|
``,
|
|
632260
633299
|
`Return JSON only with this schema:`,
|
|
632261
|
-
|
|
633300
|
+
TELEGRAM_INTERACTION_DECISION_REPAIR_SCHEMA,
|
|
632262
633301
|
``,
|
|
632263
633302
|
`Original router output:`,
|
|
632264
633303
|
rawPreview,
|
|
@@ -632276,7 +633315,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
|
|
|
632276
633315
|
],
|
|
632277
633316
|
tools: [],
|
|
632278
633317
|
temperature: 0,
|
|
632279
|
-
maxTokens:
|
|
633318
|
+
maxTokens: 800,
|
|
632280
633319
|
timeoutMs: telegramRouterTimeoutMs(timeoutMs, 8e3, 2e4),
|
|
632281
633320
|
think: false
|
|
632282
633321
|
}, diagnostics, "router-repair", sessionKey);
|
|
@@ -632322,7 +633361,7 @@ ${userPrompt.slice(-4e3)}` : userPrompt;
|
|
|
632322
633361
|
`Return exactly one JSON object and no prose. No <think> tags. No commentary.`,
|
|
632323
633362
|
routeInstruction,
|
|
632324
633363
|
``,
|
|
632325
|
-
`Required schema: {
|
|
633364
|
+
`Required schema: ${TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA}`,
|
|
632326
633365
|
``,
|
|
632327
633366
|
`Invalid previous output, for diagnostics only:`,
|
|
632328
633367
|
invalidPreview,
|
|
@@ -632343,7 +633382,7 @@ ${userPrompt.slice(-4e3)}` : userPrompt;
|
|
|
632343
633382
|
],
|
|
632344
633383
|
tools: [],
|
|
632345
633384
|
temperature: 0,
|
|
632346
|
-
maxTokens:
|
|
633385
|
+
maxTokens: 1e3,
|
|
632347
633386
|
timeoutMs: telegramRouterTimeoutMs(timeoutMs, 1e4, 3e4),
|
|
632348
633387
|
think: false
|
|
632349
633388
|
}, diagnostics, "router-strict-retry", sessionKey);
|
|
@@ -632635,25 +633674,23 @@ ${stimulationProbe.context}`,
|
|
|
632635
633674
|
"",
|
|
632636
633675
|
context2
|
|
632637
633676
|
].filter(Boolean).join("\n");
|
|
632638
|
-
const
|
|
632639
|
-
const
|
|
632640
|
-
const
|
|
633677
|
+
const routerPipelineStartMs = Date.now();
|
|
633678
|
+
const consolidatedMode = process.env["OMNIUS_TG_DELIBERATIVE_ROUTER"] !== "1";
|
|
633679
|
+
const routerMode = consolidatedMode ? "consolidated" : "deliberative";
|
|
633680
|
+
const withRouterTelemetry = (decision2) => ({
|
|
633681
|
+
...decision2,
|
|
633682
|
+
routerMode,
|
|
633683
|
+
routerLatencyMs: Date.now() - routerPipelineStartMs
|
|
633684
|
+
});
|
|
632641
633685
|
let reflectionNotes;
|
|
632642
633686
|
let reflectionContext;
|
|
632643
633687
|
if (consolidatedMode) {
|
|
632644
|
-
reflectionNotes =
|
|
633688
|
+
reflectionNotes = {};
|
|
632645
633689
|
reflectionContext = [
|
|
632646
|
-
"##
|
|
632647
|
-
"
|
|
632648
|
-
"
|
|
632649
|
-
"
|
|
632650
|
-
" memory_note: what scoped memory should retain or connect",
|
|
632651
|
-
" relationship_note: relationship/thread implication",
|
|
632652
|
-
" procedure_note: active tree/branch/abort implication",
|
|
632653
|
-
" voice_note: final voice implication if a reply happens",
|
|
632654
|
-
" scenario_note: identified scenario and transition state",
|
|
632655
|
-
" scenario_id / scenario_label / scenario_confidence / scenario_objective / scenario_state_loop",
|
|
632656
|
-
"Use these as your attention substrate, then decide route/should_reply/confidence. Return all fields in ONE JSON."
|
|
633690
|
+
"## Router fast-path note policy",
|
|
633691
|
+
"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.",
|
|
633692
|
+
"Only decide route, should_reply, confidence, reason, optional stimulation cadence, and optional explicit reply_mode_preference.",
|
|
633693
|
+
"If notes are needed, the bridge will synthesize or commit them after the visible reply according to the resolved reply mode."
|
|
632657
633694
|
].join("\n");
|
|
632658
633695
|
} else {
|
|
632659
633696
|
reflectionNotes = await this.inferTelegramSilentReflectionNotes(
|
|
@@ -632683,22 +633720,22 @@ ${stimulationProbe.context}`,
|
|
|
632683
633720
|
}
|
|
632684
633721
|
const userPrompt = [
|
|
632685
633722
|
`You are the Telegram live routing and reply-discretion model.`,
|
|
632686
|
-
`
|
|
633723
|
+
`Make the smallest sufficient live attention decision. Do not include internal notes unless explicitly supplied by deliberative mode context.`,
|
|
632687
633724
|
`Use the persona docs below as binding behavioral guidance for whether speaking is appropriate and how to avoid over-eager or adversarially bad interventions.`,
|
|
632688
633725
|
`Return JSON only, with no markdown and no explanation outside JSON.`,
|
|
632689
633726
|
``,
|
|
632690
|
-
`Schema: {
|
|
633727
|
+
`Schema: ${TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA}`,
|
|
632691
633728
|
``,
|
|
632692
633729
|
`Route meanings:`,
|
|
632693
633730
|
`- chat: a short conversational answer can be produced without tools.`,
|
|
632694
633731
|
`- action: tools, workspace context, media processing, web lookup, delegation, or a multi-step agent loop may be needed.`,
|
|
632695
|
-
`Route discipline: infer whether the
|
|
633732
|
+
`Route discipline: infer whether the current request can be completed as immediate conversation or needs an external capability. Do not route from keyword categories.`,
|
|
632696
633733
|
``,
|
|
632697
633734
|
`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.`,
|
|
632698
633735
|
`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.`,
|
|
632699
633736
|
`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.`,
|
|
632700
633737
|
`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.`,
|
|
632701
|
-
`Observation notes:
|
|
633738
|
+
`Observation notes: omit note fields on the fast path. Do not expose hidden chain-of-thought or produce scratch notes in this router JSON.`,
|
|
632702
633739
|
`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.`,
|
|
632703
633740
|
`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.`,
|
|
632704
633741
|
`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.`,
|
|
@@ -632765,11 +633802,9 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632765
633802
|
],
|
|
632766
633803
|
tools: [],
|
|
632767
633804
|
temperature: 0,
|
|
632768
|
-
//
|
|
632769
|
-
//
|
|
632770
|
-
|
|
632771
|
-
// for normal verbose values without slowing the call appreciably.
|
|
632772
|
-
maxTokens: 2400,
|
|
633805
|
+
// Minimal route JSON should fit comfortably; keeping this small avoids
|
|
633806
|
+
// reintroducing truncated-note repair cascades.
|
|
633807
|
+
maxTokens: 900,
|
|
632773
633808
|
timeoutMs: telegramRouterTimeoutMs(config.timeoutMs),
|
|
632774
633809
|
think: false
|
|
632775
633810
|
}, diagnostics, "router", sessionKey);
|
|
@@ -632793,7 +633828,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632793
633828
|
defaultShouldReply: false
|
|
632794
633829
|
});
|
|
632795
633830
|
if (parsed) {
|
|
632796
|
-
return this.applyTelegramSilentReflectionNotes(parsed, reflectionNotes);
|
|
633831
|
+
return withRouterTelemetry(this.applyTelegramSilentReflectionNotes(parsed, reflectionNotes));
|
|
632797
633832
|
}
|
|
632798
633833
|
if (isLikelyTruncatedRouterJson(text)) {
|
|
632799
633834
|
if (diagnostics) diagnostics.repairStatus = "skipped-truncation-rerun";
|
|
@@ -632808,7 +633843,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632808
633843
|
],
|
|
632809
633844
|
tools: [],
|
|
632810
633845
|
temperature: 0,
|
|
632811
|
-
maxTokens:
|
|
633846
|
+
maxTokens: 1400,
|
|
632812
633847
|
timeoutMs: telegramRouterTimeoutMs(config.timeoutMs),
|
|
632813
633848
|
think: false
|
|
632814
633849
|
}, diagnostics, "router", sessionKey);
|
|
@@ -632817,7 +633852,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632817
633852
|
defaultShouldReply: false
|
|
632818
633853
|
});
|
|
632819
633854
|
if (reparsed) {
|
|
632820
|
-
return this.applyTelegramSilentReflectionNotes(reparsed, reflectionNotes);
|
|
633855
|
+
return withRouterTelemetry(this.applyTelegramSilentReflectionNotes(reparsed, reflectionNotes));
|
|
632821
633856
|
}
|
|
632822
633857
|
} catch {
|
|
632823
633858
|
}
|
|
@@ -632831,7 +633866,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632831
633866
|
sessionKey
|
|
632832
633867
|
);
|
|
632833
633868
|
if (repaired) {
|
|
632834
|
-
return this.applyTelegramSilentReflectionNotes(repaired, reflectionNotes);
|
|
633869
|
+
return withRouterTelemetry(this.applyTelegramSilentReflectionNotes(repaired, reflectionNotes));
|
|
632835
633870
|
}
|
|
632836
633871
|
const strictRetry = await this.retryTelegramInteractionDecisionStrict(
|
|
632837
633872
|
backend,
|
|
@@ -632843,7 +633878,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632843
633878
|
sessionKey
|
|
632844
633879
|
);
|
|
632845
633880
|
if (strictRetry) {
|
|
632846
|
-
return this.applyTelegramSilentReflectionNotes(strictRetry, reflectionNotes);
|
|
633881
|
+
return withRouterTelemetry(this.applyTelegramSilentReflectionNotes(strictRetry, reflectionNotes));
|
|
632847
633882
|
}
|
|
632848
633883
|
const invalidRouterPreview = telegramRouterRawPreview(text);
|
|
632849
633884
|
const failureNarrative = this.summarizeTelegramRouterFailure(diagnostics);
|
|
@@ -632861,7 +633896,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632861
633896
|
),
|
|
632862
633897
|
raw: text
|
|
632863
633898
|
}, reflectionNotes);
|
|
632864
|
-
return fallback;
|
|
633899
|
+
return withRouterTelemetry(fallback);
|
|
632865
633900
|
} catch (err) {
|
|
632866
633901
|
const failureNarrative = this.summarizeTelegramRouterFailure(diagnostics);
|
|
632867
633902
|
const errMsg = err instanceof Error ? err.message : String(err);
|
|
@@ -632878,7 +633913,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
|
632878
633913
|
`router failed before live notes were generated: ${errMsg.slice(0, 160)}`
|
|
632879
633914
|
)
|
|
632880
633915
|
}, reflectionNotes);
|
|
632881
|
-
return fallback;
|
|
633916
|
+
return withRouterTelemetry(fallback);
|
|
632882
633917
|
}
|
|
632883
633918
|
}
|
|
632884
633919
|
/**
|
|
@@ -633082,7 +634117,7 @@ ${list}` : "No shared group target is currently known for this sender. Ask in th
|
|
|
633082
634117
|
}
|
|
633083
634118
|
telegramRunnerStateDir(sessionKey) {
|
|
633084
634119
|
if (!this.repoRoot) return void 0;
|
|
633085
|
-
const safe =
|
|
634120
|
+
const safe = createHash31("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
633086
634121
|
return join135(this.repoRoot, ".omnius", "telegram-runner-state", safe);
|
|
633087
634122
|
}
|
|
633088
634123
|
buildTelegramAdminOverviewContext(currentSessionKey) {
|
|
@@ -633772,6 +634807,10 @@ Join: ${newUrl}`);
|
|
|
633772
634807
|
}
|
|
633773
634808
|
const rapidContext = this.formatTelegramQueuedSessionContext(work);
|
|
633774
634809
|
const attentionViewId = this.registerTelegramAttentionView(msg, toolContext);
|
|
634810
|
+
this.subAgentViewCallbacks?.onWrite(
|
|
634811
|
+
attentionViewId || this.viewIdForMessage(msg),
|
|
634812
|
+
`pipeline: queued ${formatTelegramPipelineDuration(Date.now() - work.enqueuedAtMs)}; bundled ${work.messageCount} message${work.messageCount === 1 ? "" : "s"}; entering attention router`
|
|
634813
|
+
);
|
|
633775
634814
|
let decision2;
|
|
633776
634815
|
try {
|
|
633777
634816
|
decision2 = await this.inferTelegramInteractionDecisionCoalesced(msg, toolContext);
|
|
@@ -633786,7 +634825,7 @@ Join: ${newUrl}`);
|
|
|
633786
634825
|
);
|
|
633787
634826
|
if (storedPreference) this.subAgentViewCallbacks?.onWrite(attentionViewId || this.viewIdForMessage(msg), `preference: ${storedPreference}`);
|
|
633788
634827
|
const replyMode = this.resolvedTelegramReplyMode(sessionKey, msg);
|
|
633789
|
-
const deliveredDecision = replyMode === "
|
|
634828
|
+
const deliveredDecision = replyMode === "notes_then_reply" ? this.notesThenReplyDecision(decision2, msg) : this.stripTelegramDecisionNotes(decision2);
|
|
633790
634829
|
const daydreamOpportunities = this.markLatestTelegramDaydreamOpportunitiesConsidered(sessionKey, msg);
|
|
633791
634830
|
const shouldDeferNotes = replyMode === "reply_then_notes" && decision2.shouldReply;
|
|
633792
634831
|
if (!shouldDeferNotes) {
|
|
@@ -633820,26 +634859,22 @@ Join: ${newUrl}`);
|
|
|
633820
634859
|
this.enqueueTelegramSubAgentContext(sessionKey, existingAfterDecision, decisionContext, msg.username);
|
|
633821
634860
|
await this.enqueueTelegramQueuedSessionWorkForExistingSubAgent(work, existingAfterDecision);
|
|
633822
634861
|
if (shouldDeferNotes) {
|
|
633823
|
-
this.
|
|
633824
|
-
|
|
633825
|
-
|
|
633826
|
-
attentionViewId,
|
|
633827
|
-
deliveredDecision,
|
|
633828
|
-
this.telegramMessageIdentitySalienceSignals(msg),
|
|
633829
|
-
daydreamOpportunities
|
|
634862
|
+
this.subAgentViewCallbacks?.onWrite(
|
|
634863
|
+
attentionViewId || existingAfterDecision.viewId,
|
|
634864
|
+
"post-reply/internal notes deferred to active reply completion"
|
|
633830
634865
|
);
|
|
633831
634866
|
}
|
|
633832
634867
|
return;
|
|
633833
634868
|
}
|
|
633834
634869
|
const subAgentProfile = decision2.route === "chat" ? "chat" : "action";
|
|
633835
634870
|
if (decision2.route === "chat" && msg.chatType === "private") {
|
|
633836
|
-
await this.handleTelegramChatCompletion(msg, toolContext, [decisionContext, rapidContext].filter(Boolean).join("\n\n"));
|
|
633837
|
-
if (shouldDeferNotes) {
|
|
633838
|
-
this.
|
|
634871
|
+
const visibleReplyAttempted = await this.handleTelegramChatCompletion(msg, toolContext, [decisionContext, rapidContext].filter(Boolean).join("\n\n"));
|
|
634872
|
+
if (shouldDeferNotes && visibleReplyAttempted) {
|
|
634873
|
+
this.deliverTelegramPostReplyNotes(
|
|
633839
634874
|
sessionKey,
|
|
633840
634875
|
msg,
|
|
633841
634876
|
attentionViewId,
|
|
633842
|
-
|
|
634877
|
+
decision2,
|
|
633843
634878
|
this.telegramMessageIdentitySalienceSignals(msg),
|
|
633844
634879
|
daydreamOpportunities
|
|
633845
634880
|
);
|
|
@@ -633928,16 +634963,6 @@ Join: ${newUrl}`);
|
|
|
633928
634963
|
await this.deleteLiveMessage(msg.chatId, subAgent.liveMessageId).catch(() => {
|
|
633929
634964
|
});
|
|
633930
634965
|
}
|
|
633931
|
-
if (shouldDeferNotes) {
|
|
633932
|
-
this.deliverTelegramAttentionDecision(
|
|
633933
|
-
sessionKey,
|
|
633934
|
-
msg,
|
|
633935
|
-
attentionViewId,
|
|
633936
|
-
deliveredDecision,
|
|
633937
|
-
this.telegramMessageIdentitySalienceSignals(msg),
|
|
633938
|
-
daydreamOpportunities
|
|
633939
|
-
);
|
|
633940
|
-
}
|
|
633941
634966
|
return;
|
|
633942
634967
|
}
|
|
633943
634968
|
if (subAgent.liveMessagePromise) {
|
|
@@ -633960,19 +634985,20 @@ Join: ${newUrl}`);
|
|
|
633960
634985
|
finalText,
|
|
633961
634986
|
Boolean(subAgent.liveMessageId && !msg.guestQueryId)
|
|
633962
634987
|
);
|
|
634988
|
+
this.tuiWrite(() => renderTelegramSubAgentComplete(msg.username, finalText));
|
|
634989
|
+
this.subAgentViewCallbacks?.onWrite(subAgent.viewId, `completed: ${finalText}`);
|
|
634990
|
+
this.subAgentViewCallbacks?.onStatus(subAgent.viewId, "completed");
|
|
633963
634991
|
if (shouldDeferNotes) {
|
|
633964
|
-
this.
|
|
634992
|
+
this.deliverTelegramPostReplyNotes(
|
|
633965
634993
|
sessionKey,
|
|
633966
634994
|
msg,
|
|
633967
634995
|
attentionViewId,
|
|
633968
|
-
|
|
634996
|
+
decision2,
|
|
633969
634997
|
this.telegramMessageIdentitySalienceSignals(msg),
|
|
633970
|
-
daydreamOpportunities
|
|
634998
|
+
daydreamOpportunities,
|
|
634999
|
+
finalText
|
|
633971
635000
|
);
|
|
633972
635001
|
}
|
|
633973
|
-
this.tuiWrite(() => renderTelegramSubAgentComplete(msg.username, finalText));
|
|
633974
|
-
this.subAgentViewCallbacks?.onWrite(subAgent.viewId, `completed: ${finalText}`);
|
|
633975
|
-
this.subAgentViewCallbacks?.onStatus(subAgent.viewId, "completed");
|
|
633976
635002
|
} catch (err) {
|
|
633977
635003
|
if (subAgent.typingInterval) {
|
|
633978
635004
|
clearInterval(subAgent.typingInterval);
|
|
@@ -633990,16 +635016,6 @@ Join: ${newUrl}`);
|
|
|
633990
635016
|
await this.deleteLiveMessage(msg.chatId, subAgent.liveMessageId).catch(() => {
|
|
633991
635017
|
});
|
|
633992
635018
|
}
|
|
633993
|
-
if (shouldDeferNotes) {
|
|
633994
|
-
this.deliverTelegramAttentionDecision(
|
|
633995
|
-
sessionKey,
|
|
633996
|
-
msg,
|
|
633997
|
-
attentionViewId,
|
|
633998
|
-
deliveredDecision,
|
|
633999
|
-
this.telegramMessageIdentitySalienceSignals(msg),
|
|
634000
|
-
daydreamOpportunities
|
|
634001
|
-
);
|
|
634002
|
-
}
|
|
634003
635019
|
} finally {
|
|
634004
635020
|
this.clearTelegramSubAgentContextBuffer(sessionKey);
|
|
634005
635021
|
this.subAgents.delete(sessionKey);
|
|
@@ -634127,7 +635143,7 @@ Join: ${newUrl}`);
|
|
|
634127
635143
|
async handleTelegramChatCompletion(msg, toolContext, additionalContext = "") {
|
|
634128
635144
|
if (toolContext === "telegram-admin-dm") {
|
|
634129
635145
|
await this.handleTelegramAdminChatAgent(msg, toolContext, additionalContext);
|
|
634130
|
-
return;
|
|
635146
|
+
return true;
|
|
634131
635147
|
}
|
|
634132
635148
|
const viewId = `${this.viewIdForMessage(msg)}-chat`;
|
|
634133
635149
|
const sessionKey = this.sessionKeyForMessage(msg);
|
|
@@ -634212,7 +635228,7 @@ Join: ${newUrl}`);
|
|
|
634212
635228
|
}
|
|
634213
635229
|
this.subAgentViewCallbacks?.onWrite(viewId, "completed: no model reply");
|
|
634214
635230
|
this.subAgentViewCallbacks?.onStatus(viewId, "completed");
|
|
634215
|
-
return;
|
|
635231
|
+
return false;
|
|
634216
635232
|
}
|
|
634217
635233
|
const finalHtml = convertMarkdownToTelegramHTML(cleaned);
|
|
634218
635234
|
const sentMessageId = await this.sendOrEditFinalTelegramHTML(msg, finalHtml, liveMessageId);
|
|
@@ -634226,6 +635242,7 @@ Join: ${newUrl}`);
|
|
|
634226
635242
|
}
|
|
634227
635243
|
this.subAgentViewCallbacks?.onWrite(viewId, `completed: ${cleaned}`);
|
|
634228
635244
|
this.subAgentViewCallbacks?.onStatus(viewId, "completed");
|
|
635245
|
+
return true;
|
|
634229
635246
|
} catch (err) {
|
|
634230
635247
|
if (typingInterval) {
|
|
634231
635248
|
clearInterval(typingInterval);
|
|
@@ -634244,6 +635261,7 @@ Join: ${newUrl}`);
|
|
|
634244
635261
|
await this.deleteLiveMessage(msg.chatId, liveMessageId).catch(() => {
|
|
634245
635262
|
});
|
|
634246
635263
|
}
|
|
635264
|
+
return false;
|
|
634247
635265
|
} finally {
|
|
634248
635266
|
this.activeChatViews.delete(viewId);
|
|
634249
635267
|
this.activeChatSessions.delete(sessionKey);
|
|
@@ -639485,14 +640503,14 @@ var init_direct_input = __esm({
|
|
|
639485
640503
|
return;
|
|
639486
640504
|
case "C":
|
|
639487
640505
|
if (params === "1;5") {
|
|
639488
|
-
this.
|
|
640506
|
+
this.emit("ctrl-right");
|
|
639489
640507
|
return;
|
|
639490
640508
|
}
|
|
639491
640509
|
if (this.cursor < this.line.length) this.cursor++;
|
|
639492
640510
|
return;
|
|
639493
640511
|
case "D":
|
|
639494
640512
|
if (params === "1;5") {
|
|
639495
|
-
this.
|
|
640513
|
+
this.emit("ctrl-left");
|
|
639496
640514
|
return;
|
|
639497
640515
|
}
|
|
639498
640516
|
if (this.cursor > 0) this.cursor--;
|
|
@@ -639786,14 +640804,14 @@ var init_access_policy = __esm({
|
|
|
639786
640804
|
});
|
|
639787
640805
|
|
|
639788
640806
|
// packages/cli/src/api/project-preferences.ts
|
|
639789
|
-
import { createHash as
|
|
640807
|
+
import { createHash as createHash32 } from "node:crypto";
|
|
639790
640808
|
import { existsSync as existsSync124, mkdirSync as mkdirSync72, readFileSync as readFileSync101, renameSync as renameSync8, writeFileSync as writeFileSync66, unlinkSync as unlinkSync26 } from "node:fs";
|
|
639791
640809
|
import { homedir as homedir46 } from "node:os";
|
|
639792
640810
|
import { join as join138, resolve as resolve50 } from "node:path";
|
|
639793
640811
|
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
639794
640812
|
function projectKey(root) {
|
|
639795
640813
|
const canonical = resolve50(root);
|
|
639796
|
-
return
|
|
640814
|
+
return createHash32("sha256").update(canonical).digest("hex").slice(0, 16);
|
|
639797
640815
|
}
|
|
639798
640816
|
function projectDir(root) {
|
|
639799
640817
|
return join138(PROJECTS_DIR, projectKey(root));
|
|
@@ -639885,7 +640903,7 @@ __export(voicechat_exports, {
|
|
|
639885
640903
|
VoiceChatSession: () => VoiceChatSession
|
|
639886
640904
|
});
|
|
639887
640905
|
import { EventEmitter as EventEmitter13 } from "node:events";
|
|
639888
|
-
function
|
|
640906
|
+
function clamp0112(x) {
|
|
639889
640907
|
return x < 0 ? 0 : x > 1 ? 1 : x;
|
|
639890
640908
|
}
|
|
639891
640909
|
function alnumRatio(s2) {
|
|
@@ -639924,9 +640942,9 @@ function computeSignalFromText(text, confidence2) {
|
|
|
639924
640942
|
else score = 0.15;
|
|
639925
640943
|
score -= repeatingCharPenalty(t2) * 0.4;
|
|
639926
640944
|
if (typeof confidence2 === "number" && !Number.isNaN(confidence2)) {
|
|
639927
|
-
score = 0.7 * score + 0.3 *
|
|
640945
|
+
score = 0.7 * score + 0.3 * clamp0112(confidence2);
|
|
639928
640946
|
}
|
|
639929
|
-
return
|
|
640947
|
+
return clamp0112(score);
|
|
639930
640948
|
}
|
|
639931
640949
|
function truncateForLog(s2, n2) {
|
|
639932
640950
|
return s2.length <= n2 ? s2 : s2.slice(0, n2 - 1) + "…";
|
|
@@ -640196,7 +641214,7 @@ Rules:
|
|
|
640196
641214
|
}, MAX_SEGMENT_MS);
|
|
640197
641215
|
}
|
|
640198
641216
|
this.captureBuffer = text;
|
|
640199
|
-
this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ?
|
|
641217
|
+
this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp0112(snr) : computeSignalFromText(text, confidence2);
|
|
640200
641218
|
this.emit("snr", { score: this.lastSignalScore });
|
|
640201
641219
|
this.onPartialTranscript(text);
|
|
640202
641220
|
if (this.silenceTimer) clearTimeout(this.silenceTimer);
|
|
@@ -640971,7 +641989,7 @@ var init_disk_task_output = __esm({
|
|
|
640971
641989
|
});
|
|
640972
641990
|
|
|
640973
641991
|
// packages/cli/src/api/http.ts
|
|
640974
|
-
import { createHash as
|
|
641992
|
+
import { createHash as createHash33 } from "node:crypto";
|
|
640975
641993
|
function problemDetails(opts) {
|
|
640976
641994
|
const p2 = {
|
|
640977
641995
|
type: opts.type ?? "about:blank",
|
|
@@ -641034,7 +642052,7 @@ function paginated(items, page2, total) {
|
|
|
641034
642052
|
}
|
|
641035
642053
|
function computeEtag(payload) {
|
|
641036
642054
|
const json = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
641037
|
-
const hash =
|
|
642055
|
+
const hash = createHash33("sha1").update(json).digest("hex").slice(0, 16);
|
|
641038
642056
|
return `W/"${hash}"`;
|
|
641039
642057
|
}
|
|
641040
642058
|
function checkNotModified(req2, res, etag) {
|
|
@@ -655465,7 +656483,7 @@ import { homedir as homedir53 } from "node:os";
|
|
|
655465
656483
|
import { spawn as spawn31, execSync as execSync58 } from "node:child_process";
|
|
655466
656484
|
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";
|
|
655467
656485
|
import { randomBytes as randomBytes27, randomUUID as randomUUID17 } from "node:crypto";
|
|
655468
|
-
import { createHash as
|
|
656486
|
+
import { createHash as createHash35 } from "node:crypto";
|
|
655469
656487
|
function memoryDbPaths3(baseDir = process.cwd()) {
|
|
655470
656488
|
const dir = join149(baseDir, ".omnius");
|
|
655471
656489
|
return {
|
|
@@ -661418,7 +662436,7 @@ function listScheduledTasks() {
|
|
|
661418
662436
|
const schedule = String(t2?.schedule || t2?.cron || t2?.when || "");
|
|
661419
662437
|
const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
|
|
661420
662438
|
const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
|
|
661421
|
-
const fallbackId =
|
|
662439
|
+
const fallbackId = createHash35("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
|
|
661422
662440
|
const uid = realId || fallbackId;
|
|
661423
662441
|
const key = `${uid}`;
|
|
661424
662442
|
if (seen.has(key)) return;
|
|
@@ -661535,8 +662553,8 @@ function deleteScheduledById(id) {
|
|
|
661535
662553
|
if (id) candidates.push(id);
|
|
661536
662554
|
if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id)) candidates.push(entry.id);
|
|
661537
662555
|
try {
|
|
661538
|
-
const { createHash:
|
|
661539
|
-
const fallback =
|
|
662556
|
+
const { createHash: createHash36 } = require4("node:crypto");
|
|
662557
|
+
const fallback = createHash36("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
|
|
661540
662558
|
if (!candidates.includes(fallback)) candidates.push(fallback);
|
|
661541
662559
|
} catch {
|
|
661542
662560
|
}
|
|
@@ -671685,13 +672703,13 @@ ${taskInput}`;
|
|
|
671685
672703
|
writeContent(() => renderError(errMsg));
|
|
671686
672704
|
if (failureStore) {
|
|
671687
672705
|
try {
|
|
671688
|
-
const { createHash:
|
|
672706
|
+
const { createHash: createHash36 } = await import("node:crypto");
|
|
671689
672707
|
failureStore.insert({
|
|
671690
672708
|
taskId: "",
|
|
671691
672709
|
sessionId: `${Date.now()}`,
|
|
671692
672710
|
repoRoot,
|
|
671693
672711
|
failureType: "runtime-error",
|
|
671694
|
-
fingerprint:
|
|
672712
|
+
fingerprint: createHash36("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
|
|
671695
672713
|
filePath: null,
|
|
671696
672714
|
errorMessage: errMsg.slice(0, 500),
|
|
671697
672715
|
context: null,
|