omnius 1.0.71 → 1.0.73

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 CHANGED
@@ -87766,7 +87766,7 @@ var require_axios = __commonJS({
87766
87766
  }
87767
87767
  var isString = typeOfTest("string");
87768
87768
  var isFunction$1 = typeOfTest("function");
87769
- var isNumber = typeOfTest("number");
87769
+ var isNumber2 = typeOfTest("number");
87770
87770
  var isObject = (thing) => thing !== null && typeof thing === "object";
87771
87771
  var isBoolean = (thing) => thing === true || thing === false;
87772
87772
  var isPlainObject = (val) => {
@@ -87966,7 +87966,7 @@ var require_axios = __commonJS({
87966
87966
  if (!thing) return null;
87967
87967
  if (isArray(thing)) return thing;
87968
87968
  let i2 = thing.length;
87969
- if (!isNumber(i2)) return null;
87969
+ if (!isNumber2(i2)) return null;
87970
87970
  const arr = new Array(i2);
87971
87971
  while (i2-- > 0) {
87972
87972
  arr[i2] = thing[i2];
@@ -88107,7 +88107,7 @@ var require_axios = __commonJS({
88107
88107
  isFormData,
88108
88108
  isArrayBufferView,
88109
88109
  isString,
88110
- isNumber,
88110
+ isNumber: isNumber2,
88111
88111
  isBoolean,
88112
88112
  isObject,
88113
88113
  isPlainObject,
@@ -92298,7 +92298,7 @@ var require_auto = __commonJS({
92298
92298
  // ../node_modules/acme-client/src/client.js
92299
92299
  var require_client = __commonJS({
92300
92300
  "../node_modules/acme-client/src/client.js"(exports, module) {
92301
- var { createHash: createHash28 } = __require("crypto");
92301
+ var { createHash: createHash29 } = __require("crypto");
92302
92302
  var { getPemBodyAsB64u } = require_crypto();
92303
92303
  var { log: log22 } = require_logger();
92304
92304
  var HttpClient = require_http();
@@ -92609,14 +92609,14 @@ var require_client = __commonJS({
92609
92609
  */
92610
92610
  async getChallengeKeyAuthorization(challenge) {
92611
92611
  const jwk = this.http.getJwk();
92612
- const keysum = createHash28("sha256").update(JSON.stringify(jwk));
92612
+ const keysum = createHash29("sha256").update(JSON.stringify(jwk));
92613
92613
  const thumbprint = keysum.digest("base64url");
92614
92614
  const result = `${challenge.token}.${thumbprint}`;
92615
92615
  if (challenge.type === "http-01") {
92616
92616
  return result;
92617
92617
  }
92618
92618
  if (challenge.type === "dns-01") {
92619
- return createHash28("sha256").update(result).digest("base64url");
92619
+ return createHash29("sha256").update(result).digest("base64url");
92620
92620
  }
92621
92621
  if (challenge.type === "tls-alpn-01") {
92622
92622
  return result;
@@ -235296,7 +235296,7 @@ var require_websocket2 = __commonJS({
235296
235296
  var http6 = __require("http");
235297
235297
  var net5 = __require("net");
235298
235298
  var tls2 = __require("tls");
235299
- var { randomBytes: randomBytes27, createHash: createHash28 } = __require("crypto");
235299
+ var { randomBytes: randomBytes27, createHash: createHash29 } = __require("crypto");
235300
235300
  var { Duplex: Duplex3, Readable } = __require("stream");
235301
235301
  var { URL: URL3 } = __require("url");
235302
235302
  var PerMessageDeflate3 = require_permessage_deflate2();
@@ -235956,7 +235956,7 @@ var require_websocket2 = __commonJS({
235956
235956
  abortHandshake(websocket, socket, "Invalid Upgrade header");
235957
235957
  return;
235958
235958
  }
235959
- const digest3 = createHash28("sha1").update(key + GUID).digest("base64");
235959
+ const digest3 = createHash29("sha1").update(key + GUID).digest("base64");
235960
235960
  if (res.headers["sec-websocket-accept"] !== digest3) {
235961
235961
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
235962
235962
  return;
@@ -236323,7 +236323,7 @@ var require_websocket_server = __commonJS({
236323
236323
  var EventEmitter14 = __require("events");
236324
236324
  var http6 = __require("http");
236325
236325
  var { Duplex: Duplex3 } = __require("stream");
236326
- var { createHash: createHash28 } = __require("crypto");
236326
+ var { createHash: createHash29 } = __require("crypto");
236327
236327
  var extension3 = require_extension2();
236328
236328
  var PerMessageDeflate3 = require_permessage_deflate2();
236329
236329
  var subprotocol3 = require_subprotocol();
@@ -236624,7 +236624,7 @@ var require_websocket_server = __commonJS({
236624
236624
  );
236625
236625
  }
236626
236626
  if (this._state > RUNNING) return abortHandshake(socket, 503);
236627
- const digest3 = createHash28("sha1").update(key + GUID).digest("base64");
236627
+ const digest3 = createHash29("sha1").update(key + GUID).digest("base64");
236628
236628
  const headers = [
236629
236629
  "HTTP/1.1 101 Switching Protocols",
236630
236630
  "Upgrade: websocket",
@@ -243390,15 +243390,15 @@ var require_is_number = __commonJS({
243390
243390
  var require_to_regex_range = __commonJS({
243391
243391
  "../node_modules/to-regex-range/index.js"(exports, module) {
243392
243392
  "use strict";
243393
- var isNumber = require_is_number();
243393
+ var isNumber2 = require_is_number();
243394
243394
  var toRegexRange = (min, max, options2) => {
243395
- if (isNumber(min) === false) {
243395
+ if (isNumber2(min) === false) {
243396
243396
  throw new TypeError("toRegexRange: expected the first argument to be a number");
243397
243397
  }
243398
243398
  if (max === void 0 || min === max) {
243399
243399
  return String(min);
243400
243400
  }
243401
- if (isNumber(max) === false) {
243401
+ if (isNumber2(max) === false) {
243402
243402
  throw new TypeError("toRegexRange: expected the second argument to be a number.");
243403
243403
  }
243404
243404
  let opts = { relaxZeros: true, ...options2 };
@@ -243610,7 +243610,7 @@ var require_fill_range = __commonJS({
243610
243610
  var isValidValue = (value2) => {
243611
243611
  return typeof value2 === "number" || typeof value2 === "string" && value2 !== "";
243612
243612
  };
243613
- var isNumber = (num) => Number.isInteger(+num);
243613
+ var isNumber2 = (num) => Number.isInteger(+num);
243614
243614
  var zeros = (input) => {
243615
243615
  let value2 = `${input}`;
243616
243616
  let index = -1;
@@ -243738,7 +243738,7 @@ var require_fill_range = __commonJS({
243738
243738
  return range;
243739
243739
  };
243740
243740
  var fillLetters = (start2, end, step = 1, options2 = {}) => {
243741
- if (!isNumber(start2) && start2.length > 1 || !isNumber(end) && end.length > 1) {
243741
+ if (!isNumber2(start2) && start2.length > 1 || !isNumber2(end) && end.length > 1) {
243742
243742
  return invalidRange(start2, end, options2);
243743
243743
  }
243744
243744
  let format3 = options2.transform || ((val) => String.fromCharCode(val));
@@ -243778,11 +243778,11 @@ var require_fill_range = __commonJS({
243778
243778
  let opts = { ...options2 };
243779
243779
  if (opts.capture === true) opts.wrap = true;
243780
243780
  step = step || opts.step || 1;
243781
- if (!isNumber(step)) {
243781
+ if (!isNumber2(step)) {
243782
243782
  if (step != null && !isObject(step)) return invalidStep(step, opts);
243783
243783
  return fill(start2, end, 1, step);
243784
243784
  }
243785
- if (isNumber(start2) && isNumber(end)) {
243785
+ if (isNumber2(start2) && isNumber2(end)) {
243786
243786
  return fillNumbers(start2, end, step, opts);
243787
243787
  }
243788
243788
  return fillLetters(start2, end, Math.max(Math.abs(step), 1), opts);
@@ -249431,13 +249431,13 @@ Justification: ${justification || "(none provided)"}`,
249431
249431
  }
249432
249432
  const snapshot = JSON.stringify(this.selfState, null, 2);
249433
249433
  try {
249434
- const { createHash: createHash28 } = await import("node:crypto");
249434
+ const { createHash: createHash29 } = await import("node:crypto");
249435
249435
  const snapshotDir = join30(this.cwd, ".omnius", "identity", "snapshots");
249436
249436
  await mkdir7(snapshotDir, { recursive: true });
249437
249437
  const version4 = this.selfState.version;
249438
249438
  const snapshotPath = join30(snapshotDir, `v${version4}.json`);
249439
249439
  await writeFile12(snapshotPath, snapshot, "utf8");
249440
- const hash = createHash28("sha256").update(snapshot).digest("hex");
249440
+ const hash = createHash29("sha256").update(snapshot).digest("hex");
249441
249441
  await writeFile12(join30(this.cwd, ".omnius", "identity", "latest-hash.txt"), hash, "utf8");
249442
249442
  let ipfsCid = "";
249443
249443
  try {
@@ -249570,8 +249570,8 @@ New: ${newNarrative.slice(0, 200)}...`,
249570
249570
  }
249571
249571
  // ── Helpers ──────────────────────────────────────────────────────────────
249572
249572
  createDefaultState() {
249573
- const { createHash: createHash28 } = __require("node:crypto");
249574
- const machineId = createHash28("sha256").update(this.cwd).digest("hex").slice(0, 12);
249573
+ const { createHash: createHash29 } = __require("node:crypto");
249574
+ const machineId = createHash29("sha256").update(this.cwd).digest("hex").slice(0, 12);
249575
249575
  return {
249576
249576
  self_id: `omnius-${machineId}`,
249577
249577
  version: 1,
@@ -249653,9 +249653,9 @@ New: ${newNarrative.slice(0, 200)}...`,
249653
249653
  let cid;
249654
249654
  if (this.selfState.version > prevVersion) {
249655
249655
  try {
249656
- const { createHash: createHash28 } = await import("node:crypto");
249656
+ const { createHash: createHash29 } = await import("node:crypto");
249657
249657
  const stateJson = JSON.stringify(this.selfState);
249658
- const hash = createHash28("sha256").update(stateJson).digest("hex").slice(0, 32);
249658
+ const hash = createHash29("sha256").update(stateJson).digest("hex").slice(0, 32);
249659
249659
  const cidsPath = join30(this.cwd, ".omnius", "identity", "cids.json");
249660
249660
  const cidsData = { latest: "", hash, version: this.selfState.version };
249661
249661
  try {
@@ -270064,7 +270064,7 @@ var require_typescript = __commonJS({
270064
270064
  commandLineOptionOfCustomType: () => commandLineOptionOfCustomType,
270065
270065
  commentPragmas: () => commentPragmas,
270066
270066
  commonOptionsWithBuild: () => commonOptionsWithBuild,
270067
- compact: () => compact2,
270067
+ compact: () => compact3,
270068
270068
  compareBooleans: () => compareBooleans,
270069
270069
  compareComparableValues: () => compareComparableValues,
270070
270070
  compareDataObjects: () => compareDataObjects,
@@ -271372,7 +271372,7 @@ var require_typescript = __commonJS({
271372
271372
  isNonStaticMethodOrAccessorWithPrivateName: () => isNonStaticMethodOrAccessorWithPrivateName,
271373
271373
  isNotEmittedStatement: () => isNotEmittedStatement,
271374
271374
  isNullishCoalesce: () => isNullishCoalesce,
271375
- isNumber: () => isNumber,
271375
+ isNumber: () => isNumber2,
271376
271376
  isNumericLiteral: () => isNumericLiteral,
271377
271377
  isNumericLiteralName: () => isNumericLiteralName,
271378
271378
  isObjectBindingElementWithoutPropertyName: () => isObjectBindingElementWithoutPropertyName,
@@ -272579,7 +272579,7 @@ var require_typescript = __commonJS({
272579
272579
  }
272580
272580
  return true;
272581
272581
  }
272582
- function compact2(array) {
272582
+ function compact3(array) {
272583
272583
  let result;
272584
272584
  if (array !== void 0) {
272585
272585
  for (let i2 = 0; i2 < array.length; i2++) {
@@ -273114,7 +273114,7 @@ var require_typescript = __commonJS({
273114
273114
  function isString(text) {
273115
273115
  return typeof text === "string";
273116
273116
  }
273117
- function isNumber(x) {
273117
+ function isNumber2(x) {
273118
273118
  return typeof x === "number";
273119
273119
  }
273120
273120
  function tryCast(value2, test) {
@@ -378650,7 +378650,7 @@ ${lanes.join("\n")}
378650
378650
  node.operatorToken,
378651
378651
  visitNode(node.right, visitor, isExpression)
378652
378652
  );
378653
- const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact2([...pendingExpressions, node])) : node;
378653
+ const expr = some(pendingExpressions) ? factory2.inlineExpressions(compact3([...pendingExpressions, node])) : node;
378654
378654
  pendingExpressions = savedPendingExpressions;
378655
378655
  return expr;
378656
378656
  }
@@ -398919,7 +398919,7 @@ ${lanes.join("\n")}
398919
398919
  let parameterProperties;
398920
398920
  if (ctor) {
398921
398921
  const oldDiag2 = getSymbolAccessibilityDiagnostic;
398922
- parameterProperties = compact2(flatMap(ctor.parameters, (param) => {
398922
+ parameterProperties = compact3(flatMap(ctor.parameters, (param) => {
398923
398923
  if (!hasSyntacticModifier(
398924
398924
  param,
398925
398925
  31
@@ -410266,8 +410266,8 @@ ${lanes.join("\n")}
410266
410266
  return result;
410267
410267
  }
410268
410268
  function getPendingEmitKind(optionsOrEmitKind, oldOptionsOrEmitKind) {
410269
- const oldEmitKind = oldOptionsOrEmitKind && (isNumber(oldOptionsOrEmitKind) ? oldOptionsOrEmitKind : getBuilderFileEmit(oldOptionsOrEmitKind));
410270
- const emitKind = isNumber(optionsOrEmitKind) ? optionsOrEmitKind : getBuilderFileEmit(optionsOrEmitKind);
410269
+ const oldEmitKind = oldOptionsOrEmitKind && (isNumber2(oldOptionsOrEmitKind) ? oldOptionsOrEmitKind : getBuilderFileEmit(oldOptionsOrEmitKind));
410270
+ const emitKind = isNumber2(optionsOrEmitKind) ? optionsOrEmitKind : getBuilderFileEmit(optionsOrEmitKind);
410271
410271
  if (oldEmitKind === emitKind) return 0;
410272
410272
  if (!oldEmitKind || !emitKind) return emitKind;
410273
410273
  const diff = oldEmitKind ^ emitKind;
@@ -410998,7 +410998,7 @@ ${lanes.join("\n")}
410998
410998
  if (isLastStartEnd && last22[1] === fileId - 1) return last22[1] = fileId;
410999
410999
  if (isLastStartEnd || root.length === 1 || last22 !== fileId - 1) return root.push(fileId);
411000
411000
  const lastButOne = root[root.length - 2];
411001
- if (!isNumber(lastButOne) || lastButOne !== last22 - 1) return root.push(fileId);
411001
+ if (!isNumber2(lastButOne) || lastButOne !== last22 - 1) return root.push(fileId);
411002
411002
  root[root.length - 2] = [lastButOne, fileId];
411003
411003
  return root.length = root.length - 1;
411004
411004
  }
@@ -411598,7 +411598,7 @@ ${lanes.join("\n")}
411598
411598
  return isString(fileInfo) ? { version: fileInfo, signature: fileInfo, affectsGlobalScope: void 0, impliedFormat: void 0 } : isString(fileInfo.signature) ? fileInfo : { version: fileInfo.version, signature: fileInfo.signature === false ? void 0 : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat };
411599
411599
  }
411600
411600
  function toBuilderFileEmit(value2, fullEmitForOptions) {
411601
- return isNumber(value2) ? fullEmitForOptions : value2[1] || 24;
411601
+ return isNumber2(value2) ? fullEmitForOptions : value2[1] || 24;
411602
411602
  }
411603
411603
  function toProgramEmitPending(value2, options2) {
411604
411604
  return !value2 ? getBuilderFileEmit(options2 || {}) : value2;
@@ -411641,7 +411641,7 @@ ${lanes.join("\n")}
411641
411641
  if (emitSignatures && stateFileInfo.signature) emitSignatures.set(path12, stateFileInfo.signature);
411642
411642
  });
411643
411643
  (_d = buildInfo.emitSignatures) == null ? void 0 : _d.forEach((value2) => {
411644
- if (isNumber(value2)) emitSignatures.delete(toFilePath(value2));
411644
+ if (isNumber2(value2)) emitSignatures.delete(toFilePath(value2));
411645
411645
  else {
411646
411646
  const key = toFilePath(value2[0]);
411647
411647
  emitSignatures.set(
@@ -411662,7 +411662,7 @@ ${lanes.join("\n")}
411662
411662
  emitDiagnosticsPerFile: toPerFileEmitDiagnostics(buildInfo.emitDiagnosticsPerFile),
411663
411663
  hasReusableDiagnostic: true,
411664
411664
  changedFilesSet,
411665
- affectedFilesPendingEmit: buildInfo.affectedFilesPendingEmit && arrayToMap(buildInfo.affectedFilesPendingEmit, (value2) => toFilePath(isNumber(value2) ? value2 : value2[0]), (value2) => toBuilderFileEmit(value2, fullEmitForOptions)),
411665
+ affectedFilesPendingEmit: buildInfo.affectedFilesPendingEmit && arrayToMap(buildInfo.affectedFilesPendingEmit, (value2) => toFilePath(isNumber2(value2) ? value2 : value2[0]), (value2) => toBuilderFileEmit(value2, fullEmitForOptions)),
411666
411666
  latestChangedDtsFile,
411667
411667
  emitSignatures: (emitSignatures == null ? void 0 : emitSignatures.size) ? emitSignatures : void 0,
411668
411668
  hasErrors: buildInfo.errors,
@@ -411718,7 +411718,7 @@ ${lanes.join("\n")}
411718
411718
  )
411719
411719
  );
411720
411720
  diagnostics == null ? void 0 : diagnostics.forEach((value2) => {
411721
- if (isNumber(value2)) semanticDiagnostics.delete(toFilePath(value2));
411721
+ if (isNumber2(value2)) semanticDiagnostics.delete(toFilePath(value2));
411722
411722
  else semanticDiagnostics.set(toFilePath(value2[0]), value2[1]);
411723
411723
  });
411724
411724
  return semanticDiagnostics;
@@ -435962,7 +435962,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
435962
435962
  return decl;
435963
435963
  }
435964
435964
  function getIsMatchingAsyncError(span, errorCode) {
435965
- return ({ start: start2, length: length22, relatedInformation, code: code8 }) => isNumber(start2) && isNumber(length22) && textSpansEqual({ start: start2, length: length22 }, span) && code8 === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code);
435965
+ return ({ start: start2, length: length22, relatedInformation, code: code8 }) => isNumber2(start2) && isNumber2(length22) && textSpansEqual({ start: start2, length: length22 }, span) && code8 === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_mean_to_mark_this_function_as_async.code);
435966
435966
  }
435967
435967
  var fixId3 = "addMissingAwait";
435968
435968
  var propertyAccessCode = Diagnostics.Property_0_does_not_exist_on_type_1.code;
@@ -436000,7 +436000,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
436000
436000
  }
436001
436001
  const checker = context2.program.getTypeChecker();
436002
436002
  const trackChanges = (cb) => ts_textChanges_exports.ChangeTracker.with(context2, cb);
436003
- return compact2([
436003
+ return compact3([
436004
436004
  getDeclarationSiteFix(context2, expression, errorCode, checker, trackChanges),
436005
436005
  getUseSiteFix(context2, expression, errorCode, checker, trackChanges)
436006
436006
  ]);
@@ -436047,7 +436047,7 @@ ${newComment.split("\n").map((c9) => ` * ${c9}`).join("\n")}
436047
436047
  function isMissingAwaitError(sourceFile, errorCode, span, cancellationToken, program) {
436048
436048
  const checker = program.getTypeChecker();
436049
436049
  const diagnostics = checker.getDiagnostics(sourceFile, cancellationToken);
436050
- return some(diagnostics, ({ start: start2, length: length22, relatedInformation, code: code8 }) => isNumber(start2) && isNumber(length22) && textSpansEqual({ start: start2, length: length22 }, span) && code8 === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_forget_to_use_await.code));
436050
+ return some(diagnostics, ({ start: start2, length: length22, relatedInformation, code: code8 }) => isNumber2(start2) && isNumber2(length22) && textSpansEqual({ start: start2, length: length22 }, span) && code8 === errorCode && !!relatedInformation && some(relatedInformation, (related) => related.code === Diagnostics.Did_you_forget_to_use_await.code));
436051
436051
  }
436052
436052
  function findAwaitableInitializers(expression, sourceFile, cancellationToken, program, checker) {
436053
436053
  const identifiers = getIdentifiersFromErrorSpanExpression(expression, checker);
@@ -459591,7 +459591,7 @@ ${content}
459591
459591
  const lastToken = last2(children2);
459592
459592
  const separateLastToken = separateTrailingSemicolon && lastToken.kind === 27;
459593
459593
  const rightChildren = children2.slice(splitTokenIndex + 1, separateLastToken ? children2.length - 1 : void 0);
459594
- const result = compact2([
459594
+ const result = compact3([
459595
459595
  leftChildren.length ? createSyntaxList2(leftChildren) : void 0,
459596
459596
  splitToken,
459597
459597
  rightChildren.length ? createSyntaxList2(rightChildren) : void 0
@@ -466315,7 +466315,7 @@ ${options2.prefix}` : "\n" : options2.prefix
466315
466315
  commandLineOptionOfCustomType: () => commandLineOptionOfCustomType,
466316
466316
  commentPragmas: () => commentPragmas,
466317
466317
  commonOptionsWithBuild: () => commonOptionsWithBuild,
466318
- compact: () => compact2,
466318
+ compact: () => compact3,
466319
466319
  compareBooleans: () => compareBooleans,
466320
466320
  compareComparableValues: () => compareComparableValues,
466321
466321
  compareDataObjects: () => compareDataObjects,
@@ -467623,7 +467623,7 @@ ${options2.prefix}` : "\n" : options2.prefix
467623
467623
  isNonStaticMethodOrAccessorWithPrivateName: () => isNonStaticMethodOrAccessorWithPrivateName,
467624
467624
  isNotEmittedStatement: () => isNotEmittedStatement,
467625
467625
  isNullishCoalesce: () => isNullishCoalesce,
467626
- isNumber: () => isNumber,
467626
+ isNumber: () => isNumber2,
467627
467627
  isNumericLiteral: () => isNumericLiteral,
467628
467628
  isNumericLiteralName: () => isNumericLiteralName,
467629
467629
  isObjectBindingElementWithoutPropertyName: () => isObjectBindingElementWithoutPropertyName,
@@ -544024,8 +544024,8 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
544024
544024
  if (process.env["OMNIUS_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
544025
544025
  const goalForSig = (this._taskState.goal || "").slice(0, 200);
544026
544026
  const recentTools = this._toolSequence.slice(-5).join("|");
544027
- const { createHash: createHash28 } = await import("node:crypto");
544028
- const sig = createHash28("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
544027
+ const { createHash: createHash29 } = await import("node:crypto");
544028
+ const sig = createHash29("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
544029
544029
  if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
544030
544030
  compacted.push({
544031
544031
  role: "system",
@@ -559204,7 +559204,7 @@ var require_websocket3 = __commonJS({
559204
559204
  var http6 = __require("http");
559205
559205
  var net5 = __require("net");
559206
559206
  var tls2 = __require("tls");
559207
- var { randomBytes: randomBytes27, createHash: createHash28 } = __require("crypto");
559207
+ var { randomBytes: randomBytes27, createHash: createHash29 } = __require("crypto");
559208
559208
  var { Duplex: Duplex3, Readable } = __require("stream");
559209
559209
  var { URL: URL3 } = __require("url");
559210
559210
  var PerMessageDeflate3 = require_permessage_deflate3();
@@ -559864,7 +559864,7 @@ var require_websocket3 = __commonJS({
559864
559864
  abortHandshake(websocket, socket, "Invalid Upgrade header");
559865
559865
  return;
559866
559866
  }
559867
- const digest3 = createHash28("sha1").update(key + GUID).digest("base64");
559867
+ const digest3 = createHash29("sha1").update(key + GUID).digest("base64");
559868
559868
  if (res.headers["sec-websocket-accept"] !== digest3) {
559869
559869
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
559870
559870
  return;
@@ -560231,7 +560231,7 @@ var require_websocket_server2 = __commonJS({
560231
560231
  var EventEmitter14 = __require("events");
560232
560232
  var http6 = __require("http");
560233
560233
  var { Duplex: Duplex3 } = __require("stream");
560234
- var { createHash: createHash28 } = __require("crypto");
560234
+ var { createHash: createHash29 } = __require("crypto");
560235
560235
  var extension3 = require_extension3();
560236
560236
  var PerMessageDeflate3 = require_permessage_deflate3();
560237
560237
  var subprotocol3 = require_subprotocol2();
@@ -560532,7 +560532,7 @@ var require_websocket_server2 = __commonJS({
560532
560532
  );
560533
560533
  }
560534
560534
  if (this._state > RUNNING) return abortHandshake(socket, 503);
560535
- const digest3 = createHash28("sha1").update(key + GUID).digest("base64");
560535
+ const digest3 = createHash29("sha1").update(key + GUID).digest("base64");
560536
560536
  const headers = [
560537
560537
  "HTTP/1.1 101 Switching Protocols",
560538
560538
  "Upgrade: websocket",
@@ -563932,9 +563932,9 @@ function keywords(text) {
563932
563932
  return out;
563933
563933
  }
563934
563934
  function compactLine(text, limit = 220) {
563935
- const compact2 = text.replace(/\s+/g, " ").trim();
563936
- if (compact2.length <= limit) return compact2;
563937
- return `${compact2.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
563935
+ const compact3 = text.replace(/\s+/g, " ").trim();
563936
+ if (compact3.length <= limit) return compact3;
563937
+ return `${compact3.slice(0, Math.max(0, limit - 3)).trimEnd()}...`;
563938
563938
  }
563939
563939
  function newDocument(scope) {
563940
563940
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -567606,9 +567606,9 @@ function formatCaps(caps) {
567606
567606
  if (caps.thinking) tags.push("think");
567607
567607
  return tags.join("+");
567608
567608
  }
567609
- function formatRelativeTime(iso) {
567609
+ function formatRelativeTime(iso2) {
567610
567610
  const now = Date.now();
567611
- const then = new Date(iso).getTime();
567611
+ const then = new Date(iso2).getTime();
567612
567612
  const diffMs = now - then;
567613
567613
  const minutes = Math.floor(diffMs / 6e4);
567614
567614
  if (minutes < 1) return "just now";
@@ -573449,10 +573449,10 @@ ${CONTENT_BG_SEQ}`);
573449
573449
  if (this._telegramStatus.active) {
573450
573450
  const suffix = this._telegramStatus.activeSubAgents > 0 ? ` ${this._telegramStatus.activeSubAgents}` : "";
573451
573451
  const label = `✈ tg${suffix}`;
573452
- const compact2 = `✈${suffix}`;
573452
+ const compact3 = `✈${suffix}`;
573453
573453
  sections.push({
573454
573454
  expanded: `\x1B[38;5;45m${label}\x1B[0m`,
573455
- compact: `\x1B[38;5;45m${compact2}\x1B[0m`,
573455
+ compact: `\x1B[38;5;45m${compact3}\x1B[0m`,
573456
573456
  expandedW: 2 + 3 + suffix.length,
573457
573457
  compactW: 2 + suffix.length,
573458
573458
  empty: false
@@ -608152,26 +608152,38 @@ function buildOpenQuestions(input) {
608152
608152
  }
608153
608153
  function buildReplyOpportunities(input, openQuestions) {
608154
608154
  const opportunities = [];
608155
+ const lifecycleUpdatedAt = new Date(input.generatedAtMs).toISOString();
608155
608156
  for (const question of openQuestions.slice(-3)) {
608157
+ const trigger = question;
608156
608158
  opportunities.push({
608157
- trigger: question,
608159
+ id: daydreamOpportunityId(input, trigger),
608160
+ trigger,
608158
608161
  rationale: "The group left a question or uncertainty that may benefit from a concise clarification.",
608159
608162
  suggestedTone: "brief, contextual, ask one concrete follow-up if needed",
608160
- confidence: 0.62
608163
+ confidence: 0.62,
608164
+ lifecycle: "proposed",
608165
+ lifecycleUpdatedAt
608161
608166
  });
608162
608167
  }
608163
608168
  const recent = recentUserMessages(input);
608164
608169
  const last2 = recent[recent.length - 1];
608165
608170
  if (last2 && /\b(omnius|bot|agent)\b/i.test(last2.text) && opportunities.length < 4) {
608171
+ const trigger = `${last2.speaker || last2.username || "user"} mentioned the agent: ${compactLine2(last2.text, 160)}`;
608166
608172
  opportunities.push({
608167
- trigger: `${last2.speaker || last2.username || "user"} mentioned the agent: ${compactLine2(last2.text, 160)}`,
608173
+ id: daydreamOpportunityId(input, trigger),
608174
+ trigger,
608168
608175
  rationale: "A later live-router pass should consider whether this is a direct social opening or just third-person chatter.",
608169
608176
  suggestedTone: "low-intrusion, do not assume the turn belongs to the agent",
608170
- confidence: 0.48
608177
+ confidence: 0.48,
608178
+ lifecycle: "proposed",
608179
+ lifecycleUpdatedAt
608171
608180
  });
608172
608181
  }
608173
608182
  return opportunities;
608174
608183
  }
608184
+ function daydreamOpportunityId(input, trigger) {
608185
+ return createHash21("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
608186
+ }
608175
608187
  function clamp018(value2) {
608176
608188
  if (!Number.isFinite(value2)) return 0;
608177
608189
  return Math.max(0, Math.min(1, value2));
@@ -608607,6 +608619,8 @@ Selected seed: ${artifact.selectedSeed.nodeText} (${artifact.selectedSeed.nodeTy
608607
608619
  "",
608608
608620
  "## Reply Opportunities",
608609
608621
  artifact.replyOpportunities.length ? artifact.replyOpportunities.map((item) => `- ${item.trigger}
608622
+ - id: ${item.id}
608623
+ - lifecycle: ${item.lifecycle}${item.lifecycleUpdatedAt ? ` at ${item.lifecycleUpdatedAt}` : ""}
608610
608624
  - rationale: ${item.rationale}
608611
608625
  - tone: ${item.suggestedTone}
608612
608626
  - confidence: ${item.confidence.toFixed(2)}`).join("\n") : "- None",
@@ -608690,7 +608704,7 @@ ${artifact.contextEngineeringNotes.slice(0, 5).map((line) => `- ${line}`).join("
608690
608704
  artifact.openQuestions.length ? `Open questions:
608691
608705
  ${artifact.openQuestions.slice(0, 4).map((line) => `- ${line}`).join("\n")}` : "",
608692
608706
  artifact.replyOpportunities.length ? `Possible reply opportunities:
608693
- ${artifact.replyOpportunities.slice(0, 3).map((item) => `- ${item.trigger} (confidence ${item.confidence.toFixed(2)}; ${item.suggestedTone})`).join("\n")}` : ""
608707
+ ${artifact.replyOpportunities.slice(0, 3).map((item) => `- ${item.id} [${item.lifecycle}] ${item.trigger} (confidence ${item.confidence.toFixed(2)}; ${item.suggestedTone})`).join("\n")}` : ""
608694
608708
  ].filter(Boolean);
608695
608709
  return lines.join("\n");
608696
608710
  }
@@ -609415,6 +609429,600 @@ var init_telegram_reflection_extraction = __esm({
609415
609429
  }
609416
609430
  });
609417
609431
 
609432
+ // packages/cli/src/tui/telegram-social-state-types.ts
609433
+ import { createHash as createHash23 } from "node:crypto";
609434
+ function telegramSocialActorKey(actor) {
609435
+ if (!actor) return "unknown";
609436
+ if (typeof actor.userId === "number") return `user:${actor.userId}`;
609437
+ const username = cleanUsername(actor.username);
609438
+ if (username) return `username:${username.toLowerCase()}`;
609439
+ const first2 = compact2(actor.firstName, 80).toLowerCase();
609440
+ return first2 ? `name:${first2}` : "unknown";
609441
+ }
609442
+ function telegramSocialActorKind(actor) {
609443
+ if (actor.isSelf || actor.isBot) return "bot";
609444
+ if (actor.userId || actor.username || actor.firstName) return "human";
609445
+ return "unknown";
609446
+ }
609447
+ function telegramSocialThreadKey(input) {
609448
+ return input.messageThreadId !== void 0 ? `chat:${String(input.chatId)}:thread:${input.messageThreadId}` : `chat:${String(input.chatId)}`;
609449
+ }
609450
+ function appendUnique(items, value2, max) {
609451
+ if (value2 === void 0 || value2 === null) return items.slice(-max);
609452
+ const next = items.filter((item) => item !== value2);
609453
+ next.push(value2);
609454
+ return next.slice(-max);
609455
+ }
609456
+ function hashTelegramSocialId(parts) {
609457
+ return createHash23("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
609458
+ }
609459
+ function cleanUsername(value2) {
609460
+ if (typeof value2 !== "string") return void 0;
609461
+ const clean5 = value2.trim().replace(/^@/, "");
609462
+ return clean5 ? clean5.slice(0, 80) : void 0;
609463
+ }
609464
+ function compactOptional(value2, max) {
609465
+ const clean5 = compact2(value2, max);
609466
+ return clean5 || void 0;
609467
+ }
609468
+ function compact2(value2, max) {
609469
+ if (value2 === void 0 || value2 === null) return "";
609470
+ const clean5 = String(value2).replace(/\s+/g, " ").trim();
609471
+ return clean5.length > max ? `${clean5.slice(0, Math.max(0, max - 3)).trimEnd()}...` : clean5;
609472
+ }
609473
+ function jsonLine(value2, max) {
609474
+ return JSON.stringify(compact2(value2, max));
609475
+ }
609476
+ function numberOr(value2, fallback) {
609477
+ return typeof value2 === "number" && Number.isFinite(value2) ? value2 : fallback;
609478
+ }
609479
+ function isNumber(value2) {
609480
+ return typeof value2 === "number" && Number.isFinite(value2);
609481
+ }
609482
+ function clamp019(value2) {
609483
+ return Math.max(0, Math.min(1, Number.isFinite(value2) ? value2 : 0));
609484
+ }
609485
+ function iso(ts) {
609486
+ try {
609487
+ return new Date(ts).toISOString();
609488
+ } catch {
609489
+ return "";
609490
+ }
609491
+ }
609492
+ var TELEGRAM_SOCIAL_LIMITS;
609493
+ var init_telegram_social_state_types = __esm({
609494
+ "packages/cli/src/tui/telegram-social-state-types.ts"() {
609495
+ "use strict";
609496
+ TELEGRAM_SOCIAL_LIMITS = {
609497
+ relationships: 240,
609498
+ salience: 180,
609499
+ outcomes: 160,
609500
+ daydreamOpportunities: 120,
609501
+ daydreamStaleMs: 6 * 60 * 6e4
609502
+ };
609503
+ }
609504
+ });
609505
+
609506
+ // packages/cli/src/tui/telegram-social-state-context.ts
609507
+ function formatTelegramSocialStateContext(state, input) {
609508
+ const limit = Math.max(3, Math.min(12, Math.floor(input.limit ?? 8)));
609509
+ const senderKey3 = telegramSocialActorKey(input);
609510
+ const selfKey = input.self ? telegramSocialActorKey(input.self) : void 0;
609511
+ const replyKey = input.replySender ? telegramSocialActorKey(input.replySender) : void 0;
609512
+ const thread = state.threads[telegramSocialThreadKey(input)];
609513
+ const participant = state.participants[senderKey3];
609514
+ const relevantKeys = new Set([senderKey3, selfKey, replyKey].filter(Boolean));
609515
+ const edges = state.relationships.filter((edge) => relevantKeys.has(edge.fromKey) || relevantKeys.has(edge.toKey)).sort((a2, b) => b.lastSeenAt - a2.lastSeenAt).slice(0, limit);
609516
+ const outcomes = state.outcomes.filter((outcome) => outcome.senderKey === senderKey3 || outcome.chatId === String(input.chatId)).sort((a2, b) => b.ts - a2.ts).slice(0, limit);
609517
+ const salience = state.salience.filter((item) => item.senderKey === senderKey3 || item.chatId === String(input.chatId)).sort((a2, b) => b.ts - a2.ts).slice(0, limit);
609518
+ const daydreams = Object.values(state.daydreamOpportunities).filter((item) => item.lifecycle !== "retired").sort((a2, b) => b.updatedAt - a2.updatedAt).slice(0, Math.min(5, limit));
609519
+ const preferences = preferenceLines(state.preferences[senderKey3]);
609520
+ return [
609521
+ "### Telegram Structured Social State",
609522
+ `Current actor node: ${senderKey3} [${participant?.actorKind || telegramSocialActorKind(input)}] messages=${participant?.messageCount ?? 0}${participant?.lastText ? ` last=${jsonLine(participant.lastText, 140)}` : ""}`,
609523
+ thread ? `Active channel/thread: ${thread.key}; messages=${thread.messageCount}; participants=${thread.participantKeys.slice(-8).join(", ") || "none"}; last_outcomes=${thread.lastOutcomeIds.slice(-5).join(", ") || "none"}` : "",
609524
+ preferences.length ? `Relevant preference vector for ${senderKey3}:
609525
+ ${preferences.join("\n")}` : `Relevant preference vector for ${senderKey3}: no durable preferences yet`,
609526
+ salience.length ? `Recent salience observations:
609527
+ ${salience.map((item) => `- ${iso(item.ts)} ${item.senderKey}: ${item.signals.join(", ") || "none"}; text=${jsonLine(item.textPreview, 120)}`).join("\n")}` : "",
609528
+ edges.length ? `Relevant relationship edges:
609529
+ ${edges.map(formatEdge).join("\n")}` : "Relevant relationship edges: none yet",
609530
+ outcomes.length ? `Prior response outcomes:
609531
+ ${outcomes.map(formatOutcome).join("\n")}` : "Prior response outcomes: none yet",
609532
+ daydreams.length ? `Active daydream opportunity lifecycle:
609533
+ ${daydreams.map((item) => `- ${item.id} [${item.lifecycle}] confidence=${item.confidence.toFixed(2)} trigger=${jsonLine(item.trigger, 140)}`).join("\n")}` : ""
609534
+ ].filter(Boolean).join("\n");
609535
+ }
609536
+ function preferenceLines(vector) {
609537
+ if (!vector) return [];
609538
+ return Object.entries(vector).map(([key, evidence]) => {
609539
+ const item = evidence;
609540
+ return `- ${key}: value=${item.value.toFixed(2)} confidence=${item.confidence.toFixed(2)} evidence=${item.evidenceMessageIds.join(",") || "none"}${item.note ? ` note=${jsonLine(item.note, 120)}` : ""}`;
609541
+ });
609542
+ }
609543
+ function formatEdge(edge) {
609544
+ const evidence = edge.evidenceMessageIds.length ? ` evidence=${edge.evidenceMessageIds.join(",")}` : "";
609545
+ const note = edge.note ? ` note=${jsonLine(edge.note, 140)}` : "";
609546
+ return `- ${edge.fromKey} --${edge.kind}--> ${edge.toKey} confidence=${edge.confidence.toFixed(2)} weight=${edge.weight.toFixed(2)}${evidence}${note}`;
609547
+ }
609548
+ function formatOutcome(outcome) {
609549
+ const action = outcome.shouldReply ? `replied via ${outcome.route}` : "silent";
609550
+ const note = outcome.mentalNote || outcome.memoryNote || outcome.relationshipNote || outcome.silentDisposition || outcome.reason;
609551
+ return `- ${iso(outcome.ts)} message=${outcome.messageId ?? "?"} ${action} confidence=${outcome.confidence.toFixed(2)} reason=${jsonLine(note, 160)}`;
609552
+ }
609553
+ var init_telegram_social_state_context = __esm({
609554
+ "packages/cli/src/tui/telegram-social-state-context.ts"() {
609555
+ "use strict";
609556
+ init_telegram_social_state_types();
609557
+ }
609558
+ });
609559
+
609560
+ // packages/cli/src/tui/telegram-social-state-normalize.ts
609561
+ function createTelegramSocialState(now = Date.now()) {
609562
+ return {
609563
+ version: 1,
609564
+ createdAt: now,
609565
+ updatedAt: now,
609566
+ participants: {},
609567
+ relationships: [],
609568
+ preferences: {},
609569
+ threads: {},
609570
+ salience: [],
609571
+ outcomes: [],
609572
+ daydreamOpportunities: {}
609573
+ };
609574
+ }
609575
+ function normalizeTelegramSocialState(raw) {
609576
+ const now = Date.now();
609577
+ if (!raw || typeof raw !== "object") return createTelegramSocialState(now);
609578
+ const value2 = raw;
609579
+ const state = createTelegramSocialState(now);
609580
+ state.createdAt = numberOr(value2.createdAt, state.createdAt);
609581
+ state.updatedAt = numberOr(value2.updatedAt, state.updatedAt);
609582
+ state.participants = normalizeRecord(value2.participants, normalizeParticipant);
609583
+ state.relationships = Array.isArray(value2.relationships) ? value2.relationships.map(normalizeRelationship).filter(Boolean).slice(-TELEGRAM_SOCIAL_LIMITS.relationships) : [];
609584
+ state.preferences = normalizePreferences(value2.preferences);
609585
+ state.threads = normalizeRecord(value2.threads, normalizeThread);
609586
+ state.salience = Array.isArray(value2.salience) ? value2.salience.map(normalizeSalience).filter(Boolean).slice(-TELEGRAM_SOCIAL_LIMITS.salience) : [];
609587
+ state.outcomes = Array.isArray(value2.outcomes) ? value2.outcomes.map(normalizeOutcome).filter(Boolean).slice(-TELEGRAM_SOCIAL_LIMITS.outcomes) : [];
609588
+ state.daydreamOpportunities = normalizeRecord(value2.daydreamOpportunities, normalizeDaydreamOpportunity);
609589
+ return state;
609590
+ }
609591
+ function normalizeRecord(raw, fn) {
609592
+ const output = {};
609593
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return output;
609594
+ for (const [key, value2] of Object.entries(raw)) {
609595
+ const normalized = fn(value2);
609596
+ if (normalized) output[key] = normalized;
609597
+ }
609598
+ return output;
609599
+ }
609600
+ function normalizeParticipant(raw) {
609601
+ if (!raw || typeof raw !== "object") return null;
609602
+ const value2 = raw;
609603
+ const key = String(value2.key || "").trim();
609604
+ if (!key) return null;
609605
+ return {
609606
+ key,
609607
+ userId: typeof value2.userId === "number" ? value2.userId : void 0,
609608
+ username: cleanUsername(value2.username),
609609
+ displayName: compactOptional(value2.displayName, 120),
609610
+ actorKind: value2.actorKind === "bot" || value2.actorKind === "human" ? value2.actorKind : "unknown",
609611
+ aliases: Array.isArray(value2.aliases) ? value2.aliases.map(String).slice(0, 20) : [],
609612
+ firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
609613
+ lastSeenAt: numberOr(value2.lastSeenAt, Date.now()),
609614
+ messageCount: numberOr(value2.messageCount, 0),
609615
+ lastMessageIds: Array.isArray(value2.lastMessageIds) ? value2.lastMessageIds.filter(isNumber).slice(-30) : [],
609616
+ lastText: compactOptional(value2.lastText, 500)
609617
+ };
609618
+ }
609619
+ function normalizeRelationship(raw) {
609620
+ if (!raw || typeof raw !== "object") return null;
609621
+ const value2 = raw;
609622
+ if (!value2.kind || !value2.fromKey || !value2.toKey) return null;
609623
+ return {
609624
+ id: String(value2.id || hashTelegramSocialId(["edge", value2.kind, value2.fromKey, value2.toKey])),
609625
+ kind: value2.kind,
609626
+ fromKey: String(value2.fromKey),
609627
+ toKey: String(value2.toKey),
609628
+ confidence: clamp019(numberOr(value2.confidence, 0)),
609629
+ weight: clamp019(numberOr(value2.weight, 0)),
609630
+ firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
609631
+ lastSeenAt: numberOr(value2.lastSeenAt, Date.now()),
609632
+ evidenceMessageIds: Array.isArray(value2.evidenceMessageIds) ? value2.evidenceMessageIds.filter(isNumber).slice(-40) : [],
609633
+ note: compactOptional(value2.note, 260),
609634
+ source: value2.source === "router" || value2.source === "daydream" ? value2.source : "message"
609635
+ };
609636
+ }
609637
+ function normalizePreferences(raw) {
609638
+ const out = {};
609639
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
609640
+ for (const [actorKey, vector] of Object.entries(raw)) {
609641
+ if (!vector || typeof vector !== "object") continue;
609642
+ out[actorKey] = {};
609643
+ for (const key of ["verbosity", "depth", "silence", "directness", "botToBotTolerance"]) {
609644
+ const evidence = vector[key];
609645
+ if (!evidence || typeof evidence !== "object") continue;
609646
+ out[actorKey][key] = {
609647
+ value: Math.max(-1, Math.min(1, numberOr(evidence.value, 0))),
609648
+ confidence: clamp019(numberOr(evidence.confidence, 0)),
609649
+ updatedAt: numberOr(evidence.updatedAt, Date.now()),
609650
+ evidenceMessageIds: Array.isArray(evidence.evidenceMessageIds) ? evidence.evidenceMessageIds.filter(isNumber).slice(-12) : [],
609651
+ note: compactOptional(evidence.note, 220)
609652
+ };
609653
+ }
609654
+ }
609655
+ return out;
609656
+ }
609657
+ function normalizeThread(raw) {
609658
+ if (!raw || typeof raw !== "object") return null;
609659
+ const value2 = raw;
609660
+ const key = String(value2.key || "").trim();
609661
+ if (!key) return null;
609662
+ return {
609663
+ key,
609664
+ chatId: String(value2.chatId || ""),
609665
+ chatType: compactOptional(value2.chatType, 40),
609666
+ chatTitle: compactOptional(value2.chatTitle, 120),
609667
+ messageThreadId: typeof value2.messageThreadId === "number" ? value2.messageThreadId : void 0,
609668
+ firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
609669
+ lastSeenAt: numberOr(value2.lastSeenAt, Date.now()),
609670
+ messageCount: numberOr(value2.messageCount, 0),
609671
+ participantKeys: Array.isArray(value2.participantKeys) ? value2.participantKeys.map(String).slice(-40) : [],
609672
+ lastMessageIds: Array.isArray(value2.lastMessageIds) ? value2.lastMessageIds.filter(isNumber).slice(-40) : [],
609673
+ lastOutcomeIds: Array.isArray(value2.lastOutcomeIds) ? value2.lastOutcomeIds.map(String).slice(-30) : []
609674
+ };
609675
+ }
609676
+ function normalizeSalience(raw) {
609677
+ if (!raw || typeof raw !== "object") return null;
609678
+ const value2 = raw;
609679
+ if (!value2.senderKey) return null;
609680
+ return {
609681
+ id: String(value2.id || hashTelegramSocialId(["salience", value2.senderKey, value2.messageId ?? Date.now()])),
609682
+ ts: numberOr(value2.ts, Date.now()),
609683
+ chatId: String(value2.chatId || ""),
609684
+ messageId: typeof value2.messageId === "number" ? value2.messageId : void 0,
609685
+ messageThreadId: typeof value2.messageThreadId === "number" ? value2.messageThreadId : void 0,
609686
+ senderKey: String(value2.senderKey),
609687
+ actorKind: value2.actorKind === "bot" || value2.actorKind === "human" ? value2.actorKind : "unknown",
609688
+ signals: Array.isArray(value2.signals) ? value2.signals.map(String).slice(0, 16) : [],
609689
+ textPreview: compact2(value2.textPreview || "", 240)
609690
+ };
609691
+ }
609692
+ function normalizeOutcome(raw) {
609693
+ if (!raw || typeof raw !== "object") return null;
609694
+ const value2 = raw;
609695
+ if (!value2.senderKey) return null;
609696
+ return {
609697
+ id: String(value2.id || hashTelegramSocialId(["outcome", value2.senderKey, value2.messageId ?? Date.now()])),
609698
+ ts: numberOr(value2.ts, Date.now()),
609699
+ chatId: String(value2.chatId || ""),
609700
+ messageId: typeof value2.messageId === "number" ? value2.messageId : void 0,
609701
+ messageThreadId: typeof value2.messageThreadId === "number" ? value2.messageThreadId : void 0,
609702
+ senderKey: String(value2.senderKey),
609703
+ replyToMessageId: typeof value2.replyToMessageId === "number" ? value2.replyToMessageId : void 0,
609704
+ route: value2.route === "action" ? "action" : "chat",
609705
+ shouldReply: value2.shouldReply === true,
609706
+ confidence: clamp019(numberOr(value2.confidence, 0)),
609707
+ reason: compact2(value2.reason || "", 280),
609708
+ source: compact2(value2.source || "unknown", 80),
609709
+ silentDisposition: compactOptional(value2.silentDisposition, 280),
609710
+ mentalNote: compactOptional(value2.mentalNote, 360),
609711
+ memoryNote: compactOptional(value2.memoryNote, 360),
609712
+ relationshipNote: compactOptional(value2.relationshipNote, 360),
609713
+ salienceSignals: Array.isArray(value2.salienceSignals) ? value2.salienceSignals.map(String).slice(0, 16) : [],
609714
+ daydreamOpportunityIds: Array.isArray(value2.daydreamOpportunityIds) ? value2.daydreamOpportunityIds.map(String).slice(0, 16) : []
609715
+ };
609716
+ }
609717
+ function normalizeDaydreamOpportunity(raw) {
609718
+ if (!raw || typeof raw !== "object") return null;
609719
+ const value2 = raw;
609720
+ const id = String(value2.id || "").trim();
609721
+ if (!id) return null;
609722
+ const lifecycle = ["proposed", "considered", "acted", "suppressed", "retired"].includes(String(value2.lifecycle)) ? value2.lifecycle : "proposed";
609723
+ return {
609724
+ id,
609725
+ artifactId: String(value2.artifactId || "unknown"),
609726
+ generatedAt: String(value2.generatedAt || (/* @__PURE__ */ new Date()).toISOString()),
609727
+ trigger: compact2(value2.trigger || "", 240),
609728
+ confidence: clamp019(numberOr(value2.confidence, 0)),
609729
+ lifecycle,
609730
+ firstSeenAt: numberOr(value2.firstSeenAt, Date.now()),
609731
+ updatedAt: numberOr(value2.updatedAt, Date.now()),
609732
+ consideredMessageIds: Array.isArray(value2.consideredMessageIds) ? value2.consideredMessageIds.filter(isNumber).slice(-20) : [],
609733
+ actedMessageIds: Array.isArray(value2.actedMessageIds) ? value2.actedMessageIds.filter(isNumber).slice(-20) : [],
609734
+ suppressedMessageIds: Array.isArray(value2.suppressedMessageIds) ? value2.suppressedMessageIds.filter(isNumber).slice(-20) : [],
609735
+ retiredAt: typeof value2.retiredAt === "number" ? value2.retiredAt : void 0
609736
+ };
609737
+ }
609738
+ var init_telegram_social_state_normalize = __esm({
609739
+ "packages/cli/src/tui/telegram-social-state-normalize.ts"() {
609740
+ "use strict";
609741
+ init_telegram_social_state_types();
609742
+ }
609743
+ });
609744
+
609745
+ // packages/cli/src/tui/telegram-social-state.ts
609746
+ function observeTelegramSocialMessage(state, input) {
609747
+ const now = input.ts ?? Date.now();
609748
+ state.updatedAt = now;
609749
+ const senderKey3 = upsertParticipant(state, input, now, true);
609750
+ const thread = upsertThread(state, input, senderKey3, now, true);
609751
+ const text = compact2(input.text || "", 500);
609752
+ const participant = state.participants[senderKey3];
609753
+ if (participant) {
609754
+ participant.lastText = text || participant.lastText;
609755
+ participant.lastMessageIds = appendUnique(participant.lastMessageIds, input.messageId, 30);
609756
+ }
609757
+ addSalience(state, input, senderKey3, now, text);
609758
+ if (input.replySender || input.replyToMessageId !== void 0) {
609759
+ const targetKey = input.replySender ? upsertParticipant(state, input.replySender, now, false) : `message:${input.replyToMessageId}`;
609760
+ upsertRelationship(state, "replied_to", senderKey3, targetKey, input.messageId, 0.86, "message", replyNote(input), now);
609761
+ }
609762
+ const selfKey = input.self ? upsertParticipant(state, { ...input.self, isBot: true }, now, false) : void 0;
609763
+ addMessageDerivedEdges(state, input, senderKey3, selfKey, text, now);
609764
+ updatePreferencesFromText(state, senderKey3, text, input.messageId, now, telegramSocialActorKind(input));
609765
+ thread.lastMessageIds = appendUnique(thread.lastMessageIds, input.messageId, 30);
609766
+ trimSocialState(state, now);
609767
+ }
609768
+ function commitTelegramSocialDecision(state, input) {
609769
+ const now = input.ts ?? Date.now();
609770
+ state.updatedAt = now;
609771
+ const senderKey3 = upsertParticipant(state, input.sender, now, false);
609772
+ const selfKey = input.self ? upsertParticipant(state, { ...input.self, isBot: true }, now, false) : void 0;
609773
+ const opportunities = registerDaydreamOpportunities(state, input.daydreamOpportunities ?? [], now);
609774
+ const opportunityIds = markDecisionOpportunities(opportunities, input.shouldReply, input.messageId, now);
609775
+ const outcome = {
609776
+ id: hashTelegramSocialId(["outcome", input.sessionKey, input.chatId, input.messageId ?? now, now, input.reason]),
609777
+ ts: now,
609778
+ chatId: String(input.chatId),
609779
+ messageId: input.messageId,
609780
+ messageThreadId: input.messageThreadId,
609781
+ senderKey: senderKey3,
609782
+ replyToMessageId: input.replyToMessageId,
609783
+ route: input.route,
609784
+ shouldReply: input.shouldReply,
609785
+ confidence: clamp019(input.confidence),
609786
+ reason: compact2(input.reason, 280),
609787
+ source: compact2(input.source, 80),
609788
+ silentDisposition: compactOptional(input.silentDisposition, 280),
609789
+ mentalNote: compactOptional(input.mentalNote, 360),
609790
+ memoryNote: compactOptional(input.memoryNote, 360),
609791
+ relationshipNote: compactOptional(input.relationshipNote, 360),
609792
+ salienceSignals: [...new Set((input.salienceSignals ?? []).map(String))].slice(0, 16),
609793
+ daydreamOpportunityIds: opportunityIds
609794
+ };
609795
+ state.outcomes.push(outcome);
609796
+ state.outcomes = state.outcomes.slice(-TELEGRAM_SOCIAL_LIMITS.outcomes);
609797
+ const thread = upsertThread(state, input, senderKey3, now, false);
609798
+ thread.lastOutcomeIds = appendUnique(thread.lastOutcomeIds, outcome.id, 30);
609799
+ commitDecisionEdges(state, input, senderKey3, selfKey, now);
609800
+ trimSocialState(state, now);
609801
+ return outcome;
609802
+ }
609803
+ function registerDaydreamOpportunities(state, opportunities, now = Date.now()) {
609804
+ const registered = [];
609805
+ for (const opportunity of opportunities) {
609806
+ const id = opportunity.id || hashTelegramSocialId(["daydream", opportunity.artifactId || "", opportunity.generatedAt || "", opportunity.trigger]);
609807
+ const existing = state.daydreamOpportunities[id];
609808
+ const item = existing ?? {
609809
+ id,
609810
+ artifactId: opportunity.artifactId || "unknown",
609811
+ generatedAt: opportunity.generatedAt || new Date(now).toISOString(),
609812
+ trigger: compact2(opportunity.trigger, 240),
609813
+ confidence: clamp019(opportunity.confidence),
609814
+ lifecycle: "proposed",
609815
+ firstSeenAt: now,
609816
+ updatedAt: now,
609817
+ consideredMessageIds: [],
609818
+ actedMessageIds: [],
609819
+ suppressedMessageIds: []
609820
+ };
609821
+ if (existing) {
609822
+ item.trigger = compact2(opportunity.trigger, 240) || item.trigger;
609823
+ item.confidence = clamp019(opportunity.confidence);
609824
+ item.updatedAt = now;
609825
+ }
609826
+ state.daydreamOpportunities[id] = item;
609827
+ registered.push(item);
609828
+ }
609829
+ retireStaleDaydreamOpportunities(state, now);
609830
+ return registered;
609831
+ }
609832
+ function markTelegramDaydreamOpportunitiesConsidered(state, opportunities, messageId, now = Date.now()) {
609833
+ const registered = registerDaydreamOpportunities(state, opportunities, now);
609834
+ for (const opportunity of registered) {
609835
+ if (opportunity.lifecycle === "proposed") opportunity.lifecycle = "considered";
609836
+ opportunity.updatedAt = now;
609837
+ opportunity.consideredMessageIds = appendUnique(opportunity.consideredMessageIds, messageId, 20);
609838
+ }
609839
+ return registered;
609840
+ }
609841
+ function commitDecisionEdges(state, input, senderKey3, selfKey, now) {
609842
+ if (!selfKey) return;
609843
+ if (input.shouldReply) {
609844
+ upsertRelationship(state, "addressed", selfKey, senderKey3, input.messageId, input.confidence, "router", input.reason, now);
609845
+ } else {
609846
+ upsertRelationship(state, "ignored", selfKey, senderKey3, input.messageId, input.confidence, "router", input.silentDisposition || input.reason, now);
609847
+ }
609848
+ if (input.relationshipNote) {
609849
+ upsertRelationship(state, "addressed", senderKey3, selfKey, input.messageId, Math.max(0.35, input.confidence), "router", input.relationshipNote, now);
609850
+ }
609851
+ }
609852
+ function markDecisionOpportunities(opportunities, shouldReply, messageId, now) {
609853
+ for (const opportunity of opportunities) {
609854
+ opportunity.lifecycle = shouldReply ? "acted" : "suppressed";
609855
+ opportunity.updatedAt = now;
609856
+ opportunity.consideredMessageIds = appendUnique(opportunity.consideredMessageIds, messageId, 20);
609857
+ if (shouldReply) {
609858
+ opportunity.actedMessageIds = appendUnique(opportunity.actedMessageIds, messageId, 20);
609859
+ } else {
609860
+ opportunity.suppressedMessageIds = appendUnique(opportunity.suppressedMessageIds, messageId, 20);
609861
+ }
609862
+ }
609863
+ return opportunities.map((item) => item.id);
609864
+ }
609865
+ function addMessageDerivedEdges(state, input, senderKey3, selfKey, text, now) {
609866
+ if (!selfKey) return;
609867
+ const signals = input.salienceSignals ?? [];
609868
+ const direct = signals.some((signal) => !signal.startsWith("private_dm_delivery"));
609869
+ if (direct) upsertRelationship(state, "addressed", senderKey3, selfKey, input.messageId, 0.78, "message", signals.join(", "), now);
609870
+ if (telegramSocialActorKind(input) === "bot" && direct) {
609871
+ upsertRelationship(state, "bot_to_bot_reference", senderKey3, selfKey, input.messageId, 0.7, "message", signals.join(", "), now);
609872
+ }
609873
+ if (/\b(deep dive|go deeper|more detail|be thorough|proper analysis|full breakdown|analyze this)\b/i.test(text)) {
609874
+ upsertRelationship(state, "asked_for_depth", senderKey3, selfKey, input.messageId, 0.68, "message", text, now);
609875
+ }
609876
+ if (/\b(don't reply|do not reply|listen only|stay silent|no response needed|just observe)\b/i.test(text)) {
609877
+ upsertRelationship(state, "asked_for_silence", senderKey3, selfKey, input.messageId, 0.72, "message", text, now);
609878
+ }
609879
+ if (/\b(yes|exactly|correct|good point|that works|agreed)\b/i.test(text)) {
609880
+ upsertRelationship(state, "affirmed", senderKey3, selfKey, input.messageId, 0.52, "message", text, now);
609881
+ }
609882
+ if (/\b(no,|wrong|incorrect|not what|missing|regression|failed|doesn't work|dont do that|don't do that)\b/i.test(text)) {
609883
+ upsertRelationship(state, "corrected", senderKey3, selfKey, input.messageId, 0.56, "message", text, now);
609884
+ }
609885
+ }
609886
+ function updatePreferencesFromText(state, actorKey, text, messageId, now, actorKind) {
609887
+ const vector = state.preferences[actorKey] ?? {};
609888
+ if (/\b(concise|short|brief|tl;dr|summarize)\b/i.test(text)) setPreference(vector, "verbosity", -0.55, 0.58, messageId, now, "prefers concise replies");
609889
+ if (/\b(verbose|long form|exhaustive|full breakdown|deep dive|proper analysis|thorough)\b/i.test(text)) setPreference(vector, "verbosity", 0.65, 0.62, messageId, now, "accepts longer detailed replies");
609890
+ if (/\b(deep dive|go deeper|analyze|reason through|proper analysis|full breakdown)\b/i.test(text)) setPreference(vector, "depth", 0.72, 0.68, messageId, now, "prefers deeper analysis");
609891
+ if (/\b(don't reply|do not reply|stay silent|listen only|just observe|silent reflection)\b/i.test(text)) setPreference(vector, "silence", 0.76, 0.7, messageId, now, "explicitly values silence/observation");
609892
+ if (/\b(direct|straight answer|no fluff|be clear|plainly)\b/i.test(text)) setPreference(vector, "directness", 0.68, 0.62, messageId, now, "prefers direct language");
609893
+ if (actorKind === "bot") setPreference(vector, "botToBotTolerance", 0.25, 0.4, messageId, now, "peer bot observed; keep bot-to-bot exchanges low-intrusion");
609894
+ state.preferences[actorKey] = vector;
609895
+ }
609896
+ function upsertParticipant(state, actor, now, countMessage) {
609897
+ const key = telegramSocialActorKey(actor);
609898
+ const username = cleanUsername(actor.username);
609899
+ const displayName = compactOptional(actor.firstName, 120);
609900
+ const node = state.participants[key] ?? {
609901
+ key,
609902
+ userId: actor.userId,
609903
+ username,
609904
+ displayName,
609905
+ actorKind: telegramSocialActorKind(actor),
609906
+ aliases: [],
609907
+ firstSeenAt: now,
609908
+ lastSeenAt: now,
609909
+ messageCount: 0,
609910
+ lastMessageIds: []
609911
+ };
609912
+ node.userId = actor.userId ?? node.userId;
609913
+ node.username = username || node.username;
609914
+ node.displayName = displayName || node.displayName;
609915
+ node.actorKind = actor.isSelf || actor.isBot ? "bot" : node.actorKind === "bot" ? "bot" : telegramSocialActorKind(actor);
609916
+ for (const alias of [username, displayName, actor.userId !== void 0 ? String(actor.userId) : ""].filter(Boolean)) {
609917
+ if (!node.aliases.includes(alias)) node.aliases.push(alias);
609918
+ }
609919
+ node.aliases = node.aliases.slice(0, 20);
609920
+ node.lastSeenAt = now;
609921
+ if (countMessage) node.messageCount += 1;
609922
+ state.participants[key] = node;
609923
+ return key;
609924
+ }
609925
+ function upsertThread(state, input, senderKey3, now, countMessage) {
609926
+ const key = telegramSocialThreadKey(input);
609927
+ const thread = state.threads[key] ?? {
609928
+ key,
609929
+ chatId: String(input.chatId),
609930
+ chatType: input.chatType,
609931
+ chatTitle: input.chatTitle,
609932
+ messageThreadId: input.messageThreadId,
609933
+ firstSeenAt: now,
609934
+ lastSeenAt: now,
609935
+ messageCount: 0,
609936
+ participantKeys: [],
609937
+ lastMessageIds: [],
609938
+ lastOutcomeIds: []
609939
+ };
609940
+ thread.chatType = input.chatType || thread.chatType;
609941
+ thread.chatTitle = input.chatTitle || thread.chatTitle;
609942
+ thread.lastSeenAt = now;
609943
+ if (countMessage) thread.messageCount += 1;
609944
+ thread.participantKeys = appendUnique(thread.participantKeys, senderKey3, 40);
609945
+ thread.lastMessageIds = appendUnique(thread.lastMessageIds, input.messageId, 40);
609946
+ state.threads[key] = thread;
609947
+ return thread;
609948
+ }
609949
+ function upsertRelationship(state, kind, fromKey, toKey, messageId, confidence2, source, note, now) {
609950
+ const id = hashTelegramSocialId(["edge", kind, fromKey, toKey]);
609951
+ const edge = state.relationships.find((item) => item.id === id) ?? {
609952
+ id,
609953
+ kind,
609954
+ fromKey,
609955
+ toKey,
609956
+ confidence: 0,
609957
+ weight: 0,
609958
+ firstSeenAt: now,
609959
+ lastSeenAt: now,
609960
+ evidenceMessageIds: [],
609961
+ source
609962
+ };
609963
+ edge.confidence = Math.max(edge.confidence, clamp019(confidence2));
609964
+ edge.weight = Math.min(1, edge.weight + 0.12 + clamp019(confidence2) * 0.2);
609965
+ edge.lastSeenAt = now;
609966
+ edge.evidenceMessageIds = appendUnique(edge.evidenceMessageIds, messageId, 40);
609967
+ edge.note = compactOptional(note, 260) || edge.note;
609968
+ edge.source = source;
609969
+ if (!state.relationships.some((item) => item.id === id)) state.relationships.push(edge);
609970
+ }
609971
+ function addSalience(state, input, senderKey3, now, text) {
609972
+ const signals = [...new Set((input.salienceSignals ?? []).map(String))].slice(0, 16);
609973
+ state.salience.push({
609974
+ id: hashTelegramSocialId(["salience", input.sessionKey, input.messageId ?? now, signals.join("|")]),
609975
+ ts: now,
609976
+ chatId: String(input.chatId),
609977
+ messageId: input.messageId,
609978
+ messageThreadId: input.messageThreadId,
609979
+ senderKey: senderKey3,
609980
+ actorKind: telegramSocialActorKind(input),
609981
+ signals,
609982
+ textPreview: compact2(text, 240)
609983
+ });
609984
+ state.salience = state.salience.slice(-TELEGRAM_SOCIAL_LIMITS.salience);
609985
+ }
609986
+ function retireStaleDaydreamOpportunities(state, now) {
609987
+ for (const item of Object.values(state.daydreamOpportunities)) {
609988
+ if (item.lifecycle === "retired" || now - item.updatedAt <= TELEGRAM_SOCIAL_LIMITS.daydreamStaleMs) continue;
609989
+ item.lifecycle = "retired";
609990
+ item.retiredAt = now;
609991
+ item.updatedAt = now;
609992
+ }
609993
+ const entries = Object.values(state.daydreamOpportunities).sort((a2, b) => b.updatedAt - a2.updatedAt);
609994
+ state.daydreamOpportunities = Object.fromEntries(entries.slice(0, TELEGRAM_SOCIAL_LIMITS.daydreamOpportunities).map((item) => [item.id, item]));
609995
+ }
609996
+ function trimSocialState(state, now) {
609997
+ state.relationships = state.relationships.sort((a2, b) => b.lastSeenAt - a2.lastSeenAt).slice(0, TELEGRAM_SOCIAL_LIMITS.relationships);
609998
+ state.salience = state.salience.slice(-TELEGRAM_SOCIAL_LIMITS.salience);
609999
+ state.outcomes = state.outcomes.slice(-TELEGRAM_SOCIAL_LIMITS.outcomes);
610000
+ retireStaleDaydreamOpportunities(state, now);
610001
+ }
610002
+ function setPreference(vector, key, value2, confidence2, messageId, now, note) {
610003
+ const existing = vector[key];
610004
+ vector[key] = {
610005
+ value: existing ? existing.value * 0.7 + value2 * 0.3 : value2,
610006
+ confidence: Math.max(existing?.confidence ?? 0, clamp019(confidence2)),
610007
+ updatedAt: now,
610008
+ evidenceMessageIds: appendUnique(existing?.evidenceMessageIds ?? [], messageId, 12),
610009
+ note
610010
+ };
610011
+ }
610012
+ function replyNote(input) {
610013
+ const target = input.replySender ? input.replySender.username || input.replySender.firstName || String(input.replySender.userId || "unknown") : `message ${input.replyToMessageId}`;
610014
+ return `reply relationship to ${target}`;
610015
+ }
610016
+ var init_telegram_social_state = __esm({
610017
+ "packages/cli/src/tui/telegram-social-state.ts"() {
610018
+ "use strict";
610019
+ init_telegram_social_state_types();
610020
+ init_telegram_social_state_types();
610021
+ init_telegram_social_state_context();
610022
+ init_telegram_social_state_normalize();
610023
+ }
610024
+ });
610025
+
609418
610026
  // packages/cli/src/tui/vision-ingress.ts
609419
610027
  var vision_ingress_exports = {};
609420
610028
  __export(vision_ingress_exports, {
@@ -609573,7 +610181,29 @@ import { mkdirSync as mkdirSync65, existsSync as existsSync113, unlinkSync as un
609573
610181
  import { join as join127, resolve as resolve43, basename as basename27, relative as relative13, isAbsolute as isAbsolute8, extname as extname16 } from "node:path";
609574
610182
  import { homedir as homedir40 } from "node:os";
609575
610183
  import { writeFile as writeFileAsync } from "node:fs/promises";
609576
- import { createHash as createHash23, randomBytes as randomBytes22, randomInt } from "node:crypto";
610184
+ import { createHash as createHash24, randomBytes as randomBytes22, randomInt } from "node:crypto";
610185
+ function cleanTelegramDecisionNote(value2, maxLength = 260) {
610186
+ if (typeof value2 !== "string") return void 0;
610187
+ const clean5 = stripTelegramHiddenThinking(value2).replace(/\s+/g, " ").trim();
610188
+ if (!clean5) return void 0;
610189
+ return clean5.length > maxLength ? `${clean5.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...` : clean5;
610190
+ }
610191
+ function telegramDecisionNote(parsed, keys, nestedKeys = ["internal_notes", "internalNotes", "notes"]) {
610192
+ for (const key of keys) {
610193
+ const direct = cleanTelegramDecisionNote(parsed[key]);
610194
+ if (direct) return direct;
610195
+ }
610196
+ for (const nestedKey of nestedKeys) {
610197
+ const nested = parsed[nestedKey];
610198
+ if (!nested || typeof nested !== "object" || Array.isArray(nested)) continue;
610199
+ const record = nested;
610200
+ for (const key of keys) {
610201
+ const value2 = cleanTelegramDecisionNote(record[key]);
610202
+ if (value2) return value2;
610203
+ }
610204
+ }
610205
+ return void 0;
610206
+ }
609577
610207
  function parseTelegramInteractionDecision(text, forcedRoute, options2 = {}) {
609578
610208
  const cleaned = stripTelegramHiddenThinking(text).replace(/```(?:json)?/gi, "").replace(/```/g, "").trim();
609579
610209
  const jsonText = cleaned.startsWith("{") ? cleaned : cleaned.match(/\{[\s\S]*\}/)?.[0] ?? "";
@@ -609603,7 +610233,11 @@ function parseTelegramInteractionDecision(text, forcedRoute, options2 = {}) {
609603
610233
  attentionDelta: Number.isFinite(attentionDeltaRaw) ? Math.max(-1, Math.min(1, attentionDeltaRaw)) : void 0,
609604
610234
  attentionScore: Number.isFinite(attentionScoreRaw) ? Math.max(0, Math.min(1, attentionScoreRaw)) : void 0,
609605
610235
  nextCheckAfterMessages: Number.isFinite(nextMessagesRaw) ? Math.max(1, Math.floor(nextMessagesRaw)) : void 0,
609606
- nextCheckAfterMs: Number.isFinite(nextMsRaw) ? Math.max(0, Math.floor(nextMsRaw)) : void 0
610236
+ nextCheckAfterMs: Number.isFinite(nextMsRaw) ? Math.max(0, Math.floor(nextMsRaw)) : void 0,
610237
+ silentDisposition: telegramDecisionNote(parsed, ["silent_disposition", "silentDisposition", "disposition"]),
610238
+ mentalNote: telegramDecisionNote(parsed, ["mental_note", "mentalNote", "observation", "insight"]),
610239
+ memoryNote: telegramDecisionNote(parsed, ["memory_note", "memoryNote", "memory"]),
610240
+ relationshipNote: telegramDecisionNote(parsed, ["relationship_note", "relationshipNote", "relationship"])
609607
610241
  };
609608
610242
  } catch {
609609
610243
  return null;
@@ -609817,8 +610451,8 @@ function stripTelegramHiddenThinking(text) {
609817
610451
  return withoutClosedThink.replace(/<think>[\s\S]*$/gi, "");
609818
610452
  }
609819
610453
  function sanitizeTelegramProgressText(text, maxLength) {
609820
- const compact2 = stripTelegramHiddenThinking(text).replace(/\s+/g, " ").trim();
609821
- return compact2.length > maxLength ? compact2.slice(0, Math.max(0, maxLength - 3)) + "..." : compact2;
610454
+ const compact3 = stripTelegramHiddenThinking(text).replace(/\s+/g, " ").trim();
610455
+ return compact3.length > maxLength ? compact3.slice(0, Math.max(0, maxLength - 3)) + "..." : compact3;
609822
610456
  }
609823
610457
  function isCodebaseMemoryStatus(text) {
609824
610458
  return /^\s*\[CODEBASE MEMORY\]/i.test(stripTelegramHiddenThinking(text));
@@ -609860,26 +610494,26 @@ function isTelegramNoReplySentinel(text) {
609860
610494
  return lower === "no_reply" || lower.startsWith("no_reply");
609861
610495
  }
609862
610496
  function isTelegramInternalStatusText(text) {
609863
- const compact2 = compactTelegramVisibleText(text);
609864
- if (!compact2) return false;
609865
- const lower = compact2.toLowerCase();
609866
- if (isTelegramNoReplySentinel(compact2)) return true;
610497
+ const compact3 = compactTelegramVisibleText(text);
610498
+ if (!compact3) return false;
610499
+ const lower = compact3.toLowerCase();
610500
+ if (isTelegramNoReplySentinel(compact3)) return true;
609867
610501
  if (lower === "complete" || lower === "completed") return true;
609868
- if (/^memory stage:/i.test(compact2)) return true;
609869
- if (/^\[ppr[-_\s]?skip\]/i.test(compact2)) return true;
609870
- if (/^(casual|ambient|group)\b.{0,180}\b(skipping|skipped|not directed|no action needed|no reply)\b/i.test(compact2)) return true;
609871
- if (/^no further action needed\b/i.test(compact2)) return true;
609872
- if (/^no action needed\b.{0,120}\b(task|complete|completed|done)\b/i.test(compact2)) return true;
609873
- if (/^(there'?s|there is) no active task\b/i.test(compact2)) return true;
609874
- if (/^everything'?s (done|complete|completed|wrapped up)\b/i.test(compact2)) return true;
609875
- if (/\balready (been )?(provided|answered|handled|delivered) above\b/i.test(compact2)) return true;
609876
- if (/\b(no remaining work|nothing left to do|task is complete|task has been completed)\b/i.test(compact2)) return true;
610502
+ if (/^memory stage:/i.test(compact3)) return true;
610503
+ if (/^\[ppr[-_\s]?skip\]/i.test(compact3)) return true;
610504
+ if (/^(casual|ambient|group)\b.{0,180}\b(skipping|skipped|not directed|no action needed|no reply)\b/i.test(compact3)) return true;
610505
+ if (/^no further action needed\b/i.test(compact3)) return true;
610506
+ if (/^no action needed\b.{0,120}\b(task|complete|completed|done)\b/i.test(compact3)) return true;
610507
+ if (/^(there'?s|there is) no active task\b/i.test(compact3)) return true;
610508
+ if (/^everything'?s (done|complete|completed|wrapped up)\b/i.test(compact3)) return true;
610509
+ if (/\balready (been )?(provided|answered|handled|delivered) above\b/i.test(compact3)) return true;
610510
+ if (/\b(no remaining work|nothing left to do|task is complete|task has been completed)\b/i.test(compact3)) return true;
609877
610511
  return false;
609878
610512
  }
609879
610513
  function isTelegramStuckSelfTalkSegment(text) {
609880
- const compact2 = text.trim();
609881
- if (!compact2) return false;
609882
- return TELEGRAM_STUCK_SELF_TALK_PREFIXES.some((re) => re.test(compact2));
610514
+ const compact3 = text.trim();
610515
+ if (!compact3) return false;
610516
+ return TELEGRAM_STUCK_SELF_TALK_PREFIXES.some((re) => re.test(compact3));
609883
610517
  }
609884
610518
  function stripTelegramStuckSelfTalk(text) {
609885
610519
  if (!text) return "";
@@ -609947,9 +610581,12 @@ function truncateTelegramContext(text, maxLength) {
609947
610581
  [Telegram context truncated; use tools for full detail.]`;
609948
610582
  }
609949
610583
  function truncateTelegramContextLine(text, maxLength = TELEGRAM_CONTEXT_LINE_LIMIT) {
609950
- const compact2 = stripTelegramHiddenThinking(text).replace(/\s+/g, " ").trim();
609951
- if (compact2.length <= maxLength) return compact2;
609952
- return `${compact2.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;
610584
+ const compact3 = stripTelegramHiddenThinking(text).replace(/\s+/g, " ").trim();
610585
+ if (compact3.length <= maxLength) return compact3;
610586
+ return `${compact3.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;
610587
+ }
610588
+ function telegramRegexEscape(text) {
610589
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
609953
610590
  }
609954
610591
  function redactTelegramLocalPaths(text) {
609955
610592
  return text.replace(/\/(?:home|root|tmp|var|etc|usr|opt|mnt|media|srv|run)\/[^\s"'`<>)]*/g, "[local-path-redacted]");
@@ -610156,7 +610793,7 @@ function buildTelegramRuntimeContext(now = /* @__PURE__ */ new Date(), repoRoot)
610156
610793
  ].filter(Boolean).join("\n");
610157
610794
  }
610158
610795
  function telegramSessionIdFromKey(sessionKey) {
610159
- return `telegram-${createHash23("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
610796
+ return `telegram-${createHash24("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
610160
610797
  }
610161
610798
  function selectTelegramFinalResponse(args) {
610162
610799
  const committedVisibleReply = cleanTelegramVisibleReply(args.visibleReplyText || "");
@@ -610983,6 +611620,7 @@ var init_telegram_bridge = __esm({
610983
611620
  init_telegram_reflection_corpus();
610984
611621
  init_memory_paths();
610985
611622
  init_telegram_reflection_extraction();
611623
+ init_telegram_social_state();
610986
611624
  init_dist7();
610987
611625
  TELEGRAM_TOOL_ACTION_GROUPS = [
610988
611626
  "read",
@@ -611379,6 +612017,7 @@ External acquisition contract:
611379
612017
  lastUpdateId = 0;
611380
612018
  state = {
611381
612019
  active: false,
612020
+ botUserId: void 0,
611382
612021
  botUsername: "",
611383
612022
  botFirstName: void 0,
611384
612023
  supportsGuestQueries: false,
@@ -611403,6 +612042,8 @@ External acquisition contract:
611403
612042
  chatMemoryCards = /* @__PURE__ */ new Map();
611404
612043
  /** Durable associative memory by scoped Telegram chat key. */
611405
612044
  chatAssociativeMemory = /* @__PURE__ */ new Map();
612045
+ /** Durable social cognition state by scoped Telegram chat key. */
612046
+ chatSocialState = /* @__PURE__ */ new Map();
611406
612047
  /** Generic chronological attention cadence shared by live surfaces. */
611407
612048
  stimulation = new StimulationController();
611408
612049
  /** Throttles noisy "skipped group chatter" waterfall logs */
@@ -611550,6 +612191,38 @@ External acquisition contract:
611550
612191
  get botUsername() {
611551
612192
  return this.state.botUsername;
611552
612193
  }
612194
+ currentTelegramBotUserId() {
612195
+ const stateId = this.state.botUserId;
612196
+ if (typeof stateId === "number" && Number.isFinite(stateId)) return stateId;
612197
+ if (typeof this.botUserId === "number" && Number.isFinite(this.botUserId)) return this.botUserId;
612198
+ return void 0;
612199
+ }
612200
+ telegramSelfIdentitySignals() {
612201
+ const username = this.state.botUsername.trim().replace(/^@/, "");
612202
+ const firstName = this.state.botFirstName?.trim() ?? "";
612203
+ const botUserId = this.currentTelegramBotUserId();
612204
+ return [
612205
+ username ? `@${username}` : "",
612206
+ username,
612207
+ firstName,
612208
+ botUserId !== void 0 ? `telegram_user_id:${botUserId}` : ""
612209
+ ];
612210
+ }
612211
+ buildTelegramSelfIdentityContext() {
612212
+ const username = this.state.botUsername.trim().replace(/^@/, "");
612213
+ const firstName = this.state.botFirstName?.trim() ?? "";
612214
+ const botUserId = this.currentTelegramBotUserId();
612215
+ const detail = [
612216
+ botUserId !== void 0 ? `user_id=${botUserId}` : "user_id=unknown",
612217
+ username ? `username=@${username}` : "username=unknown",
612218
+ firstName ? `display_name=${firstName}` : "display_name=unknown"
612219
+ ].join(", ");
612220
+ return [
612221
+ `Telegram bot self identity: ${detail}.`,
612222
+ `Known self identity signals (context only, not triggers): ${formatTelegramIdentitySignals(this.telegramSelfIdentitySignals())}.`,
612223
+ `Use these signals to infer whether heard text is probably aimed at this bot; identity matches raise salience but never force should_reply.`
612224
+ ].join("\n");
612225
+ }
611553
612226
  beginAdminAuthChallenge(ttlMs = 5 * 60 * 1e3) {
611554
612227
  const code8 = String(randomInt(1e5, 1e6));
611555
612228
  this.adminAuthChallenge = {
@@ -611572,11 +612245,61 @@ External acquisition contract:
611572
612245
  return !!this.adminAuthChallenge && this.adminAuthChallenge.expiresAtMs > Date.now();
611573
612246
  }
611574
612247
  hashAdminAuthCode(code8) {
611575
- return createHash23("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
612248
+ return createHash24("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
611576
612249
  }
611577
612250
  viewIdForMessage(msg) {
611578
612251
  return `telegram-${this.sessionKeyForMessage(msg).replace(/[^A-Za-z0-9_-]/g, "-")}`;
611579
612252
  }
612253
+ attentionViewIdForMessage(msg) {
612254
+ const id = Number.isFinite(msg.messageId) ? msg.messageId : Date.now();
612255
+ return `${this.viewIdForMessage(msg)}-heard-${id}`;
612256
+ }
612257
+ registerTelegramAttentionView(msg, toolContext, detail = "heard message") {
612258
+ if (!this.subAgentViewCallbacks) return null;
612259
+ const viewId = this.attentionViewIdForMessage(msg);
612260
+ const preview = truncateTelegramContextLine(msg.text || summarizeTelegramMessageAttachments(msg) || "[non-text Telegram message]", 160);
612261
+ const chat = msg.chatTitle || msg.chatType;
612262
+ this.subAgentViewCallbacks.onRegister(
612263
+ viewId,
612264
+ `✈ heard @${msg.username || "telegram"}`,
612265
+ `Telegram attention: ${preview}`
612266
+ );
612267
+ this.subAgentViewCallbacks.onWrite(
612268
+ viewId,
612269
+ `heard: @${msg.username || "unknown"} [${telegramActorKindLabel(msg)}] in ${chat}: ${preview}`
612270
+ );
612271
+ const replyEdge = this.formatTelegramReplyEdgeForTui(this.sessionKeyForMessage(msg), msg);
612272
+ if (replyEdge) this.subAgentViewCallbacks.onWrite(viewId, replyEdge);
612273
+ this.subAgentViewCallbacks.onWrite(viewId, `context: ${detail}; tool_context=${toolContext}; assessing attention, memory, and relationship state`);
612274
+ this.subAgentViewCallbacks.onStatus(viewId, "running");
612275
+ return viewId;
612276
+ }
612277
+ writeTelegramAttentionDecision(viewId, decision) {
612278
+ if (!viewId || !this.subAgentViewCallbacks) return;
612279
+ const route = decision.shouldReply ? `reply via ${decision.route}` : "silent";
612280
+ const attention = [
612281
+ decision.attentionState ? `state=${decision.attentionState}` : "",
612282
+ decision.attentionDelta !== void 0 ? `delta=${decision.attentionDelta.toFixed(2)}` : "",
612283
+ decision.attentionScore !== void 0 ? `score=${decision.attentionScore.toFixed(2)}` : ""
612284
+ ].filter(Boolean).join(", ");
612285
+ const cadence = [
612286
+ decision.nextCheckAfterMessages !== void 0 ? `after ${decision.nextCheckAfterMessages} message(s)` : "",
612287
+ decision.nextCheckAfterMs !== void 0 ? `after ${Math.round(decision.nextCheckAfterMs / 1e3)}s` : ""
612288
+ ].filter(Boolean).join(" or ");
612289
+ const lines = [
612290
+ `decision: ${route} (${decision.source}, confidence ${decision.confidence.toFixed(2)})`,
612291
+ attention ? `attention: ${attention}` : "",
612292
+ `reason: ${decision.reason}`,
612293
+ decision.silentDisposition ? `silent disposition: ${decision.silentDisposition}` : "",
612294
+ decision.mentalNote ? `mental note: ${decision.mentalNote}` : "",
612295
+ decision.memoryNote ? `memory note: ${decision.memoryNote}` : "",
612296
+ decision.relationshipNote ? `relationship note: ${decision.relationshipNote}` : "",
612297
+ cadence ? `next attention sample: ${cadence}` : ""
612298
+ ].filter(Boolean);
612299
+ this.subAgentViewCallbacks.onWrite(viewId, lines.join("\n"));
612300
+ this.subAgentViewCallbacks.onStatus(viewId, "completed");
612301
+ this.subAgentViewCallbacks.onComplete(viewId);
612302
+ }
611580
612303
  normalizeTelegramCommandText(input) {
611581
612304
  const trimmed = input.trim();
611582
612305
  if (!trimmed.startsWith("/")) return input;
@@ -611776,7 +612499,10 @@ No scoped reflection artifact exists yet for this chat. Use <code>/reflect</code
611776
612499
  if (!sender) return void 0;
611777
612500
  const bot = this.state.botUsername.trim().replace(/^@/, "").toLowerCase();
611778
612501
  const senderUsername = sender.username?.trim().replace(/^@/, "").toLowerCase();
611779
- const isSelf = Boolean(sender.isSelf || bot && senderUsername === bot);
612502
+ const botUserId = this.currentTelegramBotUserId();
612503
+ const isSelf = Boolean(
612504
+ sender.isSelf || bot && senderUsername === bot || botUserId !== void 0 && sender.id === botUserId
612505
+ );
611780
612506
  return isSelf === sender.isSelf ? sender : { ...sender, isSelf };
611781
612507
  }
611782
612508
  telegramReplyContextFromHistoryEntry(entry) {
@@ -611995,11 +612721,11 @@ ${mediaContext}` : ""
611995
612721
  return payload;
611996
612722
  }
611997
612723
  telegramConversationPath(sessionKey) {
611998
- const safe = createHash23("sha1").update(sessionKey).digest("hex").slice(0, 20);
612724
+ const safe = createHash24("sha1").update(sessionKey).digest("hex").slice(0, 20);
611999
612725
  return join127(this.telegramConversationDir, `${safe}.json`);
612000
612726
  }
612001
612727
  telegramConversationLedgerPath(sessionKey) {
612002
- const safe = createHash23("sha1").update(sessionKey).digest("hex").slice(0, 20);
612728
+ const safe = createHash24("sha1").update(sessionKey).digest("hex").slice(0, 20);
612003
612729
  return join127(this.telegramConversationDir, `${safe}.events.jsonl`);
612004
612730
  }
612005
612731
  telegramDb() {
@@ -612227,7 +612953,7 @@ ${mediaContext}` : ""
612227
612953
  users,
612228
612954
  relationships: Array.isArray(raw.relationships) ? raw.relationships.slice(0, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT).map((fact) => this.normalizeTelegramAssociativeFact(fact)) : [],
612229
612955
  actions: Array.isArray(raw.actions) ? raw.actions.slice(-TELEGRAM_ASSOCIATIVE_ACTION_LIMIT).map((action) => ({
612230
- id: String(action.id || createHash23("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)),
612956
+ id: String(action.id || createHash24("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)),
612231
612957
  ts: typeof action.ts === "number" ? action.ts : Date.now(),
612232
612958
  role: action.role === "assistant" ? "assistant" : "user",
612233
612959
  speaker: String(action.speaker || "unknown"),
@@ -612244,7 +612970,7 @@ ${mediaContext}` : ""
612244
612970
  const text = String(raw.text || "").trim();
612245
612971
  const now = Date.now();
612246
612972
  return {
612247
- id: String(raw.id || createHash23("sha1").update(text || String(now)).digest("hex").slice(0, 12)),
612973
+ id: String(raw.id || createHash24("sha1").update(text || String(now)).digest("hex").slice(0, 12)),
612248
612974
  text,
612249
612975
  tags: Array.isArray(raw.tags) ? raw.tags.map(String).slice(0, 16) : [],
612250
612976
  speakers: Array.isArray(raw.speakers) ? raw.speakers.map(String).slice(0, 16) : [],
@@ -612265,6 +612991,98 @@ ${mediaContext}` : ""
612265
612991
  }
612266
612992
  return memory;
612267
612993
  }
612994
+ telegramSocialStateForSession(sessionKey) {
612995
+ this.ensureTelegramConversationLoaded(sessionKey);
612996
+ let state = this.chatSocialState.get(sessionKey);
612997
+ if (!state) {
612998
+ state = createTelegramSocialState();
612999
+ this.chatSocialState.set(sessionKey, state);
613000
+ }
613001
+ return state;
613002
+ }
613003
+ telegramSelfSocialActorInput() {
613004
+ return {
613005
+ userId: this.currentTelegramBotUserId(),
613006
+ username: this.state.botUsername || void 0,
613007
+ firstName: this.state.botFirstName || "Omnius",
613008
+ isBot: true,
613009
+ isSelf: true
613010
+ };
613011
+ }
613012
+ telegramMessageSocialActorInput(msg) {
613013
+ return {
613014
+ userId: msg.fromUserId,
613015
+ username: msg.username,
613016
+ firstName: msg.firstName,
613017
+ isBot: Boolean(msg.isBot)
613018
+ };
613019
+ }
613020
+ telegramReplySocialActorInput(msg) {
613021
+ const sender = msg.replyContext?.sender;
613022
+ if (sender) {
613023
+ return {
613024
+ userId: sender.id,
613025
+ username: sender.username,
613026
+ firstName: sender.firstName || sender.title,
613027
+ isBot: Boolean(sender.isBot || sender.isSelf),
613028
+ isSelf: Boolean(sender.isSelf)
613029
+ };
613030
+ }
613031
+ if (!msg.replyToUsername) return void 0;
613032
+ return {
613033
+ username: msg.replyToUsername,
613034
+ isBot: Boolean(msg.replyToBot)
613035
+ };
613036
+ }
613037
+ observeTelegramSocialMessage(sessionKey, msg, text, salienceSignals) {
613038
+ try {
613039
+ observeTelegramSocialMessage(this.telegramSocialStateForSession(sessionKey), {
613040
+ sessionKey,
613041
+ chatId: msg.chatId,
613042
+ chatType: msg.chatType,
613043
+ chatTitle: msg.chatTitle,
613044
+ text,
613045
+ messageId: msg.messageId,
613046
+ messageThreadId: msg.messageThreadId,
613047
+ replyToMessageId: msg.replyToMessageId,
613048
+ replySender: this.telegramReplySocialActorInput(msg),
613049
+ salienceSignals: salienceSignals ?? this.telegramMessageIdentitySalienceSignals(msg),
613050
+ self: this.telegramSelfSocialActorInput(),
613051
+ ...this.telegramMessageSocialActorInput(msg)
613052
+ });
613053
+ } catch {
613054
+ }
613055
+ }
613056
+ hydrateTelegramSocialStateFromHistory(sessionKey, history) {
613057
+ const state = createTelegramSocialState();
613058
+ this.chatSocialState.set(sessionKey, state);
613059
+ for (const entry of history) {
613060
+ if (entry.role !== "user") continue;
613061
+ observeTelegramSocialMessage(state, {
613062
+ sessionKey,
613063
+ chatId: entry.chatId ?? sessionKey.replace(/^chat:/, ""),
613064
+ chatType: entry.chatType,
613065
+ chatTitle: entry.chatTitle,
613066
+ text: entry.text,
613067
+ messageId: entry.messageId,
613068
+ messageThreadId: entry.messageThreadId,
613069
+ replyToMessageId: entry.replyToMessageId,
613070
+ replySender: entry.replyContext?.sender ? {
613071
+ userId: entry.replyContext.sender.id,
613072
+ username: entry.replyContext.sender.username,
613073
+ firstName: entry.replyContext.sender.firstName || entry.replyContext.sender.title,
613074
+ isBot: Boolean(entry.replyContext.sender.isBot || entry.replyContext.sender.isSelf),
613075
+ isSelf: Boolean(entry.replyContext.sender.isSelf)
613076
+ } : void 0,
613077
+ self: this.telegramSelfSocialActorInput(),
613078
+ userId: entry.fromUserId,
613079
+ username: entry.username,
613080
+ firstName: entry.firstName,
613081
+ isBot: Boolean(entry.isBot),
613082
+ ts: entry.ts
613083
+ });
613084
+ }
613085
+ }
612268
613086
  telegramPersonalityScope(sessionKey, msg) {
612269
613087
  const label = msg.chatType !== "private" ? `${msg.chatTitle || msg.chatType}-${String(msg.chatId)}` : `private-${msg.username || msg.fromUserId || msg.chatId}`;
612270
613088
  return {
@@ -612324,6 +613142,11 @@ ${mediaContext}` : ""
612324
613142
  } else if (loadedHistory.length > 0) {
612325
613143
  this.hydrateTelegramAssociativeMemoryFromHistory(sessionKey, loadedHistory);
612326
613144
  }
613145
+ if (parsed.socialState) {
613146
+ this.chatSocialState.set(sessionKey, normalizeTelegramSocialState(parsed.socialState));
613147
+ } else if (loadedHistory.length > 0) {
613148
+ this.hydrateTelegramSocialStateFromHistory(sessionKey, loadedHistory);
613149
+ }
612327
613150
  if (loadedHistory.length > 0) {
612328
613151
  this.backfillTelegramLoadedHistory(sessionKey, loadedHistory);
612329
613152
  }
@@ -612349,7 +613172,7 @@ ${mediaContext}` : ""
612349
613172
  }
612350
613173
  telegramHistoryBackfillMessageId(sessionKey, entry, index) {
612351
613174
  if (typeof entry.messageId === "number" && Number.isFinite(entry.messageId)) return entry.messageId;
612352
- const digest3 = createHash23("sha1").update(`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`).digest("hex").slice(0, 8);
613175
+ const digest3 = createHash24("sha1").update(`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`).digest("hex").slice(0, 8);
612353
613176
  return -Number.parseInt(digest3, 16);
612354
613177
  }
612355
613178
  backfillTelegramLoadedHistory(sessionKey, history) {
@@ -612496,6 +613319,7 @@ ${mediaContext}` : ""
612496
613319
  participants,
612497
613320
  memoryCards: this.chatMemoryCards.get(sessionKey) ?? [],
612498
613321
  associativeMemory: this.telegramAssociativeMemoryForSession(sessionKey),
613322
+ socialState: this.telegramSocialStateForSession(sessionKey),
612499
613323
  stimulation: this.stimulation.getState(sessionKey),
612500
613324
  reflection: this.channelReflectionState.get(sessionKey) ?? { autoFollowup: false }
612501
613325
  };
@@ -612768,6 +613592,7 @@ ${mediaContext}` : ""
612768
613592
  }
612769
613593
  }
612770
613594
  formatLatestTelegramChannelDaydreamContext(sessionKey) {
613595
+ this.registerLatestTelegramDaydreamOpportunities(sessionKey);
612771
613596
  return formatTelegramChannelDaydreamContext(this.latestTelegramChannelDaydream(sessionKey));
612772
613597
  }
612773
613598
  shouldForceAnalysisFromChannelDaydream(sessionKey) {
@@ -612781,6 +613606,81 @@ ${mediaContext}` : ""
612781
613606
  this.channelDmnPromptedArtifactAt.set(sessionKey, artifact.generatedAt);
612782
613607
  return true;
612783
613608
  }
613609
+ latestTelegramDaydreamOpportunityInputs(sessionKey) {
613610
+ const artifact = this.latestTelegramChannelDaydream(sessionKey);
613611
+ if (!artifact || artifact.replyOpportunities.length === 0) return [];
613612
+ return artifact.replyOpportunities.map((opportunity) => ({
613613
+ id: opportunity.id,
613614
+ trigger: opportunity.trigger,
613615
+ confidence: opportunity.confidence,
613616
+ artifactId: artifact.id,
613617
+ generatedAt: artifact.generatedAt
613618
+ }));
613619
+ }
613620
+ registerLatestTelegramDaydreamOpportunities(sessionKey) {
613621
+ const opportunities = this.latestTelegramDaydreamOpportunityInputs(sessionKey);
613622
+ if (opportunities.length === 0) return;
613623
+ try {
613624
+ registerDaydreamOpportunities(this.telegramSocialStateForSession(sessionKey), opportunities);
613625
+ } catch {
613626
+ }
613627
+ }
613628
+ markLatestTelegramDaydreamOpportunitiesConsidered(sessionKey, msg) {
613629
+ const opportunities = this.latestTelegramDaydreamOpportunityInputs(sessionKey);
613630
+ if (opportunities.length === 0) return [];
613631
+ try {
613632
+ markTelegramDaydreamOpportunitiesConsidered(this.telegramSocialStateForSession(sessionKey), opportunities, msg.messageId);
613633
+ } catch {
613634
+ }
613635
+ return opportunities;
613636
+ }
613637
+ commitTelegramSocialDecision(sessionKey, msg, decision, salienceSignals, daydreamOpportunities = this.latestTelegramDaydreamOpportunityInputs(sessionKey)) {
613638
+ try {
613639
+ commitTelegramSocialDecision(this.telegramSocialStateForSession(sessionKey), {
613640
+ sessionKey,
613641
+ chatId: msg.chatId,
613642
+ messageId: msg.messageId,
613643
+ messageThreadId: msg.messageThreadId,
613644
+ sender: this.telegramMessageSocialActorInput(msg),
613645
+ replyToMessageId: msg.replyToMessageId,
613646
+ route: decision.route,
613647
+ shouldReply: decision.shouldReply,
613648
+ confidence: decision.confidence,
613649
+ reason: decision.reason,
613650
+ source: decision.source,
613651
+ silentDisposition: decision.silentDisposition,
613652
+ mentalNote: decision.mentalNote,
613653
+ memoryNote: decision.memoryNote,
613654
+ relationshipNote: decision.relationshipNote,
613655
+ salienceSignals,
613656
+ self: this.telegramSelfSocialActorInput(),
613657
+ daydreamOpportunities
613658
+ });
613659
+ this.saveTelegramConversationState(sessionKey);
613660
+ } catch {
613661
+ }
613662
+ }
613663
+ buildTelegramSocialStateContext(sessionKey, msg, salienceSignals = []) {
613664
+ try {
613665
+ this.registerLatestTelegramDaydreamOpportunities(sessionKey);
613666
+ return formatTelegramSocialStateContext(this.telegramSocialStateForSession(sessionKey), {
613667
+ sessionKey,
613668
+ chatId: msg.chatId,
613669
+ chatType: msg.chatType,
613670
+ chatTitle: msg.chatTitle,
613671
+ text: msg.text,
613672
+ messageId: msg.messageId,
613673
+ messageThreadId: msg.messageThreadId,
613674
+ replyToMessageId: msg.replyToMessageId,
613675
+ replySender: this.telegramReplySocialActorInput(msg),
613676
+ salienceSignals,
613677
+ self: this.telegramSelfSocialActorInput(),
613678
+ ...this.telegramMessageSocialActorInput(msg)
613679
+ });
613680
+ } catch {
613681
+ return "";
613682
+ }
613683
+ }
612784
613684
  renderTelegramScopedPersonality(sessionKey, msg) {
612785
613685
  try {
612786
613686
  return buildScopedPersonalityContext(this.telegramPersonalityScope(sessionKey, msg));
@@ -612856,6 +613756,7 @@ ${mediaContext}` : ""
612856
613756
  this.updateTelegramParticipantProfile(sessionKey, msg, text);
612857
613757
  this.updateTelegramMemoryCards(sessionKey, entry);
612858
613758
  this.updateTelegramAssociativeMemory(sessionKey, entry);
613759
+ this.observeTelegramSocialMessage(sessionKey, msg, text);
612859
613760
  try {
612860
613761
  updateScopedPersonality(this.telegramPersonalityScope(sessionKey, msg), {
612861
613762
  speaker: telegramSpeakerLabel(msg),
@@ -613097,7 +613998,7 @@ ${mediaContext}` : ""
613097
613998
  const now = entry.ts ?? Date.now();
613098
613999
  memory.updatedAt = now;
613099
614000
  const speaker = telegramHistorySpeaker(entry);
613100
- const actionId = createHash23("sha1").update(`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now}:${entry.text}`).digest("hex").slice(0, 16);
614001
+ const actionId = createHash24("sha1").update(`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now}:${entry.text}`).digest("hex").slice(0, 16);
613101
614002
  if (!memory.actions.some((action) => action.id === actionId)) {
613102
614003
  memory.actions.push({
613103
614004
  id: actionId,
@@ -613158,9 +614059,9 @@ ${mediaContext}` : ""
613158
614059
  if (!userMemory.toneTags.includes(tag)) userMemory.toneTags.push(tag);
613159
614060
  }
613160
614061
  userMemory.toneTags = userMemory.toneTags.slice(0, 20);
613161
- const compact2 = stripTelegramHiddenThinking(entry.text || "").replace(/\s+/g, " ").trim();
613162
- if (compact2) {
613163
- userMemory.lastMessages.push(compact2);
614062
+ const compact3 = stripTelegramHiddenThinking(entry.text || "").replace(/\s+/g, " ").trim();
614063
+ if (compact3) {
614064
+ userMemory.lastMessages.push(compact3);
613164
614065
  userMemory.lastMessages = userMemory.lastMessages.slice(-40);
613165
614066
  }
613166
614067
  for (const topic of telegramMemoryTags(entry.text, entry.mediaSummary).slice(0, 6)) {
@@ -613219,7 +614120,7 @@ ${mediaContext}` : ""
613219
614120
  let fact = facts.find((item) => item.text.toLowerCase() === key);
613220
614121
  if (!fact) {
613221
614122
  fact = {
613222
- id: createHash23("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
614123
+ id: createHash24("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
613223
614124
  text: clean5,
613224
614125
  tags: telegramMemoryTags(clean5, entry.mediaSummary),
613225
614126
  speakers: [],
@@ -613274,7 +614175,7 @@ ${mediaContext}` : ""
613274
614175
  const titleTags = tags.slice(0, 4);
613275
614176
  const title = titleTags.length > 0 ? `${speaker} / ${titleTags.join(" ")}` : `${speaker} / conversation`;
613276
614177
  const card = {
613277
- id: createHash23("sha1").update(`${sessionKey}:${now}:${speaker}:${text}`).digest("hex").slice(0, 12),
614178
+ id: createHash24("sha1").update(`${sessionKey}:${now}:${speaker}:${text}`).digest("hex").slice(0, 12),
613278
614179
  title,
613279
614180
  notes: [],
613280
614181
  tags: [],
@@ -614050,7 +614951,7 @@ ${lines.join("\n")}`);
614050
614951
  lines.push(" 5. memory_search accepts NATURAL-LANGUAGE TIME phrases inside the `query` argument or explicit `since`/`until`/`bucket` args. Examples: query='what did manitcor say yesterday', query='last 3 hours', query='earlier today', query='2 days ago', query='since 2026-05-15', query='between 2026-05-15 and 2026-05-16', query='oldest memory about github', query='most recent flux discussion'. Use these for chronological/'how far back' style queries instead of guessing — the tool parses the phrase, filters by time, and returns the right window.");
614051
614952
  return lines.join("\n");
614052
614953
  }
614053
- buildTelegramConversationContextStream(sessionKey, msg, maxRecent = TELEGRAM_CONTEXT_RECENT_DEFAULT) {
614954
+ buildTelegramConversationContextStream(sessionKey, msg, maxRecent = TELEGRAM_CONTEXT_RECENT_DEFAULT, salienceSignals = []) {
614054
614955
  this.ensureTelegramConversationLoaded(sessionKey);
614055
614956
  const history = this.chatHistory.get(sessionKey) ?? [];
614056
614957
  const participants = [...this.chatParticipants.get(sessionKey)?.values() ?? []].sort((a2, b) => b.lastSeenTs - a2.lastSeenTs);
@@ -614082,6 +614983,10 @@ ${lines.join("\n")}`);
614082
614983
  if (scopedPersonality) {
614083
614984
  sections.push(scopedPersonality);
614084
614985
  }
614986
+ const socialStateContext = this.buildTelegramSocialStateContext(sessionKey, msg, salienceSignals);
614987
+ if (socialStateContext) {
614988
+ sections.push(socialStateContext);
614989
+ }
614085
614990
  if (participants.length > 0) {
614086
614991
  const participantLines = participants.slice(0, 12).map((profile) => {
614087
614992
  const label = profile.username && profile.username !== "unknown" ? `@${profile.username}` : profile.firstName || `user:${profile.fromUserId}`;
@@ -614215,26 +615120,45 @@ ${lines.join("\n")}`);
614215
615120
  this.groupSkipLogAt.set(sessionKey, now);
614216
615121
  this.tuiWrite(() => renderTelegramSubAgentEvent(msg.username, `${reason} (context retained)`));
614217
615122
  }
614218
- telegramMessageAddressesBot(msg) {
614219
- const bot = this.state.botUsername.trim().replace(/^@/, "").toLowerCase();
614220
- if (!bot) return false;
614221
- const mentioned = (msg.mentionedUsernames ?? []).some(
614222
- (name10) => name10.trim().replace(/^@/, "").toLowerCase() === bot
614223
- );
614224
- if (mentioned) return true;
614225
- if (msg.replyToUsername && msg.replyToUsername.trim().replace(/^@/, "").toLowerCase() === bot) return true;
614226
- const replyUsername = msg.replyContext?.sender?.username?.trim().replace(/^@/, "").toLowerCase();
614227
- if (replyUsername && replyUsername === bot) return true;
615123
+ telegramMessageIdentitySalienceSignals(msg) {
615124
+ const signals = /* @__PURE__ */ new Set();
615125
+ const username = this.state.botUsername.trim().replace(/^@/, "");
615126
+ const usernameLower = username.toLowerCase();
615127
+ const displayName = this.state.botFirstName?.trim() ?? "";
615128
+ const botUserId = this.currentTelegramBotUserId();
615129
+ const text = msg.text || "";
615130
+ if (msg.chatType === "private") signals.add("private_dm_delivery");
615131
+ if (usernameLower) {
615132
+ const mentioned = (msg.mentionedUsernames ?? []).some(
615133
+ (name10) => name10.trim().replace(/^@/, "").toLowerCase() === usernameLower
615134
+ );
615135
+ if (mentioned) signals.add(`entity_mention:@${username}`);
615136
+ const rawMention = new RegExp(`(^|[^A-Za-z0-9_@])@${telegramRegexEscape(username)}(?![A-Za-z0-9_])`, "i");
615137
+ if (rawMention.test(text)) signals.add(`raw_text_mention:@${username}`);
615138
+ if (msg.replyToUsername && msg.replyToUsername.trim().replace(/^@/, "").toLowerCase() === usernameLower) {
615139
+ signals.add(`reply_to_username:@${username}`);
615140
+ }
615141
+ const replyUsername = msg.replyContext?.sender?.username?.trim().replace(/^@/, "").toLowerCase();
615142
+ if (replyUsername && replyUsername === usernameLower) signals.add(`reply_context_username:@${username}`);
615143
+ }
615144
+ if (displayName.length >= 3) {
615145
+ const displayPattern = new RegExp(`(^|[^\\p{L}\\p{N}_])${telegramRegexEscape(displayName)}(?![\\p{L}\\p{N}_])`, "iu");
615146
+ if (displayPattern.test(text)) signals.add(`display_name:${displayName}`);
615147
+ }
615148
+ if (botUserId !== void 0 && msg.replyContext?.sender?.id === botUserId) {
615149
+ signals.add(`reply_context_user_id:${botUserId}`);
615150
+ }
614228
615151
  const resolvedReply = this.resolveTelegramReplyContext(this.sessionKeyForMessage(msg), msg);
614229
- if (resolvedReply?.sender?.isSelf) return true;
614230
- return false;
615152
+ if (resolvedReply?.sender?.isSelf) signals.add("reply_to_self_history");
615153
+ return [...signals];
614231
615154
  }
614232
615155
  telegramMessageRepliesToBot(msg) {
614233
615156
  const bot = this.state.botUsername.trim().replace(/^@/, "").toLowerCase();
614234
- if (!bot) return false;
615157
+ const botUserId = this.currentTelegramBotUserId();
614235
615158
  const legacyReply = msg.replyToUsername?.trim().replace(/^@/, "").toLowerCase();
614236
615159
  const contextReply = msg.replyContext?.sender?.username?.trim().replace(/^@/, "").toLowerCase();
614237
- if (legacyReply === bot || contextReply === bot) return true;
615160
+ if (bot && (legacyReply === bot || contextReply === bot)) return true;
615161
+ if (botUserId !== void 0 && msg.replyContext?.sender?.id === botUserId) return true;
614238
615162
  const resolvedReply = this.resolveTelegramReplyContext(this.sessionKeyForMessage(msg), msg);
614239
615163
  return Boolean(resolvedReply?.sender?.isSelf);
614240
615164
  }
@@ -614252,7 +615176,8 @@ ${lines.join("\n")}`);
614252
615176
  const config = this.agentConfig;
614253
615177
  const forcedRoute = this.interactionMode === "chat" || this.interactionMode === "action" ? this.interactionMode : null;
614254
615178
  const isGroup = msg.chatType !== "private";
614255
- const addressesBot = this.telegramMessageAddressesBot(msg);
615179
+ const identitySalienceSignals = this.telegramMessageIdentitySalienceSignals(msg);
615180
+ const addressesBot = identitySalienceSignals.length > 0;
614256
615181
  const sessionKey = this.sessionKeyForMessage(msg);
614257
615182
  const daydreamForceCheck = isGroup && this.shouldForceAnalysisFromChannelDaydream(sessionKey);
614258
615183
  const stimulationProbe = this.stimulation.observe({
@@ -614269,7 +615194,9 @@ ${lines.join("\n")}`);
614269
615194
  shouldReply: false,
614270
615195
  confidence: 0,
614271
615196
  reason: "router inference unavailable; no model-derived reply decision",
614272
- source: "inference-unavailable"
615197
+ source: "inference-unavailable",
615198
+ silentDisposition: "retained as context without replying",
615199
+ mentalNote: "router unavailable, so no model-derived attention note was produced"
614273
615200
  };
614274
615201
  this.applyTelegramStimulationDecision(sessionKey, fallback2);
614275
615202
  return fallback2;
@@ -614280,19 +615207,14 @@ ${lines.join("\n")}`);
614280
615207
  config.apiKey
614281
615208
  );
614282
615209
  const forcedLine = forcedRoute ? `The operator selected Telegram mode "${forcedRoute}". The route field MUST be "${forcedRoute}", but should_reply must still be inferred live from context.` : `The operator selected Telegram mode "auto". Infer route live from context.`;
614283
- const context2 = this.buildTelegramConversationContextStream(sessionKey, msg, isGroup ? 36 : 20);
615210
+ const context2 = this.buildTelegramConversationContextStream(sessionKey, msg, isGroup ? 36 : 20, identitySalienceSignals);
614284
615211
  const currentReplyContext = this.buildTelegramCurrentReplyContext(sessionKey, msg);
614285
- const botUsername = this.state.botUsername || "unknown";
614286
- const botIdentitySignals = [
614287
- botUsername && botUsername !== "unknown" ? `@${botUsername}` : "",
614288
- botUsername && botUsername !== "unknown" ? botUsername.replace(/^@/, "") : "",
614289
- this.state.botFirstName || ""
614290
- ];
615212
+ const selfIdentityContext = this.buildTelegramSelfIdentityContext();
614291
615213
  const userPrompt = [
614292
615214
  `You are the Telegram live routing and reply-discretion model.`,
614293
615215
  `Return JSON only, with no markdown and no explanation outside JSON.`,
614294
615216
  ``,
614295
- `Schema: {"route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","attention_state":"idle"|"observing"|"engaged"|"cooldown","attention_delta":-1.0..1.0,"next_check_after_messages":1..12}`,
615217
+ `Schema: {"route":"chat"|"action","should_reply":true|false,"confidence":0.0-1.0,"reason":"short reason","attention_state":"idle"|"observing"|"engaged"|"cooldown","attention_delta":-1.0..1.0,"next_check_after_messages":1..12,"silent_disposition":"short outcome-level disposition","mental_note":"short outcome-level observation","memory_note":"short memory/summary update","relationship_note":"short relationship/thread note"}`,
614296
615218
  ``,
614297
615219
  `Route meanings:`,
614298
615220
  `- chat: a short conversational answer can be produced without tools.`,
@@ -614301,7 +615223,9 @@ ${lines.join("\n")}`);
614301
615223
  ``,
614302
615224
  `Reply discretion: make a human-like attention decision from the full social context. Observe the message, relationship stream, reply graph, conversation momentum, prior bot involvement, speaker intent, and notification-like signals, then decide whether a visible reply would be natural.`,
614303
615225
  `No hard triggers: direct address, @mentions, name/identity references, private-chat delivery, replies, active threads, and stimulation score are evidence only. They may raise or lower salience, but none guarantees should_reply=true or should_reply=false.`,
615226
+ `High-salience evidence: private DMs, exact @username matches, display-name self references, and replies to this bot are notification-like signals. They should usually move attention toward deeper processing and a likely response unless the surrounding context makes silence more natural.`,
614304
615227
  `No keyword routing: do not use static keyword rules. Infer whether identity references are actually aimed at this bot from syntax, tone, recent turns, and relationships.`,
615228
+ `Observation notes: always fill silent_disposition, mental_note, memory_note, and relationship_note with concise outcome-level notes for the TUI. Do not expose hidden chain-of-thought; summarize what the bot did with the heard message.`,
614305
615229
  `Bot-to-bot discipline: sender labels include [bot] or [human]. Treat peer bots as autonomous actors, not human users. Avoid bot loops by replying only when the exchange context makes a response socially useful.`,
614306
615230
  `Ingress discipline: this Telegram message has already been retained as chat context. should_reply controls only whether to emit a visible reply.`,
614307
615231
  `Memory discipline: use durable associative user memory, relationships, prior actions, and recent context to infer whether this speaker is continuing a bot-related thread. A mention is not required when the semantic target is clearly the bot or an ongoing bot-mediated discussion.`,
@@ -614310,8 +615234,9 @@ ${lines.join("\n")}`);
614310
615234
  forcedLine,
614311
615235
  ``,
614312
615236
  `Tool context: ${toolContext}`,
614313
- `Known self identity signals (context only, not triggers): ${formatTelegramIdentitySignals(botIdentitySignals)}`,
615237
+ selfIdentityContext,
614314
615238
  `Platform notification/direct-address signal (salience evidence only, not a decision): ${addressesBot ? "yes" : "no"}`,
615239
+ `Platform salience signals (context only, not triggers): ${identitySalienceSignals.length ? identitySalienceSignals.join(", ") : "none"}`,
614315
615240
  `Current chat type: ${msg.chatType}`,
614316
615241
  `Current sender: ${telegramSpeakerLabel(msg)} [${telegramActorKindLabel(msg)}]`,
614317
615242
  msg.replyToMessageId ? `Current message replies to message_id ${msg.replyToMessageId}` : "",
@@ -614359,7 +615284,9 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
614359
615284
  shouldReply: false,
614360
615285
  confidence: 0,
614361
615286
  reason: "router inference failed; no model-derived reply decision",
614362
- source: "inference-unavailable"
615287
+ source: "inference-unavailable",
615288
+ silentDisposition: "retained as context without replying",
615289
+ mentalNote: "router failed, so no model-derived attention note was produced"
614363
615290
  };
614364
615291
  this.applyTelegramStimulationDecision(sessionKey, fallback);
614365
615292
  return fallback;
@@ -614490,7 +615417,7 @@ ${list}` : "No shared group target is currently known for this sender. Ask in th
614490
615417
  }
614491
615418
  telegramRunnerStateDir(sessionKey) {
614492
615419
  if (!this.repoRoot) return void 0;
614493
- const safe = createHash23("sha1").update(sessionKey).digest("hex").slice(0, 20);
615420
+ const safe = createHash24("sha1").update(sessionKey).digest("hex").slice(0, 20);
614494
615421
  return join127(this.repoRoot, ".omnius", "telegram-runner-state", safe);
614495
615422
  }
614496
615423
  buildTelegramAdminOverviewContext(currentSessionKey) {
@@ -614709,6 +615636,7 @@ ${TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT}`);
614709
615636
  }
614710
615637
  this.state = {
614711
615638
  active: true,
615639
+ botUserId: typeof me.result?.id === "number" ? me.result.id : void 0,
614712
615640
  botUsername: me.result?.username ?? "unknown",
614713
615641
  botFirstName: typeof me.result?.first_name === "string" ? me.result.first_name : void 0,
614714
615642
  supportsGuestQueries: Boolean(me.result?.supports_guest_queries),
@@ -614958,10 +615886,8 @@ ${TELEGRAM_PUBLIC_ORCHESTRATOR_CONTRACT}`);
614958
615886
  if (startsWithSlash && isAdminAuthSecretCommand && await this.handleAdminAuthCommand({ ...msg, text: normalizedCommandText })) {
614959
615887
  return;
614960
615888
  }
614961
- if (msg.chatType !== "private") {
614962
- this.recordTelegramUserMessage(msg, "ambient");
614963
- this.tuiWrite(() => renderTelegramIngressMessage(msg));
614964
- }
615889
+ this.recordTelegramUserMessage(msg, "ambient");
615890
+ this.tuiWrite(() => renderTelegramIngressMessage(msg));
614965
615891
  if (startsWithSlash && !isAdminAuthSecretCommand && await this.handleAdminAuthCommand({ ...msg, text: normalizedCommandText })) {
614966
615892
  return;
614967
615893
  }
@@ -615083,8 +616009,16 @@ Join: ${newUrl}`);
615083
616009
  if (existing && !existing.aborted) {
615084
616010
  const isGroup = msg.chatType !== "private";
615085
616011
  if (isGroup) {
615086
- this.recordTelegramUserMessage(msg, "ambient");
616012
+ const attentionViewId2 = this.registerTelegramAttentionView(msg, existing.toolContext || toolContext, "active Telegram thread");
615087
616013
  const decision2 = await this.inferTelegramInteractionDecision(msg, existing.toolContext || toolContext);
616014
+ this.writeTelegramAttentionDecision(attentionViewId2, decision2);
616015
+ this.commitTelegramSocialDecision(
616016
+ sessionKey,
616017
+ msg,
616018
+ decision2,
616019
+ this.telegramMessageIdentitySalienceSignals(msg),
616020
+ this.markLatestTelegramDaydreamOpportunitiesConsidered(sessionKey, msg)
616021
+ );
615088
616022
  this.markLastTelegramUserMessageMode(msg, decision2.shouldReply ? "steering" : "ambient");
615089
616023
  this.subAgentViewCallbacks?.onWrite(
615090
616024
  existing.viewId,
@@ -615119,8 +616053,16 @@ Join: ${newUrl}`);
615119
616053
  }
615120
616054
  return;
615121
616055
  }
615122
- this.recordTelegramUserMessage(msg, "ambient");
616056
+ const attentionViewId = this.registerTelegramAttentionView(msg, toolContext);
615123
616057
  const decision = await this.inferTelegramInteractionDecision(msg, toolContext);
616058
+ this.writeTelegramAttentionDecision(attentionViewId, decision);
616059
+ this.commitTelegramSocialDecision(
616060
+ sessionKey,
616061
+ msg,
616062
+ decision,
616063
+ this.telegramMessageIdentitySalienceSignals(msg),
616064
+ this.markLatestTelegramDaydreamOpportunitiesConsidered(sessionKey, msg)
616065
+ );
615124
616066
  this.markLastTelegramUserMessageMode(msg, decision.shouldReply ? decision.route : "ambient");
615125
616067
  this.subAgentViewCallbacks?.onWrite(
615126
616068
  this.viewIdForMessage(msg),
@@ -615502,6 +616444,7 @@ ${TELEGRAM_PUBLIC_MEMORY_SCOPE_CONTRACT}
615502
616444
  ${TELEGRAM_PUBLIC_VISION_STACK_CONTRACT}`;
615503
616445
  const groupHint = isGroup ? `Telegram group: ${msg.chatTitle || "unknown"}. The live router selected this turn as reply-worthy; keep the reply short and relevant. Never output a skip decision, no_reply marker, memory-stage note, or completion status.` : "Telegram private chat.";
615504
616446
  const runtime = buildTelegramRuntimeContext(/* @__PURE__ */ new Date());
616447
+ const selfIdentityContext = this.buildTelegramSelfIdentityContext();
615505
616448
  const messages2 = [
615506
616449
  {
615507
616450
  role: "system",
@@ -615511,6 +616454,8 @@ ${TELEGRAM_PUBLIC_VISION_STACK_CONTRACT}`;
615511
616454
 
615512
616455
  ${runtime}
615513
616456
 
616457
+ ${selfIdentityContext}
616458
+
615514
616459
  ${safety}
615515
616460
 
615516
616461
  ${groupHint}
@@ -615548,12 +616493,17 @@ ${conversationStream}`
615548
616493
  };
615549
616494
  let accumulated = "";
615550
616495
  const streamable = backend;
615551
- if (typeof streamable.chatCompletionStream === "function") {
615552
- for await (const chunk of streamable.chatCompletionStream(request)) {
615553
- if (chunk.type === "content" && !chunk.thinking && chunk.content) {
615554
- accumulated += chunk.content;
615555
- await onToken(accumulated);
616496
+ const stream = typeof streamable.chatCompletionStream === "function" ? streamable.chatCompletionStream(request) : null;
616497
+ if (stream && typeof stream[Symbol.asyncIterator] === "function") {
616498
+ try {
616499
+ for await (const chunk of stream) {
616500
+ if (chunk.type === "content" && !chunk.thinking && chunk.content) {
616501
+ accumulated += chunk.content;
616502
+ await onToken(accumulated);
616503
+ }
615556
616504
  }
616505
+ } catch {
616506
+ accumulated = "";
615557
616507
  }
615558
616508
  }
615559
616509
  if (!accumulated.trim()) {
@@ -615787,10 +616737,13 @@ Respond concisely and safely. Send the actual chat reply, not router/status/comp
615787
616737
  [Media attached — processed content below]
615788
616738
  ${mediaContext}`;
615789
616739
  }
616740
+ const selfIdentityContext = this.buildTelegramSelfIdentityContext();
615790
616741
  const systemCtx = isAdminDM ? `${runtimeContext}
616742
+ ${selfIdentityContext}
615791
616743
  Telegram admin: @${msg.username}
615792
616744
  Telegram profile: ${profile}
615793
616745
  Todo/session id: ${sessionContext.sessionId}` : `${runtimeContext}
616746
+ ${selfIdentityContext}
615794
616747
  Telegram ${isGroup ? "group" : "public"} chat. Respond concisely. Safety filter: ACTIVE.${creativeWorkspace ? `
615795
616748
 
615796
616749
  ${creativeWorkspace}` : ""}`;
@@ -617201,7 +618154,9 @@ Scoped workspace: ${scopedRoot}`,
617201
618154
  }
617202
618155
  const botId = result.result.id;
617203
618156
  this.botUserId = botId;
618157
+ this.state.botUserId = botId;
617204
618158
  if (typeof result.result.username === "string") this.state.botUsername = result.result.username;
618159
+ if (typeof result.result.first_name === "string") this.state.botFirstName = result.result.first_name;
617205
618160
  return botId;
617206
618161
  }
617207
618162
  async getChatMember(chatId, userId) {
@@ -617795,9 +618750,9 @@ ${knownList}` : "Private-user telegram_send_file target must be this DM or a kno
617795
618750
  }
617796
618751
  const target = String(rawTarget).trim();
617797
618752
  if (/^-?\d+$/.test(target)) return { ok: true, chatId: target };
617798
- const cleanUsername = target.replace(/^@/, "");
617799
- if (/^[A-Za-z0-9_]{5,32}$/.test(cleanUsername)) {
617800
- return { ok: true, chatId: `@${cleanUsername}` };
618753
+ const cleanUsername2 = target.replace(/^@/, "");
618754
+ if (/^[A-Za-z0-9_]{5,32}$/.test(cleanUsername2)) {
618755
+ return { ok: true, chatId: `@${cleanUsername2}` };
617801
618756
  }
617802
618757
  return { ok: false, error: "Expected chat_id/user_id as digits, or a valid @username." };
617803
618758
  }
@@ -620342,14 +621297,14 @@ var init_access_policy = __esm({
620342
621297
  });
620343
621298
 
620344
621299
  // packages/cli/src/api/project-preferences.ts
620345
- import { createHash as createHash24 } from "node:crypto";
621300
+ import { createHash as createHash25 } from "node:crypto";
620346
621301
  import { existsSync as existsSync116, mkdirSync as mkdirSync68, readFileSync as readFileSync95, renameSync as renameSync8, writeFileSync as writeFileSync62, unlinkSync as unlinkSync24 } from "node:fs";
620347
621302
  import { homedir as homedir43 } from "node:os";
620348
621303
  import { join as join130, resolve as resolve45 } from "node:path";
620349
621304
  import { randomUUID as randomUUID15 } from "node:crypto";
620350
621305
  function projectKey(root) {
620351
621306
  const canonical = resolve45(root);
620352
- return createHash24("sha256").update(canonical).digest("hex").slice(0, 16);
621307
+ return createHash25("sha256").update(canonical).digest("hex").slice(0, 16);
620353
621308
  }
620354
621309
  function projectDir(root) {
620355
621310
  return join130(PROJECTS_DIR, projectKey(root));
@@ -620441,7 +621396,7 @@ __export(voicechat_exports, {
620441
621396
  VoiceChatSession: () => VoiceChatSession
620442
621397
  });
620443
621398
  import { EventEmitter as EventEmitter12 } from "node:events";
620444
- function clamp019(x) {
621399
+ function clamp0110(x) {
620445
621400
  return x < 0 ? 0 : x > 1 ? 1 : x;
620446
621401
  }
620447
621402
  function alnumRatio(s2) {
@@ -620480,9 +621435,9 @@ function computeSignalFromText(text, confidence2) {
620480
621435
  else score = 0.15;
620481
621436
  score -= repeatingCharPenalty(t2) * 0.4;
620482
621437
  if (typeof confidence2 === "number" && !Number.isNaN(confidence2)) {
620483
- score = 0.7 * score + 0.3 * clamp019(confidence2);
621438
+ score = 0.7 * score + 0.3 * clamp0110(confidence2);
620484
621439
  }
620485
- return clamp019(score);
621440
+ return clamp0110(score);
620486
621441
  }
620487
621442
  function truncateForLog(s2, n2) {
620488
621443
  return s2.length <= n2 ? s2 : s2.slice(0, n2 - 1) + "…";
@@ -620752,7 +621707,7 @@ Rules:
620752
621707
  }, MAX_SEGMENT_MS);
620753
621708
  }
620754
621709
  this.captureBuffer = text;
620755
- this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp019(snr) : computeSignalFromText(text, confidence2);
621710
+ this.lastSignalScore = typeof snr === "number" && !Number.isNaN(snr) ? clamp0110(snr) : computeSignalFromText(text, confidence2);
620756
621711
  this.emit("snr", { score: this.lastSignalScore });
620757
621712
  this.onPartialTranscript(text);
620758
621713
  if (this.silenceTimer) clearTimeout(this.silenceTimer);
@@ -621527,7 +622482,7 @@ var init_disk_task_output = __esm({
621527
622482
  });
621528
622483
 
621529
622484
  // packages/cli/src/api/http.ts
621530
- import { createHash as createHash25 } from "node:crypto";
622485
+ import { createHash as createHash26 } from "node:crypto";
621531
622486
  function problemDetails(opts) {
621532
622487
  const p2 = {
621533
622488
  type: opts.type ?? "about:blank",
@@ -621590,7 +622545,7 @@ function paginated(items, page2, total) {
621590
622545
  }
621591
622546
  function computeEtag(payload) {
621592
622547
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
621593
- const hash = createHash25("sha1").update(json).digest("hex").slice(0, 16);
622548
+ const hash = createHash26("sha1").update(json).digest("hex").slice(0, 16);
621594
622549
  return `W/"${hash}"`;
621595
622550
  }
621596
622551
  function checkNotModified(req2, res, etag) {
@@ -635861,7 +636816,7 @@ import { homedir as homedir50 } from "node:os";
635861
636816
  import { spawn as spawn30, execSync as execSync57 } from "node:child_process";
635862
636817
  import { mkdirSync as mkdirSync76, writeFileSync as writeFileSync68, readFileSync as readFileSync103, readdirSync as readdirSync45, existsSync as existsSync127, watch as fsWatch3, renameSync as renameSync9, unlinkSync as unlinkSync26 } from "node:fs";
635863
636818
  import { randomBytes as randomBytes25, randomUUID as randomUUID16 } from "node:crypto";
635864
- import { createHash as createHash27 } from "node:crypto";
636819
+ import { createHash as createHash28 } from "node:crypto";
635865
636820
  function memoryDbPaths3(baseDir = process.cwd()) {
635866
636821
  const dir = join141(baseDir, ".omnius");
635867
636822
  return {
@@ -641741,7 +642696,7 @@ function listScheduledTasks() {
641741
642696
  const schedule = String(t2?.schedule || t2?.cron || t2?.when || "");
641742
642697
  const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
641743
642698
  const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
641744
- const fallbackId = createHash27("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
642699
+ const fallbackId = createHash28("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
641745
642700
  const uid = realId || fallbackId;
641746
642701
  const key = `${uid}`;
641747
642702
  if (seen.has(key)) return;
@@ -641858,8 +642813,8 @@ function deleteScheduledById(id) {
641858
642813
  if (id) candidates.push(id);
641859
642814
  if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id)) candidates.push(entry.id);
641860
642815
  try {
641861
- const { createHash: createHash28 } = require4("node:crypto");
641862
- const fallback = createHash28("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
642816
+ const { createHash: createHash29 } = require4("node:crypto");
642817
+ const fallback = createHash29("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
641863
642818
  if (!candidates.includes(fallback)) candidates.push(fallback);
641864
642819
  } catch {
641865
642820
  }
@@ -651775,13 +652730,13 @@ NEW TASK: ${fullInput}`;
651775
652730
  writeContent(() => renderError(errMsg));
651776
652731
  if (failureStore) {
651777
652732
  try {
651778
- const { createHash: createHash28 } = await import("node:crypto");
652733
+ const { createHash: createHash29 } = await import("node:crypto");
651779
652734
  failureStore.insert({
651780
652735
  taskId: "",
651781
652736
  sessionId: `${Date.now()}`,
651782
652737
  repoRoot,
651783
652738
  failureType: "runtime-error",
651784
- fingerprint: createHash28("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
652739
+ fingerprint: createHash29("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
651785
652740
  filePath: null,
651786
652741
  errorMessage: errMsg.slice(0, 500),
651787
652742
  context: null,