@inline-openclaw/inline 0.0.29 → 0.0.31

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
@@ -5560,6 +5560,13 @@ var import_runtime = __toESM(require_commonjs(), 1);
5560
5560
  var import_runtime2 = __toESM(require_commonjs(), 1);
5561
5561
  var import_runtime3 = __toESM(require_commonjs(), 1);
5562
5562
  var import_runtime4 = __toESM(require_commonjs(), 1);
5563
+ var ConnectionError_Reason;
5564
+ (function(ConnectionError_Reason2) {
5565
+ ConnectionError_Reason2[ConnectionError_Reason2["REASON_UNSPECIFIED"] = 0] = "REASON_UNSPECIFIED";
5566
+ ConnectionError_Reason2[ConnectionError_Reason2["UNAUTHORIZED"] = 1] = "UNAUTHORIZED";
5567
+ ConnectionError_Reason2[ConnectionError_Reason2["INVALID_AUTH"] = 2] = "INVALID_AUTH";
5568
+ ConnectionError_Reason2[ConnectionError_Reason2["SESSION_REVOKED"] = 3] = "SESSION_REVOKED";
5569
+ })(ConnectionError_Reason || (ConnectionError_Reason = {}));
5563
5570
  var MessageEntity_Type;
5564
5571
  (function(MessageEntity_Type2) {
5565
5572
  MessageEntity_Type2[MessageEntity_Type2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
@@ -5719,6 +5726,7 @@ var Method;
5719
5726
  Method2[Method2["RESERVE_CHAT_IDS"] = 47] = "RESERVE_CHAT_IDS";
5720
5727
  Method2[Method2["INVOKE_MESSAGE_ACTION"] = 48] = "INVOKE_MESSAGE_ACTION";
5721
5728
  Method2[Method2["ANSWER_MESSAGE_ACTION"] = 49] = "ANSWER_MESSAGE_ACTION";
5729
+ Method2[Method2["REVOKE_SESSION"] = 50] = "REVOKE_SESSION";
5722
5730
  })(Method || (Method = {}));
5723
5731
  var PushNotificationProvider;
5724
5732
  (function(PushNotificationProvider2) {
@@ -6161,18 +6169,39 @@ var ConnectionOpen = new ConnectionOpen$Type;
6161
6169
 
6162
6170
  class ConnectionError$Type extends import_runtime4.MessageType {
6163
6171
  constructor() {
6164
- super("ConnectionError", []);
6172
+ super("ConnectionError", [
6173
+ { no: 1, name: "reason", kind: "enum", T: () => ["ConnectionError.Reason", ConnectionError_Reason] }
6174
+ ]);
6165
6175
  }
6166
6176
  create(value) {
6167
6177
  const message = globalThis.Object.create(this.messagePrototype);
6178
+ message.reason = 0;
6168
6179
  if (value !== undefined)
6169
6180
  import_runtime3.reflectionMergePartial(this, message, value);
6170
6181
  return message;
6171
6182
  }
6172
6183
  internalBinaryRead(reader, length, options, target) {
6173
- return target ?? this.create();
6184
+ let message = target ?? this.create(), end = reader.pos + length;
6185
+ while (reader.pos < end) {
6186
+ let [fieldNo, wireType] = reader.tag();
6187
+ switch (fieldNo) {
6188
+ case 1:
6189
+ message.reason = reader.int32();
6190
+ break;
6191
+ default:
6192
+ let u = options.readUnknownField;
6193
+ if (u === "throw")
6194
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
6195
+ let d = reader.skip(wireType);
6196
+ if (u !== false)
6197
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
6198
+ }
6199
+ }
6200
+ return message;
6174
6201
  }
6175
6202
  internalBinaryWrite(message, writer, options) {
6203
+ if (message.reason !== 0)
6204
+ writer.tag(1, import_runtime.WireType.Varint).int32(message.reason);
6176
6205
  let u = options.writeUnknownFields;
6177
6206
  if (u !== false)
6178
6207
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
@@ -9370,7 +9399,8 @@ class RpcCall$Type extends import_runtime4.MessageType {
9370
9399
  { no: 47, name: "showChatInSidebar", kind: "message", oneof: "input", T: () => ShowChatInSidebarInput },
9371
9400
  { no: 48, name: "reserveChatIds", kind: "message", oneof: "input", T: () => ReserveChatIdsInput },
9372
9401
  { no: 49, name: "invokeMessageAction", kind: "message", oneof: "input", T: () => InvokeMessageActionInput },
9373
- { no: 50, name: "answerMessageAction", kind: "message", oneof: "input", T: () => AnswerMessageActionInput }
9402
+ { no: 50, name: "answerMessageAction", kind: "message", oneof: "input", T: () => AnswerMessageActionInput },
9403
+ { no: 51, name: "revokeSession", kind: "message", oneof: "input", T: () => RevokeSessionInput }
9374
9404
  ]);
9375
9405
  }
9376
9406
  create(value) {
@@ -9683,6 +9713,12 @@ class RpcCall$Type extends import_runtime4.MessageType {
9683
9713
  answerMessageAction: AnswerMessageActionInput.internalBinaryRead(reader, reader.uint32(), options, message.input.answerMessageAction)
9684
9714
  };
9685
9715
  break;
9716
+ case 51:
9717
+ message.input = {
9718
+ oneofKind: "revokeSession",
9719
+ revokeSession: RevokeSessionInput.internalBinaryRead(reader, reader.uint32(), options, message.input.revokeSession)
9720
+ };
9721
+ break;
9686
9722
  default:
9687
9723
  let u = options.readUnknownField;
9688
9724
  if (u === "throw")
@@ -9795,6 +9831,8 @@ class RpcCall$Type extends import_runtime4.MessageType {
9795
9831
  InvokeMessageActionInput.internalBinaryWrite(message.input.invokeMessageAction, writer.tag(49, import_runtime.WireType.LengthDelimited).fork(), options).join();
9796
9832
  if (message.input.oneofKind === "answerMessageAction")
9797
9833
  AnswerMessageActionInput.internalBinaryWrite(message.input.answerMessageAction, writer.tag(50, import_runtime.WireType.LengthDelimited).fork(), options).join();
9834
+ if (message.input.oneofKind === "revokeSession")
9835
+ RevokeSessionInput.internalBinaryWrite(message.input.revokeSession, writer.tag(51, import_runtime.WireType.LengthDelimited).fork(), options).join();
9798
9836
  let u = options.writeUnknownFields;
9799
9837
  if (u !== false)
9800
9838
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
@@ -9855,7 +9893,8 @@ class RpcResult$Type extends import_runtime4.MessageType {
9855
9893
  { no: 47, name: "showChatInSidebar", kind: "message", oneof: "result", T: () => ShowChatInSidebarResult },
9856
9894
  { no: 48, name: "reserveChatIds", kind: "message", oneof: "result", T: () => ReserveChatIdsResult },
9857
9895
  { no: 49, name: "invokeMessageAction", kind: "message", oneof: "result", T: () => InvokeMessageActionResult },
9858
- { no: 50, name: "answerMessageAction", kind: "message", oneof: "result", T: () => AnswerMessageActionResult }
9896
+ { no: 50, name: "answerMessageAction", kind: "message", oneof: "result", T: () => AnswerMessageActionResult },
9897
+ { no: 51, name: "revokeSession", kind: "message", oneof: "result", T: () => RevokeSessionResult }
9859
9898
  ]);
9860
9899
  }
9861
9900
  create(value) {
@@ -10168,6 +10207,12 @@ class RpcResult$Type extends import_runtime4.MessageType {
10168
10207
  answerMessageAction: AnswerMessageActionResult.internalBinaryRead(reader, reader.uint32(), options, message.result.answerMessageAction)
10169
10208
  };
10170
10209
  break;
10210
+ case 51:
10211
+ message.result = {
10212
+ oneofKind: "revokeSession",
10213
+ revokeSession: RevokeSessionResult.internalBinaryRead(reader, reader.uint32(), options, message.result.revokeSession)
10214
+ };
10215
+ break;
10171
10216
  default:
10172
10217
  let u = options.readUnknownField;
10173
10218
  if (u === "throw")
@@ -10280,6 +10325,8 @@ class RpcResult$Type extends import_runtime4.MessageType {
10280
10325
  InvokeMessageActionResult.internalBinaryWrite(message.result.invokeMessageAction, writer.tag(49, import_runtime.WireType.LengthDelimited).fork(), options).join();
10281
10326
  if (message.result.oneofKind === "answerMessageAction")
10282
10327
  AnswerMessageActionResult.internalBinaryWrite(message.result.answerMessageAction, writer.tag(50, import_runtime.WireType.LengthDelimited).fork(), options).join();
10328
+ if (message.result.oneofKind === "revokeSession")
10329
+ RevokeSessionResult.internalBinaryWrite(message.result.revokeSession, writer.tag(51, import_runtime.WireType.LengthDelimited).fork(), options).join();
10283
10330
  let u = options.writeUnknownFields;
10284
10331
  if (u !== false)
10285
10332
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
@@ -11417,18 +11464,15 @@ class ListBotsResult$Type extends import_runtime4.MessageType {
11417
11464
  }
11418
11465
  var ListBotsResult = new ListBotsResult$Type;
11419
11466
 
11420
- class BotCommand$Type extends import_runtime4.MessageType {
11467
+ class RevokeSessionInput$Type extends import_runtime4.MessageType {
11421
11468
  constructor() {
11422
- super("BotCommand", [
11423
- { no: 1, name: "command", kind: "scalar", T: 9 },
11424
- { no: 2, name: "description", kind: "scalar", T: 9 },
11425
- { no: 3, name: "sort_order", kind: "scalar", opt: true, T: 5 }
11469
+ super("RevokeSessionInput", [
11470
+ { no: 1, name: "session_id", kind: "scalar", T: 3, L: 0 }
11426
11471
  ]);
11427
11472
  }
11428
11473
  create(value) {
11429
11474
  const message = globalThis.Object.create(this.messagePrototype);
11430
- message.command = "";
11431
- message.description = "";
11475
+ message.sessionId = 0n;
11432
11476
  if (value !== undefined)
11433
11477
  import_runtime3.reflectionMergePartial(this, message, value);
11434
11478
  return message;
@@ -11439,13 +11483,7 @@ class BotCommand$Type extends import_runtime4.MessageType {
11439
11483
  let [fieldNo, wireType] = reader.tag();
11440
11484
  switch (fieldNo) {
11441
11485
  case 1:
11442
- message.command = reader.string();
11443
- break;
11444
- case 2:
11445
- message.description = reader.string();
11446
- break;
11447
- case 3:
11448
- message.sortOrder = reader.int32();
11486
+ message.sessionId = reader.int64().toBigInt();
11449
11487
  break;
11450
11488
  default:
11451
11489
  let u = options.readUnknownField;
@@ -11459,30 +11497,27 @@ class BotCommand$Type extends import_runtime4.MessageType {
11459
11497
  return message;
11460
11498
  }
11461
11499
  internalBinaryWrite(message, writer, options) {
11462
- if (message.command !== "")
11463
- writer.tag(1, import_runtime.WireType.LengthDelimited).string(message.command);
11464
- if (message.description !== "")
11465
- writer.tag(2, import_runtime.WireType.LengthDelimited).string(message.description);
11466
- if (message.sortOrder !== undefined)
11467
- writer.tag(3, import_runtime.WireType.Varint).int32(message.sortOrder);
11500
+ if (message.sessionId !== 0n)
11501
+ writer.tag(1, import_runtime.WireType.Varint).int64(message.sessionId);
11468
11502
  let u = options.writeUnknownFields;
11469
11503
  if (u !== false)
11470
11504
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11471
11505
  return writer;
11472
11506
  }
11473
11507
  }
11474
- var BotCommand = new BotCommand$Type;
11508
+ var RevokeSessionInput = new RevokeSessionInput$Type;
11475
11509
 
11476
- class PeerBotCommands$Type extends import_runtime4.MessageType {
11510
+ class RevokeSessionResult$Type extends import_runtime4.MessageType {
11477
11511
  constructor() {
11478
- super("PeerBotCommands", [
11479
- { no: 1, name: "bot", kind: "message", T: () => User },
11480
- { no: 2, name: "commands", kind: "message", repeat: 1, T: () => BotCommand }
11512
+ super("RevokeSessionResult", [
11513
+ { no: 1, name: "revoked", kind: "scalar", T: 8 },
11514
+ { no: 2, name: "already_revoked", kind: "scalar", T: 8 }
11481
11515
  ]);
11482
11516
  }
11483
11517
  create(value) {
11484
11518
  const message = globalThis.Object.create(this.messagePrototype);
11485
- message.commands = [];
11519
+ message.revoked = false;
11520
+ message.alreadyRevoked = false;
11486
11521
  if (value !== undefined)
11487
11522
  import_runtime3.reflectionMergePartial(this, message, value);
11488
11523
  return message;
@@ -11493,10 +11528,10 @@ class PeerBotCommands$Type extends import_runtime4.MessageType {
11493
11528
  let [fieldNo, wireType] = reader.tag();
11494
11529
  switch (fieldNo) {
11495
11530
  case 1:
11496
- message.bot = User.internalBinaryRead(reader, reader.uint32(), options, message.bot);
11531
+ message.revoked = reader.bool();
11497
11532
  break;
11498
11533
  case 2:
11499
- message.commands.push(BotCommand.internalBinaryRead(reader, reader.uint32(), options));
11534
+ message.alreadyRevoked = reader.bool();
11500
11535
  break;
11501
11536
  default:
11502
11537
  let u = options.readUnknownField;
@@ -11510,27 +11545,30 @@ class PeerBotCommands$Type extends import_runtime4.MessageType {
11510
11545
  return message;
11511
11546
  }
11512
11547
  internalBinaryWrite(message, writer, options) {
11513
- if (message.bot)
11514
- User.internalBinaryWrite(message.bot, writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11515
- for (let i = 0;i < message.commands.length; i++)
11516
- BotCommand.internalBinaryWrite(message.commands[i], writer.tag(2, import_runtime.WireType.LengthDelimited).fork(), options).join();
11548
+ if (message.revoked !== false)
11549
+ writer.tag(1, import_runtime.WireType.Varint).bool(message.revoked);
11550
+ if (message.alreadyRevoked !== false)
11551
+ writer.tag(2, import_runtime.WireType.Varint).bool(message.alreadyRevoked);
11517
11552
  let u = options.writeUnknownFields;
11518
11553
  if (u !== false)
11519
11554
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11520
11555
  return writer;
11521
11556
  }
11522
11557
  }
11523
- var PeerBotCommands = new PeerBotCommands$Type;
11558
+ var RevokeSessionResult = new RevokeSessionResult$Type;
11524
11559
 
11525
- class GetBotCommandsInput$Type extends import_runtime4.MessageType {
11560
+ class BotCommand$Type extends import_runtime4.MessageType {
11526
11561
  constructor() {
11527
- super("GetBotCommandsInput", [
11528
- { no: 1, name: "bot_user_id", kind: "scalar", T: 3, L: 0 }
11562
+ super("BotCommand", [
11563
+ { no: 1, name: "command", kind: "scalar", T: 9 },
11564
+ { no: 2, name: "description", kind: "scalar", T: 9 },
11565
+ { no: 3, name: "sort_order", kind: "scalar", opt: true, T: 5 }
11529
11566
  ]);
11530
11567
  }
11531
11568
  create(value) {
11532
11569
  const message = globalThis.Object.create(this.messagePrototype);
11533
- message.botUserId = 0n;
11570
+ message.command = "";
11571
+ message.description = "";
11534
11572
  if (value !== undefined)
11535
11573
  import_runtime3.reflectionMergePartial(this, message, value);
11536
11574
  return message;
@@ -11541,50 +11579,13 @@ class GetBotCommandsInput$Type extends import_runtime4.MessageType {
11541
11579
  let [fieldNo, wireType] = reader.tag();
11542
11580
  switch (fieldNo) {
11543
11581
  case 1:
11544
- message.botUserId = reader.int64().toBigInt();
11582
+ message.command = reader.string();
11545
11583
  break;
11546
- default:
11547
- let u = options.readUnknownField;
11548
- if (u === "throw")
11549
- throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11550
- let d = reader.skip(wireType);
11551
- if (u !== false)
11552
- (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11553
- }
11554
- }
11555
- return message;
11556
- }
11557
- internalBinaryWrite(message, writer, options) {
11558
- if (message.botUserId !== 0n)
11559
- writer.tag(1, import_runtime.WireType.Varint).int64(message.botUserId);
11560
- let u = options.writeUnknownFields;
11561
- if (u !== false)
11562
- (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11563
- return writer;
11564
- }
11565
- }
11566
- var GetBotCommandsInput = new GetBotCommandsInput$Type;
11567
-
11568
- class GetBotCommandsResult$Type extends import_runtime4.MessageType {
11569
- constructor() {
11570
- super("GetBotCommandsResult", [
11571
- { no: 1, name: "commands", kind: "message", repeat: 1, T: () => BotCommand }
11572
- ]);
11573
- }
11574
- create(value) {
11575
- const message = globalThis.Object.create(this.messagePrototype);
11576
- message.commands = [];
11577
- if (value !== undefined)
11578
- import_runtime3.reflectionMergePartial(this, message, value);
11579
- return message;
11580
- }
11581
- internalBinaryRead(reader, length, options, target) {
11582
- let message = target ?? this.create(), end = reader.pos + length;
11583
- while (reader.pos < end) {
11584
- let [fieldNo, wireType] = reader.tag();
11585
- switch (fieldNo) {
11586
- case 1:
11587
- message.commands.push(BotCommand.internalBinaryRead(reader, reader.uint32(), options));
11584
+ case 2:
11585
+ message.description = reader.string();
11586
+ break;
11587
+ case 3:
11588
+ message.sortOrder = reader.int32();
11588
11589
  break;
11589
11590
  default:
11590
11591
  let u = options.readUnknownField;
@@ -11598,26 +11599,29 @@ class GetBotCommandsResult$Type extends import_runtime4.MessageType {
11598
11599
  return message;
11599
11600
  }
11600
11601
  internalBinaryWrite(message, writer, options) {
11601
- for (let i = 0;i < message.commands.length; i++)
11602
- BotCommand.internalBinaryWrite(message.commands[i], writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11602
+ if (message.command !== "")
11603
+ writer.tag(1, import_runtime.WireType.LengthDelimited).string(message.command);
11604
+ if (message.description !== "")
11605
+ writer.tag(2, import_runtime.WireType.LengthDelimited).string(message.description);
11606
+ if (message.sortOrder !== undefined)
11607
+ writer.tag(3, import_runtime.WireType.Varint).int32(message.sortOrder);
11603
11608
  let u = options.writeUnknownFields;
11604
11609
  if (u !== false)
11605
11610
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11606
11611
  return writer;
11607
11612
  }
11608
11613
  }
11609
- var GetBotCommandsResult = new GetBotCommandsResult$Type;
11614
+ var BotCommand = new BotCommand$Type;
11610
11615
 
11611
- class SetBotCommandsInput$Type extends import_runtime4.MessageType {
11616
+ class PeerBotCommands$Type extends import_runtime4.MessageType {
11612
11617
  constructor() {
11613
- super("SetBotCommandsInput", [
11614
- { no: 1, name: "bot_user_id", kind: "scalar", T: 3, L: 0 },
11618
+ super("PeerBotCommands", [
11619
+ { no: 1, name: "bot", kind: "message", T: () => User },
11615
11620
  { no: 2, name: "commands", kind: "message", repeat: 1, T: () => BotCommand }
11616
11621
  ]);
11617
11622
  }
11618
11623
  create(value) {
11619
11624
  const message = globalThis.Object.create(this.messagePrototype);
11620
- message.botUserId = 0n;
11621
11625
  message.commands = [];
11622
11626
  if (value !== undefined)
11623
11627
  import_runtime3.reflectionMergePartial(this, message, value);
@@ -11629,7 +11633,7 @@ class SetBotCommandsInput$Type extends import_runtime4.MessageType {
11629
11633
  let [fieldNo, wireType] = reader.tag();
11630
11634
  switch (fieldNo) {
11631
11635
  case 1:
11632
- message.botUserId = reader.int64().toBigInt();
11636
+ message.bot = User.internalBinaryRead(reader, reader.uint32(), options, message.bot);
11633
11637
  break;
11634
11638
  case 2:
11635
11639
  message.commands.push(BotCommand.internalBinaryRead(reader, reader.uint32(), options));
@@ -11646,8 +11650,8 @@ class SetBotCommandsInput$Type extends import_runtime4.MessageType {
11646
11650
  return message;
11647
11651
  }
11648
11652
  internalBinaryWrite(message, writer, options) {
11649
- if (message.botUserId !== 0n)
11650
- writer.tag(1, import_runtime.WireType.Varint).int64(message.botUserId);
11653
+ if (message.bot)
11654
+ User.internalBinaryWrite(message.bot, writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11651
11655
  for (let i = 0;i < message.commands.length; i++)
11652
11656
  BotCommand.internalBinaryWrite(message.commands[i], writer.tag(2, import_runtime.WireType.LengthDelimited).fork(), options).join();
11653
11657
  let u = options.writeUnknownFields;
@@ -11656,139 +11660,275 @@ class SetBotCommandsInput$Type extends import_runtime4.MessageType {
11656
11660
  return writer;
11657
11661
  }
11658
11662
  }
11659
- var SetBotCommandsInput = new SetBotCommandsInput$Type;
11660
-
11661
- class SetBotCommandsResult$Type extends import_runtime4.MessageType {
11662
- constructor() {
11663
- super("SetBotCommandsResult", [
11664
- { no: 1, name: "commands", kind: "message", repeat: 1, T: () => BotCommand }
11665
- ]);
11666
- }
11667
- create(value) {
11668
- const message = globalThis.Object.create(this.messagePrototype);
11669
- message.commands = [];
11670
- if (value !== undefined)
11671
- import_runtime3.reflectionMergePartial(this, message, value);
11672
- return message;
11673
- }
11674
- internalBinaryRead(reader, length, options, target) {
11675
- let message = target ?? this.create(), end = reader.pos + length;
11676
- while (reader.pos < end) {
11677
- let [fieldNo, wireType] = reader.tag();
11678
- switch (fieldNo) {
11679
- case 1:
11680
- message.commands.push(BotCommand.internalBinaryRead(reader, reader.uint32(), options));
11681
- break;
11682
- default:
11683
- let u = options.readUnknownField;
11684
- if (u === "throw")
11685
- throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11686
- let d = reader.skip(wireType);
11687
- if (u !== false)
11688
- (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11689
- }
11690
- }
11691
- return message;
11692
- }
11693
- internalBinaryWrite(message, writer, options) {
11694
- for (let i = 0;i < message.commands.length; i++)
11695
- BotCommand.internalBinaryWrite(message.commands[i], writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11696
- let u = options.writeUnknownFields;
11697
- if (u !== false)
11698
- (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11699
- return writer;
11700
- }
11701
- }
11702
- var SetBotCommandsResult = new SetBotCommandsResult$Type;
11703
-
11704
- class GetPeerBotCommandsInput$Type extends import_runtime4.MessageType {
11705
- constructor() {
11706
- super("GetPeerBotCommandsInput", [
11707
- { no: 1, name: "peer_id", kind: "message", T: () => InputPeer }
11708
- ]);
11709
- }
11710
- create(value) {
11711
- const message = globalThis.Object.create(this.messagePrototype);
11712
- if (value !== undefined)
11713
- import_runtime3.reflectionMergePartial(this, message, value);
11714
- return message;
11715
- }
11716
- internalBinaryRead(reader, length, options, target) {
11717
- let message = target ?? this.create(), end = reader.pos + length;
11718
- while (reader.pos < end) {
11719
- let [fieldNo, wireType] = reader.tag();
11720
- switch (fieldNo) {
11721
- case 1:
11722
- message.peerId = InputPeer.internalBinaryRead(reader, reader.uint32(), options, message.peerId);
11723
- break;
11724
- default:
11725
- let u = options.readUnknownField;
11726
- if (u === "throw")
11727
- throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11728
- let d = reader.skip(wireType);
11729
- if (u !== false)
11730
- (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11731
- }
11732
- }
11733
- return message;
11734
- }
11735
- internalBinaryWrite(message, writer, options) {
11736
- if (message.peerId)
11737
- InputPeer.internalBinaryWrite(message.peerId, writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11738
- let u = options.writeUnknownFields;
11739
- if (u !== false)
11740
- (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11741
- return writer;
11742
- }
11743
- }
11744
- var GetPeerBotCommandsInput = new GetPeerBotCommandsInput$Type;
11745
-
11746
- class GetPeerBotCommandsResult$Type extends import_runtime4.MessageType {
11747
- constructor() {
11748
- super("GetPeerBotCommandsResult", [
11749
- { no: 1, name: "bots", kind: "message", repeat: 1, T: () => PeerBotCommands }
11750
- ]);
11751
- }
11752
- create(value) {
11753
- const message = globalThis.Object.create(this.messagePrototype);
11754
- message.bots = [];
11755
- if (value !== undefined)
11756
- import_runtime3.reflectionMergePartial(this, message, value);
11757
- return message;
11758
- }
11759
- internalBinaryRead(reader, length, options, target) {
11760
- let message = target ?? this.create(), end = reader.pos + length;
11761
- while (reader.pos < end) {
11762
- let [fieldNo, wireType] = reader.tag();
11763
- switch (fieldNo) {
11764
- case 1:
11765
- message.bots.push(PeerBotCommands.internalBinaryRead(reader, reader.uint32(), options));
11766
- break;
11767
- default:
11768
- let u = options.readUnknownField;
11769
- if (u === "throw")
11770
- throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11771
- let d = reader.skip(wireType);
11772
- if (u !== false)
11773
- (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11774
- }
11775
- }
11776
- return message;
11777
- }
11778
- internalBinaryWrite(message, writer, options) {
11779
- for (let i = 0;i < message.bots.length; i++)
11780
- PeerBotCommands.internalBinaryWrite(message.bots[i], writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11781
- let u = options.writeUnknownFields;
11782
- if (u !== false)
11783
- (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11784
- return writer;
11785
- }
11786
- }
11787
- var GetPeerBotCommandsResult = new GetPeerBotCommandsResult$Type;
11663
+ var PeerBotCommands = new PeerBotCommands$Type;
11788
11664
 
11789
- class RevealBotTokenInput$Type extends import_runtime4.MessageType {
11665
+ class GetBotCommandsInput$Type extends import_runtime4.MessageType {
11790
11666
  constructor() {
11791
- super("RevealBotTokenInput", [
11667
+ super("GetBotCommandsInput", [
11668
+ { no: 1, name: "bot_user_id", kind: "scalar", T: 3, L: 0 }
11669
+ ]);
11670
+ }
11671
+ create(value) {
11672
+ const message = globalThis.Object.create(this.messagePrototype);
11673
+ message.botUserId = 0n;
11674
+ if (value !== undefined)
11675
+ import_runtime3.reflectionMergePartial(this, message, value);
11676
+ return message;
11677
+ }
11678
+ internalBinaryRead(reader, length, options, target) {
11679
+ let message = target ?? this.create(), end = reader.pos + length;
11680
+ while (reader.pos < end) {
11681
+ let [fieldNo, wireType] = reader.tag();
11682
+ switch (fieldNo) {
11683
+ case 1:
11684
+ message.botUserId = reader.int64().toBigInt();
11685
+ break;
11686
+ default:
11687
+ let u = options.readUnknownField;
11688
+ if (u === "throw")
11689
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11690
+ let d = reader.skip(wireType);
11691
+ if (u !== false)
11692
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11693
+ }
11694
+ }
11695
+ return message;
11696
+ }
11697
+ internalBinaryWrite(message, writer, options) {
11698
+ if (message.botUserId !== 0n)
11699
+ writer.tag(1, import_runtime.WireType.Varint).int64(message.botUserId);
11700
+ let u = options.writeUnknownFields;
11701
+ if (u !== false)
11702
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11703
+ return writer;
11704
+ }
11705
+ }
11706
+ var GetBotCommandsInput = new GetBotCommandsInput$Type;
11707
+
11708
+ class GetBotCommandsResult$Type extends import_runtime4.MessageType {
11709
+ constructor() {
11710
+ super("GetBotCommandsResult", [
11711
+ { no: 1, name: "commands", kind: "message", repeat: 1, T: () => BotCommand }
11712
+ ]);
11713
+ }
11714
+ create(value) {
11715
+ const message = globalThis.Object.create(this.messagePrototype);
11716
+ message.commands = [];
11717
+ if (value !== undefined)
11718
+ import_runtime3.reflectionMergePartial(this, message, value);
11719
+ return message;
11720
+ }
11721
+ internalBinaryRead(reader, length, options, target) {
11722
+ let message = target ?? this.create(), end = reader.pos + length;
11723
+ while (reader.pos < end) {
11724
+ let [fieldNo, wireType] = reader.tag();
11725
+ switch (fieldNo) {
11726
+ case 1:
11727
+ message.commands.push(BotCommand.internalBinaryRead(reader, reader.uint32(), options));
11728
+ break;
11729
+ default:
11730
+ let u = options.readUnknownField;
11731
+ if (u === "throw")
11732
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11733
+ let d = reader.skip(wireType);
11734
+ if (u !== false)
11735
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11736
+ }
11737
+ }
11738
+ return message;
11739
+ }
11740
+ internalBinaryWrite(message, writer, options) {
11741
+ for (let i = 0;i < message.commands.length; i++)
11742
+ BotCommand.internalBinaryWrite(message.commands[i], writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11743
+ let u = options.writeUnknownFields;
11744
+ if (u !== false)
11745
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11746
+ return writer;
11747
+ }
11748
+ }
11749
+ var GetBotCommandsResult = new GetBotCommandsResult$Type;
11750
+
11751
+ class SetBotCommandsInput$Type extends import_runtime4.MessageType {
11752
+ constructor() {
11753
+ super("SetBotCommandsInput", [
11754
+ { no: 1, name: "bot_user_id", kind: "scalar", T: 3, L: 0 },
11755
+ { no: 2, name: "commands", kind: "message", repeat: 1, T: () => BotCommand }
11756
+ ]);
11757
+ }
11758
+ create(value) {
11759
+ const message = globalThis.Object.create(this.messagePrototype);
11760
+ message.botUserId = 0n;
11761
+ message.commands = [];
11762
+ if (value !== undefined)
11763
+ import_runtime3.reflectionMergePartial(this, message, value);
11764
+ return message;
11765
+ }
11766
+ internalBinaryRead(reader, length, options, target) {
11767
+ let message = target ?? this.create(), end = reader.pos + length;
11768
+ while (reader.pos < end) {
11769
+ let [fieldNo, wireType] = reader.tag();
11770
+ switch (fieldNo) {
11771
+ case 1:
11772
+ message.botUserId = reader.int64().toBigInt();
11773
+ break;
11774
+ case 2:
11775
+ message.commands.push(BotCommand.internalBinaryRead(reader, reader.uint32(), options));
11776
+ break;
11777
+ default:
11778
+ let u = options.readUnknownField;
11779
+ if (u === "throw")
11780
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11781
+ let d = reader.skip(wireType);
11782
+ if (u !== false)
11783
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11784
+ }
11785
+ }
11786
+ return message;
11787
+ }
11788
+ internalBinaryWrite(message, writer, options) {
11789
+ if (message.botUserId !== 0n)
11790
+ writer.tag(1, import_runtime.WireType.Varint).int64(message.botUserId);
11791
+ for (let i = 0;i < message.commands.length; i++)
11792
+ BotCommand.internalBinaryWrite(message.commands[i], writer.tag(2, import_runtime.WireType.LengthDelimited).fork(), options).join();
11793
+ let u = options.writeUnknownFields;
11794
+ if (u !== false)
11795
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11796
+ return writer;
11797
+ }
11798
+ }
11799
+ var SetBotCommandsInput = new SetBotCommandsInput$Type;
11800
+
11801
+ class SetBotCommandsResult$Type extends import_runtime4.MessageType {
11802
+ constructor() {
11803
+ super("SetBotCommandsResult", [
11804
+ { no: 1, name: "commands", kind: "message", repeat: 1, T: () => BotCommand }
11805
+ ]);
11806
+ }
11807
+ create(value) {
11808
+ const message = globalThis.Object.create(this.messagePrototype);
11809
+ message.commands = [];
11810
+ if (value !== undefined)
11811
+ import_runtime3.reflectionMergePartial(this, message, value);
11812
+ return message;
11813
+ }
11814
+ internalBinaryRead(reader, length, options, target) {
11815
+ let message = target ?? this.create(), end = reader.pos + length;
11816
+ while (reader.pos < end) {
11817
+ let [fieldNo, wireType] = reader.tag();
11818
+ switch (fieldNo) {
11819
+ case 1:
11820
+ message.commands.push(BotCommand.internalBinaryRead(reader, reader.uint32(), options));
11821
+ break;
11822
+ default:
11823
+ let u = options.readUnknownField;
11824
+ if (u === "throw")
11825
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11826
+ let d = reader.skip(wireType);
11827
+ if (u !== false)
11828
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11829
+ }
11830
+ }
11831
+ return message;
11832
+ }
11833
+ internalBinaryWrite(message, writer, options) {
11834
+ for (let i = 0;i < message.commands.length; i++)
11835
+ BotCommand.internalBinaryWrite(message.commands[i], writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11836
+ let u = options.writeUnknownFields;
11837
+ if (u !== false)
11838
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11839
+ return writer;
11840
+ }
11841
+ }
11842
+ var SetBotCommandsResult = new SetBotCommandsResult$Type;
11843
+
11844
+ class GetPeerBotCommandsInput$Type extends import_runtime4.MessageType {
11845
+ constructor() {
11846
+ super("GetPeerBotCommandsInput", [
11847
+ { no: 1, name: "peer_id", kind: "message", T: () => InputPeer }
11848
+ ]);
11849
+ }
11850
+ create(value) {
11851
+ const message = globalThis.Object.create(this.messagePrototype);
11852
+ if (value !== undefined)
11853
+ import_runtime3.reflectionMergePartial(this, message, value);
11854
+ return message;
11855
+ }
11856
+ internalBinaryRead(reader, length, options, target) {
11857
+ let message = target ?? this.create(), end = reader.pos + length;
11858
+ while (reader.pos < end) {
11859
+ let [fieldNo, wireType] = reader.tag();
11860
+ switch (fieldNo) {
11861
+ case 1:
11862
+ message.peerId = InputPeer.internalBinaryRead(reader, reader.uint32(), options, message.peerId);
11863
+ break;
11864
+ default:
11865
+ let u = options.readUnknownField;
11866
+ if (u === "throw")
11867
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11868
+ let d = reader.skip(wireType);
11869
+ if (u !== false)
11870
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11871
+ }
11872
+ }
11873
+ return message;
11874
+ }
11875
+ internalBinaryWrite(message, writer, options) {
11876
+ if (message.peerId)
11877
+ InputPeer.internalBinaryWrite(message.peerId, writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11878
+ let u = options.writeUnknownFields;
11879
+ if (u !== false)
11880
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11881
+ return writer;
11882
+ }
11883
+ }
11884
+ var GetPeerBotCommandsInput = new GetPeerBotCommandsInput$Type;
11885
+
11886
+ class GetPeerBotCommandsResult$Type extends import_runtime4.MessageType {
11887
+ constructor() {
11888
+ super("GetPeerBotCommandsResult", [
11889
+ { no: 1, name: "bots", kind: "message", repeat: 1, T: () => PeerBotCommands }
11890
+ ]);
11891
+ }
11892
+ create(value) {
11893
+ const message = globalThis.Object.create(this.messagePrototype);
11894
+ message.bots = [];
11895
+ if (value !== undefined)
11896
+ import_runtime3.reflectionMergePartial(this, message, value);
11897
+ return message;
11898
+ }
11899
+ internalBinaryRead(reader, length, options, target) {
11900
+ let message = target ?? this.create(), end = reader.pos + length;
11901
+ while (reader.pos < end) {
11902
+ let [fieldNo, wireType] = reader.tag();
11903
+ switch (fieldNo) {
11904
+ case 1:
11905
+ message.bots.push(PeerBotCommands.internalBinaryRead(reader, reader.uint32(), options));
11906
+ break;
11907
+ default:
11908
+ let u = options.readUnknownField;
11909
+ if (u === "throw")
11910
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
11911
+ let d = reader.skip(wireType);
11912
+ if (u !== false)
11913
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
11914
+ }
11915
+ }
11916
+ return message;
11917
+ }
11918
+ internalBinaryWrite(message, writer, options) {
11919
+ for (let i = 0;i < message.bots.length; i++)
11920
+ PeerBotCommands.internalBinaryWrite(message.bots[i], writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
11921
+ let u = options.writeUnknownFields;
11922
+ if (u !== false)
11923
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
11924
+ return writer;
11925
+ }
11926
+ }
11927
+ var GetPeerBotCommandsResult = new GetPeerBotCommandsResult$Type;
11928
+
11929
+ class RevealBotTokenInput$Type extends import_runtime4.MessageType {
11930
+ constructor() {
11931
+ super("RevealBotTokenInput", [
11792
11932
  { no: 1, name: "bot_user_id", kind: "scalar", T: 3, L: 0 }
11793
11933
  ]);
11794
11934
  }
@@ -18857,6 +18997,9 @@ class WebSocketTransport {
18857
18997
  }
18858
18998
  async reconnect(options) {
18859
18999
  const skipDelay = options?.skipDelay ?? false;
19000
+ if (this.state === "connecting" && this.reconnectionTimer) {
19001
+ return;
19002
+ }
18860
19003
  await this.setConnecting();
18861
19004
  this.cleanUpPreviousConnection();
18862
19005
  this.connectionAttemptNo = this.connectionAttemptNo + 1 >>> 0;
@@ -34276,6 +34419,10 @@ import {
34276
34419
  parseCommandArgs,
34277
34420
  resolveCommandArgMenu
34278
34421
  } from "openclaw/plugin-sdk/native-command-registry";
34422
+ import {
34423
+ createChannelInboundDebouncer,
34424
+ shouldDebounceTextInbound
34425
+ } from "openclaw/plugin-sdk/channel-inbound";
34279
34426
  import { resolveDefaultModelForAgent } from "openclaw/plugin-sdk/agent-runtime";
34280
34427
  import { applyModelOverrideToSessionEntry, updateSessionStore } from "openclaw/plugin-sdk/config-runtime";
34281
34428
  import { buildModelsProviderData } from "openclaw/plugin-sdk/models-provider-runtime";
@@ -35151,6 +35298,9 @@ function formatSdkLogLine(message, meta3) {
35151
35298
  return message;
35152
35299
  return `${message} ${detail}`;
35153
35300
  }
35301
+ function isTransientSdkConnectionLog(line) {
35302
+ return line.startsWith("WebSocket reconnect scheduled ") || line.startsWith("WebSocket closed ") || line.startsWith("WebSocket error: ") || line.startsWith("Protocol reconnect scheduled ") || line.startsWith("Ping timeout, reconnecting ") || line.startsWith("Failed to send ping") || line.startsWith("Failed to send RPC request; waiting for reconnect");
35303
+ }
35154
35304
  var DEFAULT_DM_HISTORY_LIMIT = 6;
35155
35305
  var HISTORY_LINE_MAX_CHARS = 280;
35156
35306
  var URL_LIKE_PATTERN = /https?:\/\/\S+/i;
@@ -35219,6 +35369,18 @@ function buildInlineInboundMessageSid(params) {
35219
35369
  }
35220
35370
  return String(params.msgId);
35221
35371
  }
35372
+ function buildInlineDebounceKey(params) {
35373
+ if (params.senderId == null)
35374
+ return null;
35375
+ return `inline:${params.accountId}:${String(params.chatId)}:${String(params.senderId)}`;
35376
+ }
35377
+ function buildSyntheticInlineTextMessage(params) {
35378
+ return {
35379
+ ...params.base,
35380
+ message: params.text,
35381
+ ...params.mentioned !== undefined ? { mentioned: params.mentioned } : {}
35382
+ };
35383
+ }
35222
35384
  var INLINE_ACTION_MAX_ROWS = 8;
35223
35385
  var INLINE_ACTION_MAX_PER_ROW = 8;
35224
35386
  function isRecord3(value) {
@@ -35395,9 +35557,7 @@ function resolveInlineReplyActions(payload) {
35395
35557
  }
35396
35558
  if (!hasExplicitButtons)
35397
35559
  return;
35398
- const rows = normalizeReplyMarkupButtonsWith(rawButtons, {
35399
- ...mapCallbackData ? { mapCallbackData } : {}
35400
- });
35560
+ const rows = normalizeReplyMarkupButtonsWith(rawButtons, mapCallbackData ? { mapCallbackData } : undefined);
35401
35561
  return {
35402
35562
  rows: rows.map((row, rowIndex) => ({
35403
35563
  actions: row.map((button, buttonIndex) => ({
@@ -35956,7 +36116,7 @@ async function monitorInlineProvider(params) {
35956
36116
  let client = null;
35957
36117
  const pushDiagnostics = (patch) => {
35958
36118
  statusSink?.({
35959
- ...patch ?? {},
36119
+ ...patch,
35960
36120
  ...client ? { diagnostics: client.getDiagnostics() } : {}
35961
36121
  });
35962
36122
  };
@@ -35966,12 +36126,12 @@ async function monitorInlineProvider(params) {
35966
36126
  warn: (msg, meta3) => {
35967
36127
  const line = formatSdkLogLine(msg, meta3);
35968
36128
  log?.warn(line);
35969
- pushDiagnostics({ lastError: line });
36129
+ pushDiagnostics();
35970
36130
  },
35971
36131
  error: (msg, meta3) => {
35972
36132
  const line = formatSdkLogLine(msg, meta3);
35973
36133
  log?.error(line);
35974
- pushDiagnostics({ lastError: line });
36134
+ pushDiagnostics(isTransientSdkConnectionLog(line) ? undefined : { lastError: line });
35975
36135
  }
35976
36136
  };
35977
36137
  client = new InlineSdkClient({
@@ -36037,1000 +36197,1071 @@ async function monitorInlineProvider(params) {
36037
36197
  participantFetches.set(chatKey, run);
36038
36198
  await run;
36039
36199
  };
36040
- const loop = (async () => {
36200
+ const handleInboundNow = async (input) => {
36201
+ const chatId = input.chatId;
36202
+ const msg = input.msg;
36203
+ const rawBodyOverride = input.rawBodyOverride ?? null;
36204
+ const reactionEvent = input.reactionEvent ?? null;
36205
+ const callbackActionEvent = input.callbackActionEvent ?? null;
36206
+ let rawBody = "";
36207
+ let currentContent = null;
36208
+ let currentAttachmentText = null;
36209
+ let currentEntityText = null;
36210
+ if (!reactionEvent && !callbackActionEvent) {
36211
+ if (rawBodyOverride != null) {
36212
+ rawBody = rawBodyOverride.trim();
36213
+ } else {
36214
+ currentContent = summarizeInlineMessageContent(msg);
36215
+ rawBody = buildInlineInboundBodyText(currentContent);
36216
+ currentAttachmentText = currentContent.attachmentText || null;
36217
+ currentEntityText = currentContent.entityText || null;
36218
+ }
36219
+ if (!rawBody)
36220
+ return;
36221
+ }
36222
+ statusSink?.({ lastInboundAt: Date.now() });
36223
+ let chatInfo;
36041
36224
  try {
36042
- for await (const event of client.events()) {
36043
- if (abortSignal.aborted)
36044
- break;
36045
- const rawEvent = event;
36046
- let msg;
36047
- let rawBody = "";
36048
- let currentContent = null;
36049
- let currentAttachmentText = null;
36050
- let currentEntityText = null;
36051
- let reactionEvent = null;
36052
- let inboundChatId = null;
36053
- let callbackActionEvent = null;
36054
- if (event.kind === "message.new") {
36055
- inboundChatId = event.chatId;
36056
- msg = {
36057
- ...event.message,
36058
- chatId: event.chatId
36059
- };
36060
- currentContent = summarizeInlineMessageContent(msg);
36061
- rawBody = buildInlineInboundBodyText(currentContent);
36062
- currentAttachmentText = currentContent.attachmentText || null;
36063
- currentEntityText = currentContent.entityText || null;
36064
- if (!rawBody)
36065
- continue;
36066
- if (msg.out || msg.fromId === meId)
36067
- continue;
36068
- } else if (event.kind === "reaction.add") {
36069
- inboundChatId = event.chatId;
36070
- if (event.reaction.userId === meId)
36071
- continue;
36072
- const onBotMessage = await isReactionTargetBotMessage({
36073
- client,
36074
- chatId: event.chatId,
36075
- messageId: event.reaction.messageId,
36076
- meId,
36077
- botMessageIdsByChat
36078
- }).catch((err) => {
36079
- statusSink?.({ lastError: `getChatHistory (reaction target) failed: ${String(err)}` });
36080
- return false;
36081
- });
36082
- if (!onBotMessage)
36083
- continue;
36084
- reactionEvent = {
36085
- action: "added",
36086
- emoji: event.reaction.emoji,
36087
- targetMessageId: event.reaction.messageId
36088
- };
36089
- msg = {
36090
- id: event.reaction.messageId,
36091
- chatId: event.chatId,
36092
- date: event.date,
36093
- fromId: event.reaction.userId,
36094
- message: "",
36095
- out: false,
36096
- mentioned: false,
36097
- replyToMsgId: event.reaction.messageId
36098
- };
36099
- } else if (event.kind === "reaction.delete") {
36100
- inboundChatId = event.chatId;
36101
- if (event.userId === meId)
36102
- continue;
36103
- const onBotMessage = await isReactionTargetBotMessage({
36104
- client,
36105
- chatId: event.chatId,
36106
- messageId: event.messageId,
36107
- meId,
36108
- botMessageIdsByChat
36109
- }).catch((err) => {
36110
- statusSink?.({ lastError: `getChatHistory (reaction target) failed: ${String(err)}` });
36111
- return false;
36112
- });
36113
- if (!onBotMessage)
36114
- continue;
36115
- reactionEvent = {
36116
- action: "removed",
36117
- emoji: event.emoji,
36118
- targetMessageId: event.messageId
36119
- };
36120
- msg = {
36121
- id: event.messageId,
36122
- chatId: event.chatId,
36123
- date: event.date,
36124
- fromId: event.userId,
36125
- message: "",
36126
- out: false,
36127
- mentioned: false,
36128
- replyToMsgId: event.messageId
36129
- };
36130
- } else if (rawEvent["kind"] === "message.action.invoke") {
36131
- const actorUserId = rawEvent["actorUserId"];
36132
- const interactionId = rawEvent["interactionId"];
36133
- const actionId = rawEvent["actionId"];
36134
- const targetMessageId = rawEvent["messageId"];
36135
- const data = rawEvent["data"];
36136
- const eventChatId = rawEvent["chatId"];
36137
- const eventDate = rawEvent["date"];
36138
- if (!actorUserId || !interactionId || !actionId || !targetMessageId || !eventChatId || !eventDate || !data) {
36139
- continue;
36140
- }
36141
- inboundChatId = eventChatId;
36142
- if (actorUserId === meId)
36143
- continue;
36144
- callbackActionEvent = {
36145
- interactionId,
36146
- actionId,
36147
- targetMessageId,
36148
- data
36149
- };
36150
- msg = {
36151
- id: targetMessageId,
36152
- chatId: eventChatId,
36153
- date: eventDate,
36154
- fromId: actorUserId,
36155
- message: "",
36156
- out: false,
36157
- mentioned: false,
36158
- replyToMsgId: targetMessageId
36159
- };
36160
- } else {
36161
- continue;
36162
- }
36163
- if (!inboundChatId)
36164
- continue;
36165
- const chatId = inboundChatId;
36166
- statusSink?.({ lastInboundAt: Date.now() });
36167
- let chatInfo;
36168
- try {
36169
- chatInfo = await resolveChatInfo(client, chatCache, chatId);
36170
- } catch (err) {
36171
- chatInfo = { kind: "group", title: null };
36172
- statusSink?.({ lastError: `getChat failed: ${String(err)}` });
36173
- }
36174
- const isGroup = chatInfo.kind !== "direct";
36175
- const replyThreadsEnabled = account.config.capabilities?.replyThreads === true || isInlineReplyThreadsEnabled({ cfg, accountId: account.accountId });
36176
- const replyThreadContext = await resolveInlineInboundReplyThreadContext({
36177
- replyThreadsEnabled,
36178
- client,
36179
- chatId,
36180
- chatInfo,
36181
- chatCache
36182
- }).catch((err) => {
36183
- statusSink?.({ lastError: `getChat (reply thread) failed: ${String(err)}` });
36184
- return null;
36185
- });
36186
- const effectiveChatId = replyThreadContext?.parentChatId ?? chatId;
36187
- const effectiveGroupTitle = replyThreadContext?.parentChatTitle ?? chatInfo.title ?? null;
36188
- const senderId = String(msg.fromId);
36189
- await hydrateChatParticipants(chatId);
36190
- const senderProfile = senderProfilesById.get(senderId);
36191
- const senderUsername = senderProfile?.username;
36192
- const senderName = senderProfile?.name ?? (!isGroup ? chatInfo.title ?? undefined : undefined);
36193
- if (reactionEvent) {
36194
- const actor = senderUsername != null && senderUsername.length > 0 ? `@${senderUsername}` : senderName ?? `user:${senderId}`;
36195
- const emoji3 = reactionEvent.emoji.trim() || "a reaction";
36196
- const messageId = String(reactionEvent.targetMessageId);
36197
- if (reactionEvent.action === "added") {
36198
- rawBody = `${actor} reacted with ${emoji3} to your message #${messageId}`;
36199
- } else {
36200
- rawBody = `${actor} removed ${emoji3} from your message #${messageId}`;
36201
- }
36202
- } else if (callbackActionEvent) {
36203
- const actor = senderUsername != null && senderUsername.length > 0 ? `@${senderUsername}` : senderName ?? `user:${senderId}`;
36204
- const payload = {
36205
- type: "inline_message_action_callback",
36206
- interaction_id: String(callbackActionEvent.interactionId),
36207
- actor_user_id: senderId,
36208
- chat_id: String(chatId),
36209
- message_id: String(callbackActionEvent.targetMessageId),
36210
- action_id: callbackActionEvent.actionId,
36211
- data_base64: callbackDataToBase64(callbackActionEvent.data),
36212
- data_utf8: callbackDataToUtf8(callbackActionEvent.data) ?? null
36213
- };
36214
- rawBody = `${actor} pressed a button on message #${String(callbackActionEvent.targetMessageId)}
36225
+ chatInfo = await resolveChatInfo(client, chatCache, chatId);
36226
+ } catch (err) {
36227
+ chatInfo = { kind: "group", title: null };
36228
+ statusSink?.({ lastError: `getChat failed: ${String(err)}` });
36229
+ }
36230
+ const isGroup = chatInfo.kind !== "direct";
36231
+ const replyThreadsEnabled = account.config.capabilities?.replyThreads === true || isInlineReplyThreadsEnabled({ cfg, accountId: account.accountId });
36232
+ const replyThreadContext = await resolveInlineInboundReplyThreadContext({
36233
+ replyThreadsEnabled,
36234
+ client,
36235
+ chatId,
36236
+ chatInfo,
36237
+ chatCache
36238
+ }).catch((err) => {
36239
+ statusSink?.({ lastError: `getChat (reply thread) failed: ${String(err)}` });
36240
+ return null;
36241
+ });
36242
+ const effectiveChatId = replyThreadContext?.parentChatId ?? chatId;
36243
+ const effectiveGroupTitle = replyThreadContext?.parentChatTitle ?? chatInfo.title ?? null;
36244
+ const senderId = String(msg.fromId);
36245
+ await hydrateChatParticipants(chatId);
36246
+ const senderProfile = senderProfilesById.get(senderId);
36247
+ const senderUsername = senderProfile?.username;
36248
+ const senderName = senderProfile?.name ?? (!isGroup ? chatInfo.title ?? undefined : undefined);
36249
+ if (reactionEvent) {
36250
+ const actor = senderUsername != null && senderUsername.length > 0 ? `@${senderUsername}` : senderName ?? `user:${senderId}`;
36251
+ const emoji3 = reactionEvent.emoji.trim() || "a reaction";
36252
+ const messageId = String(reactionEvent.targetMessageId);
36253
+ if (reactionEvent.action === "added") {
36254
+ rawBody = `${actor} reacted with ${emoji3} to your message #${messageId}`;
36255
+ } else {
36256
+ rawBody = `${actor} removed ${emoji3} from your message #${messageId}`;
36257
+ }
36258
+ } else if (callbackActionEvent) {
36259
+ const actor = senderUsername != null && senderUsername.length > 0 ? `@${senderUsername}` : senderName ?? `user:${senderId}`;
36260
+ const payload = {
36261
+ type: "inline_message_action_callback",
36262
+ interaction_id: String(callbackActionEvent.interactionId),
36263
+ actor_user_id: senderId,
36264
+ chat_id: String(chatId),
36265
+ message_id: String(callbackActionEvent.targetMessageId),
36266
+ action_id: callbackActionEvent.actionId,
36267
+ data_base64: callbackDataToBase64(callbackActionEvent.data),
36268
+ data_utf8: callbackDataToUtf8(callbackActionEvent.data) ?? null
36269
+ };
36270
+ rawBody = `${actor} pressed a button on message #${String(callbackActionEvent.targetMessageId)}
36215
36271
  ${JSON.stringify(payload)}`;
36216
- }
36217
- const dmPolicy = account.config.dmPolicy ?? "pairing";
36218
- const defaultGroupPolicy = cfg.channels?.defaults?.groupPolicy;
36219
- const groupPolicy = account.config.groupPolicy ?? defaultGroupPolicy ?? "allowlist";
36220
- const configAllowFrom = normalizeAllowlist(account.config.allowFrom);
36221
- const configGroupAllowFrom = normalizeAllowlist(account.config.groupAllowFrom);
36222
- const storeAllowFrom = await core3.channel.pairing.readAllowFromStore({
36223
- channel: CHANNEL_ID,
36224
- accountId: account.accountId
36225
- }).catch(() => []);
36226
- const storeAllowList = normalizeAllowlist(storeAllowFrom);
36227
- const effectiveAllowFrom = [...configAllowFrom, ...storeAllowList].filter(Boolean);
36228
- const effectiveGroupAllowFrom = [
36229
- ...configGroupAllowFrom.length > 0 ? configGroupAllowFrom : configAllowFrom,
36230
- ...storeAllowList
36231
- ].filter(Boolean);
36232
- const callbackCommandBody = callbackActionEvent ? resolveCallbackCommandBodyFromActionData({
36233
- data: callbackActionEvent.data,
36234
- ...botUsername ? { botUsername } : {}
36235
- }) : undefined;
36236
- let callbackActionAnswered = false;
36237
- const answerCallbackIfNeeded = async () => {
36238
- if (!callbackActionEvent || callbackActionAnswered)
36239
- return;
36240
- await answerInlineMessageAction(client, callbackActionEvent.interactionId);
36241
- callbackActionAnswered = true;
36242
- };
36243
- if (callbackActionEvent) {
36272
+ }
36273
+ const dmPolicy = account.config.dmPolicy ?? "pairing";
36274
+ const defaultGroupPolicy = cfg.channels?.defaults?.groupPolicy;
36275
+ const groupPolicy = account.config.groupPolicy ?? defaultGroupPolicy ?? "allowlist";
36276
+ const configAllowFrom = normalizeAllowlist(account.config.allowFrom);
36277
+ const configGroupAllowFrom = normalizeAllowlist(account.config.groupAllowFrom);
36278
+ const storeAllowFrom = await core3.channel.pairing.readAllowFromStore({
36279
+ channel: CHANNEL_ID,
36280
+ accountId: account.accountId
36281
+ }).catch(() => []);
36282
+ const storeAllowList = normalizeAllowlist(storeAllowFrom);
36283
+ const effectiveAllowFrom = [...configAllowFrom, ...storeAllowList].filter(Boolean);
36284
+ const effectiveGroupAllowFrom = [
36285
+ ...configGroupAllowFrom.length > 0 ? configGroupAllowFrom : configAllowFrom,
36286
+ ...storeAllowList
36287
+ ].filter(Boolean);
36288
+ const callbackCommandBody = callbackActionEvent ? resolveCallbackCommandBodyFromActionData({
36289
+ data: callbackActionEvent.data,
36290
+ ...botUsername ? { botUsername } : {}
36291
+ }) : undefined;
36292
+ let callbackActionAnswered = false;
36293
+ const answerCallbackIfNeeded = async () => {
36294
+ if (!callbackActionEvent || callbackActionAnswered)
36295
+ return;
36296
+ await answerInlineMessageAction(client, callbackActionEvent.interactionId);
36297
+ callbackActionAnswered = true;
36298
+ };
36299
+ if (callbackActionEvent) {
36300
+ await answerCallbackIfNeeded().catch((error48) => {
36301
+ runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36302
+ });
36303
+ }
36304
+ const shouldEditCallbackTargetInPlace = callbackActionEvent != null;
36305
+ const normalizedCommandBody = callbackCommandBody ?? normalizeInlineCommandBody(rawBody, botUsername);
36306
+ const allowTextCommands = core3.channel.commands.shouldHandleTextCommands({
36307
+ cfg,
36308
+ surface: CHANNEL_ID
36309
+ });
36310
+ const useAccessGroups = cfg.commands?.useAccessGroups !== false;
36311
+ const allowForCommands = isGroup ? effectiveGroupAllowFrom : effectiveAllowFrom;
36312
+ const senderAllowedForCommands = allowlistMatch({ allowFrom: allowForCommands, senderId });
36313
+ const hasControlCommand = core3.channel.text.hasControlCommand(callbackCommandBody ?? rawBody, cfg, botUsername ? { botUsername } : undefined);
36314
+ const commandGate = resolveControlCommandGate({
36315
+ useAccessGroups,
36316
+ authorizers: [{ configured: allowForCommands.length > 0, allowed: senderAllowedForCommands }],
36317
+ allowTextCommands,
36318
+ hasControlCommand
36319
+ });
36320
+ const commandAuthorized = commandGate.commandAuthorized;
36321
+ if (isGroup) {
36322
+ if (groupPolicy === "disabled") {
36323
+ log?.info(`[${account.accountId}] inline: drop group chat=${String(chatId)} (groupPolicy=disabled)`);
36324
+ await answerCallbackIfNeeded().catch((error48) => {
36325
+ runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36326
+ });
36327
+ return;
36328
+ }
36329
+ if (groupPolicy === "allowlist") {
36330
+ const allowed = allowlistMatch({ allowFrom: effectiveGroupAllowFrom, senderId });
36331
+ if (!allowed) {
36332
+ log?.info(`[${account.accountId}] inline: drop group sender=${senderId} (groupPolicy=allowlist)`);
36244
36333
  await answerCallbackIfNeeded().catch((error48) => {
36245
36334
  runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36246
36335
  });
36336
+ return;
36247
36337
  }
36248
- const shouldEditCallbackTargetInPlace = callbackActionEvent != null;
36249
- const normalizedCommandBody = callbackCommandBody ?? normalizeInlineCommandBody(rawBody, botUsername);
36250
- const allowTextCommands = core3.channel.commands.shouldHandleTextCommands({
36251
- cfg,
36252
- surface: CHANNEL_ID
36253
- });
36254
- const useAccessGroups = cfg.commands?.useAccessGroups !== false;
36255
- const allowForCommands = isGroup ? effectiveGroupAllowFrom : effectiveAllowFrom;
36256
- const senderAllowedForCommands = allowlistMatch({ allowFrom: allowForCommands, senderId });
36257
- const hasControlCommand = core3.channel.text.hasControlCommand(callbackCommandBody ?? rawBody, cfg, botUsername ? { botUsername } : undefined);
36258
- const commandGate = resolveControlCommandGate({
36259
- useAccessGroups,
36260
- authorizers: [{ configured: allowForCommands.length > 0, allowed: senderAllowedForCommands }],
36261
- allowTextCommands,
36262
- hasControlCommand
36338
+ }
36339
+ } else {
36340
+ if (dmPolicy === "disabled") {
36341
+ log?.info(`[${account.accountId}] inline: drop DM sender=${senderId} (dmPolicy=disabled)`);
36342
+ await answerCallbackIfNeeded().catch((error48) => {
36343
+ runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36263
36344
  });
36264
- const commandAuthorized = commandGate.commandAuthorized;
36265
- if (isGroup) {
36266
- if (groupPolicy === "disabled") {
36267
- log?.info(`[${account.accountId}] inline: drop group chat=${String(chatId)} (groupPolicy=disabled)`);
36268
- await answerCallbackIfNeeded().catch((error48) => {
36269
- runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36270
- });
36271
- continue;
36272
- }
36273
- if (groupPolicy === "allowlist") {
36274
- const allowed = allowlistMatch({ allowFrom: effectiveGroupAllowFrom, senderId });
36275
- if (!allowed) {
36276
- log?.info(`[${account.accountId}] inline: drop group sender=${senderId} (groupPolicy=allowlist)`);
36277
- await answerCallbackIfNeeded().catch((error48) => {
36278
- runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36279
- });
36280
- continue;
36281
- }
36282
- }
36283
- } else {
36284
- if (dmPolicy === "disabled") {
36285
- log?.info(`[${account.accountId}] inline: drop DM sender=${senderId} (dmPolicy=disabled)`);
36286
- await answerCallbackIfNeeded().catch((error48) => {
36287
- runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36345
+ return;
36346
+ }
36347
+ if (dmPolicy !== "open") {
36348
+ const allowed = allowlistMatch({ allowFrom: effectiveAllowFrom, senderId });
36349
+ if (!allowed) {
36350
+ if (dmPolicy === "pairing") {
36351
+ const { code, created } = await core3.channel.pairing.upsertPairingRequest({
36352
+ channel: CHANNEL_ID,
36353
+ id: senderId,
36354
+ accountId: account.accountId,
36355
+ meta: {},
36356
+ pairingAdapter: { idLabel: "inlineUserId", normalizeAllowEntry }
36288
36357
  });
36289
- continue;
36290
- }
36291
- if (dmPolicy !== "open") {
36292
- const allowed = allowlistMatch({ allowFrom: effectiveAllowFrom, senderId });
36293
- if (!allowed) {
36294
- if (dmPolicy === "pairing") {
36295
- const { code, created } = await core3.channel.pairing.upsertPairingRequest({
36296
- channel: CHANNEL_ID,
36297
- id: senderId,
36298
- accountId: account.accountId,
36299
- meta: {},
36300
- pairingAdapter: { idLabel: "inlineUserId", normalizeAllowEntry }
36358
+ if (created) {
36359
+ try {
36360
+ await client.sendMessage({
36361
+ chatId,
36362
+ text: core3.channel.pairing.buildPairingReply({
36363
+ channel: CHANNEL_ID,
36364
+ idLine: `Your Inline user id: ${senderId}`,
36365
+ code
36366
+ })
36301
36367
  });
36302
- if (created) {
36303
- try {
36304
- await client.sendMessage({
36305
- chatId,
36306
- text: core3.channel.pairing.buildPairingReply({
36307
- channel: CHANNEL_ID,
36308
- idLine: `Your Inline user id: ${senderId}`,
36309
- code
36310
- })
36311
- });
36312
- statusSink?.({ lastOutboundAt: Date.now() });
36313
- } catch (err) {
36314
- runtime2.error?.(`inline: pairing reply failed for ${senderId}: ${String(err)}`);
36315
- }
36316
- }
36368
+ statusSink?.({ lastOutboundAt: Date.now() });
36369
+ } catch (err) {
36370
+ runtime2.error?.(`inline: pairing reply failed for ${senderId}: ${String(err)}`);
36317
36371
  }
36318
- log?.info(`[${account.accountId}] inline: drop DM sender=${senderId} (dmPolicy=${dmPolicy})`);
36319
- await answerCallbackIfNeeded().catch((error48) => {
36320
- runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36321
- });
36322
- continue;
36323
36372
  }
36324
36373
  }
36325
- }
36326
- if (isGroup && commandGate.shouldBlock) {
36327
- logInboundDrop({
36328
- log: (m) => runtime2.log?.(m),
36329
- channel: CHANNEL_ID,
36330
- reason: "control command (unauthorized)",
36331
- target: senderId
36332
- });
36374
+ log?.info(`[${account.accountId}] inline: drop DM sender=${senderId} (dmPolicy=${dmPolicy})`);
36333
36375
  await answerCallbackIfNeeded().catch((error48) => {
36334
36376
  runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36335
36377
  });
36336
- continue;
36378
+ return;
36337
36379
  }
36338
- const route = core3.channel.routing.resolveAgentRoute({
36339
- cfg,
36340
- channel: CHANNEL_ID,
36341
- accountId: account.accountId,
36342
- peer: {
36343
- kind: isGroup ? "group" : "direct",
36344
- id: isGroup ? String(effectiveChatId) : senderId
36380
+ }
36381
+ }
36382
+ if (isGroup && commandGate.shouldBlock) {
36383
+ logInboundDrop({
36384
+ log: (m) => runtime2.log?.(m),
36385
+ channel: CHANNEL_ID,
36386
+ reason: "control command (unauthorized)",
36387
+ target: senderId
36388
+ });
36389
+ await answerCallbackIfNeeded().catch((error48) => {
36390
+ runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36391
+ });
36392
+ return;
36393
+ }
36394
+ const route = core3.channel.routing.resolveAgentRoute({
36395
+ cfg,
36396
+ channel: CHANNEL_ID,
36397
+ accountId: account.accountId,
36398
+ peer: {
36399
+ kind: isGroup ? "group" : "direct",
36400
+ id: isGroup ? String(effectiveChatId) : senderId
36401
+ }
36402
+ });
36403
+ const mentionRegexes = core3.channel.mentions.buildMentionRegexes(cfg, route.agentId);
36404
+ const nativeMentioned = typeof msg.mentioned === "boolean" ? msg.mentioned : false;
36405
+ const patternMentioned = mentionRegexes.length ? core3.channel.mentions.matchesMentionPatterns(rawBody, mentionRegexes) : false;
36406
+ const wasMentioned = nativeMentioned || patternMentioned;
36407
+ const messageTimestamp = Number(msg.date) * 1000;
36408
+ const groupHistoryKey = isGroup ? replyThreadContext ? `${route.sessionKey}:thread:${String(replyThreadContext.childChatId)}` : route.sessionKey : null;
36409
+ const pendingHistorySender = senderUsername ? `@${senderUsername}` : senderName ?? `user:${senderId}`;
36410
+ const historyLimit = resolveHistoryLimit({
36411
+ cfg,
36412
+ isGroup,
36413
+ historyLimit: account.config.historyLimit,
36414
+ dmHistoryLimit: account.config.dmHistoryLimit
36415
+ });
36416
+ const historyContext = await buildHistoryContext2({
36417
+ client,
36418
+ chatId,
36419
+ currentMessageId: msg.id,
36420
+ replyToMsgId: msg.replyToMsgId,
36421
+ senderProfilesById,
36422
+ meId,
36423
+ historyLimit,
36424
+ botMessageIdsByChat
36425
+ }).catch((err) => {
36426
+ statusSink?.({ lastError: `getChatHistory failed: ${String(err)}` });
36427
+ return {
36428
+ historyText: null,
36429
+ attachmentText: null,
36430
+ entityText: null,
36431
+ inboundHistory: [],
36432
+ repliedToBot: false,
36433
+ replyToSenderId: null
36434
+ };
36435
+ });
36436
+ const effectiveHistoryContext = replyThreadContext?.anchorMessage != null ? prependInlineReplyThreadAnchor({
36437
+ historyContext,
36438
+ anchorMessage: replyThreadContext.anchorMessage,
36439
+ parentChatId: replyThreadContext.parentChatId,
36440
+ senderProfilesById,
36441
+ meId
36442
+ }) : historyContext;
36443
+ const implicitMention = (reactionEvent != null || callbackActionEvent != null) && isGroup || isGroup && (account.config.replyToBotWithoutMention ?? false) && msg.replyToMsgId != null && effectiveHistoryContext.repliedToBot;
36444
+ const requireMention = isGroup ? resolveInlineGroupRequireMention({
36445
+ cfg,
36446
+ groupId: String(effectiveChatId),
36447
+ accountId: account.accountId,
36448
+ requireMentionDefault: account.config.requireMention ?? false
36449
+ }) : false;
36450
+ const mentionGate = resolveMentionGatingWithBypass({
36451
+ isGroup,
36452
+ requireMention,
36453
+ canDetectMention: typeof msg.mentioned === "boolean" || mentionRegexes.length > 0,
36454
+ wasMentioned,
36455
+ implicitMention,
36456
+ allowTextCommands,
36457
+ hasControlCommand,
36458
+ commandAuthorized
36459
+ });
36460
+ if (isGroup && mentionGate.shouldSkip) {
36461
+ runtime2.log?.(`inline: drop group chat ${String(chatId)} (no mention)`);
36462
+ const pendingBody = normalizeHistoryText(currentContent?.text) ?? normalizeHistoryText(rawBody);
36463
+ recordPendingHistoryEntryIfEnabled({
36464
+ historyMap: groupPendingHistories,
36465
+ historyKey: groupHistoryKey ?? "",
36466
+ limit: historyLimit,
36467
+ entry: groupHistoryKey && pendingBody ? {
36468
+ sender: pendingHistorySender,
36469
+ body: pendingBody,
36470
+ timestamp: messageTimestamp || Date.now(),
36471
+ messageId: String(msg.id)
36472
+ } : null
36473
+ });
36474
+ await answerCallbackIfNeeded().catch((error48) => {
36475
+ runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36476
+ });
36477
+ return;
36478
+ }
36479
+ const parseMarkdown = account.config.parseMarkdown ?? true;
36480
+ const nativeCommandMenu = resolveInlineNativeCommandMenu({
36481
+ commandBody: normalizedCommandBody,
36482
+ cfg
36483
+ });
36484
+ if (nativeCommandMenu) {
36485
+ const menuActions = resolveInlineReplyActions({
36486
+ channelData: {
36487
+ inline: {
36488
+ buttons: nativeCommandMenu.buttons
36345
36489
  }
36346
- });
36347
- const mentionRegexes = core3.channel.mentions.buildMentionRegexes(cfg, route.agentId);
36348
- const nativeMentioned = typeof msg.mentioned === "boolean" ? msg.mentioned : false;
36349
- const patternMentioned = mentionRegexes.length ? core3.channel.mentions.matchesMentionPatterns(rawBody, mentionRegexes) : false;
36350
- const wasMentioned = nativeMentioned || patternMentioned;
36351
- const messageTimestamp = Number(msg.date) * 1000;
36352
- const groupHistoryKey = isGroup ? replyThreadContext ? `${route.sessionKey}:thread:${String(replyThreadContext.childChatId)}` : route.sessionKey : null;
36353
- const pendingHistorySender = senderUsername ? `@${senderUsername}` : senderName ?? `user:${senderId}`;
36354
- const historyLimit = resolveHistoryLimit({
36355
- cfg,
36356
- isGroup,
36357
- historyLimit: account.config.historyLimit,
36358
- dmHistoryLimit: account.config.dmHistoryLimit
36359
- });
36360
- const historyContext = await buildHistoryContext2({
36361
- client,
36362
- chatId,
36363
- currentMessageId: msg.id,
36364
- replyToMsgId: msg.replyToMsgId,
36365
- senderProfilesById,
36366
- meId,
36367
- historyLimit,
36368
- botMessageIdsByChat
36369
- }).catch((err) => {
36370
- statusSink?.({ lastError: `getChatHistory failed: ${String(err)}` });
36371
- return {
36372
- historyText: null,
36373
- attachmentText: null,
36374
- entityText: null,
36375
- inboundHistory: [],
36376
- repliedToBot: false,
36377
- replyToSenderId: null
36378
- };
36379
- });
36380
- const effectiveHistoryContext = replyThreadContext?.anchorMessage != null ? prependInlineReplyThreadAnchor({
36381
- historyContext,
36382
- anchorMessage: replyThreadContext.anchorMessage,
36383
- parentChatId: replyThreadContext.parentChatId,
36384
- senderProfilesById,
36385
- meId
36386
- }) : historyContext;
36387
- const implicitMention = (reactionEvent != null || callbackActionEvent != null) && isGroup || isGroup && (account.config.replyToBotWithoutMention ?? false) && msg.replyToMsgId != null && effectiveHistoryContext.repliedToBot;
36388
- const requireMention = isGroup ? resolveInlineGroupRequireMention({
36389
- cfg,
36390
- groupId: String(effectiveChatId),
36391
- accountId: account.accountId,
36392
- requireMentionDefault: account.config.requireMention ?? false
36393
- }) : false;
36394
- const mentionGate = resolveMentionGatingWithBypass({
36395
- isGroup,
36396
- requireMention,
36397
- canDetectMention: typeof msg.mentioned === "boolean" || mentionRegexes.length > 0,
36398
- wasMentioned,
36399
- implicitMention,
36400
- allowTextCommands,
36401
- hasControlCommand,
36402
- commandAuthorized
36403
- });
36404
- if (isGroup && mentionGate.shouldSkip) {
36405
- runtime2.log?.(`inline: drop group chat ${String(chatId)} (no mention)`);
36406
- const pendingBody = normalizeHistoryText(currentContent?.text) ?? normalizeHistoryText(rawBody);
36407
- recordPendingHistoryEntryIfEnabled({
36408
- historyMap: groupPendingHistories,
36409
- historyKey: groupHistoryKey ?? "",
36410
- limit: historyLimit,
36411
- entry: groupHistoryKey && pendingBody ? {
36412
- sender: pendingHistorySender,
36413
- body: pendingBody,
36414
- timestamp: messageTimestamp || Date.now(),
36415
- messageId: String(msg.id)
36416
- } : null
36417
- });
36418
- await answerCallbackIfNeeded().catch((error48) => {
36419
- runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36420
- });
36421
- continue;
36422
36490
  }
36423
- const parseMarkdown = account.config.parseMarkdown ?? true;
36424
- const nativeCommandMenu = resolveInlineNativeCommandMenu({
36425
- commandBody: normalizedCommandBody,
36426
- cfg
36427
- });
36428
- if (nativeCommandMenu) {
36429
- const menuActions = resolveInlineReplyActions({
36430
- channelData: {
36431
- inline: {
36432
- buttons: nativeCommandMenu.buttons
36433
- }
36491
+ });
36492
+ let deliveredNativeMenu = false;
36493
+ if (shouldEditCallbackTargetInPlace && callbackActionEvent) {
36494
+ try {
36495
+ const result = await client.invokeRaw(Method.EDIT_MESSAGE, {
36496
+ oneofKind: "editMessage",
36497
+ editMessage: {
36498
+ messageId: callbackActionEvent.targetMessageId,
36499
+ peerId: buildChatPeer2(chatId),
36500
+ text: nativeCommandMenu.title,
36501
+ ...menuActions ? { actions: menuActions } : {},
36502
+ parseMarkdown
36434
36503
  }
36435
36504
  });
36436
- let deliveredNativeMenu = false;
36437
- if (shouldEditCallbackTargetInPlace && callbackActionEvent) {
36438
- try {
36439
- const result = await client.invokeRaw(Method.EDIT_MESSAGE, {
36440
- oneofKind: "editMessage",
36441
- editMessage: {
36442
- messageId: callbackActionEvent.targetMessageId,
36443
- peerId: buildChatPeer2(chatId),
36444
- text: nativeCommandMenu.title,
36445
- ...menuActions ? { actions: menuActions } : {},
36446
- parseMarkdown
36447
- }
36448
- });
36449
- if (result.oneofKind !== "editMessage") {
36450
- throw new Error(`inline native command menu: expected editMessage result, got ${String(result.oneofKind)}`);
36451
- }
36452
- deliveredNativeMenu = true;
36453
- } catch (error48) {
36454
- runtime2.error?.(`inline native command menu edit failed; falling back to send (${String(error48)})`);
36505
+ if (result.oneofKind !== "editMessage") {
36506
+ throw new Error(`inline native command menu: expected editMessage result, got ${String(result.oneofKind)}`);
36507
+ }
36508
+ deliveredNativeMenu = true;
36509
+ } catch (error48) {
36510
+ runtime2.error?.(`inline native command menu edit failed; falling back to send (${String(error48)})`);
36511
+ }
36512
+ }
36513
+ if (!deliveredNativeMenu) {
36514
+ const sent = await client.sendMessage({
36515
+ chatId,
36516
+ text: nativeCommandMenu.title,
36517
+ ...menuActions ? { actions: menuActions } : {}
36518
+ });
36519
+ if (sent.messageId != null) {
36520
+ rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
36521
+ }
36522
+ }
36523
+ statusSink?.({ lastOutboundAt: Date.now() });
36524
+ await answerCallbackIfNeeded().catch((error48) => {
36525
+ runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36526
+ });
36527
+ return;
36528
+ }
36529
+ const modelPickerCallbackData = callbackActionEvent ? callbackDataToUtf8(callbackActionEvent.data) : undefined;
36530
+ const modelPickerCallback = modelPickerCallbackData ? parseInlineModelPickerCallback(modelPickerCallbackData) : null;
36531
+ if (shouldEditCallbackTargetInPlace && callbackActionEvent && modelPickerCallback?.type === "select") {
36532
+ const deliverModelPickerEdit = async (text, buttons) => {
36533
+ const actions = resolveInlineReplyActions({
36534
+ channelData: {
36535
+ inline: {
36536
+ buttons
36455
36537
  }
36456
36538
  }
36457
- if (!deliveredNativeMenu) {
36458
- const sent = await client.sendMessage({
36459
- chatId,
36460
- text: nativeCommandMenu.title,
36461
- ...menuActions ? { actions: menuActions } : {}
36462
- });
36463
- if (sent.messageId != null) {
36464
- rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
36539
+ }) ?? { rows: [] };
36540
+ try {
36541
+ const result = await client.invokeRaw(Method.EDIT_MESSAGE, {
36542
+ oneofKind: "editMessage",
36543
+ editMessage: {
36544
+ messageId: callbackActionEvent.targetMessageId,
36545
+ peerId: buildChatPeer2(chatId),
36546
+ text,
36547
+ actions,
36548
+ parseMarkdown
36465
36549
  }
36550
+ });
36551
+ if (result.oneofKind !== "editMessage") {
36552
+ throw new Error(`inline model picker edit: expected editMessage result, got ${String(result.oneofKind)}`);
36466
36553
  }
36467
- statusSink?.({ lastOutboundAt: Date.now() });
36468
- await answerCallbackIfNeeded().catch((error48) => {
36469
- runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36554
+ } catch (error48) {
36555
+ runtime2.error?.(`inline model picker edit failed; falling back to send (${String(error48)})`);
36556
+ const sent = await client.sendMessage({
36557
+ chatId,
36558
+ text,
36559
+ actions,
36560
+ parseMarkdown
36470
36561
  });
36471
- continue;
36562
+ if (sent.messageId != null) {
36563
+ rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
36564
+ }
36472
36565
  }
36473
- const modelPickerCallbackData = callbackActionEvent ? callbackDataToUtf8(callbackActionEvent.data) : undefined;
36474
- const modelPickerCallback = modelPickerCallbackData ? parseInlineModelPickerCallback(modelPickerCallbackData) : null;
36475
- if (shouldEditCallbackTargetInPlace && callbackActionEvent && modelPickerCallback?.type === "select") {
36476
- const deliverModelPickerEdit = async (text, buttons) => {
36477
- const actions = resolveInlineReplyActions({
36478
- channelData: {
36479
- inline: {
36480
- buttons
36481
- }
36482
- }
36483
- }) ?? { rows: [] };
36484
- try {
36485
- const result = await client.invokeRaw(Method.EDIT_MESSAGE, {
36486
- oneofKind: "editMessage",
36487
- editMessage: {
36488
- messageId: callbackActionEvent.targetMessageId,
36489
- peerId: buildChatPeer2(chatId),
36490
- text,
36491
- actions,
36492
- parseMarkdown
36493
- }
36494
- });
36495
- if (result.oneofKind !== "editMessage") {
36496
- throw new Error(`inline model picker edit: expected editMessage result, got ${String(result.oneofKind)}`);
36497
- }
36498
- } catch (error48) {
36499
- runtime2.error?.(`inline model picker edit failed; falling back to send (${String(error48)})`);
36500
- const sent = await client.sendMessage({
36501
- chatId,
36502
- text,
36503
- actions,
36504
- parseMarkdown
36505
- });
36506
- if (sent.messageId != null) {
36507
- rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
36508
- }
36509
- }
36510
- };
36511
- const { byProvider, providers } = await buildModelsProviderData(cfg, route.agentId);
36512
- const providerButtons = buildInlineModelProviderButtons(providers.map((provider) => ({
36513
- id: provider,
36514
- count: byProvider.get(provider)?.size ?? 0
36515
- })));
36516
- const selection = resolveInlineModelPickerSelection({
36517
- callback: modelPickerCallback,
36518
- providers,
36519
- byProvider
36520
- });
36521
- if (selection.kind !== "resolved") {
36522
- await deliverModelPickerEdit(`Could not resolve model "${selection.model}".
36566
+ };
36567
+ const { byProvider, providers } = await buildModelsProviderData(cfg, route.agentId);
36568
+ const providerButtons = buildInlineModelProviderButtons(providers.map((provider) => ({
36569
+ id: provider,
36570
+ count: byProvider.get(provider)?.size ?? 0
36571
+ })));
36572
+ const selection = resolveInlineModelPickerSelection({
36573
+ callback: modelPickerCallback,
36574
+ providers,
36575
+ byProvider
36576
+ });
36577
+ if (selection.kind !== "resolved") {
36578
+ await deliverModelPickerEdit(`Could not resolve model "${selection.model}".
36523
36579
 
36524
36580
  Select a provider:`, providerButtons);
36525
- } else {
36526
- const modelSet = byProvider.get(selection.provider);
36527
- if (!modelSet?.has(selection.model)) {
36528
- await deliverModelPickerEdit(`❌ Model "${selection.provider}/${selection.model}" is not allowed.`, []);
36529
- } else {
36530
- try {
36531
- const storePath2 = core3.channel.session.resolveStorePath(cfg.session?.store, {
36532
- agentId: route.agentId
36533
- });
36534
- const resolvedDefault = resolveDefaultModelForAgent({
36535
- cfg,
36536
- agentId: route.agentId
36537
- });
36538
- const isDefaultSelection = selection.provider === resolvedDefault.provider && selection.model === resolvedDefault.model;
36539
- await updateSessionStore(storePath2, (store) => {
36540
- const entry = store[route.sessionKey] ?? {
36541
- sessionId: route.sessionKey,
36542
- updatedAt: Date.now()
36543
- };
36544
- store[route.sessionKey] = entry;
36545
- applyModelOverrideToSessionEntry({
36546
- entry,
36547
- selection: {
36548
- provider: selection.provider,
36549
- model: selection.model,
36550
- isDefault: isDefaultSelection
36551
- }
36552
- });
36553
- });
36554
- const actionText = isDefaultSelection ? "reset to default" : `changed to **${selection.provider}/${selection.model}**`;
36555
- await deliverModelPickerEdit(`✅ Model ${actionText}
36581
+ } else {
36582
+ const modelSet = byProvider.get(selection.provider);
36583
+ if (!modelSet?.has(selection.model)) {
36584
+ await deliverModelPickerEdit(`❌ Model "${selection.provider}/${selection.model}" is not allowed.`, []);
36585
+ } else {
36586
+ try {
36587
+ const storePath2 = core3.channel.session.resolveStorePath(cfg.session?.store, {
36588
+ agentId: route.agentId
36589
+ });
36590
+ const resolvedDefault = resolveDefaultModelForAgent({
36591
+ cfg,
36592
+ agentId: route.agentId
36593
+ });
36594
+ const isDefaultSelection = selection.provider === resolvedDefault.provider && selection.model === resolvedDefault.model;
36595
+ await updateSessionStore(storePath2, (store) => {
36596
+ const entry = store[route.sessionKey] ?? {
36597
+ sessionId: route.sessionKey,
36598
+ updatedAt: Date.now()
36599
+ };
36600
+ store[route.sessionKey] = entry;
36601
+ applyModelOverrideToSessionEntry({
36602
+ entry,
36603
+ selection: {
36604
+ provider: selection.provider,
36605
+ model: selection.model,
36606
+ isDefault: isDefaultSelection
36607
+ }
36608
+ });
36609
+ });
36610
+ const actionText = isDefaultSelection ? "reset to default" : `changed to **${selection.provider}/${selection.model}**`;
36611
+ await deliverModelPickerEdit(`✅ Model ${actionText}
36556
36612
 
36557
36613
  This model will be used for your next message.`, []);
36558
- } catch (error48) {
36559
- await deliverModelPickerEdit(`❌ Failed to change model: ${String(error48)}`, []);
36560
- }
36561
- }
36614
+ } catch (error48) {
36615
+ await deliverModelPickerEdit(`❌ Failed to change model: ${String(error48)}`, []);
36562
36616
  }
36563
- statusSink?.({ lastOutboundAt: Date.now() });
36564
- await answerCallbackIfNeeded().catch((error48) => {
36565
- runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36566
- });
36567
- continue;
36568
36617
  }
36569
- const inboundMedia = reactionEvent ? [] : await resolveInlineInboundMedia({
36570
- core: core3,
36571
- message: msg,
36572
- maxBytes: inboundMediaMaxBytes,
36573
- ...log ? { log } : {}
36574
- });
36575
- const timestamp = messageTimestamp;
36576
- const fromLabel = isGroup ? `chat:${effectiveGroupTitle ?? String(effectiveChatId)}` : `user:${senderId}`;
36577
- const storePath = core3.channel.session.resolveStorePath(cfg.session?.store, { agentId: route.agentId });
36578
- const envelopeOptions = core3.channel.reply.resolveEnvelopeFormatOptions(cfg);
36579
- const previousTimestamp = core3.channel.session.readSessionUpdatedAt({ storePath, sessionKey: route.sessionKey });
36580
- const combinedBody = [
36581
- effectiveHistoryContext.historyText,
36582
- effectiveHistoryContext.attachmentText,
36583
- effectiveHistoryContext.entityText,
36584
- INLINE_FORMATTING_NOTE,
36585
- `Current message:
36618
+ }
36619
+ statusSink?.({ lastOutboundAt: Date.now() });
36620
+ await answerCallbackIfNeeded().catch((error48) => {
36621
+ runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
36622
+ });
36623
+ return;
36624
+ }
36625
+ const inboundMedia = reactionEvent ? [] : await resolveInlineInboundMedia({
36626
+ core: core3,
36627
+ message: msg,
36628
+ maxBytes: inboundMediaMaxBytes,
36629
+ ...log ? { log } : {}
36630
+ });
36631
+ const timestamp = messageTimestamp;
36632
+ const fromLabel = isGroup ? `chat:${effectiveGroupTitle ?? String(effectiveChatId)}` : `user:${senderId}`;
36633
+ const storePath = core3.channel.session.resolveStorePath(cfg.session?.store, { agentId: route.agentId });
36634
+ const envelopeOptions = core3.channel.reply.resolveEnvelopeFormatOptions(cfg);
36635
+ const previousTimestamp = core3.channel.session.readSessionUpdatedAt({ storePath, sessionKey: route.sessionKey });
36636
+ const combinedBody = [
36637
+ effectiveHistoryContext.historyText,
36638
+ effectiveHistoryContext.attachmentText,
36639
+ effectiveHistoryContext.entityText,
36640
+ INLINE_FORMATTING_NOTE,
36641
+ `Current message:
36586
36642
  ${rawBody}`,
36587
- currentAttachmentText && currentAttachmentText !== rawBody ? `Current media/attachments:
36643
+ currentAttachmentText && currentAttachmentText !== rawBody ? `Current media/attachments:
36588
36644
  ${currentAttachmentText}` : null,
36589
- currentEntityText ? `Current message entities:
36645
+ currentEntityText ? `Current message entities:
36590
36646
  ${currentEntityText}` : null
36591
- ].filter(Boolean).join(`
36647
+ ].filter(Boolean).join(`
36592
36648
 
36593
36649
  `);
36594
- let body = core3.channel.reply.formatAgentEnvelope({
36650
+ let body = core3.channel.reply.formatAgentEnvelope({
36651
+ channel: "Inline",
36652
+ from: fromLabel,
36653
+ timestamp,
36654
+ ...previousTimestamp != null ? { previousTimestamp } : {},
36655
+ envelope: envelopeOptions,
36656
+ body: combinedBody || rawBody
36657
+ });
36658
+ if (isGroup && groupHistoryKey) {
36659
+ body = buildPendingHistoryContextFromMap({
36660
+ historyMap: groupPendingHistories,
36661
+ historyKey: groupHistoryKey,
36662
+ limit: historyLimit,
36663
+ currentMessage: body,
36664
+ formatEntry: (entry) => core3.channel.reply.formatAgentEnvelope({
36595
36665
  channel: "Inline",
36596
36666
  from: fromLabel,
36597
- timestamp,
36598
- ...previousTimestamp != null ? { previousTimestamp } : {},
36667
+ ...entry.timestamp != null ? { timestamp: entry.timestamp } : {},
36599
36668
  envelope: envelopeOptions,
36600
- body: combinedBody || rawBody
36601
- });
36602
- if (isGroup && groupHistoryKey) {
36603
- body = buildPendingHistoryContextFromMap({
36604
- historyMap: groupPendingHistories,
36605
- historyKey: groupHistoryKey,
36606
- limit: historyLimit,
36607
- currentMessage: body,
36608
- formatEntry: (entry) => core3.channel.reply.formatAgentEnvelope({
36609
- channel: "Inline",
36610
- from: fromLabel,
36611
- ...entry.timestamp != null ? { timestamp: entry.timestamp } : {},
36612
- envelope: envelopeOptions,
36613
- body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} chat:${String(chatId)}]` : ""}`
36614
- })
36615
- });
36669
+ body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} chat:${String(chatId)}]` : ""}`
36670
+ })
36671
+ });
36672
+ }
36673
+ const inboundHistory = isGroup && groupHistoryKey ? mergeInboundHistoryEntries({
36674
+ historyContextEntries: effectiveHistoryContext.inboundHistory,
36675
+ pendingEntries: groupPendingHistories.get(groupHistoryKey) ?? [],
36676
+ limit: historyLimit
36677
+ }) : [];
36678
+ const bodyForAgent = buildInlineBodyForAgent({
36679
+ rawBody,
36680
+ currentAttachmentText,
36681
+ currentEntityText
36682
+ });
36683
+ const effectiveSurface = shouldUseTelegramSurfaceForModelCommands(normalizedCommandBody) ? "telegram" : CHANNEL_ID;
36684
+ const systemPrompt = resolveInlineSystemPrompt({
36685
+ account,
36686
+ ...isGroup ? { groupId: String(effectiveChatId) } : {}
36687
+ });
36688
+ const ctxPayload = core3.channel.reply.finalizeInboundContext({
36689
+ Body: body,
36690
+ BodyForAgent: bodyForAgent,
36691
+ ...isGroup ? { InboundHistory: inboundHistory } : {},
36692
+ RawBody: rawBody,
36693
+ CommandBody: normalizedCommandBody,
36694
+ From: isGroup ? `inline:chat:${String(effectiveChatId)}` : `inline:${senderId}`,
36695
+ To: `inline:${String(effectiveChatId)}`,
36696
+ SessionKey: route.sessionKey,
36697
+ ...replyThreadContext ? { ParentSessionKey: route.sessionKey } : {},
36698
+ AccountId: route.accountId,
36699
+ ChatType: isGroup ? "group" : "direct",
36700
+ ConversationLabel: fromLabel,
36701
+ ...isGroup ? { GroupSubject: effectiveGroupTitle ?? String(effectiveChatId) } : {},
36702
+ SenderId: senderId,
36703
+ ...senderName ? { SenderName: senderName } : {},
36704
+ ...senderUsername ? { SenderUsername: senderUsername } : {},
36705
+ Provider: CHANNEL_ID,
36706
+ Surface: effectiveSurface,
36707
+ MessageSid: buildInlineInboundMessageSid({
36708
+ msgId: msg.id,
36709
+ ...callbackActionEvent ? { callbackActionEvent } : {}
36710
+ }),
36711
+ ...replyThreadContext ? { MessageThreadId: String(replyThreadContext.childChatId) } : {},
36712
+ ...replyThreadContext?.threadLabel ? { ThreadLabel: replyThreadContext.threadLabel } : {},
36713
+ ...msg.replyToMsgId != null ? { ReplyToId: String(msg.replyToMsgId) } : {},
36714
+ ...effectiveHistoryContext.replyToSenderId != null ? { ReplyToSenderId: effectiveHistoryContext.replyToSenderId } : {},
36715
+ ...msg.replyToMsgId != null ? { ReplyToWasBot: effectiveHistoryContext.repliedToBot } : {},
36716
+ ...callbackActionEvent ? {
36717
+ MessageActionInteractionId: String(callbackActionEvent.interactionId),
36718
+ MessageActionId: callbackActionEvent.actionId,
36719
+ MessageActionDataBase64: callbackDataToBase64(callbackActionEvent.data),
36720
+ ...callbackDataToUtf8(callbackActionEvent.data) ? { MessageActionDataUtf8: callbackDataToUtf8(callbackActionEvent.data) } : {}
36721
+ } : {},
36722
+ ...buildInlineInboundMediaPayload(inboundMedia),
36723
+ Timestamp: timestamp || Date.now(),
36724
+ WasMentioned: mentionGate.effectiveWasMentioned,
36725
+ CommandAuthorized: commandAuthorized,
36726
+ GroupSystemPrompt: systemPrompt,
36727
+ OriginatingChannel: CHANNEL_ID,
36728
+ OriginatingTo: `inline:${String(effectiveChatId)}`
36729
+ });
36730
+ await core3.channel.session.recordInboundSession({
36731
+ storePath,
36732
+ sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
36733
+ ctx: ctxPayload,
36734
+ ...!isGroup ? {
36735
+ updateLastRoute: {
36736
+ sessionKey: route.mainSessionKey,
36737
+ channel: CHANNEL_ID,
36738
+ to: `inline:${String(effectiveChatId)}`,
36739
+ accountId: route.accountId
36616
36740
  }
36617
- const inboundHistory = isGroup && groupHistoryKey ? mergeInboundHistoryEntries({
36618
- historyContextEntries: effectiveHistoryContext.inboundHistory,
36619
- pendingEntries: groupPendingHistories.get(groupHistoryKey) ?? [],
36620
- limit: historyLimit
36621
- }) : [];
36622
- const bodyForAgent = buildInlineBodyForAgent({
36623
- rawBody,
36624
- currentAttachmentText,
36625
- currentEntityText
36626
- });
36627
- const effectiveSurface = shouldUseTelegramSurfaceForModelCommands(normalizedCommandBody) ? "telegram" : CHANNEL_ID;
36628
- const systemPrompt = resolveInlineSystemPrompt({
36629
- account,
36630
- ...isGroup ? { groupId: String(effectiveChatId) } : {}
36631
- });
36632
- const ctxPayload = core3.channel.reply.finalizeInboundContext({
36633
- Body: body,
36634
- BodyForAgent: bodyForAgent,
36635
- ...isGroup ? { InboundHistory: inboundHistory } : {},
36636
- RawBody: rawBody,
36637
- CommandBody: normalizedCommandBody,
36638
- From: isGroup ? `inline:chat:${String(effectiveChatId)}` : `inline:${senderId}`,
36639
- To: `inline:${String(effectiveChatId)}`,
36640
- SessionKey: route.sessionKey,
36641
- ...replyThreadContext ? { ParentSessionKey: route.sessionKey } : {},
36642
- AccountId: route.accountId,
36643
- ChatType: isGroup ? "group" : "direct",
36644
- ConversationLabel: fromLabel,
36645
- ...isGroup ? { GroupSubject: effectiveGroupTitle ?? String(effectiveChatId) } : {},
36646
- SenderId: senderId,
36647
- ...senderName ? { SenderName: senderName } : {},
36648
- ...senderUsername ? { SenderUsername: senderUsername } : {},
36649
- Provider: CHANNEL_ID,
36650
- Surface: effectiveSurface,
36651
- MessageSid: buildInlineInboundMessageSid({
36652
- msgId: msg.id,
36653
- ...callbackActionEvent ? { callbackActionEvent } : {}
36654
- }),
36655
- ...replyThreadContext ? { MessageThreadId: String(replyThreadContext.childChatId) } : {},
36656
- ...replyThreadContext?.threadLabel ? { ThreadLabel: replyThreadContext.threadLabel } : {},
36657
- ...msg.replyToMsgId != null ? { ReplyToId: String(msg.replyToMsgId) } : {},
36658
- ...effectiveHistoryContext.replyToSenderId != null ? { ReplyToSenderId: effectiveHistoryContext.replyToSenderId } : {},
36659
- ...msg.replyToMsgId != null ? { ReplyToWasBot: effectiveHistoryContext.repliedToBot } : {},
36660
- ...callbackActionEvent ? {
36661
- MessageActionInteractionId: String(callbackActionEvent.interactionId),
36662
- MessageActionId: callbackActionEvent.actionId,
36663
- MessageActionDataBase64: callbackDataToBase64(callbackActionEvent.data),
36664
- ...callbackDataToUtf8(callbackActionEvent.data) ? { MessageActionDataUtf8: callbackDataToUtf8(callbackActionEvent.data) } : {}
36665
- } : {},
36666
- ...buildInlineInboundMediaPayload(inboundMedia),
36667
- Timestamp: timestamp || Date.now(),
36668
- WasMentioned: mentionGate.effectiveWasMentioned,
36669
- CommandAuthorized: commandAuthorized,
36670
- GroupSystemPrompt: systemPrompt,
36671
- OriginatingChannel: CHANNEL_ID,
36672
- OriginatingTo: `inline:${String(effectiveChatId)}`
36673
- });
36674
- await core3.channel.session.recordInboundSession({
36675
- storePath,
36676
- sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
36677
- ctx: ctxPayload,
36678
- ...!isGroup ? {
36679
- updateLastRoute: {
36680
- sessionKey: route.mainSessionKey,
36681
- channel: CHANNEL_ID,
36682
- to: `inline:${String(effectiveChatId)}`,
36683
- accountId: route.accountId
36741
+ } : {},
36742
+ onRecordError: (err) => runtime2.error?.(`inline: failed updating session meta: ${String(err)}`)
36743
+ });
36744
+ const replyPipeline = await createChannelReplyPipelineCompat({
36745
+ cfg,
36746
+ agentId: route.agentId,
36747
+ channel: CHANNEL_ID,
36748
+ accountId: account.accountId,
36749
+ typing: {
36750
+ start: () => client.sendTyping({ chatId, typing: true }),
36751
+ stop: () => client.sendTyping({ chatId, typing: false }),
36752
+ onStartError: (err) => runtime2.error?.(`inline typing start failed: ${String(err)}`),
36753
+ onStopError: (err) => runtime2.error?.(`inline typing stop failed: ${String(err)}`)
36754
+ }
36755
+ });
36756
+ const onModelSelected = replyPipeline.onModelSelected;
36757
+ const typingCallbacks = replyPipeline.typingCallbacks;
36758
+ const prefixOptions = {
36759
+ ...replyPipeline.responsePrefix !== undefined ? { responsePrefix: replyPipeline.responsePrefix } : {},
36760
+ ...replyPipeline.enableSlackInteractiveReplies !== undefined ? { enableSlackInteractiveReplies: replyPipeline.enableSlackInteractiveReplies } : {},
36761
+ ...replyPipeline.responsePrefixContextProvider ? {
36762
+ responsePrefixContextProvider: replyPipeline.responsePrefixContextProvider
36763
+ } : {}
36764
+ };
36765
+ const callbackTargetMessage = shouldEditCallbackTargetInPlace && callbackActionEvent ? await findChatMessageById({
36766
+ client,
36767
+ chatId,
36768
+ messageId: callbackActionEvent.targetMessageId,
36769
+ limit: REPLY_TARGET_LOOKUP_LIMIT,
36770
+ meId,
36771
+ botMessageIdsByChat
36772
+ }).catch(() => null) : null;
36773
+ const streamViaEditMessage = account.config.streamViaEditMessage === true && !shouldEditCallbackTargetInPlace;
36774
+ const defaultReplyToMsgId = isGroup && msg.replyToMsgId != null ? msg.id : undefined;
36775
+ const disableBlockStreaming = streamViaEditMessage ? true : typeof account.config.blockStreaming === "boolean" ? !account.config.blockStreaming : undefined;
36776
+ const editStreamState = {
36777
+ messageId: shouldEditCallbackTargetInPlace ? callbackActionEvent?.targetMessageId ?? null : null,
36778
+ accumulatedText: callbackTargetMessage?.message ?? "",
36779
+ lastPartialText: "",
36780
+ finalTextAccumulator: "",
36781
+ failed: false,
36782
+ opChain: Promise.resolve()
36783
+ };
36784
+ let finalDeliveredForCurrentAssistantMessage = false;
36785
+ const resetEditStreamForAssistantMessage = async () => {
36786
+ await editStreamState.opChain;
36787
+ const hasActiveState = editStreamState.messageId != null || editStreamState.accumulatedText.length > 0 || editStreamState.lastPartialText.length > 0 || editStreamState.finalTextAccumulator.length > 0;
36788
+ if (!hasActiveState)
36789
+ return;
36790
+ editStreamState.messageId = null;
36791
+ editStreamState.accumulatedText = "";
36792
+ editStreamState.lastPartialText = "";
36793
+ editStreamState.finalTextAccumulator = "";
36794
+ editStreamState.failed = false;
36795
+ finalDeliveredForCurrentAssistantMessage = false;
36796
+ };
36797
+ const resetEditStreamOnBoundary = async () => {
36798
+ if (!streamViaEditMessage)
36799
+ return;
36800
+ await resetEditStreamForAssistantMessage();
36801
+ };
36802
+ const handlePartialStreamPayload = async (payload) => {
36803
+ if (editStreamState.failed)
36804
+ return;
36805
+ if ((payload.mediaUrls?.length ?? 0) > 0)
36806
+ return;
36807
+ const partialText = typeof payload.text === "string" ? payload.text : "";
36808
+ if (!partialText || partialText === editStreamState.lastPartialText)
36809
+ return;
36810
+ editStreamState.lastPartialText = partialText;
36811
+ const nextText = rewriteNumericMentionsToUsernames(extractCompleteParagraphText(partialText), senderProfilesById).trim();
36812
+ if (!nextText || nextText === editStreamState.accumulatedText)
36813
+ return;
36814
+ editStreamState.opChain = editStreamState.opChain.then(async () => {
36815
+ if (editStreamState.failed)
36816
+ return;
36817
+ if (!nextText || nextText === editStreamState.accumulatedText)
36818
+ return;
36819
+ try {
36820
+ if (editStreamState.messageId == null) {
36821
+ const sent = await client.sendMessage({
36822
+ chatId,
36823
+ text: nextText,
36824
+ ...defaultReplyToMsgId != null ? { replyToMsgId: defaultReplyToMsgId } : {},
36825
+ parseMarkdown
36826
+ });
36827
+ if (sent.messageId == null) {
36828
+ throw new Error("inline edit stream: sendMessage returned no messageId");
36829
+ }
36830
+ editStreamState.messageId = sent.messageId;
36831
+ rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
36832
+ } else {
36833
+ const result = await client.invokeRaw(Method.EDIT_MESSAGE, {
36834
+ oneofKind: "editMessage",
36835
+ editMessage: {
36836
+ messageId: editStreamState.messageId,
36837
+ peerId: buildChatPeer2(chatId),
36838
+ text: nextText,
36839
+ parseMarkdown
36840
+ }
36841
+ });
36842
+ if (result.oneofKind !== "editMessage") {
36843
+ throw new Error(`inline edit stream: expected editMessage result, got ${String(result.oneofKind)}`);
36684
36844
  }
36685
- } : {},
36686
- onRecordError: (err) => runtime2.error?.(`inline: failed updating session meta: ${String(err)}`)
36687
- });
36688
- const replyPipeline = await createChannelReplyPipelineCompat({
36689
- cfg,
36690
- agentId: route.agentId,
36691
- channel: CHANNEL_ID,
36692
- accountId: account.accountId,
36693
- typing: {
36694
- start: () => client.sendTyping({ chatId, typing: true }),
36695
- stop: () => client.sendTyping({ chatId, typing: false }),
36696
- onStartError: (err) => runtime2.error?.(`inline typing start failed: ${String(err)}`),
36697
- onStopError: (err) => runtime2.error?.(`inline typing stop failed: ${String(err)}`)
36698
36845
  }
36699
- });
36700
- const onModelSelected = replyPipeline.onModelSelected;
36701
- const typingCallbacks = replyPipeline.typingCallbacks;
36702
- const prefixOptions = {
36703
- ...replyPipeline.responsePrefix !== undefined ? { responsePrefix: replyPipeline.responsePrefix } : {},
36704
- ...replyPipeline.enableSlackInteractiveReplies !== undefined ? { enableSlackInteractiveReplies: replyPipeline.enableSlackInteractiveReplies } : {},
36705
- ...replyPipeline.responsePrefixContextProvider ? {
36706
- responsePrefixContextProvider: replyPipeline.responsePrefixContextProvider
36707
- } : {}
36708
- };
36709
- const callbackTargetMessage = shouldEditCallbackTargetInPlace && callbackActionEvent ? await findChatMessageById({
36710
- client,
36711
- chatId,
36712
- messageId: callbackActionEvent.targetMessageId,
36713
- limit: REPLY_TARGET_LOOKUP_LIMIT,
36714
- meId,
36715
- botMessageIdsByChat
36716
- }).catch(() => null) : null;
36717
- const streamViaEditMessage = account.config.streamViaEditMessage === true && !shouldEditCallbackTargetInPlace;
36718
- const defaultReplyToMsgId = isGroup && msg.replyToMsgId != null ? msg.id : undefined;
36719
- const disableBlockStreaming = streamViaEditMessage ? true : typeof account.config.blockStreaming === "boolean" ? !account.config.blockStreaming : undefined;
36720
- const editStreamState = {
36721
- messageId: shouldEditCallbackTargetInPlace ? callbackActionEvent?.targetMessageId ?? null : null,
36722
- accumulatedText: callbackTargetMessage?.message ?? "",
36723
- lastPartialText: "",
36724
- finalTextAccumulator: "",
36725
- failed: false,
36726
- opChain: Promise.resolve()
36727
- };
36728
- let finalDeliveredForCurrentAssistantMessage = false;
36729
- const resetEditStreamForAssistantMessage = async () => {
36730
- await editStreamState.opChain;
36731
- const hasActiveState = editStreamState.messageId != null || editStreamState.accumulatedText.length > 0 || editStreamState.lastPartialText.length > 0 || editStreamState.finalTextAccumulator.length > 0;
36732
- if (!hasActiveState)
36733
- return;
36734
- editStreamState.messageId = null;
36735
- editStreamState.accumulatedText = "";
36736
- editStreamState.lastPartialText = "";
36737
- editStreamState.finalTextAccumulator = "";
36738
- editStreamState.failed = false;
36739
- finalDeliveredForCurrentAssistantMessage = false;
36740
- };
36741
- const resetEditStreamOnBoundary = async () => {
36742
- if (!streamViaEditMessage)
36743
- return;
36744
- await resetEditStreamForAssistantMessage();
36745
- };
36746
- const handlePartialStreamPayload = async (payload) => {
36747
- if (editStreamState.failed)
36748
- return;
36749
- if ((payload.mediaUrls?.length ?? 0) > 0)
36750
- return;
36751
- const partialText = typeof payload.text === "string" ? payload.text : "";
36752
- if (!partialText || partialText === editStreamState.lastPartialText)
36753
- return;
36754
- editStreamState.lastPartialText = partialText;
36755
- const nextText = rewriteNumericMentionsToUsernames(extractCompleteParagraphText(partialText), senderProfilesById).trim();
36756
- if (!nextText || nextText === editStreamState.accumulatedText)
36757
- return;
36758
- editStreamState.opChain = editStreamState.opChain.then(async () => {
36759
- if (editStreamState.failed)
36760
- return;
36761
- if (!nextText || nextText === editStreamState.accumulatedText)
36762
- return;
36763
- try {
36764
- if (editStreamState.messageId == null) {
36846
+ editStreamState.accumulatedText = nextText;
36847
+ statusSink?.({ lastOutboundAt: Date.now() });
36848
+ } catch (error48) {
36849
+ editStreamState.failed = true;
36850
+ runtime2.error?.(`inline edit stream failed: ${String(error48)}`);
36851
+ }
36852
+ });
36853
+ await editStreamState.opChain;
36854
+ };
36855
+ const replyOptions = {
36856
+ ...onModelSelected ? { onModelSelected } : {},
36857
+ blockReplyTimeoutMs: 25000,
36858
+ ...streamViaEditMessage ? {
36859
+ onAssistantMessageStart: async () => {
36860
+ await resetEditStreamOnBoundary();
36861
+ }
36862
+ } : {},
36863
+ ...streamViaEditMessage ? {
36864
+ onPartialReply: async (payload) => {
36865
+ await handlePartialStreamPayload(payload);
36866
+ }
36867
+ } : {},
36868
+ ...streamViaEditMessage ? {
36869
+ onToolStart: async () => {
36870
+ await resetEditStreamOnBoundary();
36871
+ }
36872
+ } : {},
36873
+ ...streamViaEditMessage ? {
36874
+ onCompactionStart: async () => {
36875
+ await resetEditStreamOnBoundary();
36876
+ }
36877
+ } : {},
36878
+ ...streamViaEditMessage ? {
36879
+ onCompactionEnd: async () => {
36880
+ await resetEditStreamOnBoundary();
36881
+ }
36882
+ } : {},
36883
+ ...typeof disableBlockStreaming === "boolean" ? { disableBlockStreaming } : {}
36884
+ };
36885
+ try {
36886
+ let delivered = false;
36887
+ let skippedNonSilent = false;
36888
+ let failedNonSilent = false;
36889
+ let dispatchError = null;
36890
+ try {
36891
+ await core3.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
36892
+ ctx: ctxPayload,
36893
+ cfg,
36894
+ dispatcherOptions: {
36895
+ ...prefixOptions,
36896
+ ...typingCallbacks ? { typingCallbacks } : {},
36897
+ deliver: async (payload, info) => {
36898
+ if (payload.isReasoning === true) {
36899
+ return;
36900
+ }
36901
+ const rawText = payload.text ?? "";
36902
+ const mediaList = payload.mediaUrls?.length ? payload.mediaUrls : payload.mediaUrl ? [payload.mediaUrl] : [];
36903
+ const outboundText = rewriteNumericMentionsToUsernames(rawText, senderProfilesById);
36904
+ const outboundActions = resolveInlineReplyActions(payload);
36905
+ const infoKind = typeof info?.kind === "string" ? info.kind : undefined;
36906
+ let replyToMsgId;
36907
+ if (payload.replyToId != null) {
36908
+ try {
36909
+ replyToMsgId = BigInt(payload.replyToId);
36910
+ } catch {}
36911
+ }
36912
+ if (replyToMsgId == null && isGroup && msg.replyToMsgId != null) {
36913
+ replyToMsgId = msg.id;
36914
+ }
36915
+ const rememberSent = (messageId) => {
36916
+ if (messageId != null) {
36917
+ rememberBotMessageId(botMessageIdsByChat, chatId, messageId);
36918
+ }
36919
+ };
36920
+ const sendTextFallback = async (text, includeReplyTo, includeActions) => {
36921
+ if (!text.trim())
36922
+ return;
36765
36923
  const sent = await client.sendMessage({
36766
36924
  chatId,
36767
- text: nextText,
36768
- ...defaultReplyToMsgId != null ? { replyToMsgId: defaultReplyToMsgId } : {},
36925
+ text,
36926
+ ...includeReplyTo && replyToMsgId != null ? { replyToMsgId } : {},
36927
+ ...includeActions && outboundActions !== undefined ? { actions: outboundActions } : {},
36769
36928
  parseMarkdown
36770
36929
  });
36771
- if (sent.messageId == null) {
36772
- throw new Error("inline edit stream: sendMessage returned no messageId");
36773
- }
36774
- editStreamState.messageId = sent.messageId;
36775
- rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
36776
- } else {
36930
+ rememberSent(sent.messageId);
36931
+ delivered = true;
36932
+ };
36933
+ const updateStreamedMessage = async (text, actions) => {
36934
+ await editStreamState.opChain;
36935
+ if (editStreamState.messageId == null)
36936
+ return false;
36937
+ const nextText = text.trim();
36938
+ const textForEdit = nextText || editStreamState.accumulatedText;
36939
+ if (!textForEdit && actions === undefined)
36940
+ return true;
36941
+ const shouldSkipTextUpdate = !editStreamState.failed && textForEdit === editStreamState.accumulatedText;
36942
+ if (shouldSkipTextUpdate && actions === undefined)
36943
+ return true;
36777
36944
  const result = await client.invokeRaw(Method.EDIT_MESSAGE, {
36778
36945
  oneofKind: "editMessage",
36779
36946
  editMessage: {
36780
36947
  messageId: editStreamState.messageId,
36781
36948
  peerId: buildChatPeer2(chatId),
36782
- text: nextText,
36783
- parseMarkdown
36949
+ text: textForEdit,
36950
+ parseMarkdown,
36951
+ ...actions !== undefined ? { actions } : {}
36784
36952
  }
36785
36953
  });
36786
36954
  if (result.oneofKind !== "editMessage") {
36787
36955
  throw new Error(`inline edit stream: expected editMessage result, got ${String(result.oneofKind)}`);
36788
36956
  }
36789
- }
36790
- editStreamState.accumulatedText = nextText;
36791
- statusSink?.({ lastOutboundAt: Date.now() });
36792
- } catch (error48) {
36793
- editStreamState.failed = true;
36794
- runtime2.error?.(`inline edit stream failed: ${String(error48)}`);
36795
- }
36796
- });
36797
- await editStreamState.opChain;
36798
- };
36799
- const replyOptions = {
36800
- ...onModelSelected ? { onModelSelected } : {},
36801
- blockReplyTimeoutMs: 25000,
36802
- ...streamViaEditMessage ? {
36803
- onAssistantMessageStart: async () => {
36804
- await resetEditStreamOnBoundary();
36805
- }
36806
- } : {},
36807
- ...streamViaEditMessage ? {
36808
- onPartialReply: async (payload) => {
36809
- await handlePartialStreamPayload(payload);
36810
- }
36811
- } : {},
36812
- ...streamViaEditMessage ? {
36813
- onReasoningStream: async (payload) => {
36814
- await handlePartialStreamPayload(payload);
36815
- }
36816
- } : {},
36817
- ...streamViaEditMessage ? {
36818
- onReasoningEnd: async () => {
36819
- await editStreamState.opChain;
36820
- }
36821
- } : {},
36822
- ...streamViaEditMessage ? {
36823
- onToolStart: async () => {
36824
- await resetEditStreamOnBoundary();
36825
- }
36826
- } : {},
36827
- ...streamViaEditMessage ? {
36828
- onCompactionStart: async () => {
36829
- await resetEditStreamOnBoundary();
36830
- }
36831
- } : {},
36832
- ...streamViaEditMessage ? {
36833
- onCompactionEnd: async () => {
36834
- await resetEditStreamOnBoundary();
36835
- }
36836
- } : {},
36837
- ...typeof disableBlockStreaming === "boolean" ? { disableBlockStreaming } : {}
36838
- };
36839
- try {
36840
- let delivered = false;
36841
- let skippedNonSilent = false;
36842
- let failedNonSilent = false;
36843
- let dispatchError = null;
36844
- try {
36845
- await core3.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
36846
- ctx: ctxPayload,
36847
- cfg,
36848
- dispatcherOptions: {
36849
- ...prefixOptions,
36850
- ...typingCallbacks ? { typingCallbacks } : {},
36851
- deliver: async (payload, info) => {
36852
- const rawText = payload.text ?? "";
36853
- const mediaList = payload.mediaUrls?.length ? payload.mediaUrls : payload.mediaUrl ? [payload.mediaUrl] : [];
36854
- const outboundText = rewriteNumericMentionsToUsernames(rawText, senderProfilesById);
36855
- const outboundActions = resolveInlineReplyActions(payload);
36856
- const infoKind = typeof info?.kind === "string" ? info.kind : undefined;
36857
- let replyToMsgId;
36858
- if (payload.replyToId != null) {
36859
- try {
36860
- replyToMsgId = BigInt(payload.replyToId);
36861
- } catch {}
36957
+ if (!shouldSkipTextUpdate) {
36958
+ editStreamState.accumulatedText = textForEdit;
36959
+ editStreamState.lastPartialText = textForEdit;
36960
+ }
36961
+ editStreamState.failed = false;
36962
+ return true;
36963
+ };
36964
+ if (mediaList.length === 0) {
36965
+ if (shouldEditCallbackTargetInPlace && editStreamState.messageId != null) {
36966
+ const callbackEditActions = outboundActions ?? { rows: [] };
36967
+ if (!outboundText.trim() && outboundActions === undefined) {
36968
+ return;
36862
36969
  }
36863
- if (replyToMsgId == null && isGroup && msg.replyToMsgId != null) {
36864
- replyToMsgId = msg.id;
36970
+ await updateStreamedMessage(outboundText, callbackEditActions);
36971
+ delivered = true;
36972
+ statusSink?.({ lastOutboundAt: Date.now() });
36973
+ return;
36974
+ }
36975
+ if (streamViaEditMessage && infoKind === "final" && finalDeliveredForCurrentAssistantMessage && editStreamState.messageId != null) {
36976
+ await resetEditStreamForAssistantMessage();
36977
+ }
36978
+ if (streamViaEditMessage && editStreamState.messageId != null) {
36979
+ if (outboundText.trim()) {
36980
+ editStreamState.finalTextAccumulator += outboundText;
36865
36981
  }
36866
- const rememberSent = (messageId) => {
36867
- if (messageId != null) {
36868
- rememberBotMessageId(botMessageIdsByChat, chatId, messageId);
36869
- }
36870
- };
36871
- const sendTextFallback = async (text, includeReplyTo, includeActions) => {
36872
- if (!text.trim())
36873
- return;
36874
- const sent = await client.sendMessage({
36875
- chatId,
36876
- text,
36877
- ...includeReplyTo && replyToMsgId != null ? { replyToMsgId } : {},
36878
- ...includeActions && outboundActions !== undefined ? { actions: outboundActions } : {},
36879
- parseMarkdown
36880
- });
36881
- rememberSent(sent.messageId);
36882
- delivered = true;
36883
- };
36884
- const updateStreamedMessage = async (text, actions) => {
36885
- await editStreamState.opChain;
36886
- if (editStreamState.messageId == null)
36887
- return false;
36888
- const nextText = text.trim();
36889
- const textForEdit = nextText || editStreamState.accumulatedText;
36890
- if (!textForEdit && actions === undefined)
36891
- return true;
36892
- const shouldSkipTextUpdate = !editStreamState.failed && textForEdit === editStreamState.accumulatedText;
36893
- if (shouldSkipTextUpdate && actions === undefined)
36894
- return true;
36895
- const result = await client.invokeRaw(Method.EDIT_MESSAGE, {
36896
- oneofKind: "editMessage",
36897
- editMessage: {
36898
- messageId: editStreamState.messageId,
36899
- peerId: buildChatPeer2(chatId),
36900
- text: textForEdit,
36901
- parseMarkdown,
36902
- ...actions !== undefined ? { actions } : {}
36903
- }
36904
- });
36905
- if (result.oneofKind !== "editMessage") {
36906
- throw new Error(`inline edit stream: expected editMessage result, got ${String(result.oneofKind)}`);
36907
- }
36908
- if (!shouldSkipTextUpdate) {
36909
- editStreamState.accumulatedText = textForEdit;
36910
- editStreamState.lastPartialText = textForEdit;
36911
- }
36912
- editStreamState.failed = false;
36913
- return true;
36914
- };
36915
- if (mediaList.length === 0) {
36916
- if (shouldEditCallbackTargetInPlace && editStreamState.messageId != null) {
36917
- const callbackEditActions = outboundActions ?? { rows: [] };
36918
- if (!outboundText.trim() && outboundActions === undefined) {
36919
- return;
36920
- }
36921
- await updateStreamedMessage(outboundText, callbackEditActions);
36922
- delivered = true;
36923
- statusSink?.({ lastOutboundAt: Date.now() });
36924
- return;
36925
- }
36926
- if (streamViaEditMessage && infoKind === "final" && finalDeliveredForCurrentAssistantMessage && editStreamState.messageId != null) {
36927
- await resetEditStreamForAssistantMessage();
36928
- }
36929
- if (streamViaEditMessage && editStreamState.messageId != null) {
36930
- if (outboundText.trim()) {
36931
- editStreamState.finalTextAccumulator += outboundText;
36932
- }
36933
- if (!editStreamState.finalTextAccumulator.trim() && outboundActions === undefined) {
36934
- return;
36935
- }
36936
- await updateStreamedMessage(editStreamState.finalTextAccumulator, outboundActions);
36937
- delivered = true;
36938
- if (infoKind === "final") {
36939
- finalDeliveredForCurrentAssistantMessage = true;
36940
- }
36941
- statusSink?.({ lastOutboundAt: Date.now() });
36942
- return;
36943
- }
36944
- if (!outboundText.trim())
36945
- return;
36946
- await sendTextFallback(outboundText, true, true);
36947
- statusSink?.({ lastOutboundAt: Date.now() });
36982
+ if (!editStreamState.finalTextAccumulator.trim() && outboundActions === undefined) {
36948
36983
  return;
36949
36984
  }
36950
- if (streamViaEditMessage && editStreamState.messageId != null && outboundText.trim()) {
36951
- await updateStreamedMessage(outboundText, outboundActions);
36985
+ await updateStreamedMessage(editStreamState.finalTextAccumulator, outboundActions);
36986
+ delivered = true;
36987
+ if (infoKind === "final") {
36988
+ finalDeliveredForCurrentAssistantMessage = true;
36952
36989
  }
36953
- for (let index = 0;index < mediaList.length; index++) {
36954
- const mediaUrl = mediaList[index];
36955
- if (!mediaUrl?.trim())
36956
- continue;
36957
- const isFirst = index === 0;
36958
- const shouldAttachActionsToMedia = isFirst && (!(streamViaEditMessage && editStreamState.messageId != null) || !outboundText.trim());
36959
- const caption = isFirst && !(streamViaEditMessage && editStreamState.messageId != null) ? outboundText : "";
36960
- try {
36961
- const media = await uploadInlineMediaFromUrl({
36962
- client,
36963
- cfg,
36964
- accountId: account.accountId,
36965
- mediaUrl
36966
- });
36967
- const sent = await client.sendMessage({
36968
- chatId,
36969
- ...caption ? { text: caption } : {},
36970
- media,
36971
- ...isFirst && replyToMsgId != null ? { replyToMsgId } : {},
36972
- ...shouldAttachActionsToMedia && outboundActions !== undefined ? { actions: outboundActions } : {},
36973
- ...caption ? { parseMarkdown } : {}
36974
- });
36975
- rememberSent(sent.messageId);
36976
- delivered = true;
36977
- } catch (error48) {
36978
- runtime2.error?.(`inline media upload failed; falling back to url text (${String(error48)})`);
36979
- const fallbackText = caption ? `${caption}
36990
+ statusSink?.({ lastOutboundAt: Date.now() });
36991
+ return;
36992
+ }
36993
+ if (!outboundText.trim())
36994
+ return;
36995
+ await sendTextFallback(outboundText, true, true);
36996
+ statusSink?.({ lastOutboundAt: Date.now() });
36997
+ return;
36998
+ }
36999
+ if (streamViaEditMessage && editStreamState.messageId != null && outboundText.trim()) {
37000
+ await updateStreamedMessage(outboundText, outboundActions);
37001
+ }
37002
+ for (let index = 0;index < mediaList.length; index++) {
37003
+ const mediaUrl = mediaList[index];
37004
+ if (!mediaUrl?.trim())
37005
+ continue;
37006
+ const isFirst = index === 0;
37007
+ const shouldAttachActionsToMedia = isFirst && (!(streamViaEditMessage && editStreamState.messageId != null) || !outboundText.trim());
37008
+ const caption = isFirst && !(streamViaEditMessage && editStreamState.messageId != null) ? outboundText : "";
37009
+ try {
37010
+ const media = await uploadInlineMediaFromUrl({
37011
+ client,
37012
+ cfg,
37013
+ accountId: account.accountId,
37014
+ mediaUrl
37015
+ });
37016
+ const sent = await client.sendMessage({
37017
+ chatId,
37018
+ ...caption ? { text: caption } : {},
37019
+ media,
37020
+ ...isFirst && replyToMsgId != null ? { replyToMsgId } : {},
37021
+ ...shouldAttachActionsToMedia && outboundActions !== undefined ? { actions: outboundActions } : {},
37022
+ ...caption ? { parseMarkdown } : {}
37023
+ });
37024
+ rememberSent(sent.messageId);
37025
+ delivered = true;
37026
+ } catch (error48) {
37027
+ runtime2.error?.(`inline media upload failed; falling back to url text (${String(error48)})`);
37028
+ const fallbackText = caption ? `${caption}
36980
37029
 
36981
37030
  Attachment: ${mediaUrl}` : `Attachment: ${mediaUrl}`;
36982
- await sendTextFallback(fallbackText, isFirst, isFirst);
36983
- }
36984
- }
36985
- statusSink?.({ lastOutboundAt: Date.now() });
36986
- },
36987
- onSkip: (_payload, info) => {
36988
- if (info?.reason !== "silent") {
36989
- skippedNonSilent = true;
36990
- }
36991
- },
36992
- onError: (err, info) => {
36993
- failedNonSilent = true;
36994
- runtime2.error?.(`inline ${info?.kind ?? "final"} reply failed: ${String(err)}`);
37031
+ await sendTextFallback(fallbackText, isFirst, isFirst);
36995
37032
  }
36996
- },
36997
- replyOptions
36998
- });
36999
- } catch (error48) {
37000
- dispatchError = error48;
37001
- runtime2.error?.(`inline dispatch failed: ${String(error48)}`);
37002
- }
37003
- if (!delivered && streamViaEditMessage && editStreamState.messageId != null) {
37004
- delivered = true;
37005
- }
37006
- if (!delivered && (dispatchError != null || skippedNonSilent || failedNonSilent)) {
37007
- const fallbackText = dispatchError != null ? "Something went wrong while processing your request. Please try again." : EMPTY_RESPONSE_FALLBACK;
37008
- const sent = await client.sendMessage({
37009
- chatId,
37010
- text: fallbackText,
37011
- ...defaultReplyToMsgId != null ? { replyToMsgId: defaultReplyToMsgId } : {},
37012
- parseMarkdown
37013
- });
37014
- if (sent.messageId != null) {
37015
- rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
37033
+ }
37034
+ statusSink?.({ lastOutboundAt: Date.now() });
37035
+ },
37036
+ onSkip: (_payload, info) => {
37037
+ if (info?.reason !== "silent") {
37038
+ skippedNonSilent = true;
37039
+ }
37040
+ },
37041
+ onError: (err, info) => {
37042
+ failedNonSilent = true;
37043
+ runtime2.error?.(`inline ${info?.kind ?? "final"} reply failed: ${String(err)}`);
37016
37044
  }
37017
- statusSink?.({ lastOutboundAt: Date.now() });
37018
- }
37019
- } finally {
37020
- if (callbackActionEvent && !callbackActionAnswered) {
37021
- try {
37022
- await answerCallbackIfNeeded();
37023
- } catch (error48) {
37024
- runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
37045
+ },
37046
+ replyOptions
37047
+ });
37048
+ } catch (error48) {
37049
+ dispatchError = error48;
37050
+ runtime2.error?.(`inline dispatch failed: ${String(error48)}`);
37051
+ }
37052
+ if (!delivered && streamViaEditMessage && editStreamState.messageId != null) {
37053
+ delivered = true;
37054
+ }
37055
+ if (!delivered && (dispatchError != null || skippedNonSilent || failedNonSilent)) {
37056
+ const fallbackText = dispatchError != null ? "Something went wrong while processing your request. Please try again." : EMPTY_RESPONSE_FALLBACK;
37057
+ const sent = await client.sendMessage({
37058
+ chatId,
37059
+ text: fallbackText,
37060
+ ...defaultReplyToMsgId != null ? { replyToMsgId: defaultReplyToMsgId } : {},
37061
+ parseMarkdown
37062
+ });
37063
+ if (sent.messageId != null) {
37064
+ rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
37065
+ }
37066
+ statusSink?.({ lastOutboundAt: Date.now() });
37067
+ }
37068
+ } finally {
37069
+ if (callbackActionEvent && !callbackActionAnswered) {
37070
+ try {
37071
+ await answerCallbackIfNeeded();
37072
+ } catch (error48) {
37073
+ runtime2.error?.(`inline callback answer failed: ${String(error48)}`);
37074
+ }
37075
+ }
37076
+ }
37077
+ if (isGroup && groupHistoryKey) {
37078
+ clearHistoryEntriesIfEnabled({
37079
+ historyMap: groupPendingHistories,
37080
+ historyKey: groupHistoryKey,
37081
+ limit: historyLimit
37082
+ });
37083
+ }
37084
+ };
37085
+ const { debouncer: inboundDebouncer } = createChannelInboundDebouncer({
37086
+ cfg,
37087
+ channel: CHANNEL_ID,
37088
+ buildKey: (entry) => buildInlineDebounceKey({
37089
+ accountId: account.accountId,
37090
+ chatId: entry.chatId,
37091
+ senderId: entry.msg.fromId
37092
+ }),
37093
+ shouldDebounce: (entry) => {
37094
+ const content = summarizeInlineMessageContent(entry.msg);
37095
+ return shouldDebounceTextInbound({
37096
+ text: buildInlineInboundBodyText(content),
37097
+ cfg,
37098
+ hasMedia: Boolean(content.media || content.attachments.length > 0),
37099
+ ...botUsername ? { commandOptions: { botUsername } } : {}
37100
+ });
37101
+ },
37102
+ onFlush: async (entries) => {
37103
+ const last = entries.at(-1);
37104
+ if (!last)
37105
+ return;
37106
+ if (entries.length === 1) {
37107
+ await handleInboundNow({
37108
+ chatId: last.chatId,
37109
+ msg: last.msg
37110
+ });
37111
+ return;
37112
+ }
37113
+ const combinedText = entries.map((entry) => buildInlineInboundBodyText(summarizeInlineMessageContent(entry.msg))).filter(Boolean).join(`
37114
+ `);
37115
+ if (!combinedText.trim()) {
37116
+ return;
37117
+ }
37118
+ await handleInboundNow({
37119
+ chatId: last.chatId,
37120
+ msg: buildSyntheticInlineTextMessage({
37121
+ base: last.msg,
37122
+ text: combinedText,
37123
+ mentioned: entries.some((entry) => entry.msg.mentioned === true)
37124
+ }),
37125
+ rawBodyOverride: combinedText
37126
+ });
37127
+ },
37128
+ onError: (err, items) => {
37129
+ runtime2.error?.(`inline debounce flush failed: ${String(err)}`);
37130
+ const chatId = items[0]?.chatId;
37131
+ if (chatId == null)
37132
+ return;
37133
+ client.sendMessage({
37134
+ chatId,
37135
+ text: "Something went wrong while processing your message. Please try again."
37136
+ }).then(() => {
37137
+ statusSink?.({ lastOutboundAt: Date.now() });
37138
+ }).catch((sendErr) => {
37139
+ runtime2.error?.(`inline debounce fallback send failed: ${String(sendErr)}`);
37140
+ });
37141
+ }
37142
+ });
37143
+ const loop = (async () => {
37144
+ try {
37145
+ for await (const event of client.events()) {
37146
+ if (abortSignal.aborted)
37147
+ break;
37148
+ const rawEvent = event;
37149
+ if (event.kind === "message.new") {
37150
+ const msg = {
37151
+ ...event.message,
37152
+ chatId: event.chatId
37153
+ };
37154
+ if (msg.out || msg.fromId === meId)
37155
+ continue;
37156
+ await inboundDebouncer.enqueue({
37157
+ chatId: event.chatId,
37158
+ msg
37159
+ });
37160
+ continue;
37161
+ }
37162
+ if (event.kind === "reaction.add") {
37163
+ if (event.reaction.userId === meId)
37164
+ continue;
37165
+ const onBotMessage = await isReactionTargetBotMessage({
37166
+ client,
37167
+ chatId: event.chatId,
37168
+ messageId: event.reaction.messageId,
37169
+ meId,
37170
+ botMessageIdsByChat
37171
+ }).catch((err) => {
37172
+ statusSink?.({ lastError: `getChatHistory (reaction target) failed: ${String(err)}` });
37173
+ return false;
37174
+ });
37175
+ if (!onBotMessage)
37176
+ continue;
37177
+ await handleInboundNow({
37178
+ chatId: event.chatId,
37179
+ msg: {
37180
+ id: event.reaction.messageId,
37181
+ chatId: event.chatId,
37182
+ date: event.date,
37183
+ fromId: event.reaction.userId,
37184
+ message: "",
37185
+ out: false,
37186
+ mentioned: false,
37187
+ replyToMsgId: event.reaction.messageId
37188
+ },
37189
+ reactionEvent: {
37190
+ action: "added",
37191
+ emoji: event.reaction.emoji,
37192
+ targetMessageId: event.reaction.messageId
37025
37193
  }
37026
- }
37194
+ });
37195
+ continue;
37027
37196
  }
37028
- if (isGroup && groupHistoryKey) {
37029
- clearHistoryEntriesIfEnabled({
37030
- historyMap: groupPendingHistories,
37031
- historyKey: groupHistoryKey,
37032
- limit: historyLimit
37197
+ if (event.kind === "reaction.delete") {
37198
+ if (event.userId === meId)
37199
+ continue;
37200
+ const onBotMessage = await isReactionTargetBotMessage({
37201
+ client,
37202
+ chatId: event.chatId,
37203
+ messageId: event.messageId,
37204
+ meId,
37205
+ botMessageIdsByChat
37206
+ }).catch((err) => {
37207
+ statusSink?.({ lastError: `getChatHistory (reaction target) failed: ${String(err)}` });
37208
+ return false;
37209
+ });
37210
+ if (!onBotMessage)
37211
+ continue;
37212
+ await handleInboundNow({
37213
+ chatId: event.chatId,
37214
+ msg: {
37215
+ id: event.messageId,
37216
+ chatId: event.chatId,
37217
+ date: event.date,
37218
+ fromId: event.userId,
37219
+ message: "",
37220
+ out: false,
37221
+ mentioned: false,
37222
+ replyToMsgId: event.messageId
37223
+ },
37224
+ reactionEvent: {
37225
+ action: "removed",
37226
+ emoji: event.emoji,
37227
+ targetMessageId: event.messageId
37228
+ }
37229
+ });
37230
+ continue;
37231
+ }
37232
+ if (rawEvent["kind"] === "message.action.invoke") {
37233
+ const actorUserId = rawEvent["actorUserId"];
37234
+ const interactionId = rawEvent["interactionId"];
37235
+ const actionId = rawEvent["actionId"];
37236
+ const targetMessageId = rawEvent["messageId"];
37237
+ const data = rawEvent["data"];
37238
+ const eventChatId = rawEvent["chatId"];
37239
+ const eventDate = rawEvent["date"];
37240
+ if (!actorUserId || !interactionId || !actionId || !targetMessageId || !eventChatId || !eventDate || !data) {
37241
+ continue;
37242
+ }
37243
+ if (actorUserId === meId)
37244
+ continue;
37245
+ await handleInboundNow({
37246
+ chatId: eventChatId,
37247
+ msg: {
37248
+ id: targetMessageId,
37249
+ chatId: eventChatId,
37250
+ date: eventDate,
37251
+ fromId: actorUserId,
37252
+ message: "",
37253
+ out: false,
37254
+ mentioned: false,
37255
+ replyToMsgId: targetMessageId
37256
+ },
37257
+ callbackActionEvent: {
37258
+ interactionId,
37259
+ actionId,
37260
+ targetMessageId,
37261
+ data
37262
+ }
37033
37263
  });
37264
+ continue;
37034
37265
  }
37035
37266
  }
37036
37267
  } catch (err) {
@@ -38921,6 +39152,9 @@ function readInlineProbeSummary(value) {
38921
39152
  function looksLikeAuthError(text) {
38922
39153
  return /(401|403|unauth|forbidden|invalid token|token invalid|unauthorized)/i.test(text);
38923
39154
  }
39155
+ function looksLikeTransientConnectionNotice(text) {
39156
+ return text.startsWith("WebSocket reconnect scheduled ") || text.startsWith("WebSocket closed ") || text.startsWith("WebSocket error: ") || text.startsWith("Protocol reconnect scheduled ") || text.startsWith("Ping timeout, reconnecting ") || text.startsWith("Failed to send ping") || text.startsWith("Failed to send RPC request; waiting for reconnect");
39157
+ }
38924
39158
  function readInlineDiagnosticsSummary(value) {
38925
39159
  if (!isRecord5(value)) {
38926
39160
  return {};
@@ -38989,7 +39223,7 @@ function collectInlineStatusIssues(accounts) {
38989
39223
  });
38990
39224
  }
38991
39225
  const lastError = asString(entry.lastError);
38992
- if (lastError) {
39226
+ if (lastError && !looksLikeTransientConnectionNotice(lastError)) {
38993
39227
  issues.push({
38994
39228
  channel: "inline",
38995
39229
  accountId,
@@ -41217,5 +41451,5 @@ export {
41217
41451
  src_default as default
41218
41452
  };
41219
41453
 
41220
- //# debugId=3B7100874DF4D61664756E2164756E21
41454
+ //# debugId=AA2B11EC366875DE64756E2164756E21
41221
41455
  //# sourceMappingURL=index.js.map