omnius 1.0.668 → 1.0.669
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 +470 -2784
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -72598,13 +72598,13 @@ var init_episodeStore = __esm({
|
|
|
72598
72598
|
}
|
|
72599
72599
|
return true;
|
|
72600
72600
|
}
|
|
72601
|
-
recordRetrieved(episodes,
|
|
72601
|
+
recordRetrieved(episodes, timestamp) {
|
|
72602
72602
|
if (episodes.length === 0)
|
|
72603
72603
|
return;
|
|
72604
72604
|
const updateStmt = this.db.prepare("UPDATE episodes SET strength = strength + 1, last_retrieved = ? WHERE id = ?");
|
|
72605
72605
|
const updateAll = this.db.transaction(() => {
|
|
72606
72606
|
for (const episode of episodes)
|
|
72607
|
-
updateStmt.run(
|
|
72607
|
+
updateStmt.run(timestamp, episode.id);
|
|
72608
72608
|
});
|
|
72609
72609
|
updateAll();
|
|
72610
72610
|
}
|
|
@@ -73777,7 +73777,7 @@ var init_temporalGraph = __esm({
|
|
|
73777
73777
|
* earlier recorded time. The recorded-time branch deliberately treats an
|
|
73778
73778
|
* edge as open before Omnius learned of its later supersession.
|
|
73779
73779
|
*/
|
|
73780
|
-
edgesAtTime(nodeId2,
|
|
73780
|
+
edgesAtTime(nodeId2, timestamp, recordedAsOf) {
|
|
73781
73781
|
if (recordedAsOf !== void 0) {
|
|
73782
73782
|
return this.db.prepare(`
|
|
73783
73783
|
SELECT * FROM kg_edges
|
|
@@ -73790,7 +73790,7 @@ var init_temporalGraph = __esm({
|
|
|
73790
73790
|
OR valid_until > ?
|
|
73791
73791
|
)
|
|
73792
73792
|
ORDER BY valid_from DESC, recorded_at DESC
|
|
73793
|
-
`).all(nodeId2, nodeId2, recordedAsOf,
|
|
73793
|
+
`).all(nodeId2, nodeId2, recordedAsOf, timestamp, recordedAsOf, timestamp).map((r2) => this.rowToEdge(r2));
|
|
73794
73794
|
}
|
|
73795
73795
|
return this.db.prepare(`
|
|
73796
73796
|
SELECT * FROM kg_edges
|
|
@@ -73798,7 +73798,7 @@ var init_temporalGraph = __esm({
|
|
|
73798
73798
|
AND valid_from <= ?
|
|
73799
73799
|
AND (valid_until IS NULL OR valid_until > ?)
|
|
73800
73800
|
ORDER BY valid_from DESC
|
|
73801
|
-
`).all(nodeId2, nodeId2,
|
|
73801
|
+
`).all(nodeId2, nodeId2, timestamp, timestamp).map((r2) => this.rowToEdge(r2));
|
|
73802
73802
|
}
|
|
73803
73803
|
/** Get full history of a node (all edges, including superseded). */
|
|
73804
73804
|
nodeHistory(nodeId2) {
|
|
@@ -74331,10 +74331,10 @@ function seededUnit(seed) {
|
|
|
74331
74331
|
function edgeKey(edge) {
|
|
74332
74332
|
return String(edge.id ?? `${edge.srcId}:${edge.dstId}:${edge.relation}:${edge.sourceEpisodeId ?? ""}`);
|
|
74333
74333
|
}
|
|
74334
|
-
function recencyScore(
|
|
74335
|
-
if (!
|
|
74334
|
+
function recencyScore(timestamp, now2) {
|
|
74335
|
+
if (!timestamp || !Number.isFinite(timestamp))
|
|
74336
74336
|
return 0;
|
|
74337
|
-
const ageMs = Math.max(0, now2 -
|
|
74337
|
+
const ageMs = Math.max(0, now2 - timestamp);
|
|
74338
74338
|
return Math.exp(-ageMs / (7 * 24 * 60 * 6e4));
|
|
74339
74339
|
}
|
|
74340
74340
|
function relationAllowed(edge, options2) {
|
|
@@ -98581,9 +98581,9 @@ var init_transcribe_tool = __esm({
|
|
|
98581
98581
|
const transcriptDir = join49(this.workingDir, ".omnius", "transcripts");
|
|
98582
98582
|
mkdirSync30(transcriptDir, { recursive: true });
|
|
98583
98583
|
const fileBase = basename8(filePath).replace(/\.[^.]+$/, "");
|
|
98584
|
-
const
|
|
98585
|
-
const txtFile = join49(transcriptDir, `${fileBase}-${
|
|
98586
|
-
const jsonFile = join49(transcriptDir, `${fileBase}-${
|
|
98584
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
98585
|
+
const txtFile = join49(transcriptDir, `${fileBase}-${timestamp}.txt`);
|
|
98586
|
+
const jsonFile = join49(transcriptDir, `${fileBase}-${timestamp}.json`);
|
|
98587
98587
|
writeFileSync29(txtFile, text3, "utf-8");
|
|
98588
98588
|
const structured = {
|
|
98589
98589
|
source: filePath,
|
|
@@ -170739,12 +170739,12 @@ var require_axios = __commonJS({
|
|
|
170739
170739
|
};
|
|
170740
170740
|
}
|
|
170741
170741
|
function throttle(fn, freq) {
|
|
170742
|
-
let
|
|
170742
|
+
let timestamp = 0;
|
|
170743
170743
|
let threshold = 1e3 / freq;
|
|
170744
170744
|
let lastArgs;
|
|
170745
170745
|
let timer;
|
|
170746
170746
|
const invoke = (args, now2 = Date.now()) => {
|
|
170747
|
-
|
|
170747
|
+
timestamp = now2;
|
|
170748
170748
|
lastArgs = null;
|
|
170749
170749
|
if (timer) {
|
|
170750
170750
|
clearTimeout(timer);
|
|
@@ -170754,7 +170754,7 @@ var require_axios = __commonJS({
|
|
|
170754
170754
|
};
|
|
170755
170755
|
const throttled = (...args) => {
|
|
170756
170756
|
const now2 = Date.now();
|
|
170757
|
-
const passed = now2 -
|
|
170757
|
+
const passed = now2 - timestamp;
|
|
170758
170758
|
if (passed >= threshold) {
|
|
170759
170759
|
invoke(args, now2);
|
|
170760
170760
|
} else {
|
|
@@ -173686,7 +173686,7 @@ var require_auto = __commonJS({
|
|
|
173686
173686
|
// ../node_modules/acme-client/src/client.js
|
|
173687
173687
|
var require_client = __commonJS({
|
|
173688
173688
|
"../node_modules/acme-client/src/client.js"(exports, module) {
|
|
173689
|
-
var { createHash:
|
|
173689
|
+
var { createHash: createHash81 } = __require("crypto");
|
|
173690
173690
|
var { getPemBodyAsB64u } = require_crypto();
|
|
173691
173691
|
var { log: log22 } = require_logger();
|
|
173692
173692
|
var HttpClient = require_http();
|
|
@@ -173997,14 +173997,14 @@ var require_client = __commonJS({
|
|
|
173997
173997
|
*/
|
|
173998
173998
|
async getChallengeKeyAuthorization(challenge) {
|
|
173999
173999
|
const jwk = this.http.getJwk();
|
|
174000
|
-
const keysum =
|
|
174000
|
+
const keysum = createHash81("sha256").update(JSON.stringify(jwk));
|
|
174001
174001
|
const thumbprint = keysum.digest("base64url");
|
|
174002
174002
|
const result = `${challenge.token}.${thumbprint}`;
|
|
174003
174003
|
if (challenge.type === "http-01") {
|
|
174004
174004
|
return result;
|
|
174005
174005
|
}
|
|
174006
174006
|
if (challenge.type === "dns-01") {
|
|
174007
|
-
return
|
|
174007
|
+
return createHash81("sha256").update(result).digest("base64url");
|
|
174008
174008
|
}
|
|
174009
174009
|
if (challenge.type === "tls-alpn-01") {
|
|
174010
174010
|
return result;
|
|
@@ -191728,9 +191728,9 @@ var require_pkcs7 = __commonJS({
|
|
|
191728
191728
|
var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z");
|
|
191729
191729
|
var date = attr.value;
|
|
191730
191730
|
if (typeof date === "string") {
|
|
191731
|
-
var
|
|
191732
|
-
if (!isNaN(
|
|
191733
|
-
date = new Date(
|
|
191731
|
+
var timestamp = Date.parse(date);
|
|
191732
|
+
if (!isNaN(timestamp)) {
|
|
191733
|
+
date = new Date(timestamp);
|
|
191734
191734
|
} else if (date.length === 13) {
|
|
191735
191735
|
date = asn1.utcTimeToDate(date);
|
|
191736
191736
|
} else {
|
|
@@ -193412,7 +193412,7 @@ var init_autonat = __esm({
|
|
|
193412
193412
|
};
|
|
193413
193413
|
}
|
|
193414
193414
|
this.log("dial multiaddrs %s for peer %p", multiaddrs.map((ma) => ma.toString()).join(", "), peerId);
|
|
193415
|
-
let
|
|
193415
|
+
let errorMessage = "";
|
|
193416
193416
|
let lastMultiaddr = multiaddrs[0];
|
|
193417
193417
|
for (const multiaddr2 of multiaddrs) {
|
|
193418
193418
|
let connection2;
|
|
@@ -193433,7 +193433,7 @@ var init_autonat = __esm({
|
|
|
193433
193433
|
};
|
|
193434
193434
|
} catch (err) {
|
|
193435
193435
|
this.log.error("could not dial %p - %e", peerId, err);
|
|
193436
|
-
|
|
193436
|
+
errorMessage = err.message;
|
|
193437
193437
|
} finally {
|
|
193438
193438
|
if (connection2 != null) {
|
|
193439
193439
|
await connection2.close();
|
|
@@ -193444,7 +193444,7 @@ var init_autonat = __esm({
|
|
|
193444
193444
|
type: Message.MessageType.DIAL_RESPONSE,
|
|
193445
193445
|
dialResponse: {
|
|
193446
193446
|
status: Message.ResponseStatus.E_DIAL_ERROR,
|
|
193447
|
-
statusText:
|
|
193447
|
+
statusText: errorMessage,
|
|
193448
193448
|
addr: lastMultiaddr.bytes
|
|
193449
193449
|
}
|
|
193450
193450
|
};
|
|
@@ -201479,8 +201479,8 @@ var require_util4 = __commonJS({
|
|
|
201479
201479
|
request.headersList.append("origin", serializedOrigin, true);
|
|
201480
201480
|
}
|
|
201481
201481
|
}
|
|
201482
|
-
function coarsenTime(
|
|
201483
|
-
return
|
|
201482
|
+
function coarsenTime(timestamp, crossOriginIsolatedCapability) {
|
|
201483
|
+
return timestamp;
|
|
201484
201484
|
}
|
|
201485
201485
|
function clampAndCoarsenConnectionTimingInfo(connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) {
|
|
201486
201486
|
if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) {
|
|
@@ -206463,8 +206463,8 @@ var require_socks5_client = __commonJS({
|
|
|
206463
206463
|
return;
|
|
206464
206464
|
}
|
|
206465
206465
|
if (reply !== REPLY_CODES.SUCCEEDED) {
|
|
206466
|
-
const
|
|
206467
|
-
throw new Socks5ProxyError(`SOCKS5 connection failed: ${
|
|
206466
|
+
const errorMessage = this.getReplyErrorMessage(reply);
|
|
206467
|
+
throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`);
|
|
206468
206468
|
}
|
|
206469
206469
|
let boundAddress;
|
|
206470
206470
|
let offset = 4;
|
|
@@ -211331,11 +211331,11 @@ var require_dns = __commonJS({
|
|
|
211331
211331
|
return ip;
|
|
211332
211332
|
}
|
|
211333
211333
|
setRecords(origin, addresses) {
|
|
211334
|
-
const
|
|
211334
|
+
const timestamp = Date.now();
|
|
211335
211335
|
const records = { records: { 4: null, 6: null } };
|
|
211336
211336
|
let minTTL = this.#maxTTL;
|
|
211337
211337
|
for (const record of addresses) {
|
|
211338
|
-
record.timestamp =
|
|
211338
|
+
record.timestamp = timestamp;
|
|
211339
211339
|
if (typeof record.ttl === "number") {
|
|
211340
211340
|
record.ttl = Math.min(record.ttl, this.#maxTTL);
|
|
211341
211341
|
minTTL = Math.min(minTTL, record.ttl);
|
|
@@ -297526,7 +297526,7 @@ var require_build3 = __commonJS({
|
|
|
297526
297526
|
return validations;
|
|
297527
297527
|
}
|
|
297528
297528
|
var JsonProp = (options2 = {}) => (target, propertyKey) => {
|
|
297529
|
-
const
|
|
297529
|
+
const errorMessage = `Cannot set type for ${propertyKey} property of ${target.constructor.name} schema`;
|
|
297530
297530
|
let schema;
|
|
297531
297531
|
if (!schemaStorage.has(target.constructor)) {
|
|
297532
297532
|
schema = schemaStorage.create(target.constructor);
|
|
@@ -297546,7 +297546,7 @@ var require_build3 = __commonJS({
|
|
|
297546
297546
|
copyOptions.validations = getValidations(copyOptions);
|
|
297547
297547
|
if (typeof copyOptions.type !== "number") {
|
|
297548
297548
|
if (!schemaStorage.has(copyOptions.type) && !isConvertible(copyOptions.type)) {
|
|
297549
|
-
throw new Error(`${
|
|
297549
|
+
throw new Error(`${errorMessage}. Assigning type doesn't have schema.`);
|
|
297550
297550
|
}
|
|
297551
297551
|
}
|
|
297552
297552
|
let schemaNames;
|
|
@@ -316684,7 +316684,7 @@ var require_websocket2 = __commonJS({
|
|
|
316684
316684
|
var http6 = __require("http");
|
|
316685
316685
|
var net5 = __require("net");
|
|
316686
316686
|
var tls2 = __require("tls");
|
|
316687
|
-
var { randomBytes: randomBytes32, createHash:
|
|
316687
|
+
var { randomBytes: randomBytes32, createHash: createHash81 } = __require("crypto");
|
|
316688
316688
|
var { Duplex: Duplex3, Readable: Readable2 } = __require("stream");
|
|
316689
316689
|
var { URL: URL3 } = __require("url");
|
|
316690
316690
|
var PerMessageDeflate3 = require_permessage_deflate2();
|
|
@@ -317344,7 +317344,7 @@ var require_websocket2 = __commonJS({
|
|
|
317344
317344
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
317345
317345
|
return;
|
|
317346
317346
|
}
|
|
317347
|
-
const digest4 =
|
|
317347
|
+
const digest4 = createHash81("sha1").update(key + GUID).digest("base64");
|
|
317348
317348
|
if (res.headers["sec-websocket-accept"] !== digest4) {
|
|
317349
317349
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
317350
317350
|
return;
|
|
@@ -317711,7 +317711,7 @@ var require_websocket_server = __commonJS({
|
|
|
317711
317711
|
var EventEmitter15 = __require("events");
|
|
317712
317712
|
var http6 = __require("http");
|
|
317713
317713
|
var { Duplex: Duplex3 } = __require("stream");
|
|
317714
|
-
var { createHash:
|
|
317714
|
+
var { createHash: createHash81 } = __require("crypto");
|
|
317715
317715
|
var extension3 = require_extension2();
|
|
317716
317716
|
var PerMessageDeflate3 = require_permessage_deflate2();
|
|
317717
317717
|
var subprotocol3 = require_subprotocol();
|
|
@@ -318012,7 +318012,7 @@ var require_websocket_server = __commonJS({
|
|
|
318012
318012
|
);
|
|
318013
318013
|
}
|
|
318014
318014
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
318015
|
-
const digest4 =
|
|
318015
|
+
const digest4 = createHash81("sha1").update(key + GUID).digest("base64");
|
|
318016
318016
|
const headers = [
|
|
318017
318017
|
"HTTP/1.1 101 Switching Protocols",
|
|
318018
318018
|
"Upgrade: websocket",
|
|
@@ -330819,13 +330819,13 @@ Justification: ${justification || "(none provided)"}`,
|
|
|
330819
330819
|
}
|
|
330820
330820
|
const snapshot = JSON.stringify(this.selfState, null, 2);
|
|
330821
330821
|
try {
|
|
330822
|
-
const { createHash:
|
|
330822
|
+
const { createHash: createHash81 } = await import("node:crypto");
|
|
330823
330823
|
const snapshotDir = join52(this.cwd, ".omnius", "identity", "snapshots");
|
|
330824
330824
|
await mkdir7(snapshotDir, { recursive: true });
|
|
330825
330825
|
const version5 = this.selfState.version;
|
|
330826
330826
|
const snapshotPath = join52(snapshotDir, `v${version5}.json`);
|
|
330827
330827
|
await writeFile12(snapshotPath, snapshot, "utf8");
|
|
330828
|
-
const hash2 =
|
|
330828
|
+
const hash2 = createHash81("sha256").update(snapshot).digest("hex");
|
|
330829
330829
|
await writeFile12(join52(this.cwd, ".omnius", "identity", "latest-hash.txt"), hash2, "utf8");
|
|
330830
330830
|
let ipfsCid = "";
|
|
330831
330831
|
try {
|
|
@@ -330958,8 +330958,8 @@ New: ${newNarrative.slice(0, 200)}...`,
|
|
|
330958
330958
|
}
|
|
330959
330959
|
// ── Helpers ──────────────────────────────────────────────────────────────
|
|
330960
330960
|
createDefaultState() {
|
|
330961
|
-
const { createHash:
|
|
330962
|
-
const machineId =
|
|
330961
|
+
const { createHash: createHash81 } = __require("node:crypto");
|
|
330962
|
+
const machineId = createHash81("sha256").update(this.cwd).digest("hex").slice(0, 12);
|
|
330963
330963
|
return {
|
|
330964
330964
|
self_id: `omnius-${machineId}`,
|
|
330965
330965
|
version: 1,
|
|
@@ -331041,9 +331041,9 @@ New: ${newNarrative.slice(0, 200)}...`,
|
|
|
331041
331041
|
let cid;
|
|
331042
331042
|
if (this.selfState.version > prevVersion) {
|
|
331043
331043
|
try {
|
|
331044
|
-
const { createHash:
|
|
331044
|
+
const { createHash: createHash81 } = await import("node:crypto");
|
|
331045
331045
|
const stateJson = JSON.stringify(this.selfState);
|
|
331046
|
-
const hash2 =
|
|
331046
|
+
const hash2 = createHash81("sha256").update(stateJson).digest("hex").slice(0, 32);
|
|
331047
331047
|
const cidsPath = join52(this.cwd, ".omnius", "identity", "cids.json");
|
|
331048
331048
|
const cidsData = { latest: "", hash: hash2, version: this.selfState.version };
|
|
331049
331049
|
try {
|
|
@@ -353460,7 +353460,7 @@ function requireWorkboard(workingDir, runId) {
|
|
|
353460
353460
|
}
|
|
353461
353461
|
return snapshot;
|
|
353462
353462
|
}
|
|
353463
|
-
function normalizeCardInput(input,
|
|
353463
|
+
function normalizeCardInput(input, timestamp) {
|
|
353464
353464
|
const title = cleanString(input.title);
|
|
353465
353465
|
if (!title)
|
|
353466
353466
|
throw new WorkboardError("title_required", "card title is required");
|
|
@@ -353488,9 +353488,9 @@ function normalizeCardInput(input, timestamp2) {
|
|
|
353488
353488
|
evidenceRequirements,
|
|
353489
353489
|
evidence: [],
|
|
353490
353490
|
decisions: [],
|
|
353491
|
-
createdAt:
|
|
353492
|
-
updatedAt:
|
|
353493
|
-
startedAt: status === "in_progress" ?
|
|
353491
|
+
createdAt: timestamp,
|
|
353492
|
+
updatedAt: timestamp,
|
|
353493
|
+
startedAt: status === "in_progress" ? timestamp : void 0,
|
|
353494
353494
|
blocker: status === "blocked" ? "Blocked when created." : void 0,
|
|
353495
353495
|
diagnosticFingerprint: cleanString(input.diagnosticFingerprint),
|
|
353496
353496
|
ownedFiles: normalizeStringArray(input.ownedFiles),
|
|
@@ -360989,7 +360989,7 @@ var require_typescript = __commonJS({
|
|
|
360989
360989
|
textSpanOverlapsWith: () => textSpanOverlapsWith,
|
|
360990
360990
|
textSpansEqual: () => textSpansEqual,
|
|
360991
360991
|
textToKeywordObj: () => textToKeywordObj,
|
|
360992
|
-
timestamp: () =>
|
|
360992
|
+
timestamp: () => timestamp,
|
|
360993
360993
|
toArray: () => toArray,
|
|
360994
360994
|
toBuilderFileEmit: () => toBuilderFileEmit,
|
|
360995
360995
|
toBuilderStateFileInfoForMultiEmit: () => toBuilderStateFileInfoForMultiEmit,
|
|
@@ -363948,7 +363948,7 @@ ${lanes.join("\n")}
|
|
|
363948
363948
|
function tryGetNativePerformanceHooks() {
|
|
363949
363949
|
return nativePerformanceHooks;
|
|
363950
363950
|
}
|
|
363951
|
-
var
|
|
363951
|
+
var timestamp = nativePerformanceTime ? () => nativePerformanceTime.now() : Date.now;
|
|
363952
363952
|
var ts_performance_exports = {};
|
|
363953
363953
|
__export2(ts_performance_exports, {
|
|
363954
363954
|
clearMarks: () => clearMarks,
|
|
@@ -363993,7 +363993,7 @@ ${lanes.join("\n")}
|
|
|
363993
363993
|
}
|
|
363994
363994
|
var nullTimer = { enter: noop2, exit: noop2 };
|
|
363995
363995
|
var enabled2 = false;
|
|
363996
|
-
var timeorigin =
|
|
363996
|
+
var timeorigin = timestamp();
|
|
363997
363997
|
var marks = /* @__PURE__ */ new Map();
|
|
363998
363998
|
var counts = /* @__PURE__ */ new Map();
|
|
363999
363999
|
var durations = /* @__PURE__ */ new Map();
|
|
@@ -364001,7 +364001,7 @@ ${lanes.join("\n")}
|
|
|
364001
364001
|
if (enabled2) {
|
|
364002
364002
|
const count = counts.get(markName) ?? 0;
|
|
364003
364003
|
counts.set(markName, count + 1);
|
|
364004
|
-
marks.set(markName,
|
|
364004
|
+
marks.set(markName, timestamp());
|
|
364005
364005
|
performanceImpl == null ? void 0 : performanceImpl.mark(markName);
|
|
364006
364006
|
if (typeof onProfilerEvent === "function") {
|
|
364007
364007
|
onProfilerEvent(markName);
|
|
@@ -364010,7 +364010,7 @@ ${lanes.join("\n")}
|
|
|
364010
364010
|
}
|
|
364011
364011
|
function measure(measureName, startMarkName, endMarkName) {
|
|
364012
364012
|
if (enabled2) {
|
|
364013
|
-
const end = (endMarkName !== void 0 ? marks.get(endMarkName) : void 0) ??
|
|
364013
|
+
const end = (endMarkName !== void 0 ? marks.get(endMarkName) : void 0) ?? timestamp();
|
|
364014
364014
|
const start2 = (startMarkName !== void 0 ? marks.get(startMarkName) : void 0) ?? timeorigin;
|
|
364015
364015
|
const previousDuration = durations.get(measureName) || 0;
|
|
364016
364016
|
durations.set(measureName, previousDuration + (end - start2));
|
|
@@ -364108,7 +364108,7 @@ ${lanes.join("\n")}
|
|
|
364108
364108
|
});
|
|
364109
364109
|
traceFd = fs14.openSync(tracePath, "w");
|
|
364110
364110
|
tracing = tracingEnabled2;
|
|
364111
|
-
const meta = { cat: "__metadata", ph: "M", ts: 1e3 *
|
|
364111
|
+
const meta = { cat: "__metadata", ph: "M", ts: 1e3 * timestamp(), pid: 1, tid: 1 };
|
|
364112
364112
|
fs14.writeSync(
|
|
364113
364113
|
traceFd,
|
|
364114
364114
|
"[\n" + [{ name: "process_name", args: { name: "tsc" }, ...meta }, { name: "thread_name", args: { name: "Main" }, ...meta }, { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" }].map((v) => JSON.stringify(v)).join(",\n")
|
|
@@ -364155,17 +364155,17 @@ ${lanes.join("\n")}
|
|
|
364155
364155
|
if (separateBeginAndEnd) {
|
|
364156
364156
|
writeEvent("B", phase, name10, args);
|
|
364157
364157
|
}
|
|
364158
|
-
eventStack.push({ phase, name: name10, args, time: 1e3 *
|
|
364158
|
+
eventStack.push({ phase, name: name10, args, time: 1e3 * timestamp(), separateBeginAndEnd });
|
|
364159
364159
|
}
|
|
364160
364160
|
tracingEnabled2.push = push;
|
|
364161
364161
|
function pop(results) {
|
|
364162
364162
|
Debug.assert(eventStack.length > 0);
|
|
364163
|
-
writeStackEvent(eventStack.length - 1, 1e3 *
|
|
364163
|
+
writeStackEvent(eventStack.length - 1, 1e3 * timestamp(), results);
|
|
364164
364164
|
eventStack.length--;
|
|
364165
364165
|
}
|
|
364166
364166
|
tracingEnabled2.pop = pop;
|
|
364167
364167
|
function popAll() {
|
|
364168
|
-
const endTime = 1e3 *
|
|
364168
|
+
const endTime = 1e3 * timestamp();
|
|
364169
364169
|
for (let i2 = eventStack.length - 1; i2 >= 0; i2--) {
|
|
364170
364170
|
writeStackEvent(i2, endTime);
|
|
364171
364171
|
}
|
|
@@ -364190,7 +364190,7 @@ ${lanes.join("\n")}
|
|
|
364190
364190
|
writeEvent("X", phase, name10, { ...args, results }, `"dur":${endTime - time}`, time);
|
|
364191
364191
|
}
|
|
364192
364192
|
}
|
|
364193
|
-
function writeEvent(eventType, phase, name10, args, extras, time = 1e3 *
|
|
364193
|
+
function writeEvent(eventType, phase, name10, args, extras, time = 1e3 * timestamp()) {
|
|
364194
364194
|
if (mode === "server" && phase === "checkTypes") return;
|
|
364195
364195
|
mark("beginTracing");
|
|
364196
364196
|
fs14.writeSync(traceFd, `,
|
|
@@ -366905,7 +366905,7 @@ ${lanes.join("\n")}
|
|
|
366905
366905
|
var _a2;
|
|
366906
366906
|
timerToUpdateChildWatches = void 0;
|
|
366907
366907
|
sysLog(`sysLog:: onTimerToUpdateChildWatches:: ${cacheToUpdateChildWatches.size}`);
|
|
366908
|
-
const start2 =
|
|
366908
|
+
const start2 = timestamp();
|
|
366909
366909
|
const invokeMap = /* @__PURE__ */ new Map();
|
|
366910
366910
|
while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
|
|
366911
366911
|
const result = cacheToUpdateChildWatches.entries().next();
|
|
@@ -366915,7 +366915,7 @@ ${lanes.join("\n")}
|
|
|
366915
366915
|
const hasChanges = updateChildWatches(dirName, dirPath, options2);
|
|
366916
366916
|
if (!((_a2 = cache8.get(dirPath)) == null ? void 0 : _a2.targetWatcher)) invokeCallbacks(dirName, dirPath, invokeMap, hasChanges ? void 0 : fileNames);
|
|
366917
366917
|
}
|
|
366918
|
-
sysLog(`sysLog:: invokingWatchers:: Elapsed:: ${
|
|
366918
|
+
sysLog(`sysLog:: invokingWatchers:: Elapsed:: ${timestamp() - start2}ms:: ${cacheToUpdateChildWatches.size}`);
|
|
366919
366919
|
callbackCache.forEach((callbacks, rootDirName) => {
|
|
366920
366920
|
const existing = invokeMap.get(rootDirName);
|
|
366921
366921
|
if (existing) {
|
|
@@ -366928,7 +366928,7 @@ ${lanes.join("\n")}
|
|
|
366928
366928
|
});
|
|
366929
366929
|
}
|
|
366930
366930
|
});
|
|
366931
|
-
const elapsed =
|
|
366931
|
+
const elapsed = timestamp() - start2;
|
|
366932
366932
|
sysLog(`sysLog:: Elapsed:: ${elapsed}ms:: onTimerToUpdateChildWatches:: ${cacheToUpdateChildWatches.size} ${timerToUpdateChildWatches}`);
|
|
366933
366933
|
}
|
|
366934
366934
|
function removeChildWatches(parentWatcher) {
|
|
@@ -416760,10 +416760,10 @@ ${lanes.join("\n")}
|
|
|
416760
416760
|
}
|
|
416761
416761
|
}
|
|
416762
416762
|
}
|
|
416763
|
-
function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors,
|
|
416763
|
+
function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors, errorMessage) {
|
|
416764
416764
|
const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1;
|
|
416765
|
-
|
|
416766
|
-
return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? void 0 :
|
|
416765
|
+
errorMessage ?? (errorMessage = getCannotResolveModuleNameErrorForSpecificModule(moduleReferenceExpression) ?? (isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations));
|
|
416766
|
+
return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? void 0 : errorMessage, ignoreErrors);
|
|
416767
416767
|
}
|
|
416768
416768
|
function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, ignoreErrors = false, isForAugmentation = false) {
|
|
416769
416769
|
return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, !ignoreErrors ? moduleReferenceExpression : void 0, isForAugmentation) : void 0;
|
|
@@ -431169,8 +431169,8 @@ ${lanes.join("\n")}
|
|
|
431169
431169
|
if (moduleSymbol.flags & targetMeaning) {
|
|
431170
431170
|
links3.resolvedType = resolveImportSymbolType(node, links3, moduleSymbol, targetMeaning);
|
|
431171
431171
|
} else {
|
|
431172
|
-
const
|
|
431173
|
-
error2(node,
|
|
431172
|
+
const errorMessage = targetMeaning === 111551 ? Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here : Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
|
|
431173
|
+
error2(node, errorMessage, node.argument.literal.text);
|
|
431174
431174
|
links3.resolvedSymbol = unknownSymbol;
|
|
431175
431175
|
links3.resolvedType = errorType;
|
|
431176
431176
|
}
|
|
@@ -432459,7 +432459,7 @@ ${lanes.join("\n")}
|
|
|
432459
432459
|
function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
|
|
432460
432460
|
let reportedError = false;
|
|
432461
432461
|
for (const value2 of iterator) {
|
|
432462
|
-
const { errorNode: prop, innerExpression: next, nameType, errorMessage
|
|
432462
|
+
const { errorNode: prop, innerExpression: next, nameType, errorMessage } = value2;
|
|
432463
432463
|
let targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
|
|
432464
432464
|
if (!targetPropType || targetPropType.flags & 33554432) continue;
|
|
432465
432465
|
let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
|
|
@@ -432499,9 +432499,9 @@ ${lanes.join("\n")}
|
|
|
432499
432499
|
const sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & 16777216);
|
|
432500
432500
|
targetPropType = removeMissingType(targetPropType, targetIsOptional);
|
|
432501
432501
|
sourcePropType = removeMissingType(sourcePropType, targetIsOptional && sourceIsOptional);
|
|
432502
|
-
const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop,
|
|
432502
|
+
const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
|
|
432503
432503
|
if (result && specificSource !== sourcePropType) {
|
|
432504
|
-
checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop,
|
|
432504
|
+
checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
|
|
432505
432505
|
}
|
|
432506
432506
|
}
|
|
432507
432507
|
if (resultObj.errors) {
|
|
@@ -432548,7 +432548,7 @@ ${lanes.join("\n")}
|
|
|
432548
432548
|
) : void 0;
|
|
432549
432549
|
let reportedError = false;
|
|
432550
432550
|
for (let status = iterator.next(); !status.done; status = iterator.next()) {
|
|
432551
|
-
const { errorNode: prop, innerExpression: next, nameType, errorMessage
|
|
432551
|
+
const { errorNode: prop, innerExpression: next, nameType, errorMessage } = status.value;
|
|
432552
432552
|
let targetPropType = iterationType;
|
|
432553
432553
|
const targetIndexedPropType = tupleOrArrayLikeTargetParts !== neverType ? getBestMatchIndexedAccessTypeOrUndefined(source, tupleOrArrayLikeTargetParts, nameType) : void 0;
|
|
432554
432554
|
if (targetIndexedPropType && !(targetIndexedPropType.flags & 33554432)) {
|
|
@@ -432592,9 +432592,9 @@ ${lanes.join("\n")}
|
|
|
432592
432592
|
const sourceIsOptional = !!(propName && (getPropertyOfType(source, propName) || unknownSymbol).flags & 16777216);
|
|
432593
432593
|
targetPropType = removeMissingType(targetPropType, targetIsOptional);
|
|
432594
432594
|
sourcePropType = removeMissingType(sourcePropType, targetIsOptional && sourceIsOptional);
|
|
432595
|
-
const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop,
|
|
432595
|
+
const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
|
|
432596
432596
|
if (result && specificSource !== sourcePropType) {
|
|
432597
|
-
checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop,
|
|
432597
|
+
checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
|
|
432598
432598
|
}
|
|
432599
432599
|
}
|
|
432600
432600
|
}
|
|
@@ -443619,9 +443619,9 @@ ${lanes.join("\n")}
|
|
|
443619
443619
|
return void 0;
|
|
443620
443620
|
}
|
|
443621
443621
|
const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1;
|
|
443622
|
-
const
|
|
443622
|
+
const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_for_the_appropriate_package_installed;
|
|
443623
443623
|
const specifier = getJSXRuntimeImportSpecifier(file, runtimeImportSpecifier);
|
|
443624
|
-
const mod3 = resolveExternalModule(specifier || location, runtimeImportSpecifier,
|
|
443624
|
+
const mod3 = resolveExternalModule(specifier || location, runtimeImportSpecifier, errorMessage, location);
|
|
443625
443625
|
const result = mod3 && mod3 !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod3)) : void 0;
|
|
443626
443626
|
if (links3) {
|
|
443627
443627
|
links3.jsxImplicitImportContainer = result || false;
|
|
@@ -455325,7 +455325,7 @@ ${lanes.join("\n")}
|
|
|
455325
455325
|
if (baseDeclarationFlags & 2 || derivedDeclarationFlags & 2) {
|
|
455326
455326
|
continue;
|
|
455327
455327
|
}
|
|
455328
|
-
let
|
|
455328
|
+
let errorMessage;
|
|
455329
455329
|
const basePropertyFlags = base3.flags & 98308;
|
|
455330
455330
|
const derivedPropertyFlags = derived.flags & 98308;
|
|
455331
455331
|
if (basePropertyFlags && derivedPropertyFlags) {
|
|
@@ -455335,16 +455335,16 @@ ${lanes.join("\n")}
|
|
|
455335
455335
|
const overriddenInstanceProperty = basePropertyFlags !== 4 && derivedPropertyFlags === 4;
|
|
455336
455336
|
const overriddenInstanceAccessor = basePropertyFlags === 4 && derivedPropertyFlags !== 4;
|
|
455337
455337
|
if (overriddenInstanceProperty || overriddenInstanceAccessor) {
|
|
455338
|
-
const
|
|
455339
|
-
error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration,
|
|
455338
|
+
const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
|
|
455339
|
+
error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base3), typeToString(baseType), typeToString(type));
|
|
455340
455340
|
} else if (useDefineForClassFields) {
|
|
455341
455341
|
const uninitialized = (_d = derived.declarations) == null ? void 0 : _d.find((d2) => d2.kind === 173 && !d2.initializer);
|
|
455342
455342
|
if (uninitialized && !(derived.flags & 33554432) && !(baseDeclarationFlags & 64) && !(derivedDeclarationFlags & 64) && !((_e = derived.declarations) == null ? void 0 : _e.some((d2) => !!(d2.flags & 33554432)))) {
|
|
455343
455343
|
const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol));
|
|
455344
455344
|
const propName = uninitialized.name;
|
|
455345
455345
|
if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) {
|
|
455346
|
-
const
|
|
455347
|
-
error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration,
|
|
455346
|
+
const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration;
|
|
455347
|
+
error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base3), typeToString(baseType));
|
|
455348
455348
|
}
|
|
455349
455349
|
}
|
|
455350
455350
|
}
|
|
@@ -455354,14 +455354,14 @@ ${lanes.join("\n")}
|
|
|
455354
455354
|
continue;
|
|
455355
455355
|
} else {
|
|
455356
455356
|
Debug.assert(!!(derived.flags & 98304));
|
|
455357
|
-
|
|
455357
|
+
errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
|
|
455358
455358
|
}
|
|
455359
455359
|
} else if (base3.flags & 98304) {
|
|
455360
|
-
|
|
455360
|
+
errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
|
|
455361
455361
|
} else {
|
|
455362
|
-
|
|
455362
|
+
errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
|
|
455363
455363
|
}
|
|
455364
|
-
error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration,
|
|
455364
|
+
error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base3), typeToString(type));
|
|
455365
455365
|
}
|
|
455366
455366
|
}
|
|
455367
455367
|
for (const [errorNode, memberInfo] of notImplementedInfo) {
|
|
@@ -456368,10 +456368,10 @@ ${lanes.join("\n")}
|
|
|
456368
456368
|
}
|
|
456369
456369
|
return false;
|
|
456370
456370
|
}
|
|
456371
|
-
function checkGrammarModuleElementContext(node,
|
|
456371
|
+
function checkGrammarModuleElementContext(node, errorMessage) {
|
|
456372
456372
|
const isInAppropriateContext = node.parent.kind === 308 || node.parent.kind === 269 || node.parent.kind === 268;
|
|
456373
456373
|
if (!isInAppropriateContext) {
|
|
456374
|
-
grammarErrorOnFirstToken(node,
|
|
456374
|
+
grammarErrorOnFirstToken(node, errorMessage);
|
|
456375
456375
|
}
|
|
456376
456376
|
return !isInAppropriateContext;
|
|
456377
456377
|
}
|
|
@@ -494595,17 +494595,17 @@ ${lanes.join("\n")}
|
|
|
494595
494595
|
function createDirectoryWatcherWithLogging(file, cb, flags, options2, detailInfo1, detailInfo2) {
|
|
494596
494596
|
const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options2, detailInfo1, detailInfo2, getDetailWatchInfo2)}`;
|
|
494597
494597
|
log22(watchInfo);
|
|
494598
|
-
const start2 =
|
|
494598
|
+
const start2 = timestamp();
|
|
494599
494599
|
const watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options2, detailInfo1, detailInfo2);
|
|
494600
|
-
const elapsed =
|
|
494600
|
+
const elapsed = timestamp() - start2;
|
|
494601
494601
|
log22(`Elapsed:: ${elapsed}ms ${watchInfo}`);
|
|
494602
494602
|
return {
|
|
494603
494603
|
close: () => {
|
|
494604
494604
|
const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options2, detailInfo1, detailInfo2, getDetailWatchInfo2)}`;
|
|
494605
494605
|
log22(watchInfo2);
|
|
494606
|
-
const start22 =
|
|
494606
|
+
const start22 = timestamp();
|
|
494607
494607
|
watcher.close();
|
|
494608
|
-
const elapsed2 =
|
|
494608
|
+
const elapsed2 = timestamp() - start22;
|
|
494609
494609
|
log22(`Elapsed:: ${elapsed2}ms ${watchInfo2}`);
|
|
494610
494610
|
}
|
|
494611
494611
|
};
|
|
@@ -494618,13 +494618,13 @@ ${lanes.join("\n")}
|
|
|
494618
494618
|
(...args) => {
|
|
494619
494619
|
const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options2, detailInfo1, detailInfo2, getDetailWatchInfo2)}`;
|
|
494620
494620
|
log22(triggerredInfo);
|
|
494621
|
-
const start2 =
|
|
494621
|
+
const start2 = timestamp();
|
|
494622
494622
|
cb.call(
|
|
494623
494623
|
/*thisArg*/
|
|
494624
494624
|
void 0,
|
|
494625
494625
|
...args
|
|
494626
494626
|
);
|
|
494627
|
-
const elapsed =
|
|
494627
|
+
const elapsed = timestamp() - start2;
|
|
494628
494628
|
log22(`Elapsed:: ${elapsed}ms ${triggerredInfo}`);
|
|
494629
494629
|
},
|
|
494630
494630
|
flags,
|
|
@@ -494898,14 +494898,14 @@ ${lanes.join("\n")}
|
|
|
494898
494898
|
return output2;
|
|
494899
494899
|
}
|
|
494900
494900
|
function formatDiagnostic(diagnostic, host2) {
|
|
494901
|
-
const
|
|
494901
|
+
const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, host2.getNewLine())}${host2.getNewLine()}`;
|
|
494902
494902
|
if (diagnostic.file) {
|
|
494903
494903
|
const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
|
|
494904
494904
|
const fileName = diagnostic.file.fileName;
|
|
494905
494905
|
const relativeFileName = convertToRelativePath(fileName, host2.getCurrentDirectory(), (fileName2) => host2.getCanonicalFileName(fileName2));
|
|
494906
|
-
return `${relativeFileName}(${line + 1},${character + 1}): ` +
|
|
494906
|
+
return `${relativeFileName}(${line + 1},${character + 1}): ` + errorMessage;
|
|
494907
494907
|
}
|
|
494908
|
-
return
|
|
494908
|
+
return errorMessage;
|
|
494909
494909
|
}
|
|
494910
494910
|
var ForegroundColorEscapeSequences = /* @__PURE__ */ ((ForegroundColorEscapeSequences2) => {
|
|
494911
494911
|
ForegroundColorEscapeSequences2["Grey"] = "\x1B[90m";
|
|
@@ -511483,7 +511483,7 @@ ${lanes.join("\n")}
|
|
|
511483
511483
|
));
|
|
511484
511484
|
const autoImportProvider = useAutoImportProvider && ((_a2 = host2.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host2));
|
|
511485
511485
|
if (autoImportProvider) {
|
|
511486
|
-
const start2 =
|
|
511486
|
+
const start2 = timestamp();
|
|
511487
511487
|
const checker = program.getTypeChecker();
|
|
511488
511488
|
forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), excludePatterns, host2, (module22, file) => {
|
|
511489
511489
|
if (file && !program.getSourceFile(file.fileName) || !file && !checker.resolveName(
|
|
@@ -511503,7 +511503,7 @@ ${lanes.join("\n")}
|
|
|
511503
511503
|
);
|
|
511504
511504
|
}
|
|
511505
511505
|
});
|
|
511506
|
-
(_b = host2.log) == null ? void 0 : _b.call(host2, `forEachExternalModuleToImportFrom autoImportProvider: ${
|
|
511506
|
+
(_b = host2.log) == null ? void 0 : _b.call(host2, `forEachExternalModuleToImportFrom autoImportProvider: ${timestamp() - start2}`);
|
|
511507
511507
|
}
|
|
511508
511508
|
}
|
|
511509
511509
|
function getIsExcludedPatterns(preferences, useCaseSensitiveFileNames2) {
|
|
@@ -511558,7 +511558,7 @@ ${lanes.join("\n")}
|
|
|
511558
511558
|
}
|
|
511559
511559
|
function getExportInfoMap(importingFile, host2, program, preferences, cancellationToken) {
|
|
511560
511560
|
var _a2, _b, _c, _d, _e;
|
|
511561
|
-
const start2 =
|
|
511561
|
+
const start2 = timestamp();
|
|
511562
511562
|
(_a2 = host2.getPackageJsonAutoImportProvider) == null ? void 0 : _a2.call(host2);
|
|
511563
511563
|
const cache8 = ((_b = host2.getCachedExportInfoMap) == null ? void 0 : _b.call(host2)) || createCacheableExportInfoMap({
|
|
511564
511564
|
getCurrentProgram: () => program,
|
|
@@ -511621,7 +511621,7 @@ ${lanes.join("\n")}
|
|
|
511621
511621
|
cache8.clear();
|
|
511622
511622
|
throw err;
|
|
511623
511623
|
}
|
|
511624
|
-
(_e = host2.log) == null ? void 0 : _e.call(host2, `getExportInfoMap: done in ${
|
|
511624
|
+
(_e = host2.log) == null ? void 0 : _e.call(host2, `getExportInfoMap: done in ${timestamp() - start2} ms`);
|
|
511625
511625
|
return cache8;
|
|
511626
511626
|
}
|
|
511627
511627
|
function getDefaultLikeExportInfo(moduleSymbol, checker) {
|
|
@@ -522252,7 +522252,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
522252
522252
|
this.lastCancellationCheckTime = 0;
|
|
522253
522253
|
}
|
|
522254
522254
|
isCancellationRequested() {
|
|
522255
|
-
const time =
|
|
522255
|
+
const time = timestamp();
|
|
522256
522256
|
const duration = Math.abs(time - this.lastCancellationCheckTime);
|
|
522257
522257
|
if (duration >= this.throttleWaitMilliseconds) {
|
|
522258
522258
|
this.lastCancellationCheckTime = time;
|
|
@@ -523076,13 +523076,13 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
523076
523076
|
return match ? [createTextSpanFromNode(token, sourceFile), createTextSpanFromNode(match, sourceFile)].sort((a2, b) => a2.start - b.start) : emptyArray;
|
|
523077
523077
|
}
|
|
523078
523078
|
function getIndentationAtPosition(fileName, position, editorOptions) {
|
|
523079
|
-
let start2 =
|
|
523079
|
+
let start2 = timestamp();
|
|
523080
523080
|
const settings = toEditorSettings(editorOptions);
|
|
523081
523081
|
const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
|
|
523082
|
-
log22("getIndentationAtPosition: getCurrentSourceFile: " + (
|
|
523083
|
-
start2 =
|
|
523082
|
+
log22("getIndentationAtPosition: getCurrentSourceFile: " + (timestamp() - start2));
|
|
523083
|
+
start2 = timestamp();
|
|
523084
523084
|
const result = ts_formatting_exports.SmartIndenter.getIndentation(position, sourceFile, settings);
|
|
523085
|
-
log22("getIndentationAtPosition: computeIndentation : " + (
|
|
523085
|
+
log22("getIndentationAtPosition: computeIndentation : " + (timestamp() - start2));
|
|
523086
523086
|
return result;
|
|
523087
523087
|
}
|
|
523088
523088
|
function getFormattingEditsForRange(fileName, start2, end, options2) {
|
|
@@ -536800,7 +536800,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
536800
536800
|
}
|
|
536801
536801
|
function resolvingModuleSpecifiers(logPrefix, host2, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) {
|
|
536802
536802
|
var _a2, _b, _c, _d;
|
|
536803
|
-
const start2 =
|
|
536803
|
+
const start2 = timestamp();
|
|
536804
536804
|
const needsFullResolution = isForImportStatementCompletion || getResolvePackageJsonExports(program.getCompilerOptions()) || ((_a2 = preferences.autoImportSpecifierExcludeRegexes) == null ? void 0 : _a2.length);
|
|
536805
536805
|
let skippedAny = false;
|
|
536806
536806
|
let ambientCount = 0;
|
|
@@ -536816,7 +536816,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
536816
536816
|
const hitRateMessage = cacheAttemptCount ? ` (${(resolvedFromCacheCount / cacheAttemptCount * 100).toFixed(1)}% hit rate)` : "";
|
|
536817
536817
|
(_b = host2.log) == null ? void 0 : _b.call(host2, `${logPrefix}: resolved ${resolvedCount} module specifiers, plus ${ambientCount} ambient and ${resolvedFromCacheCount} from cache${hitRateMessage}`);
|
|
536818
536818
|
(_c = host2.log) == null ? void 0 : _c.call(host2, `${logPrefix}: response is ${skippedAny ? "incomplete" : "complete"}`);
|
|
536819
|
-
(_d = host2.log) == null ? void 0 : _d.call(host2, `${logPrefix}: ${
|
|
536819
|
+
(_d = host2.log) == null ? void 0 : _d.call(host2, `${logPrefix}: ${timestamp() - start2}`);
|
|
536820
536820
|
return result;
|
|
536821
536821
|
function tryResolve(exportInfo, isFromAmbientModule) {
|
|
536822
536822
|
if (isFromAmbientModule) {
|
|
@@ -538403,7 +538403,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
538403
538403
|
}
|
|
538404
538404
|
}
|
|
538405
538405
|
function getCompletionEntriesFromSymbols(symbols, entries2, replacementToken, contextToken, location, position, sourceFile, host2, program, target, log22, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol = false) {
|
|
538406
|
-
const start2 =
|
|
538406
|
+
const start2 = timestamp();
|
|
538407
538407
|
const closestSymbolDeclaration = getClosestSymbolDeclaration(contextToken, location);
|
|
538408
538408
|
const useSemicolons = probablyUsesSemicolons(sourceFile);
|
|
538409
538409
|
const typeChecker = program.getTypeChecker();
|
|
@@ -538462,7 +538462,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
538462
538462
|
true
|
|
538463
538463
|
);
|
|
538464
538464
|
}
|
|
538465
|
-
log22("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (
|
|
538465
|
+
log22("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (timestamp() - start2));
|
|
538466
538466
|
return {
|
|
538467
538467
|
has: (name10) => uniques.has(name10),
|
|
538468
538468
|
add: (name10) => uniques.set(name10, true)
|
|
@@ -538885,12 +538885,12 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
538885
538885
|
function getCompletionData(program, log22, sourceFile, compilerOptions, position, preferences, detailsEntryId, host2, formatContext, cancellationToken) {
|
|
538886
538886
|
const typeChecker = program.getTypeChecker();
|
|
538887
538887
|
const inCheckedFile = isCheckedFile(sourceFile, compilerOptions);
|
|
538888
|
-
let start2 =
|
|
538888
|
+
let start2 = timestamp();
|
|
538889
538889
|
let currentToken = getTokenAtPosition(sourceFile, position);
|
|
538890
|
-
log22("getCompletionData: Get current token: " + (
|
|
538891
|
-
start2 =
|
|
538890
|
+
log22("getCompletionData: Get current token: " + (timestamp() - start2));
|
|
538891
|
+
start2 = timestamp();
|
|
538892
538892
|
const insideComment = isInComment(sourceFile, position, currentToken);
|
|
538893
|
-
log22("getCompletionData: Is inside comment: " + (
|
|
538893
|
+
log22("getCompletionData: Is inside comment: " + (timestamp() - start2));
|
|
538894
538894
|
let insideJsDocTagTypeExpression = false;
|
|
538895
538895
|
let insideJsDocImportTag = false;
|
|
538896
538896
|
let isInSnippetScope = false;
|
|
@@ -538939,12 +538939,12 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
538939
538939
|
return void 0;
|
|
538940
538940
|
}
|
|
538941
538941
|
}
|
|
538942
|
-
start2 =
|
|
538942
|
+
start2 = timestamp();
|
|
538943
538943
|
const isJsOnlyLocation = !insideJsDocTagTypeExpression && !insideJsDocImportTag && isSourceFileJS(sourceFile);
|
|
538944
538944
|
const tokens3 = getRelevantTokens(position, sourceFile);
|
|
538945
538945
|
const previousToken = tokens3.previousToken;
|
|
538946
538946
|
let contextToken = tokens3.contextToken;
|
|
538947
|
-
log22("getCompletionData: Get previous token: " + (
|
|
538947
|
+
log22("getCompletionData: Get previous token: " + (timestamp() - start2));
|
|
538948
538948
|
let node = currentToken;
|
|
538949
538949
|
let propertyAccessToConvert;
|
|
538950
538950
|
let isRightOfDot = false;
|
|
@@ -539077,7 +539077,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
539077
539077
|
}
|
|
539078
539078
|
}
|
|
539079
539079
|
}
|
|
539080
|
-
const semanticStart =
|
|
539080
|
+
const semanticStart = timestamp();
|
|
539081
539081
|
let completionKind = 5;
|
|
539082
539082
|
let hasUnresolvedAutoImports = false;
|
|
539083
539083
|
let symbols = [];
|
|
@@ -539110,7 +539110,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
539110
539110
|
return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierLocation) : void 0;
|
|
539111
539111
|
}
|
|
539112
539112
|
}
|
|
539113
|
-
log22("getCompletionData: Semantic work: " + (
|
|
539113
|
+
log22("getCompletionData: Semantic work: " + (timestamp() - semanticStart));
|
|
539114
539114
|
const contextualTypeOrConstraint = previousToken && (getContextualType(previousToken, position, sourceFile, typeChecker) ?? getConstraintOfTypeArgumentProperty(previousToken, typeChecker));
|
|
539115
539115
|
const isLiteralExpected = !tryCast(previousToken, isStringLiteralLike) && !isJsxIdentifierExpected;
|
|
539116
539116
|
const literals = !isLiteralExpected ? [] : mapDefined(
|
|
@@ -539655,9 +539655,9 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
|
|
|
539655
539655
|
return scope;
|
|
539656
539656
|
}
|
|
539657
539657
|
function isCompletionListBlocker(contextToken2) {
|
|
539658
|
-
const start22 =
|
|
539658
|
+
const start22 = timestamp();
|
|
539659
539659
|
const result = isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) || isSolelyIdentifierDefinitionLocation(contextToken2) || isDotOfNumericLiteral(contextToken2) || isInJsxText(contextToken2) || isBigIntLiteral(contextToken2);
|
|
539660
|
-
log22("getCompletionsAtPosition: isCompletionListBlocker: " + (
|
|
539660
|
+
log22("getCompletionsAtPosition: isCompletionListBlocker: " + (timestamp() - start22));
|
|
539661
539661
|
return result;
|
|
539662
539662
|
}
|
|
539663
539663
|
function isInJsxText(contextToken2) {
|
|
@@ -557240,7 +557240,7 @@ ${options2.prefix}` : "\n" : options2.prefix
|
|
|
557240
557240
|
textSpanOverlapsWith: () => textSpanOverlapsWith,
|
|
557241
557241
|
textSpansEqual: () => textSpansEqual,
|
|
557242
557242
|
textToKeywordObj: () => textToKeywordObj,
|
|
557243
|
-
timestamp: () =>
|
|
557243
|
+
timestamp: () => timestamp,
|
|
557244
557244
|
toArray: () => toArray,
|
|
557245
557245
|
toBuilderFileEmit: () => toBuilderFileEmit,
|
|
557246
557246
|
toBuilderStateFileInfoForMultiEmit: () => toBuilderStateFileInfoForMultiEmit,
|
|
@@ -559959,7 +559959,7 @@ ${options2.prefix}` : "\n" : options2.prefix
|
|
|
559959
559959
|
Debug.assert(oldProgram === this.program);
|
|
559960
559960
|
Debug.assert(!this.isClosed(), "Called update graph worker of closed project");
|
|
559961
559961
|
this.writeLog(`Starting updateGraphWorker: Project: ${this.getProjectName()}`);
|
|
559962
|
-
const start2 =
|
|
559962
|
+
const start2 = timestamp();
|
|
559963
559963
|
const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = this.resolutionCache.createHasInvalidatedResolutions(returnFalse, returnFalse);
|
|
559964
559964
|
this.hasInvalidatedResolutions = hasInvalidatedResolutions;
|
|
559965
559965
|
this.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions;
|
|
@@ -560065,7 +560065,7 @@ ${options2.prefix}` : "\n" : options2.prefix
|
|
|
560065
560065
|
},
|
|
560066
560066
|
(removed) => this.detachScriptInfoFromProject(removed)
|
|
560067
560067
|
);
|
|
560068
|
-
const elapsed =
|
|
560068
|
+
const elapsed = timestamp() - start2;
|
|
560069
560069
|
this.sendPerformanceEvent("UpdateGraph", elapsed);
|
|
560070
560070
|
this.writeLog(`Finishing updateGraphWorker: Project: ${this.getProjectName()} projectStateVersion: ${this.projectStateVersion} projectProgramVersion: ${this.projectProgramVersion} structureChanged: ${hasNewProgram}${this.program ? ` structureIsReused:: ${StructureIsReused[this.program.structureIsReused]}` : ""} Elapsed: ${elapsed}ms`);
|
|
560071
560071
|
if (this.projectService.logger.isTestLogger) {
|
|
@@ -560535,7 +560535,7 @@ ${options2.prefix}` : "\n" : options2.prefix
|
|
|
560535
560535
|
const dependencySelection = this.includePackageJsonAutoImports();
|
|
560536
560536
|
if (dependencySelection) {
|
|
560537
560537
|
(_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Session, "getPackageJsonAutoImportProvider");
|
|
560538
|
-
const start2 =
|
|
560538
|
+
const start2 = timestamp();
|
|
560539
560539
|
this.autoImportProviderHost = AutoImportProviderProject.create(
|
|
560540
560540
|
dependencySelection,
|
|
560541
560541
|
this,
|
|
@@ -560543,7 +560543,7 @@ ${options2.prefix}` : "\n" : options2.prefix
|
|
|
560543
560543
|
) ?? false;
|
|
560544
560544
|
if (this.autoImportProviderHost) {
|
|
560545
560545
|
updateProjectIfDirty(this.autoImportProviderHost);
|
|
560546
|
-
this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider",
|
|
560546
|
+
this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider", timestamp() - start2);
|
|
560547
560547
|
(_b = tracing) == null ? void 0 : _b.pop();
|
|
560548
560548
|
return this.autoImportProviderHost.getCurrentProgram();
|
|
560549
560549
|
}
|
|
@@ -560786,7 +560786,7 @@ ${options2.prefix}` : "\n" : options2.prefix
|
|
|
560786
560786
|
if (!program) {
|
|
560787
560787
|
return emptyArray;
|
|
560788
560788
|
}
|
|
560789
|
-
const start2 =
|
|
560789
|
+
const start2 = timestamp();
|
|
560790
560790
|
let dependencyNames;
|
|
560791
560791
|
let rootNames;
|
|
560792
560792
|
const rootFileName = combinePaths(hostProject.currentDirectory, inferredTypesContainingFile);
|
|
@@ -560878,7 +560878,7 @@ ${options2.prefix}` : "\n" : options2.prefix
|
|
|
560878
560878
|
});
|
|
560879
560879
|
}
|
|
560880
560880
|
if (rootNames == null ? void 0 : rootNames.size) {
|
|
560881
|
-
hostProject.log(`AutoImportProviderProject: found ${rootNames.size} root files in ${dependenciesAdded} dependencies ${referencesAddded} referenced projects in ${
|
|
560881
|
+
hostProject.log(`AutoImportProviderProject: found ${rootNames.size} root files in ${dependenciesAdded} dependencies ${referencesAddded} referenced projects in ${timestamp() - start2} ms`);
|
|
560882
560882
|
}
|
|
560883
560883
|
return rootNames ? arrayFrom(rootNames.values()) : emptyArray;
|
|
560884
560884
|
function addRootNames(entrypoints) {
|
|
@@ -567219,7 +567219,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter
|
|
|
567219
567219
|
}
|
|
567220
567220
|
semanticCheck(file, project) {
|
|
567221
567221
|
var _a2, _b;
|
|
567222
|
-
const diagnosticsStartTime =
|
|
567222
|
+
const diagnosticsStartTime = timestamp();
|
|
567223
567223
|
(_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Session, "semanticCheck", { file, configFilePath: project.canonicalConfigFilePath });
|
|
567224
567224
|
const diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) ? emptyArray2 : project.getLanguageService().getSemanticDiagnostics(file).filter((d2) => !!d2.file);
|
|
567225
567225
|
this.sendDiagnosticsEvent(file, project, diags, "semanticDiag", diagnosticsStartTime);
|
|
@@ -567227,21 +567227,21 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter
|
|
|
567227
567227
|
}
|
|
567228
567228
|
syntacticCheck(file, project) {
|
|
567229
567229
|
var _a2, _b;
|
|
567230
|
-
const diagnosticsStartTime =
|
|
567230
|
+
const diagnosticsStartTime = timestamp();
|
|
567231
567231
|
(_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Session, "syntacticCheck", { file, configFilePath: project.canonicalConfigFilePath });
|
|
567232
567232
|
this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag", diagnosticsStartTime);
|
|
567233
567233
|
(_b = tracing) == null ? void 0 : _b.pop();
|
|
567234
567234
|
}
|
|
567235
567235
|
suggestionCheck(file, project) {
|
|
567236
567236
|
var _a2, _b;
|
|
567237
|
-
const diagnosticsStartTime =
|
|
567237
|
+
const diagnosticsStartTime = timestamp();
|
|
567238
567238
|
(_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Session, "suggestionCheck", { file, configFilePath: project.canonicalConfigFilePath });
|
|
567239
567239
|
this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag", diagnosticsStartTime);
|
|
567240
567240
|
(_b = tracing) == null ? void 0 : _b.pop();
|
|
567241
567241
|
}
|
|
567242
567242
|
regionSemanticCheck(file, project, ranges) {
|
|
567243
567243
|
var _a2, _b, _c;
|
|
567244
|
-
const diagnosticsStartTime =
|
|
567244
|
+
const diagnosticsStartTime = timestamp();
|
|
567245
567245
|
(_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Session, "regionSemanticCheck", { file, configFilePath: project.canonicalConfigFilePath });
|
|
567246
567246
|
let diagnosticsResult;
|
|
567247
567247
|
if (!this.shouldDoRegionCheck(file) || !(diagnosticsResult = project.getLanguageService().getRegionSemanticDiagnostics(file, ranges))) {
|
|
@@ -567263,7 +567263,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter
|
|
|
567263
567263
|
sendDiagnosticsEvent(file, project, diagnostics, kind, diagnosticsStartTime, spans) {
|
|
567264
567264
|
try {
|
|
567265
567265
|
const scriptInfo = Debug.checkDefined(project.getScriptInfo(file));
|
|
567266
|
-
const duration =
|
|
567266
|
+
const duration = timestamp() - diagnosticsStartTime;
|
|
567267
567267
|
const body = {
|
|
567268
567268
|
file,
|
|
567269
567269
|
diagnostics: diagnostics.map((diag2) => formatDiag(file, project, diag2)),
|
|
@@ -575662,9 +575662,9 @@ ${nodeLocation}` : message2;
|
|
|
575662
575662
|
throw new ArgumentError(argName, "Expected a non-negative value.");
|
|
575663
575663
|
}
|
|
575664
575664
|
errors.throwIfNegative = throwIfNegative;
|
|
575665
|
-
function throwIfNullOrUndefined(value2,
|
|
575665
|
+
function throwIfNullOrUndefined(value2, errorMessage, node) {
|
|
575666
575666
|
if (value2 == null)
|
|
575667
|
-
throw new InvalidOperationError(typeof
|
|
575667
|
+
throw new InvalidOperationError(typeof errorMessage === "string" ? errorMessage : errorMessage(), node);
|
|
575668
575668
|
return value2;
|
|
575669
575669
|
}
|
|
575670
575670
|
errors.throwIfNullOrUndefined = throwIfNullOrUndefined;
|
|
@@ -575680,9 +575680,9 @@ ${nodeLocation}` : message2;
|
|
|
575680
575680
|
throw new InvalidOperationError(`Expected ${actual} to equal ${expected}. ${description}`);
|
|
575681
575681
|
}
|
|
575682
575682
|
errors.throwIfNotEqual = throwIfNotEqual;
|
|
575683
|
-
function throwIfTrue(value2,
|
|
575683
|
+
function throwIfTrue(value2, errorMessage) {
|
|
575684
575684
|
if (value2 === true)
|
|
575685
|
-
throw new InvalidOperationError(
|
|
575685
|
+
throw new InvalidOperationError(errorMessage);
|
|
575686
575686
|
}
|
|
575687
575687
|
errors.throwIfTrue = throwIfTrue;
|
|
575688
575688
|
})(exports.errors || (exports.errors = {}));
|
|
@@ -581649,8 +581649,8 @@ var require_ts_morph = __commonJS({
|
|
|
581649
581649
|
filePath;
|
|
581650
581650
|
oldText;
|
|
581651
581651
|
newText;
|
|
581652
|
-
constructor(filePath, oldText, newText,
|
|
581653
|
-
super(
|
|
581652
|
+
constructor(filePath, oldText, newText, errorMessage) {
|
|
581653
|
+
super(errorMessage);
|
|
581654
581654
|
this.filePath = filePath;
|
|
581655
581655
|
this.oldText = oldText;
|
|
581656
581656
|
this.newText = newText;
|
|
@@ -614913,10 +614913,10 @@ var init_video_understand = __esm({
|
|
|
614913
614913
|
for (let i2 = 0; i2 < frameFiles.length; i2++) {
|
|
614914
614914
|
const framePath = join97(framesDir, frameFiles[i2]);
|
|
614915
614915
|
const hash2 = imageHash(framePath);
|
|
614916
|
-
const
|
|
614916
|
+
const timestamp2 = duration > 0 ? i2 / Math.max(1, frameFiles.length - 1) * duration : i2 * frameInterval;
|
|
614917
614917
|
frames.push({
|
|
614918
614918
|
path: framePath,
|
|
614919
|
-
timestamp:
|
|
614919
|
+
timestamp: timestamp2,
|
|
614920
614920
|
hash: hash2,
|
|
614921
614921
|
isDuplicate: false
|
|
614922
614922
|
});
|
|
@@ -614966,8 +614966,8 @@ var init_video_understand = __esm({
|
|
|
614966
614966
|
frames: frames.filter((f2) => !f2.isDuplicate),
|
|
614967
614967
|
alignedTimeline
|
|
614968
614968
|
};
|
|
614969
|
-
const
|
|
614970
|
-
const resultFile = join97(outDir, `understanding-${
|
|
614969
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
614970
|
+
const resultFile = join97(outDir, `understanding-${timestamp}.json`);
|
|
614971
614971
|
writeFileSync46(resultFile, JSON.stringify(result, null, 2), "utf-8");
|
|
614972
614972
|
try {
|
|
614973
614973
|
const memDir = join97(this.workingDir, ".omnius", "memory");
|
|
@@ -621117,7 +621117,7 @@ import { z } from "zod";
|
|
|
621117
621117
|
function validateManifest(data, source) {
|
|
621118
621118
|
const result = manifestSchema.safeParse(data);
|
|
621119
621119
|
if (!result.success) {
|
|
621120
|
-
const errors = result.error.issues.map((
|
|
621120
|
+
const errors = result.error.issues.map((issue2) => ` - ${issue2.path.join(".")}: ${issue2.message}`);
|
|
621121
621121
|
const location = source ? ` in ${source}` : "";
|
|
621122
621122
|
throw new Error(`Invalid plugin manifest${location}:
|
|
621123
621123
|
${errors.join("\n")}
|
|
@@ -623254,7 +623254,7 @@ var init_operational_world = __esm({
|
|
|
623254
623254
|
issues: z16.array(OperationalValidationIssueSchema).max(1e4),
|
|
623255
623255
|
checkedAt: z16.string().datetime()
|
|
623256
623256
|
}).strict().superRefine((result, ctx3) => {
|
|
623257
|
-
const hasErrors = result.issues.some((
|
|
623257
|
+
const hasErrors = result.issues.some((issue2) => issue2.severity === "error");
|
|
623258
623258
|
if (result.valid !== (result.status === "pass")) {
|
|
623259
623259
|
ctx3.addIssue({
|
|
623260
623260
|
code: "custom",
|
|
@@ -624521,7 +624521,7 @@ var init_ralphLoop = __esm({
|
|
|
624521
624521
|
// -------------------------------------------------------------------------
|
|
624522
624522
|
// Private: error report builder
|
|
624523
624523
|
// -------------------------------------------------------------------------
|
|
624524
|
-
buildErrorReport(task, rawRequest, repoRoot, startedAt2,
|
|
624524
|
+
buildErrorReport(task, rawRequest, repoRoot, startedAt2, errorMessage) {
|
|
624525
624525
|
const fallbackTask = task ?? {
|
|
624526
624526
|
id: `task-error-${Date.now()}`,
|
|
624527
624527
|
goal: rawRequest.slice(0, 200),
|
|
@@ -624543,7 +624543,7 @@ var init_ralphLoop = __esm({
|
|
|
624543
624543
|
subtaskExecutions: [],
|
|
624544
624544
|
startedAt: startedAt2,
|
|
624545
624545
|
completedAt: isoNow(),
|
|
624546
|
-
summary:
|
|
624546
|
+
summary: errorMessage,
|
|
624547
624547
|
filesChanged: []
|
|
624548
624548
|
};
|
|
624549
624549
|
}
|
|
@@ -633170,7 +633170,7 @@ function inspectDeliveryCoverageManifest(workspace) {
|
|
|
633170
633170
|
if (parsed.success) {
|
|
633171
633171
|
return { status: "valid", manifest: parsed.data, path: path16 };
|
|
633172
633172
|
}
|
|
633173
|
-
const error = parsed.error.issues.slice(0, 8).map((
|
|
633173
|
+
const error = parsed.error.issues.slice(0, 8).map((issue2) => `${issue2.path.join(".") || "manifest"}: ${issue2.message}`).join("; ").slice(0, 1600);
|
|
633174
633174
|
return {
|
|
633175
633175
|
status: "invalid",
|
|
633176
633176
|
path: path16,
|
|
@@ -642770,11 +642770,11 @@ function recordContextWindowDump(input) {
|
|
|
642770
642770
|
if (process.env["OMNIUS_DISABLE_CONTEXT_WINDOW_DUMPS"] === "1")
|
|
642771
642771
|
return null;
|
|
642772
642772
|
const cwd4 = resolve59(input.cwd || process.cwd());
|
|
642773
|
-
const
|
|
642773
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
642774
642774
|
const sessionId = safeId(input.sessionId || process.env["OMNIUS_SESSION_ID"] || "unknown-session");
|
|
642775
642775
|
const runId = safeId(input.runId || input.sessionId || "unknown-run");
|
|
642776
642776
|
const stable2 = [
|
|
642777
|
-
|
|
642777
|
+
timestamp,
|
|
642778
642778
|
input.source,
|
|
642779
642779
|
input.stage,
|
|
642780
642780
|
input.agentType,
|
|
@@ -642782,7 +642782,7 @@ function recordContextWindowDump(input) {
|
|
|
642782
642782
|
String(input.turn ?? ""),
|
|
642783
642783
|
String(input.attempt ?? "")
|
|
642784
642784
|
].join("|");
|
|
642785
|
-
const id2 = `${
|
|
642785
|
+
const id2 = `${timestamp.replace(/[:.]/g, "-")}-${input.agentType}-${shortHash4(stable2)}`;
|
|
642786
642786
|
const metrics2 = analyzeContextWindowDumpRequest(input.request);
|
|
642787
642787
|
const requestBudget = input.requestBudget && budgetMatchesOutboundRequest(input.requestBudget, input.request) ? input.requestBudget : compileOutboundRequestBudget({
|
|
642788
642788
|
messages: Array.isArray(input.request["messages"]) ? input.request["messages"] : [],
|
|
@@ -642795,7 +642795,7 @@ function recordContextWindowDump(input) {
|
|
|
642795
642795
|
const record = {
|
|
642796
642796
|
schemaVersion: 1,
|
|
642797
642797
|
id: id2,
|
|
642798
|
-
timestamp
|
|
642798
|
+
timestamp,
|
|
642799
642799
|
source: input.source,
|
|
642800
642800
|
stage: input.stage,
|
|
642801
642801
|
agentType: input.agentType,
|
|
@@ -644534,9 +644534,9 @@ function validateCandidateRepresentation(candidate, record, claimRecords) {
|
|
|
644534
644534
|
if (isArtifactRecord(record)) {
|
|
644535
644535
|
if (!candidate.artifact)
|
|
644536
644536
|
return `artifact candidate ${candidate.id} lacks a durable artifact reference`;
|
|
644537
|
-
const
|
|
644538
|
-
if (
|
|
644539
|
-
return `candidate ${candidate.id} ${
|
|
644537
|
+
const issue2 = referenceMatchesRecord(candidate.artifact, record);
|
|
644538
|
+
if (issue2)
|
|
644539
|
+
return `candidate ${candidate.id} ${issue2}`;
|
|
644540
644540
|
} else if (candidate.artifact) {
|
|
644541
644541
|
return `non-artifact candidate ${candidate.id} may not claim an artifact reference`;
|
|
644542
644542
|
}
|
|
@@ -644601,9 +644601,9 @@ function validateMemoryCompilationPlan(input) {
|
|
|
644601
644601
|
return planHold(input, ["orientation exceeds bounded working-set limit"], planById);
|
|
644602
644602
|
for (const [id2, candidate] of planById) {
|
|
644603
644603
|
const record = candidateById.get(id2);
|
|
644604
|
-
const
|
|
644605
|
-
if (
|
|
644606
|
-
return planHold(input, [
|
|
644604
|
+
const issue2 = validateCandidateRepresentation(candidate, record, candidateById);
|
|
644605
|
+
if (issue2)
|
|
644606
|
+
return planHold(input, [issue2], planById);
|
|
644607
644607
|
if ((record.authority === "system" || record.authority === "user") && candidate.disposition !== "retain_full") {
|
|
644608
644608
|
return planHold(input, [`authority record ${id2} must be retained in full`], planById);
|
|
644609
644609
|
}
|
|
@@ -644712,10 +644712,10 @@ function recordDebugToolEvent(input) {
|
|
|
644712
644712
|
});
|
|
644713
644713
|
if (!shouldRecordToolEvent(input, diagnoses))
|
|
644714
644714
|
return null;
|
|
644715
|
-
const
|
|
644715
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
644716
644716
|
const argsHash = shortHash5(argsPreview);
|
|
644717
644717
|
const eventId = [
|
|
644718
|
-
|
|
644718
|
+
timestamp.replace(/[:.]/g, "-"),
|
|
644719
644719
|
safeId2(input.toolName),
|
|
644720
644720
|
argsHash
|
|
644721
644721
|
].join("-");
|
|
@@ -644736,7 +644736,7 @@ function recordDebugToolEvent(input) {
|
|
|
644736
644736
|
schemaVersion: 1,
|
|
644737
644737
|
id: eventId,
|
|
644738
644738
|
kind: lifecycle === "started" ? "tool_attempt" : "tool_result",
|
|
644739
|
-
timestamp
|
|
644739
|
+
timestamp,
|
|
644740
644740
|
runId,
|
|
644741
644741
|
sessionId,
|
|
644742
644742
|
cwd: cwd4,
|
|
@@ -644794,10 +644794,10 @@ function recordDebugContextWindowDump(input) {
|
|
|
644794
644794
|
const runId = safeId2(input.runId || input.record.runId || input.record.sessionId);
|
|
644795
644795
|
const sessionId = safeId2(input.sessionId || input.record.sessionId || runId);
|
|
644796
644796
|
const paths = debugRunPaths(cwd4, runId, input.stateDir);
|
|
644797
|
-
const
|
|
644797
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
644798
644798
|
const contextPath = join124(cwd4, ".omnius", "context-window-dumps", `${input.record.id}.json`);
|
|
644799
644799
|
const eventId = [
|
|
644800
|
-
|
|
644800
|
+
timestamp.replace(/[:.]/g, "-"),
|
|
644801
644801
|
"context",
|
|
644802
644802
|
shortHash5(input.record.id)
|
|
644803
644803
|
].join("-");
|
|
@@ -644808,7 +644808,7 @@ function recordDebugContextWindowDump(input) {
|
|
|
644808
644808
|
schemaVersion: 1,
|
|
644809
644809
|
id: eventId,
|
|
644810
644810
|
kind: "context_window_dump",
|
|
644811
|
-
timestamp
|
|
644811
|
+
timestamp,
|
|
644812
644812
|
runId,
|
|
644813
644813
|
sessionId,
|
|
644814
644814
|
cwd: cwd4,
|
|
@@ -644848,10 +644848,10 @@ function recordDebugTrajectoryCheckpoint(input) {
|
|
|
644848
644848
|
const cwd4 = resolve60(input.cwd || process.cwd());
|
|
644849
644849
|
const runId = safeId2(input.runId || input.sessionId || "unknown-run");
|
|
644850
644850
|
const sessionId = safeId2(input.sessionId || runId);
|
|
644851
|
-
const
|
|
644851
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
644852
644852
|
const paths = debugRunPaths(cwd4, runId, input.stateDir);
|
|
644853
644853
|
const eventId = [
|
|
644854
|
-
|
|
644854
|
+
timestamp.replace(/[:.]/g, "-"),
|
|
644855
644855
|
"trajectory",
|
|
644856
644856
|
shortHash5(checkpoint.id)
|
|
644857
644857
|
].join("-");
|
|
@@ -644865,7 +644865,7 @@ function recordDebugTrajectoryCheckpoint(input) {
|
|
|
644865
644865
|
schemaVersion: 1,
|
|
644866
644866
|
id: eventId,
|
|
644867
644867
|
kind: "trajectory_checkpoint",
|
|
644868
|
-
timestamp
|
|
644868
|
+
timestamp,
|
|
644869
644869
|
runId,
|
|
644870
644870
|
sessionId,
|
|
644871
644871
|
cwd: cwd4,
|
|
@@ -647467,10 +647467,10 @@ function computeStalenessLoad(messages2, currentTurn, stalenessThresholds) {
|
|
|
647467
647467
|
const staleSpanIds = [];
|
|
647468
647468
|
const detailParts = [];
|
|
647469
647469
|
for (const m2 of timed) {
|
|
647470
|
-
const { span_id, token_count, timestamp
|
|
647470
|
+
const { span_id, token_count, timestamp, provenance } = m2.spanMeta;
|
|
647471
647471
|
const tok = typeof token_count === "number" && !Number.isNaN(token_count) ? token_count : 0;
|
|
647472
647472
|
totalTokens += tok;
|
|
647473
|
-
const pos = (
|
|
647473
|
+
const pos = (timestamp - minTs) / totalSpan;
|
|
647474
647474
|
const estimatedTurn = 1 + pos * (currentTurn - 1);
|
|
647475
647475
|
const turnAge = currentTurn - estimatedTurn;
|
|
647476
647476
|
const type = classifyProvenance(provenance);
|
|
@@ -655034,13 +655034,13 @@ runtime_module_sha256=${record.runtimeProvenance.module.sha256 ?? "unknown"}`
|
|
|
655034
655034
|
}
|
|
655035
655035
|
};
|
|
655036
655036
|
commitCompletionFinalization(stateDir, committed);
|
|
655037
|
-
const
|
|
655037
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
655038
655038
|
this.emit({
|
|
655039
655039
|
type: "complete",
|
|
655040
655040
|
content: input.summary,
|
|
655041
655041
|
success: input.status === "completed",
|
|
655042
655042
|
terminalReceiptId: committed.id,
|
|
655043
|
-
timestamp
|
|
655043
|
+
timestamp
|
|
655044
655044
|
});
|
|
655045
655045
|
this._onTypedEvent?.({
|
|
655046
655046
|
type: "run_finished",
|
|
@@ -655048,7 +655048,7 @@ runtime_module_sha256=${record.runtimeProvenance.module.sha256 ?? "unknown"}`
|
|
|
655048
655048
|
status: input.status,
|
|
655049
655049
|
success: input.status === "completed",
|
|
655050
655050
|
terminalReceiptId: committed.id,
|
|
655051
|
-
timestamp
|
|
655051
|
+
timestamp
|
|
655052
655052
|
});
|
|
655053
655053
|
return committed;
|
|
655054
655054
|
} catch {
|
|
@@ -668745,8 +668745,8 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
|
|
|
668745
668745
|
if (process.env["OMNIUS_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
|
|
668746
668746
|
const goalForSig = (this._taskState.goal || "").slice(0, 200);
|
|
668747
668747
|
const recentTools = this._toolSequence.slice(-5).join("|");
|
|
668748
|
-
const { createHash:
|
|
668749
|
-
const sig =
|
|
668748
|
+
const { createHash: createHash81 } = await import("node:crypto");
|
|
668749
|
+
const sig = createHash81("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
|
|
668750
668750
|
if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
|
|
668751
668751
|
compacted.push({
|
|
668752
668752
|
role: "system",
|
|
@@ -673971,19 +673971,19 @@ ${terminalFeedback.slice(0, 4e3)}`,
|
|
|
673971
673971
|
summary = summary ? `${summary}
|
|
673972
673972
|
|
|
673973
673973
|
${detail}` : detail;
|
|
673974
|
-
const
|
|
673974
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
673975
673975
|
this.emit({
|
|
673976
673976
|
type: "complete",
|
|
673977
673977
|
content: summary,
|
|
673978
673978
|
success: false,
|
|
673979
|
-
timestamp
|
|
673979
|
+
timestamp
|
|
673980
673980
|
});
|
|
673981
673981
|
this._onTypedEvent?.({
|
|
673982
673982
|
type: "run_finished",
|
|
673983
673983
|
runId: this.currentArtifactRunId(),
|
|
673984
673984
|
status: runStatus,
|
|
673985
673985
|
success: false,
|
|
673986
|
-
timestamp
|
|
673986
|
+
timestamp
|
|
673987
673987
|
});
|
|
673988
673988
|
}
|
|
673989
673989
|
this._emitMASTSummary("run-end");
|
|
@@ -677250,7 +677250,7 @@ Describe what you see and integrate this into your current approach.` : "[User s
|
|
|
677250
677250
|
const postChars = combinedSummary.length + retainedMiddle.reduce((s2, m2) => s2 + _estimateMsgChars(m2), 0) + recent.reduce((s2, m2) => s2 + _estimateMsgChars(m2), 0) + head.reduce((s2, m2) => s2 + _estimateMsgChars(m2), 0);
|
|
677251
677251
|
const postTokens = Math.ceil(postChars / 4);
|
|
677252
677252
|
const savedTokens = preTokens - postTokens;
|
|
677253
|
-
const
|
|
677253
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
677254
677254
|
const removedMessages = messages2.slice(headEndIdx, recentStart).map((message2, offset) => ({ message: message2, index: headEndIdx + offset })).filter(({ index }) => analyst.retiredIds.has(`c_${index}`)).map(({ message: message2, index }) => {
|
|
677255
677255
|
const content = typeof message2.content === "string" ? message2.content : JSON.stringify(message2.content);
|
|
677256
677256
|
const isLegacy = this._isLegacyControlMessage(message2);
|
|
@@ -677268,7 +677268,7 @@ Describe what you see and integrate this into your current approach.` : "[User s
|
|
|
677268
677268
|
id: `cmp-${this.currentArtifactRunId()}-${Date.now().toString(36)}`,
|
|
677269
677269
|
runId: this.currentArtifactRunId(),
|
|
677270
677270
|
sessionId: this._sessionId,
|
|
677271
|
-
timestamp
|
|
677271
|
+
timestamp,
|
|
677272
677272
|
strategy,
|
|
677273
677273
|
manual: force,
|
|
677274
677274
|
beforeTokens: preTokens,
|
|
@@ -677292,7 +677292,7 @@ Describe what you see and integrate this into your current approach.` : "[User s
|
|
|
677292
677292
|
this.emit({
|
|
677293
677293
|
type: "compaction",
|
|
677294
677294
|
content: `Inference-compacted ${removedMessages.length} messages${strategyLabel}${forceLabel} | ~${preTokens.toLocaleString()} → ~${postTokens.toLocaleString()} tokens (saved ~${savedTokens.toLocaleString()})`,
|
|
677295
|
-
timestamp
|
|
677295
|
+
timestamp,
|
|
677296
677296
|
compaction: compactionAudit
|
|
677297
677297
|
});
|
|
677298
677298
|
const tier = this.options.modelTier ?? "large";
|
|
@@ -682701,14 +682701,14 @@ function text2(value2, max = 500) {
|
|
|
682701
682701
|
return out ? out.slice(0, max) : "";
|
|
682702
682702
|
}
|
|
682703
682703
|
function legacyAgenticEventToRunEvent(runId, event) {
|
|
682704
|
-
const
|
|
682704
|
+
const timestamp = event.timestamp;
|
|
682705
682705
|
if (event.type === "assistant_text") {
|
|
682706
682706
|
return {
|
|
682707
682707
|
type: "assistant_visible_text",
|
|
682708
682708
|
runId,
|
|
682709
682709
|
text: text2(event.content, 8e3),
|
|
682710
682710
|
source: event["source"] === "task_complete_summary" ? "summary_fallback" : "model",
|
|
682711
|
-
timestamp
|
|
682711
|
+
timestamp
|
|
682712
682712
|
};
|
|
682713
682713
|
}
|
|
682714
682714
|
if (event.type === "tool_call") {
|
|
@@ -682718,7 +682718,7 @@ function legacyAgenticEventToRunEvent(runId, event) {
|
|
|
682718
682718
|
toolName: text2(event.toolName ?? event["name"], 120),
|
|
682719
682719
|
callId: typeof event.callId === "string" ? event.callId : void 0,
|
|
682720
682720
|
argsPreview: text2(event["args"] ?? event.content, 500),
|
|
682721
|
-
timestamp
|
|
682721
|
+
timestamp
|
|
682722
682722
|
};
|
|
682723
682723
|
}
|
|
682724
682724
|
if (event.type === "tool_result") {
|
|
@@ -682729,7 +682729,7 @@ function legacyAgenticEventToRunEvent(runId, event) {
|
|
|
682729
682729
|
callId: typeof event.callId === "string" ? event.callId : void 0,
|
|
682730
682730
|
success: event.success === true,
|
|
682731
682731
|
outputPreview: text2(event.content, 500),
|
|
682732
|
-
timestamp
|
|
682732
|
+
timestamp
|
|
682733
682733
|
};
|
|
682734
682734
|
}
|
|
682735
682735
|
if (event.type === "trajectory_checkpoint") {
|
|
@@ -682741,7 +682741,7 @@ function legacyAgenticEventToRunEvent(runId, event) {
|
|
|
682741
682741
|
...typeof trajectory?.["assessment"] === "string" ? { assessment: text2(trajectory["assessment"], 80) } : {},
|
|
682742
682742
|
...typeof trajectory?.["nextAction"] === "string" ? { nextAction: text2(trajectory["nextAction"], 500) } : {},
|
|
682743
682743
|
summary: text2(event.content, 900),
|
|
682744
|
-
timestamp
|
|
682744
|
+
timestamp
|
|
682745
682745
|
};
|
|
682746
682746
|
}
|
|
682747
682747
|
if (event.type === "complete") {
|
|
@@ -682752,7 +682752,7 @@ function legacyAgenticEventToRunEvent(runId, event) {
|
|
|
682752
682752
|
status: success ? "completed" : "incomplete",
|
|
682753
682753
|
success,
|
|
682754
682754
|
...typeof event["terminalReceiptId"] === "string" ? { terminalReceiptId: event["terminalReceiptId"] } : {},
|
|
682755
|
-
timestamp
|
|
682755
|
+
timestamp
|
|
682756
682756
|
};
|
|
682757
682757
|
}
|
|
682758
682758
|
return null;
|
|
@@ -703855,7 +703855,7 @@ var require_websocket3 = __commonJS({
|
|
|
703855
703855
|
var http6 = __require("http");
|
|
703856
703856
|
var net5 = __require("net");
|
|
703857
703857
|
var tls2 = __require("tls");
|
|
703858
|
-
var { randomBytes: randomBytes32, createHash:
|
|
703858
|
+
var { randomBytes: randomBytes32, createHash: createHash81 } = __require("crypto");
|
|
703859
703859
|
var { Duplex: Duplex3, Readable: Readable2 } = __require("stream");
|
|
703860
703860
|
var { URL: URL3 } = __require("url");
|
|
703861
703861
|
var PerMessageDeflate3 = require_permessage_deflate3();
|
|
@@ -704515,7 +704515,7 @@ var require_websocket3 = __commonJS({
|
|
|
704515
704515
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
704516
704516
|
return;
|
|
704517
704517
|
}
|
|
704518
|
-
const digest4 =
|
|
704518
|
+
const digest4 = createHash81("sha1").update(key + GUID).digest("base64");
|
|
704519
704519
|
if (res.headers["sec-websocket-accept"] !== digest4) {
|
|
704520
704520
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
704521
704521
|
return;
|
|
@@ -704882,7 +704882,7 @@ var require_websocket_server2 = __commonJS({
|
|
|
704882
704882
|
var EventEmitter15 = __require("events");
|
|
704883
704883
|
var http6 = __require("http");
|
|
704884
704884
|
var { Duplex: Duplex3 } = __require("stream");
|
|
704885
|
-
var { createHash:
|
|
704885
|
+
var { createHash: createHash81 } = __require("crypto");
|
|
704886
704886
|
var extension3 = require_extension3();
|
|
704887
704887
|
var PerMessageDeflate3 = require_permessage_deflate3();
|
|
704888
704888
|
var subprotocol3 = require_subprotocol2();
|
|
@@ -705183,7 +705183,7 @@ var require_websocket_server2 = __commonJS({
|
|
|
705183
705183
|
);
|
|
705184
705184
|
}
|
|
705185
705185
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
705186
|
-
const digest4 =
|
|
705186
|
+
const digest4 = createHash81("sha1").update(key + GUID).digest("base64");
|
|
705187
705187
|
const headers = [
|
|
705188
705188
|
"HTTP/1.1 101 Switching Protocols",
|
|
705189
705189
|
"Upgrade: websocket",
|
|
@@ -718103,9 +718103,9 @@ function computeDedupeHash(task, savedAt) {
|
|
|
718103
718103
|
return createHash67("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
|
|
718104
718104
|
}
|
|
718105
718105
|
function generateSessionId() {
|
|
718106
|
-
const
|
|
718106
|
+
const timestamp = Date.now().toString(36);
|
|
718107
718107
|
const random = Math.random().toString(36).slice(2, 8);
|
|
718108
|
-
return `${
|
|
718108
|
+
return `${timestamp}-${random}`;
|
|
718109
718109
|
}
|
|
718110
718110
|
function acquireLock(lockPath) {
|
|
718111
718111
|
const startTime = Date.now();
|
|
@@ -721921,11 +721921,11 @@ function normalizeValueSignature(value2) {
|
|
|
721921
721921
|
function trimMemoryValueMetadata(value2) {
|
|
721922
721922
|
return value2.replace(/\b(?:confidence|weight|salience|score|noise_score|relevance)\s*[=:]\s*\d*\.?\d+\b/gi, "").replace(/\b(?:evidence|sources?|refs?)\s*[=:]\s*[\d,\s]+\b/gi, "").replace(/\bvalue_?hash\s*[=:]\s*[0-9a-f]{8,}\b/gi, "").replace(/[ \t]{2,}/g, " ").replace(/\s+([,.;])/g, "$1").trim();
|
|
721923
721923
|
}
|
|
721924
|
-
function parseMemoryTimestamp(
|
|
721925
|
-
if (!
|
|
721926
|
-
const asNumber3 = Number(
|
|
721924
|
+
function parseMemoryTimestamp(timestamp) {
|
|
721925
|
+
if (!timestamp) return void 0;
|
|
721926
|
+
const asNumber3 = Number(timestamp);
|
|
721927
721927
|
if (Number.isFinite(asNumber3) && asNumber3 > 0) return asNumber3;
|
|
721928
|
-
const parsed = Date.parse(
|
|
721928
|
+
const parsed = Date.parse(timestamp);
|
|
721929
721929
|
return Number.isFinite(parsed) ? parsed : void 0;
|
|
721930
721930
|
}
|
|
721931
721931
|
function memoryContextCharBudget() {
|
|
@@ -737191,8 +737191,8 @@ async function showEpisodesMenu(options2) {
|
|
|
737191
737191
|
renderError(`Failed to load episodes: ${e2}`);
|
|
737192
737192
|
}
|
|
737193
737193
|
}
|
|
737194
|
-
function formatTimeAgo(
|
|
737195
|
-
const seconds = Math.floor((Date.now() -
|
|
737194
|
+
function formatTimeAgo(timestamp) {
|
|
737195
|
+
const seconds = Math.floor((Date.now() - timestamp) / 1e3);
|
|
737196
737196
|
if (seconds < 60) return "just now";
|
|
737197
737197
|
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
|
|
737198
737198
|
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
|
|
@@ -739187,9 +739187,9 @@ function saveJobOutput(jobId, output2) {
|
|
|
739187
739187
|
chmodSync10(jobOutDir, 448);
|
|
739188
739188
|
} catch {
|
|
739189
739189
|
}
|
|
739190
|
-
const
|
|
739190
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
739191
739191
|
const suffix = randomUUID30().slice(0, 6);
|
|
739192
|
-
const outFile = join165(jobOutDir, `${
|
|
739192
|
+
const outFile = join165(jobOutDir, `${timestamp}-${suffix}.md`);
|
|
739193
739193
|
writeFileSync85(outFile, output2, "utf-8");
|
|
739194
739194
|
secureFile(outFile);
|
|
739195
739195
|
return outFile;
|
|
@@ -774066,1842 +774066,6 @@ var init_emotion_engine = __esm({
|
|
|
774066
774066
|
}
|
|
774067
774067
|
});
|
|
774068
774068
|
|
|
774069
|
-
// packages/cli/src/tui/telegram-context-packet-v2.ts
|
|
774070
|
-
import { createHash as createHash70 } from "node:crypto";
|
|
774071
|
-
function assertId(value2, field) {
|
|
774072
|
-
if (!ID_PATTERN.test(value2)) {
|
|
774073
|
-
throw new TelegramContextPacketValidationError(
|
|
774074
|
-
`${field} must match ${ID_PATTERN.source}`
|
|
774075
|
-
);
|
|
774076
|
-
}
|
|
774077
|
-
}
|
|
774078
|
-
function normalizedInteger(value2, fallback, field) {
|
|
774079
|
-
const resolved = value2 ?? fallback;
|
|
774080
|
-
if (!Number.isSafeInteger(resolved)) {
|
|
774081
|
-
throw new TelegramContextPacketValidationError(
|
|
774082
|
-
`${field} must be a safe integer`
|
|
774083
|
-
);
|
|
774084
|
-
}
|
|
774085
|
-
return resolved;
|
|
774086
|
-
}
|
|
774087
|
-
function normalizedBudget(value2, field) {
|
|
774088
|
-
if (!Number.isSafeInteger(value2) || value2 < 0) {
|
|
774089
|
-
throw new TelegramContextPacketValidationError(
|
|
774090
|
-
`${field} must be a non-negative safe integer`
|
|
774091
|
-
);
|
|
774092
|
-
}
|
|
774093
|
-
return value2;
|
|
774094
|
-
}
|
|
774095
|
-
function compareText(left, right) {
|
|
774096
|
-
return left < right ? -1 : left > right ? 1 : 0;
|
|
774097
|
-
}
|
|
774098
|
-
function compareBlocksForRender(left, right) {
|
|
774099
|
-
return left.order - right.order || right.priority - left.priority || compareText(left.semanticId, right.semanticId);
|
|
774100
|
-
}
|
|
774101
|
-
function compareRecordsForRender(left, right) {
|
|
774102
|
-
return left.blockOrder - right.blockOrder || right.blockPriority - left.blockPriority || compareText(left.semanticId, right.semanticId) || left.recordOrder - right.recordOrder || right.recordPriority - left.recordPriority || compareText(left.recordId, right.recordId);
|
|
774103
|
-
}
|
|
774104
|
-
function compareRecordsForAdmission(left, right) {
|
|
774105
|
-
return right.blockPriority - left.blockPriority || right.recordPriority - left.recordPriority || left.blockOrder - right.blockOrder || left.recordOrder - right.recordOrder || compareText(left.semanticId, right.semanticId) || compareText(left.recordId, right.recordId);
|
|
774106
|
-
}
|
|
774107
|
-
function canonicalBlock(block) {
|
|
774108
|
-
const records = [...block.records].map((record) => ({
|
|
774109
|
-
recordId: record.recordId,
|
|
774110
|
-
content: record.content,
|
|
774111
|
-
order: record.order ?? 0,
|
|
774112
|
-
priority: record.priority ?? 0
|
|
774113
|
-
})).sort(
|
|
774114
|
-
(left, right) => left.order - right.order || right.priority - left.priority || compareText(left.recordId, right.recordId)
|
|
774115
|
-
);
|
|
774116
|
-
return JSON.stringify({
|
|
774117
|
-
semanticId: block.semanticId,
|
|
774118
|
-
revision: block.revision,
|
|
774119
|
-
stability: block.stability,
|
|
774120
|
-
order: block.order ?? 0,
|
|
774121
|
-
priority: block.priority ?? 0,
|
|
774122
|
-
records
|
|
774123
|
-
});
|
|
774124
|
-
}
|
|
774125
|
-
function normalizeBlock(block) {
|
|
774126
|
-
assertId(block.semanticId, "semanticId");
|
|
774127
|
-
const revision = normalizedInteger(block.revision, 0, "revision");
|
|
774128
|
-
if (revision < 0) {
|
|
774129
|
-
throw new TelegramContextPacketValidationError(
|
|
774130
|
-
"revision must be non-negative"
|
|
774131
|
-
);
|
|
774132
|
-
}
|
|
774133
|
-
if (block.stability !== "stable" && block.stability !== "dynamic") {
|
|
774134
|
-
throw new TelegramContextPacketValidationError(
|
|
774135
|
-
"stability must be stable or dynamic"
|
|
774136
|
-
);
|
|
774137
|
-
}
|
|
774138
|
-
const order = normalizedInteger(block.order, 0, "block order");
|
|
774139
|
-
const priority = normalizedInteger(block.priority, 0, "block priority");
|
|
774140
|
-
const recordIds = /* @__PURE__ */ new Set();
|
|
774141
|
-
const records = block.records.map((record) => {
|
|
774142
|
-
assertId(record.recordId, "recordId");
|
|
774143
|
-
if (recordIds.has(record.recordId)) {
|
|
774144
|
-
throw new TelegramContextPacketValidationError(
|
|
774145
|
-
`Duplicate recordId=${JSON.stringify(record.recordId)} in semanticId=${JSON.stringify(block.semanticId)}`
|
|
774146
|
-
);
|
|
774147
|
-
}
|
|
774148
|
-
recordIds.add(record.recordId);
|
|
774149
|
-
if (typeof record.content !== "string") {
|
|
774150
|
-
throw new TelegramContextPacketValidationError(
|
|
774151
|
-
`content for recordId=${JSON.stringify(record.recordId)} must be a string`
|
|
774152
|
-
);
|
|
774153
|
-
}
|
|
774154
|
-
return {
|
|
774155
|
-
semanticId: block.semanticId,
|
|
774156
|
-
revision,
|
|
774157
|
-
stability: block.stability,
|
|
774158
|
-
blockOrder: order,
|
|
774159
|
-
blockPriority: priority,
|
|
774160
|
-
recordId: record.recordId,
|
|
774161
|
-
content: record.content,
|
|
774162
|
-
recordOrder: normalizedInteger(record.order, 0, "record order"),
|
|
774163
|
-
recordPriority: normalizedInteger(record.priority, 0, "record priority")
|
|
774164
|
-
};
|
|
774165
|
-
});
|
|
774166
|
-
records.sort(compareRecordsForRender);
|
|
774167
|
-
return {
|
|
774168
|
-
semanticId: block.semanticId,
|
|
774169
|
-
revision,
|
|
774170
|
-
stability: block.stability,
|
|
774171
|
-
order,
|
|
774172
|
-
priority,
|
|
774173
|
-
records
|
|
774174
|
-
};
|
|
774175
|
-
}
|
|
774176
|
-
function selectBlockRevisions(blocks) {
|
|
774177
|
-
const selected = /* @__PURE__ */ new Map();
|
|
774178
|
-
for (const block of blocks) {
|
|
774179
|
-
const normalized4 = normalizeBlock(block);
|
|
774180
|
-
const source = {
|
|
774181
|
-
semanticId: normalized4.semanticId,
|
|
774182
|
-
revision: normalized4.revision,
|
|
774183
|
-
stability: normalized4.stability,
|
|
774184
|
-
order: normalized4.order,
|
|
774185
|
-
priority: normalized4.priority,
|
|
774186
|
-
records: normalized4.records.map((record) => ({
|
|
774187
|
-
recordId: record.recordId,
|
|
774188
|
-
content: record.content,
|
|
774189
|
-
order: record.recordOrder,
|
|
774190
|
-
priority: record.recordPriority
|
|
774191
|
-
}))
|
|
774192
|
-
};
|
|
774193
|
-
const canonical3 = canonicalBlock(source);
|
|
774194
|
-
const current = selected.get(source.semanticId);
|
|
774195
|
-
if (!current || source.revision > current.source.revision) {
|
|
774196
|
-
selected.set(source.semanticId, { source, canonical: canonical3 });
|
|
774197
|
-
continue;
|
|
774198
|
-
}
|
|
774199
|
-
if (source.revision < current.source.revision) continue;
|
|
774200
|
-
if (canonical3 !== current.canonical) {
|
|
774201
|
-
throw new TelegramContextPacketRevisionConflictError(
|
|
774202
|
-
source.semanticId,
|
|
774203
|
-
source.revision
|
|
774204
|
-
);
|
|
774205
|
-
}
|
|
774206
|
-
}
|
|
774207
|
-
return [...selected.values()].map(({ source }) => normalizeBlock(source)).sort(compareBlocksForRender);
|
|
774208
|
-
}
|
|
774209
|
-
function segmentHeader(segment) {
|
|
774210
|
-
return JSON.stringify({
|
|
774211
|
-
type: "telegram_context_packet_v2",
|
|
774212
|
-
schemaVersion: TELEGRAM_CONTEXT_PACKET_SCHEMA_VERSION,
|
|
774213
|
-
segment
|
|
774214
|
-
});
|
|
774215
|
-
}
|
|
774216
|
-
function segmentFooter(segment) {
|
|
774217
|
-
return JSON.stringify({
|
|
774218
|
-
type: "telegram_context_packet_end_v2",
|
|
774219
|
-
schemaVersion: TELEGRAM_CONTEXT_PACKET_SCHEMA_VERSION,
|
|
774220
|
-
segment
|
|
774221
|
-
});
|
|
774222
|
-
}
|
|
774223
|
-
function serializeRecord(record) {
|
|
774224
|
-
return JSON.stringify({
|
|
774225
|
-
type: "telegram_context_record_v2",
|
|
774226
|
-
schemaVersion: TELEGRAM_CONTEXT_PACKET_SCHEMA_VERSION,
|
|
774227
|
-
semanticId: record.semanticId,
|
|
774228
|
-
revision: record.revision,
|
|
774229
|
-
recordId: record.recordId,
|
|
774230
|
-
content: record.content
|
|
774231
|
-
});
|
|
774232
|
-
}
|
|
774233
|
-
function omittedRecordRef(record) {
|
|
774234
|
-
return {
|
|
774235
|
-
semanticId: record.semanticId,
|
|
774236
|
-
revision: record.revision,
|
|
774237
|
-
recordId: record.recordId
|
|
774238
|
-
};
|
|
774239
|
-
}
|
|
774240
|
-
function buildOmissionReceipt(segment, omitted) {
|
|
774241
|
-
if (omitted.length === 0) return void 0;
|
|
774242
|
-
const omittedRecords = [...omitted].sort(compareRecordsForRender).map(omittedRecordRef);
|
|
774243
|
-
const omittedSemanticIds = [
|
|
774244
|
-
...new Set(omittedRecords.map((record) => record.semanticId))
|
|
774245
|
-
].sort(compareText);
|
|
774246
|
-
return {
|
|
774247
|
-
type: "telegram_context_omission_receipt_v2",
|
|
774248
|
-
schemaVersion: TELEGRAM_CONTEXT_PACKET_SCHEMA_VERSION,
|
|
774249
|
-
segment,
|
|
774250
|
-
reason: "char_budget",
|
|
774251
|
-
omittedBlockCount: omittedSemanticIds.length,
|
|
774252
|
-
omittedRecordCount: omittedRecords.length,
|
|
774253
|
-
omittedDigest: createHash70("sha256").update(JSON.stringify(omittedRecords)).digest("hex"),
|
|
774254
|
-
omittedSemanticIds,
|
|
774255
|
-
omittedRecords
|
|
774256
|
-
};
|
|
774257
|
-
}
|
|
774258
|
-
function serializeOmissionReceipt(receipt2) {
|
|
774259
|
-
return JSON.stringify({
|
|
774260
|
-
type: receipt2.type,
|
|
774261
|
-
schemaVersion: receipt2.schemaVersion,
|
|
774262
|
-
segment: receipt2.segment,
|
|
774263
|
-
reason: receipt2.reason,
|
|
774264
|
-
omittedBlockCount: receipt2.omittedBlockCount,
|
|
774265
|
-
omittedRecordCount: receipt2.omittedRecordCount,
|
|
774266
|
-
omittedDigest: receipt2.omittedDigest
|
|
774267
|
-
});
|
|
774268
|
-
}
|
|
774269
|
-
function renderSegmentText(segment, included, omitted) {
|
|
774270
|
-
const receipt2 = buildOmissionReceipt(segment, omitted);
|
|
774271
|
-
const lines = [
|
|
774272
|
-
segmentHeader(segment),
|
|
774273
|
-
...[...included].sort(compareRecordsForRender).map(serializeRecord),
|
|
774274
|
-
...receipt2 ? [serializeOmissionReceipt(receipt2)] : [],
|
|
774275
|
-
segmentFooter(segment)
|
|
774276
|
-
];
|
|
774277
|
-
return {
|
|
774278
|
-
text: lines.join("\n"),
|
|
774279
|
-
...receipt2 ? { receipt: receipt2 } : {}
|
|
774280
|
-
};
|
|
774281
|
-
}
|
|
774282
|
-
function compileSegment(segment, blocks, budgetChars) {
|
|
774283
|
-
const records = blocks.flatMap((block) => block.records);
|
|
774284
|
-
const admissionOrder = [...records].sort(compareRecordsForAdmission);
|
|
774285
|
-
const included = /* @__PURE__ */ new Set();
|
|
774286
|
-
const empty2 = renderSegmentText(segment, [], admissionOrder);
|
|
774287
|
-
if (empty2.text.length > budgetChars) {
|
|
774288
|
-
throw new TelegramContextPacketBudgetError(
|
|
774289
|
-
segment,
|
|
774290
|
-
budgetChars,
|
|
774291
|
-
empty2.text.length
|
|
774292
|
-
);
|
|
774293
|
-
}
|
|
774294
|
-
for (const candidate of admissionOrder) {
|
|
774295
|
-
const tentativeIncluded = [...included, candidate];
|
|
774296
|
-
const tentativeOmitted = admissionOrder.filter(
|
|
774297
|
-
(record) => !included.has(record) && record !== candidate
|
|
774298
|
-
);
|
|
774299
|
-
const tentative = renderSegmentText(
|
|
774300
|
-
segment,
|
|
774301
|
-
tentativeIncluded,
|
|
774302
|
-
tentativeOmitted
|
|
774303
|
-
);
|
|
774304
|
-
if (tentative.text.length <= budgetChars) included.add(candidate);
|
|
774305
|
-
}
|
|
774306
|
-
const includedRecords = records.filter((record) => included.has(record));
|
|
774307
|
-
const omittedRecords = records.filter((record) => !included.has(record));
|
|
774308
|
-
const rendered = renderSegmentText(segment, includedRecords, omittedRecords);
|
|
774309
|
-
const compiledBlocks = blocks.flatMap((block) => {
|
|
774310
|
-
const admitted = block.records.filter((record) => included.has(record));
|
|
774311
|
-
if (admitted.length === 0) return [];
|
|
774312
|
-
return [
|
|
774313
|
-
{
|
|
774314
|
-
semanticId: block.semanticId,
|
|
774315
|
-
revision: block.revision,
|
|
774316
|
-
stability: block.stability,
|
|
774317
|
-
order: block.order,
|
|
774318
|
-
priority: block.priority,
|
|
774319
|
-
records: admitted.sort(compareRecordsForRender).map((record) => ({
|
|
774320
|
-
semanticId: record.semanticId,
|
|
774321
|
-
revision: record.revision,
|
|
774322
|
-
recordId: record.recordId,
|
|
774323
|
-
content: record.content,
|
|
774324
|
-
order: record.recordOrder,
|
|
774325
|
-
priority: record.recordPriority,
|
|
774326
|
-
serializedChars: serializeRecord(record).length
|
|
774327
|
-
}))
|
|
774328
|
-
}
|
|
774329
|
-
];
|
|
774330
|
-
});
|
|
774331
|
-
return {
|
|
774332
|
-
segment,
|
|
774333
|
-
text: rendered.text,
|
|
774334
|
-
charLength: rendered.text.length,
|
|
774335
|
-
budgetChars,
|
|
774336
|
-
blocks: compiledBlocks,
|
|
774337
|
-
...rendered.receipt ? { omissionReceipt: rendered.receipt } : {}
|
|
774338
|
-
};
|
|
774339
|
-
}
|
|
774340
|
-
function compileTelegramContextPacketV2(input) {
|
|
774341
|
-
const stableChars = normalizedBudget(
|
|
774342
|
-
input.budgets.stableChars,
|
|
774343
|
-
"stableChars"
|
|
774344
|
-
);
|
|
774345
|
-
const dynamicChars = normalizedBudget(
|
|
774346
|
-
input.budgets.dynamicChars,
|
|
774347
|
-
"dynamicChars"
|
|
774348
|
-
);
|
|
774349
|
-
const selected = selectBlockRevisions(input.blocks);
|
|
774350
|
-
const stable2 = compileSegment(
|
|
774351
|
-
"stable",
|
|
774352
|
-
selected.filter((block) => block.stability === "stable"),
|
|
774353
|
-
stableChars
|
|
774354
|
-
);
|
|
774355
|
-
const dynamic = compileSegment(
|
|
774356
|
-
"dynamic",
|
|
774357
|
-
selected.filter((block) => block.stability === "dynamic"),
|
|
774358
|
-
dynamicChars
|
|
774359
|
-
);
|
|
774360
|
-
const selectedRevisions = Object.fromEntries(
|
|
774361
|
-
[...selected].sort((left, right) => compareText(left.semanticId, right.semanticId)).map((block) => [block.semanticId, block.revision])
|
|
774362
|
-
);
|
|
774363
|
-
const combinedContext = `${stable2.text}
|
|
774364
|
-
${dynamic.text}`;
|
|
774365
|
-
return {
|
|
774366
|
-
schemaVersion: TELEGRAM_CONTEXT_PACKET_SCHEMA_VERSION,
|
|
774367
|
-
stablePrefix: stable2.text,
|
|
774368
|
-
stablePrefixHash: createHash70("sha256").update(stable2.text).digest("hex"),
|
|
774369
|
-
dynamicContext: dynamic.text,
|
|
774370
|
-
combinedContext,
|
|
774371
|
-
selectedRevisions,
|
|
774372
|
-
stable: stable2,
|
|
774373
|
-
dynamic
|
|
774374
|
-
};
|
|
774375
|
-
}
|
|
774376
|
-
var TELEGRAM_CONTEXT_PACKET_SCHEMA_VERSION, TelegramContextPacketValidationError, TelegramContextPacketRevisionConflictError, TelegramContextPacketBudgetError, ID_PATTERN;
|
|
774377
|
-
var init_telegram_context_packet_v2 = __esm({
|
|
774378
|
-
"packages/cli/src/tui/telegram-context-packet-v2.ts"() {
|
|
774379
|
-
TELEGRAM_CONTEXT_PACKET_SCHEMA_VERSION = 2;
|
|
774380
|
-
TelegramContextPacketValidationError = class extends Error {
|
|
774381
|
-
constructor(message2) {
|
|
774382
|
-
super(message2);
|
|
774383
|
-
this.name = "TelegramContextPacketValidationError";
|
|
774384
|
-
}
|
|
774385
|
-
};
|
|
774386
|
-
TelegramContextPacketRevisionConflictError = class extends Error {
|
|
774387
|
-
constructor(semanticId, revision) {
|
|
774388
|
-
super(
|
|
774389
|
-
`Conflicting Telegram context blocks use semanticId=${JSON.stringify(semanticId)} revision=${revision}`
|
|
774390
|
-
);
|
|
774391
|
-
this.name = "TelegramContextPacketRevisionConflictError";
|
|
774392
|
-
}
|
|
774393
|
-
};
|
|
774394
|
-
TelegramContextPacketBudgetError = class extends Error {
|
|
774395
|
-
segment;
|
|
774396
|
-
budgetChars;
|
|
774397
|
-
requiredChars;
|
|
774398
|
-
constructor(segment, budgetChars, requiredChars) {
|
|
774399
|
-
super(
|
|
774400
|
-
`Telegram ${segment} context budget ${budgetChars} cannot fit the mandatory packet envelope and omission receipt (${requiredChars} chars required)`
|
|
774401
|
-
);
|
|
774402
|
-
this.name = "TelegramContextPacketBudgetError";
|
|
774403
|
-
this.segment = segment;
|
|
774404
|
-
this.budgetChars = budgetChars;
|
|
774405
|
-
this.requiredChars = requiredChars;
|
|
774406
|
-
}
|
|
774407
|
-
};
|
|
774408
|
-
ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
|
|
774409
|
-
}
|
|
774410
|
-
});
|
|
774411
|
-
|
|
774412
|
-
// packages/cli/src/tui/telegram-input-ownership.ts
|
|
774413
|
-
function nonEmpty2(value2, label) {
|
|
774414
|
-
if (typeof value2 !== "string" || value2.length === 0) {
|
|
774415
|
-
throw new TypeError(`${label} must be a non-empty string`);
|
|
774416
|
-
}
|
|
774417
|
-
return value2;
|
|
774418
|
-
}
|
|
774419
|
-
function finiteInteger(value2, label) {
|
|
774420
|
-
if (!Number.isSafeInteger(value2)) {
|
|
774421
|
-
throw new TypeError(`${label} must be a safe integer`);
|
|
774422
|
-
}
|
|
774423
|
-
return value2;
|
|
774424
|
-
}
|
|
774425
|
-
function timestamp(value2) {
|
|
774426
|
-
if (!Number.isFinite(value2) || value2 < 0) {
|
|
774427
|
-
throw new TypeError("atMs must be a non-negative finite number");
|
|
774428
|
-
}
|
|
774429
|
-
return value2;
|
|
774430
|
-
}
|
|
774431
|
-
function createTelegramInputTargetBinding(target) {
|
|
774432
|
-
return Object.freeze({
|
|
774433
|
-
inputId: nonEmpty2(target.inputId, "inputId"),
|
|
774434
|
-
sessionKey: nonEmpty2(target.sessionKey, "sessionKey"),
|
|
774435
|
-
chatId: nonEmpty2(target.chatId, "chatId"),
|
|
774436
|
-
messageId: finiteInteger(target.messageId, "messageId"),
|
|
774437
|
-
messageThreadId: finiteInteger(target.messageThreadId, "messageThreadId"),
|
|
774438
|
-
senderActorKey: nonEmpty2(target.senderActorKey, "senderActorKey")
|
|
774439
|
-
});
|
|
774440
|
-
}
|
|
774441
|
-
function telegramInputTargetsEqual(left, right) {
|
|
774442
|
-
return left.inputId === right.inputId && left.sessionKey === right.sessionKey && left.chatId === right.chatId && left.messageId === right.messageId && left.messageThreadId === right.messageThreadId && left.senderActorKey === right.senderActorKey;
|
|
774443
|
-
}
|
|
774444
|
-
function isTelegramInputTerminalLifecycle(state5) {
|
|
774445
|
-
return TERMINAL_STATES.has(state5);
|
|
774446
|
-
}
|
|
774447
|
-
function freezeOwner(owner) {
|
|
774448
|
-
const generation = finiteInteger(owner.generation, "owner.generation");
|
|
774449
|
-
if (generation < 0) {
|
|
774450
|
-
throw new TypeError("owner.generation must be non-negative");
|
|
774451
|
-
}
|
|
774452
|
-
return Object.freeze({
|
|
774453
|
-
ownerId: nonEmpty2(owner.ownerId, "owner.ownerId"),
|
|
774454
|
-
generation
|
|
774455
|
-
});
|
|
774456
|
-
}
|
|
774457
|
-
function ownersEqual(left, right) {
|
|
774458
|
-
return left.ownerId === right.ownerId && left.generation === right.generation;
|
|
774459
|
-
}
|
|
774460
|
-
function freezeEvent(state5, atMs, owner) {
|
|
774461
|
-
return Object.freeze({ state: state5, atMs: timestamp(atMs), owner });
|
|
774462
|
-
}
|
|
774463
|
-
function freezeRecord(record) {
|
|
774464
|
-
return Object.freeze({
|
|
774465
|
-
...record,
|
|
774466
|
-
history: Object.freeze([...record.history])
|
|
774467
|
-
});
|
|
774468
|
-
}
|
|
774469
|
-
function decisionsEqual(left, right) {
|
|
774470
|
-
return left.decisionId === right.decisionId && left.contractFingerprint === right.contractFingerprint && left.contractVersion === right.contractVersion && left.disposition === right.disposition;
|
|
774471
|
-
}
|
|
774472
|
-
function deliveriesEqual(left, right) {
|
|
774473
|
-
return left.deliveryId === right.deliveryId && left.decisionId === right.decisionId && left.kind === right.kind && left.transportReceiptId === right.transportReceiptId;
|
|
774474
|
-
}
|
|
774475
|
-
var TERMINAL_STATES, ALLOWED_TRANSITIONS, TelegramInputOwnershipLedger;
|
|
774476
|
-
var init_telegram_input_ownership = __esm({
|
|
774477
|
-
"packages/cli/src/tui/telegram-input-ownership.ts"() {
|
|
774478
|
-
TERMINAL_STATES = /* @__PURE__ */ new Set([
|
|
774479
|
-
"consumed",
|
|
774480
|
-
"superseded",
|
|
774481
|
-
"failed"
|
|
774482
|
-
]);
|
|
774483
|
-
ALLOWED_TRANSITIONS = {
|
|
774484
|
-
received: /* @__PURE__ */ new Set([
|
|
774485
|
-
"classified",
|
|
774486
|
-
"queued",
|
|
774487
|
-
"dispatched",
|
|
774488
|
-
"decision_committed",
|
|
774489
|
-
"superseded",
|
|
774490
|
-
"failed"
|
|
774491
|
-
]),
|
|
774492
|
-
classified: /* @__PURE__ */ new Set([
|
|
774493
|
-
"queued",
|
|
774494
|
-
"dispatched",
|
|
774495
|
-
"decision_committed",
|
|
774496
|
-
"superseded",
|
|
774497
|
-
"failed"
|
|
774498
|
-
]),
|
|
774499
|
-
queued: /* @__PURE__ */ new Set([
|
|
774500
|
-
"dispatched",
|
|
774501
|
-
"deferred",
|
|
774502
|
-
"decision_committed",
|
|
774503
|
-
"superseded",
|
|
774504
|
-
"failed"
|
|
774505
|
-
]),
|
|
774506
|
-
dispatched: /* @__PURE__ */ new Set([
|
|
774507
|
-
"deferred",
|
|
774508
|
-
"decision_committed",
|
|
774509
|
-
"superseded",
|
|
774510
|
-
"failed"
|
|
774511
|
-
]),
|
|
774512
|
-
deferred: /* @__PURE__ */ new Set([
|
|
774513
|
-
"queued",
|
|
774514
|
-
"dispatched",
|
|
774515
|
-
"decision_committed",
|
|
774516
|
-
"superseded",
|
|
774517
|
-
"failed"
|
|
774518
|
-
]),
|
|
774519
|
-
decision_committed: /* @__PURE__ */ new Set([
|
|
774520
|
-
"deferred",
|
|
774521
|
-
"queued",
|
|
774522
|
-
"dispatched",
|
|
774523
|
-
"delivery_committed",
|
|
774524
|
-
"consumed",
|
|
774525
|
-
"superseded",
|
|
774526
|
-
"failed"
|
|
774527
|
-
]),
|
|
774528
|
-
delivery_committed: /* @__PURE__ */ new Set(["consumed"]),
|
|
774529
|
-
consumed: /* @__PURE__ */ new Set(),
|
|
774530
|
-
superseded: /* @__PURE__ */ new Set(),
|
|
774531
|
-
failed: /* @__PURE__ */ new Set()
|
|
774532
|
-
};
|
|
774533
|
-
TelegramInputOwnershipLedger = class {
|
|
774534
|
-
records = /* @__PURE__ */ new Map();
|
|
774535
|
-
get(inputId) {
|
|
774536
|
-
return this.records.get(inputId);
|
|
774537
|
-
}
|
|
774538
|
-
register(targetInput, ownerInput, atMs = Date.now()) {
|
|
774539
|
-
const target = createTelegramInputTargetBinding(targetInput);
|
|
774540
|
-
const owner = freezeOwner(ownerInput);
|
|
774541
|
-
const existing = this.records.get(target.inputId);
|
|
774542
|
-
if (existing) {
|
|
774543
|
-
if (telegramInputTargetsEqual(existing.target, target)) {
|
|
774544
|
-
return { status: "duplicate", record: existing };
|
|
774545
|
-
}
|
|
774546
|
-
return {
|
|
774547
|
-
status: "contradiction",
|
|
774548
|
-
record: existing,
|
|
774549
|
-
reason: "inputId is already bound to a different immutable target"
|
|
774550
|
-
};
|
|
774551
|
-
}
|
|
774552
|
-
const record = freezeRecord({
|
|
774553
|
-
target,
|
|
774554
|
-
owner,
|
|
774555
|
-
lifecycle: "received",
|
|
774556
|
-
revision: 0,
|
|
774557
|
-
history: Object.freeze([freezeEvent("received", atMs, owner)])
|
|
774558
|
-
});
|
|
774559
|
-
this.records.set(target.inputId, record);
|
|
774560
|
-
return { status: "applied", record };
|
|
774561
|
-
}
|
|
774562
|
-
claim(targetInput, ownerInput) {
|
|
774563
|
-
const bound = this.boundRecord(targetInput);
|
|
774564
|
-
if (bound.status !== "applied") return bound;
|
|
774565
|
-
const record = bound.record;
|
|
774566
|
-
const owner = freezeOwner(ownerInput);
|
|
774567
|
-
if (ownersEqual(record.owner, owner)) {
|
|
774568
|
-
return { status: "duplicate", record };
|
|
774569
|
-
}
|
|
774570
|
-
if (isTelegramInputTerminalLifecycle(record.lifecycle)) {
|
|
774571
|
-
return {
|
|
774572
|
-
status: "terminal",
|
|
774573
|
-
record,
|
|
774574
|
-
reason: "terminal input ownership cannot be transferred"
|
|
774575
|
-
};
|
|
774576
|
-
}
|
|
774577
|
-
if (owner.generation < record.owner.generation) {
|
|
774578
|
-
return {
|
|
774579
|
-
status: "stale",
|
|
774580
|
-
record,
|
|
774581
|
-
reason: "owner generation is older than the authoritative claim"
|
|
774582
|
-
};
|
|
774583
|
-
}
|
|
774584
|
-
if (owner.generation === record.owner.generation) {
|
|
774585
|
-
return {
|
|
774586
|
-
status: "contradiction",
|
|
774587
|
-
record,
|
|
774588
|
-
reason: "one owner generation cannot name two owners"
|
|
774589
|
-
};
|
|
774590
|
-
}
|
|
774591
|
-
const next = freezeRecord({
|
|
774592
|
-
...record,
|
|
774593
|
-
owner,
|
|
774594
|
-
revision: record.revision + 1
|
|
774595
|
-
});
|
|
774596
|
-
this.records.set(targetInput.inputId, next);
|
|
774597
|
-
return { status: "applied", record: next };
|
|
774598
|
-
}
|
|
774599
|
-
transition(targetInput, ownerInput, nextState, atMs = Date.now()) {
|
|
774600
|
-
const authorized = this.authorizedRecord(targetInput, ownerInput);
|
|
774601
|
-
if (authorized.status !== "applied") return authorized;
|
|
774602
|
-
const record = authorized.record;
|
|
774603
|
-
if (record.lifecycle === nextState) {
|
|
774604
|
-
return { status: "duplicate", record };
|
|
774605
|
-
}
|
|
774606
|
-
if (isTelegramInputTerminalLifecycle(record.lifecycle)) {
|
|
774607
|
-
return {
|
|
774608
|
-
status: "terminal",
|
|
774609
|
-
record,
|
|
774610
|
-
reason: "terminal input lifecycle cannot advance"
|
|
774611
|
-
};
|
|
774612
|
-
}
|
|
774613
|
-
if (!ALLOWED_TRANSITIONS[record.lifecycle].has(nextState)) {
|
|
774614
|
-
return {
|
|
774615
|
-
status: "invalid_transition",
|
|
774616
|
-
record,
|
|
774617
|
-
reason: `${record.lifecycle} cannot transition to ${nextState}`
|
|
774618
|
-
};
|
|
774619
|
-
}
|
|
774620
|
-
return this.storeLifecycle(record, nextState, atMs);
|
|
774621
|
-
}
|
|
774622
|
-
commitDecision(targetInput, ownerInput, decisionInput, atMs = Date.now()) {
|
|
774623
|
-
const bound = this.boundRecord(targetInput);
|
|
774624
|
-
if (bound.status !== "applied") return bound;
|
|
774625
|
-
const record = bound.record;
|
|
774626
|
-
const decision2 = {
|
|
774627
|
-
decisionId: nonEmpty2(decisionInput.decisionId, "decisionId"),
|
|
774628
|
-
contractFingerprint: nonEmpty2(
|
|
774629
|
-
decisionInput.contractFingerprint,
|
|
774630
|
-
"contractFingerprint"
|
|
774631
|
-
),
|
|
774632
|
-
contractVersion: decisionInput.contractVersion,
|
|
774633
|
-
disposition: decisionInput.disposition
|
|
774634
|
-
};
|
|
774635
|
-
if (decision2.contractVersion !== 2) {
|
|
774636
|
-
return {
|
|
774637
|
-
status: "invalid_transition",
|
|
774638
|
-
record,
|
|
774639
|
-
reason: "only Telegram turn contract version 2 can be committed"
|
|
774640
|
-
};
|
|
774641
|
-
}
|
|
774642
|
-
if (record.decision) {
|
|
774643
|
-
return decisionsEqual(record.decision, decision2) ? { status: "duplicate", record } : {
|
|
774644
|
-
status: "contradiction",
|
|
774645
|
-
record,
|
|
774646
|
-
reason: "an input can have only one committed decision"
|
|
774647
|
-
};
|
|
774648
|
-
}
|
|
774649
|
-
const authorized = this.authorizedRecord(targetInput, ownerInput);
|
|
774650
|
-
if (authorized.status !== "applied") return authorized;
|
|
774651
|
-
if (isTelegramInputTerminalLifecycle(record.lifecycle)) {
|
|
774652
|
-
return {
|
|
774653
|
-
status: "terminal",
|
|
774654
|
-
record,
|
|
774655
|
-
reason: "a terminal input cannot accept a decision"
|
|
774656
|
-
};
|
|
774657
|
-
}
|
|
774658
|
-
if (!ALLOWED_TRANSITIONS[record.lifecycle].has("decision_committed")) {
|
|
774659
|
-
return {
|
|
774660
|
-
status: "invalid_transition",
|
|
774661
|
-
record,
|
|
774662
|
-
reason: `${record.lifecycle} cannot commit a decision`
|
|
774663
|
-
};
|
|
774664
|
-
}
|
|
774665
|
-
const committed = Object.freeze({
|
|
774666
|
-
...decision2,
|
|
774667
|
-
committedBy: record.owner,
|
|
774668
|
-
committedAtMs: timestamp(atMs)
|
|
774669
|
-
});
|
|
774670
|
-
const next = freezeRecord({
|
|
774671
|
-
...record,
|
|
774672
|
-
decision: committed,
|
|
774673
|
-
lifecycle: "decision_committed",
|
|
774674
|
-
revision: record.revision + 1,
|
|
774675
|
-
history: [
|
|
774676
|
-
...record.history,
|
|
774677
|
-
freezeEvent("decision_committed", atMs, record.owner)
|
|
774678
|
-
]
|
|
774679
|
-
});
|
|
774680
|
-
this.records.set(record.target.inputId, next);
|
|
774681
|
-
return { status: "applied", record: next };
|
|
774682
|
-
}
|
|
774683
|
-
commitDelivery(targetInput, ownerInput, deliveryInput, atMs = Date.now()) {
|
|
774684
|
-
const bound = this.boundRecord(targetInput);
|
|
774685
|
-
if (bound.status !== "applied") return bound;
|
|
774686
|
-
const record = bound.record;
|
|
774687
|
-
const delivery = {
|
|
774688
|
-
deliveryId: nonEmpty2(deliveryInput.deliveryId, "deliveryId"),
|
|
774689
|
-
decisionId: nonEmpty2(deliveryInput.decisionId, "decisionId"),
|
|
774690
|
-
kind: deliveryInput.kind,
|
|
774691
|
-
transportReceiptId: nonEmpty2(
|
|
774692
|
-
deliveryInput.transportReceiptId,
|
|
774693
|
-
"transportReceiptId"
|
|
774694
|
-
)
|
|
774695
|
-
};
|
|
774696
|
-
if (record.delivery) {
|
|
774697
|
-
return deliveriesEqual(record.delivery, delivery) ? { status: "duplicate", record } : {
|
|
774698
|
-
status: "contradiction",
|
|
774699
|
-
record,
|
|
774700
|
-
reason: "an input can have only one committed delivery"
|
|
774701
|
-
};
|
|
774702
|
-
}
|
|
774703
|
-
const authorized = this.authorizedRecord(targetInput, ownerInput);
|
|
774704
|
-
if (authorized.status !== "applied") return authorized;
|
|
774705
|
-
if (isTelegramInputTerminalLifecycle(record.lifecycle)) {
|
|
774706
|
-
return {
|
|
774707
|
-
status: "terminal",
|
|
774708
|
-
record,
|
|
774709
|
-
reason: "a terminal input cannot accept a delivery"
|
|
774710
|
-
};
|
|
774711
|
-
}
|
|
774712
|
-
if (!record.decision || record.decision.decisionId !== delivery.decisionId) {
|
|
774713
|
-
return {
|
|
774714
|
-
status: "invalid_transition",
|
|
774715
|
-
record,
|
|
774716
|
-
reason: "delivery must cite the committed decision"
|
|
774717
|
-
};
|
|
774718
|
-
}
|
|
774719
|
-
if (record.decision.disposition === "no_reply") {
|
|
774720
|
-
return {
|
|
774721
|
-
status: "invalid_transition",
|
|
774722
|
-
record,
|
|
774723
|
-
reason: "a no_reply decision cannot have a delivery"
|
|
774724
|
-
};
|
|
774725
|
-
}
|
|
774726
|
-
if (record.decision.disposition === "chat_reply" && delivery.kind !== "visible_reply" || record.decision.disposition === "action" && delivery.kind !== "action_effect") {
|
|
774727
|
-
return {
|
|
774728
|
-
status: "contradiction",
|
|
774729
|
-
record,
|
|
774730
|
-
reason: "delivery kind contradicts the committed disposition"
|
|
774731
|
-
};
|
|
774732
|
-
}
|
|
774733
|
-
const committed = Object.freeze({
|
|
774734
|
-
...delivery,
|
|
774735
|
-
committedBy: record.owner,
|
|
774736
|
-
committedAtMs: timestamp(atMs)
|
|
774737
|
-
});
|
|
774738
|
-
const next = freezeRecord({
|
|
774739
|
-
...record,
|
|
774740
|
-
delivery: committed,
|
|
774741
|
-
lifecycle: "delivery_committed",
|
|
774742
|
-
revision: record.revision + 1,
|
|
774743
|
-
history: [
|
|
774744
|
-
...record.history,
|
|
774745
|
-
freezeEvent("delivery_committed", atMs, record.owner)
|
|
774746
|
-
]
|
|
774747
|
-
});
|
|
774748
|
-
this.records.set(record.target.inputId, next);
|
|
774749
|
-
return { status: "applied", record: next };
|
|
774750
|
-
}
|
|
774751
|
-
complete(targetInput, ownerInput, terminal, atMs = Date.now()) {
|
|
774752
|
-
const bound = this.boundRecord(targetInput);
|
|
774753
|
-
if (bound.status !== "applied") return bound;
|
|
774754
|
-
const record = bound.record;
|
|
774755
|
-
if (record.terminal) {
|
|
774756
|
-
return record.terminal === terminal ? { status: "duplicate", record } : {
|
|
774757
|
-
status: "contradiction",
|
|
774758
|
-
record,
|
|
774759
|
-
reason: "an input can have only one terminal lifecycle result"
|
|
774760
|
-
};
|
|
774761
|
-
}
|
|
774762
|
-
const authorized = this.authorizedRecord(targetInput, ownerInput);
|
|
774763
|
-
if (authorized.status !== "applied") return authorized;
|
|
774764
|
-
if (terminal === "consumed") {
|
|
774765
|
-
if (!record.decision) {
|
|
774766
|
-
return {
|
|
774767
|
-
status: "invalid_transition",
|
|
774768
|
-
record,
|
|
774769
|
-
reason: "consumed input requires a committed decision"
|
|
774770
|
-
};
|
|
774771
|
-
}
|
|
774772
|
-
if (record.decision.disposition !== "no_reply" && !record.delivery) {
|
|
774773
|
-
return {
|
|
774774
|
-
status: "invalid_transition",
|
|
774775
|
-
record,
|
|
774776
|
-
reason: "reply and action decisions require a delivery receipt"
|
|
774777
|
-
};
|
|
774778
|
-
}
|
|
774779
|
-
}
|
|
774780
|
-
if (!ALLOWED_TRANSITIONS[record.lifecycle].has(terminal)) {
|
|
774781
|
-
return {
|
|
774782
|
-
status: "invalid_transition",
|
|
774783
|
-
record,
|
|
774784
|
-
reason: `${record.lifecycle} cannot transition to ${terminal}`
|
|
774785
|
-
};
|
|
774786
|
-
}
|
|
774787
|
-
return this.storeLifecycle(record, terminal, atMs, terminal);
|
|
774788
|
-
}
|
|
774789
|
-
boundRecord(targetInput) {
|
|
774790
|
-
const existing = this.records.get(targetInput.inputId);
|
|
774791
|
-
if (!existing) {
|
|
774792
|
-
return { status: "unknown_input", reason: "input is not registered" };
|
|
774793
|
-
}
|
|
774794
|
-
let target;
|
|
774795
|
-
try {
|
|
774796
|
-
target = createTelegramInputTargetBinding(targetInput);
|
|
774797
|
-
} catch (error) {
|
|
774798
|
-
return {
|
|
774799
|
-
status: "contradiction",
|
|
774800
|
-
record: existing,
|
|
774801
|
-
reason: error instanceof Error ? error.message : String(error)
|
|
774802
|
-
};
|
|
774803
|
-
}
|
|
774804
|
-
if (!telegramInputTargetsEqual(existing.target, target)) {
|
|
774805
|
-
return {
|
|
774806
|
-
status: "contradiction",
|
|
774807
|
-
record: existing,
|
|
774808
|
-
reason: "operation target contradicts the immutable input binding"
|
|
774809
|
-
};
|
|
774810
|
-
}
|
|
774811
|
-
return { status: "applied", record: existing };
|
|
774812
|
-
}
|
|
774813
|
-
authorizedRecord(targetInput, ownerInput) {
|
|
774814
|
-
const bound = this.boundRecord(targetInput);
|
|
774815
|
-
if (bound.status !== "applied") return bound;
|
|
774816
|
-
const record = bound.record;
|
|
774817
|
-
let owner;
|
|
774818
|
-
try {
|
|
774819
|
-
owner = freezeOwner(ownerInput);
|
|
774820
|
-
} catch (error) {
|
|
774821
|
-
return {
|
|
774822
|
-
status: "contradiction",
|
|
774823
|
-
record,
|
|
774824
|
-
reason: error instanceof Error ? error.message : String(error)
|
|
774825
|
-
};
|
|
774826
|
-
}
|
|
774827
|
-
if (ownersEqual(record.owner, owner)) return bound;
|
|
774828
|
-
if (owner.generation < record.owner.generation) {
|
|
774829
|
-
return {
|
|
774830
|
-
status: "stale",
|
|
774831
|
-
record,
|
|
774832
|
-
reason: "operation belongs to an older owner generation"
|
|
774833
|
-
};
|
|
774834
|
-
}
|
|
774835
|
-
return {
|
|
774836
|
-
status: "contradiction",
|
|
774837
|
-
record,
|
|
774838
|
-
reason: "operation owner does not match the authoritative claim"
|
|
774839
|
-
};
|
|
774840
|
-
}
|
|
774841
|
-
storeLifecycle(record, state5, atMs, terminal) {
|
|
774842
|
-
const next = freezeRecord({
|
|
774843
|
-
...record,
|
|
774844
|
-
lifecycle: state5,
|
|
774845
|
-
terminal,
|
|
774846
|
-
revision: record.revision + 1,
|
|
774847
|
-
history: [...record.history, freezeEvent(state5, atMs, record.owner)]
|
|
774848
|
-
});
|
|
774849
|
-
this.records.set(record.target.inputId, next);
|
|
774850
|
-
return { status: "applied", record: next };
|
|
774851
|
-
}
|
|
774852
|
-
};
|
|
774853
|
-
}
|
|
774854
|
-
});
|
|
774855
|
-
|
|
774856
|
-
// packages/cli/src/tui/telegram-cognition-queue.ts
|
|
774857
|
-
function positiveSafeInteger(value2, field) {
|
|
774858
|
-
if (!Number.isSafeInteger(value2) || value2 <= 0) {
|
|
774859
|
-
throw new TelegramCognitionQueueValidationError(
|
|
774860
|
-
`${field} must be a positive safe integer`
|
|
774861
|
-
);
|
|
774862
|
-
}
|
|
774863
|
-
return value2;
|
|
774864
|
-
}
|
|
774865
|
-
function boundedIdentity(value2, field) {
|
|
774866
|
-
if (typeof value2 !== "string" || value2.length === 0 || value2.length > 300) {
|
|
774867
|
-
throw new TelegramCognitionQueueValidationError(
|
|
774868
|
-
`${field} must contain 1 to 300 characters`
|
|
774869
|
-
);
|
|
774870
|
-
}
|
|
774871
|
-
return value2;
|
|
774872
|
-
}
|
|
774873
|
-
function errorMessage(error) {
|
|
774874
|
-
return error instanceof Error ? error.message : String(error);
|
|
774875
|
-
}
|
|
774876
|
-
function deferredOutcome() {
|
|
774877
|
-
let resolve92;
|
|
774878
|
-
const promise = new Promise((done) => {
|
|
774879
|
-
resolve92 = done;
|
|
774880
|
-
});
|
|
774881
|
-
return { promise, resolve: resolve92 };
|
|
774882
|
-
}
|
|
774883
|
-
var TELEGRAM_COGNITION_AUTHORITY, TelegramCognitionQueueValidationError, JOB_KINDS, TelegramCognitionQueue;
|
|
774884
|
-
var init_telegram_cognition_queue = __esm({
|
|
774885
|
-
"packages/cli/src/tui/telegram-cognition-queue.ts"() {
|
|
774886
|
-
TELEGRAM_COGNITION_AUTHORITY = "internal_cognition_only";
|
|
774887
|
-
TelegramCognitionQueueValidationError = class extends Error {
|
|
774888
|
-
constructor(message2) {
|
|
774889
|
-
super(message2);
|
|
774890
|
-
this.name = "TelegramCognitionQueueValidationError";
|
|
774891
|
-
}
|
|
774892
|
-
};
|
|
774893
|
-
JOB_KINDS = /* @__PURE__ */ new Set([
|
|
774894
|
-
"social_state",
|
|
774895
|
-
"memory",
|
|
774896
|
-
"reflection",
|
|
774897
|
-
"cognition_batch"
|
|
774898
|
-
]);
|
|
774899
|
-
TelegramCognitionQueue = class {
|
|
774900
|
-
maxConcurrentScopes;
|
|
774901
|
-
maxQueuedJobs;
|
|
774902
|
-
defaultTimeBudgetMs;
|
|
774903
|
-
pending = [];
|
|
774904
|
-
running = /* @__PURE__ */ new Map();
|
|
774905
|
-
activeScopes = /* @__PURE__ */ new Set();
|
|
774906
|
-
dedupe = /* @__PURE__ */ new Map();
|
|
774907
|
-
jobsById = /* @__PURE__ */ new Map();
|
|
774908
|
-
idleWaiters = /* @__PURE__ */ new Set();
|
|
774909
|
-
totals = {
|
|
774910
|
-
accepted: 0,
|
|
774911
|
-
deduplicated: 0,
|
|
774912
|
-
rejectedCapacity: 0,
|
|
774913
|
-
rejectedClosed: 0,
|
|
774914
|
-
started: 0,
|
|
774915
|
-
succeeded: 0,
|
|
774916
|
-
failed: 0,
|
|
774917
|
-
timedOut: 0,
|
|
774918
|
-
cancelled: 0
|
|
774919
|
-
};
|
|
774920
|
-
state = "open";
|
|
774921
|
-
pumpScheduled = false;
|
|
774922
|
-
nextJobSequence = 1;
|
|
774923
|
-
constructor(options2) {
|
|
774924
|
-
this.maxConcurrentScopes = positiveSafeInteger(
|
|
774925
|
-
options2.maxConcurrentScopes,
|
|
774926
|
-
"maxConcurrentScopes"
|
|
774927
|
-
);
|
|
774928
|
-
this.maxQueuedJobs = positiveSafeInteger(
|
|
774929
|
-
options2.maxQueuedJobs,
|
|
774930
|
-
"maxQueuedJobs"
|
|
774931
|
-
);
|
|
774932
|
-
this.defaultTimeBudgetMs = positiveSafeInteger(
|
|
774933
|
-
options2.defaultTimeBudgetMs,
|
|
774934
|
-
"defaultTimeBudgetMs"
|
|
774935
|
-
);
|
|
774936
|
-
}
|
|
774937
|
-
enqueue(job) {
|
|
774938
|
-
const scopeKey2 = boundedIdentity(job.scopeKey, "scopeKey");
|
|
774939
|
-
const dedupeKey = boundedIdentity(job.dedupeKey, "dedupeKey");
|
|
774940
|
-
if (!JOB_KINDS.has(job.kind)) {
|
|
774941
|
-
throw new TelegramCognitionQueueValidationError(
|
|
774942
|
-
`Unsupported cognition job kind: ${String(job.kind)}`
|
|
774943
|
-
);
|
|
774944
|
-
}
|
|
774945
|
-
if (typeof job.execute !== "function") {
|
|
774946
|
-
throw new TelegramCognitionQueueValidationError(
|
|
774947
|
-
"execute must be a function"
|
|
774948
|
-
);
|
|
774949
|
-
}
|
|
774950
|
-
const timeBudgetMs = positiveSafeInteger(
|
|
774951
|
-
job.timeBudgetMs ?? this.defaultTimeBudgetMs,
|
|
774952
|
-
"timeBudgetMs"
|
|
774953
|
-
);
|
|
774954
|
-
const dedupeIdentity = `${scopeKey2}\0${dedupeKey}`;
|
|
774955
|
-
const existing = this.dedupe.get(dedupeIdentity);
|
|
774956
|
-
if (existing) {
|
|
774957
|
-
this.totals.deduplicated++;
|
|
774958
|
-
return {
|
|
774959
|
-
admission: "deduplicated",
|
|
774960
|
-
jobId: existing.jobId,
|
|
774961
|
-
scopeKey: scopeKey2,
|
|
774962
|
-
dedupeKey,
|
|
774963
|
-
completion: existing.completion
|
|
774964
|
-
};
|
|
774965
|
-
}
|
|
774966
|
-
const jobId = boundedIdentity(
|
|
774967
|
-
job.jobId ?? `tg-cognition-${this.nextJobSequence++}`,
|
|
774968
|
-
"jobId"
|
|
774969
|
-
);
|
|
774970
|
-
if (this.jobsById.has(jobId)) {
|
|
774971
|
-
throw new TelegramCognitionQueueValidationError(
|
|
774972
|
-
`jobId is already active: ${jobId}`
|
|
774973
|
-
);
|
|
774974
|
-
}
|
|
774975
|
-
if (this.state !== "open") {
|
|
774976
|
-
this.totals.rejectedClosed++;
|
|
774977
|
-
return this.rejectedReceipt(
|
|
774978
|
-
"rejected_closed",
|
|
774979
|
-
jobId,
|
|
774980
|
-
scopeKey2,
|
|
774981
|
-
dedupeKey,
|
|
774982
|
-
job.kind,
|
|
774983
|
-
"Telegram cognition queue is closing or closed"
|
|
774984
|
-
);
|
|
774985
|
-
}
|
|
774986
|
-
this.pump();
|
|
774987
|
-
const canStartNow = this.running.size < this.maxConcurrentScopes && !this.activeScopes.has(scopeKey2);
|
|
774988
|
-
if (!canStartNow && this.pending.length >= this.maxQueuedJobs) {
|
|
774989
|
-
this.totals.rejectedCapacity++;
|
|
774990
|
-
return this.rejectedReceipt(
|
|
774991
|
-
"rejected_capacity",
|
|
774992
|
-
jobId,
|
|
774993
|
-
scopeKey2,
|
|
774994
|
-
dedupeKey,
|
|
774995
|
-
job.kind,
|
|
774996
|
-
"Telegram cognition queue capacity reached"
|
|
774997
|
-
);
|
|
774998
|
-
}
|
|
774999
|
-
const completion = deferredOutcome();
|
|
775000
|
-
const accepted = {
|
|
775001
|
-
jobId,
|
|
775002
|
-
scopeKey: scopeKey2,
|
|
775003
|
-
dedupeKey,
|
|
775004
|
-
dedupeIdentity,
|
|
775005
|
-
kind: job.kind,
|
|
775006
|
-
timeBudgetMs,
|
|
775007
|
-
execute: job.execute,
|
|
775008
|
-
enqueuedAtMs: Date.now(),
|
|
775009
|
-
completion: completion.promise,
|
|
775010
|
-
resolve: completion.resolve
|
|
775011
|
-
};
|
|
775012
|
-
this.dedupe.set(dedupeIdentity, accepted);
|
|
775013
|
-
this.jobsById.set(jobId, accepted);
|
|
775014
|
-
this.totals.accepted++;
|
|
775015
|
-
if (canStartNow) this.start(accepted);
|
|
775016
|
-
else this.pending.push(accepted);
|
|
775017
|
-
return {
|
|
775018
|
-
admission: "accepted",
|
|
775019
|
-
jobId,
|
|
775020
|
-
scopeKey: scopeKey2,
|
|
775021
|
-
dedupeKey,
|
|
775022
|
-
completion: completion.promise
|
|
775023
|
-
};
|
|
775024
|
-
}
|
|
775025
|
-
cancel(jobId, reason = "cancelled") {
|
|
775026
|
-
const job = this.jobsById.get(jobId);
|
|
775027
|
-
if (!job) return false;
|
|
775028
|
-
const pendingIndex = this.pending.indexOf(job);
|
|
775029
|
-
if (pendingIndex >= 0) {
|
|
775030
|
-
this.pending.splice(pendingIndex, 1);
|
|
775031
|
-
this.finish(job, "cancelled", reason);
|
|
775032
|
-
return true;
|
|
775033
|
-
}
|
|
775034
|
-
if (job.controller && !job.controller.signal.aborted) {
|
|
775035
|
-
job.forcedStatus = "cancelled";
|
|
775036
|
-
job.forcedReason = reason;
|
|
775037
|
-
job.controller.abort(new Error(reason));
|
|
775038
|
-
return true;
|
|
775039
|
-
}
|
|
775040
|
-
return false;
|
|
775041
|
-
}
|
|
775042
|
-
cancelScope(scopeKey2, reason = "scope cancelled") {
|
|
775043
|
-
let cancelled = 0;
|
|
775044
|
-
for (const job of [...this.pending, ...this.running.values()]) {
|
|
775045
|
-
if (job.scopeKey === scopeKey2 && this.cancel(job.jobId, reason)) {
|
|
775046
|
-
cancelled++;
|
|
775047
|
-
}
|
|
775048
|
-
}
|
|
775049
|
-
return cancelled;
|
|
775050
|
-
}
|
|
775051
|
-
snapshot() {
|
|
775052
|
-
const now2 = Date.now();
|
|
775053
|
-
const queuedByScope = {};
|
|
775054
|
-
for (const job of this.pending) {
|
|
775055
|
-
queuedByScope[job.scopeKey] = (queuedByScope[job.scopeKey] ?? 0) + 1;
|
|
775056
|
-
}
|
|
775057
|
-
const oldest = this.pending.reduce(
|
|
775058
|
-
(value2, job) => Math.min(value2, job.enqueuedAtMs),
|
|
775059
|
-
Number.POSITIVE_INFINITY
|
|
775060
|
-
);
|
|
775061
|
-
return {
|
|
775062
|
-
state: this.state,
|
|
775063
|
-
maxConcurrentScopes: this.maxConcurrentScopes,
|
|
775064
|
-
maxQueuedJobs: this.maxQueuedJobs,
|
|
775065
|
-
defaultTimeBudgetMs: this.defaultTimeBudgetMs,
|
|
775066
|
-
queuedJobs: this.pending.length,
|
|
775067
|
-
runningJobs: this.running.size,
|
|
775068
|
-
activeScopes: [...this.activeScopes].sort(),
|
|
775069
|
-
queuedByScope: Object.fromEntries(
|
|
775070
|
-
Object.entries(queuedByScope).sort(
|
|
775071
|
-
([left], [right]) => left < right ? -1 : left > right ? 1 : 0
|
|
775072
|
-
)
|
|
775073
|
-
),
|
|
775074
|
-
oldestQueuedAgeMs: Number.isFinite(oldest) ? Math.max(0, now2 - oldest) : 0,
|
|
775075
|
-
totals: { ...this.totals }
|
|
775076
|
-
};
|
|
775077
|
-
}
|
|
775078
|
-
waitForIdle() {
|
|
775079
|
-
if (this.pending.length === 0 && this.running.size === 0) {
|
|
775080
|
-
return Promise.resolve();
|
|
775081
|
-
}
|
|
775082
|
-
return new Promise((resolve92) => {
|
|
775083
|
-
this.idleWaiters.add(resolve92);
|
|
775084
|
-
});
|
|
775085
|
-
}
|
|
775086
|
-
async close(options2 = {}) {
|
|
775087
|
-
if (this.state === "closed") return;
|
|
775088
|
-
this.state = "closing";
|
|
775089
|
-
const reason = options2.reason ?? "queue closed";
|
|
775090
|
-
if (options2.cancelQueued) {
|
|
775091
|
-
for (const job of [...this.pending]) this.cancel(job.jobId, reason);
|
|
775092
|
-
}
|
|
775093
|
-
if (options2.cancelRunning) {
|
|
775094
|
-
for (const job of [...this.running.values()]) {
|
|
775095
|
-
this.cancel(job.jobId, reason);
|
|
775096
|
-
}
|
|
775097
|
-
}
|
|
775098
|
-
this.schedulePump();
|
|
775099
|
-
await this.waitForIdle();
|
|
775100
|
-
this.state = "closed";
|
|
775101
|
-
}
|
|
775102
|
-
rejectedReceipt(status, jobId, scopeKey2, dedupeKey, kind, error) {
|
|
775103
|
-
const now2 = Date.now();
|
|
775104
|
-
return {
|
|
775105
|
-
admission: status,
|
|
775106
|
-
jobId,
|
|
775107
|
-
scopeKey: scopeKey2,
|
|
775108
|
-
dedupeKey,
|
|
775109
|
-
completion: Promise.resolve({
|
|
775110
|
-
jobId,
|
|
775111
|
-
scopeKey: scopeKey2,
|
|
775112
|
-
dedupeKey,
|
|
775113
|
-
kind,
|
|
775114
|
-
status,
|
|
775115
|
-
enqueuedAtMs: now2,
|
|
775116
|
-
finishedAtMs: now2,
|
|
775117
|
-
errorMessage: error
|
|
775118
|
-
})
|
|
775119
|
-
};
|
|
775120
|
-
}
|
|
775121
|
-
schedulePump() {
|
|
775122
|
-
if (this.pumpScheduled) return;
|
|
775123
|
-
this.pumpScheduled = true;
|
|
775124
|
-
queueMicrotask(() => {
|
|
775125
|
-
this.pumpScheduled = false;
|
|
775126
|
-
this.pump();
|
|
775127
|
-
});
|
|
775128
|
-
}
|
|
775129
|
-
pump() {
|
|
775130
|
-
while (this.running.size < this.maxConcurrentScopes) {
|
|
775131
|
-
const nextIndex = this.pending.findIndex(
|
|
775132
|
-
(job2) => !this.activeScopes.has(job2.scopeKey)
|
|
775133
|
-
);
|
|
775134
|
-
if (nextIndex < 0) break;
|
|
775135
|
-
const [job] = this.pending.splice(nextIndex, 1);
|
|
775136
|
-
if (!job) break;
|
|
775137
|
-
this.start(job);
|
|
775138
|
-
}
|
|
775139
|
-
this.maybeResolveIdle();
|
|
775140
|
-
}
|
|
775141
|
-
start(job) {
|
|
775142
|
-
job.startedAtMs = Date.now();
|
|
775143
|
-
job.controller = new AbortController();
|
|
775144
|
-
this.running.set(job.jobId, job);
|
|
775145
|
-
this.activeScopes.add(job.scopeKey);
|
|
775146
|
-
this.totals.started++;
|
|
775147
|
-
const deadlineAtMs = job.startedAtMs + job.timeBudgetMs;
|
|
775148
|
-
const timer = setTimeout(() => {
|
|
775149
|
-
if (!job.controller || job.controller.signal.aborted) return;
|
|
775150
|
-
job.forcedStatus = "timed_out";
|
|
775151
|
-
job.forcedReason = `time budget exceeded after ${job.timeBudgetMs}ms`;
|
|
775152
|
-
job.controller.abort(new Error(job.forcedReason));
|
|
775153
|
-
}, job.timeBudgetMs);
|
|
775154
|
-
if (typeof timer.unref === "function") {
|
|
775155
|
-
timer.unref();
|
|
775156
|
-
}
|
|
775157
|
-
const abortOutcome = new Promise((resolve92) => {
|
|
775158
|
-
job.controller.signal.addEventListener(
|
|
775159
|
-
"abort",
|
|
775160
|
-
() => resolve92("aborted"),
|
|
775161
|
-
{
|
|
775162
|
-
once: true
|
|
775163
|
-
}
|
|
775164
|
-
);
|
|
775165
|
-
});
|
|
775166
|
-
const execution = Promise.resolve().then(
|
|
775167
|
-
() => job.execute({
|
|
775168
|
-
authority: TELEGRAM_COGNITION_AUTHORITY,
|
|
775169
|
-
jobId: job.jobId,
|
|
775170
|
-
scopeKey: job.scopeKey,
|
|
775171
|
-
kind: job.kind,
|
|
775172
|
-
signal: job.controller.signal,
|
|
775173
|
-
deadlineAtMs
|
|
775174
|
-
})
|
|
775175
|
-
).then(
|
|
775176
|
-
() => ({ type: "succeeded" }),
|
|
775177
|
-
(error) => ({ type: "failed", error })
|
|
775178
|
-
);
|
|
775179
|
-
void Promise.race([
|
|
775180
|
-
execution,
|
|
775181
|
-
abortOutcome.then(() => ({ type: "aborted" }))
|
|
775182
|
-
]).then((result) => {
|
|
775183
|
-
clearTimeout(timer);
|
|
775184
|
-
if (result.type === "aborted") {
|
|
775185
|
-
this.finish(
|
|
775186
|
-
job,
|
|
775187
|
-
job.forcedStatus ?? "cancelled",
|
|
775188
|
-
job.forcedReason ?? "cancelled"
|
|
775189
|
-
);
|
|
775190
|
-
} else if (result.type === "failed") {
|
|
775191
|
-
this.finish(job, "failed", errorMessage(result.error));
|
|
775192
|
-
} else {
|
|
775193
|
-
this.finish(job, "succeeded");
|
|
775194
|
-
}
|
|
775195
|
-
}).catch((error) => {
|
|
775196
|
-
clearTimeout(timer);
|
|
775197
|
-
this.finish(job, "failed", errorMessage(error));
|
|
775198
|
-
});
|
|
775199
|
-
void execution.then(() => void 0);
|
|
775200
|
-
}
|
|
775201
|
-
finish(job, status, error) {
|
|
775202
|
-
if (!this.jobsById.has(job.jobId)) return;
|
|
775203
|
-
this.running.delete(job.jobId);
|
|
775204
|
-
this.activeScopes.delete(job.scopeKey);
|
|
775205
|
-
this.jobsById.delete(job.jobId);
|
|
775206
|
-
if (this.dedupe.get(job.dedupeIdentity) === job) {
|
|
775207
|
-
this.dedupe.delete(job.dedupeIdentity);
|
|
775208
|
-
}
|
|
775209
|
-
this.totals[status === "timed_out" ? "timedOut" : status]++;
|
|
775210
|
-
const finishedAtMs = Date.now();
|
|
775211
|
-
const startedAtMs = job.startedAtMs;
|
|
775212
|
-
job.resolve({
|
|
775213
|
-
jobId: job.jobId,
|
|
775214
|
-
scopeKey: job.scopeKey,
|
|
775215
|
-
dedupeKey: job.dedupeKey,
|
|
775216
|
-
kind: job.kind,
|
|
775217
|
-
status,
|
|
775218
|
-
enqueuedAtMs: job.enqueuedAtMs,
|
|
775219
|
-
...startedAtMs !== void 0 ? {
|
|
775220
|
-
startedAtMs,
|
|
775221
|
-
queueWaitMs: Math.max(0, startedAtMs - job.enqueuedAtMs),
|
|
775222
|
-
runDurationMs: Math.max(0, finishedAtMs - startedAtMs)
|
|
775223
|
-
} : {},
|
|
775224
|
-
finishedAtMs,
|
|
775225
|
-
...error ? { errorMessage: error } : {}
|
|
775226
|
-
});
|
|
775227
|
-
this.schedulePump();
|
|
775228
|
-
}
|
|
775229
|
-
maybeResolveIdle() {
|
|
775230
|
-
if (this.pending.length > 0 || this.running.size > 0) return;
|
|
775231
|
-
for (const resolve92 of this.idleWaiters) resolve92();
|
|
775232
|
-
this.idleWaiters.clear();
|
|
775233
|
-
if (this.state === "closing") this.state = "closed";
|
|
775234
|
-
}
|
|
775235
|
-
};
|
|
775236
|
-
}
|
|
775237
|
-
});
|
|
775238
|
-
|
|
775239
|
-
// packages/cli/src/tui/telegram-action-session-registry.ts
|
|
775240
|
-
function nonEmpty3(value2, label) {
|
|
775241
|
-
if (typeof value2 !== "string" || value2.length === 0) {
|
|
775242
|
-
throw new TypeError(`${label} must be a non-empty string`);
|
|
775243
|
-
}
|
|
775244
|
-
return value2;
|
|
775245
|
-
}
|
|
775246
|
-
function positiveInteger3(value2, label) {
|
|
775247
|
-
if (!Number.isSafeInteger(value2) || value2 <= 0) {
|
|
775248
|
-
throw new TypeError(`${label} must be a positive safe integer`);
|
|
775249
|
-
}
|
|
775250
|
-
return value2;
|
|
775251
|
-
}
|
|
775252
|
-
function nonNegativeTime(value2) {
|
|
775253
|
-
if (!Number.isFinite(value2) || value2 < 0) {
|
|
775254
|
-
throw new TypeError(
|
|
775255
|
-
"registry clock must return a non-negative finite number"
|
|
775256
|
-
);
|
|
775257
|
-
}
|
|
775258
|
-
return value2;
|
|
775259
|
-
}
|
|
775260
|
-
function createTelegramActionSessionTarget(target) {
|
|
775261
|
-
return Object.freeze({
|
|
775262
|
-
chatSessionKey: nonEmpty3(target.chatSessionKey, "target.chatSessionKey"),
|
|
775263
|
-
principalKey: nonEmpty3(target.principalKey, "target.principalKey")
|
|
775264
|
-
});
|
|
775265
|
-
}
|
|
775266
|
-
function telegramActionSessionKey(targetInput) {
|
|
775267
|
-
const target = createTelegramActionSessionTarget(targetInput);
|
|
775268
|
-
return JSON.stringify([target.chatSessionKey, target.principalKey]);
|
|
775269
|
-
}
|
|
775270
|
-
var TelegramActionSessionLeaseError, DEFAULT_TTL_MS3, DEFAULT_MAX_ENTRIES, TelegramActionSessionRegistry;
|
|
775271
|
-
var init_telegram_action_session_registry = __esm({
|
|
775272
|
-
"packages/cli/src/tui/telegram-action-session-registry.ts"() {
|
|
775273
|
-
TelegramActionSessionLeaseError = class extends Error {
|
|
775274
|
-
constructor(code8, message2) {
|
|
775275
|
-
super(message2);
|
|
775276
|
-
this.code = code8;
|
|
775277
|
-
this.name = "TelegramActionSessionLeaseError";
|
|
775278
|
-
}
|
|
775279
|
-
code;
|
|
775280
|
-
};
|
|
775281
|
-
DEFAULT_TTL_MS3 = 15 * 6e4;
|
|
775282
|
-
DEFAULT_MAX_ENTRIES = 32;
|
|
775283
|
-
TelegramActionSessionRegistry = class {
|
|
775284
|
-
entries = /* @__PURE__ */ new Map();
|
|
775285
|
-
create;
|
|
775286
|
-
ttlMs;
|
|
775287
|
-
maxEntries;
|
|
775288
|
-
now;
|
|
775289
|
-
onEvict;
|
|
775290
|
-
generationSequence = 0;
|
|
775291
|
-
leaseSequence = 0;
|
|
775292
|
-
closed = false;
|
|
775293
|
-
constructor(options2) {
|
|
775294
|
-
this.create = options2.create;
|
|
775295
|
-
this.ttlMs = positiveInteger3(options2.ttlMs ?? DEFAULT_TTL_MS3, "ttlMs");
|
|
775296
|
-
this.maxEntries = positiveInteger3(
|
|
775297
|
-
options2.maxEntries ?? DEFAULT_MAX_ENTRIES,
|
|
775298
|
-
"maxEntries"
|
|
775299
|
-
);
|
|
775300
|
-
this.now = options2.now ?? Date.now;
|
|
775301
|
-
this.onEvict = options2.onEvict;
|
|
775302
|
-
}
|
|
775303
|
-
get size() {
|
|
775304
|
-
return this.entries.size;
|
|
775305
|
-
}
|
|
775306
|
-
acquire(options2) {
|
|
775307
|
-
if (this.closed) {
|
|
775308
|
-
return {
|
|
775309
|
-
status: "closed",
|
|
775310
|
-
reason: "Telegram action session registry is closed"
|
|
775311
|
-
};
|
|
775312
|
-
}
|
|
775313
|
-
const now2 = this.readNow();
|
|
775314
|
-
this.pruneExpiredAt(now2);
|
|
775315
|
-
const target = createTelegramActionSessionTarget(options2.target);
|
|
775316
|
-
const key = telegramActionSessionKey(target);
|
|
775317
|
-
const ownerId = nonEmpty3(options2.ownerId, "ownerId");
|
|
775318
|
-
const compatibilityKey = nonEmpty3(
|
|
775319
|
-
options2.compatibilityKey,
|
|
775320
|
-
"compatibilityKey"
|
|
775321
|
-
);
|
|
775322
|
-
let entry = this.entries.get(key);
|
|
775323
|
-
if (entry && entry.compatibilityKey !== compatibilityKey) {
|
|
775324
|
-
if (entry.lease) {
|
|
775325
|
-
return {
|
|
775326
|
-
status: "busy",
|
|
775327
|
-
reason: "active session has incompatible runner configuration",
|
|
775328
|
-
current: this.snapshotEntry(entry)
|
|
775329
|
-
};
|
|
775330
|
-
}
|
|
775331
|
-
this.evictEntry(entry, "incompatible");
|
|
775332
|
-
entry = void 0;
|
|
775333
|
-
}
|
|
775334
|
-
if (!entry) {
|
|
775335
|
-
while (this.entries.size >= this.maxEntries) {
|
|
775336
|
-
const evicted = this.evictLeastRecentlyUsedIdle();
|
|
775337
|
-
if (!evicted) {
|
|
775338
|
-
return {
|
|
775339
|
-
status: "capacity",
|
|
775340
|
-
reason: "all bounded Telegram action sessions are active"
|
|
775341
|
-
};
|
|
775342
|
-
}
|
|
775343
|
-
}
|
|
775344
|
-
entry = this.createEntry(target, key, compatibilityKey, now2);
|
|
775345
|
-
this.entries.set(key, entry);
|
|
775346
|
-
}
|
|
775347
|
-
if (entry.lease) {
|
|
775348
|
-
return {
|
|
775349
|
-
status: "busy",
|
|
775350
|
-
reason: "Telegram action session already has an active lease",
|
|
775351
|
-
current: this.snapshotEntry(entry)
|
|
775352
|
-
};
|
|
775353
|
-
}
|
|
775354
|
-
const token = Object.freeze({
|
|
775355
|
-
key,
|
|
775356
|
-
generation: entry.generation,
|
|
775357
|
-
leaseId: ++this.leaseSequence,
|
|
775358
|
-
ownerId
|
|
775359
|
-
});
|
|
775360
|
-
entry.lease = {
|
|
775361
|
-
token,
|
|
775362
|
-
onEvent: options2.onEvent,
|
|
775363
|
-
onTypedEvent: options2.onTypedEvent,
|
|
775364
|
-
runStarted: false
|
|
775365
|
-
};
|
|
775366
|
-
entry.lastUsedAtMs = now2;
|
|
775367
|
-
const lease = Object.freeze({
|
|
775368
|
-
token,
|
|
775369
|
-
target: entry.target,
|
|
775370
|
-
run: (input) => this.runLease(token, input),
|
|
775371
|
-
abort: () => this.abortLease(token),
|
|
775372
|
-
release: () => this.releaseLease(token)
|
|
775373
|
-
});
|
|
775374
|
-
return { status: "acquired", lease };
|
|
775375
|
-
}
|
|
775376
|
-
pruneExpired() {
|
|
775377
|
-
return this.pruneExpiredAt(this.readNow());
|
|
775378
|
-
}
|
|
775379
|
-
snapshot() {
|
|
775380
|
-
return Object.freeze(
|
|
775381
|
-
[...this.entries.values()].sort(
|
|
775382
|
-
(left, right) => left.lastUsedAtMs - right.lastUsedAtMs || left.generation - right.generation
|
|
775383
|
-
).map((entry) => this.snapshotEntry(entry))
|
|
775384
|
-
);
|
|
775385
|
-
}
|
|
775386
|
-
/** Abort active work, dispose every cached resource, and reject new leases. */
|
|
775387
|
-
shutdown() {
|
|
775388
|
-
if (this.closed) return;
|
|
775389
|
-
this.closed = true;
|
|
775390
|
-
for (const entry of [...this.entries.values()]) {
|
|
775391
|
-
this.evictEntry(entry, "shutdown");
|
|
775392
|
-
}
|
|
775393
|
-
}
|
|
775394
|
-
createEntry(target, key, compatibilityKey, now2) {
|
|
775395
|
-
const generation = ++this.generationSequence;
|
|
775396
|
-
let entry;
|
|
775397
|
-
const resource = this.create(
|
|
775398
|
-
Object.freeze({
|
|
775399
|
-
key,
|
|
775400
|
-
target,
|
|
775401
|
-
generation,
|
|
775402
|
-
onTypedEvent: (event) => {
|
|
775403
|
-
if (entry) this.dispatchTypedEvent(entry, event);
|
|
775404
|
-
}
|
|
775405
|
-
})
|
|
775406
|
-
);
|
|
775407
|
-
if (!resource || !resource.runner) {
|
|
775408
|
-
throw new TypeError("Telegram action session factory returned no runner");
|
|
775409
|
-
}
|
|
775410
|
-
entry = {
|
|
775411
|
-
key,
|
|
775412
|
-
target,
|
|
775413
|
-
generation,
|
|
775414
|
-
compatibilityKey,
|
|
775415
|
-
runner: resource.runner,
|
|
775416
|
-
dispose: resource.dispose,
|
|
775417
|
-
createdAtMs: now2,
|
|
775418
|
-
lastUsedAtMs: now2,
|
|
775419
|
-
lease: null,
|
|
775420
|
-
disposed: false
|
|
775421
|
-
};
|
|
775422
|
-
resource.runner.onEvent((event) => {
|
|
775423
|
-
if (entry) this.dispatchEvent(entry, event);
|
|
775424
|
-
});
|
|
775425
|
-
return entry;
|
|
775426
|
-
}
|
|
775427
|
-
async runLease(token, input) {
|
|
775428
|
-
const owned = this.ownedEntry(token);
|
|
775429
|
-
if (!owned) {
|
|
775430
|
-
throw new TelegramActionSessionLeaseError(
|
|
775431
|
-
"stale_lease",
|
|
775432
|
-
"Telegram action session lease is no longer authoritative"
|
|
775433
|
-
);
|
|
775434
|
-
}
|
|
775435
|
-
if (owned.lease.runStarted) {
|
|
775436
|
-
throw new TelegramActionSessionLeaseError(
|
|
775437
|
-
"already_started",
|
|
775438
|
-
"Telegram action session lease can run only once"
|
|
775439
|
-
);
|
|
775440
|
-
}
|
|
775441
|
-
owned.lease.runStarted = true;
|
|
775442
|
-
try {
|
|
775443
|
-
await input.prepare?.(owned.entry.runner);
|
|
775444
|
-
return await owned.entry.runner.run(
|
|
775445
|
-
input.task,
|
|
775446
|
-
input.context,
|
|
775447
|
-
input.actualUserGoal
|
|
775448
|
-
);
|
|
775449
|
-
} finally {
|
|
775450
|
-
this.finishLease(token);
|
|
775451
|
-
}
|
|
775452
|
-
}
|
|
775453
|
-
abortLease(token) {
|
|
775454
|
-
const owned = this.ownedEntry(token);
|
|
775455
|
-
if (!owned) return false;
|
|
775456
|
-
try {
|
|
775457
|
-
owned.entry.runner.abort();
|
|
775458
|
-
} catch {
|
|
775459
|
-
}
|
|
775460
|
-
return true;
|
|
775461
|
-
}
|
|
775462
|
-
releaseLease(token) {
|
|
775463
|
-
const owned = this.ownedEntry(token);
|
|
775464
|
-
if (!owned) return "stale";
|
|
775465
|
-
if (owned.lease.runStarted) return "running";
|
|
775466
|
-
owned.entry.lease = null;
|
|
775467
|
-
owned.entry.lastUsedAtMs = this.readNow();
|
|
775468
|
-
return "released";
|
|
775469
|
-
}
|
|
775470
|
-
finishLease(token) {
|
|
775471
|
-
const owned = this.ownedEntry(token);
|
|
775472
|
-
if (!owned) return;
|
|
775473
|
-
owned.entry.lease = null;
|
|
775474
|
-
owned.entry.lastUsedAtMs = this.readNow();
|
|
775475
|
-
}
|
|
775476
|
-
ownedEntry(token) {
|
|
775477
|
-
const entry = this.entries.get(token.key);
|
|
775478
|
-
if (!entry || entry.generation !== token.generation || !entry.lease || entry.lease.token !== token) {
|
|
775479
|
-
return null;
|
|
775480
|
-
}
|
|
775481
|
-
return { entry, lease: entry.lease };
|
|
775482
|
-
}
|
|
775483
|
-
dispatchEvent(entry, event) {
|
|
775484
|
-
const lease = entry.lease;
|
|
775485
|
-
if (!lease?.runStarted || !lease.onEvent) return;
|
|
775486
|
-
try {
|
|
775487
|
-
lease.onEvent(event, lease.token);
|
|
775488
|
-
} catch {
|
|
775489
|
-
}
|
|
775490
|
-
}
|
|
775491
|
-
dispatchTypedEvent(entry, event) {
|
|
775492
|
-
const lease = entry.lease;
|
|
775493
|
-
if (!lease?.runStarted || !lease.onTypedEvent) return;
|
|
775494
|
-
try {
|
|
775495
|
-
lease.onTypedEvent(event, lease.token);
|
|
775496
|
-
} catch {
|
|
775497
|
-
}
|
|
775498
|
-
}
|
|
775499
|
-
pruneExpiredAt(now2) {
|
|
775500
|
-
let evicted = 0;
|
|
775501
|
-
for (const entry of [...this.entries.values()]) {
|
|
775502
|
-
if (entry.lease || now2 - entry.lastUsedAtMs < this.ttlMs) continue;
|
|
775503
|
-
this.evictEntry(entry, "ttl");
|
|
775504
|
-
evicted++;
|
|
775505
|
-
}
|
|
775506
|
-
return evicted;
|
|
775507
|
-
}
|
|
775508
|
-
evictLeastRecentlyUsedIdle() {
|
|
775509
|
-
const candidate = [...this.entries.values()].filter((entry) => !entry.lease).sort(
|
|
775510
|
-
(left, right) => left.lastUsedAtMs - right.lastUsedAtMs || left.generation - right.generation
|
|
775511
|
-
)[0];
|
|
775512
|
-
if (!candidate) return false;
|
|
775513
|
-
this.evictEntry(candidate, "lru");
|
|
775514
|
-
return true;
|
|
775515
|
-
}
|
|
775516
|
-
evictEntry(entry, reason) {
|
|
775517
|
-
if (entry.disposed) return;
|
|
775518
|
-
entry.disposed = true;
|
|
775519
|
-
const snapshot = this.snapshotEntry(entry);
|
|
775520
|
-
entry.lease = null;
|
|
775521
|
-
this.entries.delete(entry.key);
|
|
775522
|
-
try {
|
|
775523
|
-
entry.runner.abort();
|
|
775524
|
-
} catch {
|
|
775525
|
-
}
|
|
775526
|
-
try {
|
|
775527
|
-
entry.dispose?.();
|
|
775528
|
-
} catch {
|
|
775529
|
-
}
|
|
775530
|
-
try {
|
|
775531
|
-
this.onEvict?.(snapshot, reason);
|
|
775532
|
-
} catch {
|
|
775533
|
-
}
|
|
775534
|
-
}
|
|
775535
|
-
snapshotEntry(entry) {
|
|
775536
|
-
return Object.freeze({
|
|
775537
|
-
key: entry.key,
|
|
775538
|
-
target: entry.target,
|
|
775539
|
-
generation: entry.generation,
|
|
775540
|
-
compatibilityKey: entry.compatibilityKey,
|
|
775541
|
-
createdAtMs: entry.createdAtMs,
|
|
775542
|
-
lastUsedAtMs: entry.lastUsedAtMs,
|
|
775543
|
-
busy: Boolean(entry.lease),
|
|
775544
|
-
ownerId: entry.lease?.token.ownerId,
|
|
775545
|
-
leaseId: entry.lease?.token.leaseId,
|
|
775546
|
-
runStarted: entry.lease?.runStarted ?? false
|
|
775547
|
-
});
|
|
775548
|
-
}
|
|
775549
|
-
readNow() {
|
|
775550
|
-
return nonNegativeTime(this.now());
|
|
775551
|
-
}
|
|
775552
|
-
};
|
|
775553
|
-
}
|
|
775554
|
-
});
|
|
775555
|
-
|
|
775556
|
-
// packages/cli/src/tui/telegram-turn-contract-v2.ts
|
|
775557
|
-
function isRecord2(value2) {
|
|
775558
|
-
return Boolean(value2) && typeof value2 === "object" && !Array.isArray(value2);
|
|
775559
|
-
}
|
|
775560
|
-
function issue2(code8, path16, message2) {
|
|
775561
|
-
return Object.freeze({ code: code8, path: path16, message: message2 });
|
|
775562
|
-
}
|
|
775563
|
-
function collectUnknownFields(value2, allowed, path16, issues) {
|
|
775564
|
-
for (const key of Object.keys(value2)) {
|
|
775565
|
-
if (!allowed.has(key)) {
|
|
775566
|
-
issues.push(
|
|
775567
|
-
issue2(
|
|
775568
|
-
"unknown_field",
|
|
775569
|
-
`${path16}.${key}`,
|
|
775570
|
-
"field is not part of the V2 contract"
|
|
775571
|
-
)
|
|
775572
|
-
);
|
|
775573
|
-
}
|
|
775574
|
-
}
|
|
775575
|
-
}
|
|
775576
|
-
function readString2(value2, path16, issues) {
|
|
775577
|
-
if (typeof value2 !== "string" || value2.trim().length === 0) {
|
|
775578
|
-
issues.push(issue2("invalid_field", path16, "must be a non-empty string"));
|
|
775579
|
-
return null;
|
|
775580
|
-
}
|
|
775581
|
-
return value2;
|
|
775582
|
-
}
|
|
775583
|
-
function readInteger2(value2, path16, issues) {
|
|
775584
|
-
if (!Number.isSafeInteger(value2)) {
|
|
775585
|
-
issues.push(issue2("invalid_field", path16, "must be a safe integer"));
|
|
775586
|
-
return null;
|
|
775587
|
-
}
|
|
775588
|
-
return value2;
|
|
775589
|
-
}
|
|
775590
|
-
function readStringArray(value2, path16, issues) {
|
|
775591
|
-
if (!Array.isArray(value2) || value2.some((item) => typeof item !== "string" || item.length === 0)) {
|
|
775592
|
-
issues.push(
|
|
775593
|
-
issue2("invalid_field", path16, "must be an array of non-empty strings")
|
|
775594
|
-
);
|
|
775595
|
-
return null;
|
|
775596
|
-
}
|
|
775597
|
-
if (new Set(value2).size !== value2.length) {
|
|
775598
|
-
issues.push(
|
|
775599
|
-
issue2("invalid_field", path16, "must not contain duplicate values")
|
|
775600
|
-
);
|
|
775601
|
-
return null;
|
|
775602
|
-
}
|
|
775603
|
-
return Object.freeze([...value2]);
|
|
775604
|
-
}
|
|
775605
|
-
function validateWireTarget(raw, expected, issues) {
|
|
775606
|
-
if (!isRecord2(raw)) {
|
|
775607
|
-
issues.push(issue2("invalid_field", "$.target", "must be an object"));
|
|
775608
|
-
return null;
|
|
775609
|
-
}
|
|
775610
|
-
collectUnknownFields(
|
|
775611
|
-
raw,
|
|
775612
|
-
/* @__PURE__ */ new Set([
|
|
775613
|
-
"input_id",
|
|
775614
|
-
"session_key",
|
|
775615
|
-
"chat_id",
|
|
775616
|
-
"message_id",
|
|
775617
|
-
"message_thread_id",
|
|
775618
|
-
"sender_actor_key"
|
|
775619
|
-
]),
|
|
775620
|
-
"$.target",
|
|
775621
|
-
issues
|
|
775622
|
-
);
|
|
775623
|
-
const inputId = readString2(raw["input_id"], "$.target.input_id", issues);
|
|
775624
|
-
const sessionKey = readString2(
|
|
775625
|
-
raw["session_key"],
|
|
775626
|
-
"$.target.session_key",
|
|
775627
|
-
issues
|
|
775628
|
-
);
|
|
775629
|
-
const chatId = readString2(raw["chat_id"], "$.target.chat_id", issues);
|
|
775630
|
-
const messageId = readInteger2(
|
|
775631
|
-
raw["message_id"],
|
|
775632
|
-
"$.target.message_id",
|
|
775633
|
-
issues
|
|
775634
|
-
);
|
|
775635
|
-
const messageThreadId = readInteger2(
|
|
775636
|
-
raw["message_thread_id"],
|
|
775637
|
-
"$.target.message_thread_id",
|
|
775638
|
-
issues
|
|
775639
|
-
);
|
|
775640
|
-
const senderActorKey = readString2(
|
|
775641
|
-
raw["sender_actor_key"],
|
|
775642
|
-
"$.target.sender_actor_key",
|
|
775643
|
-
issues
|
|
775644
|
-
);
|
|
775645
|
-
if (inputId === null || sessionKey === null || chatId === null || messageId === null || messageThreadId === null || senderActorKey === null) {
|
|
775646
|
-
return null;
|
|
775647
|
-
}
|
|
775648
|
-
const target = createTelegramInputTargetBinding({
|
|
775649
|
-
inputId,
|
|
775650
|
-
sessionKey,
|
|
775651
|
-
chatId,
|
|
775652
|
-
messageId,
|
|
775653
|
-
messageThreadId,
|
|
775654
|
-
senderActorKey
|
|
775655
|
-
});
|
|
775656
|
-
if (!telegramInputTargetsEqual(target, expected)) {
|
|
775657
|
-
issues.push(
|
|
775658
|
-
issue2(
|
|
775659
|
-
"target_mismatch",
|
|
775660
|
-
"$.target",
|
|
775661
|
-
"target does not match the host-owned input binding"
|
|
775662
|
-
)
|
|
775663
|
-
);
|
|
775664
|
-
return null;
|
|
775665
|
-
}
|
|
775666
|
-
return target;
|
|
775667
|
-
}
|
|
775668
|
-
function validateTelegramTurnContractV2(raw, context2) {
|
|
775669
|
-
const issues = [];
|
|
775670
|
-
if (!isRecord2(raw)) {
|
|
775671
|
-
return Object.freeze({
|
|
775672
|
-
ok: false,
|
|
775673
|
-
value: null,
|
|
775674
|
-
issues: Object.freeze([
|
|
775675
|
-
issue2("not_object", "$", "turn must be an object")
|
|
775676
|
-
])
|
|
775677
|
-
});
|
|
775678
|
-
}
|
|
775679
|
-
const rawKind = raw["kind"];
|
|
775680
|
-
const kind = typeof rawKind === "string" && KINDS.has(rawKind) ? rawKind : null;
|
|
775681
|
-
if (raw["version"] !== TELEGRAM_TURN_CONTRACT_V2_VERSION) {
|
|
775682
|
-
issues.push(issue2("invalid_version", "$.version", "version must equal 2"));
|
|
775683
|
-
}
|
|
775684
|
-
if (!kind) {
|
|
775685
|
-
issues.push(
|
|
775686
|
-
issue2(
|
|
775687
|
-
"invalid_kind",
|
|
775688
|
-
"$.kind",
|
|
775689
|
-
"kind must be no_reply, chat_reply, or action"
|
|
775690
|
-
)
|
|
775691
|
-
);
|
|
775692
|
-
}
|
|
775693
|
-
const allowed = new Set(COMMON_WIRE_KEYS);
|
|
775694
|
-
if (kind === "chat_reply") allowed.add("reply");
|
|
775695
|
-
if (kind === "action") allowed.add("objective");
|
|
775696
|
-
collectUnknownFields(raw, allowed, "$", issues);
|
|
775697
|
-
const expectedTarget = createTelegramInputTargetBinding(context2.target);
|
|
775698
|
-
const inputId = readString2(raw["input_id"], "$.input_id", issues);
|
|
775699
|
-
if (inputId !== null && inputId !== expectedTarget.inputId) {
|
|
775700
|
-
issues.push(
|
|
775701
|
-
issue2(
|
|
775702
|
-
"target_mismatch",
|
|
775703
|
-
"$.input_id",
|
|
775704
|
-
"input_id does not match the host target"
|
|
775705
|
-
)
|
|
775706
|
-
);
|
|
775707
|
-
}
|
|
775708
|
-
const target = validateWireTarget(raw["target"], expectedTarget, issues);
|
|
775709
|
-
if (inputId !== null && target && inputId !== target.inputId) {
|
|
775710
|
-
issues.push(
|
|
775711
|
-
issue2(
|
|
775712
|
-
"target_mismatch",
|
|
775713
|
-
"$.input_id",
|
|
775714
|
-
"input_id contradicts target.input_id"
|
|
775715
|
-
)
|
|
775716
|
-
);
|
|
775717
|
-
}
|
|
775718
|
-
const confidence2 = raw["confidence"];
|
|
775719
|
-
if (typeof confidence2 !== "number" || !Number.isFinite(confidence2) || confidence2 < 0 || confidence2 > 1) {
|
|
775720
|
-
issues.push(
|
|
775721
|
-
issue2(
|
|
775722
|
-
"invalid_field",
|
|
775723
|
-
"$.confidence",
|
|
775724
|
-
"confidence must be between 0 and 1"
|
|
775725
|
-
)
|
|
775726
|
-
);
|
|
775727
|
-
}
|
|
775728
|
-
const reason = readString2(raw["reason"], "$.reason", issues);
|
|
775729
|
-
const addressedActorKeys = readStringArray(
|
|
775730
|
-
raw["addressed_actor_keys"],
|
|
775731
|
-
"$.addressed_actor_keys",
|
|
775732
|
-
issues
|
|
775733
|
-
);
|
|
775734
|
-
const evidenceIds = readStringArray(
|
|
775735
|
-
raw["evidence_ids"],
|
|
775736
|
-
"$.evidence_ids",
|
|
775737
|
-
issues
|
|
775738
|
-
);
|
|
775739
|
-
const rawSelfRole = raw["self_role"];
|
|
775740
|
-
const selfRole = typeof rawSelfRole === "string" && SELF_ROLES.has(rawSelfRole) ? rawSelfRole : null;
|
|
775741
|
-
if (!selfRole) {
|
|
775742
|
-
issues.push(issue2("invalid_field", "$.self_role", "self_role is invalid"));
|
|
775743
|
-
}
|
|
775744
|
-
const rawReplyBasis = raw["reply_basis"];
|
|
775745
|
-
const replyBasis = typeof rawReplyBasis === "string" && REPLY_BASES.has(rawReplyBasis) ? rawReplyBasis : null;
|
|
775746
|
-
if (!replyBasis) {
|
|
775747
|
-
issues.push(
|
|
775748
|
-
issue2("invalid_field", "$.reply_basis", "reply_basis is invalid")
|
|
775749
|
-
);
|
|
775750
|
-
}
|
|
775751
|
-
const knownActors = new Set(context2.actorKeys);
|
|
775752
|
-
for (const actorKey of addressedActorKeys ?? []) {
|
|
775753
|
-
if (!knownActors.has(actorKey)) {
|
|
775754
|
-
issues.push(
|
|
775755
|
-
issue2(
|
|
775756
|
-
"unknown_actor_key",
|
|
775757
|
-
"$.addressed_actor_keys",
|
|
775758
|
-
`unknown actor key: ${actorKey}`
|
|
775759
|
-
)
|
|
775760
|
-
);
|
|
775761
|
-
}
|
|
775762
|
-
}
|
|
775763
|
-
const knownEvidence = new Set(context2.evidenceIds);
|
|
775764
|
-
for (const evidenceId of evidenceIds ?? []) {
|
|
775765
|
-
if (!knownEvidence.has(evidenceId)) {
|
|
775766
|
-
issues.push(
|
|
775767
|
-
issue2(
|
|
775768
|
-
"unknown_evidence_id",
|
|
775769
|
-
"$.evidence_ids",
|
|
775770
|
-
`unknown evidence id: ${evidenceId}`
|
|
775771
|
-
)
|
|
775772
|
-
);
|
|
775773
|
-
}
|
|
775774
|
-
}
|
|
775775
|
-
if (kind === "chat_reply" || kind === "action") {
|
|
775776
|
-
if (selfRole === "observer" || selfRole === "uncertain") {
|
|
775777
|
-
issues.push(
|
|
775778
|
-
issue2(
|
|
775779
|
-
"reply_not_authorized",
|
|
775780
|
-
"$.self_role",
|
|
775781
|
-
`${kind} requires an authorized self role`
|
|
775782
|
-
)
|
|
775783
|
-
);
|
|
775784
|
-
}
|
|
775785
|
-
if (replyBasis === "none" || replyBasis === "uncertain") {
|
|
775786
|
-
issues.push(
|
|
775787
|
-
issue2(
|
|
775788
|
-
"reply_not_authorized",
|
|
775789
|
-
"$.reply_basis",
|
|
775790
|
-
`${kind} requires an affirmative reply basis`
|
|
775791
|
-
)
|
|
775792
|
-
);
|
|
775793
|
-
}
|
|
775794
|
-
if ((evidenceIds?.length ?? 0) === 0) {
|
|
775795
|
-
issues.push(
|
|
775796
|
-
issue2(
|
|
775797
|
-
"reply_not_authorized",
|
|
775798
|
-
"$.evidence_ids",
|
|
775799
|
-
`${kind} requires host evidence`
|
|
775800
|
-
)
|
|
775801
|
-
);
|
|
775802
|
-
}
|
|
775803
|
-
}
|
|
775804
|
-
if (context2.selfActorKey && selfRole === "addressee" && addressedActorKeys && !addressedActorKeys.includes(context2.selfActorKey)) {
|
|
775805
|
-
issues.push(
|
|
775806
|
-
issue2(
|
|
775807
|
-
"reply_not_authorized",
|
|
775808
|
-
"$.addressed_actor_keys",
|
|
775809
|
-
"addressee role must include the host self actor"
|
|
775810
|
-
)
|
|
775811
|
-
);
|
|
775812
|
-
}
|
|
775813
|
-
if (context2.selfActorKey && selfRole === "observer" && addressedActorKeys?.includes(context2.selfActorKey)) {
|
|
775814
|
-
issues.push(
|
|
775815
|
-
issue2(
|
|
775816
|
-
"reply_not_authorized",
|
|
775817
|
-
"$.addressed_actor_keys",
|
|
775818
|
-
"observer role contradicts a self addressee"
|
|
775819
|
-
)
|
|
775820
|
-
);
|
|
775821
|
-
}
|
|
775822
|
-
let reply = null;
|
|
775823
|
-
let objective = null;
|
|
775824
|
-
if (kind === "chat_reply") {
|
|
775825
|
-
reply = readString2(raw["reply"], "$.reply", issues);
|
|
775826
|
-
}
|
|
775827
|
-
if (kind === "action") {
|
|
775828
|
-
objective = readString2(raw["objective"], "$.objective", issues);
|
|
775829
|
-
}
|
|
775830
|
-
if (issues.length > 0 || !kind || !target || inputId === null || reason === null || !addressedActorKeys || !selfRole || !replyBasis || !evidenceIds || typeof confidence2 !== "number") {
|
|
775831
|
-
return Object.freeze({
|
|
775832
|
-
ok: false,
|
|
775833
|
-
value: null,
|
|
775834
|
-
issues: Object.freeze([...issues])
|
|
775835
|
-
});
|
|
775836
|
-
}
|
|
775837
|
-
const common = {
|
|
775838
|
-
version: TELEGRAM_TURN_CONTRACT_V2_VERSION,
|
|
775839
|
-
inputId,
|
|
775840
|
-
target,
|
|
775841
|
-
confidence: confidence2,
|
|
775842
|
-
reason,
|
|
775843
|
-
addressedActorKeys,
|
|
775844
|
-
selfRole,
|
|
775845
|
-
replyBasis,
|
|
775846
|
-
evidenceIds
|
|
775847
|
-
};
|
|
775848
|
-
const value2 = kind === "chat_reply" ? Object.freeze({ ...common, kind, reply }) : kind === "action" ? Object.freeze({ ...common, kind, objective }) : Object.freeze({ ...common, kind });
|
|
775849
|
-
return Object.freeze({ ok: true, value: value2, issues: Object.freeze([]) });
|
|
775850
|
-
}
|
|
775851
|
-
function telegramTurnContractV2Fingerprint(contract) {
|
|
775852
|
-
return JSON.stringify({
|
|
775853
|
-
version: contract.version,
|
|
775854
|
-
kind: contract.kind,
|
|
775855
|
-
inputId: contract.inputId,
|
|
775856
|
-
target: contract.target,
|
|
775857
|
-
confidence: contract.confidence,
|
|
775858
|
-
reason: contract.reason,
|
|
775859
|
-
addressedActorKeys: [...contract.addressedActorKeys].sort(),
|
|
775860
|
-
selfRole: contract.selfRole,
|
|
775861
|
-
replyBasis: contract.replyBasis,
|
|
775862
|
-
evidenceIds: [...contract.evidenceIds].sort(),
|
|
775863
|
-
reply: contract.kind === "chat_reply" ? contract.reply : void 0,
|
|
775864
|
-
objective: contract.kind === "action" ? contract.objective : void 0
|
|
775865
|
-
});
|
|
775866
|
-
}
|
|
775867
|
-
var TELEGRAM_TURN_CONTRACT_V2_VERSION, SELF_ROLES, REPLY_BASES, KINDS, COMMON_WIRE_KEYS;
|
|
775868
|
-
var init_telegram_turn_contract_v2 = __esm({
|
|
775869
|
-
"packages/cli/src/tui/telegram-turn-contract-v2.ts"() {
|
|
775870
|
-
init_telegram_input_ownership();
|
|
775871
|
-
TELEGRAM_TURN_CONTRACT_V2_VERSION = 2;
|
|
775872
|
-
SELF_ROLES = /* @__PURE__ */ new Set([
|
|
775873
|
-
"addressee",
|
|
775874
|
-
"participant",
|
|
775875
|
-
"observer",
|
|
775876
|
-
"uncertain"
|
|
775877
|
-
]);
|
|
775878
|
-
REPLY_BASES = /* @__PURE__ */ new Set([
|
|
775879
|
-
"direct_turn",
|
|
775880
|
-
"ongoing_self_task",
|
|
775881
|
-
"social_intervention",
|
|
775882
|
-
"none",
|
|
775883
|
-
"uncertain"
|
|
775884
|
-
]);
|
|
775885
|
-
KINDS = /* @__PURE__ */ new Set([
|
|
775886
|
-
"no_reply",
|
|
775887
|
-
"chat_reply",
|
|
775888
|
-
"action"
|
|
775889
|
-
]);
|
|
775890
|
-
COMMON_WIRE_KEYS = [
|
|
775891
|
-
"version",
|
|
775892
|
-
"kind",
|
|
775893
|
-
"input_id",
|
|
775894
|
-
"target",
|
|
775895
|
-
"confidence",
|
|
775896
|
-
"reason",
|
|
775897
|
-
"addressed_actor_keys",
|
|
775898
|
-
"self_role",
|
|
775899
|
-
"reply_basis",
|
|
775900
|
-
"evidence_ids"
|
|
775901
|
-
];
|
|
775902
|
-
}
|
|
775903
|
-
});
|
|
775904
|
-
|
|
775905
774069
|
// packages/cli/src/tui/telegram-format.ts
|
|
775906
774070
|
function escapeHtml2(text3) {
|
|
775907
774071
|
return String(text3 ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
@@ -777503,7 +775667,7 @@ var init_telegram_command_menu = __esm({
|
|
|
777503
775667
|
});
|
|
777504
775668
|
|
|
777505
775669
|
// packages/cli/src/tui/telegram-public-media.ts
|
|
777506
|
-
import { createHash as
|
|
775670
|
+
import { createHash as createHash70, randomBytes as randomBytes27 } from "node:crypto";
|
|
777507
775671
|
import { lookup as dnsLookup2 } from "node:dns/promises";
|
|
777508
775672
|
import { link, mkdir as mkdir23, unlink as unlink4, writeFile as writeFile27 } from "node:fs/promises";
|
|
777509
775673
|
import { request as httpsRequest2 } from "node:https";
|
|
@@ -778124,7 +776288,7 @@ ${output2}`,
|
|
|
778124
776288
|
responseContentType(response.headers),
|
|
778125
776289
|
kind
|
|
778126
776290
|
);
|
|
778127
|
-
const sha25610 =
|
|
776291
|
+
const sha25610 = createHash70("sha256").update(response.body).digest("hex");
|
|
778128
776292
|
if (this.acquiredFiles >= MAX_ACQUIRED_FILES_PER_RUN) {
|
|
778129
776293
|
throw new Error(
|
|
778130
776294
|
`Rejected media: this run already acquired ${MAX_ACQUIRED_FILES_PER_RUN} files.`
|
|
@@ -779667,7 +777831,7 @@ import {
|
|
|
779667
777831
|
unlinkSync as unlinkSync43
|
|
779668
777832
|
} from "node:fs";
|
|
779669
777833
|
import { join as join184 } from "node:path";
|
|
779670
|
-
import { createHash as
|
|
777834
|
+
import { createHash as createHash71 } from "node:crypto";
|
|
779671
777835
|
function safeFilePart(value2) {
|
|
779672
777836
|
return value2.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 80) || "telegram";
|
|
779673
777837
|
}
|
|
@@ -779675,7 +777839,7 @@ function daydreamRoot(repoRoot) {
|
|
|
779675
777839
|
return join184(repoRoot, ".omnius", "telegram-daydreams");
|
|
779676
777840
|
}
|
|
779677
777841
|
function sessionDir(repoRoot, sessionKey) {
|
|
779678
|
-
const hash2 =
|
|
777842
|
+
const hash2 = createHash71("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
779679
777843
|
return join184(daydreamRoot(repoRoot), safeFilePart(hash2));
|
|
779680
777844
|
}
|
|
779681
777845
|
function compactLine2(value2, max = 220) {
|
|
@@ -779786,7 +777950,7 @@ function buildReplyOpportunities(input, openQuestions) {
|
|
|
779786
777950
|
return opportunities;
|
|
779787
777951
|
}
|
|
779788
777952
|
function daydreamOpportunityId(input, trigger) {
|
|
779789
|
-
return
|
|
777953
|
+
return createHash71("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
|
|
779790
777954
|
}
|
|
779791
777955
|
function clamp0116(value2) {
|
|
779792
777956
|
if (!Number.isFinite(value2)) return 0;
|
|
@@ -780191,7 +778355,7 @@ function buildTelegramChannelDaydream(input, corpus, extraction, extractionCommi
|
|
|
780191
778355
|
const seed = `${input.sessionKey}:${input.generatedAtMs}:${input.history.length}`;
|
|
780192
778356
|
return {
|
|
780193
778357
|
version: 3,
|
|
780194
|
-
id:
|
|
778358
|
+
id: createHash71("sha1").update(seed).digest("hex").slice(0, 16),
|
|
780195
778359
|
sessionKey: input.sessionKey,
|
|
780196
778360
|
chatId: input.chatId,
|
|
780197
778361
|
chatTitle: input.chatTitle,
|
|
@@ -780503,12 +778667,12 @@ var init_telegram_channel_dmn = __esm({
|
|
|
780503
778667
|
});
|
|
780504
778668
|
|
|
780505
778669
|
// packages/cli/src/tui/telegram-reflection-corpus.ts
|
|
780506
|
-
import { createHash as
|
|
778670
|
+
import { createHash as createHash72 } from "node:crypto";
|
|
780507
778671
|
function telegramReflectionMemoryDbPaths(repoRoot) {
|
|
780508
778672
|
return omniusMemoryDbPaths(repoRoot);
|
|
780509
778673
|
}
|
|
780510
778674
|
function stableHash2(value2, length4 = 16) {
|
|
780511
|
-
return
|
|
778675
|
+
return createHash72("sha1").update(value2).digest("hex").slice(0, length4);
|
|
780512
778676
|
}
|
|
780513
778677
|
function clean5(value2) {
|
|
780514
778678
|
return String(value2 ?? "").replace(/\s+/g, " ").trim();
|
|
@@ -781321,7 +779485,7 @@ var init_telegram_reflection_extraction = __esm({
|
|
|
781321
779485
|
});
|
|
781322
779486
|
|
|
781323
779487
|
// packages/cli/src/tui/telegram-social-state-types.ts
|
|
781324
|
-
import { createHash as
|
|
779488
|
+
import { createHash as createHash73 } from "node:crypto";
|
|
781325
779489
|
function telegramSocialActorKey(actor) {
|
|
781326
779490
|
if (!actor) return "unknown";
|
|
781327
779491
|
if (typeof actor.userId === "number") return `user:${actor.userId}`;
|
|
@@ -781357,7 +779521,7 @@ function appendUnique(items, value2, max) {
|
|
|
781357
779521
|
return next.slice(-max);
|
|
781358
779522
|
}
|
|
781359
779523
|
function hashTelegramSocialId(parts) {
|
|
781360
|
-
return
|
|
779524
|
+
return createHash73("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
|
|
781361
779525
|
}
|
|
781362
779526
|
function cleanUsername(value2) {
|
|
781363
779527
|
if (typeof value2 !== "string") return void 0;
|
|
@@ -782612,7 +780776,7 @@ var init_telegram_social_state = __esm({
|
|
|
782612
780776
|
});
|
|
782613
780777
|
|
|
782614
780778
|
// packages/cli/src/tui/telegram-social-event-log.ts
|
|
782615
|
-
import { createHash as
|
|
780779
|
+
import { createHash as createHash74 } from "node:crypto";
|
|
782616
780780
|
import {
|
|
782617
780781
|
appendFileSync as appendFileSync21,
|
|
782618
780782
|
existsSync as existsSync175,
|
|
@@ -782621,7 +780785,7 @@ import {
|
|
|
782621
780785
|
} from "node:fs";
|
|
782622
780786
|
import { join as join185, resolve as resolve82 } from "node:path";
|
|
782623
780787
|
function stableEventId2(type, sessionKey, occurredAt, payload) {
|
|
782624
|
-
return
|
|
780788
|
+
return createHash74("sha256").update(JSON.stringify({ type, sessionKey, occurredAt, payload })).digest("hex").slice(0, 24);
|
|
782625
780789
|
}
|
|
782626
780790
|
function createTelegramSocialEvent(type, payload, recordedAt = Date.now()) {
|
|
782627
780791
|
const sessionKey = String(payload.sessionKey);
|
|
@@ -782637,7 +780801,7 @@ function createTelegramSocialEvent(type, payload, recordedAt = Date.now()) {
|
|
|
782637
780801
|
};
|
|
782638
780802
|
}
|
|
782639
780803
|
function telegramSocialEventLogPath(repoRoot, sessionKey) {
|
|
782640
|
-
const scope =
|
|
780804
|
+
const scope = createHash74("sha256").update(sessionKey).digest("hex").slice(0, 24);
|
|
782641
780805
|
return resolve82(repoRoot, ".omnius", "telegram-social-events", `${scope}.jsonl`);
|
|
782642
780806
|
}
|
|
782643
780807
|
function appendTelegramSocialEvent(repoRoot, event) {
|
|
@@ -782789,7 +780953,7 @@ var init_telegram_vision_router = __esm({
|
|
|
782789
780953
|
});
|
|
782790
780954
|
|
|
782791
780955
|
// packages/cli/src/tui/telegram-api-governor.ts
|
|
782792
|
-
function
|
|
780956
|
+
function positiveInteger3(value2, fallback) {
|
|
782793
780957
|
return Number.isFinite(value2) && value2 > 0 ? Math.max(1, Math.floor(value2)) : fallback;
|
|
782794
780958
|
}
|
|
782795
780959
|
function nonNegativeInteger(value2, fallback) {
|
|
@@ -782896,11 +781060,11 @@ var init_telegram_api_governor = __esm({
|
|
|
782896
781060
|
groupMessageStarts = /* @__PURE__ */ new Map();
|
|
782897
781061
|
nextChatMessageAtMs = /* @__PURE__ */ new Map();
|
|
782898
781062
|
constructor(options2 = {}) {
|
|
782899
|
-
this.globalRequestsPerSecond =
|
|
781063
|
+
this.globalRequestsPerSecond = positiveInteger3(
|
|
782900
781064
|
options2.globalRequestsPerSecond,
|
|
782901
781065
|
28
|
|
782902
781066
|
);
|
|
782903
|
-
this.globalMessagesPerSecond =
|
|
781067
|
+
this.globalMessagesPerSecond = positiveInteger3(
|
|
782904
781068
|
options2.globalMessagesPerSecond,
|
|
782905
781069
|
28
|
|
782906
781070
|
);
|
|
@@ -782908,15 +781072,15 @@ var init_telegram_api_governor = __esm({
|
|
|
782908
781072
|
options2.perChatMessageIntervalMs,
|
|
782909
781073
|
1050
|
|
782910
781074
|
);
|
|
782911
|
-
this.groupMessagesPerMinute =
|
|
781075
|
+
this.groupMessagesPerMinute = positiveInteger3(
|
|
782912
781076
|
options2.groupMessagesPerMinute,
|
|
782913
781077
|
20
|
|
782914
781078
|
);
|
|
782915
|
-
this.maxConcurrentRequests =
|
|
781079
|
+
this.maxConcurrentRequests = positiveInteger3(
|
|
782916
781080
|
options2.maxConcurrentRequests,
|
|
782917
781081
|
8
|
|
782918
781082
|
);
|
|
782919
|
-
this.maxQueuedRequests =
|
|
781083
|
+
this.maxQueuedRequests = positiveInteger3(options2.maxQueuedRequests, 2048);
|
|
782920
781084
|
this.now = options2.now ?? Date.now;
|
|
782921
781085
|
}
|
|
782922
781086
|
run(request) {
|
|
@@ -783492,7 +781656,7 @@ import {
|
|
|
783492
781656
|
mkdir as mkdirAsync,
|
|
783493
781657
|
writeFile as writeFileAsync
|
|
783494
781658
|
} from "node:fs/promises";
|
|
783495
|
-
import { createHash as
|
|
781659
|
+
import { createHash as createHash75, randomBytes as randomBytes29, randomInt } from "node:crypto";
|
|
783496
781660
|
function formatModelBytes(bytes2) {
|
|
783497
781661
|
if (!Number.isFinite(bytes2) || bytes2 <= 0) return "0 B";
|
|
783498
781662
|
const units = ["B", "KB", "MB", "GB", "TB"];
|
|
@@ -783955,8 +782119,6 @@ function parseTelegramInteractionDecision(text3, forcedRoute, options2 = {}) {
|
|
|
783955
782119
|
const reason = String(
|
|
783956
782120
|
parsed["reason"] ?? "live inference decision"
|
|
783957
782121
|
).slice(0, 240);
|
|
783958
|
-
const replyTextRaw = parsed["reply"] ?? parsed["reply_text"];
|
|
783959
|
-
const replyText = typeof replyTextRaw === "string" ? cleanTelegramVisibleReply(replyTextRaw).slice(0, 3900) : void 0;
|
|
783960
782122
|
const inputIdRaw = parsed["input_id"] ?? parsed["inputId"];
|
|
783961
782123
|
const addressedActorKeysRaw = parsed["addressed_actor_keys"] ?? parsed["addressedActorKeys"];
|
|
783962
782124
|
const evidenceIdsRaw = parsed["evidence_ids"] ?? parsed["evidenceIds"];
|
|
@@ -783983,7 +782145,6 @@ function parseTelegramInteractionDecision(text3, forcedRoute, options2 = {}) {
|
|
|
783983
782145
|
shouldReply,
|
|
783984
782146
|
confidence: confidence2,
|
|
783985
782147
|
reason,
|
|
783986
|
-
replyText: replyText || void 0,
|
|
783987
782148
|
inputId: typeof inputIdRaw === "string" ? inputIdRaw : void 0,
|
|
783988
782149
|
addressedActorKeys,
|
|
783989
782150
|
selfRole,
|
|
@@ -784805,7 +782966,7 @@ function buildTelegramRuntimeContext(now2 = /* @__PURE__ */ new Date(), repoRoot
|
|
|
784805
782966
|
return buildConversationRuntimeContext(now2, repoRoot);
|
|
784806
782967
|
}
|
|
784807
782968
|
function telegramSessionIdFromKey(sessionKey) {
|
|
784808
|
-
return `telegram-${
|
|
782969
|
+
return `telegram-${createHash75("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
|
|
784809
782970
|
}
|
|
784810
782971
|
function normalizeTelegramSubAgentLimit(value2) {
|
|
784811
782972
|
const parsed = typeof value2 === "number" ? value2 : typeof value2 === "string" && value2.trim() ? Number(value2.trim()) : TELEGRAM_SUB_AGENT_DEFAULT_LIMIT;
|
|
@@ -786217,11 +784378,6 @@ var TELEGRAM_TOOL_ACTION_GROUPS, TELEGRAM_TOOL_ACTION_GROUP, TELEGRAM_TOOL_MUTAT
|
|
|
786217
784378
|
var init_telegram_bridge = __esm({
|
|
786218
784379
|
"packages/cli/src/tui/telegram-bridge.ts"() {
|
|
786219
784380
|
init_conversation_context();
|
|
786220
|
-
init_telegram_context_packet_v2();
|
|
786221
|
-
init_telegram_input_ownership();
|
|
786222
|
-
init_telegram_cognition_queue();
|
|
786223
|
-
init_telegram_action_session_registry();
|
|
786224
|
-
init_telegram_turn_contract_v2();
|
|
786225
784381
|
init_telegram_format();
|
|
786226
784382
|
init_async_process();
|
|
786227
784383
|
init_dist8();
|
|
@@ -786581,7 +784737,6 @@ Telegram link integrity contract:
|
|
|
786581
784737
|
"should_reply",
|
|
786582
784738
|
"confidence",
|
|
786583
784739
|
"reason",
|
|
786584
|
-
"reply",
|
|
786585
784740
|
"addressed_actor_keys",
|
|
786586
784741
|
"self_role",
|
|
786587
784742
|
"reply_basis",
|
|
@@ -786594,16 +784749,6 @@ Telegram link integrity contract:
|
|
|
786594
784749
|
should_reply: { type: "boolean" },
|
|
786595
784750
|
confidence: { type: "number", minimum: 0, maximum: 1 },
|
|
786596
784751
|
reason: { type: "string" },
|
|
786597
|
-
reply: {
|
|
786598
|
-
anyOf: [
|
|
786599
|
-
{
|
|
786600
|
-
type: "string",
|
|
786601
|
-
maxLength: 3900,
|
|
786602
|
-
description: "Exact Telegram reply text when route=chat and should_reply=true."
|
|
786603
|
-
},
|
|
786604
|
-
{ type: "null" }
|
|
786605
|
-
]
|
|
786606
|
-
},
|
|
786607
784752
|
addressed_actor_keys: {
|
|
786608
784753
|
type: "array",
|
|
786609
784754
|
items: { type: "string" },
|
|
@@ -786697,7 +784842,7 @@ Telegram link integrity contract:
|
|
|
786697
784842
|
TELEGRAM_MODERATION_APPROVAL_TTL_MS = 5 * 6e4;
|
|
786698
784843
|
TELEGRAM_MODERATION_APPROVAL_RETENTION_MS = 24 * 60 * 6e4;
|
|
786699
784844
|
TELEGRAM_MODERATION_APPROVAL_MAX_RECORDS = 64;
|
|
786700
|
-
TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA = `{"input_id":"exact host input_id","route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","
|
|
784845
|
+
TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA = `{"input_id":"exact host input_id","route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","addressed_actor_keys":["only actor keys from evidence packet"],"self_role":"addressee"|"participant"|"observer"|"uncertain","reply_basis":"direct_turn"|"ongoing_self_task"|"social_intervention"|"none"|"uncertain","evidence_ids":["only evidence ids from evidence packet"],"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"}}`;
|
|
786701
784846
|
TELEGRAM_CHAT_REPLY_RESPONSE_FORMAT = {
|
|
786702
784847
|
type: "json_schema",
|
|
786703
784848
|
json_schema: {
|
|
@@ -787063,28 +785208,12 @@ Telegram link integrity contract:
|
|
|
787063
785208
|
telegramModerationApprovalAuditPath;
|
|
787064
785209
|
/** Active sub-agents by chat/guest session key */
|
|
787065
785210
|
subAgents = /* @__PURE__ */ new Map();
|
|
787066
|
-
/** Factories exist only during synchronous session acquisition. */
|
|
787067
|
-
telegramActionSessionBlueprints = /* @__PURE__ */ new Map();
|
|
787068
|
-
/** Reusable, single-owner action runners keyed by chat and principal. */
|
|
787069
|
-
telegramActionSessions = null;
|
|
787070
785211
|
/** Debounced live-context packets for messages arriving during a runner. */
|
|
787071
785212
|
telegramSubAgentContextBuffers = /* @__PURE__ */ new Map();
|
|
787072
785213
|
/** Append-only, durable ingress ledger for every agent-routed Telegram task input. */
|
|
787073
785214
|
telegramIntakeRecords = /* @__PURE__ */ new Map();
|
|
787074
785215
|
telegramIntakeMessages = /* @__PURE__ */ new Map();
|
|
787075
785216
|
telegramIntakeWriteTail = Promise.resolve();
|
|
787076
|
-
/** In-process authority mirror for exact input ownership and delivery idempotency. */
|
|
787077
|
-
telegramInputOwnership = new TelegramInputOwnershipLedger();
|
|
787078
|
-
/**
|
|
787079
|
-
* Derived social/memory work runs after visible delivery. The queue has no
|
|
787080
|
-
* Telegram send authority, serializes each chat scope, and cannot revise the
|
|
787081
|
-
* already committed turn decision.
|
|
787082
|
-
*/
|
|
787083
|
-
telegramCognitionQueue = new TelegramCognitionQueue({
|
|
787084
|
-
maxConcurrentScopes: 2,
|
|
787085
|
-
maxQueuedJobs: 128,
|
|
787086
|
-
defaultTimeBudgetMs: 15e3
|
|
787087
|
-
});
|
|
787088
785217
|
/** Intent epochs isolate redirected/replaced work inside a long-lived chat session. */
|
|
787089
785218
|
telegramTaskEpochs = /* @__PURE__ */ new Map();
|
|
787090
785219
|
/** Active direct chat completions, counted with Telegram activity in the TUI */
|
|
@@ -787100,6 +785229,12 @@ Telegram link integrity contract:
|
|
|
787100
785229
|
telegramActiveWorkSessions = /* @__PURE__ */ new Set();
|
|
787101
785230
|
telegramActiveWorkGenerations = /* @__PURE__ */ new Map();
|
|
787102
785231
|
telegramActiveWorkStartedAtMs = /* @__PURE__ */ new Map();
|
|
785232
|
+
/**
|
|
785233
|
+
* Native Telegram typing heartbeats owned by the outer work lifecycle.
|
|
785234
|
+
* Group work starts one heartbeat before attention routing and keeps it
|
|
785235
|
+
* alive through the selected reply path and final delivery.
|
|
785236
|
+
*/
|
|
785237
|
+
telegramWorkTypingIntervals = /* @__PURE__ */ new Map();
|
|
787103
785238
|
/** Queued Telegram sessions waiting for a global work slot. */
|
|
787104
785239
|
telegramQueuedSessionWork = /* @__PURE__ */ new Map();
|
|
787105
785240
|
telegramQueuedSessionCompletions = /* @__PURE__ */ new Map();
|
|
@@ -787591,7 +785726,7 @@ Telegram link integrity contract:
|
|
|
787591
785726
|
return !!this.adminAuthChallenge && this.adminAuthChallenge.expiresAtMs > Date.now();
|
|
787592
785727
|
}
|
|
787593
785728
|
hashAdminAuthCode(code8) {
|
|
787594
|
-
return
|
|
785729
|
+
return createHash75("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
|
|
787595
785730
|
}
|
|
787596
785731
|
viewIdForMessage(msg) {
|
|
787597
785732
|
return `telegram-${this.sessionKeyForMessage(msg).replace(/[^A-Za-z0-9_-]/g, "-")}`;
|
|
@@ -788049,6 +786184,9 @@ No scoped reflection artifact exists yet for this chat. Use <code>/reflect</code
|
|
|
788049
786184
|
if (idleMs <= maxIdleMs) continue;
|
|
788050
786185
|
const generation = this.telegramActiveWorkGenerations.get(sessionKey) ?? 0;
|
|
788051
786186
|
this.telegramActiveWorkGenerations.set(sessionKey, generation + 1);
|
|
786187
|
+
const typingInterval = this.telegramWorkTypingIntervals.get(sessionKey);
|
|
786188
|
+
if (typingInterval) clearInterval(typingInterval);
|
|
786189
|
+
this.telegramWorkTypingIntervals.delete(sessionKey);
|
|
788052
786190
|
this.telegramActiveWorkSessions.delete(sessionKey);
|
|
788053
786191
|
this.telegramActiveWorkStartedAtMs.delete(sessionKey);
|
|
788054
786192
|
this.refreshActiveTelegramInteractionCount();
|
|
@@ -788183,6 +786321,18 @@ No scoped reflection artifact exists yet for this chat. Use <code>/reflect</code
|
|
|
788183
786321
|
this.telegramActiveWorkSessions.add(work.sessionKey);
|
|
788184
786322
|
this.telegramActiveWorkStartedAtMs.set(work.sessionKey, Date.now());
|
|
788185
786323
|
const generation = this.nextTelegramWorkGeneration(work.sessionKey);
|
|
786324
|
+
let workTypingInterval = null;
|
|
786325
|
+
if (work.msg.chatType !== "private" && this.canUseChatActions(work.msg)) {
|
|
786326
|
+
const staleTypingInterval = this.telegramWorkTypingIntervals.get(
|
|
786327
|
+
work.sessionKey
|
|
786328
|
+
);
|
|
786329
|
+
if (staleTypingInterval) clearInterval(staleTypingInterval);
|
|
786330
|
+
workTypingInterval = this.startTypingIndicator(
|
|
786331
|
+
work.msg.chatId,
|
|
786332
|
+
work.msg.messageThreadId
|
|
786333
|
+
);
|
|
786334
|
+
this.telegramWorkTypingIntervals.set(work.sessionKey, workTypingInterval);
|
|
786335
|
+
}
|
|
788186
786336
|
this.refreshActiveTelegramInteractionCount();
|
|
788187
786337
|
const completion = this.telegramQueuedSessionCompletions.get(
|
|
788188
786338
|
work.sessionKey
|
|
@@ -788197,6 +786347,10 @@ No scoped reflection artifact exists yet for this chat. Use <code>/reflect</code
|
|
|
788197
786347
|
);
|
|
788198
786348
|
completion?.reject(err);
|
|
788199
786349
|
}).finally(() => {
|
|
786350
|
+
if (workTypingInterval && this.telegramWorkTypingIntervals.get(work.sessionKey) === workTypingInterval) {
|
|
786351
|
+
clearInterval(workTypingInterval);
|
|
786352
|
+
this.telegramWorkTypingIntervals.delete(work.sessionKey);
|
|
786353
|
+
}
|
|
788200
786354
|
this.telegramQueuedSessionCompletions.delete(work.sessionKey);
|
|
788201
786355
|
if (this.telegramWorkGenerationIsCurrent(work.sessionKey, generation)) {
|
|
788202
786356
|
this.telegramActiveWorkSessions.delete(work.sessionKey);
|
|
@@ -788588,87 +786742,6 @@ ${context2}` : context2;
|
|
|
788588
786742
|
const thread = msg.messageThreadId ?? 0;
|
|
788589
786743
|
return `telegram:${this.sessionKeyForMessage(msg)}:${thread}:${msg.messageId ?? "unknown"}`;
|
|
788590
786744
|
}
|
|
788591
|
-
telegramInputTargetForMessage(msg) {
|
|
788592
|
-
return {
|
|
788593
|
-
inputId: this.telegramInputIdForMessage(msg),
|
|
788594
|
-
sessionKey: this.sessionKeyForMessage(msg),
|
|
788595
|
-
chatId: String(msg.chatId),
|
|
788596
|
-
messageId: msg.messageId,
|
|
788597
|
-
messageThreadId: msg.messageThreadId ?? 0,
|
|
788598
|
-
senderActorKey: telegramSocialActorKey(
|
|
788599
|
-
this.telegramMessageSocialActorInput(msg)
|
|
788600
|
-
)
|
|
788601
|
-
};
|
|
788602
|
-
}
|
|
788603
|
-
telegramInputOwnerForWork(sessionKey, generation) {
|
|
788604
|
-
return {
|
|
788605
|
-
ownerId: `telegram-work:${sessionKey}`,
|
|
788606
|
-
generation
|
|
788607
|
-
};
|
|
788608
|
-
}
|
|
788609
|
-
telegramTurnContractForDecision(msg, decision2) {
|
|
788610
|
-
const packet = this.buildTelegramInteractionEvidencePacket(msg);
|
|
788611
|
-
const target = this.telegramInputTargetForMessage(msg);
|
|
788612
|
-
const kind = !decision2.shouldReply ? "no_reply" : decision2.route === "chat" ? "chat_reply" : "action";
|
|
788613
|
-
const raw = {
|
|
788614
|
-
version: 2,
|
|
788615
|
-
kind,
|
|
788616
|
-
input_id: target.inputId,
|
|
788617
|
-
target: {
|
|
788618
|
-
input_id: target.inputId,
|
|
788619
|
-
session_key: target.sessionKey,
|
|
788620
|
-
chat_id: target.chatId,
|
|
788621
|
-
message_id: target.messageId,
|
|
788622
|
-
message_thread_id: target.messageThreadId,
|
|
788623
|
-
sender_actor_key: target.senderActorKey
|
|
788624
|
-
},
|
|
788625
|
-
confidence: decision2.confidence,
|
|
788626
|
-
reason: decision2.reason,
|
|
788627
|
-
addressed_actor_keys: decision2.addressedActorKeys ?? [],
|
|
788628
|
-
self_role: decision2.selfRole ?? "uncertain",
|
|
788629
|
-
reply_basis: decision2.replyBasis ?? "uncertain",
|
|
788630
|
-
evidence_ids: decision2.evidenceIds ?? [],
|
|
788631
|
-
...kind === "chat_reply" && decision2.replyText ? { reply: decision2.replyText } : {},
|
|
788632
|
-
...kind === "action" ? { objective: decision2.reason } : {}
|
|
788633
|
-
};
|
|
788634
|
-
const validated = validateTelegramTurnContractV2(raw, {
|
|
788635
|
-
target,
|
|
788636
|
-
selfActorKey: packet.selfActorKey,
|
|
788637
|
-
actorKeys: packet.actorKeys,
|
|
788638
|
-
evidenceIds: packet.evidence.map((entry) => entry.id)
|
|
788639
|
-
});
|
|
788640
|
-
return validated.value;
|
|
788641
|
-
}
|
|
788642
|
-
async commitTelegramTurnDecision(msg, decision2, owner) {
|
|
788643
|
-
const contract = this.telegramTurnContractForDecision(msg, decision2);
|
|
788644
|
-
if (!contract) return null;
|
|
788645
|
-
const target = this.telegramInputTargetForMessage(msg);
|
|
788646
|
-
const result = this.telegramInputOwnership.commitDecision(target, owner, {
|
|
788647
|
-
decisionId: decision2.decisionId ?? `tgdec-${telegramTurnContractV2Fingerprint(contract).slice(0, 20)}`,
|
|
788648
|
-
contractFingerprint: telegramTurnContractV2Fingerprint(contract),
|
|
788649
|
-
contractVersion: 2,
|
|
788650
|
-
disposition: contract.kind
|
|
788651
|
-
});
|
|
788652
|
-
if (result.status === "applied" || result.status === "duplicate") {
|
|
788653
|
-
await this.appendTelegramIntakeJournal(target.sessionKey, {
|
|
788654
|
-
kind: "turn_contract_committed",
|
|
788655
|
-
inputId: target.inputId,
|
|
788656
|
-
decisionId: decision2.decisionId ?? result.record?.decision?.decisionId,
|
|
788657
|
-
contractFingerprint: telegramTurnContractV2Fingerprint(contract),
|
|
788658
|
-
disposition: contract.kind,
|
|
788659
|
-
owner,
|
|
788660
|
-
status: result.status
|
|
788661
|
-
});
|
|
788662
|
-
return contract;
|
|
788663
|
-
}
|
|
788664
|
-
this.tuiWrite(
|
|
788665
|
-
() => renderTelegramSubAgentError(
|
|
788666
|
-
msg.username,
|
|
788667
|
-
`input ownership rejected turn contract (${result.status}): ${result.reason ?? "authority conflict"}`
|
|
788668
|
-
)
|
|
788669
|
-
);
|
|
788670
|
-
return null;
|
|
788671
|
-
}
|
|
788672
786745
|
telegramTaskEpoch(sessionKey) {
|
|
788673
786746
|
const current = this.telegramTaskEpochs.get(sessionKey);
|
|
788674
786747
|
if (current !== void 0) return current;
|
|
@@ -788688,7 +786761,7 @@ ${context2}` : context2;
|
|
|
788688
786761
|
};
|
|
788689
786762
|
}
|
|
788690
786763
|
telegramIntakePath(sessionKey) {
|
|
788691
|
-
const digest4 =
|
|
786764
|
+
const digest4 = createHash75("sha256").update(sessionKey).digest("hex").slice(0, 20);
|
|
788692
786765
|
return join187(
|
|
788693
786766
|
this.repoRoot ?? process.cwd(),
|
|
788694
786767
|
".omnius",
|
|
@@ -788710,25 +786783,8 @@ ${context2}` : context2;
|
|
|
788710
786783
|
async registerTelegramIntake(msg, triage) {
|
|
788711
786784
|
const sessionKey = this.sessionKeyForMessage(msg);
|
|
788712
786785
|
const inputId = this.telegramInputIdForMessage(msg);
|
|
788713
|
-
const ownership = this.telegramInputOwnership.register(
|
|
788714
|
-
this.telegramInputTargetForMessage(msg),
|
|
788715
|
-
{ ownerId: `telegram-ingress:${sessionKey}`, generation: 0 }
|
|
788716
|
-
);
|
|
788717
786786
|
const existing = this.telegramIntakeRecords.get(inputId);
|
|
788718
|
-
if (
|
|
788719
|
-
await this.appendTelegramIntakeJournal(sessionKey, {
|
|
788720
|
-
kind: "intake_duplicate_or_conflict",
|
|
788721
|
-
inputId,
|
|
788722
|
-
status: ownership.status,
|
|
788723
|
-
reason: ownership.reason,
|
|
788724
|
-
observedTarget: this.telegramInputTargetForMessage(msg)
|
|
788725
|
-
});
|
|
788726
|
-
return {
|
|
788727
|
-
record: existing,
|
|
788728
|
-
ownershipStatus: ownership.status,
|
|
788729
|
-
reason: ownership.reason
|
|
788730
|
-
};
|
|
788731
|
-
}
|
|
786787
|
+
if (existing) return existing;
|
|
788732
786788
|
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
788733
786789
|
const record = {
|
|
788734
786790
|
inputId,
|
|
@@ -788753,7 +786809,7 @@ ${context2}` : context2;
|
|
|
788753
786809
|
record
|
|
788754
786810
|
});
|
|
788755
786811
|
await this.transitionTelegramIntake(record, "classified", triage.reason);
|
|
788756
|
-
return
|
|
786812
|
+
return record;
|
|
788757
786813
|
}
|
|
788758
786814
|
async transitionTelegramIntake(record, lifecycle, reason, links3 = {}) {
|
|
788759
786815
|
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -790200,11 +788256,11 @@ ${antecedents.join("\n")}` : "Immediate antecedents: none.",
|
|
|
790200
788256
|
return payload;
|
|
790201
788257
|
}
|
|
790202
788258
|
telegramConversationPath(sessionKey) {
|
|
790203
|
-
const safe =
|
|
788259
|
+
const safe = createHash75("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
790204
788260
|
return join187(this.telegramConversationDir, `${safe}.json`);
|
|
790205
788261
|
}
|
|
790206
788262
|
telegramConversationLedgerPath(sessionKey) {
|
|
790207
|
-
const safe =
|
|
788263
|
+
const safe = createHash75("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
790208
788264
|
return join187(this.telegramConversationDir, `${safe}.events.jsonl`);
|
|
790209
788265
|
}
|
|
790210
788266
|
telegramDb() {
|
|
@@ -790437,7 +788493,7 @@ ${antecedents.join("\n")}` : "Immediate antecedents: none.",
|
|
|
790437
788493
|
relationships: Array.isArray(raw.relationships) ? raw.relationships.slice(0, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT).map((fact) => this.normalizeTelegramAssociativeFact(fact)) : [],
|
|
790438
788494
|
actions: Array.isArray(raw.actions) ? raw.actions.slice(-TELEGRAM_ASSOCIATIVE_ACTION_LIMIT).map((action) => ({
|
|
790439
788495
|
id: String(
|
|
790440
|
-
action.id ||
|
|
788496
|
+
action.id || createHash75("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)
|
|
790441
788497
|
),
|
|
790442
788498
|
ts: typeof action.ts === "number" ? action.ts : Date.now(),
|
|
790443
788499
|
role: action.role === "assistant" ? "assistant" : "user",
|
|
@@ -790456,7 +788512,7 @@ ${antecedents.join("\n")}` : "Immediate antecedents: none.",
|
|
|
790456
788512
|
const now2 = Date.now();
|
|
790457
788513
|
return {
|
|
790458
788514
|
id: String(
|
|
790459
|
-
raw.id ||
|
|
788515
|
+
raw.id || createHash75("sha1").update(text3 || String(now2)).digest("hex").slice(0, 12)
|
|
790460
788516
|
),
|
|
790461
788517
|
text: text3,
|
|
790462
788518
|
tags: Array.isArray(raw.tags) ? raw.tags.map(String).slice(0, 16) : [],
|
|
@@ -790821,65 +788877,22 @@ ${antecedents.join("\n")}` : "Immediate antecedents: none.",
|
|
|
790821
788877
|
};
|
|
790822
788878
|
}
|
|
790823
788879
|
deliverTelegramPostReplyNotes(sessionKey, msg, viewId, decision2, salienceSignals, daydreamOpportunities, visibleReplyText) {
|
|
790824
|
-
const
|
|
790825
|
-
|
|
790826
|
-
|
|
790827
|
-
|
|
790828
|
-
|
|
790829
|
-
|
|
790830
|
-
|
|
790831
|
-
};
|
|
790832
|
-
const immutableMessage = {
|
|
790833
|
-
...msg,
|
|
790834
|
-
mentionedUsernames: msg.mentionedUsernames ? [...msg.mentionedUsernames] : void 0,
|
|
790835
|
-
mentionedActors: msg.mentionedActors ? msg.mentionedActors.map((actor) => ({ ...actor })) : void 0
|
|
790836
|
-
};
|
|
790837
|
-
const immutableSalience = [...salienceSignals];
|
|
790838
|
-
const immutableOpportunities = daydreamOpportunities.map((item) => ({
|
|
790839
|
-
...item
|
|
790840
|
-
}));
|
|
790841
|
-
const receipt2 = this.telegramCognitionQueue.enqueue({
|
|
790842
|
-
scopeKey: sessionKey,
|
|
790843
|
-
dedupeKey: `post-reply:${inputId}:${decisionId}`,
|
|
790844
|
-
kind: "cognition_batch",
|
|
790845
|
-
execute: ({ signal }) => {
|
|
790846
|
-
if (signal.aborted) return;
|
|
790847
|
-
const postReplyDecision = this.synthesizeTelegramPostReplyDecision(
|
|
790848
|
-
immutableDecision,
|
|
790849
|
-
immutableMessage,
|
|
790850
|
-
visibleReplyText
|
|
790851
|
-
);
|
|
790852
|
-
if (viewId && this.subAgentViewCallbacks) {
|
|
790853
|
-
this.subAgentViewCallbacks.onWrite(
|
|
790854
|
-
viewId,
|
|
790855
|
-
"post-reply/internal notes:"
|
|
790856
|
-
);
|
|
790857
|
-
}
|
|
790858
|
-
if (signal.aborted) return;
|
|
790859
|
-
this.deliverTelegramAttentionDecision(
|
|
790860
|
-
sessionKey,
|
|
790861
|
-
immutableMessage,
|
|
790862
|
-
viewId,
|
|
790863
|
-
postReplyDecision,
|
|
790864
|
-
immutableSalience,
|
|
790865
|
-
immutableOpportunities
|
|
790866
|
-
);
|
|
790867
|
-
}
|
|
790868
|
-
});
|
|
790869
|
-
if (receipt2.admission === "rejected_capacity" || receipt2.admission === "rejected_closed") {
|
|
790870
|
-
this.subAgentViewCallbacks?.onWrite(
|
|
790871
|
-
viewId || this.viewIdForMessage(msg),
|
|
790872
|
-
`post-reply cognition ${receipt2.admission.replace("rejected_", "rejected: ")}`
|
|
790873
|
-
);
|
|
790874
|
-
return;
|
|
788880
|
+
const postReplyDecision = this.synthesizeTelegramPostReplyDecision(
|
|
788881
|
+
decision2,
|
|
788882
|
+
msg,
|
|
788883
|
+
visibleReplyText
|
|
788884
|
+
);
|
|
788885
|
+
if (viewId && this.subAgentViewCallbacks) {
|
|
788886
|
+
this.subAgentViewCallbacks.onWrite(viewId, "post-reply/internal notes:");
|
|
790875
788887
|
}
|
|
790876
|
-
|
|
790877
|
-
|
|
790878
|
-
|
|
790879
|
-
|
|
790880
|
-
|
|
790881
|
-
|
|
790882
|
-
|
|
788888
|
+
this.deliverTelegramAttentionDecision(
|
|
788889
|
+
sessionKey,
|
|
788890
|
+
msg,
|
|
788891
|
+
viewId,
|
|
788892
|
+
postReplyDecision,
|
|
788893
|
+
salienceSignals,
|
|
788894
|
+
daydreamOpportunities
|
|
788895
|
+
);
|
|
790883
788896
|
}
|
|
790884
788897
|
telegramTextDeliveryCapability(sessionKey, chatId, messageThreadId) {
|
|
790885
788898
|
try {
|
|
@@ -791058,7 +789071,7 @@ ${antecedents.join("\n")}` : "Immediate antecedents: none.",
|
|
|
791058
789071
|
telegramHistoryBackfillMessageId(sessionKey, entry, index) {
|
|
791059
789072
|
if (typeof entry.messageId === "number" && Number.isFinite(entry.messageId))
|
|
791060
789073
|
return entry.messageId;
|
|
791061
|
-
const digest4 =
|
|
789074
|
+
const digest4 = createHash75("sha1").update(
|
|
791062
789075
|
`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`
|
|
791063
789076
|
).digest("hex").slice(0, 8);
|
|
791064
789077
|
return -Number.parseInt(digest4, 16);
|
|
@@ -792332,7 +790345,7 @@ ${antecedents.join("\n")}` : "Immediate antecedents: none.",
|
|
|
792332
790345
|
const now2 = entry.ts ?? Date.now();
|
|
792333
790346
|
memory.updatedAt = now2;
|
|
792334
790347
|
const speaker = telegramHistorySpeaker(entry);
|
|
792335
|
-
const actionId =
|
|
790348
|
+
const actionId = createHash75("sha1").update(
|
|
792336
790349
|
`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now2}:${entry.text}`
|
|
792337
790350
|
).digest("hex").slice(0, 16);
|
|
792338
790351
|
if (!memory.actions.some((action) => action.id === actionId)) {
|
|
@@ -792495,7 +790508,7 @@ ${antecedents.join("\n")}` : "Immediate antecedents: none.",
|
|
|
792495
790508
|
let fact = facts.find((item) => item.text.toLowerCase() === key);
|
|
792496
790509
|
if (!fact) {
|
|
792497
790510
|
fact = {
|
|
792498
|
-
id:
|
|
790511
|
+
id: createHash75("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
|
|
792499
790512
|
text: clean7,
|
|
792500
790513
|
tags: telegramMemoryTags(clean7, entry.mediaSummary),
|
|
792501
790514
|
speakers: [],
|
|
@@ -792580,7 +790593,7 @@ ${antecedents.join("\n")}` : "Immediate antecedents: none.",
|
|
|
792580
790593
|
const titleTags = tags.slice(0, 4);
|
|
792581
790594
|
const title = titleTags.length > 0 ? `${speaker} / ${titleTags.join(" ")}` : `${speaker} / conversation`;
|
|
792582
790595
|
const card = {
|
|
792583
|
-
id:
|
|
790596
|
+
id: createHash75("sha1").update(`${sessionKey}:${now2}:${speaker}:${text3}`).digest("hex").slice(0, 12),
|
|
792584
790597
|
title,
|
|
792585
790598
|
notes: [],
|
|
792586
790599
|
tags: [],
|
|
@@ -794713,7 +792726,7 @@ arguments=` : ""}` + (chunk.toolCallArgs ?? "");
|
|
|
794713
792726
|
}
|
|
794714
792727
|
}
|
|
794715
792728
|
if (issues.length > 0) return { decision: null, issues };
|
|
794716
|
-
const decisionId = `tgdec-${
|
|
792729
|
+
const decisionId = `tgdec-${createHash75("sha256").update(
|
|
794717
792730
|
JSON.stringify({
|
|
794718
792731
|
inputId: packet.inputId,
|
|
794719
792732
|
route: decision2.route,
|
|
@@ -794721,8 +792734,7 @@ arguments=` : ""}` + (chunk.toolCallArgs ?? "");
|
|
|
794721
792734
|
addressed,
|
|
794722
792735
|
selfRole: decision2.selfRole,
|
|
794723
792736
|
replyBasis: decision2.replyBasis,
|
|
794724
|
-
evidenceIds
|
|
794725
|
-
replyText: decision2.replyText
|
|
792737
|
+
evidenceIds
|
|
794726
792738
|
})
|
|
794727
792739
|
).digest("hex").slice(0, 20)}`;
|
|
794728
792740
|
return { decision: { ...decision2, decisionId }, issues: [] };
|
|
@@ -794730,26 +792742,6 @@ arguments=` : ""}` + (chunk.toolCallArgs ?? "");
|
|
|
794730
792742
|
validateTelegramInteractionDecision(decision2, packet) {
|
|
794731
792743
|
return this.validateTelegramInteractionDecisionDetailed(decision2, packet).decision;
|
|
794732
792744
|
}
|
|
794733
|
-
/**
|
|
794734
|
-
* Materialize fields that are logical consequences of the model's chosen
|
|
794735
|
-
* reply basis. The model still decides whether to reply and why. Once it
|
|
794736
|
-
* chooses direct_turn, however, asking it to repeat "self is an addressee"
|
|
794737
|
-
* in two additional fields creates three representations of one decision.
|
|
794738
|
-
* A disagreement between those copies must not spend another inference.
|
|
794739
|
-
*/
|
|
794740
|
-
normalizeTelegramInteractionDecisionImplications(decision2, packet) {
|
|
794741
|
-
if (decision2.replyBasis !== "direct_turn") return decision2;
|
|
794742
|
-
return {
|
|
794743
|
-
...decision2,
|
|
794744
|
-
addressedActorKeys: [
|
|
794745
|
-
.../* @__PURE__ */ new Set([
|
|
794746
|
-
...decision2.addressedActorKeys ?? [],
|
|
794747
|
-
packet.selfActorKey
|
|
794748
|
-
])
|
|
794749
|
-
],
|
|
794750
|
-
selfRole: "addressee"
|
|
794751
|
-
};
|
|
794752
|
-
}
|
|
794753
792745
|
bindTrustedTelegramDecision(decision2, packet) {
|
|
794754
792746
|
const bound = {
|
|
794755
792747
|
...decision2,
|
|
@@ -794771,7 +792763,7 @@ arguments=` : ""}` + (chunk.toolCallArgs ?? "");
|
|
|
794771
792763
|
...validationIssues.length > 0 ? [
|
|
794772
792764
|
`The host rejected the prior semantic contract for these exact reasons:`,
|
|
794773
792765
|
...validationIssues.map(
|
|
794774
|
-
(
|
|
792766
|
+
(issue2) => `- ${issue2.code}: ${issue2.message}`
|
|
794775
792767
|
),
|
|
794776
792768
|
`Correct every listed issue. Do not repeat a rejected identifier.`
|
|
794777
792769
|
] : [],
|
|
@@ -794814,21 +792806,17 @@ arguments=` : ""}` + (chunk.toolCallArgs ?? "");
|
|
|
794814
792806
|
requireShouldReply: true
|
|
794815
792807
|
});
|
|
794816
792808
|
if (parsed && evidencePacket) parsed.inputId = evidencePacket.inputId;
|
|
794817
|
-
const
|
|
792809
|
+
const validation = parsed && evidencePacket ? this.validateTelegramInteractionDecisionDetailed(
|
|
794818
792810
|
parsed,
|
|
794819
792811
|
evidencePacket
|
|
794820
|
-
) : parsed;
|
|
794821
|
-
const validation = normalized4 && evidencePacket ? this.validateTelegramInteractionDecisionDetailed(
|
|
794822
|
-
normalized4,
|
|
794823
|
-
evidencePacket
|
|
794824
|
-
) : { decision: normalized4, issues: [] };
|
|
792812
|
+
) : { decision: parsed, issues: [] };
|
|
794825
792813
|
const validated = validation.decision;
|
|
794826
792814
|
if (!validated) {
|
|
794827
792815
|
if (diagnostics) {
|
|
794828
792816
|
const cleaned = stripTelegramHiddenThinking(retryText).trim();
|
|
794829
792817
|
diagnostics.strictRetryStatus = parsed && validation.issues.length > 0 ? "semantic-invalid" : cleaned ? "unparseable" : "empty";
|
|
794830
792818
|
diagnostics.strictRetryValidationIssues = validation.issues.map(
|
|
794831
|
-
(
|
|
792819
|
+
(issue2) => issue2.code
|
|
794832
792820
|
);
|
|
794833
792821
|
}
|
|
794834
792822
|
return null;
|
|
@@ -795057,6 +793045,9 @@ ${retryText}`,
|
|
|
795057
793045
|
agent.typingInterval = null;
|
|
795058
793046
|
}
|
|
795059
793047
|
this.stopTelegramPublicProgressMessage(agent);
|
|
793048
|
+
const workTypingInterval = this.telegramWorkTypingIntervals.get(sessionKey);
|
|
793049
|
+
if (workTypingInterval) clearInterval(workTypingInterval);
|
|
793050
|
+
this.telegramWorkTypingIntervals.delete(sessionKey);
|
|
795060
793051
|
try {
|
|
795061
793052
|
agent.runner?.abort?.();
|
|
795062
793053
|
} catch {
|
|
@@ -795246,7 +793237,7 @@ ${stimulationProbe.context}`,
|
|
|
795246
793237
|
reflectionContext = [
|
|
795247
793238
|
"## Router fast-path note policy",
|
|
795248
793239
|
"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.",
|
|
795249
|
-
"
|
|
793240
|
+
"Only decide route, should_reply, confidence, reason, optional stimulation cadence, and optional explicit reply_mode_preference.",
|
|
795250
793241
|
"If notes are needed, the bridge will synthesize or commit them after the visible reply according to the resolved reply mode."
|
|
795251
793242
|
].join("\n");
|
|
795252
793243
|
} else {
|
|
@@ -795275,77 +793266,6 @@ ${stimulationProbe.context}`,
|
|
|
795275
793266
|
`scenario_state_loop: ${reflectionNotes.scenarioStateLoop ?? "pending model-derived classifier output"}`
|
|
795276
793267
|
].join("\n");
|
|
795277
793268
|
}
|
|
795278
|
-
const routerContractContext = [
|
|
795279
|
-
`Schema: ${TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA}`,
|
|
795280
|
-
`Route meanings:`,
|
|
795281
|
-
`- chat: a short conversational answer can be produced without tools.`,
|
|
795282
|
-
`- action: tools, workspace context, media processing, web lookup, delegation, or a multi-step agent loop may be needed.`,
|
|
795283
|
-
`Unified reply boundary: when route="chat" and should_reply=true, write the exact natural Telegram response in reply. This response is delivered directly, so do not describe a future reply, expose the contract, or include internal notes. Use reply=null for no_reply and action decisions.`
|
|
795284
|
-
].join("\n");
|
|
795285
|
-
const routerContextBlocks = [
|
|
795286
|
-
{
|
|
795287
|
-
semanticId: "telegram.router.contract",
|
|
795288
|
-
revision: 2,
|
|
795289
|
-
stability: "stable",
|
|
795290
|
-
order: 10,
|
|
795291
|
-
priority: 100,
|
|
795292
|
-
records: [
|
|
795293
|
-
{ recordId: "turn-contract", content: routerContractContext }
|
|
795294
|
-
]
|
|
795295
|
-
},
|
|
795296
|
-
{
|
|
795297
|
-
semanticId: "telegram.router.persona",
|
|
795298
|
-
revision: msg.messageId,
|
|
795299
|
-
stability: "dynamic",
|
|
795300
|
-
order: 20,
|
|
795301
|
-
priority: 90,
|
|
795302
|
-
records: [{ recordId: "persona", content: personaContext }]
|
|
795303
|
-
},
|
|
795304
|
-
{
|
|
795305
|
-
semanticId: "telegram.router.reflection",
|
|
795306
|
-
revision: msg.messageId,
|
|
795307
|
-
stability: "dynamic",
|
|
795308
|
-
order: 30,
|
|
795309
|
-
priority: 70,
|
|
795310
|
-
records: [{ recordId: "reflection", content: reflectionContext }]
|
|
795311
|
-
},
|
|
795312
|
-
{
|
|
795313
|
-
semanticId: "telegram.router.observation",
|
|
795314
|
-
revision: msg.messageId,
|
|
795315
|
-
stability: "dynamic",
|
|
795316
|
-
order: 40,
|
|
795317
|
-
priority: 100,
|
|
795318
|
-
records: [{ recordId: "evidence", content: observationContext }]
|
|
795319
|
-
},
|
|
795320
|
-
{
|
|
795321
|
-
semanticId: "telegram.router.system-observations",
|
|
795322
|
-
revision: msg.messageId,
|
|
795323
|
-
stability: "dynamic",
|
|
795324
|
-
order: 50,
|
|
795325
|
-
priority: 60,
|
|
795326
|
-
records: [
|
|
795327
|
-
{
|
|
795328
|
-
recordId: "observations",
|
|
795329
|
-
content: formatSystemObservations(sessionKey)
|
|
795330
|
-
}
|
|
795331
|
-
]
|
|
795332
|
-
},
|
|
795333
|
-
{
|
|
795334
|
-
semanticId: "telegram.turn.current",
|
|
795335
|
-
revision: msg.messageId,
|
|
795336
|
-
stability: "dynamic",
|
|
795337
|
-
order: 60,
|
|
795338
|
-
priority: 110,
|
|
795339
|
-
records: [{ recordId: "message-text", content: msg.text }]
|
|
795340
|
-
}
|
|
795341
|
-
];
|
|
795342
|
-
const routerContextPacket = compileTelegramContextPacketV2({
|
|
795343
|
-
blocks: routerContextBlocks,
|
|
795344
|
-
budgets: {
|
|
795345
|
-
stableChars: 12e3,
|
|
795346
|
-
dynamicChars: 48e3
|
|
795347
|
-
}
|
|
795348
|
-
});
|
|
795349
793269
|
const userPrompt = [
|
|
795350
793270
|
`You are the Telegram live routing and reply-discretion model.`,
|
|
795351
793271
|
`Make the smallest sufficient live attention decision. Do not include internal notes unless explicitly supplied by deliberative mode context.`,
|
|
@@ -795356,6 +793276,12 @@ ${stimulationProbe.context}`,
|
|
|
795356
793276
|
`Target binding: infer the addressees and this bot's role before should_reply. Another actor being addressed does not force silence; a reply can still be valid for an ongoing self-owned task or a socially useful intervention, but it must use that reply_basis and cite current evidence.`,
|
|
795357
793277
|
`Authorization integrity: should_reply=true requires a non-none, non-uncertain reply_basis and at least one cited evidence_id. direct_turn requires self_role=addressee and the self actor key in addressed_actor_keys. ongoing_self_task requires the active_task evidence id.`,
|
|
795358
793278
|
`Classification boundary: decide whether an action runner is needed, but do not execute a tool and do not emit a tool invocation. A required capability is represented only by route="action" in the attention schema.`,
|
|
793279
|
+
``,
|
|
793280
|
+
`Schema: ${TELEGRAM_INTERACTION_DECISION_MINIMAL_SCHEMA}`,
|
|
793281
|
+
``,
|
|
793282
|
+
`Route meanings:`,
|
|
793283
|
+
`- chat: a short conversational answer can be produced without tools.`,
|
|
793284
|
+
`- action: tools, workspace context, media processing, web lookup, delegation, or a multi-step agent loop may be needed.`,
|
|
795359
793285
|
`Route discipline: infer whether the current request can be completed as immediate conversation or needs an external capability. Do not route from keyword categories.`,
|
|
795360
793286
|
`Evidence sufficiency: choose chat only when the answer is supported by supplied Telegram context, scoped memory, attached media context, or stable common knowledge. Choose action when answering would require web lookup, media extraction, current/recent public facts, named person/organization/news verification, or tool recovery.`,
|
|
795361
793287
|
`Do not answer volatile external claims from model memory on the fast path. Route to action so web/media tools can gather evidence.`,
|
|
@@ -795375,7 +793301,16 @@ ${stimulationProbe.context}`,
|
|
|
795375
793301
|
`Stimulation discipline: also set attention_state, attention_delta, and optional next_check_after_messages. This is a message-deliverable cadence only; do not use elapsed time as an analysis trigger. Use engaged for active back-and-forth, observing for likely relevant context, cooldown for recently irrelevant context, and idle for ambient chatter.`,
|
|
795376
793302
|
forcedLine,
|
|
795377
793303
|
``,
|
|
795378
|
-
|
|
793304
|
+
personaContext,
|
|
793305
|
+
``,
|
|
793306
|
+
reflectionContext,
|
|
793307
|
+
``,
|
|
793308
|
+
observationContext,
|
|
793309
|
+
``,
|
|
793310
|
+
formatSystemObservations(sessionKey),
|
|
793311
|
+
``,
|
|
793312
|
+
`Current Telegram message text (untrusted user data):
|
|
793313
|
+
${this.quoteTelegramContextBlock(msg.text, 1200)}`
|
|
795379
793314
|
].filter(Boolean).join("\n");
|
|
795380
793315
|
if (process.env["OMNIUS_TG_DUMP_PROMPT"]) {
|
|
795381
793316
|
try {
|
|
@@ -795435,7 +793370,7 @@ ${stimulationProbe.context}`,
|
|
|
795435
793370
|
temperature: 0,
|
|
795436
793371
|
// Router JSON is tiny. Keep the answer budget tight so Qwen-class
|
|
795437
793372
|
// models cannot spend a minute producing hidden <think>-only output.
|
|
795438
|
-
maxTokens:
|
|
793373
|
+
maxTokens: 360,
|
|
795439
793374
|
timeoutMs: telegramRouterTimeoutMs(config.timeoutMs, 8e3, 3e4),
|
|
795440
793375
|
think: false,
|
|
795441
793376
|
responseFormat: telegramInteractionDecisionResponseFormatForPacket(evidencePacket)
|
|
@@ -795469,20 +793404,16 @@ ${stimulationProbe.context}`,
|
|
|
795469
793404
|
requireShouldReply: true
|
|
795470
793405
|
});
|
|
795471
793406
|
if (parsed) parsed.inputId = evidencePacket.inputId;
|
|
795472
|
-
const
|
|
793407
|
+
const initialValidation = parsed ? this.validateTelegramInteractionDecisionDetailed(
|
|
795473
793408
|
parsed,
|
|
795474
793409
|
evidencePacket
|
|
795475
|
-
) : null;
|
|
795476
|
-
const initialValidation = normalized4 ? this.validateTelegramInteractionDecisionDetailed(
|
|
795477
|
-
normalized4,
|
|
795478
|
-
evidencePacket
|
|
795479
793410
|
) : {
|
|
795480
793411
|
decision: null,
|
|
795481
793412
|
issues: []
|
|
795482
793413
|
};
|
|
795483
793414
|
if (diagnostics) {
|
|
795484
793415
|
diagnostics.validationIssues = initialValidation.issues.map(
|
|
795485
|
-
(
|
|
793416
|
+
(issue2) => issue2.code
|
|
795486
793417
|
);
|
|
795487
793418
|
}
|
|
795488
793419
|
const validated = initialValidation.decision;
|
|
@@ -795873,7 +793804,7 @@ ${list}` : "No shared group target is currently known for this sender. Ask in th
|
|
|
795873
793804
|
}
|
|
795874
793805
|
telegramRunnerStateDir(sessionKey) {
|
|
795875
793806
|
if (!this.repoRoot) return void 0;
|
|
795876
|
-
const safe =
|
|
793807
|
+
const safe = createHash75("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
795877
793808
|
return join187(this.repoRoot, ".omnius", "telegram-runner-state", safe);
|
|
795878
793809
|
}
|
|
795879
793810
|
buildTelegramAdminOverviewContext(currentSessionKey) {
|
|
@@ -796286,14 +794217,6 @@ ${TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT}`
|
|
|
796286
794217
|
this.state.active = false;
|
|
796287
794218
|
this.abortController?.abort(new TelegramBridgeStoppedError());
|
|
796288
794219
|
this.telegramApiGovernor.stop("Telegram bridge stopped");
|
|
796289
|
-
this.telegramActionSessions?.shutdown();
|
|
796290
|
-
this.telegramActionSessions = null;
|
|
796291
|
-
this.telegramActionSessionBlueprints.clear();
|
|
796292
|
-
void this.telegramCognitionQueue.close({
|
|
796293
|
-
cancelQueued: true,
|
|
796294
|
-
cancelRunning: true,
|
|
796295
|
-
reason: "Telegram bridge stopped"
|
|
796296
|
-
});
|
|
796297
794220
|
if (this.mediaCacheCleanupTimer) {
|
|
796298
794221
|
clearInterval(this.mediaCacheCleanupTimer);
|
|
796299
794222
|
this.mediaCacheCleanupTimer = null;
|
|
@@ -796326,6 +794249,10 @@ ${TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT}`
|
|
|
796326
794249
|
);
|
|
796327
794250
|
}
|
|
796328
794251
|
this.telegramQueuedSessionCompletions.clear();
|
|
794252
|
+
for (const interval of this.telegramWorkTypingIntervals.values()) {
|
|
794253
|
+
clearInterval(interval);
|
|
794254
|
+
}
|
|
794255
|
+
this.telegramWorkTypingIntervals.clear();
|
|
796329
794256
|
this.telegramActiveWorkSessions.clear();
|
|
796330
794257
|
this.telegramActiveWorkGenerations.clear();
|
|
796331
794258
|
this.telegramActiveWorkStartedAtMs.clear();
|
|
@@ -796468,17 +794395,21 @@ ${TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT}`
|
|
|
796468
794395
|
}
|
|
796469
794396
|
// ── Typing indicator ──────────────────────────────────────────────────
|
|
796470
794397
|
/** Start sending "typing" indicator every 4 seconds */
|
|
796471
|
-
startTypingIndicator(chatId) {
|
|
796472
|
-
this.sendChatAction(chatId, "typing").catch(() => {
|
|
794398
|
+
startTypingIndicator(chatId, messageThreadId) {
|
|
794399
|
+
this.sendChatAction(chatId, "typing", messageThreadId).catch(() => {
|
|
796473
794400
|
});
|
|
796474
794401
|
return setInterval(() => {
|
|
796475
|
-
this.sendChatAction(chatId, "typing").catch(() => {
|
|
794402
|
+
this.sendChatAction(chatId, "typing", messageThreadId).catch(() => {
|
|
796476
794403
|
});
|
|
796477
794404
|
}, 4e3);
|
|
796478
794405
|
}
|
|
796479
794406
|
/** Send a chat action (typing indicator) */
|
|
796480
|
-
async sendChatAction(chatId, action) {
|
|
796481
|
-
await this.apiCall("sendChatAction", {
|
|
794407
|
+
async sendChatAction(chatId, action, messageThreadId) {
|
|
794408
|
+
await this.apiCall("sendChatAction", {
|
|
794409
|
+
chat_id: chatId,
|
|
794410
|
+
action,
|
|
794411
|
+
...messageThreadId !== void 0 ? { message_thread_id: messageThreadId } : {}
|
|
794412
|
+
});
|
|
796482
794413
|
}
|
|
796483
794414
|
createTelegramGenerativeProgressBridge(chatId, msg) {
|
|
796484
794415
|
if (chatId === void 0) return void 0;
|
|
@@ -797717,20 +795648,7 @@ Join: ${newUrl}`
|
|
|
797717
795648
|
}
|
|
797718
795649
|
}
|
|
797719
795650
|
const intakeTriage = this.triageTelegramSteeringInput(msg);
|
|
797720
|
-
const
|
|
797721
|
-
msg,
|
|
797722
|
-
intakeTriage
|
|
797723
|
-
);
|
|
797724
|
-
if (intakeRegistration.ownershipStatus !== "applied" || !intakeRegistration.record) {
|
|
797725
|
-
this.tuiWrite(
|
|
797726
|
-
() => renderTelegramSubAgentEvent(
|
|
797727
|
-
msg.username,
|
|
797728
|
-
`input ${this.telegramInputIdForMessage(msg)} ignored after ${intakeRegistration.ownershipStatus}${intakeRegistration.reason ? `: ${intakeRegistration.reason}` : ""}`
|
|
797729
|
-
)
|
|
797730
|
-
);
|
|
797731
|
-
return;
|
|
797732
|
-
}
|
|
797733
|
-
const intakeRecord = intakeRegistration.record;
|
|
795651
|
+
const intakeRecord = await this.registerTelegramIntake(msg, intakeTriage);
|
|
797734
795652
|
const existing = this.subAgents.get(sessionKey);
|
|
797735
795653
|
if (existing && !existing.aborted) {
|
|
797736
795654
|
const trustedPreemption = isAdminDM && (intakeRecord.intent === "cancel" || intakeRecord.intent === "redirect" || intakeRecord.intent === "replace");
|
|
@@ -797764,26 +795682,6 @@ Join: ${newUrl}`
|
|
|
797764
795682
|
const isAdminDM = toolContext === "telegram-admin-dm";
|
|
797765
795683
|
if (!this.telegramWorkGenerationIsCurrent(sessionKey, workGeneration))
|
|
797766
795684
|
return;
|
|
797767
|
-
const workOwner = this.telegramInputOwnerForWork(
|
|
797768
|
-
sessionKey,
|
|
797769
|
-
workGeneration
|
|
797770
|
-
);
|
|
797771
|
-
const primaryOwnership = this.telegramInputOwnership.claim(
|
|
797772
|
-
this.telegramInputTargetForMessage(msg),
|
|
797773
|
-
workOwner
|
|
797774
|
-
);
|
|
797775
|
-
if (primaryOwnership.status !== "applied" && primaryOwnership.status !== "duplicate") {
|
|
797776
|
-
await Promise.all(
|
|
797777
|
-
work.intakeRecords.map(
|
|
797778
|
-
(intake) => this.transitionTelegramIntake(
|
|
797779
|
-
intake,
|
|
797780
|
-
"failed",
|
|
797781
|
-
`Telegram input ownership rejected work admission (${primaryOwnership.status}): ${primaryOwnership.reason ?? "authority conflict"}`
|
|
797782
|
-
)
|
|
797783
|
-
)
|
|
797784
|
-
);
|
|
797785
|
-
return;
|
|
797786
|
-
}
|
|
797787
795685
|
await Promise.all(
|
|
797788
795686
|
work.intakeRecords.map(
|
|
797789
795687
|
(record) => this.transitionTelegramIntake(
|
|
@@ -797868,23 +795766,6 @@ Join: ${newUrl}`
|
|
|
797868
795766
|
);
|
|
797869
795767
|
return;
|
|
797870
795768
|
}
|
|
797871
|
-
const turnContract = await this.commitTelegramTurnDecision(
|
|
797872
|
-
msg,
|
|
797873
|
-
decision2,
|
|
797874
|
-
workOwner
|
|
797875
|
-
);
|
|
797876
|
-
if (decision2.shouldReply && decision2.route === "chat" && decision2.replyText && !turnContract) {
|
|
797877
|
-
await Promise.all(
|
|
797878
|
-
work.intakeRecords.map(
|
|
797879
|
-
(intake) => this.transitionTelegramIntake(
|
|
797880
|
-
intake,
|
|
797881
|
-
"failed",
|
|
797882
|
-
"Telegram V2 chat contract failed exact-input ownership validation"
|
|
797883
|
-
)
|
|
797884
|
-
)
|
|
797885
|
-
);
|
|
797886
|
-
return;
|
|
797887
|
-
}
|
|
797888
795769
|
const replyMode = this.resolvedTelegramReplyMode(sessionKey, msg);
|
|
797889
795770
|
const storedPreference = this.applyTelegramReplyPreferenceUpdate(
|
|
797890
795771
|
sessionKey,
|
|
@@ -797937,20 +795818,6 @@ Join: ${newUrl}`
|
|
|
797937
795818
|
)
|
|
797938
795819
|
)
|
|
797939
795820
|
);
|
|
797940
|
-
if (turnContract?.kind === "no_reply") {
|
|
797941
|
-
const terminal = this.telegramInputOwnership.complete(
|
|
797942
|
-
this.telegramInputTargetForMessage(msg),
|
|
797943
|
-
workOwner,
|
|
797944
|
-
"consumed"
|
|
797945
|
-
);
|
|
797946
|
-
await this.appendTelegramIntakeJournal(sessionKey, {
|
|
797947
|
-
kind: "turn_terminal_committed",
|
|
797948
|
-
inputId: turnContract.inputId,
|
|
797949
|
-
terminal: "consumed",
|
|
797950
|
-
status: terminal.status,
|
|
797951
|
-
owner: workOwner
|
|
797952
|
-
});
|
|
797953
|
-
}
|
|
797954
795821
|
return;
|
|
797955
795822
|
}
|
|
797956
795823
|
const decisionContext = this.formatTelegramAttentionDecisionContext(
|
|
@@ -797977,8 +795844,8 @@ Join: ${newUrl}`
|
|
|
797977
795844
|
return;
|
|
797978
795845
|
}
|
|
797979
795846
|
const subAgentProfile = decision2.route === "chat" ? "chat" : "action";
|
|
797980
|
-
if (decision2.route === "chat") {
|
|
797981
|
-
const visibleReplyDelivered =
|
|
795847
|
+
if (decision2.route === "chat" && msg.chatType === "private") {
|
|
795848
|
+
const visibleReplyDelivered = await this.handleTelegramChatCompletion(
|
|
797982
795849
|
msg,
|
|
797983
795850
|
toolContext,
|
|
797984
795851
|
rapidContext,
|
|
@@ -798092,8 +795959,11 @@ Join: ${newUrl}`
|
|
|
798092
795959
|
subAgent.viewId,
|
|
798093
795960
|
`✈ Telegram message from @${msg.username}: ${msg.text}`
|
|
798094
795961
|
);
|
|
798095
|
-
if (this.canUseChatActions(msg)) {
|
|
798096
|
-
subAgent.typingInterval = this.startTypingIndicator(
|
|
795962
|
+
if (this.canUseChatActions(msg) && !this.telegramWorkTypingIntervals.has(sessionKey)) {
|
|
795963
|
+
subAgent.typingInterval = this.startTypingIndicator(
|
|
795964
|
+
msg.chatId,
|
|
795965
|
+
msg.messageThreadId
|
|
795966
|
+
);
|
|
798097
795967
|
}
|
|
798098
795968
|
this.tuiWrite(
|
|
798099
795969
|
() => renderTelegramSubAgentStart(msg.username, msg.text, isAdminDM)
|
|
@@ -798305,13 +796175,6 @@ Join: ${newUrl}`
|
|
|
798305
796175
|
deliveredFinalText,
|
|
798306
796176
|
Boolean(subAgent.liveMessageId && !msg.guestQueryId)
|
|
798307
796177
|
);
|
|
798308
|
-
if (sentMessageId !== null || msg.guestQueryId) {
|
|
798309
|
-
await this.commitTelegramTurnDeliveryReceipt(
|
|
798310
|
-
msg,
|
|
798311
|
-
"action_effect",
|
|
798312
|
-
sentMessageId !== null ? `telegram-message:${sentMessageId}:run:${subAgent.runId}` : `telegram-guest-query:${msg.guestQueryId}:run:${subAgent.runId}`
|
|
798313
|
-
);
|
|
798314
|
-
}
|
|
798315
796178
|
this.tuiWrite(
|
|
798316
796179
|
() => renderTelegramSubAgentComplete(msg.username, deliveredFinalText)
|
|
798317
796180
|
);
|
|
@@ -798460,8 +796323,11 @@ ${errMsg}`
|
|
|
798460
796323
|
`route: chat (${this.interactionMode}) with admin tools`
|
|
798461
796324
|
);
|
|
798462
796325
|
this.subAgentViewCallbacks?.onStatus(subAgent.viewId, "running");
|
|
798463
|
-
if (this.canUseChatActions(msg)) {
|
|
798464
|
-
subAgent.typingInterval = this.startTypingIndicator(
|
|
796326
|
+
if (this.canUseChatActions(msg) && !this.telegramWorkTypingIntervals.has(sessionKey)) {
|
|
796327
|
+
subAgent.typingInterval = this.startTypingIndicator(
|
|
796328
|
+
msg.chatId,
|
|
796329
|
+
msg.messageThreadId
|
|
796330
|
+
);
|
|
798465
796331
|
}
|
|
798466
796332
|
this.tuiWrite(
|
|
798467
796333
|
() => renderTelegramSubAgentEvent(
|
|
@@ -798686,96 +796552,6 @@ ${errMsg}`
|
|
|
798686
796552
|
}
|
|
798687
796553
|
}
|
|
798688
796554
|
/** Fast Telegram chat path: direct streamed completion, no tool loop. */
|
|
798689
|
-
async commitTelegramTurnDeliveryReceipt(msg, kind, transportReceiptId) {
|
|
798690
|
-
const target = this.telegramInputTargetForMessage(msg);
|
|
798691
|
-
const ownership = this.telegramInputOwnership.get(target.inputId);
|
|
798692
|
-
if (!ownership?.decision) return false;
|
|
798693
|
-
const expectedDisposition = kind === "visible_reply" ? "chat_reply" : "action";
|
|
798694
|
-
if (ownership.decision.disposition !== expectedDisposition) return false;
|
|
798695
|
-
const deliveryId = `tgdelivery-${createHash76("sha256").update(`${ownership.decision.decisionId}:${transportReceiptId}`).digest("hex").slice(0, 20)}`;
|
|
798696
|
-
const delivery = this.telegramInputOwnership.commitDelivery(
|
|
798697
|
-
target,
|
|
798698
|
-
ownership.owner,
|
|
798699
|
-
{
|
|
798700
|
-
deliveryId,
|
|
798701
|
-
decisionId: ownership.decision.decisionId,
|
|
798702
|
-
kind,
|
|
798703
|
-
transportReceiptId
|
|
798704
|
-
}
|
|
798705
|
-
);
|
|
798706
|
-
const terminal = delivery.status === "applied" || delivery.status === "duplicate" ? this.telegramInputOwnership.complete(
|
|
798707
|
-
target,
|
|
798708
|
-
ownership.owner,
|
|
798709
|
-
"consumed"
|
|
798710
|
-
) : void 0;
|
|
798711
|
-
await this.appendTelegramIntakeJournal(target.sessionKey, {
|
|
798712
|
-
kind: "turn_delivery_committed",
|
|
798713
|
-
inputId: target.inputId,
|
|
798714
|
-
decisionId: ownership.decision.decisionId,
|
|
798715
|
-
deliveryId,
|
|
798716
|
-
deliveryKind: kind,
|
|
798717
|
-
transportReceiptId,
|
|
798718
|
-
deliveryStatus: delivery.status,
|
|
798719
|
-
terminalStatus: terminal?.status,
|
|
798720
|
-
owner: ownership.owner
|
|
798721
|
-
});
|
|
798722
|
-
return (delivery.status === "applied" || delivery.status === "duplicate") && (terminal?.status === "applied" || terminal?.status === "duplicate");
|
|
798723
|
-
}
|
|
798724
|
-
/** Fast Telegram chat path: direct streamed completion, no tool loop. */
|
|
798725
|
-
async deliverTelegramContractReply(msg, decision2) {
|
|
798726
|
-
const cleaned = cleanTelegramVisibleReply(decision2.replyText ?? "");
|
|
798727
|
-
if (!cleaned) return false;
|
|
798728
|
-
const viewId = `${this.viewIdForMessage(msg)}-contract-reply`;
|
|
798729
|
-
this.subAgentViewCallbacks?.onRegister(
|
|
798730
|
-
viewId,
|
|
798731
|
-
`✈ @${msg.username || "telegram"}`,
|
|
798732
|
-
`Telegram unified chat reply: ${msg.text.slice(0, 160)}`
|
|
798733
|
-
);
|
|
798734
|
-
this.subAgentViewCallbacks?.onWrite(
|
|
798735
|
-
viewId,
|
|
798736
|
-
`delivering input-bound reply ${decision2.decisionId ?? decision2.inputId ?? "unbound"}`
|
|
798737
|
-
);
|
|
798738
|
-
this.subAgentViewCallbacks?.onStatus(viewId, "running");
|
|
798739
|
-
try {
|
|
798740
|
-
const sentMessageId = await this.sendOrEditFinalTelegramHTML(
|
|
798741
|
-
msg,
|
|
798742
|
-
convertMarkdownToTelegramHTML(cleaned),
|
|
798743
|
-
null
|
|
798744
|
-
);
|
|
798745
|
-
if (sentMessageId === null && !msg.guestQueryId) {
|
|
798746
|
-
throw new Error("Telegram unified reply produced no delivery receipt");
|
|
798747
|
-
}
|
|
798748
|
-
const deliveryCommitted = await this.commitTelegramTurnDeliveryReceipt(
|
|
798749
|
-
msg,
|
|
798750
|
-
"visible_reply",
|
|
798751
|
-
sentMessageId !== null ? `telegram-message:${sentMessageId}` : `telegram-guest-query:${msg.guestQueryId}`
|
|
798752
|
-
);
|
|
798753
|
-
if (!deliveryCommitted) {
|
|
798754
|
-
this.subAgentViewCallbacks?.onWrite(
|
|
798755
|
-
viewId,
|
|
798756
|
-
"delivery receipt authority conflict"
|
|
798757
|
-
);
|
|
798758
|
-
}
|
|
798759
|
-
this.recordTelegramAssistantMessage(msg, cleaned, "chat", {
|
|
798760
|
-
messageId: sentMessageId,
|
|
798761
|
-
replyToMessageId: msg.chatType !== "private" ? msg.messageId : void 0
|
|
798762
|
-
});
|
|
798763
|
-
this.subAgentViewCallbacks?.onWrite(viewId, `completed: ${cleaned}`);
|
|
798764
|
-
this.subAgentViewCallbacks?.onStatus(viewId, "completed");
|
|
798765
|
-
this.tuiWrite(
|
|
798766
|
-
() => renderTelegramSubAgentComplete(msg.username, cleaned)
|
|
798767
|
-
);
|
|
798768
|
-
return true;
|
|
798769
|
-
} catch (err) {
|
|
798770
|
-
const errMsg = err instanceof Error ? err.message : String(err);
|
|
798771
|
-
this.subAgentViewCallbacks?.onWrite(viewId, `delivery failed: ${errMsg}`);
|
|
798772
|
-
this.subAgentViewCallbacks?.onStatus(viewId, "failed");
|
|
798773
|
-
throw err;
|
|
798774
|
-
} finally {
|
|
798775
|
-
this.subAgentViewCallbacks?.onComplete(viewId);
|
|
798776
|
-
}
|
|
798777
|
-
}
|
|
798778
|
-
/** Fast Telegram chat path: direct streamed completion, no tool loop. */
|
|
798779
796555
|
async handleTelegramChatCompletion(msg, toolContext, additionalContext = "", authorizationContext = "") {
|
|
798780
796556
|
if (toolContext === "telegram-admin-dm") {
|
|
798781
796557
|
return this.handleTelegramAdminChatAgent(
|
|
@@ -798815,8 +796591,11 @@ ${errMsg}`
|
|
|
798815
796591
|
`route: chat (${this.interactionMode})`
|
|
798816
796592
|
);
|
|
798817
796593
|
this.subAgentViewCallbacks?.onStatus(viewId, "running");
|
|
798818
|
-
if (this.canUseChatActions(msg)) {
|
|
798819
|
-
typingInterval = this.startTypingIndicator(
|
|
796594
|
+
if (this.canUseChatActions(msg) && !this.telegramWorkTypingIntervals.has(sessionKey)) {
|
|
796595
|
+
typingInterval = this.startTypingIndicator(
|
|
796596
|
+
msg.chatId,
|
|
796597
|
+
msg.messageThreadId
|
|
796598
|
+
);
|
|
798820
796599
|
}
|
|
798821
796600
|
this.tuiWrite(
|
|
798822
796601
|
() => renderTelegramSubAgentEvent(
|
|
@@ -798925,11 +796704,6 @@ ${errMsg}`
|
|
|
798925
796704
|
if (sentMessageId === null && !msg.guestQueryId) {
|
|
798926
796705
|
throw new Error("Telegram final reply produced no delivery receipt");
|
|
798927
796706
|
}
|
|
798928
|
-
await this.commitTelegramTurnDeliveryReceipt(
|
|
798929
|
-
msg,
|
|
798930
|
-
"visible_reply",
|
|
798931
|
-
sentMessageId !== null ? `telegram-message:${sentMessageId}` : `telegram-guest-query:${msg.guestQueryId}`
|
|
798932
|
-
);
|
|
798933
796707
|
if (sentMessageId !== null || msg.guestQueryId) {
|
|
798934
796708
|
this.recordTelegramAssistantMessage(msg, cleaned, "chat", {
|
|
798935
796709
|
messageId: sentMessageId,
|
|
@@ -799141,23 +796915,6 @@ ${conversationStream}`
|
|
|
799141
796915
|
subAgent.currentStreamToolNames
|
|
799142
796916
|
);
|
|
799143
796917
|
}
|
|
799144
|
-
ensureTelegramActionSessionRegistry() {
|
|
799145
|
-
if (this.telegramActionSessions) return this.telegramActionSessions;
|
|
799146
|
-
this.telegramActionSessions = new TelegramActionSessionRegistry({
|
|
799147
|
-
ttlMs: 15 * 6e4,
|
|
799148
|
-
maxEntries: 32,
|
|
799149
|
-
create: ({ key, onTypedEvent }) => {
|
|
799150
|
-
const createRunner = this.telegramActionSessionBlueprints.get(key);
|
|
799151
|
-
if (!createRunner) {
|
|
799152
|
-
throw new Error(
|
|
799153
|
-
`Telegram action session ${key} has no active runner blueprint`
|
|
799154
|
-
);
|
|
799155
|
-
}
|
|
799156
|
-
return { runner: createRunner(onTypedEvent) };
|
|
799157
|
-
}
|
|
799158
|
-
});
|
|
799159
|
-
return this.telegramActionSessions;
|
|
799160
|
-
}
|
|
799161
796918
|
/** Run a sub-agent for a Telegram message */
|
|
799162
796919
|
async runSubAgent(msg, subAgent, mediaContext = "", profile = "action", additionalContext = "", authorizationContext = "") {
|
|
799163
796920
|
const config = this.agentConfig;
|
|
@@ -799198,7 +796955,122 @@ ${authorizationContext}` : "",
|
|
|
799198
796955
|
|
|
799199
796956
|
${creativeWorkspace}` : ""
|
|
799200
796957
|
].filter(Boolean).join("\n\n");
|
|
796958
|
+
const backend = new OllamaAgenticBackend(
|
|
796959
|
+
config.backendUrl,
|
|
796960
|
+
config.model,
|
|
796961
|
+
config.apiKey,
|
|
796962
|
+
void 0,
|
|
796963
|
+
config.providerProtocol,
|
|
796964
|
+
config.providerId,
|
|
796965
|
+
config.backendType
|
|
796966
|
+
);
|
|
799201
796967
|
const requestTimeoutMs = config.timeoutMs ?? 3e5;
|
|
796968
|
+
const runner = new AgenticRunner(backend, {
|
|
796969
|
+
surface: isAdminDM || isAdminGroup ? "telegram-admin" : "telegram-public",
|
|
796970
|
+
interactionProfile: profile === "chat" ? "conversation" : "task",
|
|
796971
|
+
// Admin DMs are operator-directed work sessions. A hard turn cap turns
|
|
796972
|
+
// active tool progress into a false "completed" Telegram panel when the
|
|
796973
|
+
// model has not reached task_complete yet. Public/group runs stay bounded.
|
|
796974
|
+
maxTurns: isAdminDM ? 0 : isAdminGroup ? 12 : 8,
|
|
796975
|
+
maxTokens: isAdminDM ? 8192 : 2048,
|
|
796976
|
+
temperature: 0.3,
|
|
796977
|
+
requestTimeoutMs,
|
|
796978
|
+
taskTimeoutMs: isAdminDM ? Math.max(requestTimeoutMs * 3, 9e5) : requestTimeoutMs,
|
|
796979
|
+
compactionThreshold: this.telegramFallbackCompactionThreshold(modelTier2),
|
|
796980
|
+
contextWindowSize,
|
|
796981
|
+
modelTier: modelTier2,
|
|
796982
|
+
disableTodoCompletionGuard: true,
|
|
796983
|
+
disableTodoPlanningNudges: true,
|
|
796984
|
+
// The attention router already classified this private-admin turn as
|
|
796985
|
+
// chat. Accept its first visible assistant answer as the terminal result
|
|
796986
|
+
// instead of spending two more generations demanding task_complete.
|
|
796987
|
+
// Action routes keep the normal explicit completion/evidence boundary.
|
|
796988
|
+
acceptTextOnlyCompletion: isAdminDM && profile === "chat",
|
|
796989
|
+
streamEnabled: true,
|
|
796990
|
+
dynamicContext: runnerDynamicContext,
|
|
796991
|
+
captureContextFrame: true,
|
|
796992
|
+
stateDir: runnerStateDir,
|
|
796993
|
+
sessionId: sessionContext.sessionId,
|
|
796994
|
+
disablePersistentMemory: false,
|
|
796995
|
+
disableCodebaseMap: !isAdminDM,
|
|
796996
|
+
subAgent: !isAdminDM,
|
|
796997
|
+
// Telegram sub-agents run tool-heavy workflows where qwen3 <think>
|
|
796998
|
+
// reasoning is notorious for stalling: the model burns its token
|
|
796999
|
+
// budget inside <think>...</think> and never closes the tag, producing
|
|
797000
|
+
// empty content or 10+ minute replies after 24h. The runner's
|
|
797001
|
+
// computeEffectiveThink() already kills thinking when hasTools=true,
|
|
797002
|
+
// but we set it explicitly here as well so a future no-tools turn
|
|
797003
|
+
// (compaction window, recovery prompt, watchdog probe) inherits the
|
|
797004
|
+
// off default rather than the global config's value.
|
|
797005
|
+
thinking: false,
|
|
797006
|
+
// Surface-specific profile. PUBLIC/GROUP: bounded + fast + provenance
|
|
797007
|
+
// guard off (truthfulness still enforced by the independent fabricated-
|
|
797008
|
+
// provenance audit) so replies are quick and non-fabricated. ADMIN DM:
|
|
797009
|
+
// evidence-heavy — provenance guard on + adversarial backward-pass
|
|
797010
|
+
// approval on, persistence via unlimited maxTurns above. Both keep
|
|
797011
|
+
// brute-force re-engagement and Adversary turn-extension OFF, which is
|
|
797012
|
+
// how Telegram avoids the 60+ turn self-talk loops.
|
|
797013
|
+
...isAdminDM ? TELEGRAM_ADMIN_EVIDENCE_OPTIONS : TELEGRAM_PUBLIC_FAST_OPTIONS,
|
|
797014
|
+
// ── WO #03 (Typed Gateway Event Stream): structured event feed ──
|
|
797015
|
+
onTypedEvent: (event) => {
|
|
797016
|
+
this.forwardTelegramRunnerIntakeLifecycle(event);
|
|
797017
|
+
if (event.type === "steering_lifecycle" && event.reconciliation) {
|
|
797018
|
+
upsertTelegramSteeringReconciliation(
|
|
797019
|
+
subAgent.steeringReconciliations,
|
|
797020
|
+
event.reconciliation
|
|
797021
|
+
);
|
|
797022
|
+
if (isAdminDM) {
|
|
797023
|
+
const state5 = this.ensureTelegramAdminLivePanel(subAgent, msg);
|
|
797024
|
+
state5.steeringReconciliations = [
|
|
797025
|
+
...subAgent.steeringReconciliations.values()
|
|
797026
|
+
];
|
|
797027
|
+
if (state5.activePage !== "response")
|
|
797028
|
+
state5.dirtyPages.response = true;
|
|
797029
|
+
}
|
|
797030
|
+
}
|
|
797031
|
+
if (event.type === "run_finished") {
|
|
797032
|
+
subAgent.runnerCompleted = event.success;
|
|
797033
|
+
subAgent.runnerStatus = event.status;
|
|
797034
|
+
subAgent.completionBoundarySeen = event.status === "completed";
|
|
797035
|
+
}
|
|
797036
|
+
if (event.type === "completion_incomplete_verification") {
|
|
797037
|
+
subAgent.completionBoundarySeen = false;
|
|
797038
|
+
}
|
|
797039
|
+
if (event.type === "completion_accepted") {
|
|
797040
|
+
subAgent.completionBoundarySeen = true;
|
|
797041
|
+
}
|
|
797042
|
+
}
|
|
797043
|
+
});
|
|
797044
|
+
runner.setWorkingDirectory(repoRoot);
|
|
797045
|
+
subAgent.runner = runner;
|
|
797046
|
+
if (subAgent.pendingIntakeRecords.length > 0) {
|
|
797047
|
+
for (const queued of subAgent.pendingIntakeRecords) {
|
|
797048
|
+
this.injectTelegramSteeringInput(
|
|
797049
|
+
subAgent,
|
|
797050
|
+
queued.intake,
|
|
797051
|
+
queued.content
|
|
797052
|
+
);
|
|
797053
|
+
void this.transitionTelegramIntake(
|
|
797054
|
+
queued.intake,
|
|
797055
|
+
"accepted",
|
|
797056
|
+
"initial Telegram intake handed to runner",
|
|
797057
|
+
{ runId: subAgent.runId }
|
|
797058
|
+
);
|
|
797059
|
+
}
|
|
797060
|
+
this.tuiWrite(
|
|
797061
|
+
() => renderTelegramSubAgentEvent(
|
|
797062
|
+
msg.username,
|
|
797063
|
+
`replayed ${subAgent.pendingIntakeRecords.length} typed intake record(s)`
|
|
797064
|
+
)
|
|
797065
|
+
);
|
|
797066
|
+
subAgent.pendingIntakeRecords.length = 0;
|
|
797067
|
+
}
|
|
797068
|
+
if (subAgent.pendingContextPackets.length > 0) {
|
|
797069
|
+
for (const packet of subAgent.pendingContextPackets) {
|
|
797070
|
+
this.injectTelegramRuntimeGuidance(subAgent, packet);
|
|
797071
|
+
}
|
|
797072
|
+
subAgent.pendingContextPackets.length = 0;
|
|
797073
|
+
}
|
|
799202
797074
|
const tools = this.buildSubAgentTools(
|
|
799203
797075
|
ctx3,
|
|
799204
797076
|
repoRoot,
|
|
@@ -799215,102 +797087,12 @@ ${creativeWorkspace}` : ""
|
|
|
799215
797087
|
}
|
|
799216
797088
|
this.subAgentViewCallbacks?.onWrite(
|
|
799217
797089
|
subAgent.viewId,
|
|
799218
|
-
`tool surface: admin
|
|
797090
|
+
`tool surface: admin core ready (${tools.length} tools; ${this.telegramAdminCoreToolNames().join(", ")})`
|
|
799219
797091
|
);
|
|
799220
797092
|
}
|
|
799221
|
-
|
|
799222
|
-
"task_complete",
|
|
799223
|
-
"todo_read",
|
|
799224
|
-
"todo_write",
|
|
799225
|
-
"memory_read",
|
|
799226
|
-
"memory_search",
|
|
799227
|
-
"file_read",
|
|
799228
|
-
"web_search",
|
|
799229
|
-
"telegram",
|
|
799230
|
-
"telegram_send_file"
|
|
799231
|
-
]);
|
|
799232
|
-
const progressiveToolPolicy = {
|
|
799233
|
-
profile: {
|
|
799234
|
-
id: `telegram:${ctx3}`,
|
|
799235
|
-
capabilities: [],
|
|
799236
|
-
maximumAlwaysVisibleTools: 10,
|
|
799237
|
-
maximumPromotedTools: 8
|
|
799238
|
-
},
|
|
799239
|
-
descriptors: [
|
|
799240
|
-
...tools.map((tool) => ({
|
|
799241
|
-
name: tool.name,
|
|
799242
|
-
role: tool.name === "task_complete" ? "completion" : tool.name === "telegram" ? "approval-boundary" : progressiveCoreTools.has(tool.name) ? "core" : "specialized"
|
|
799243
|
-
})),
|
|
799244
|
-
{ name: "tool_search", role: "dispatcher" }
|
|
799245
|
-
]
|
|
799246
|
-
};
|
|
799247
|
-
const handleTypedEvent = (event) => {
|
|
799248
|
-
this.forwardTelegramRunnerIntakeLifecycle(event);
|
|
799249
|
-
if (event.type === "steering_lifecycle" && event.reconciliation) {
|
|
799250
|
-
upsertTelegramSteeringReconciliation(
|
|
799251
|
-
subAgent.steeringReconciliations,
|
|
799252
|
-
event.reconciliation
|
|
799253
|
-
);
|
|
799254
|
-
if (isAdminDM) {
|
|
799255
|
-
const state5 = this.ensureTelegramAdminLivePanel(subAgent, msg);
|
|
799256
|
-
state5.steeringReconciliations = [
|
|
799257
|
-
...subAgent.steeringReconciliations.values()
|
|
799258
|
-
];
|
|
799259
|
-
if (state5.activePage !== "response") state5.dirtyPages.response = true;
|
|
799260
|
-
}
|
|
799261
|
-
}
|
|
799262
|
-
if (event.type === "run_finished") {
|
|
799263
|
-
subAgent.runnerCompleted = event.success;
|
|
799264
|
-
subAgent.runnerStatus = event.status;
|
|
799265
|
-
subAgent.completionBoundarySeen = event.status === "completed";
|
|
799266
|
-
}
|
|
799267
|
-
if (event.type === "completion_incomplete_verification") {
|
|
799268
|
-
subAgent.completionBoundarySeen = false;
|
|
799269
|
-
}
|
|
799270
|
-
if (event.type === "completion_accepted") {
|
|
799271
|
-
subAgent.completionBoundarySeen = true;
|
|
799272
|
-
}
|
|
799273
|
-
};
|
|
799274
|
-
const createRunner = (onTypedEvent) => {
|
|
799275
|
-
const backend = new OllamaAgenticBackend(
|
|
799276
|
-
config.backendUrl,
|
|
799277
|
-
config.model,
|
|
799278
|
-
config.apiKey,
|
|
799279
|
-
void 0,
|
|
799280
|
-
config.providerProtocol,
|
|
799281
|
-
config.providerId,
|
|
799282
|
-
config.backendType
|
|
799283
|
-
);
|
|
799284
|
-
return new AgenticRunner(backend, {
|
|
799285
|
-
surface: isAdminDM || isAdminGroup ? "telegram-admin" : "telegram-public",
|
|
799286
|
-
interactionProfile: profile === "chat" ? "conversation" : "task",
|
|
799287
|
-
maxTurns: isAdminDM ? 0 : isAdminGroup ? 12 : 8,
|
|
799288
|
-
maxTokens: isAdminDM ? 8192 : 2048,
|
|
799289
|
-
temperature: 0.3,
|
|
799290
|
-
requestTimeoutMs,
|
|
799291
|
-
taskTimeoutMs: isAdminDM ? Math.max(requestTimeoutMs * 3, 9e5) : requestTimeoutMs,
|
|
799292
|
-
compactionThreshold: this.telegramFallbackCompactionThreshold(modelTier2),
|
|
799293
|
-
contextWindowSize,
|
|
799294
|
-
modelTier: modelTier2,
|
|
799295
|
-
disableTodoCompletionGuard: true,
|
|
799296
|
-
disableTodoPlanningNudges: true,
|
|
799297
|
-
acceptTextOnlyCompletion: isAdminDM && profile === "chat",
|
|
799298
|
-
streamEnabled: true,
|
|
799299
|
-
dynamicContext: profile === "action" ? "" : runnerDynamicContext,
|
|
799300
|
-
progressiveToolPolicy,
|
|
799301
|
-
captureContextFrame: true,
|
|
799302
|
-
stateDir: runnerStateDir,
|
|
799303
|
-
sessionId: sessionContext.sessionId,
|
|
799304
|
-
disablePersistentMemory: false,
|
|
799305
|
-
disableCodebaseMap: !isAdminDM,
|
|
799306
|
-
subAgent: !isAdminDM,
|
|
799307
|
-
thinking: false,
|
|
799308
|
-
...isAdminDM ? TELEGRAM_ADMIN_EVIDENCE_OPTIONS : TELEGRAM_PUBLIC_FAST_OPTIONS,
|
|
799309
|
-
onTypedEvent
|
|
799310
|
-
});
|
|
799311
|
-
};
|
|
797093
|
+
runner.registerTools(tools);
|
|
799312
797094
|
const telegramSteeringFilter = new SteeringReconciliationStreamFilter();
|
|
799313
|
-
|
|
797095
|
+
runner.onEvent((event) => {
|
|
799314
797096
|
if (subAgent.aborted) return;
|
|
799315
797097
|
subAgent.lastActivityMs = Date.now();
|
|
799316
797098
|
let suppressExternalEvent = false;
|
|
@@ -799462,94 +797244,7 @@ ${creativeWorkspace}` : ""
|
|
|
799462
797244
|
});
|
|
799463
797245
|
}
|
|
799464
797246
|
}
|
|
799465
|
-
};
|
|
799466
|
-
const prepareRunnerForTurn = (currentRunner) => {
|
|
799467
|
-
currentRunner.prepareReusableRun({
|
|
799468
|
-
dynamicContext: runnerDynamicContext,
|
|
799469
|
-
tools,
|
|
799470
|
-
workingDirectory: repoRoot
|
|
799471
|
-
});
|
|
799472
|
-
subAgent.runner = currentRunner;
|
|
799473
|
-
if (subAgent.pendingIntakeRecords.length > 0) {
|
|
799474
|
-
for (const queued of subAgent.pendingIntakeRecords) {
|
|
799475
|
-
this.injectTelegramSteeringInput(
|
|
799476
|
-
subAgent,
|
|
799477
|
-
queued.intake,
|
|
799478
|
-
queued.content
|
|
799479
|
-
);
|
|
799480
|
-
void this.transitionTelegramIntake(
|
|
799481
|
-
queued.intake,
|
|
799482
|
-
"accepted",
|
|
799483
|
-
"initial Telegram intake handed to runner",
|
|
799484
|
-
{ runId: subAgent.runId }
|
|
799485
|
-
);
|
|
799486
|
-
}
|
|
799487
|
-
this.tuiWrite(
|
|
799488
|
-
() => renderTelegramSubAgentEvent(
|
|
799489
|
-
msg.username,
|
|
799490
|
-
`replayed ${subAgent.pendingIntakeRecords.length} typed intake record(s)`
|
|
799491
|
-
)
|
|
799492
|
-
);
|
|
799493
|
-
subAgent.pendingIntakeRecords.length = 0;
|
|
799494
|
-
}
|
|
799495
|
-
if (subAgent.pendingContextPackets.length > 0) {
|
|
799496
|
-
for (const packet of subAgent.pendingContextPackets) {
|
|
799497
|
-
this.injectTelegramRuntimeGuidance(subAgent, packet);
|
|
799498
|
-
}
|
|
799499
|
-
subAgent.pendingContextPackets.length = 0;
|
|
799500
|
-
}
|
|
799501
|
-
};
|
|
799502
|
-
let runner = null;
|
|
799503
|
-
let actionLease = null;
|
|
799504
|
-
if (profile === "action") {
|
|
799505
|
-
const target = {
|
|
799506
|
-
chatSessionKey: sessionContext.sessionKey,
|
|
799507
|
-
principalKey: telegramSocialActorKey(
|
|
799508
|
-
this.telegramMessageSocialActorInput(msg)
|
|
799509
|
-
)
|
|
799510
|
-
};
|
|
799511
|
-
const key = telegramActionSessionKey(target);
|
|
799512
|
-
const compatibilityKey = createHash76("sha256").update(
|
|
799513
|
-
JSON.stringify({
|
|
799514
|
-
schema: "telegram-action-runner.v1",
|
|
799515
|
-
backendUrl: config.backendUrl,
|
|
799516
|
-
backendType: config.backendType,
|
|
799517
|
-
providerProtocol: config.providerProtocol,
|
|
799518
|
-
providerId: config.providerId,
|
|
799519
|
-
model: config.model,
|
|
799520
|
-
surface: isAdminDM || isAdminGroup ? "telegram-admin" : "telegram-public",
|
|
799521
|
-
profile,
|
|
799522
|
-
stateDir: runnerStateDir ?? "",
|
|
799523
|
-
sessionId: sessionContext.sessionId,
|
|
799524
|
-
contextWindowSize,
|
|
799525
|
-
modelTier: modelTier2,
|
|
799526
|
-
toolNames: tools.map((tool) => tool.name).sort(),
|
|
799527
|
-
toolExposure: progressiveToolPolicy.descriptors.map((descriptor2) => [descriptor2.name, descriptor2.role]).sort(([left], [right]) => left.localeCompare(right))
|
|
799528
|
-
})
|
|
799529
|
-
).digest("hex");
|
|
799530
|
-
this.telegramActionSessionBlueprints.set(key, createRunner);
|
|
799531
|
-
try {
|
|
799532
|
-
const acquired = this.ensureTelegramActionSessionRegistry().acquire({
|
|
799533
|
-
target,
|
|
799534
|
-
ownerId: subAgent.runId,
|
|
799535
|
-
compatibilityKey,
|
|
799536
|
-
onEvent: handleRunnerEvent,
|
|
799537
|
-
onTypedEvent: handleTypedEvent
|
|
799538
|
-
});
|
|
799539
|
-
if (acquired.status !== "acquired") {
|
|
799540
|
-
throw new Error(
|
|
799541
|
-
`Telegram action session admission ${acquired.status}: ${acquired.reason}`
|
|
799542
|
-
);
|
|
799543
|
-
}
|
|
799544
|
-
actionLease = acquired.lease;
|
|
799545
|
-
} finally {
|
|
799546
|
-
this.telegramActionSessionBlueprints.delete(key);
|
|
799547
|
-
}
|
|
799548
|
-
} else {
|
|
799549
|
-
runner = createRunner(handleTypedEvent);
|
|
799550
|
-
runner.onEvent(handleRunnerEvent);
|
|
799551
|
-
prepareRunnerForTurn(runner);
|
|
799552
|
-
}
|
|
797247
|
+
});
|
|
799553
797248
|
const chatLabel = isGroup ? ` in group "${msg.chatTitle || "unknown"}"` : "";
|
|
799554
797249
|
const currentTelegramPrompt = this.formatTelegramCurrentMessageForPrompt(
|
|
799555
797250
|
sessionContext.sessionKey,
|
|
@@ -799604,20 +797299,11 @@ ${additionalContext}`;
|
|
|
799604
797299
|
toolContext: ctx3
|
|
799605
797300
|
}
|
|
799606
797301
|
},
|
|
799607
|
-
() =>
|
|
799608
|
-
|
|
799609
|
-
|
|
799610
|
-
|
|
799611
|
-
|
|
799612
|
-
actualUserGoal,
|
|
799613
|
-
prepare: prepareRunnerForTurn
|
|
799614
|
-
});
|
|
799615
|
-
}
|
|
799616
|
-
if (!runner) {
|
|
799617
|
-
throw new Error("Telegram runner was not initialized");
|
|
799618
|
-
}
|
|
799619
|
-
return runner.run(userPrompt, void 0, actualUserGoal);
|
|
799620
|
-
}
|
|
797302
|
+
() => runner.run(
|
|
797303
|
+
userPrompt,
|
|
797304
|
+
void 0,
|
|
797305
|
+
profile === "chat" ? msg.text : this.buildTelegramRunnerGoal(sessionContext.sessionKey, msg)
|
|
797306
|
+
)
|
|
799621
797307
|
);
|
|
799622
797308
|
this.retainTelegramVisibleReplyFromCompletedStream(subAgent);
|
|
799623
797309
|
subAgent.runnerCompleted = result.completed;
|
|
@@ -801757,7 +799443,7 @@ Scoped workspace: ${scopedRoot}`,
|
|
|
801757
799443
|
);
|
|
801758
799444
|
}
|
|
801759
799445
|
telegramModerationActionDigest(action) {
|
|
801760
|
-
return
|
|
799446
|
+
return createHash75("sha256").update(JSON.stringify(action)).digest("hex");
|
|
801761
799447
|
}
|
|
801762
799448
|
async requireTelegramModerationGroup(chatId) {
|
|
801763
799449
|
const result = await this.apiCall("getChat", { chat_id: chatId });
|
|
@@ -808492,7 +806178,7 @@ import { cwd } from "node:process";
|
|
|
808492
806178
|
import { resolve as resolve85, join as join190, dirname as dirname69, extname as extname23, relative as relative24, sep as sep11 } from "node:path";
|
|
808493
806179
|
import { createRequire as createRequire9 } from "node:module";
|
|
808494
806180
|
import { fileURLToPath as fileURLToPath33 } from "node:url";
|
|
808495
|
-
import { createHash as
|
|
806181
|
+
import { createHash as createHash76 } from "node:crypto";
|
|
808496
806182
|
import {
|
|
808497
806183
|
readFileSync as readFileSync152,
|
|
808498
806184
|
writeFileSync as writeFileSync103,
|
|
@@ -809365,7 +807051,7 @@ function truncateSubAgentViewText(s2, n2) {
|
|
|
809365
807051
|
return s2.length > n2 ? `${s2.slice(0, n2)}…` : s2;
|
|
809366
807052
|
}
|
|
809367
807053
|
function childAgentTaskHash(task) {
|
|
809368
|
-
return
|
|
807054
|
+
return createHash76("sha256").update(task).digest("hex").slice(0, 12);
|
|
809369
807055
|
}
|
|
809370
807056
|
function stripAnsiForParentContext(value2) {
|
|
809371
807057
|
return value2.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");
|
|
@@ -819196,13 +816882,13 @@ ${taskInput}`;
|
|
|
819196
816882
|
writeContent(() => renderError(errMsg));
|
|
819197
816883
|
if (failureStore) {
|
|
819198
816884
|
try {
|
|
819199
|
-
const { createHash:
|
|
816885
|
+
const { createHash: createHash81 } = await import("node:crypto");
|
|
819200
816886
|
failureStore.insert({
|
|
819201
816887
|
taskId: "",
|
|
819202
816888
|
sessionId: `${Date.now()}`,
|
|
819203
816889
|
repoRoot,
|
|
819204
816890
|
failureType: "runtime-error",
|
|
819205
|
-
fingerprint:
|
|
816891
|
+
fingerprint: createHash81("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
|
|
819206
816892
|
filePath: null,
|
|
819207
816893
|
errorMessage: errMsg.slice(0, 500),
|
|
819208
816894
|
context: null,
|
|
@@ -821027,14 +818713,14 @@ var init_access_policy = __esm({
|
|
|
821027
818713
|
});
|
|
821028
818714
|
|
|
821029
818715
|
// packages/cli/src/api/project-preferences.ts
|
|
821030
|
-
import { createHash as
|
|
818716
|
+
import { createHash as createHash77 } from "node:crypto";
|
|
821031
818717
|
import { existsSync as existsSync182, mkdirSync as mkdirSync117, readFileSync as readFileSync154, renameSync as renameSync31, writeFileSync as writeFileSync105, unlinkSync as unlinkSync46 } from "node:fs";
|
|
821032
818718
|
import { homedir as homedir65 } from "node:os";
|
|
821033
818719
|
import { join as join193, resolve as resolve89 } from "node:path";
|
|
821034
818720
|
import { randomUUID as randomUUID34 } from "node:crypto";
|
|
821035
818721
|
function projectKey(root) {
|
|
821036
818722
|
const canonical3 = resolve89(root);
|
|
821037
|
-
return
|
|
818723
|
+
return createHash77("sha256").update(canonical3).digest("hex").slice(0, 16);
|
|
821038
818724
|
}
|
|
821039
818725
|
function projectDir(root) {
|
|
821040
818726
|
return join193(PROJECTS_DIR, projectKey(root));
|
|
@@ -821125,7 +818811,7 @@ import { existsSync as existsSync183, mkdirSync as mkdirSync118, readFileSync as
|
|
|
821125
818811
|
import { homedir as homedir66 } from "node:os";
|
|
821126
818812
|
import { dirname as dirname70, join as join194 } from "node:path";
|
|
821127
818813
|
import { fileURLToPath as fileURLToPath34 } from "node:url";
|
|
821128
|
-
import { createHash as
|
|
818814
|
+
import { createHash as createHash78 } from "node:crypto";
|
|
821129
818815
|
function home() {
|
|
821130
818816
|
return process.env["OMNIUS_HOME"]?.trim() || join194(homedir66(), ".omnius");
|
|
821131
818817
|
}
|
|
@@ -821309,7 +818995,7 @@ async function ensureJetPackTorchvision(python2) {
|
|
|
821309
818995
|
"OpenCLIP requires CUDA-compatible torchvision. Install the JetPack vendor torchvision for OMNIUS_VISION_PYTHON, or set OMNIUS_VISION_TORCHVISION_WHEEL to a local wheel and OMNIUS_VISION_TORCHVISION_WHEEL_SHA256 to its SHA-256. Generic PyPI torchvision is intentionally blocked."
|
|
821310
818996
|
);
|
|
821311
818997
|
}
|
|
821312
|
-
const actualSha256 =
|
|
818998
|
+
const actualSha256 = createHash78("sha256").update(readFileSync155(wheel)).digest("hex");
|
|
821313
818999
|
if (actualSha256 !== expectedSha256) {
|
|
821314
819000
|
throw new VisionEmbeddingRuntimeError(
|
|
821315
819001
|
"vision_runtime_not_ready",
|
|
@@ -822239,7 +819925,7 @@ var init_disk_task_output = __esm({
|
|
|
822239
819925
|
});
|
|
822240
819926
|
|
|
822241
819927
|
// packages/cli/src/api/http.ts
|
|
822242
|
-
import { createHash as
|
|
819928
|
+
import { createHash as createHash79 } from "node:crypto";
|
|
822243
819929
|
function problemDetails(opts) {
|
|
822244
819930
|
const p2 = {
|
|
822245
819931
|
type: opts.type ?? "about:blank",
|
|
@@ -822302,7 +819988,7 @@ function paginated(items, page2, total) {
|
|
|
822302
819988
|
}
|
|
822303
819989
|
function computeEtag(payload) {
|
|
822304
819990
|
const json2 = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
822305
|
-
const hash2 =
|
|
819991
|
+
const hash2 = createHash79("sha1").update(json2).digest("hex").slice(0, 16);
|
|
822306
819992
|
return `W/"${hash2}"`;
|
|
822307
819993
|
}
|
|
822308
819994
|
function checkNotModified(req3, res, etag) {
|
|
@@ -846072,7 +843758,7 @@ import {
|
|
|
846072
843758
|
readSync as readSync5,
|
|
846073
843759
|
closeSync as closeSync12
|
|
846074
843760
|
} from "node:fs";
|
|
846075
|
-
import { createHash as
|
|
843761
|
+
import { createHash as createHash80, randomBytes as randomBytes31, randomUUID as randomUUID35, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
846076
843762
|
function memoryDbPaths3(baseDir = process.cwd()) {
|
|
846077
843763
|
const dir = join206(baseDir, ".omnius");
|
|
846078
843764
|
return {
|
|
@@ -846098,7 +843784,7 @@ function readServerPackageIdentity() {
|
|
|
846098
843784
|
return {
|
|
846099
843785
|
version: pkg.version ?? "0.0.0",
|
|
846100
843786
|
packagePath: pkgPath,
|
|
846101
|
-
packageHash:
|
|
843787
|
+
packageHash: createHash80("sha256").update(raw).digest("hex")
|
|
846102
843788
|
};
|
|
846103
843789
|
}
|
|
846104
843790
|
} catch {
|
|
@@ -855900,7 +853586,7 @@ function listScheduledTasks() {
|
|
|
855900
853586
|
);
|
|
855901
853587
|
const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
|
|
855902
853588
|
const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
|
|
855903
|
-
const fallbackId =
|
|
853589
|
+
const fallbackId = createHash80("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
|
|
855904
853590
|
const uid = realId || fallbackId;
|
|
855905
853591
|
const key = `${uid}`;
|
|
855906
853592
|
if (seen.has(key)) return;
|
|
@@ -856038,8 +853724,8 @@ function deleteScheduledById(id2) {
|
|
|
856038
853724
|
if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id))
|
|
856039
853725
|
candidates.push(entry.id);
|
|
856040
853726
|
try {
|
|
856041
|
-
const { createHash:
|
|
856042
|
-
const fallback =
|
|
853727
|
+
const { createHash: createHash81 } = require4("node:crypto");
|
|
853728
|
+
const fallback = createHash81("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
|
|
856043
853729
|
if (!candidates.includes(fallback)) candidates.push(fallback);
|
|
856044
853730
|
} catch {
|
|
856045
853731
|
}
|
|
@@ -859299,8 +856985,8 @@ var scriptPath = process.argv[1] ?? "";
|
|
|
859299
856985
|
var isMain2 = scriptPath.endsWith("index.js") || scriptPath.endsWith("index.ts") || scriptPath.endsWith("omnius-bin") || scriptPath.includes("omnius") || scriptPath.includes("/omnius");
|
|
859300
856986
|
function crashLog(label, err) {
|
|
859301
856987
|
const msg = err instanceof Error ? err.stack ?? err.message : String(err);
|
|
859302
|
-
const
|
|
859303
|
-
const logLine = `[${
|
|
856988
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
856989
|
+
const logLine = `[${timestamp}] ${label}: ${msg}
|
|
859304
856990
|
`;
|
|
859305
856991
|
try {
|
|
859306
856992
|
const { appendFileSync: appendFileSync25, mkdirSync: mkdirSync130 } = __require("node:fs");
|