@inline-openclaw/inline 0.0.37 → 0.0.39

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.
Files changed (43) hide show
  1. package/README.md +20 -3
  2. package/dist/account-inspect-api.js +34 -7
  3. package/dist/account-inspect-api.js.map +4 -4
  4. package/dist/approval-handler.runtime.js +1032 -92
  5. package/dist/approval-handler.runtime.js.map +14 -14
  6. package/dist/channel-plugin-api.js +1854 -332
  7. package/dist/channel-plugin-api.js.map +19 -18
  8. package/dist/index.d.ts +1 -1
  9. package/dist/inline/accounts.d.ts.map +1 -1
  10. package/dist/inline/actions.d.ts +1 -1
  11. package/dist/inline/actions.d.ts.map +1 -1
  12. package/dist/inline/approval-native.d.ts.map +1 -1
  13. package/dist/inline/bot-commands-sync.d.ts +4 -0
  14. package/dist/inline/bot-commands-sync.d.ts.map +1 -1
  15. package/dist/inline/channel.d.ts.map +1 -1
  16. package/dist/inline/config-schema.d.ts +125 -0
  17. package/dist/inline/config-schema.d.ts.map +1 -1
  18. package/dist/inline/exec-approvals.d.ts.map +1 -1
  19. package/dist/inline/message-tools.d.ts.map +1 -1
  20. package/dist/inline/monitor.d.ts.map +1 -1
  21. package/dist/inline/parent-context-tool.d.ts +10 -0
  22. package/dist/inline/parent-context-tool.d.ts.map +1 -0
  23. package/dist/inline/policy.d.ts +30 -1
  24. package/dist/inline/policy.d.ts.map +1 -1
  25. package/dist/inline/reply-threads.d.ts +12 -0
  26. package/dist/inline/reply-threads.d.ts.map +1 -1
  27. package/dist/inline/shared.d.ts +1 -1
  28. package/dist/inline/thread-participation.d.ts +10 -0
  29. package/dist/inline/thread-participation.d.ts.map +1 -0
  30. package/dist/inline/tool-targets.d.ts +36 -0
  31. package/dist/inline/tool-targets.d.ts.map +1 -0
  32. package/dist/runtime-register-api.d.ts.map +1 -1
  33. package/dist/runtime-register-api.js +1807 -153
  34. package/dist/runtime-register-api.js.map +20 -16
  35. package/dist/runtime-setter-api.js +11 -15
  36. package/dist/runtime-setter-api.js.map +3 -3
  37. package/dist/runtime.d.ts +2 -2
  38. package/dist/runtime.d.ts.map +1 -1
  39. package/dist/setup-entry.d.ts +1 -1
  40. package/dist/setup-plugin-api.js +34 -7
  41. package/dist/setup-plugin-api.js.map +4 -4
  42. package/openclaw.plugin.json +723 -56
  43. package/package.json +6 -6
@@ -2695,7 +2695,7 @@ var require_commonjs = __commonJS((exports) => {
2695
2695
  } });
2696
2696
  });
2697
2697
 
2698
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/constants.js
2698
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/constants.js
2699
2699
  var require_constants = __commonJS((exports, module) => {
2700
2700
  var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
2701
2701
  var hasBlob = typeof Blob !== "undefined";
@@ -2715,7 +2715,7 @@ var require_constants = __commonJS((exports, module) => {
2715
2715
  };
2716
2716
  });
2717
2717
 
2718
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/buffer-util.js
2718
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/buffer-util.js
2719
2719
  var require_buffer_util = __commonJS((exports, module) => {
2720
2720
  var { EMPTY_BUFFER } = require_constants();
2721
2721
  var FastBuffer = Buffer[Symbol.species];
@@ -2793,7 +2793,7 @@ var require_buffer_util = __commonJS((exports, module) => {
2793
2793
  }
2794
2794
  });
2795
2795
 
2796
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/limiter.js
2796
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/limiter.js
2797
2797
  var require_limiter = __commonJS((exports, module) => {
2798
2798
  var kDone = Symbol("kDone");
2799
2799
  var kRun = Symbol("kRun");
@@ -2825,7 +2825,7 @@ var require_limiter = __commonJS((exports, module) => {
2825
2825
  module.exports = Limiter;
2826
2826
  });
2827
2827
 
2828
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/permessage-deflate.js
2828
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js
2829
2829
  var require_permessage_deflate = __commonJS((exports, module) => {
2830
2830
  var zlib = __require("zlib");
2831
2831
  var bufferUtil = require_buffer_util();
@@ -3089,7 +3089,7 @@ var require_permessage_deflate = __commonJS((exports, module) => {
3089
3089
  }
3090
3090
  });
3091
3091
 
3092
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/validation.js
3092
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/validation.js
3093
3093
  var require_validation = __commonJS((exports, module) => {
3094
3094
  var { isUtf8 } = __require("buffer");
3095
3095
  var { hasBlob } = require_constants();
@@ -3276,7 +3276,7 @@ var require_validation = __commonJS((exports, module) => {
3276
3276
  }
3277
3277
  });
3278
3278
 
3279
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/receiver.js
3279
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/receiver.js
3280
3280
  var require_receiver = __commonJS((exports, module) => {
3281
3281
  var { Writable } = __require("stream");
3282
3282
  var PerMessageDeflate = require_permessage_deflate();
@@ -3304,6 +3304,8 @@ var require_receiver = __commonJS((exports, module) => {
3304
3304
  this._binaryType = options.binaryType || BINARY_TYPES[0];
3305
3305
  this._extensions = options.extensions || {};
3306
3306
  this._isServer = !!options.isServer;
3307
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
3308
+ this._maxFragments = options.maxFragments | 0;
3307
3309
  this._maxPayload = options.maxPayload | 0;
3308
3310
  this._skipUTF8Validation = !!options.skipUTF8Validation;
3309
3311
  this[kWebSocket] = undefined;
@@ -3326,6 +3328,10 @@ var require_receiver = __commonJS((exports, module) => {
3326
3328
  _write(chunk, encoding, cb) {
3327
3329
  if (this._opcode === 8 && this._state == GET_INFO)
3328
3330
  return cb();
3331
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
3332
+ cb(this.createError(RangeError, "Too many buffered chunks", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
3333
+ return;
3334
+ }
3329
3335
  this._bufferedBytes += chunk.length;
3330
3336
  this._buffers.push(chunk);
3331
3337
  this.startLoop(cb);
@@ -3529,6 +3535,11 @@ var require_receiver = __commonJS((exports, module) => {
3529
3535
  return;
3530
3536
  }
3531
3537
  if (data.length) {
3538
+ if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
3539
+ const error = this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS");
3540
+ cb(error);
3541
+ return;
3542
+ }
3532
3543
  this._messageLength = this._totalPayloadLength;
3533
3544
  this._fragments.push(data);
3534
3545
  }
@@ -3546,6 +3557,11 @@ var require_receiver = __commonJS((exports, module) => {
3546
3557
  cb(error);
3547
3558
  return;
3548
3559
  }
3560
+ if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
3561
+ const error = this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS");
3562
+ cb(error);
3563
+ return;
3564
+ }
3549
3565
  this._fragments.push(buf);
3550
3566
  }
3551
3567
  this.dataMessage(cb);
@@ -3657,7 +3673,7 @@ var require_receiver = __commonJS((exports, module) => {
3657
3673
  module.exports = Receiver;
3658
3674
  });
3659
3675
 
3660
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/sender.js
3676
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/sender.js
3661
3677
  var require_sender = __commonJS((exports, module) => {
3662
3678
  var { Duplex } = __require("stream");
3663
3679
  var { randomFillSync } = __require("crypto");
@@ -4016,7 +4032,7 @@ var require_sender = __commonJS((exports, module) => {
4016
4032
  }
4017
4033
  });
4018
4034
 
4019
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/event-target.js
4035
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/event-target.js
4020
4036
  var require_event_target = __commonJS((exports, module) => {
4021
4037
  var { kForOnEventAttribute, kListener } = require_constants();
4022
4038
  var kCode = Symbol("kCode");
@@ -4167,7 +4183,7 @@ var require_event_target = __commonJS((exports, module) => {
4167
4183
  }
4168
4184
  });
4169
4185
 
4170
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/extension.js
4186
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/extension.js
4171
4187
  var require_extension = __commonJS((exports, module) => {
4172
4188
  var { tokenChars } = require_validation();
4173
4189
  function push(dest, name, elem) {
@@ -4332,7 +4348,7 @@ var require_extension = __commonJS((exports, module) => {
4332
4348
  module.exports = { format, parse };
4333
4349
  });
4334
4350
 
4335
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/websocket.js
4351
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/websocket.js
4336
4352
  var require_websocket = __commonJS((exports, module) => {
4337
4353
  var EventEmitter = __require("events");
4338
4354
  var https = __require("https");
@@ -4453,6 +4469,8 @@ var require_websocket = __commonJS((exports, module) => {
4453
4469
  binaryType: this.binaryType,
4454
4470
  extensions: this._extensions,
4455
4471
  isServer: this._isServer,
4472
+ maxBufferedChunks: options.maxBufferedChunks,
4473
+ maxFragments: options.maxFragments,
4456
4474
  maxPayload: options.maxPayload,
4457
4475
  skipUTF8Validation: options.skipUTF8Validation
4458
4476
  });
@@ -4695,6 +4713,8 @@ var require_websocket = __commonJS((exports, module) => {
4695
4713
  autoPong: true,
4696
4714
  closeTimeout: CLOSE_TIMEOUT,
4697
4715
  protocolVersion: protocolVersions[1],
4716
+ maxBufferedChunks: 1024 * 1024,
4717
+ maxFragments: 128 * 1024,
4698
4718
  maxPayload: 100 * 1024 * 1024,
4699
4719
  skipUTF8Validation: false,
4700
4720
  perMessageDeflate: true,
@@ -4933,6 +4953,8 @@ var require_websocket = __commonJS((exports, module) => {
4933
4953
  websocket.setSocket(socket, head, {
4934
4954
  allowSynchronousEvents: opts.allowSynchronousEvents,
4935
4955
  generateMask: opts.generateMask,
4956
+ maxBufferedChunks: opts.maxBufferedChunks,
4957
+ maxFragments: opts.maxFragments,
4936
4958
  maxPayload: opts.maxPayload,
4937
4959
  skipUTF8Validation: opts.skipUTF8Validation
4938
4960
  });
@@ -5098,7 +5120,7 @@ var require_websocket = __commonJS((exports, module) => {
5098
5120
  }
5099
5121
  });
5100
5122
 
5101
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/stream.js
5123
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/stream.js
5102
5124
  var require_stream = __commonJS((exports, module) => {
5103
5125
  var WebSocket = require_websocket();
5104
5126
  var { Duplex } = __require("stream");
@@ -5201,7 +5223,7 @@ var require_stream = __commonJS((exports, module) => {
5201
5223
  module.exports = createWebSocketStream;
5202
5224
  });
5203
5225
 
5204
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/subprotocol.js
5226
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/subprotocol.js
5205
5227
  var require_subprotocol = __commonJS((exports, module) => {
5206
5228
  var { tokenChars } = require_validation();
5207
5229
  function parse(header) {
@@ -5246,7 +5268,7 @@ var require_subprotocol = __commonJS((exports, module) => {
5246
5268
  module.exports = { parse };
5247
5269
  });
5248
5270
 
5249
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/lib/websocket-server.js
5271
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/lib/websocket-server.js
5250
5272
  var require_websocket_server = __commonJS((exports, module) => {
5251
5273
  var EventEmitter = __require("events");
5252
5274
  var http = __require("http");
@@ -5268,6 +5290,8 @@ var require_websocket_server = __commonJS((exports, module) => {
5268
5290
  options = {
5269
5291
  allowSynchronousEvents: true,
5270
5292
  autoPong: true,
5293
+ maxBufferedChunks: 1024 * 1024,
5294
+ maxFragments: 128 * 1024,
5271
5295
  maxPayload: 100 * 1024 * 1024,
5272
5296
  skipUTF8Validation: false,
5273
5297
  perMessageDeflate: false,
@@ -5494,6 +5518,8 @@ var require_websocket_server = __commonJS((exports, module) => {
5494
5518
  socket.removeListener("error", socketOnError);
5495
5519
  ws.setSocket(socket, head, {
5496
5520
  allowSynchronousEvents: this.options.allowSynchronousEvents,
5521
+ maxBufferedChunks: this.options.maxBufferedChunks,
5522
+ maxFragments: this.options.maxFragments,
5497
5523
  maxPayload: this.options.maxPayload,
5498
5524
  skipUTF8Validation: this.options.skipUTF8Validation
5499
5525
  });
@@ -5563,7 +5589,7 @@ function hasInlineConfiguredState(params) {
5563
5589
 
5564
5590
  // src/inline/channel.ts
5565
5591
  import { unlink } from "node:fs/promises";
5566
- import path3 from "node:path";
5592
+ import path4 from "node:path";
5567
5593
  import {
5568
5594
  buildChannelOutboundSessionRoute,
5569
5595
  buildThreadAwareOutboundSessionRoute
@@ -5611,6 +5637,15 @@ var Member_Role;
5611
5637
  Member_Role2[Member_Role2["ADMIN"] = 1] = "ADMIN";
5612
5638
  Member_Role2[Member_Role2["MEMBER"] = 2] = "MEMBER";
5613
5639
  })(Member_Role || (Member_Role = {}));
5640
+ var UrlPreview_MediaType;
5641
+ (function(UrlPreview_MediaType2) {
5642
+ UrlPreview_MediaType2[UrlPreview_MediaType2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
5643
+ UrlPreview_MediaType2[UrlPreview_MediaType2["ARTICLE"] = 1] = "ARTICLE";
5644
+ UrlPreview_MediaType2[UrlPreview_MediaType2["IMAGE"] = 2] = "IMAGE";
5645
+ UrlPreview_MediaType2[UrlPreview_MediaType2["VIDEO"] = 3] = "VIDEO";
5646
+ UrlPreview_MediaType2[UrlPreview_MediaType2["DOCUMENT"] = 4] = "DOCUMENT";
5647
+ UrlPreview_MediaType2[UrlPreview_MediaType2["EMBED"] = 5] = "EMBED";
5648
+ })(UrlPreview_MediaType || (UrlPreview_MediaType = {}));
5614
5649
  var MessageAttachmentExternalTask_Status;
5615
5650
  (function(MessageAttachmentExternalTask_Status2) {
5616
5651
  MessageAttachmentExternalTask_Status2[MessageAttachmentExternalTask_Status2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
@@ -5753,6 +5788,9 @@ var Method;
5753
5788
  Method2[Method2["REVOKE_SESSION"] = 50] = "REVOKE_SESSION";
5754
5789
  Method2[Method2["UPDATE_DIALOG_OPEN"] = 51] = "UPDATE_DIALOG_OPEN";
5755
5790
  Method2[Method2["UPDATE_DIALOG_ORDER"] = 52] = "UPDATE_DIALOG_ORDER";
5791
+ Method2[Method2["CLEAR_CHAT_HISTORY"] = 53] = "CLEAR_CHAT_HISTORY";
5792
+ Method2[Method2["DELETE_BOT"] = 54] = "DELETE_BOT";
5793
+ Method2[Method2["DELETE_MESSAGE_ATTACHMENT"] = 55] = "DELETE_MESSAGE_ATTACHMENT";
5756
5794
  })(Method || (Method = {}));
5757
5795
  var PushNotificationProvider;
5758
5796
  (function(PushNotificationProvider2) {
@@ -8125,7 +8163,8 @@ class Space$Type extends import_runtime4.MessageType {
8125
8163
  { no: 1, name: "id", kind: "scalar", T: 3, L: 0 },
8126
8164
  { no: 2, name: "name", kind: "scalar", T: 9 },
8127
8165
  { no: 3, name: "creator", kind: "scalar", T: 8 },
8128
- { no: 4, name: "date", kind: "scalar", T: 3, L: 0 }
8166
+ { no: 4, name: "date", kind: "scalar", T: 3, L: 0 },
8167
+ { no: 5, name: "is_public", kind: "scalar", opt: true, T: 8 }
8129
8168
  ]);
8130
8169
  }
8131
8170
  create(value) {
@@ -8155,6 +8194,9 @@ class Space$Type extends import_runtime4.MessageType {
8155
8194
  case 4:
8156
8195
  message.date = reader.int64().toBigInt();
8157
8196
  break;
8197
+ case 5:
8198
+ message.isPublic = reader.bool();
8199
+ break;
8158
8200
  default:
8159
8201
  let u = options.readUnknownField;
8160
8202
  if (u === "throw")
@@ -8175,6 +8217,8 @@ class Space$Type extends import_runtime4.MessageType {
8175
8217
  writer.tag(3, import_runtime.WireType.Varint).bool(message.creator);
8176
8218
  if (message.date !== 0n)
8177
8219
  writer.tag(4, import_runtime.WireType.Varint).int64(message.date);
8220
+ if (message.isPublic !== undefined)
8221
+ writer.tag(5, import_runtime.WireType.Varint).bool(message.isPublic);
8178
8222
  let u = options.writeUnknownFields;
8179
8223
  if (u !== false)
8180
8224
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
@@ -8495,7 +8539,13 @@ class UrlPreview$Type extends import_runtime4.MessageType {
8495
8539
  { no: 4, name: "title", kind: "scalar", opt: true, T: 9 },
8496
8540
  { no: 5, name: "description", kind: "scalar", opt: true, T: 9 },
8497
8541
  { no: 6, name: "photo", kind: "message", T: () => Photo },
8498
- { no: 7, name: "duration", kind: "scalar", opt: true, T: 3, L: 0 }
8542
+ { no: 7, name: "duration", kind: "scalar", opt: true, T: 3, L: 0 },
8543
+ { no: 8, name: "media_type", kind: "enum", opt: true, T: () => ["UrlPreview.MediaType", UrlPreview_MediaType, "MEDIA_TYPE_"] },
8544
+ { no: 9, name: "display_url", kind: "scalar", opt: true, T: 9 },
8545
+ { no: 10, name: "provider", kind: "scalar", opt: true, T: 9 },
8546
+ { no: 11, name: "author", kind: "scalar", opt: true, T: 9 },
8547
+ { no: 12, name: "media", kind: "message", T: () => UrlPreviewMedia },
8548
+ { no: 13, name: "layout", kind: "message", T: () => UrlPreviewLayout }
8499
8549
  ]);
8500
8550
  }
8501
8551
  create(value) {
@@ -8531,6 +8581,24 @@ class UrlPreview$Type extends import_runtime4.MessageType {
8531
8581
  case 7:
8532
8582
  message.duration = reader.int64().toBigInt();
8533
8583
  break;
8584
+ case 8:
8585
+ message.mediaType = reader.int32();
8586
+ break;
8587
+ case 9:
8588
+ message.displayUrl = reader.string();
8589
+ break;
8590
+ case 10:
8591
+ message.provider = reader.string();
8592
+ break;
8593
+ case 11:
8594
+ message.author = reader.string();
8595
+ break;
8596
+ case 12:
8597
+ message.media = UrlPreviewMedia.internalBinaryRead(reader, reader.uint32(), options, message.media);
8598
+ break;
8599
+ case 13:
8600
+ message.layout = UrlPreviewLayout.internalBinaryRead(reader, reader.uint32(), options, message.layout);
8601
+ break;
8534
8602
  default:
8535
8603
  let u = options.readUnknownField;
8536
8604
  if (u === "throw")
@@ -8557,6 +8625,18 @@ class UrlPreview$Type extends import_runtime4.MessageType {
8557
8625
  Photo.internalBinaryWrite(message.photo, writer.tag(6, import_runtime.WireType.LengthDelimited).fork(), options).join();
8558
8626
  if (message.duration !== undefined)
8559
8627
  writer.tag(7, import_runtime.WireType.Varint).int64(message.duration);
8628
+ if (message.mediaType !== undefined)
8629
+ writer.tag(8, import_runtime.WireType.Varint).int32(message.mediaType);
8630
+ if (message.displayUrl !== undefined)
8631
+ writer.tag(9, import_runtime.WireType.LengthDelimited).string(message.displayUrl);
8632
+ if (message.provider !== undefined)
8633
+ writer.tag(10, import_runtime.WireType.LengthDelimited).string(message.provider);
8634
+ if (message.author !== undefined)
8635
+ writer.tag(11, import_runtime.WireType.LengthDelimited).string(message.author);
8636
+ if (message.media)
8637
+ UrlPreviewMedia.internalBinaryWrite(message.media, writer.tag(12, import_runtime.WireType.LengthDelimited).fork(), options).join();
8638
+ if (message.layout)
8639
+ UrlPreviewLayout.internalBinaryWrite(message.layout, writer.tag(13, import_runtime.WireType.LengthDelimited).fork(), options).join();
8560
8640
  let u = options.writeUnknownFields;
8561
8641
  if (u !== false)
8562
8642
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
@@ -8565,6 +8645,272 @@ class UrlPreview$Type extends import_runtime4.MessageType {
8565
8645
  }
8566
8646
  var UrlPreview = new UrlPreview$Type;
8567
8647
 
8648
+ class UrlPreviewMedia$Type extends import_runtime4.MessageType {
8649
+ constructor() {
8650
+ super("UrlPreviewMedia", [
8651
+ { no: 1, name: "photo", kind: "message", oneof: "media", T: () => Photo },
8652
+ { no: 2, name: "video", kind: "message", oneof: "media", T: () => Video },
8653
+ { no: 3, name: "document", kind: "message", oneof: "media", T: () => Document },
8654
+ { no: 4, name: "external_video", kind: "message", oneof: "media", T: () => UrlPreviewExternalVideo },
8655
+ { no: 5, name: "embed", kind: "message", oneof: "media", T: () => UrlPreviewEmbed }
8656
+ ]);
8657
+ }
8658
+ create(value) {
8659
+ const message = globalThis.Object.create(this.messagePrototype);
8660
+ message.media = { oneofKind: undefined };
8661
+ if (value !== undefined)
8662
+ import_runtime3.reflectionMergePartial(this, message, value);
8663
+ return message;
8664
+ }
8665
+ internalBinaryRead(reader, length, options, target) {
8666
+ let message = target ?? this.create(), end = reader.pos + length;
8667
+ while (reader.pos < end) {
8668
+ let [fieldNo, wireType] = reader.tag();
8669
+ switch (fieldNo) {
8670
+ case 1:
8671
+ message.media = {
8672
+ oneofKind: "photo",
8673
+ photo: Photo.internalBinaryRead(reader, reader.uint32(), options, message.media.photo)
8674
+ };
8675
+ break;
8676
+ case 2:
8677
+ message.media = {
8678
+ oneofKind: "video",
8679
+ video: Video.internalBinaryRead(reader, reader.uint32(), options, message.media.video)
8680
+ };
8681
+ break;
8682
+ case 3:
8683
+ message.media = {
8684
+ oneofKind: "document",
8685
+ document: Document.internalBinaryRead(reader, reader.uint32(), options, message.media.document)
8686
+ };
8687
+ break;
8688
+ case 4:
8689
+ message.media = {
8690
+ oneofKind: "externalVideo",
8691
+ externalVideo: UrlPreviewExternalVideo.internalBinaryRead(reader, reader.uint32(), options, message.media.externalVideo)
8692
+ };
8693
+ break;
8694
+ case 5:
8695
+ message.media = {
8696
+ oneofKind: "embed",
8697
+ embed: UrlPreviewEmbed.internalBinaryRead(reader, reader.uint32(), options, message.media.embed)
8698
+ };
8699
+ break;
8700
+ default:
8701
+ let u = options.readUnknownField;
8702
+ if (u === "throw")
8703
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
8704
+ let d = reader.skip(wireType);
8705
+ if (u !== false)
8706
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
8707
+ }
8708
+ }
8709
+ return message;
8710
+ }
8711
+ internalBinaryWrite(message, writer, options) {
8712
+ if (message.media.oneofKind === "photo")
8713
+ Photo.internalBinaryWrite(message.media.photo, writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
8714
+ if (message.media.oneofKind === "video")
8715
+ Video.internalBinaryWrite(message.media.video, writer.tag(2, import_runtime.WireType.LengthDelimited).fork(), options).join();
8716
+ if (message.media.oneofKind === "document")
8717
+ Document.internalBinaryWrite(message.media.document, writer.tag(3, import_runtime.WireType.LengthDelimited).fork(), options).join();
8718
+ if (message.media.oneofKind === "externalVideo")
8719
+ UrlPreviewExternalVideo.internalBinaryWrite(message.media.externalVideo, writer.tag(4, import_runtime.WireType.LengthDelimited).fork(), options).join();
8720
+ if (message.media.oneofKind === "embed")
8721
+ UrlPreviewEmbed.internalBinaryWrite(message.media.embed, writer.tag(5, import_runtime.WireType.LengthDelimited).fork(), options).join();
8722
+ let u = options.writeUnknownFields;
8723
+ if (u !== false)
8724
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
8725
+ return writer;
8726
+ }
8727
+ }
8728
+ var UrlPreviewMedia = new UrlPreviewMedia$Type;
8729
+
8730
+ class UrlPreviewExternalVideo$Type extends import_runtime4.MessageType {
8731
+ constructor() {
8732
+ super("UrlPreviewExternalVideo", [
8733
+ { no: 1, name: "url", kind: "scalar", T: 9 },
8734
+ { no: 2, name: "mime_type", kind: "scalar", opt: true, T: 9 },
8735
+ { no: 3, name: "w", kind: "scalar", opt: true, T: 5 },
8736
+ { no: 4, name: "h", kind: "scalar", opt: true, T: 5 },
8737
+ { no: 5, name: "duration", kind: "scalar", opt: true, T: 5 }
8738
+ ]);
8739
+ }
8740
+ create(value) {
8741
+ const message = globalThis.Object.create(this.messagePrototype);
8742
+ message.url = "";
8743
+ if (value !== undefined)
8744
+ import_runtime3.reflectionMergePartial(this, message, value);
8745
+ return message;
8746
+ }
8747
+ internalBinaryRead(reader, length, options, target) {
8748
+ let message = target ?? this.create(), end = reader.pos + length;
8749
+ while (reader.pos < end) {
8750
+ let [fieldNo, wireType] = reader.tag();
8751
+ switch (fieldNo) {
8752
+ case 1:
8753
+ message.url = reader.string();
8754
+ break;
8755
+ case 2:
8756
+ message.mimeType = reader.string();
8757
+ break;
8758
+ case 3:
8759
+ message.w = reader.int32();
8760
+ break;
8761
+ case 4:
8762
+ message.h = reader.int32();
8763
+ break;
8764
+ case 5:
8765
+ message.duration = reader.int32();
8766
+ break;
8767
+ default:
8768
+ let u = options.readUnknownField;
8769
+ if (u === "throw")
8770
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
8771
+ let d = reader.skip(wireType);
8772
+ if (u !== false)
8773
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
8774
+ }
8775
+ }
8776
+ return message;
8777
+ }
8778
+ internalBinaryWrite(message, writer, options) {
8779
+ if (message.url !== "")
8780
+ writer.tag(1, import_runtime.WireType.LengthDelimited).string(message.url);
8781
+ if (message.mimeType !== undefined)
8782
+ writer.tag(2, import_runtime.WireType.LengthDelimited).string(message.mimeType);
8783
+ if (message.w !== undefined)
8784
+ writer.tag(3, import_runtime.WireType.Varint).int32(message.w);
8785
+ if (message.h !== undefined)
8786
+ writer.tag(4, import_runtime.WireType.Varint).int32(message.h);
8787
+ if (message.duration !== undefined)
8788
+ writer.tag(5, import_runtime.WireType.Varint).int32(message.duration);
8789
+ let u = options.writeUnknownFields;
8790
+ if (u !== false)
8791
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
8792
+ return writer;
8793
+ }
8794
+ }
8795
+ var UrlPreviewExternalVideo = new UrlPreviewExternalVideo$Type;
8796
+
8797
+ class UrlPreviewEmbed$Type extends import_runtime4.MessageType {
8798
+ constructor() {
8799
+ super("UrlPreviewEmbed", [
8800
+ { no: 1, name: "url", kind: "scalar", T: 9 },
8801
+ { no: 2, name: "type", kind: "scalar", opt: true, T: 9 },
8802
+ { no: 3, name: "w", kind: "scalar", opt: true, T: 5 },
8803
+ { no: 4, name: "h", kind: "scalar", opt: true, T: 5 },
8804
+ { no: 5, name: "duration", kind: "scalar", opt: true, T: 5 }
8805
+ ]);
8806
+ }
8807
+ create(value) {
8808
+ const message = globalThis.Object.create(this.messagePrototype);
8809
+ message.url = "";
8810
+ if (value !== undefined)
8811
+ import_runtime3.reflectionMergePartial(this, message, value);
8812
+ return message;
8813
+ }
8814
+ internalBinaryRead(reader, length, options, target) {
8815
+ let message = target ?? this.create(), end = reader.pos + length;
8816
+ while (reader.pos < end) {
8817
+ let [fieldNo, wireType] = reader.tag();
8818
+ switch (fieldNo) {
8819
+ case 1:
8820
+ message.url = reader.string();
8821
+ break;
8822
+ case 2:
8823
+ message.type = reader.string();
8824
+ break;
8825
+ case 3:
8826
+ message.w = reader.int32();
8827
+ break;
8828
+ case 4:
8829
+ message.h = reader.int32();
8830
+ break;
8831
+ case 5:
8832
+ message.duration = reader.int32();
8833
+ break;
8834
+ default:
8835
+ let u = options.readUnknownField;
8836
+ if (u === "throw")
8837
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
8838
+ let d = reader.skip(wireType);
8839
+ if (u !== false)
8840
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
8841
+ }
8842
+ }
8843
+ return message;
8844
+ }
8845
+ internalBinaryWrite(message, writer, options) {
8846
+ if (message.url !== "")
8847
+ writer.tag(1, import_runtime.WireType.LengthDelimited).string(message.url);
8848
+ if (message.type !== undefined)
8849
+ writer.tag(2, import_runtime.WireType.LengthDelimited).string(message.type);
8850
+ if (message.w !== undefined)
8851
+ writer.tag(3, import_runtime.WireType.Varint).int32(message.w);
8852
+ if (message.h !== undefined)
8853
+ writer.tag(4, import_runtime.WireType.Varint).int32(message.h);
8854
+ if (message.duration !== undefined)
8855
+ writer.tag(5, import_runtime.WireType.Varint).int32(message.duration);
8856
+ let u = options.writeUnknownFields;
8857
+ if (u !== false)
8858
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
8859
+ return writer;
8860
+ }
8861
+ }
8862
+ var UrlPreviewEmbed = new UrlPreviewEmbed$Type;
8863
+
8864
+ class UrlPreviewLayout$Type extends import_runtime4.MessageType {
8865
+ constructor() {
8866
+ super("UrlPreviewLayout", [
8867
+ { no: 1, name: "has_large_media", kind: "scalar", T: 8 },
8868
+ { no: 2, name: "show_large_media", kind: "scalar", T: 8 }
8869
+ ]);
8870
+ }
8871
+ create(value) {
8872
+ const message = globalThis.Object.create(this.messagePrototype);
8873
+ message.hasLargeMedia = false;
8874
+ message.showLargeMedia = false;
8875
+ if (value !== undefined)
8876
+ import_runtime3.reflectionMergePartial(this, message, value);
8877
+ return message;
8878
+ }
8879
+ internalBinaryRead(reader, length, options, target) {
8880
+ let message = target ?? this.create(), end = reader.pos + length;
8881
+ while (reader.pos < end) {
8882
+ let [fieldNo, wireType] = reader.tag();
8883
+ switch (fieldNo) {
8884
+ case 1:
8885
+ message.hasLargeMedia = reader.bool();
8886
+ break;
8887
+ case 2:
8888
+ message.showLargeMedia = reader.bool();
8889
+ break;
8890
+ default:
8891
+ let u = options.readUnknownField;
8892
+ if (u === "throw")
8893
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
8894
+ let d = reader.skip(wireType);
8895
+ if (u !== false)
8896
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
8897
+ }
8898
+ }
8899
+ return message;
8900
+ }
8901
+ internalBinaryWrite(message, writer, options) {
8902
+ if (message.hasLargeMedia !== false)
8903
+ writer.tag(1, import_runtime.WireType.Varint).bool(message.hasLargeMedia);
8904
+ if (message.showLargeMedia !== false)
8905
+ writer.tag(2, import_runtime.WireType.Varint).bool(message.showLargeMedia);
8906
+ let u = options.writeUnknownFields;
8907
+ if (u !== false)
8908
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
8909
+ return writer;
8910
+ }
8911
+ }
8912
+ var UrlPreviewLayout = new UrlPreviewLayout$Type;
8913
+
8568
8914
  class MessageAttachmentExternalTask$Type extends import_runtime4.MessageType {
8569
8915
  constructor() {
8570
8916
  super("MessageAttachmentExternalTask", [
@@ -9458,7 +9804,10 @@ class RpcCall$Type extends import_runtime4.MessageType {
9458
9804
  { no: 50, name: "answerMessageAction", kind: "message", oneof: "input", T: () => AnswerMessageActionInput },
9459
9805
  { no: 51, name: "revokeSession", kind: "message", oneof: "input", T: () => RevokeSessionInput },
9460
9806
  { no: 52, name: "updateDialogOpen", kind: "message", oneof: "input", T: () => UpdateDialogOpenInput },
9461
- { no: 53, name: "updateDialogOrder", kind: "message", oneof: "input", T: () => UpdateDialogOrderInput }
9807
+ { no: 53, name: "updateDialogOrder", kind: "message", oneof: "input", T: () => UpdateDialogOrderInput },
9808
+ { no: 54, name: "clearChatHistory", kind: "message", oneof: "input", T: () => ClearChatHistoryInput },
9809
+ { no: 55, name: "deleteBot", kind: "message", oneof: "input", T: () => DeleteBotInput },
9810
+ { no: 56, name: "deleteMessageAttachment", kind: "message", oneof: "input", T: () => DeleteMessageAttachmentInput }
9462
9811
  ]);
9463
9812
  }
9464
9813
  create(value) {
@@ -9789,6 +10138,24 @@ class RpcCall$Type extends import_runtime4.MessageType {
9789
10138
  updateDialogOrder: UpdateDialogOrderInput.internalBinaryRead(reader, reader.uint32(), options, message.input.updateDialogOrder)
9790
10139
  };
9791
10140
  break;
10141
+ case 54:
10142
+ message.input = {
10143
+ oneofKind: "clearChatHistory",
10144
+ clearChatHistory: ClearChatHistoryInput.internalBinaryRead(reader, reader.uint32(), options, message.input.clearChatHistory)
10145
+ };
10146
+ break;
10147
+ case 55:
10148
+ message.input = {
10149
+ oneofKind: "deleteBot",
10150
+ deleteBot: DeleteBotInput.internalBinaryRead(reader, reader.uint32(), options, message.input.deleteBot)
10151
+ };
10152
+ break;
10153
+ case 56:
10154
+ message.input = {
10155
+ oneofKind: "deleteMessageAttachment",
10156
+ deleteMessageAttachment: DeleteMessageAttachmentInput.internalBinaryRead(reader, reader.uint32(), options, message.input.deleteMessageAttachment)
10157
+ };
10158
+ break;
9792
10159
  default:
9793
10160
  let u = options.readUnknownField;
9794
10161
  if (u === "throw")
@@ -9907,6 +10274,12 @@ class RpcCall$Type extends import_runtime4.MessageType {
9907
10274
  UpdateDialogOpenInput.internalBinaryWrite(message.input.updateDialogOpen, writer.tag(52, import_runtime.WireType.LengthDelimited).fork(), options).join();
9908
10275
  if (message.input.oneofKind === "updateDialogOrder")
9909
10276
  UpdateDialogOrderInput.internalBinaryWrite(message.input.updateDialogOrder, writer.tag(53, import_runtime.WireType.LengthDelimited).fork(), options).join();
10277
+ if (message.input.oneofKind === "clearChatHistory")
10278
+ ClearChatHistoryInput.internalBinaryWrite(message.input.clearChatHistory, writer.tag(54, import_runtime.WireType.LengthDelimited).fork(), options).join();
10279
+ if (message.input.oneofKind === "deleteBot")
10280
+ DeleteBotInput.internalBinaryWrite(message.input.deleteBot, writer.tag(55, import_runtime.WireType.LengthDelimited).fork(), options).join();
10281
+ if (message.input.oneofKind === "deleteMessageAttachment")
10282
+ DeleteMessageAttachmentInput.internalBinaryWrite(message.input.deleteMessageAttachment, writer.tag(56, import_runtime.WireType.LengthDelimited).fork(), options).join();
9910
10283
  let u = options.writeUnknownFields;
9911
10284
  if (u !== false)
9912
10285
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
@@ -9970,7 +10343,10 @@ class RpcResult$Type extends import_runtime4.MessageType {
9970
10343
  { no: 50, name: "answerMessageAction", kind: "message", oneof: "result", T: () => AnswerMessageActionResult },
9971
10344
  { no: 51, name: "revokeSession", kind: "message", oneof: "result", T: () => RevokeSessionResult },
9972
10345
  { no: 52, name: "updateDialogOpen", kind: "message", oneof: "result", T: () => UpdateDialogOpenResult },
9973
- { no: 53, name: "updateDialogOrder", kind: "message", oneof: "result", T: () => UpdateDialogOrderResult }
10346
+ { no: 53, name: "updateDialogOrder", kind: "message", oneof: "result", T: () => UpdateDialogOrderResult },
10347
+ { no: 54, name: "clearChatHistory", kind: "message", oneof: "result", T: () => ClearChatHistoryResult },
10348
+ { no: 55, name: "deleteBot", kind: "message", oneof: "result", T: () => DeleteBotResult },
10349
+ { no: 56, name: "deleteMessageAttachment", kind: "message", oneof: "result", T: () => DeleteMessageAttachmentResult }
9974
10350
  ]);
9975
10351
  }
9976
10352
  create(value) {
@@ -10301,6 +10677,24 @@ class RpcResult$Type extends import_runtime4.MessageType {
10301
10677
  updateDialogOrder: UpdateDialogOrderResult.internalBinaryRead(reader, reader.uint32(), options, message.result.updateDialogOrder)
10302
10678
  };
10303
10679
  break;
10680
+ case 54:
10681
+ message.result = {
10682
+ oneofKind: "clearChatHistory",
10683
+ clearChatHistory: ClearChatHistoryResult.internalBinaryRead(reader, reader.uint32(), options, message.result.clearChatHistory)
10684
+ };
10685
+ break;
10686
+ case 55:
10687
+ message.result = {
10688
+ oneofKind: "deleteBot",
10689
+ deleteBot: DeleteBotResult.internalBinaryRead(reader, reader.uint32(), options, message.result.deleteBot)
10690
+ };
10691
+ break;
10692
+ case 56:
10693
+ message.result = {
10694
+ oneofKind: "deleteMessageAttachment",
10695
+ deleteMessageAttachment: DeleteMessageAttachmentResult.internalBinaryRead(reader, reader.uint32(), options, message.result.deleteMessageAttachment)
10696
+ };
10697
+ break;
10304
10698
  default:
10305
10699
  let u = options.readUnknownField;
10306
10700
  if (u === "throw")
@@ -10419,6 +10813,12 @@ class RpcResult$Type extends import_runtime4.MessageType {
10419
10813
  UpdateDialogOpenResult.internalBinaryWrite(message.result.updateDialogOpen, writer.tag(52, import_runtime.WireType.LengthDelimited).fork(), options).join();
10420
10814
  if (message.result.oneofKind === "updateDialogOrder")
10421
10815
  UpdateDialogOrderResult.internalBinaryWrite(message.result.updateDialogOrder, writer.tag(53, import_runtime.WireType.LengthDelimited).fork(), options).join();
10816
+ if (message.result.oneofKind === "clearChatHistory")
10817
+ ClearChatHistoryResult.internalBinaryWrite(message.result.clearChatHistory, writer.tag(54, import_runtime.WireType.LengthDelimited).fork(), options).join();
10818
+ if (message.result.oneofKind === "deleteBot")
10819
+ DeleteBotResult.internalBinaryWrite(message.result.deleteBot, writer.tag(55, import_runtime.WireType.LengthDelimited).fork(), options).join();
10820
+ if (message.result.oneofKind === "deleteMessageAttachment")
10821
+ DeleteMessageAttachmentResult.internalBinaryWrite(message.result.deleteMessageAttachment, writer.tag(56, import_runtime.WireType.LengthDelimited).fork(), options).join();
10422
10822
  let u = options.writeUnknownFields;
10423
10823
  if (u !== false)
10424
10824
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
@@ -10604,7 +11004,8 @@ class GetUpdatesInput$Type extends import_runtime4.MessageType {
10604
11004
  { no: 1, name: "bucket", kind: "message", T: () => UpdateBucket },
10605
11005
  { no: 2, name: "start_seq", kind: "scalar", T: 3, L: 0 },
10606
11006
  { no: 3, name: "total_limit", kind: "scalar", T: 5 },
10607
- { no: 4, name: "seq_end", kind: "scalar", T: 3, L: 0 }
11007
+ { no: 4, name: "seq_end", kind: "scalar", T: 3, L: 0 },
11008
+ { no: 5, name: "limit", kind: "scalar", T: 5 }
10608
11009
  ]);
10609
11010
  }
10610
11011
  create(value) {
@@ -10612,6 +11013,7 @@ class GetUpdatesInput$Type extends import_runtime4.MessageType {
10612
11013
  message.startSeq = 0n;
10613
11014
  message.totalLimit = 0;
10614
11015
  message.seqEnd = 0n;
11016
+ message.limit = 0;
10615
11017
  if (value !== undefined)
10616
11018
  import_runtime3.reflectionMergePartial(this, message, value);
10617
11019
  return message;
@@ -10633,6 +11035,9 @@ class GetUpdatesInput$Type extends import_runtime4.MessageType {
10633
11035
  case 4:
10634
11036
  message.seqEnd = reader.int64().toBigInt();
10635
11037
  break;
11038
+ case 5:
11039
+ message.limit = reader.int32();
11040
+ break;
10636
11041
  default:
10637
11042
  let u = options.readUnknownField;
10638
11043
  if (u === "throw")
@@ -10653,6 +11058,8 @@ class GetUpdatesInput$Type extends import_runtime4.MessageType {
10653
11058
  writer.tag(3, import_runtime.WireType.Varint).int32(message.totalLimit);
10654
11059
  if (message.seqEnd !== 0n)
10655
11060
  writer.tag(4, import_runtime.WireType.Varint).int64(message.seqEnd);
11061
+ if (message.limit !== 0)
11062
+ writer.tag(5, import_runtime.WireType.Varint).int32(message.limit);
10656
11063
  let u = options.writeUnknownFields;
10657
11064
  if (u !== false)
10658
11065
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
@@ -11779,6 +12186,191 @@ class ListBotsResult$Type extends import_runtime4.MessageType {
11779
12186
  }
11780
12187
  var ListBotsResult = new ListBotsResult$Type;
11781
12188
 
12189
+ class DeleteBotInput$Type extends import_runtime4.MessageType {
12190
+ constructor() {
12191
+ super("DeleteBotInput", [
12192
+ { no: 1, name: "bot_user_id", kind: "scalar", T: 3, L: 0 }
12193
+ ]);
12194
+ }
12195
+ create(value) {
12196
+ const message = globalThis.Object.create(this.messagePrototype);
12197
+ message.botUserId = 0n;
12198
+ if (value !== undefined)
12199
+ import_runtime3.reflectionMergePartial(this, message, value);
12200
+ return message;
12201
+ }
12202
+ internalBinaryRead(reader, length, options, target) {
12203
+ let message = target ?? this.create(), end = reader.pos + length;
12204
+ while (reader.pos < end) {
12205
+ let [fieldNo, wireType] = reader.tag();
12206
+ switch (fieldNo) {
12207
+ case 1:
12208
+ message.botUserId = reader.int64().toBigInt();
12209
+ break;
12210
+ default:
12211
+ let u = options.readUnknownField;
12212
+ if (u === "throw")
12213
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
12214
+ let d = reader.skip(wireType);
12215
+ if (u !== false)
12216
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
12217
+ }
12218
+ }
12219
+ return message;
12220
+ }
12221
+ internalBinaryWrite(message, writer, options) {
12222
+ if (message.botUserId !== 0n)
12223
+ writer.tag(1, import_runtime.WireType.Varint).int64(message.botUserId);
12224
+ let u = options.writeUnknownFields;
12225
+ if (u !== false)
12226
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
12227
+ return writer;
12228
+ }
12229
+ }
12230
+ var DeleteBotInput = new DeleteBotInput$Type;
12231
+
12232
+ class DeleteBotResult$Type extends import_runtime4.MessageType {
12233
+ constructor() {
12234
+ super("DeleteBotResult", [
12235
+ { no: 1, name: "bot_user_id", kind: "scalar", T: 3, L: 0 }
12236
+ ]);
12237
+ }
12238
+ create(value) {
12239
+ const message = globalThis.Object.create(this.messagePrototype);
12240
+ message.botUserId = 0n;
12241
+ if (value !== undefined)
12242
+ import_runtime3.reflectionMergePartial(this, message, value);
12243
+ return message;
12244
+ }
12245
+ internalBinaryRead(reader, length, options, target) {
12246
+ let message = target ?? this.create(), end = reader.pos + length;
12247
+ while (reader.pos < end) {
12248
+ let [fieldNo, wireType] = reader.tag();
12249
+ switch (fieldNo) {
12250
+ case 1:
12251
+ message.botUserId = reader.int64().toBigInt();
12252
+ break;
12253
+ default:
12254
+ let u = options.readUnknownField;
12255
+ if (u === "throw")
12256
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
12257
+ let d = reader.skip(wireType);
12258
+ if (u !== false)
12259
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
12260
+ }
12261
+ }
12262
+ return message;
12263
+ }
12264
+ internalBinaryWrite(message, writer, options) {
12265
+ if (message.botUserId !== 0n)
12266
+ writer.tag(1, import_runtime.WireType.Varint).int64(message.botUserId);
12267
+ let u = options.writeUnknownFields;
12268
+ if (u !== false)
12269
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
12270
+ return writer;
12271
+ }
12272
+ }
12273
+ var DeleteBotResult = new DeleteBotResult$Type;
12274
+
12275
+ class DeleteMessageAttachmentInput$Type extends import_runtime4.MessageType {
12276
+ constructor() {
12277
+ super("DeleteMessageAttachmentInput", [
12278
+ { no: 1, name: "peer_id", kind: "message", T: () => InputPeer },
12279
+ { no: 2, name: "message_id", kind: "scalar", T: 3, L: 0 },
12280
+ { no: 3, name: "attachment_id", kind: "scalar", T: 3, L: 0 }
12281
+ ]);
12282
+ }
12283
+ create(value) {
12284
+ const message = globalThis.Object.create(this.messagePrototype);
12285
+ message.messageId = 0n;
12286
+ message.attachmentId = 0n;
12287
+ if (value !== undefined)
12288
+ import_runtime3.reflectionMergePartial(this, message, value);
12289
+ return message;
12290
+ }
12291
+ internalBinaryRead(reader, length, options, target) {
12292
+ let message = target ?? this.create(), end = reader.pos + length;
12293
+ while (reader.pos < end) {
12294
+ let [fieldNo, wireType] = reader.tag();
12295
+ switch (fieldNo) {
12296
+ case 1:
12297
+ message.peerId = InputPeer.internalBinaryRead(reader, reader.uint32(), options, message.peerId);
12298
+ break;
12299
+ case 2:
12300
+ message.messageId = reader.int64().toBigInt();
12301
+ break;
12302
+ case 3:
12303
+ message.attachmentId = reader.int64().toBigInt();
12304
+ break;
12305
+ default:
12306
+ let u = options.readUnknownField;
12307
+ if (u === "throw")
12308
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
12309
+ let d = reader.skip(wireType);
12310
+ if (u !== false)
12311
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
12312
+ }
12313
+ }
12314
+ return message;
12315
+ }
12316
+ internalBinaryWrite(message, writer, options) {
12317
+ if (message.peerId)
12318
+ InputPeer.internalBinaryWrite(message.peerId, writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
12319
+ if (message.messageId !== 0n)
12320
+ writer.tag(2, import_runtime.WireType.Varint).int64(message.messageId);
12321
+ if (message.attachmentId !== 0n)
12322
+ writer.tag(3, import_runtime.WireType.Varint).int64(message.attachmentId);
12323
+ let u = options.writeUnknownFields;
12324
+ if (u !== false)
12325
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
12326
+ return writer;
12327
+ }
12328
+ }
12329
+ var DeleteMessageAttachmentInput = new DeleteMessageAttachmentInput$Type;
12330
+
12331
+ class DeleteMessageAttachmentResult$Type extends import_runtime4.MessageType {
12332
+ constructor() {
12333
+ super("DeleteMessageAttachmentResult", [
12334
+ { no: 1, name: "updates", kind: "message", repeat: 1, T: () => Update }
12335
+ ]);
12336
+ }
12337
+ create(value) {
12338
+ const message = globalThis.Object.create(this.messagePrototype);
12339
+ message.updates = [];
12340
+ if (value !== undefined)
12341
+ import_runtime3.reflectionMergePartial(this, message, value);
12342
+ return message;
12343
+ }
12344
+ internalBinaryRead(reader, length, options, target) {
12345
+ let message = target ?? this.create(), end = reader.pos + length;
12346
+ while (reader.pos < end) {
12347
+ let [fieldNo, wireType] = reader.tag();
12348
+ switch (fieldNo) {
12349
+ case 1:
12350
+ message.updates.push(Update.internalBinaryRead(reader, reader.uint32(), options));
12351
+ break;
12352
+ default:
12353
+ let u = options.readUnknownField;
12354
+ if (u === "throw")
12355
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
12356
+ let d = reader.skip(wireType);
12357
+ if (u !== false)
12358
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
12359
+ }
12360
+ }
12361
+ return message;
12362
+ }
12363
+ internalBinaryWrite(message, writer, options) {
12364
+ for (let i = 0;i < message.updates.length; i++)
12365
+ Update.internalBinaryWrite(message.updates[i], writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
12366
+ let u = options.writeUnknownFields;
12367
+ if (u !== false)
12368
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
12369
+ return writer;
12370
+ }
12371
+ }
12372
+ var DeleteMessageAttachmentResult = new DeleteMessageAttachmentResult$Type;
12373
+
11782
12374
  class RevokeSessionInput$Type extends import_runtime4.MessageType {
11783
12375
  constructor() {
11784
12376
  super("RevokeSessionInput", [
@@ -13795,6 +14387,118 @@ class DeleteMessagesResult$Type extends import_runtime4.MessageType {
13795
14387
  }
13796
14388
  var DeleteMessagesResult = new DeleteMessagesResult$Type;
13797
14389
 
14390
+ class ClearChatHistoryInput$Type extends import_runtime4.MessageType {
14391
+ constructor() {
14392
+ super("ClearChatHistoryInput", [
14393
+ { no: 1, name: "peer_id", kind: "message", oneof: "target", T: () => InputPeer },
14394
+ { no: 4, name: "space_id", kind: "scalar", oneof: "target", T: 3, L: 0 },
14395
+ { no: 2, name: "keep_last_days", kind: "scalar", T: 5 },
14396
+ { no: 3, name: "delete_reply_threads", kind: "scalar", T: 8 }
14397
+ ]);
14398
+ }
14399
+ create(value) {
14400
+ const message = globalThis.Object.create(this.messagePrototype);
14401
+ message.target = { oneofKind: undefined };
14402
+ message.keepLastDays = 0;
14403
+ message.deleteReplyThreads = false;
14404
+ if (value !== undefined)
14405
+ import_runtime3.reflectionMergePartial(this, message, value);
14406
+ return message;
14407
+ }
14408
+ internalBinaryRead(reader, length, options, target) {
14409
+ let message = target ?? this.create(), end = reader.pos + length;
14410
+ while (reader.pos < end) {
14411
+ let [fieldNo, wireType] = reader.tag();
14412
+ switch (fieldNo) {
14413
+ case 1:
14414
+ message.target = {
14415
+ oneofKind: "peerId",
14416
+ peerId: InputPeer.internalBinaryRead(reader, reader.uint32(), options, message.target.peerId)
14417
+ };
14418
+ break;
14419
+ case 4:
14420
+ message.target = {
14421
+ oneofKind: "spaceId",
14422
+ spaceId: reader.int64().toBigInt()
14423
+ };
14424
+ break;
14425
+ case 2:
14426
+ message.keepLastDays = reader.int32();
14427
+ break;
14428
+ case 3:
14429
+ message.deleteReplyThreads = reader.bool();
14430
+ break;
14431
+ default:
14432
+ let u = options.readUnknownField;
14433
+ if (u === "throw")
14434
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
14435
+ let d = reader.skip(wireType);
14436
+ if (u !== false)
14437
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
14438
+ }
14439
+ }
14440
+ return message;
14441
+ }
14442
+ internalBinaryWrite(message, writer, options) {
14443
+ if (message.target.oneofKind === "peerId")
14444
+ InputPeer.internalBinaryWrite(message.target.peerId, writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
14445
+ if (message.target.oneofKind === "spaceId")
14446
+ writer.tag(4, import_runtime.WireType.Varint).int64(message.target.spaceId);
14447
+ if (message.keepLastDays !== 0)
14448
+ writer.tag(2, import_runtime.WireType.Varint).int32(message.keepLastDays);
14449
+ if (message.deleteReplyThreads !== false)
14450
+ writer.tag(3, import_runtime.WireType.Varint).bool(message.deleteReplyThreads);
14451
+ let u = options.writeUnknownFields;
14452
+ if (u !== false)
14453
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
14454
+ return writer;
14455
+ }
14456
+ }
14457
+ var ClearChatHistoryInput = new ClearChatHistoryInput$Type;
14458
+
14459
+ class ClearChatHistoryResult$Type extends import_runtime4.MessageType {
14460
+ constructor() {
14461
+ super("ClearChatHistoryResult", [
14462
+ { no: 1, name: "updates", kind: "message", repeat: 1, T: () => Update }
14463
+ ]);
14464
+ }
14465
+ create(value) {
14466
+ const message = globalThis.Object.create(this.messagePrototype);
14467
+ message.updates = [];
14468
+ if (value !== undefined)
14469
+ import_runtime3.reflectionMergePartial(this, message, value);
14470
+ return message;
14471
+ }
14472
+ internalBinaryRead(reader, length, options, target) {
14473
+ let message = target ?? this.create(), end = reader.pos + length;
14474
+ while (reader.pos < end) {
14475
+ let [fieldNo, wireType] = reader.tag();
14476
+ switch (fieldNo) {
14477
+ case 1:
14478
+ message.updates.push(Update.internalBinaryRead(reader, reader.uint32(), options));
14479
+ break;
14480
+ default:
14481
+ let u = options.readUnknownField;
14482
+ if (u === "throw")
14483
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
14484
+ let d = reader.skip(wireType);
14485
+ if (u !== false)
14486
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
14487
+ }
14488
+ }
14489
+ return message;
14490
+ }
14491
+ internalBinaryWrite(message, writer, options) {
14492
+ for (let i = 0;i < message.updates.length; i++)
14493
+ Update.internalBinaryWrite(message.updates[i], writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
14494
+ let u = options.writeUnknownFields;
14495
+ if (u !== false)
14496
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
14497
+ return writer;
14498
+ }
14499
+ }
14500
+ var ClearChatHistoryResult = new ClearChatHistoryResult$Type;
14501
+
13798
14502
  class EditMessageInput$Type extends import_runtime4.MessageType {
13799
14503
  constructor() {
13800
14504
  super("EditMessageInput", [
@@ -15536,7 +16240,8 @@ class Update$Type extends import_runtime4.MessageType {
15536
16240
  { no: 33, name: "dialog_notification_settings", kind: "message", oneof: "update", T: () => UpdateDialogNotificationSettings },
15537
16241
  { no: 34, name: "chat_open", kind: "message", oneof: "update", T: () => UpdateChatOpen },
15538
16242
  { no: 35, name: "message_action_invoked", kind: "message", oneof: "update", T: () => UpdateMessageActionInvoked },
15539
- { no: 36, name: "message_action_answered", kind: "message", oneof: "update", T: () => UpdateMessageActionAnswered }
16243
+ { no: 36, name: "message_action_answered", kind: "message", oneof: "update", T: () => UpdateMessageActionAnswered },
16244
+ { no: 37, name: "clear_chat_history", kind: "message", oneof: "update", T: () => UpdateClearChatHistory }
15540
16245
  ]);
15541
16246
  }
15542
16247
  create(value) {
@@ -15755,6 +16460,12 @@ class Update$Type extends import_runtime4.MessageType {
15755
16460
  messageActionAnswered: UpdateMessageActionAnswered.internalBinaryRead(reader, reader.uint32(), options, message.update.messageActionAnswered)
15756
16461
  };
15757
16462
  break;
16463
+ case 37:
16464
+ message.update = {
16465
+ oneofKind: "clearChatHistory",
16466
+ clearChatHistory: UpdateClearChatHistory.internalBinaryRead(reader, reader.uint32(), options, message.update.clearChatHistory)
16467
+ };
16468
+ break;
15758
16469
  default:
15759
16470
  let u = options.readUnknownField;
15760
16471
  if (u === "throw")
@@ -15837,6 +16548,8 @@ class Update$Type extends import_runtime4.MessageType {
15837
16548
  UpdateMessageActionInvoked.internalBinaryWrite(message.update.messageActionInvoked, writer.tag(35, import_runtime.WireType.LengthDelimited).fork(), options).join();
15838
16549
  if (message.update.oneofKind === "messageActionAnswered")
15839
16550
  UpdateMessageActionAnswered.internalBinaryWrite(message.update.messageActionAnswered, writer.tag(36, import_runtime.WireType.LengthDelimited).fork(), options).join();
16551
+ if (message.update.oneofKind === "clearChatHistory")
16552
+ UpdateClearChatHistory.internalBinaryWrite(message.update.clearChatHistory, writer.tag(37, import_runtime.WireType.LengthDelimited).fork(), options).join();
15840
16553
  let u = options.writeUnknownFields;
15841
16554
  if (u !== false)
15842
16555
  (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
@@ -17103,6 +17816,119 @@ class UpdateDeleteMessages$Type extends import_runtime4.MessageType {
17103
17816
  }
17104
17817
  var UpdateDeleteMessages = new UpdateDeleteMessages$Type;
17105
17818
 
17819
+ class UpdateClearChatHistory$Type extends import_runtime4.MessageType {
17820
+ constructor() {
17821
+ super("UpdateClearChatHistory", [
17822
+ { no: 1, name: "peer_id", kind: "message", oneof: "target", T: () => Peer },
17823
+ { no: 4, name: "space_id", kind: "scalar", oneof: "target", T: 3, L: 0 },
17824
+ { no: 2, name: "before_date", kind: "scalar", opt: true, T: 3, L: 0 },
17825
+ { no: 3, name: "delete_reply_threads", kind: "scalar", T: 8 },
17826
+ { no: 5, name: "deleted_chat_ids", kind: "scalar", repeat: 1, T: 3, L: 0 },
17827
+ { no: 6, name: "orphaned_chat_ids", kind: "scalar", repeat: 1, T: 3, L: 0 },
17828
+ { no: 7, name: "detached_chat_ids", kind: "scalar", repeat: 1, T: 3, L: 0 }
17829
+ ]);
17830
+ }
17831
+ create(value) {
17832
+ const message = globalThis.Object.create(this.messagePrototype);
17833
+ message.target = { oneofKind: undefined };
17834
+ message.deleteReplyThreads = false;
17835
+ message.deletedChatIds = [];
17836
+ message.orphanedChatIds = [];
17837
+ message.detachedChatIds = [];
17838
+ if (value !== undefined)
17839
+ import_runtime3.reflectionMergePartial(this, message, value);
17840
+ return message;
17841
+ }
17842
+ internalBinaryRead(reader, length, options, target) {
17843
+ let message = target ?? this.create(), end = reader.pos + length;
17844
+ while (reader.pos < end) {
17845
+ let [fieldNo, wireType] = reader.tag();
17846
+ switch (fieldNo) {
17847
+ case 1:
17848
+ message.target = {
17849
+ oneofKind: "peerId",
17850
+ peerId: Peer.internalBinaryRead(reader, reader.uint32(), options, message.target.peerId)
17851
+ };
17852
+ break;
17853
+ case 4:
17854
+ message.target = {
17855
+ oneofKind: "spaceId",
17856
+ spaceId: reader.int64().toBigInt()
17857
+ };
17858
+ break;
17859
+ case 2:
17860
+ message.beforeDate = reader.int64().toBigInt();
17861
+ break;
17862
+ case 3:
17863
+ message.deleteReplyThreads = reader.bool();
17864
+ break;
17865
+ case 5:
17866
+ if (wireType === import_runtime.WireType.LengthDelimited)
17867
+ for (let e = reader.int32() + reader.pos;reader.pos < e; )
17868
+ message.deletedChatIds.push(reader.int64().toBigInt());
17869
+ else
17870
+ message.deletedChatIds.push(reader.int64().toBigInt());
17871
+ break;
17872
+ case 6:
17873
+ if (wireType === import_runtime.WireType.LengthDelimited)
17874
+ for (let e = reader.int32() + reader.pos;reader.pos < e; )
17875
+ message.orphanedChatIds.push(reader.int64().toBigInt());
17876
+ else
17877
+ message.orphanedChatIds.push(reader.int64().toBigInt());
17878
+ break;
17879
+ case 7:
17880
+ if (wireType === import_runtime.WireType.LengthDelimited)
17881
+ for (let e = reader.int32() + reader.pos;reader.pos < e; )
17882
+ message.detachedChatIds.push(reader.int64().toBigInt());
17883
+ else
17884
+ message.detachedChatIds.push(reader.int64().toBigInt());
17885
+ break;
17886
+ default:
17887
+ let u = options.readUnknownField;
17888
+ if (u === "throw")
17889
+ throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
17890
+ let d = reader.skip(wireType);
17891
+ if (u !== false)
17892
+ (u === true ? import_runtime2.UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
17893
+ }
17894
+ }
17895
+ return message;
17896
+ }
17897
+ internalBinaryWrite(message, writer, options) {
17898
+ if (message.target.oneofKind === "peerId")
17899
+ Peer.internalBinaryWrite(message.target.peerId, writer.tag(1, import_runtime.WireType.LengthDelimited).fork(), options).join();
17900
+ if (message.target.oneofKind === "spaceId")
17901
+ writer.tag(4, import_runtime.WireType.Varint).int64(message.target.spaceId);
17902
+ if (message.beforeDate !== undefined)
17903
+ writer.tag(2, import_runtime.WireType.Varint).int64(message.beforeDate);
17904
+ if (message.deleteReplyThreads !== false)
17905
+ writer.tag(3, import_runtime.WireType.Varint).bool(message.deleteReplyThreads);
17906
+ if (message.deletedChatIds.length) {
17907
+ writer.tag(5, import_runtime.WireType.LengthDelimited).fork();
17908
+ for (let i = 0;i < message.deletedChatIds.length; i++)
17909
+ writer.int64(message.deletedChatIds[i]);
17910
+ writer.join();
17911
+ }
17912
+ if (message.orphanedChatIds.length) {
17913
+ writer.tag(6, import_runtime.WireType.LengthDelimited).fork();
17914
+ for (let i = 0;i < message.orphanedChatIds.length; i++)
17915
+ writer.int64(message.orphanedChatIds[i]);
17916
+ writer.join();
17917
+ }
17918
+ if (message.detachedChatIds.length) {
17919
+ writer.tag(7, import_runtime.WireType.LengthDelimited).fork();
17920
+ for (let i = 0;i < message.detachedChatIds.length; i++)
17921
+ writer.int64(message.detachedChatIds[i]);
17922
+ writer.join();
17923
+ }
17924
+ let u = options.writeUnknownFields;
17925
+ if (u !== false)
17926
+ (u == true ? import_runtime2.UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
17927
+ return writer;
17928
+ }
17929
+ }
17930
+ var UpdateClearChatHistory = new UpdateClearChatHistory$Type;
17931
+
17106
17932
  class UpdateMessageId$Type extends import_runtime4.MessageType {
17107
17933
  constructor() {
17108
17934
  super("UpdateMessageId", [
@@ -19243,7 +20069,7 @@ function describeConnectionError(error) {
19243
20069
  return `server connection error${code != null ? ` (code=${code})` : ""}: ${message}`;
19244
20070
  }
19245
20071
 
19246
- // ../../node_modules/.bun/ws@8.20.1/node_modules/ws/wrapper.mjs
20072
+ // ../../node_modules/.bun/ws@8.21.0/node_modules/ws/wrapper.mjs
19247
20073
  var import_stream = __toESM(require_stream(), 1);
19248
20074
  var import_extension = __toESM(require_extension(), 1);
19249
20075
  var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
@@ -19537,7 +20363,8 @@ var rpcInputKindByMethod = {
19537
20363
  37: "updateBotProfile",
19538
20364
  38: "getMessages",
19539
20365
  48: "invokeMessageAction",
19540
- 49: "answerMessageAction"
20366
+ 49: "answerMessageAction",
20367
+ 53: "clearChatHistory"
19541
20368
  };
19542
20369
  var rpcResultKindByMethod = {
19543
20370
  0: undefined,
@@ -19580,7 +20407,8 @@ var rpcResultKindByMethod = {
19580
20407
  37: "updateBotProfile",
19581
20408
  38: "getMessages",
19582
20409
  48: "invokeMessageAction",
19583
- 49: "answerMessageAction"
20410
+ 49: "answerMessageAction",
20411
+ 53: "clearChatHistory"
19584
20412
  };
19585
20413
 
19586
20414
  // ../sdk/dist/sdk/logger.js
@@ -19617,6 +20445,7 @@ var defaultApiBaseUrl = "https://api.inline.chat";
19617
20445
  var defaultVideoWidth = 1280;
19618
20446
  var defaultVideoHeight = 720;
19619
20447
  var defaultVideoDuration = 1;
20448
+ var defaultCatchUpPageLimit = 200;
19620
20449
  var defaultCatchUpTotalLimit = 1000;
19621
20450
  var defaultColdStartCatchUpWindow = defaultCatchUpTotalLimit;
19622
20451
  function extractFirstMessageId(updates) {
@@ -19755,7 +20584,12 @@ class InlineSdkClient {
19755
20584
  const chat = result.getChat.chat;
19756
20585
  if (!chat)
19757
20586
  throw new Error("getChat: missing chat");
19758
- return { chatId: chat.id, peer: chat.peerId, title: chat.title };
20587
+ return {
20588
+ chatId: chat.id,
20589
+ peer: chat.peerId,
20590
+ title: chat.title,
20591
+ ...chat.lastMsgId != null ? { lastMsgId: chat.lastMsgId } : {}
20592
+ };
19759
20593
  }
19760
20594
  async getMessages(params) {
19761
20595
  const peerId = this.inputPeerFromTarget(params, "getMessages");
@@ -19769,6 +20603,18 @@ class InlineSdkClient {
19769
20603
  });
19770
20604
  return { messages: result.getMessages.messages };
19771
20605
  }
20606
+ async clearChatHistory(params) {
20607
+ const keepLastDays = normalizeKeepLastDays(params.keepLastDays);
20608
+ const target = this.clearHistoryTargetFromParams(params);
20609
+ await this.invoke(Method.CLEAR_CHAT_HISTORY, {
20610
+ oneofKind: "clearChatHistory",
20611
+ clearChatHistory: {
20612
+ target,
20613
+ keepLastDays,
20614
+ deleteReplyThreads: params.deleteReplyThreads ?? false
20615
+ }
20616
+ });
20617
+ }
19772
20618
  async sendMessage(params) {
19773
20619
  if (params.entities != null && params.parseMarkdown != null) {
19774
20620
  throw new Error("sendMessage: provide either `entities` or `parseMarkdown`, not both");
@@ -20070,6 +20916,36 @@ class InlineSdkClient {
20070
20916
  });
20071
20917
  return;
20072
20918
  }
20919
+ case "clearChatHistory": {
20920
+ const payload = update.update.clearChatHistory;
20921
+ if (payload.target.oneofKind === "spaceId") {
20922
+ await this.eventStream.send({
20923
+ kind: "space.history.clear",
20924
+ spaceId: payload.target.spaceId,
20925
+ ...payload.beforeDate != null ? { beforeDate: payload.beforeDate } : {},
20926
+ deleteReplyThreads: payload.deleteReplyThreads,
20927
+ seq,
20928
+ date
20929
+ });
20930
+ return;
20931
+ }
20932
+ const peerId = payload.target.oneofKind === "peerId" ? payload.target.peerId : undefined;
20933
+ const chatId = peerId?.type.oneofKind === "chat" ? peerId.type.chat.chatId : null;
20934
+ if (!chatId) {
20935
+ this.log.warn?.("Skipping clearChatHistory update without chat peer", peerId);
20936
+ return;
20937
+ }
20938
+ this.bumpChatSeq(chatId, seq);
20939
+ await this.eventStream.send({
20940
+ kind: "message.history.clear",
20941
+ chatId,
20942
+ ...payload.beforeDate != null ? { beforeDate: payload.beforeDate } : {},
20943
+ deleteReplyThreads: payload.deleteReplyThreads,
20944
+ seq,
20945
+ date
20946
+ });
20947
+ return;
20948
+ }
20073
20949
  case "updateReaction": {
20074
20950
  const reaction = update.update.updateReaction.reaction;
20075
20951
  if (!reaction)
@@ -20213,7 +21089,8 @@ class InlineSdkClient {
20213
21089
  }
20214
21090
  }),
20215
21091
  startSeq: BigInt(cursor),
20216
- totalLimit: defaultCatchUpTotalLimit
21092
+ totalLimit: defaultCatchUpTotalLimit,
21093
+ limit: defaultCatchUpPageLimit
20217
21094
  })
20218
21095
  });
20219
21096
  const payload = result.getUpdates;
@@ -20310,7 +21187,8 @@ class InlineSdkClient {
20310
21187
  }),
20311
21188
  startSeq: BigInt(cursor),
20312
21189
  seqEnd: BigInt(endSeq),
20313
- totalLimit: defaultCatchUpTotalLimit
21190
+ totalLimit: defaultCatchUpTotalLimit,
21191
+ limit: defaultCatchUpPageLimit
20314
21192
  })
20315
21193
  });
20316
21194
  const payload = result.getUpdates;
@@ -20374,6 +21252,18 @@ class InlineSdkClient {
20374
21252
  type: { oneofKind: "chat", chat: { chatId: asInlineId(params.chatId, "chatId") } }
20375
21253
  });
20376
21254
  }
21255
+ clearHistoryTargetFromParams(params) {
21256
+ const hasChatId = params.chatId != null;
21257
+ const hasUserId = params.userId != null;
21258
+ const hasSpaceId = params.spaceId != null;
21259
+ if ([hasChatId, hasUserId, hasSpaceId].filter(Boolean).length !== 1) {
21260
+ throw new Error("clearChatHistory: provide exactly one of `chatId`, `userId`, or `spaceId`");
21261
+ }
21262
+ if (hasSpaceId) {
21263
+ return { oneofKind: "spaceId", spaceId: asInlineId(params.spaceId, "spaceId") };
21264
+ }
21265
+ return { oneofKind: "peerId", peerId: this.inputPeerFromTarget(params, "clearChatHistory") };
21266
+ }
20377
21267
  async loadState() {
20378
21268
  const store = this.options.state;
20379
21269
  if (!store)
@@ -20550,6 +21440,12 @@ function normalizePositiveInt(value, field) {
20550
21440
  }
20551
21441
  return value;
20552
21442
  }
21443
+ function normalizeKeepLastDays(value) {
21444
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 36500) {
21445
+ throw new Error("clearChatHistory: `keepLastDays` must be 0 or a positive integer up to 36500");
21446
+ }
21447
+ return value;
21448
+ }
20553
21449
  async function parseJsonResponse(response) {
20554
21450
  const contentType = response.headers.get("content-type") ?? "";
20555
21451
  if (!contentType.includes("application/json")) {
@@ -35203,10 +36099,15 @@ var InlineActionsSchema = exports_external.object({
35203
36099
  var InlineCapabilitiesSchema = exports_external.object({
35204
36100
  replyThreads: exports_external.boolean().optional()
35205
36101
  }).strict();
36102
+ var InlineReplyThreadModeSchema = exports_external.enum(["auto", "thread", "main"]);
35206
36103
  var InlineTargetSchema = exports_external.union([exports_external.string(), exports_external.number()]);
35207
36104
  var InlineAllowEntrySchema = exports_external.union([exports_external.string(), exports_external.number()]);
35208
36105
  var InlineGroupSchema = exports_external.object({
35209
36106
  requireMention: exports_external.boolean().optional(),
36107
+ replyThreadMode: InlineReplyThreadModeSchema.optional(),
36108
+ replyThreadAutoCreateMinMessages: exports_external.number().int().min(0).optional(),
36109
+ replyThreadRequireExplicitMention: exports_external.boolean().optional(),
36110
+ replyThreadParentHistoryLimit: exports_external.number().int().min(0).optional(),
35210
36111
  allowFrom: exports_external.array(InlineAllowEntrySchema).optional(),
35211
36112
  systemPrompt: exports_external.string().optional(),
35212
36113
  tools: ToolPolicySchema.optional(),
@@ -35246,6 +36147,7 @@ var InlineStreamingSchema = exports_external.union([
35246
36147
  label: exports_external.union([exports_external.string(), exports_external.literal(false)]).optional(),
35247
36148
  labels: exports_external.array(exports_external.string()).optional(),
35248
36149
  maxLines: exports_external.number().int().positive().optional(),
36150
+ maxLineChars: exports_external.number().int().positive().optional(),
35249
36151
  render: exports_external.enum(["text", "rich"]).optional(),
35250
36152
  toolProgress: exports_external.boolean().optional(),
35251
36153
  commandText: InlineStreamingCommandTextSchema.optional()
@@ -35273,6 +36175,7 @@ var InlineRuntimeStreamingSchema = exports_external.union([
35273
36175
  label: exports_external.union([exports_external.string(), exports_external.literal(false)]).optional(),
35274
36176
  labels: exports_external.array(exports_external.string()).optional(),
35275
36177
  maxLines: exports_external.number().int().positive().optional(),
36178
+ maxLineChars: exports_external.number().int().positive().optional(),
35276
36179
  render: exports_external.enum(["text", "rich"]).optional(),
35277
36180
  toolProgress: exports_external.boolean().optional(),
35278
36181
  commandText: InlineStreamingCommandTextSchema.optional()
@@ -35298,6 +36201,10 @@ var InlineAccountSchemaBase = exports_external.object({
35298
36201
  groupPolicy: GroupPolicySchema.optional().default("allowlist"),
35299
36202
  groups: exports_external.record(exports_external.string(), InlineGroupSchema.optional()).optional(),
35300
36203
  requireMention: exports_external.boolean().optional(),
36204
+ replyThreadMode: InlineReplyThreadModeSchema.optional(),
36205
+ replyThreadAutoCreateMinMessages: exports_external.number().int().min(0).optional(),
36206
+ replyThreadRequireExplicitMention: exports_external.boolean().optional(),
36207
+ replyThreadParentHistoryLimit: exports_external.number().int().min(0).optional(),
35301
36208
  replyToBotWithoutMention: exports_external.boolean().optional(),
35302
36209
  historyLimit: exports_external.number().int().min(0).optional(),
35303
36210
  dmHistoryLimit: exports_external.number().int().min(0).optional(),
@@ -35569,9 +36476,7 @@ function inspectInlineAccount(params) {
35569
36476
  }
35570
36477
  const tokenFile = account.tokenFile?.trim() ?? "";
35571
36478
  if (tokenFile) {
35572
- const token = tryReadSecretFileSync(tokenFile, "Inline bot token", {
35573
- rejectSymlink: true
35574
- }) ?? "";
36479
+ const token = tryReadInlineTokenFile(tokenFile);
35575
36480
  return {
35576
36481
  ...account,
35577
36482
  token: token || null,
@@ -35631,18 +36536,58 @@ async function resolveInlineToken(account) {
35631
36536
  }
35632
36537
  throw new Error("Inline token missing (set channels.inline.token, channels.inline.tokenFile, INLINE_TOKEN, or INLINE_BOT_TOKEN)");
35633
36538
  }
35634
- const token = tryReadSecretFileSync(tokenFile, "Inline bot token", {
35635
- rejectSymlink: true
35636
- });
36539
+ const token = readInlineTokenFile(tokenFile);
35637
36540
  if (!token)
35638
36541
  throw new Error(`Inline tokenFile is empty or unreadable: ${tokenFile}`);
35639
36542
  return token;
35640
36543
  }
36544
+ function tryReadInlineTokenFile(tokenFile) {
36545
+ try {
36546
+ return tryReadSecretFileSync(tokenFile, "Inline bot token", {
36547
+ rejectSymlink: true
36548
+ }) ?? "";
36549
+ } catch {
36550
+ return "";
36551
+ }
36552
+ }
36553
+ function readInlineTokenFile(tokenFile) {
36554
+ try {
36555
+ return tryReadSecretFileSync(tokenFile, "Inline bot token", {
36556
+ rejectSymlink: true
36557
+ }) ?? "";
36558
+ } catch (error51) {
36559
+ throw new Error(`Inline tokenFile is empty or unreadable: ${tokenFile}`, {
36560
+ cause: error51
36561
+ });
36562
+ }
36563
+ }
35641
36564
 
35642
36565
  // src/inline/reply-threads.ts
35643
36566
  var GET_CHAT_METHOD = typeof Method.GET_CHAT === "number" && Number.isInteger(Method.GET_CHAT) && Method.GET_CHAT > 0 ? Method.GET_CHAT : 25;
35644
36567
  var GET_CHAT_HISTORY_METHOD = typeof Method.GET_CHAT_HISTORY === "number" && Number.isInteger(Method.GET_CHAT_HISTORY) && Method.GET_CHAT_HISTORY > 0 ? Method.GET_CHAT_HISTORY : 5;
35645
36568
  var GET_MESSAGES_METHOD = typeof Method.GET_MESSAGES === "number" && Number.isInteger(Method.GET_MESSAGES) && Method.GET_MESSAGES > 0 ? Method.GET_MESSAGES : 38;
36569
+ var CREATE_SUBTHREAD_METHOD = typeof Method.CREATE_SUBTHREAD === "number" && Number.isInteger(Method.CREATE_SUBTHREAD) && Method.CREATE_SUBTHREAD > 0 ? Method.CREATE_SUBTHREAD : 42;
36570
+ function isPlacementMode(raw) {
36571
+ return raw === "thread" || raw === "main";
36572
+ }
36573
+ function hasReplyThreadConfig(config2) {
36574
+ if (isPlacementMode(config2.replyThreadMode))
36575
+ return true;
36576
+ if (typeof config2.replyThreadAutoCreateMinMessages === "number")
36577
+ return true;
36578
+ if (typeof config2.replyThreadRequireExplicitMention === "boolean")
36579
+ return true;
36580
+ if (typeof config2.replyThreadParentHistoryLimit === "number")
36581
+ return true;
36582
+ if (!config2.groups || typeof config2.groups !== "object" || Array.isArray(config2.groups))
36583
+ return false;
36584
+ return Object.values(config2.groups).some((group) => {
36585
+ if (!group || typeof group !== "object" || Array.isArray(group))
36586
+ return false;
36587
+ const groupConfig = group;
36588
+ return isPlacementMode(groupConfig.replyThreadMode) || typeof groupConfig.replyThreadAutoCreateMinMessages === "number" || typeof groupConfig.replyThreadRequireExplicitMention === "boolean" || typeof groupConfig.replyThreadParentHistoryLimit === "number";
36589
+ });
36590
+ }
35646
36591
  function buildChatPeer(chatId) {
35647
36592
  return {
35648
36593
  type: {
@@ -35657,7 +36602,7 @@ function getInlineReplyThreadsCapabilityConfig(params) {
35657
36602
  accountId: params.accountId ?? null
35658
36603
  });
35659
36604
  return {
35660
- replyThreads: account.config.capabilities?.replyThreads === true
36605
+ replyThreads: account.config.capabilities?.replyThreads === true || hasReplyThreadConfig(account.config)
35661
36606
  };
35662
36607
  }
35663
36608
  function isInlineReplyThreadsEnabled(params) {
@@ -35729,6 +36674,30 @@ async function loadInlineReplyThreadAnchorMessage(params) {
35729
36674
  }
35730
36675
  return (historyResult.getChatHistory.messages ?? []).find((item) => item.id === params.parentMessageId) ?? null;
35731
36676
  }
36677
+ async function createInlineReplyThreadForMessage(params) {
36678
+ const result = await params.client.invokeRaw(CREATE_SUBTHREAD_METHOD, {
36679
+ oneofKind: "createSubthread",
36680
+ createSubthread: {
36681
+ parentChatId: params.parentChatId,
36682
+ parentMessageId: params.parentMessageId,
36683
+ participants: []
36684
+ }
36685
+ });
36686
+ if (result.oneofKind !== "createSubthread") {
36687
+ return null;
36688
+ }
36689
+ const chat = result.createSubthread.chat;
36690
+ if (!chat?.id) {
36691
+ return null;
36692
+ }
36693
+ return {
36694
+ childChatId: chat.id,
36695
+ parentChatId: chat.parentChatId ?? params.parentChatId,
36696
+ parentMessageId: chat.parentMessageId ?? params.parentMessageId,
36697
+ title: chat.title?.trim() || null,
36698
+ anchorMessage: result.createSubthread.anchorMessage ?? null
36699
+ };
36700
+ }
35732
36701
 
35733
36702
  // src/inline/normalize.ts
35734
36703
  function normalizeInlineTarget(raw) {
@@ -35757,11 +36726,12 @@ function looksLikeInlineTargetId(raw, normalizedInput) {
35757
36726
 
35758
36727
  // src/inline/monitor.ts
35759
36728
  import { mkdir } from "node:fs/promises";
35760
- import path2 from "node:path";
36729
+ import path3 from "node:path";
35761
36730
  import {
35762
36731
  buildCommandTextFromArgs,
35763
36732
  findCommandByNativeName,
35764
36733
  formatCommandArgMenuTitle,
36734
+ listNativeCommandSpecsForConfig as listNativeCommandSpecsForConfig2,
35765
36735
  parseCommandArgs,
35766
36736
  resolveCommandArgMenu
35767
36737
  } from "openclaw/plugin-sdk/native-command-registry";
@@ -35778,7 +36748,9 @@ import {
35778
36748
  createTransportActivityStatusPatch
35779
36749
  } from "openclaw/plugin-sdk/gateway-runtime";
35780
36750
  import {
36751
+ classifyChannelInboundEvent,
35781
36752
  createChannelInboundDebouncer,
36753
+ resolveUnmentionedGroupInboundPolicy,
35782
36754
  shouldDebounceTextInbound
35783
36755
  } from "openclaw/plugin-sdk/channel-inbound";
35784
36756
  import {
@@ -35796,7 +36768,18 @@ import {
35796
36768
  } from "openclaw/plugin-sdk/config-runtime";
35797
36769
  import { buildModelsProviderData } from "openclaw/plugin-sdk/models-provider-runtime";
35798
36770
  import { listSkillCommandsForAgents as listSkillCommandsForAgents2 } from "openclaw/plugin-sdk/skill-commands-runtime";
36771
+ import { getPluginCommandSpecs as getPluginCommandSpecs2 } from "openclaw/plugin-sdk/plugin-runtime";
35799
36772
  import { isReasoningReplyPayload } from "openclaw/plugin-sdk/reply-payload";
36773
+ import {
36774
+ buildChannelProgressDraftLine,
36775
+ buildChannelProgressDraftLineForEntry,
36776
+ createChannelProgressDraftGate,
36777
+ formatChannelProgressDraftText,
36778
+ isChannelProgressDraftWorkToolName,
36779
+ mergeChannelProgressDraftLine,
36780
+ resolveChannelProgressDraftMaxLines,
36781
+ resolveChannelStreamingPreviewToolProgress
36782
+ } from "openclaw/plugin-sdk/channel-streaming";
35800
36783
  import {
35801
36784
  findCodeRegions,
35802
36785
  isInsideCode,
@@ -35805,8 +36788,6 @@ import {
35805
36788
  } from "openclaw/plugin-sdk/text-runtime";
35806
36789
 
35807
36790
  // src/sdk-runtime-compat.ts
35808
- var HISTORY_CONTEXT_MARKER = "[Chat messages since your last reply - for context]";
35809
- var CURRENT_MESSAGE_MARKER = "[Current message - respond to this]";
35810
36791
  var MAX_HISTORY_KEYS = 1000;
35811
36792
  var DEFAULT_GROUP_HISTORY_LIMIT = 50;
35812
36793
  function evictOldHistoryKeys(historyMap, maxKeys = MAX_HISTORY_KEYS) {
@@ -35822,20 +36803,6 @@ function evictOldHistoryKeys(historyMap, maxKeys = MAX_HISTORY_KEYS) {
35822
36803
  }
35823
36804
  }
35824
36805
  }
35825
- function buildHistoryContext(params) {
35826
- const lineBreak = params.lineBreak ?? `
35827
- `;
35828
- if (!params.historyText.trim()) {
35829
- return params.currentMessage;
35830
- }
35831
- return [
35832
- HISTORY_CONTEXT_MARKER,
35833
- params.historyText,
35834
- "",
35835
- CURRENT_MESSAGE_MARKER,
35836
- params.currentMessage
35837
- ].join(lineBreak);
35838
- }
35839
36806
  function appendHistoryEntry(params) {
35840
36807
  if (params.limit <= 0) {
35841
36808
  return [];
@@ -35852,32 +36819,6 @@ function appendHistoryEntry(params) {
35852
36819
  evictOldHistoryKeys(params.historyMap);
35853
36820
  return history;
35854
36821
  }
35855
- function buildHistoryContextFromEntries(params) {
35856
- const lineBreak = params.lineBreak ?? `
35857
- `;
35858
- const entries = params.excludeLast === false ? params.entries : params.entries.slice(0, -1);
35859
- if (entries.length === 0) {
35860
- return params.currentMessage;
35861
- }
35862
- return buildHistoryContext({
35863
- historyText: entries.map(params.formatEntry).join(lineBreak),
35864
- currentMessage: params.currentMessage,
35865
- lineBreak
35866
- });
35867
- }
35868
- function buildPendingHistoryContextFromMap(params) {
35869
- if (params.limit <= 0) {
35870
- return params.currentMessage;
35871
- }
35872
- const entries = params.historyMap.get(params.historyKey) ?? [];
35873
- return buildHistoryContextFromEntries({
35874
- entries,
35875
- currentMessage: params.currentMessage,
35876
- formatEntry: params.formatEntry,
35877
- ...params.lineBreak !== undefined ? { lineBreak: params.lineBreak } : {},
35878
- excludeLast: false
35879
- });
35880
- }
35881
36822
  function clearHistoryEntriesIfEnabled(params) {
35882
36823
  if (params.limit <= 0) {
35883
36824
  return;
@@ -36007,20 +36948,16 @@ import {
36007
36948
  import path from "node:path";
36008
36949
 
36009
36950
  // src/runtime.ts
36010
- var runtimeKey = "__inlineOpenClawRuntime";
36011
- function runtimeStore() {
36012
- return globalThis;
36013
- }
36014
- function setInlineRuntime(next) {
36015
- runtimeStore()[runtimeKey] = next;
36016
- }
36017
- function getInlineRuntime() {
36018
- const runtime = runtimeStore()[runtimeKey];
36019
- if (!runtime) {
36020
- throw new Error("Inline runtime not initialized");
36021
- }
36022
- return runtime;
36023
- }
36951
+ import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
36952
+ var {
36953
+ setRuntime: setInlineRuntime,
36954
+ clearRuntime: clearInlineRuntime,
36955
+ tryGetRuntime: getOptionalInlineRuntime,
36956
+ getRuntime: getInlineRuntime
36957
+ } = createPluginRuntimeStore({
36958
+ pluginId: "inline",
36959
+ errorMessage: "Inline runtime not initialized"
36960
+ });
36024
36961
 
36025
36962
  // src/inline/media.ts
36026
36963
  var DEFAULT_MEDIA_MAX_MB = 300;
@@ -36965,7 +37902,7 @@ for (const group of ACTION_GROUPS) {
36965
37902
  }
36966
37903
  var SUPPORTED_ACTIONS = Array.from(ACTION_TO_GATE_KEY.keys());
36967
37904
  var GET_MESSAGES_METHOD2 = typeof Method.GET_MESSAGES === "number" && Number.isInteger(Method.GET_MESSAGES) && Method.GET_MESSAGES > 0 ? Method.GET_MESSAGES : null;
36968
- var CREATE_SUBTHREAD_METHOD = typeof Method.CREATE_SUBTHREAD === "number" && Number.isInteger(Method.CREATE_SUBTHREAD) && Method.CREATE_SUBTHREAD > 0 ? Method.CREATE_SUBTHREAD : 43;
37905
+ var CREATE_SUBTHREAD_METHOD2 = typeof Method.CREATE_SUBTHREAD === "number" && Number.isInteger(Method.CREATE_SUBTHREAD) && Method.CREATE_SUBTHREAD > 0 ? Method.CREATE_SUBTHREAD : 42;
36969
37906
  var INLINE_ACTION_MAX_ROWS = 8;
36970
37907
  var INLINE_ACTION_MAX_PER_ROW = 8;
36971
37908
  function suppressedInternalTextResult() {
@@ -37211,6 +38148,20 @@ function resolveReactionMessageId(params) {
37211
38148
  }
37212
38149
  return;
37213
38150
  }
38151
+ function resolveThreadParentMessageId(params) {
38152
+ const explicit = readFlexibleId(params.args, "parentMessageId") ?? readFlexibleId(params.args, "messageId") ?? readFlexibleId(params.args, "replyTo") ?? readFlexibleId(params.args, "replyToId") ?? readStringParam(params.args, "parentMessageId") ?? readStringParam(params.args, "messageId") ?? readStringParam(params.args, "replyTo") ?? readStringParam(params.args, "replyToId");
38153
+ if (explicit)
38154
+ return explicit;
38155
+ const fromContext = params.toolContext?.currentMessageId;
38156
+ if (typeof fromContext === "number" && Number.isFinite(fromContext)) {
38157
+ return String(Math.trunc(fromContext));
38158
+ }
38159
+ if (typeof fromContext === "string") {
38160
+ const trimmed = fromContext.trim();
38161
+ return trimmed || undefined;
38162
+ }
38163
+ return;
38164
+ }
37214
38165
  function parseOptionalInlineId(raw, label) {
37215
38166
  if (raw == null)
37216
38167
  return;
@@ -38251,8 +39202,11 @@ var inlineMessageActions = {
38251
39202
  });
38252
39203
  if (replyThreadsEnabled) {
38253
39204
  const parentChatId = resolveChatIdFromParams(params);
38254
- const parentMessageId = parseOptionalInlineId(readFlexibleId(params, "parentMessageId") ?? readFlexibleId(params, "messageId") ?? readFlexibleId(params, "replyTo") ?? readFlexibleId(params, "replyToId") ?? readStringParam(params, "parentMessageId") ?? readStringParam(params, "messageId") ?? readStringParam(params, "replyTo") ?? readStringParam(params, "replyToId"), "parentMessageId");
38255
- const result2 = await client.invokeRaw(CREATE_SUBTHREAD_METHOD, {
39205
+ const parentMessageId = parseOptionalInlineId(resolveThreadParentMessageId({
39206
+ args: params,
39207
+ ...toolContext != null ? { toolContext: { currentMessageId: toolContext.currentMessageId } } : {}
39208
+ }), "parentMessageId");
39209
+ const result2 = await client.invokeRaw(CREATE_SUBTHREAD_METHOD2, {
38256
39210
  oneofKind: "createSubthread",
38257
39211
  createSubthread: {
38258
39212
  parentChatId,
@@ -38871,6 +39825,36 @@ function resolveInlineGroupRequireMention(params) {
38871
39825
  return defaultConfig.requireMention;
38872
39826
  return params.requireMentionDefault;
38873
39827
  }
39828
+ function resolveInlineGroupReplyThreadMode(params) {
39829
+ const groups = resolveInlineGroups(params.cfg, params.accountId);
39830
+ const groupConfig = resolveGroupConfig(groups, params.groupId);
39831
+ const defaultConfig = groups?.["*"];
39832
+ return groupConfig?.replyThreadMode ?? defaultConfig?.replyThreadMode ?? params.defaultMode;
39833
+ }
39834
+ function resolveInlineGroupReplyThreadAutoCreateMinMessages(params) {
39835
+ const groups = resolveInlineGroups(params.cfg, params.accountId);
39836
+ const groupConfig = resolveGroupConfig(groups, params.groupId);
39837
+ const defaultConfig = groups?.["*"];
39838
+ return groupConfig?.replyThreadAutoCreateMinMessages ?? defaultConfig?.replyThreadAutoCreateMinMessages ?? params.defaultMinMessages;
39839
+ }
39840
+ function resolveInlineGroupReplyThreadRequireExplicitMention(params) {
39841
+ const groups = resolveInlineGroups(params.cfg, params.accountId);
39842
+ const groupConfig = resolveGroupConfig(groups, params.groupId);
39843
+ const defaultConfig = groups?.["*"];
39844
+ if (typeof groupConfig?.replyThreadRequireExplicitMention === "boolean") {
39845
+ return groupConfig.replyThreadRequireExplicitMention;
39846
+ }
39847
+ if (typeof defaultConfig?.replyThreadRequireExplicitMention === "boolean") {
39848
+ return defaultConfig.replyThreadRequireExplicitMention;
39849
+ }
39850
+ return params.defaultRequireExplicitMention;
39851
+ }
39852
+ function resolveInlineGroupReplyThreadParentHistoryLimit(params) {
39853
+ const groups = resolveInlineGroups(params.cfg, params.accountId);
39854
+ const groupConfig = resolveGroupConfig(groups, params.groupId);
39855
+ const defaultConfig = groups?.["*"];
39856
+ return groupConfig?.replyThreadParentHistoryLimit ?? defaultConfig?.replyThreadParentHistoryLimit ?? params.defaultLimit;
39857
+ }
38874
39858
  function resolveInlineGroupSystemPrompt(params) {
38875
39859
  return resolveGroupConfig(params.groups, params.groupId)?.systemPrompt?.trim() || undefined;
38876
39860
  }
@@ -39069,6 +40053,134 @@ function buildInlineModelBrowseChannelData() {
39069
40053
  return inlineChannelData([[{ text: "Browse providers", callback_data: "mdl_prov" }]]);
39070
40054
  }
39071
40055
 
40056
+ // src/inline/thread-participation.ts
40057
+ import path2 from "node:path";
40058
+ import { resolveGlobalDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
40059
+ import { createPersistentDedupe } from "openclaw/plugin-sdk/persistent-dedupe";
40060
+ var TTL_MS = 24 * 60 * 60 * 1000;
40061
+ var MAX_ENTRIES = 5000;
40062
+ var PERSISTENT_MAX_ENTRIES = 1000;
40063
+ var PERSISTENT_NAMESPACE = "inline.thread-participation";
40064
+ var PERSISTENT_DEDUPE_NAMESPACE = "participation";
40065
+ var INLINE_THREAD_PARTICIPATION_KEY = Symbol.for("openclaw.inlineThreadParticipation");
40066
+ var threadParticipation = resolveGlobalDedupeCache(INLINE_THREAD_PARTICIPATION_KEY, {
40067
+ ttlMs: TTL_MS,
40068
+ maxSize: MAX_ENTRIES
40069
+ });
40070
+ var persistentStore;
40071
+ var persistentStoreDisabled = false;
40072
+ var persistentDedupe;
40073
+ function makeKey(accountId, parentChatId, threadId) {
40074
+ return `${accountId}:${String(parentChatId)}:${String(threadId)}`;
40075
+ }
40076
+ function safePathSegment(value) {
40077
+ return value.trim().replace(/[^a-z0-9._-]+/gi, "_").slice(0, 80) || "global";
40078
+ }
40079
+ function isExpectedOpenKeyedStoreUnavailable(error51) {
40080
+ return String(error51).includes("openKeyedStore is only available");
40081
+ }
40082
+ function reportPersistentThreadParticipationError(error51) {
40083
+ try {
40084
+ getOptionalInlineRuntime()?.logging.getChildLogger({ plugin: "inline", feature: "thread-participation-state" }).warn("Inline persistent thread participation state failed", { error: String(error51) });
40085
+ } catch {}
40086
+ }
40087
+ function disablePersistentThreadParticipation(error51) {
40088
+ persistentStoreDisabled = true;
40089
+ persistentStore = undefined;
40090
+ if (!isExpectedOpenKeyedStoreUnavailable(error51)) {
40091
+ reportPersistentThreadParticipationError(error51);
40092
+ }
40093
+ }
40094
+ function getPersistentThreadParticipationStore() {
40095
+ if (persistentStoreDisabled)
40096
+ return;
40097
+ if (persistentStore)
40098
+ return persistentStore;
40099
+ const runtime = getOptionalInlineRuntime();
40100
+ const openKeyedStore = runtime?.state?.openKeyedStore;
40101
+ if (typeof openKeyedStore !== "function")
40102
+ return;
40103
+ try {
40104
+ persistentStore = openKeyedStore({
40105
+ namespace: PERSISTENT_NAMESPACE,
40106
+ maxEntries: PERSISTENT_MAX_ENTRIES,
40107
+ defaultTtlMs: TTL_MS
40108
+ });
40109
+ return persistentStore;
40110
+ } catch (error51) {
40111
+ disablePersistentThreadParticipation(error51);
40112
+ return;
40113
+ }
40114
+ }
40115
+ function getPersistentThreadParticipationDedupe() {
40116
+ if (persistentDedupe)
40117
+ return persistentDedupe;
40118
+ const resolveStateDir = getOptionalInlineRuntime()?.state?.resolveStateDir;
40119
+ if (typeof resolveStateDir !== "function")
40120
+ return;
40121
+ try {
40122
+ const stateDir = resolveStateDir();
40123
+ persistentDedupe = createPersistentDedupe({
40124
+ ttlMs: TTL_MS,
40125
+ memoryMaxSize: MAX_ENTRIES,
40126
+ fileMaxEntries: PERSISTENT_MAX_ENTRIES,
40127
+ resolveFilePath: (namespace) => path2.join(stateDir, "inline", "thread-participation", `${safePathSegment(namespace)}.json`),
40128
+ onDiskError: reportPersistentThreadParticipationError
40129
+ });
40130
+ return persistentDedupe;
40131
+ } catch (error51) {
40132
+ reportPersistentThreadParticipationError(error51);
40133
+ return;
40134
+ }
40135
+ }
40136
+ function rememberPersistentThreadParticipation(params) {
40137
+ const store = getPersistentThreadParticipationStore();
40138
+ if (store) {
40139
+ store.register(params.key, {
40140
+ ...params.agentId ? { agentId: params.agentId } : {},
40141
+ repliedAt: Date.now()
40142
+ }, { ttlMs: TTL_MS }).catch(disablePersistentThreadParticipation);
40143
+ return;
40144
+ }
40145
+ getPersistentThreadParticipationDedupe()?.checkAndRecord(params.key, { namespace: PERSISTENT_DEDUPE_NAMESPACE }).catch(reportPersistentThreadParticipationError);
40146
+ }
40147
+ async function lookupPersistentThreadParticipation(key) {
40148
+ const store = getPersistentThreadParticipationStore();
40149
+ if (!store) {
40150
+ return await getPersistentThreadParticipationDedupe()?.hasRecent(key, { namespace: PERSISTENT_DEDUPE_NAMESPACE }).catch((error51) => {
40151
+ reportPersistentThreadParticipationError(error51);
40152
+ return false;
40153
+ }) ?? false;
40154
+ }
40155
+ try {
40156
+ return Boolean(await store.lookup(key));
40157
+ } catch (error51) {
40158
+ disablePersistentThreadParticipation(error51);
40159
+ return false;
40160
+ }
40161
+ }
40162
+ function recordInlineThreadParticipation(accountId, parentChatId, threadId, opts) {
40163
+ if (!accountId || parentChatId < 0n || threadId < 0n)
40164
+ return;
40165
+ const key = makeKey(accountId, parentChatId, threadId);
40166
+ threadParticipation.check(key);
40167
+ rememberPersistentThreadParticipation({
40168
+ key,
40169
+ ...opts?.agentId ? { agentId: opts.agentId } : {}
40170
+ });
40171
+ }
40172
+ async function hasInlineThreadParticipationWithPersistence(params) {
40173
+ if (!params.accountId || params.parentChatId < 0n || params.threadId < 0n)
40174
+ return false;
40175
+ const key = makeKey(params.accountId, params.parentChatId, params.threadId);
40176
+ if (threadParticipation.peek(key))
40177
+ return true;
40178
+ const found = await lookupPersistentThreadParticipation(key);
40179
+ if (found)
40180
+ threadParticipation.check(key);
40181
+ return found;
40182
+ }
40183
+
39072
40184
  // src/inline/bot-commands-sync.ts
39073
40185
  import { listNativeCommandSpecsForConfig } from "openclaw/plugin-sdk/native-command-registry";
39074
40186
  import { getPluginCommandSpecs } from "openclaw/plugin-sdk/plugin-runtime";
@@ -39174,12 +40286,12 @@ function shouldSyncInlineNativeCommandsForAccount(params) {
39174
40286
  const effective = params.account.config.commands?.native ?? params.cfg.commands?.native ?? "auto";
39175
40287
  return effective !== false;
39176
40288
  }
39177
- function shouldSyncInlineNativeSkills(params) {
40289
+ function shouldSyncInlineNativeSkillsForAccount(params) {
39178
40290
  const effective = params.account.config.commands?.nativeSkills ?? params.cfg.commands?.nativeSkills ?? "auto";
39179
40291
  return effective !== false;
39180
40292
  }
39181
40293
  async function buildInlineNativeCommandsForConfig(params) {
39182
- const route = shouldSyncInlineNativeSkills({ cfg: params.cfg, account: params.account }) ? resolveAgentRoute({
40294
+ const route = shouldSyncInlineNativeSkillsForAccount({ cfg: params.cfg, account: params.account }) ? resolveAgentRoute({
39183
40295
  cfg: params.cfg,
39184
40296
  channel: INLINE_NATIVE_COMMAND_PROVIDER,
39185
40297
  accountId: params.account.accountId
@@ -39296,6 +40408,23 @@ var INLINE_NATIVE_COMMAND_PROVIDER2 = CHANNEL_ID;
39296
40408
  var INLINE_NATIVE_COMMAND_CALLBACK_PREFIX = "icmd:";
39297
40409
  var INLINE_REQUEST_ERROR_FALLBACK = "OpenClaw could not process that request. Please try again.";
39298
40410
  var INLINE_DEBOUNCE_ERROR_FALLBACK = "OpenClaw could not process those messages. Please try again.";
40411
+ var DEFAULT_REPLY_THREAD_AUTO_CREATE_MIN_MESSAGES = 50;
40412
+ var DEFAULT_REPLY_THREAD_PARENT_HISTORY_LIMIT = 10;
40413
+ function buildInlineTypingDispatcherOptions(typingCallbacks) {
40414
+ if (!typingCallbacks) {
40415
+ return {};
40416
+ }
40417
+ return {
40418
+ typingCallbacks,
40419
+ onReplyStart: typingCallbacks.onReplyStart,
40420
+ ...typingCallbacks.onIdle ? { onIdle: typingCallbacks.onIdle } : {},
40421
+ ...typingCallbacks.onCleanup ? { onCleanup: typingCallbacks.onCleanup } : {}
40422
+ };
40423
+ }
40424
+ function buildInlineReplyThreadSessionKey(parentSessionKey, threadChatId) {
40425
+ const suffix = `:thread:${String(threadChatId)}`;
40426
+ return parentSessionKey.endsWith(suffix) ? parentSessionKey : `${parentSessionKey}${suffix}`;
40427
+ }
39299
40428
  function summarizeSdkMeta(meta3) {
39300
40429
  if (meta3 == null)
39301
40430
  return "";
@@ -39318,6 +40447,7 @@ function formatSdkLogLine(message, meta3) {
39318
40447
  }
39319
40448
  var DEFAULT_DM_HISTORY_LIMIT = 6;
39320
40449
  var HISTORY_LINE_MAX_CHARS = 280;
40450
+ var REPLY_THREAD_LABEL_MAX_CHARS = 72;
39321
40451
  var URL_LIKE_PATTERN = /https?:\/\/\S+/i;
39322
40452
  var BOT_MESSAGE_CACHE_LIMIT = 500;
39323
40453
  var REACTION_TARGET_LOOKUP_LIMIT = 8;
@@ -39582,6 +40712,11 @@ function findInlineNativeCommandFromBody(commandBody) {
39582
40712
  return null;
39583
40713
  return findCommandByNativeName(match[1], INLINE_NATIVE_COMMAND_PROVIDER2) ?? null;
39584
40714
  }
40715
+ function resolveInlineCommandNameFromBody(commandBody) {
40716
+ const match = commandBody.trim().match(/^\/([^\s]+)(?:\s+[\s\S]*)?$/);
40717
+ const raw = match?.[1]?.trim().toLowerCase();
40718
+ return raw || null;
40719
+ }
39585
40720
  function buildInlineNativeCommandCallbackData(commandText) {
39586
40721
  return `${INLINE_NATIVE_COMMAND_CALLBACK_PREFIX}${commandText}`;
39587
40722
  }
@@ -39598,7 +40733,29 @@ function isInlineNativeCommandBody(params) {
39598
40733
  if (!shouldSyncInlineNativeCommandsForAccount({ cfg: params.cfg, account: params.account })) {
39599
40734
  return false;
39600
40735
  }
39601
- return findInlineNativeCommandFromBody(params.commandBody) != null;
40736
+ const commandName = resolveInlineCommandNameFromBody(params.commandBody);
40737
+ if (!commandName)
40738
+ return false;
40739
+ const skillCommands = shouldSyncInlineNativeSkillsForAccount({
40740
+ cfg: params.cfg,
40741
+ account: params.account
40742
+ }) ? listSkillCommandsForAgents2({
40743
+ cfg: params.cfg,
40744
+ agentIds: [params.agentId]
40745
+ }) : [];
40746
+ const commandSpecs = listNativeCommandSpecsForConfig2(params.cfg, {
40747
+ skillCommands,
40748
+ provider: INLINE_NATIVE_COMMAND_PROVIDER2
40749
+ });
40750
+ for (const spec of commandSpecs) {
40751
+ if (spec.name.trim().toLowerCase() === commandName)
40752
+ return true;
40753
+ }
40754
+ for (const spec of getPluginCommandSpecs2("inline", { config: params.cfg })) {
40755
+ if (spec.name.trim().toLowerCase() === commandName)
40756
+ return true;
40757
+ }
40758
+ return false;
39602
40759
  }
39603
40760
  function escapeInlineRegExp(raw) {
39604
40761
  return raw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -39636,10 +40793,12 @@ function resolveInlineMentionSource(params) {
39636
40793
  return "explicit_bot";
39637
40794
  if (params.shouldBypassMention)
39638
40795
  return "command_bypass";
39639
- if (params.patternMentioned || params.wasMentioned)
40796
+ if (params.patternMentioned)
39640
40797
  return "mention_pattern";
39641
40798
  if (params.implicitMention)
39642
40799
  return "implicit_thread";
40800
+ if (params.wasMentioned)
40801
+ return "mention_pattern";
39643
40802
  return "none";
39644
40803
  }
39645
40804
  function callbackDataToBase64(data) {
@@ -39693,9 +40852,12 @@ function normalizeInlineStreamingMode(value) {
39693
40852
  return null;
39694
40853
  }
39695
40854
  }
39696
- function resolveInlineStreamingMode(config2) {
40855
+ function resolveExplicitInlineStreamingMode(config2) {
39697
40856
  const streaming = isRecord4(config2.streaming) ? config2.streaming : null;
39698
- const mode = normalizeInlineStreamingMode(streaming?.mode) ?? normalizeInlineStreamingMode(config2.streaming) ?? normalizeInlineStreamingMode(config2.streamMode);
40857
+ return normalizeInlineStreamingMode(streaming?.mode) ?? normalizeInlineStreamingMode(config2.streaming) ?? normalizeInlineStreamingMode(config2.streamMode);
40858
+ }
40859
+ function resolveInlineStreamingMode(config2) {
40860
+ const mode = resolveExplicitInlineStreamingMode(config2);
39699
40861
  if (mode)
39700
40862
  return mode;
39701
40863
  if (typeof config2.streaming === "boolean") {
@@ -39703,6 +40865,18 @@ function resolveInlineStreamingMode(config2) {
39703
40865
  }
39704
40866
  return config2.streamViaEditMessage === true ? "partial" : "off";
39705
40867
  }
40868
+ function resolveInlineProgressPlaceholderEnabled(config2) {
40869
+ const mode = resolveExplicitInlineStreamingMode(config2);
40870
+ if (mode === "off")
40871
+ return false;
40872
+ if (mode === "progress")
40873
+ return true;
40874
+ if (config2.streaming === false)
40875
+ return false;
40876
+ if (isRecord4(config2.streaming) && isRecord4(config2.streaming.progress))
40877
+ return true;
40878
+ return config2.streaming === undefined && config2.streamMode === undefined && config2.streamViaEditMessage !== true;
40879
+ }
39706
40880
  function resolveInlineBlockStreamingEnabled(config2) {
39707
40881
  const mode = resolveInlineStreamingMode(config2);
39708
40882
  const streaming = isRecord4(config2.streaming) ? config2.streaming : null;
@@ -39717,6 +40891,9 @@ function resolveInlineBlockStreamingEnabled(config2) {
39717
40891
  return false;
39718
40892
  return;
39719
40893
  }
40894
+ function shouldStartInlineProgressPlaceholderNow(line) {
40895
+ return typeof line === "object" && line?.kind === "patch" && Boolean(line.detail);
40896
+ }
39720
40897
  function resolveInlineCommandMenuModelContext(params) {
39721
40898
  if (!params.sessionKey.trim()) {
39722
40899
  return {};
@@ -40041,10 +41218,19 @@ function rememberBotMessageId(cache, chatId, messageId) {
40041
41218
  }
40042
41219
  cache.set(key, list);
40043
41220
  }
41221
+ function rememberInlineBotDelivery(params) {
41222
+ rememberBotMessageId(params.botMessageIdsByChat, params.chatId, params.messageId);
41223
+ if (!params.replyThreadContext || params.chatId !== params.replyThreadContext.childChatId)
41224
+ return;
41225
+ recordInlineThreadParticipation(params.accountId, params.replyThreadContext.parentChatId, params.replyThreadContext.childChatId, { agentId: params.agentId });
41226
+ }
40044
41227
  function hasBotMessageId(cache, chatId, messageId) {
40045
41228
  const key = String(chatId);
40046
41229
  return (cache.get(key) ?? []).includes(String(messageId));
40047
41230
  }
41231
+ function hasKnownBotMessageInChat(cache, chatId) {
41232
+ return (cache.get(String(chatId)) ?? []).length > 0;
41233
+ }
40048
41234
  function rememberBotMessagesFromList(params) {
40049
41235
  for (const item of params.messages) {
40050
41236
  if (item.fromId === params.meId) {
@@ -40136,6 +41322,17 @@ function normalizeHistoryText(raw) {
40136
41322
  return compact;
40137
41323
  return `${compact.slice(0, HISTORY_LINE_MAX_CHARS - 1)}…`;
40138
41324
  }
41325
+ function buildInlineReplyThreadLabel(params) {
41326
+ const title = params.title?.trim();
41327
+ if (title)
41328
+ return title;
41329
+ if (!params.anchorMessage)
41330
+ return "Re: Message";
41331
+ const anchorText = buildInlineInboundBodyText(summarizeInlineMessageContent(params.anchorMessage)).replace(/\s+/g, " ").trim();
41332
+ if (!anchorText)
41333
+ return "Re: Message";
41334
+ return `Re: ${anchorText.slice(0, REPLY_THREAD_LABEL_MAX_CHARS)}`;
41335
+ }
40139
41336
  function drainCompleteParagraphs(buffer) {
40140
41337
  const paragraphs = [];
40141
41338
  let rest = buffer;
@@ -40283,6 +41480,24 @@ function prependLabeledHistoryLine(params) {
40283
41480
  return existingBody ? `${prefix}${params.line}
40284
41481
  ${existingBody}` : `${prefix}${params.line}`;
40285
41482
  }
41483
+ function stripLabeledHistoryHeading(text, heading) {
41484
+ if (!text)
41485
+ return null;
41486
+ const prefix = `${heading}
41487
+ `;
41488
+ const body = text.startsWith(prefix) ? text.slice(prefix.length) : text;
41489
+ return body.trim() || null;
41490
+ }
41491
+ function prependLabeledHistoryBlock(params) {
41492
+ const block = stripLabeledHistoryHeading(params.block, params.heading);
41493
+ if (!block)
41494
+ return params.existing;
41495
+ const prefix = `${params.heading}
41496
+ `;
41497
+ const existingBody = stripLabeledHistoryHeading(params.existing, params.heading);
41498
+ return existingBody ? `${prefix}${block}
41499
+ ${existingBody}` : `${prefix}${block}`;
41500
+ }
40286
41501
  function prependInlineReplyThreadAnchor(params) {
40287
41502
  const entry = buildInlineHistoryEntryPayload({
40288
41503
  message: params.anchorMessage,
@@ -40290,12 +41505,17 @@ function prependInlineReplyThreadAnchor(params) {
40290
41505
  meId: params.meId,
40291
41506
  syntheticMessageId: `anchor:${String(params.parentChatId)}:${String(params.anchorMessage.id)}`
40292
41507
  });
41508
+ const hasBotMessage = params.historyContext.hasBotMessage || params.anchorMessage.fromId === params.meId;
40293
41509
  if (!entry.inboundEntry || !entry.line) {
40294
- return params.historyContext;
41510
+ return {
41511
+ ...params.historyContext,
41512
+ hasBotMessage
41513
+ };
40295
41514
  }
40296
41515
  return {
40297
41516
  ...params.historyContext,
40298
41517
  inboundHistory: [entry.inboundEntry, ...params.historyContext.inboundHistory],
41518
+ hasBotMessage,
40299
41519
  historyText: prependLabeledHistoryLine({
40300
41520
  existing: params.historyContext.historyText,
40301
41521
  heading: "Recent thread messages (oldest -> newest):",
@@ -40313,61 +41533,51 @@ function prependInlineReplyThreadAnchor(params) {
40313
41533
  })
40314
41534
  };
40315
41535
  }
40316
- function buildInlineBodyForAgent(params) {
40317
- return [
40318
- params.rawBody,
40319
- params.currentAttachmentText && params.currentAttachmentText !== params.rawBody ? `Current media/attachments:
40320
- ${params.currentAttachmentText}` : null,
40321
- params.currentEntityText ? `Current message entities:
40322
- ${params.currentEntityText}` : null
40323
- ].filter(Boolean).join(`
40324
-
40325
- `) || params.rawBody;
40326
- }
40327
- function normalizeInlineAgentMetadataValue(value) {
40328
- if (typeof value === "boolean")
40329
- return value;
40330
- const normalized = value?.replace(/\r\n|\r|\n/g, " ").replace(/\s+/g, " ").trim();
40331
- return normalized || undefined;
41536
+ function prependInlineParentHistoryContext(params) {
41537
+ return {
41538
+ ...params.historyContext,
41539
+ inboundHistory: [
41540
+ ...params.parentHistoryContext.inboundHistory,
41541
+ ...params.historyContext.inboundHistory
41542
+ ],
41543
+ hasBotMessage: params.historyContext.hasBotMessage || params.parentHistoryContext.hasBotMessage,
41544
+ historyText: prependLabeledHistoryBlock({
41545
+ existing: params.historyContext.historyText,
41546
+ heading: "Recent thread messages (oldest -> newest):",
41547
+ block: params.parentHistoryContext.historyText
41548
+ }),
41549
+ attachmentText: prependLabeledHistoryBlock({
41550
+ existing: params.historyContext.attachmentText,
41551
+ heading: "Recent media/attachments:",
41552
+ block: params.parentHistoryContext.attachmentText
41553
+ }),
41554
+ entityText: prependLabeledHistoryBlock({
41555
+ existing: params.historyContext.entityText,
41556
+ heading: "Recent message entities:",
41557
+ block: params.parentHistoryContext.entityText
41558
+ })
41559
+ };
40332
41560
  }
40333
- function buildInlineBodyForAgentPrompt(params) {
40334
- const metadata = {
40335
- schema: "inline.current_message.v1",
40336
- channel: normalizeInlineAgentMetadataValue(params.channel),
40337
- surface: normalizeInlineAgentMetadataValue(params.surface),
40338
- chat_type: normalizeInlineAgentMetadataValue(params.chatType),
40339
- chat_id: normalizeInlineAgentMetadataValue(params.chatId),
40340
- chat_ref: normalizeInlineAgentMetadataValue(params.chatRef),
40341
- conversation_label: normalizeInlineAgentMetadataValue(params.conversationLabel),
40342
- message_id: normalizeInlineAgentMetadataValue(params.messageId),
40343
- event_type: normalizeInlineAgentMetadataValue(params.eventType),
40344
- sender_id: normalizeInlineAgentMetadataValue(params.senderId),
40345
- sender_label: normalizeInlineAgentMetadataValue(params.senderLabel),
40346
- sender_name: normalizeInlineAgentMetadataValue(params.senderName ?? undefined),
40347
- sender_username: normalizeInlineAgentMetadataValue(params.senderUsername ?? undefined),
40348
- was_mentioned: params.wasMentioned,
40349
- explicitly_mentioned_bot: params.explicitlyMentionedBot === undefined ? undefined : normalizeInlineAgentMetadataValue(params.explicitlyMentionedBot),
40350
- mentioned_user_ids: params.mentionedUserIds?.length ? [...params.mentionedUserIds] : undefined,
40351
- implicit_mention_kinds: params.implicitMentionKinds?.length ? [...params.implicitMentionKinds] : undefined,
40352
- mention_source: normalizeInlineAgentMetadataValue(params.mentionSource ?? undefined),
40353
- reply_to_id: normalizeInlineAgentMetadataValue(params.replyToId ?? undefined),
40354
- reply_to_sender_id: normalizeInlineAgentMetadataValue(params.replyToSenderId ?? undefined),
40355
- reply_to_was_bot: params.replyToWasBot === undefined ? undefined : normalizeInlineAgentMetadataValue(params.replyToWasBot),
40356
- thread_id: normalizeInlineAgentMetadataValue(params.threadId ?? undefined),
40357
- thread_label: normalizeInlineAgentMetadataValue(params.threadLabel ?? undefined),
40358
- message_action_interaction_id: normalizeInlineAgentMetadataValue(params.messageActionInteractionId ?? undefined),
40359
- message_action_id: normalizeInlineAgentMetadataValue(params.messageActionId ?? undefined)
40360
- };
40361
- const payload = Object.fromEntries(Object.entries(metadata).filter(([, value]) => value !== undefined));
40362
- return [
40363
- "Inline current message metadata (generated by the Inline channel adapter):",
40364
- "```json",
40365
- JSON.stringify(payload, null, 2),
40366
- "```",
40367
- params.body
40368
- ].filter(Boolean).join(`
40369
-
40370
- `);
41561
+ function buildInlineUntrustedStructuredContext(params) {
41562
+ const entries = [];
41563
+ const append = (label, type, summary) => {
41564
+ if (!summary)
41565
+ return;
41566
+ const normalized = normalizeHistoryText(summary);
41567
+ if (!normalized || normalized === params.currentBody)
41568
+ return;
41569
+ entries.push({
41570
+ label,
41571
+ source: CHANNEL_ID,
41572
+ type,
41573
+ payload: { summary: normalized }
41574
+ });
41575
+ };
41576
+ append("Current Inline media/attachments", "current_media_attachments", params.currentAttachmentText);
41577
+ append("Current Inline message entities", "current_message_entities", params.currentEntityText);
41578
+ append("Recent Inline media/attachments", "recent_media_attachments", params.historyAttachmentText);
41579
+ append("Recent Inline message entities", "recent_message_entities", params.historyEntityText);
41580
+ return entries;
40371
41581
  }
40372
41582
  function resolveInlineMediaMaxBytes(params) {
40373
41583
  return resolveChannelMediaMaxBytes({
@@ -40414,13 +41624,20 @@ function buildInlineInboundBodyText(content) {
40414
41624
  `).trim();
40415
41625
  return textWithPlaceholder || content.text;
40416
41626
  }
41627
+ function hasDownloadableInlineMedia(content) {
41628
+ if (!content)
41629
+ return false;
41630
+ if (content.media?.url)
41631
+ return true;
41632
+ return content.attachments.some((attachment) => attachment.kind === "urlPreview" && Boolean(attachment.previewImageUrl));
41633
+ }
40417
41634
  function resolveFilePathHint(params) {
40418
41635
  const preferred = params.preferredName?.trim();
40419
41636
  if (preferred)
40420
41637
  return preferred;
40421
41638
  try {
40422
41639
  const pathname = new URL(params.sourceUrl).pathname;
40423
- const base = path2.basename(pathname).trim();
41640
+ const base = path3.basename(pathname).trim();
40424
41641
  if (base)
40425
41642
  return base;
40426
41643
  } catch {}
@@ -40487,14 +41704,42 @@ async function resolveInlineInboundReplyThreadContext(params) {
40487
41704
  childChatId: metadata.childChatId,
40488
41705
  parentChatId: metadata.parentChatId,
40489
41706
  parentChatTitle: parentChatInfo.title ?? null,
40490
- threadLabel: metadata.title ?? params.chatInfo.title ?? null,
41707
+ parentMessageId: metadata.parentMessageId,
41708
+ threadLabel: buildInlineReplyThreadLabel({
41709
+ title: metadata.title ?? params.chatInfo.title ?? null,
41710
+ anchorMessage
41711
+ }),
40491
41712
  anchorMessage
40492
41713
  };
40493
41714
  }
40494
- async function buildHistoryContext2(params) {
41715
+ function normalizeInlineReplyThreadMode(raw) {
41716
+ return raw === "thread" || raw === "main" ? raw : "auto";
41717
+ }
41718
+ function shouldAutoCreateInlineReplyThread(params) {
41719
+ if (params.minMessages <= 0)
41720
+ return true;
41721
+ return params.messageId >= BigInt(params.minMessages);
41722
+ }
41723
+ async function buildReplyThreadParentHistoryContext(params) {
41724
+ if (params.parentHistoryLimit <= 0 || params.replyThreadContext.parentMessageId == null) {
41725
+ return null;
41726
+ }
41727
+ return buildHistoryContext({
41728
+ client: params.client,
41729
+ chatId: params.replyThreadContext.parentChatId,
41730
+ currentMessageId: params.replyThreadContext.parentMessageId,
41731
+ replyToMsgId: params.replyThreadContext.anchorMessage?.replyToMsgId,
41732
+ senderProfilesById: params.senderProfilesById,
41733
+ meId: params.meId,
41734
+ historyLimit: params.parentHistoryLimit,
41735
+ botMessageIdsByChat: params.botMessageIdsByChat
41736
+ });
41737
+ }
41738
+ async function buildHistoryContext(params) {
40495
41739
  const cachedReplyToBot = params.replyToMsgId != null && hasBotMessageId(params.botMessageIdsByChat, params.chatId, params.replyToMsgId);
40496
41740
  let repliedToBot = cachedReplyToBot;
40497
41741
  let replyToSenderId = null;
41742
+ let hasBotMessage = hasKnownBotMessageInChat(params.botMessageIdsByChat, params.chatId);
40498
41743
  let foundReplyTargetInHistory = false;
40499
41744
  const lines = [];
40500
41745
  const attachmentLines = [];
@@ -40510,6 +41755,7 @@ async function buildHistoryContext2(params) {
40510
41755
  if (messages) {
40511
41756
  for (const item of messages) {
40512
41757
  if (item.fromId === params.meId) {
41758
+ hasBotMessage = true;
40513
41759
  rememberBotMessageId(params.botMessageIdsByChat, params.chatId, item.id);
40514
41760
  }
40515
41761
  }
@@ -40552,6 +41798,7 @@ async function buildHistoryContext2(params) {
40552
41798
  if (replyTarget) {
40553
41799
  replyToSenderId = String(replyTarget.fromId);
40554
41800
  repliedToBot = replyTarget.fromId === params.meId;
41801
+ hasBotMessage = hasBotMessage || repliedToBot;
40555
41802
  } else if (!cachedReplyToBot) {
40556
41803
  repliedToBot = false;
40557
41804
  }
@@ -40565,7 +41812,8 @@ async function buildHistoryContext2(params) {
40565
41812
  `) : null,
40566
41813
  inboundHistory,
40567
41814
  repliedToBot,
40568
- replyToSenderId
41815
+ replyToSenderId,
41816
+ hasBotMessage
40569
41817
  };
40570
41818
  }
40571
41819
  return {
@@ -40580,7 +41828,8 @@ ${entityLines.slice(-ATTACHMENT_CONTEXT_LIMIT).join(`
40580
41828
  `)}` : null,
40581
41829
  inboundHistory,
40582
41830
  repliedToBot,
40583
- replyToSenderId
41831
+ replyToSenderId,
41832
+ hasBotMessage
40584
41833
  };
40585
41834
  }
40586
41835
  async function monitorInlineProvider(params) {
@@ -40591,8 +41840,8 @@ async function monitorInlineProvider(params) {
40591
41840
  }
40592
41841
  const token = await resolveInlineToken(account);
40593
41842
  const stateDir = core3.state.resolveStateDir();
40594
- const statePath = path2.join(stateDir, "channels", "inline", `${account.accountId}.json`);
40595
- await mkdir(path2.dirname(statePath), { recursive: true });
41843
+ const statePath = path3.join(stateDir, "channels", "inline", `${account.accountId}.json`);
41844
+ await mkdir(path3.dirname(statePath), { recursive: true });
40596
41845
  let client = null;
40597
41846
  const pushDiagnostics = (patch) => {
40598
41847
  statusSink?.({
@@ -40770,7 +42019,7 @@ async function monitorInlineProvider(params) {
40770
42019
  chatInfo: effectiveChatInfo,
40771
42020
  effectiveChatId
40772
42021
  }),
40773
- sessionKey: route2.sessionKey
42022
+ sessionKey: replyThreadContext ? buildInlineReplyThreadSessionKey(route2.sessionKey, replyThreadContext.childChatId) : route2.sessionKey
40774
42023
  };
40775
42024
  }
40776
42025
  const peerUserId = senderId ?? (chatInfo.peerUserId != null ? String(chatInfo.peerUserId) : null);
@@ -40869,18 +42118,19 @@ async function monitorInlineProvider(params) {
40869
42118
  senderName: senderProfile?.name ?? (chatInfo?.kind === "direct" ? chatInfo.title ?? undefined : undefined),
40870
42119
  senderUsername: senderProfile?.username
40871
42120
  });
42121
+ const eventOptions = {
42122
+ sessionKey: ingress.sessionKey,
42123
+ contextKey: buildInlineReactionContextKey(params2),
42124
+ forceSenderIsOwnerFalse: true,
42125
+ trusted: false
42126
+ };
40872
42127
  core3.system.enqueueSystemEvent(describeInlineReactionSystemEvent({
40873
42128
  action: params2.action,
40874
42129
  emoji: params2.emoji,
40875
42130
  senderLabel,
40876
42131
  channelLabel: ingress.channelLabel,
40877
42132
  messageId: params2.messageId
40878
- }), {
40879
- sessionKey: ingress.sessionKey,
40880
- contextKey: buildInlineReactionContextKey(params2),
40881
- forceSenderIsOwnerFalse: true,
40882
- trusted: false
40883
- });
42133
+ }), eventOptions);
40884
42134
  };
40885
42135
  const shouldQueueInlineReactionSystemEvent = async (params2) => {
40886
42136
  const mode = account.config.reactionNotifications ?? "own";
@@ -40956,6 +42206,30 @@ async function monitorInlineProvider(params) {
40956
42206
  });
40957
42207
  const effectiveChatId = replyThreadContext?.parentChatId ?? chatId;
40958
42208
  const effectiveGroupTitle = replyThreadContext?.parentChatTitle ?? chatInfo.title ?? null;
42209
+ const replyThreadMode = isGroup && replyThreadsEnabled ? resolveInlineGroupReplyThreadMode({
42210
+ cfg,
42211
+ accountId: account.accountId,
42212
+ groupId: String(effectiveChatId),
42213
+ defaultMode: normalizeInlineReplyThreadMode(account.config.replyThreadMode)
42214
+ }) : "auto";
42215
+ const replyThreadAutoCreateMinMessages = isGroup && replyThreadsEnabled ? resolveInlineGroupReplyThreadAutoCreateMinMessages({
42216
+ cfg,
42217
+ accountId: account.accountId,
42218
+ groupId: String(effectiveChatId),
42219
+ defaultMinMessages: account.config.replyThreadAutoCreateMinMessages ?? DEFAULT_REPLY_THREAD_AUTO_CREATE_MIN_MESSAGES
42220
+ }) : DEFAULT_REPLY_THREAD_AUTO_CREATE_MIN_MESSAGES;
42221
+ const replyThreadRequireExplicitMention = isGroup && replyThreadsEnabled ? resolveInlineGroupReplyThreadRequireExplicitMention({
42222
+ cfg,
42223
+ accountId: account.accountId,
42224
+ groupId: String(effectiveChatId),
42225
+ defaultRequireExplicitMention: account.config.replyThreadRequireExplicitMention ?? false
42226
+ }) : false;
42227
+ const replyThreadParentHistoryLimit = isGroup && replyThreadsEnabled ? resolveInlineGroupReplyThreadParentHistoryLimit({
42228
+ cfg,
42229
+ accountId: account.accountId,
42230
+ groupId: String(effectiveChatId),
42231
+ defaultLimit: account.config.replyThreadParentHistoryLimit ?? DEFAULT_REPLY_THREAD_PARENT_HISTORY_LIMIT
42232
+ }) : DEFAULT_REPLY_THREAD_PARENT_HISTORY_LIMIT;
40959
42233
  const senderId = String(msg.fromId);
40960
42234
  await hydrateChatParticipants(chatId);
40961
42235
  const senderProfile = senderProfilesById.get(senderId);
@@ -40963,18 +42237,7 @@ async function monitorInlineProvider(params) {
40963
42237
  const senderName = senderProfile?.name ?? (!isGroup ? chatInfo.title ?? undefined : undefined);
40964
42238
  if (callbackActionEvent) {
40965
42239
  const actor = senderUsername != null && senderUsername.length > 0 ? `@${senderUsername}` : senderName ?? `user:${senderId}`;
40966
- const payload = {
40967
- type: "inline_message_action_callback",
40968
- interaction_id: String(callbackActionEvent.interactionId),
40969
- actor_user_id: senderId,
40970
- chat_id: String(chatId),
40971
- message_id: String(callbackActionEvent.targetMessageId),
40972
- action_id: callbackActionEvent.actionId,
40973
- data_base64: callbackDataToBase64(callbackActionEvent.data),
40974
- data_utf8: callbackDataToUtf8(callbackActionEvent.data) ?? null
40975
- };
40976
- rawBody = `${actor} pressed a button on message #${String(callbackActionEvent.targetMessageId)}
40977
- ${JSON.stringify(payload)}`;
42240
+ rawBody = `${actor} pressed "${callbackActionEvent.actionId}" on message #${String(callbackActionEvent.targetMessageId)}`;
40978
42241
  }
40979
42242
  const dmPolicy = account.config.dmPolicy ?? "pairing";
40980
42243
  const defaultGroupPolicy = cfg.channels?.defaults?.groupPolicy;
@@ -41017,9 +42280,36 @@ ${JSON.stringify(payload)}`;
41017
42280
  }
41018
42281
  const shouldEditCallbackTargetInPlace = callbackActionEvent != null;
41019
42282
  const normalizedCommandBody = callbackCommandBody ?? normalizeInlineCommandBody(rawBody, botUsername);
42283
+ const route = core3.channel.routing.resolveAgentRoute({
42284
+ cfg,
42285
+ channel: CHANNEL_ID,
42286
+ accountId: account.accountId,
42287
+ peer: {
42288
+ kind: isGroup ? "group" : "direct",
42289
+ id: isGroup ? String(effectiveChatId) : senderId
42290
+ }
42291
+ });
42292
+ const inboundSessionKey = replyThreadContext && isGroup ? buildInlineReplyThreadSessionKey(route.sessionKey, replyThreadContext.childChatId) : route.sessionKey;
42293
+ const rememberSentBotMessage = (params2) => {
42294
+ if (params2.messageId == null)
42295
+ return;
42296
+ rememberInlineBotDelivery({
42297
+ botMessageIdsByChat,
42298
+ chatId: params2.chatId,
42299
+ messageId: params2.messageId,
42300
+ accountId: account.accountId,
42301
+ agentId: route.agentId,
42302
+ replyThreadContext: params2.replyThreadContext ?? null
42303
+ });
42304
+ };
41020
42305
  const nativeCallbackCommandBody = callbackActionEvent ? parseInlineNativeCommandCallbackData(callbackDataToUtf8(callbackActionEvent.data)) : null;
41021
42306
  const hasControlCommand = core3.channel.text.hasControlCommand(callbackCommandBody ?? rawBody, cfg, botUsername ? { botUsername } : undefined);
41022
- const commandSource = hasControlCommand ? (nativeCallbackCommandBody != null || !callbackActionEvent) && isInlineNativeCommandBody({ cfg, account, commandBody: normalizedCommandBody }) ? "native" : "text" : undefined;
42307
+ const commandSource = hasControlCommand ? (nativeCallbackCommandBody != null || !callbackActionEvent) && isInlineNativeCommandBody({
42308
+ cfg,
42309
+ account,
42310
+ commandBody: normalizedCommandBody,
42311
+ agentId: route.agentId
42312
+ }) ? "native" : "text" : undefined;
41023
42313
  const allowTextCommands = core3.channel.commands.shouldHandleTextCommands({
41024
42314
  cfg,
41025
42315
  surface: CHANNEL_ID,
@@ -41130,21 +42420,13 @@ ${JSON.stringify(payload)}`;
41130
42420
  });
41131
42421
  return;
41132
42422
  }
41133
- const route = core3.channel.routing.resolveAgentRoute({
41134
- cfg,
41135
- channel: CHANNEL_ID,
41136
- accountId: account.accountId,
41137
- peer: {
41138
- kind: isGroup ? "group" : "direct",
41139
- id: isGroup ? String(effectiveChatId) : senderId
41140
- }
41141
- });
41142
42423
  const mentionRegexes = core3.channel.mentions.buildMentionRegexes(cfg, route.agentId);
41143
42424
  const nativeMentioned = typeof msg.mentioned === "boolean" ? msg.mentioned : false;
41144
42425
  const patternMentioned = mentionRegexes.length ? core3.channel.mentions.matchesMentionPatterns(rawBody, mentionRegexes) : false;
41145
42426
  const wasMentioned = nativeMentioned || patternMentioned;
41146
42427
  const messageTimestamp = Number(msg.date) * 1000;
41147
- const groupHistoryKey = isGroup ? replyThreadContext ? `${route.sessionKey}:thread:${String(replyThreadContext.childChatId)}` : route.sessionKey : null;
42428
+ const pendingReplyThreadContext = replyThreadContext;
42429
+ const pendingGroupHistoryKey = isGroup ? pendingReplyThreadContext ? inboundSessionKey : route.sessionKey : null;
41148
42430
  const senderLabel = resolveInlineSenderLabel({
41149
42431
  senderId,
41150
42432
  senderName,
@@ -41157,7 +42439,7 @@ ${JSON.stringify(payload)}`;
41157
42439
  historyLimit: account.config.historyLimit,
41158
42440
  dmHistoryLimit: account.config.dmHistoryLimit
41159
42441
  });
41160
- const historyContext = await buildHistoryContext2({
42442
+ const historyContext = await buildHistoryContext({
41161
42443
  client,
41162
42444
  chatId,
41163
42445
  currentMessageId: msg.id,
@@ -41174,17 +42456,25 @@ ${JSON.stringify(payload)}`;
41174
42456
  entityText: null,
41175
42457
  inboundHistory: [],
41176
42458
  repliedToBot: false,
41177
- replyToSenderId: null
42459
+ replyToSenderId: null,
42460
+ hasBotMessage: false
41178
42461
  };
41179
42462
  });
41180
- const effectiveHistoryContext = replyThreadContext?.anchorMessage != null ? prependInlineReplyThreadAnchor({
42463
+ let effectiveHistoryContext = replyThreadContext?.anchorMessage != null ? prependInlineReplyThreadAnchor({
41181
42464
  historyContext,
41182
42465
  anchorMessage: replyThreadContext.anchorMessage,
41183
42466
  parentChatId: replyThreadContext.parentChatId,
41184
42467
  senderProfilesById,
41185
42468
  meId
41186
42469
  }) : historyContext;
41187
- const implicitMention = callbackActionEvent != null && isGroup || isGroup && (account.config.replyToBotWithoutMention ?? false) && msg.replyToMsgId != null && effectiveHistoryContext.repliedToBot;
42470
+ const hasReplyThreadParticipation = isGroup && replyThreadContext != null && !replyThreadRequireExplicitMention && (effectiveHistoryContext.hasBotMessage || await hasInlineThreadParticipationWithPersistence({
42471
+ accountId: account.accountId,
42472
+ parentChatId: replyThreadContext.parentChatId,
42473
+ threadId: replyThreadContext.childChatId
42474
+ }));
42475
+ const replyThreadImplicitMention = hasReplyThreadParticipation;
42476
+ const replyToBotImplicitMention = isGroup && (account.config.replyToBotWithoutMention ?? false) && msg.replyToMsgId != null && effectiveHistoryContext.repliedToBot;
42477
+ const implicitMention = callbackActionEvent != null && isGroup || replyThreadImplicitMention || replyToBotImplicitMention;
41188
42478
  const requireMention = isGroup ? resolveInlineGroupRequireMention({
41189
42479
  cfg,
41190
42480
  groupId: String(effectiveChatId),
@@ -41203,7 +42493,8 @@ ${JSON.stringify(payload)}`;
41203
42493
  });
41204
42494
  const implicitMentionKinds = isGroup && implicitMention ? [
41205
42495
  ...callbackActionEvent != null ? ["message_action"] : [],
41206
- ...msg.replyToMsgId != null && effectiveHistoryContext.repliedToBot ? ["reply_to_bot"] : []
42496
+ ...replyThreadImplicitMention ? ["reply_thread"] : [],
42497
+ ...replyToBotImplicitMention ? ["reply_to_bot"] : []
41207
42498
  ] : [];
41208
42499
  const mentionedUserIds = isGroup ? collectInlineMentionedUserIds(currentContent) : [];
41209
42500
  const mentionSource = isGroup ? resolveInlineMentionSource({
@@ -41218,9 +42509,9 @@ ${JSON.stringify(payload)}`;
41218
42509
  const pendingBody = normalizeHistoryText(currentContent?.text) ?? normalizeHistoryText(rawBody);
41219
42510
  recordPendingHistoryEntryIfEnabled({
41220
42511
  historyMap: groupPendingHistories,
41221
- historyKey: groupHistoryKey ?? "",
42512
+ historyKey: pendingGroupHistoryKey ?? "",
41222
42513
  limit: historyLimit,
41223
- entry: groupHistoryKey && pendingBody ? {
42514
+ entry: pendingGroupHistoryKey && pendingBody ? {
41224
42515
  sender: pendingHistorySender,
41225
42516
  body: pendingBody,
41226
42517
  timestamp: messageTimestamp || Date.now(),
@@ -41276,9 +42567,7 @@ ${JSON.stringify(payload)}`;
41276
42567
  actions,
41277
42568
  parseMarkdown
41278
42569
  });
41279
- if (sent.messageId != null) {
41280
- rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
41281
- }
42570
+ rememberSentBotMessage({ chatId, messageId: sent.messageId, replyThreadContext });
41282
42571
  }
41283
42572
  statusSink?.({ lastOutboundAt: Date.now() });
41284
42573
  return;
@@ -41287,7 +42576,7 @@ ${JSON.stringify(payload)}`;
41287
42576
  commandBody: normalizedCommandBody,
41288
42577
  cfg,
41289
42578
  agentId: route.agentId,
41290
- sessionKey: route.sessionKey
42579
+ sessionKey: inboundSessionKey
41291
42580
  });
41292
42581
  if (nativeCommandMenu) {
41293
42582
  const menuActions = resolveInlineReplyActions({
@@ -41325,9 +42614,7 @@ ${JSON.stringify(payload)}`;
41325
42614
  text: menuText,
41326
42615
  ...menuActions ? { actions: menuActions } : {}
41327
42616
  });
41328
- if (sent.messageId != null) {
41329
- rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
41330
- }
42617
+ rememberSentBotMessage({ chatId, messageId: sent.messageId, replyThreadContext });
41331
42618
  }
41332
42619
  statusSink?.({ lastOutboundAt: Date.now() });
41333
42620
  await answerCallbackIfNeeded().catch((error51) => {
@@ -41369,9 +42656,7 @@ ${JSON.stringify(payload)}`;
41369
42656
  actions,
41370
42657
  parseMarkdown
41371
42658
  });
41372
- if (sent.messageId != null) {
41373
- rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
41374
- }
42659
+ rememberSentBotMessage({ chatId, messageId: sent.messageId, replyThreadContext });
41375
42660
  }
41376
42661
  };
41377
42662
  const { byProvider, providers } = await buildModelsProviderData(cfg, route.agentId);
@@ -41403,11 +42688,11 @@ Select a provider:`, providerButtons);
41403
42688
  });
41404
42689
  const isDefaultSelection = selection.provider === resolvedDefault.provider && selection.model === resolvedDefault.model;
41405
42690
  await updateSessionStore(storePath2, (store) => {
41406
- const entry = store[route.sessionKey] ?? {
41407
- sessionId: route.sessionKey,
42691
+ const entry = store[inboundSessionKey] ?? {
42692
+ sessionId: inboundSessionKey,
41408
42693
  updatedAt: Date.now()
41409
42694
  };
41410
- store[route.sessionKey] = entry;
42695
+ store[inboundSessionKey] = entry;
41411
42696
  applyModelOverrideToSessionEntry({
41412
42697
  entry,
41413
42698
  selection: {
@@ -41432,12 +42717,93 @@ This model will be used for your next message.`, []);
41432
42717
  });
41433
42718
  return;
41434
42719
  }
42720
+ let deliveryReplyThreadContext = replyThreadContext;
42721
+ const shouldCreateDeliveryThread = isGroup && replyThreadsEnabled && replyThreadMode === "thread" && !deliveryReplyThreadContext && shouldAutoCreateInlineReplyThread({
42722
+ messageId: msg.id,
42723
+ minMessages: replyThreadAutoCreateMinMessages
42724
+ }) && !shouldEditCallbackTargetInPlace;
42725
+ if (shouldCreateDeliveryThread) {
42726
+ const createdThread = await createInlineReplyThreadForMessage({
42727
+ client,
42728
+ parentChatId: effectiveChatId,
42729
+ parentMessageId: msg.id
42730
+ }).catch((error51) => {
42731
+ statusSink?.({ lastError: `createSubthread failed: ${String(error51)}` });
42732
+ runtime.error?.(`inline create reply thread failed: ${String(error51)}`);
42733
+ return null;
42734
+ });
42735
+ if (createdThread) {
42736
+ deliveryReplyThreadContext = {
42737
+ childChatId: createdThread.childChatId,
42738
+ parentChatId: createdThread.parentChatId,
42739
+ parentChatTitle: effectiveGroupTitle,
42740
+ parentMessageId: createdThread.parentMessageId,
42741
+ threadLabel: buildInlineReplyThreadLabel({
42742
+ title: createdThread.title,
42743
+ anchorMessage: createdThread.anchorMessage
42744
+ }),
42745
+ anchorMessage: createdThread.anchorMessage
42746
+ };
42747
+ }
42748
+ }
42749
+ if (shouldCreateDeliveryThread && !deliveryReplyThreadContext) {
42750
+ await answerCallbackIfNeeded().catch((error51) => {
42751
+ runtime.error?.(`inline callback answer failed: ${String(error51)}`);
42752
+ });
42753
+ return;
42754
+ }
42755
+ if (!replyThreadContext && deliveryReplyThreadContext?.anchorMessage != null) {
42756
+ effectiveHistoryContext = prependInlineReplyThreadAnchor({
42757
+ historyContext: {
42758
+ historyText: null,
42759
+ attachmentText: null,
42760
+ entityText: null,
42761
+ inboundHistory: [],
42762
+ repliedToBot: effectiveHistoryContext.repliedToBot,
42763
+ replyToSenderId: effectiveHistoryContext.replyToSenderId,
42764
+ hasBotMessage: effectiveHistoryContext.hasBotMessage
42765
+ },
42766
+ anchorMessage: deliveryReplyThreadContext.anchorMessage,
42767
+ parentChatId: deliveryReplyThreadContext.parentChatId,
42768
+ senderProfilesById,
42769
+ meId
42770
+ });
42771
+ }
42772
+ if (deliveryReplyThreadContext) {
42773
+ const parentHistoryContext = await buildReplyThreadParentHistoryContext({
42774
+ client,
42775
+ replyThreadContext: deliveryReplyThreadContext,
42776
+ parentHistoryLimit: replyThreadParentHistoryLimit,
42777
+ senderProfilesById,
42778
+ meId,
42779
+ botMessageIdsByChat
42780
+ }).catch((err) => {
42781
+ statusSink?.({ lastError: `getChatHistory (reply thread parent) failed: ${String(err)}` });
42782
+ return null;
42783
+ });
42784
+ if (parentHistoryContext) {
42785
+ effectiveHistoryContext = prependInlineParentHistoryContext({
42786
+ historyContext: effectiveHistoryContext,
42787
+ parentHistoryContext
42788
+ });
42789
+ }
42790
+ }
42791
+ const deliveryChatId = deliveryReplyThreadContext?.childChatId ?? chatId;
42792
+ const deliverySessionKey = deliveryReplyThreadContext && isGroup ? buildInlineReplyThreadSessionKey(route.sessionKey, deliveryReplyThreadContext.childChatId) : route.sessionKey;
42793
+ const groupHistoryKey = isGroup ? deliveryReplyThreadContext ? deliverySessionKey : route.sessionKey : null;
41435
42794
  const inboundMedia = await resolveInlineInboundMedia({
41436
42795
  core: core3,
41437
42796
  message: msg,
41438
42797
  maxBytes: inboundMediaMaxBytes,
41439
42798
  ...log ? { log } : {}
41440
42799
  });
42800
+ const inheritedAnchorMedia = deliveryReplyThreadContext?.anchorMessage != null && currentContent != null && !hasDownloadableInlineMedia(currentContent) ? await resolveInlineInboundMedia({
42801
+ core: core3,
42802
+ message: deliveryReplyThreadContext.anchorMessage,
42803
+ maxBytes: inboundMediaMaxBytes,
42804
+ ...log ? { log } : {}
42805
+ }) : [];
42806
+ const mediaForAgent = inboundMedia.length > 0 ? inboundMedia : inheritedAnchorMedia;
41441
42807
  const timestamp = messageTimestamp;
41442
42808
  const fromLabel = resolveInlineConversationLabel({
41443
42809
  isGroup,
@@ -41446,61 +42812,31 @@ This model will be used for your next message.`, []);
41446
42812
  senderLabel
41447
42813
  });
41448
42814
  const storePath = core3.channel.session.resolveStorePath(cfg.session?.store, { agentId: route.agentId });
41449
- const envelopeOptions = core3.channel.reply.resolveEnvelopeFormatOptions(cfg);
41450
- const previousTimestamp = core3.channel.session.readSessionUpdatedAt({ storePath, sessionKey: route.sessionKey });
41451
- const rawBodyForAgent = isGroup && wasMentioned ? stripInlineBotMention(rawBody, botUsername) : rawBody;
41452
- const currentEntityTextForAgent = isGroup && wasMentioned ? stripInlineBotMentionEntityText(currentEntityText, botUsername) : currentEntityText;
41453
- const currentBody = buildInlineBodyForAgent({
41454
- rawBody: rawBodyForAgent,
41455
- currentAttachmentText,
41456
- currentEntityText: currentEntityTextForAgent
41457
- });
41458
- const contextBody = [
41459
- effectiveHistoryContext.historyText,
41460
- effectiveHistoryContext.attachmentText,
41461
- effectiveHistoryContext.entityText
41462
- ].filter(Boolean).join(`
41463
-
41464
- `);
41465
- const currentEnvelope = core3.channel.reply.formatInboundEnvelope({
41466
- channel: "Inline",
41467
- from: fromLabel,
41468
- timestamp,
41469
- chatType: isGroup ? "group" : "direct",
41470
- sender: {
41471
- id: senderId,
41472
- ...senderName ? { name: senderName } : {},
41473
- ...senderUsername ? { username: senderUsername } : {}
41474
- },
41475
- ...previousTimestamp != null ? { previousTimestamp } : {},
41476
- envelope: envelopeOptions,
41477
- body: currentBody || rawBodyForAgent
41478
- });
41479
- let body = [contextBody, currentEnvelope].filter(Boolean).join(`
41480
-
41481
- `);
41482
- if (isGroup && groupHistoryKey) {
41483
- body = buildPendingHistoryContextFromMap({
41484
- historyMap: groupPendingHistories,
41485
- historyKey: groupHistoryKey,
41486
- limit: historyLimit,
41487
- currentMessage: body,
41488
- formatEntry: (entry) => core3.channel.reply.formatInboundEnvelope({
41489
- channel: "Inline",
41490
- from: fromLabel,
41491
- chatType: "group",
41492
- senderLabel: entry.sender,
41493
- ...entry.timestamp != null ? { timestamp: entry.timestamp } : {},
41494
- envelope: envelopeOptions,
41495
- body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} chat:${String(chatId)}]` : ""}`
41496
- })
41497
- });
41498
- }
42815
+ const rawBodyForAgent = isGroup && mentionGate.effectiveWasMentioned ? stripInlineBotMention(rawBody, botUsername) : rawBody;
42816
+ const currentEntityTextForAgent = isGroup && mentionGate.effectiveWasMentioned ? stripInlineBotMentionEntityText(currentEntityText, botUsername) : currentEntityText;
42817
+ const currentBody = rawBodyForAgent || rawBody;
41499
42818
  const inboundHistory = isGroup && groupHistoryKey ? mergeInboundHistoryEntries({
41500
42819
  historyContextEntries: effectiveHistoryContext.inboundHistory,
41501
42820
  pendingEntries: groupPendingHistories.get(groupHistoryKey) ?? [],
41502
42821
  limit: historyLimit
41503
- }) : [];
42822
+ }) : effectiveHistoryContext.inboundHistory;
42823
+ const untrustedStructuredContext = buildInlineUntrustedStructuredContext({
42824
+ currentAttachmentText,
42825
+ currentEntityText: currentEntityTextForAgent,
42826
+ currentBody,
42827
+ historyAttachmentText: effectiveHistoryContext.attachmentText,
42828
+ historyEntityText: effectiveHistoryContext.entityText
42829
+ });
42830
+ const inboundEventKind = classifyChannelInboundEvent({
42831
+ conversation: { kind: isGroup ? "group" : "direct" },
42832
+ unmentionedGroupPolicy: resolveUnmentionedGroupInboundPolicy({
42833
+ cfg,
42834
+ agentId: route.agentId
42835
+ }),
42836
+ ...isGroup ? { wasMentioned: mentionGate.effectiveWasMentioned } : {},
42837
+ hasControlCommand,
42838
+ ...commandSource ? { commandSource } : {}
42839
+ });
41504
42840
  const effectiveSurface = CHANNEL_ID;
41505
42841
  const systemPrompt = resolveInlineSystemPrompt({
41506
42842
  account,
@@ -41510,49 +42846,18 @@ This model will be used for your next message.`, []);
41510
42846
  msgId: msg.id,
41511
42847
  ...callbackActionEvent ? { callbackActionEvent } : {}
41512
42848
  });
41513
- const eventType = callbackActionEvent ? "message_action" : "message";
41514
- const bodyForAgent = buildInlineBodyForAgentPrompt({
41515
- body,
41516
- channel: CHANNEL_ID,
41517
- surface: effectiveSurface,
41518
- chatType: isGroup ? "group" : "direct",
41519
- chatId: String(effectiveChatId),
41520
- chatRef: `inline:${String(effectiveChatId)}`,
41521
- conversationLabel: fromLabel,
41522
- messageId: messageSid,
41523
- eventType,
41524
- senderId,
41525
- senderLabel,
41526
- wasMentioned: mentionGate.effectiveWasMentioned,
41527
- ...isGroup ? {
41528
- explicitlyMentionedBot: nativeMentioned,
41529
- mentionedUserIds,
41530
- implicitMentionKinds,
41531
- mentionSource
41532
- } : {},
41533
- ...senderName ? { senderName } : {},
41534
- ...senderUsername ? { senderUsername } : {},
41535
- ...msg.replyToMsgId != null ? { replyToId: String(msg.replyToMsgId) } : {},
41536
- ...effectiveHistoryContext.replyToSenderId != null ? { replyToSenderId: effectiveHistoryContext.replyToSenderId } : {},
41537
- ...msg.replyToMsgId != null ? { replyToWasBot: effectiveHistoryContext.repliedToBot } : {},
41538
- ...replyThreadContext ? { threadId: String(replyThreadContext.childChatId) } : {},
41539
- ...replyThreadContext?.threadLabel ? { threadLabel: replyThreadContext.threadLabel } : {},
41540
- ...callbackActionEvent ? {
41541
- messageActionInteractionId: String(callbackActionEvent.interactionId),
41542
- messageActionId: callbackActionEvent.actionId
41543
- } : {}
41544
- });
41545
42849
  const ctxPayload = core3.channel.reply.finalizeInboundContext({
41546
- Body: body,
41547
- BodyForAgent: bodyForAgent,
42850
+ Body: rawBody,
42851
+ InboundEventKind: inboundEventKind,
42852
+ BodyForAgent: currentBody,
41548
42853
  BodyForCommands: normalizedCommandBody,
41549
- ...isGroup ? { InboundHistory: inboundHistory } : {},
42854
+ InboundHistory: inboundHistory,
41550
42855
  RawBody: rawBody,
41551
42856
  CommandBody: normalizedCommandBody,
41552
42857
  From: isGroup ? `inline:chat:${String(effectiveChatId)}` : `inline:${senderId}`,
41553
42858
  To: `inline:${String(effectiveChatId)}`,
41554
- SessionKey: route.sessionKey,
41555
- ...replyThreadContext ? { ParentSessionKey: route.sessionKey } : {},
42859
+ SessionKey: deliverySessionKey,
42860
+ ...deliveryReplyThreadContext ? { ParentSessionKey: route.sessionKey } : {},
41556
42861
  AccountId: route.accountId,
41557
42862
  ChatType: isGroup ? "group" : "direct",
41558
42863
  ConversationLabel: fromLabel,
@@ -41575,20 +42880,21 @@ This model will be used for your next message.`, []);
41575
42880
  authorized: false,
41576
42881
  body: normalizedCommandBody
41577
42882
  },
41578
- ...replyThreadContext ? { MessageThreadId: String(replyThreadContext.childChatId) } : {},
41579
- ...replyThreadContext?.threadLabel ? { ThreadLabel: replyThreadContext.threadLabel } : {},
42883
+ ...deliveryReplyThreadContext ? { MessageThreadId: String(deliveryReplyThreadContext.childChatId) } : {},
42884
+ ...deliveryReplyThreadContext?.threadLabel ? { ThreadLabel: deliveryReplyThreadContext.threadLabel } : {},
41580
42885
  ...msg.replyToMsgId != null ? { ReplyToId: String(msg.replyToMsgId) } : {},
41581
42886
  ...effectiveHistoryContext.replyToSenderId != null ? { ReplyToSenderId: effectiveHistoryContext.replyToSenderId } : {},
41582
42887
  ...msg.replyToMsgId != null ? { ReplyToWasBot: effectiveHistoryContext.repliedToBot } : {},
42888
+ ...untrustedStructuredContext.length > 0 ? { UntrustedStructuredContext: untrustedStructuredContext } : {},
41583
42889
  ...callbackActionEvent ? {
41584
42890
  MessageActionInteractionId: String(callbackActionEvent.interactionId),
41585
42891
  MessageActionId: callbackActionEvent.actionId,
41586
42892
  MessageActionDataBase64: callbackDataToBase64(callbackActionEvent.data),
41587
42893
  ...callbackDataToUtf8(callbackActionEvent.data) ? { MessageActionDataUtf8: callbackDataToUtf8(callbackActionEvent.data) } : {}
41588
42894
  } : {},
41589
- ...buildInlineInboundMediaPayload(inboundMedia),
42895
+ ...buildInlineInboundMediaPayload(mediaForAgent),
41590
42896
  Timestamp: timestamp || Date.now(),
41591
- WasMentioned: mentionGate.effectiveWasMentioned,
42897
+ ...isGroup ? { WasMentioned: mentionGate.effectiveWasMentioned } : {},
41592
42898
  ...isGroup ? {
41593
42899
  ExplicitlyMentionedBot: nativeMentioned,
41594
42900
  ...mentionedUserIds.length > 0 ? { MentionedUserIds: mentionedUserIds } : {},
@@ -41602,7 +42908,7 @@ This model will be used for your next message.`, []);
41602
42908
  });
41603
42909
  await core3.channel.session.recordInboundSession({
41604
42910
  storePath,
41605
- sessionKey: ctxPayload.SessionKey ?? route.sessionKey,
42911
+ sessionKey: ctxPayload.SessionKey ?? deliverySessionKey,
41606
42912
  ctx: ctxPayload,
41607
42913
  ...!isGroup ? {
41608
42914
  updateLastRoute: {
@@ -41620,8 +42926,8 @@ This model will be used for your next message.`, []);
41620
42926
  channel: CHANNEL_ID,
41621
42927
  accountId: account.accountId,
41622
42928
  typing: {
41623
- start: () => client.sendTyping({ chatId, typing: true }),
41624
- stop: () => client.sendTyping({ chatId, typing: false }),
42929
+ start: () => client.sendTyping({ chatId: deliveryChatId, typing: true }),
42930
+ stop: () => client.sendTyping({ chatId: deliveryChatId, typing: false }),
41625
42931
  onStartError: (err) => runtime.error?.(`inline typing start failed: ${String(err)}`),
41626
42932
  onStopError: (err) => runtime.error?.(`inline typing stop failed: ${String(err)}`)
41627
42933
  }
@@ -41644,10 +42950,14 @@ This model will be used for your next message.`, []);
41644
42950
  botMessageIdsByChat
41645
42951
  }).catch(() => null) : null;
41646
42952
  const inlineStreamingMode = resolveInlineStreamingMode(account.config);
41647
- const streamViaEditMessage = (inlineStreamingMode === "partial" || inlineStreamingMode === "progress") && !shouldEditCallbackTargetInPlace;
41648
- const defaultReplyToMsgId = isGroup && msg.replyToMsgId != null ? msg.id : undefined;
42953
+ const streamViaEditMessage = inlineStreamingMode === "partial" && !shouldEditCallbackTargetInPlace;
42954
+ const progressPlaceholderEnabled = resolveInlineProgressPlaceholderEnabled(account.config) && !shouldEditCallbackTargetInPlace;
42955
+ const progressToolProgressEnabled = progressPlaceholderEnabled && resolveChannelStreamingPreviewToolProgress(account.config);
42956
+ const suppressDefaultToolProgressMessages = progressPlaceholderEnabled;
42957
+ const canReplyToSourceMessage = deliveryChatId === chatId;
42958
+ const defaultReplyToMsgId = canReplyToSourceMessage && isGroup && msg.replyToMsgId != null ? msg.id : undefined;
41649
42959
  const inlineBlockStreamingEnabled = resolveInlineBlockStreamingEnabled(account.config);
41650
- const disableBlockStreaming = streamViaEditMessage ? true : typeof inlineBlockStreamingEnabled === "boolean" ? !inlineBlockStreamingEnabled : undefined;
42960
+ const disableBlockStreaming = progressPlaceholderEnabled || streamViaEditMessage ? true : typeof inlineBlockStreamingEnabled === "boolean" ? !inlineBlockStreamingEnabled : undefined;
41651
42961
  const editStreamState = {
41652
42962
  messageId: shouldEditCallbackTargetInPlace ? callbackActionEvent?.targetMessageId ?? null : null,
41653
42963
  accumulatedText: callbackTargetMessage?.message ?? "",
@@ -41656,6 +42966,117 @@ This model will be used for your next message.`, []);
41656
42966
  failed: false,
41657
42967
  opChain: Promise.resolve()
41658
42968
  };
42969
+ const progressSeed = `${account.accountId}:${String(deliveryChatId)}:${String(msg.id)}`;
42970
+ const progressState = {
42971
+ messageId: null,
42972
+ text: "",
42973
+ lines: [],
42974
+ opChain: Promise.resolve(),
42975
+ closing: false
42976
+ };
42977
+ const renderInlineProgressPlaceholder = async () => {
42978
+ if (!progressPlaceholderEnabled || progressState.closing)
42979
+ return;
42980
+ const text = sanitizeInlineDeliveryText(formatChannelProgressDraftText({
42981
+ entry: account.config,
42982
+ lines: progressState.lines,
42983
+ seed: progressSeed
42984
+ })).trim();
42985
+ if (!text || text === progressState.text)
42986
+ return;
42987
+ progressState.opChain = progressState.opChain.then(async () => {
42988
+ if (progressState.closing || text === progressState.text)
42989
+ return;
42990
+ if (progressState.messageId == null) {
42991
+ const sent = await client.sendMessage({
42992
+ chatId: deliveryChatId,
42993
+ text,
42994
+ sendMode: "silent"
42995
+ });
42996
+ if (sent.messageId == null) {
42997
+ throw new Error("inline progress placeholder: sendMessage returned no messageId");
42998
+ }
42999
+ progressState.messageId = sent.messageId;
43000
+ rememberSentBotMessage({
43001
+ chatId: deliveryChatId,
43002
+ messageId: sent.messageId,
43003
+ replyThreadContext: deliveryReplyThreadContext
43004
+ });
43005
+ } else {
43006
+ const result = await client.invokeRaw(Method.EDIT_MESSAGE, {
43007
+ oneofKind: "editMessage",
43008
+ editMessage: {
43009
+ messageId: progressState.messageId,
43010
+ peerId: buildChatPeer3(deliveryChatId),
43011
+ text
43012
+ }
43013
+ });
43014
+ if (result.oneofKind !== "editMessage") {
43015
+ throw new Error(`inline progress placeholder: expected editMessage result, got ${String(result.oneofKind)}`);
43016
+ }
43017
+ }
43018
+ progressState.text = text;
43019
+ statusSink?.({ lastOutboundAt: Date.now() });
43020
+ }).catch((error51) => {
43021
+ runtime.error?.(`inline progress placeholder failed: ${String(error51)}`);
43022
+ });
43023
+ await progressState.opChain;
43024
+ };
43025
+ const progressDraftGate = createChannelProgressDraftGate({
43026
+ onStart: renderInlineProgressPlaceholder
43027
+ });
43028
+ const pushInlineProgressPlaceholder = async (line, options) => {
43029
+ if (!progressPlaceholderEnabled || progressState.closing)
43030
+ return;
43031
+ if (options?.toolName !== undefined && !isChannelProgressDraftWorkToolName(options.toolName)) {
43032
+ return;
43033
+ }
43034
+ const normalized = typeof line === "string" ? line.replace(/\s+/g, " ").trim() : line?.text.trim();
43035
+ if (line && !normalized)
43036
+ return;
43037
+ if (progressToolProgressEnabled && line && normalized) {
43038
+ const nextLines = mergeChannelProgressDraftLine(progressState.lines, line, {
43039
+ maxLines: resolveChannelProgressDraftMaxLines(account.config)
43040
+ });
43041
+ if (nextLines !== progressState.lines) {
43042
+ progressState.lines = nextLines;
43043
+ }
43044
+ }
43045
+ const alreadyStarted = progressDraftGate.hasStarted;
43046
+ if (options?.startImmediately || shouldStartInlineProgressPlaceholderNow(line)) {
43047
+ await progressDraftGate.startNow();
43048
+ } else {
43049
+ await progressDraftGate.noteWork();
43050
+ }
43051
+ if (alreadyStarted && progressDraftGate.hasStarted) {
43052
+ await renderInlineProgressPlaceholder();
43053
+ }
43054
+ };
43055
+ const cleanupInlineProgressPlaceholder = async () => {
43056
+ progressDraftGate.cancel();
43057
+ progressState.closing = true;
43058
+ await progressState.opChain;
43059
+ const messageId = progressState.messageId;
43060
+ if (messageId == null)
43061
+ return;
43062
+ try {
43063
+ const result = await client.invokeRaw(Method.DELETE_MESSAGES, {
43064
+ oneofKind: "deleteMessages",
43065
+ deleteMessages: {
43066
+ peerId: buildChatPeer3(deliveryChatId),
43067
+ messageIds: [messageId]
43068
+ }
43069
+ });
43070
+ if (result.oneofKind !== "deleteMessages") {
43071
+ throw new Error(`inline progress placeholder: expected deleteMessages result, got ${String(result.oneofKind)}`);
43072
+ }
43073
+ } catch (error51) {
43074
+ runtime.error?.(`inline progress placeholder cleanup failed: ${String(error51)}`);
43075
+ } finally {
43076
+ progressState.messageId = null;
43077
+ progressState.text = "";
43078
+ }
43079
+ };
41659
43080
  let finalDeliveredForCurrentAssistantMessage = false;
41660
43081
  const resetEditStreamForAssistantMessage = async () => {
41661
43082
  await editStreamState.opChain;
@@ -41697,7 +43118,7 @@ This model will be used for your next message.`, []);
41697
43118
  try {
41698
43119
  if (editStreamState.messageId == null) {
41699
43120
  const sent = await client.sendMessage({
41700
- chatId,
43121
+ chatId: deliveryChatId,
41701
43122
  text: nextText,
41702
43123
  ...defaultReplyToMsgId != null ? { replyToMsgId: defaultReplyToMsgId } : {},
41703
43124
  parseMarkdown
@@ -41706,13 +43127,17 @@ This model will be used for your next message.`, []);
41706
43127
  throw new Error("inline edit stream: sendMessage returned no messageId");
41707
43128
  }
41708
43129
  editStreamState.messageId = sent.messageId;
41709
- rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
43130
+ rememberSentBotMessage({
43131
+ chatId: deliveryChatId,
43132
+ messageId: sent.messageId,
43133
+ replyThreadContext: deliveryReplyThreadContext
43134
+ });
41710
43135
  } else {
41711
43136
  const result = await client.invokeRaw(Method.EDIT_MESSAGE, {
41712
43137
  oneofKind: "editMessage",
41713
43138
  editMessage: {
41714
43139
  messageId: editStreamState.messageId,
41715
- peerId: buildChatPeer3(chatId),
43140
+ peerId: buildChatPeer3(deliveryChatId),
41716
43141
  text: nextText,
41717
43142
  parseMarkdown
41718
43143
  }
@@ -41730,6 +43155,7 @@ This model will be used for your next message.`, []);
41730
43155
  });
41731
43156
  await editStreamState.opChain;
41732
43157
  };
43158
+ const buildInlineProgressLineForEntry = (input2, options) => buildChannelProgressDraftLineForEntry(account.config, input2, options);
41733
43159
  const replyOptions = {
41734
43160
  ...onModelSelected ? { onModelSelected } : {},
41735
43161
  blockReplyTimeoutMs: 25000,
@@ -41743,21 +43169,109 @@ This model will be used for your next message.`, []);
41743
43169
  await handlePartialStreamPayload(payload);
41744
43170
  }
41745
43171
  } : {},
41746
- ...streamViaEditMessage ? {
41747
- onToolStart: async () => {
43172
+ ...progressPlaceholderEnabled ? {
43173
+ onReasoningStream: async () => {
43174
+ await pushInlineProgressPlaceholder();
43175
+ }
43176
+ } : {},
43177
+ ...streamViaEditMessage || progressPlaceholderEnabled ? {
43178
+ onToolStart: async (payload) => {
41748
43179
  await resetEditStreamOnBoundary();
43180
+ const toolName = payload.name?.trim();
43181
+ await pushInlineProgressPlaceholder(buildInlineProgressLineForEntry({
43182
+ event: "tool",
43183
+ ...toolName ? { name: toolName } : {},
43184
+ ...payload.phase !== undefined ? { phase: payload.phase } : {},
43185
+ ...payload.args !== undefined ? { args: payload.args } : {}
43186
+ }, payload.detailMode ? { detailMode: payload.detailMode } : undefined), {
43187
+ ...toolName ? { toolName } : {},
43188
+ startImmediately: true
43189
+ });
41749
43190
  }
41750
43191
  } : {},
41751
- ...streamViaEditMessage ? {
43192
+ ...progressPlaceholderEnabled ? {
43193
+ onItemEvent: async (payload) => {
43194
+ await pushInlineProgressPlaceholder(buildInlineProgressLineForEntry({
43195
+ event: "item",
43196
+ ...payload.itemId !== undefined ? { itemId: payload.itemId } : {},
43197
+ ...payload.kind !== undefined ? { itemKind: payload.kind } : {},
43198
+ ...payload.title !== undefined ? { title: payload.title } : {},
43199
+ ...payload.name !== undefined ? { name: payload.name } : {},
43200
+ ...payload.phase !== undefined ? { phase: payload.phase } : {},
43201
+ ...payload.status !== undefined ? { status: payload.status } : {},
43202
+ ...payload.summary !== undefined ? { summary: payload.summary } : {},
43203
+ ...payload.progressText !== undefined ? { progressText: payload.progressText } : {},
43204
+ ...payload.meta !== undefined ? { meta: payload.meta } : {}
43205
+ }));
43206
+ },
43207
+ onPlanUpdate: async (payload) => {
43208
+ if (payload.phase !== "update")
43209
+ return;
43210
+ await pushInlineProgressPlaceholder(buildChannelProgressDraftLine({
43211
+ event: "plan",
43212
+ ...payload.phase !== undefined ? { phase: payload.phase } : {},
43213
+ ...payload.title !== undefined ? { title: payload.title } : {},
43214
+ ...payload.explanation !== undefined ? { explanation: payload.explanation } : {},
43215
+ ...payload.steps !== undefined ? { steps: payload.steps } : {}
43216
+ }));
43217
+ },
43218
+ onApprovalEvent: async (payload) => {
43219
+ if (payload.phase !== "requested")
43220
+ return;
43221
+ await pushInlineProgressPlaceholder(buildChannelProgressDraftLine({
43222
+ event: "approval",
43223
+ ...payload.phase !== undefined ? { phase: payload.phase } : {},
43224
+ ...payload.title !== undefined ? { title: payload.title } : {},
43225
+ ...payload.command !== undefined ? { command: payload.command } : {},
43226
+ ...payload.reason !== undefined ? { reason: payload.reason } : {},
43227
+ ...payload.message !== undefined ? { message: payload.message } : {}
43228
+ }), { startImmediately: true });
43229
+ },
43230
+ onCommandOutput: async (payload) => {
43231
+ if (payload.phase !== "end")
43232
+ return;
43233
+ await pushInlineProgressPlaceholder(buildChannelProgressDraftLine({
43234
+ event: "command-output",
43235
+ ...payload.phase !== undefined ? { phase: payload.phase } : {},
43236
+ ...payload.title !== undefined ? { title: payload.title } : {},
43237
+ ...payload.name !== undefined ? { name: payload.name } : {},
43238
+ ...payload.status !== undefined ? { status: payload.status } : {},
43239
+ ...payload.exitCode !== undefined ? { exitCode: payload.exitCode } : {}
43240
+ }));
43241
+ },
43242
+ onPatchSummary: async (payload) => {
43243
+ if (payload.phase !== "end")
43244
+ return;
43245
+ await pushInlineProgressPlaceholder(buildChannelProgressDraftLine({
43246
+ event: "patch",
43247
+ ...payload.phase !== undefined ? { phase: payload.phase } : {},
43248
+ ...payload.title !== undefined ? { title: payload.title } : {},
43249
+ ...payload.name !== undefined ? { name: payload.name } : {},
43250
+ ...payload.added !== undefined ? { added: payload.added } : {},
43251
+ ...payload.modified !== undefined ? { modified: payload.modified } : {},
43252
+ ...payload.deleted !== undefined ? { deleted: payload.deleted } : {},
43253
+ ...payload.summary !== undefined ? { summary: payload.summary } : {}
43254
+ }));
43255
+ }
43256
+ } : {},
43257
+ ...streamViaEditMessage || progressPlaceholderEnabled ? {
41752
43258
  onCompactionStart: async () => {
41753
43259
  await resetEditStreamOnBoundary();
43260
+ await pushInlineProgressPlaceholder("Compacting context", {
43261
+ startImmediately: true
43262
+ });
41754
43263
  }
41755
43264
  } : {},
41756
- ...streamViaEditMessage ? {
43265
+ ...streamViaEditMessage || progressPlaceholderEnabled ? {
41757
43266
  onCompactionEnd: async () => {
41758
43267
  await resetEditStreamOnBoundary();
43268
+ await pushInlineProgressPlaceholder("Resuming", {
43269
+ startImmediately: true
43270
+ });
41759
43271
  }
41760
43272
  } : {},
43273
+ ...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
43274
+ ...progressPlaceholderEnabled ? { allowProgressCallbacksWhenSourceDeliverySuppressed: true } : {},
41761
43275
  ...typeof disableBlockStreaming === "boolean" ? { disableBlockStreaming } : {}
41762
43276
  };
41763
43277
  try {
@@ -41771,11 +43285,12 @@ This model will be used for your next message.`, []);
41771
43285
  cfg,
41772
43286
  dispatcherOptions: {
41773
43287
  ...dispatcherPipelineOptions,
41774
- ...typingCallbacks ? { typingCallbacks } : {},
43288
+ ...buildInlineTypingDispatcherOptions(typingCallbacks),
41775
43289
  deliver: async (payload, info) => {
41776
43290
  const visiblePayload = resolveInlineChatVisibleReplyPayload(payload);
41777
43291
  if (!visiblePayload)
41778
43292
  return;
43293
+ await cleanupInlineProgressPlaceholder();
41779
43294
  const payloadRecord = visiblePayload;
41780
43295
  const rawText = resolveInlineInteractiveTextFallback({
41781
43296
  text: visiblePayload.text,
@@ -41789,23 +43304,25 @@ This model will be used for your next message.`, []);
41789
43304
  let replyToMsgId;
41790
43305
  if (visiblePayload.replyToId != null) {
41791
43306
  try {
41792
- replyToMsgId = BigInt(visiblePayload.replyToId);
43307
+ replyToMsgId = canReplyToSourceMessage ? BigInt(visiblePayload.replyToId) : undefined;
41793
43308
  } catch {}
41794
43309
  }
41795
- if (replyToMsgId == null && isGroup && msg.replyToMsgId != null) {
43310
+ if (replyToMsgId == null && canReplyToSourceMessage && isGroup && msg.replyToMsgId != null) {
41796
43311
  replyToMsgId = msg.id;
41797
43312
  }
41798
43313
  const rememberSent = (messageId) => {
41799
- if (messageId != null) {
41800
- rememberBotMessageId(botMessageIdsByChat, chatId, messageId);
41801
- }
43314
+ rememberSentBotMessage({
43315
+ chatId: deliveryChatId,
43316
+ messageId,
43317
+ replyThreadContext: deliveryReplyThreadContext
43318
+ });
41802
43319
  };
41803
43320
  const sendTextFallback = async (text, includeReplyTo, includeActions) => {
41804
43321
  const outbound = sanitizeInlineDeliveryText(text);
41805
43322
  if (!outbound.trim())
41806
43323
  return;
41807
43324
  const sent = await client.sendMessage({
41808
- chatId,
43325
+ chatId: deliveryChatId,
41809
43326
  text: outbound,
41810
43327
  ...includeReplyTo && replyToMsgId != null ? { replyToMsgId } : {},
41811
43328
  ...includeActions && outboundActions !== undefined ? { actions: outboundActions } : {},
@@ -41829,7 +43346,7 @@ This model will be used for your next message.`, []);
41829
43346
  oneofKind: "editMessage",
41830
43347
  editMessage: {
41831
43348
  messageId: editStreamState.messageId,
41832
- peerId: buildChatPeer3(chatId),
43349
+ peerId: buildChatPeer3(deliveryChatId),
41833
43350
  text: textForEdit,
41834
43351
  parseMarkdown,
41835
43352
  ...actions !== undefined ? { actions } : {}
@@ -41898,7 +43415,7 @@ This model will be used for your next message.`, []);
41898
43415
  mediaUrl
41899
43416
  });
41900
43417
  const sent = await client.sendMessage({
41901
- chatId,
43418
+ chatId: deliveryChatId,
41902
43419
  ...caption ? { text: caption } : {},
41903
43420
  media,
41904
43421
  ...isFirst && replyToMsgId != null ? { replyToMsgId } : {},
@@ -41933,20 +43450,23 @@ Attachment: ${mediaUrl}` : `Attachment: ${mediaUrl}`;
41933
43450
  dispatchError = error51;
41934
43451
  runtime.error?.(`inline dispatch failed: ${String(error51)}`);
41935
43452
  }
43453
+ await cleanupInlineProgressPlaceholder();
41936
43454
  if (!delivered && streamViaEditMessage && editStreamState.messageId != null) {
41937
43455
  delivered = true;
41938
43456
  }
41939
43457
  if (!delivered && (dispatchError != null || skippedNonSilent || failedNonSilent)) {
41940
43458
  const fallbackText = dispatchError != null ? INLINE_REQUEST_ERROR_FALLBACK : EMPTY_RESPONSE_FALLBACK;
41941
43459
  const sent = await client.sendMessage({
41942
- chatId,
43460
+ chatId: deliveryChatId,
41943
43461
  text: fallbackText,
41944
43462
  ...defaultReplyToMsgId != null ? { replyToMsgId: defaultReplyToMsgId } : {},
41945
43463
  parseMarkdown
41946
43464
  });
41947
- if (sent.messageId != null) {
41948
- rememberBotMessageId(botMessageIdsByChat, chatId, sent.messageId);
41949
- }
43465
+ rememberSentBotMessage({
43466
+ chatId: deliveryChatId,
43467
+ messageId: sent.messageId,
43468
+ replyThreadContext: deliveryReplyThreadContext
43469
+ });
41950
43470
  statusSink?.({ lastOutboundAt: Date.now() });
41951
43471
  }
41952
43472
  } finally {
@@ -43328,7 +44848,7 @@ var inlineNativeApprovalAdapter = splitChannelApprovalCapability(inlineApprovalC
43328
44848
  // src/inline/channel.ts
43329
44849
  var activeMonitors = new Map;
43330
44850
  function resolveInlineStatePath(accountId) {
43331
- return path3.join(getInlineRuntime().state.resolveStateDir(), "channels", "inline", `${accountId}.json`);
44851
+ return path4.join(getInlineRuntime().state.resolveStateDir(), "channels", "inline", `${accountId}.json`);
43332
44852
  }
43333
44853
  async function deleteInlineAccountState(accountId) {
43334
44854
  try {
@@ -44455,7 +45975,9 @@ var inlineChannelPlugin = {
44455
45975
  "- Inline history tools: `read` and `search` return media-aware message payloads (`media`, `attachments`, `attachmentUrls`) so image-only history remains discoverable. `search` is chat-scoped; run it per chat.",
44456
45976
  "- Inline special tools: use `inline_nudge` to send a nudge, and `inline_forward` to forward message ids between chats or users.",
44457
45977
  ...isInlineReplyThreadsEnabled({ cfg, accountId: accountId ?? null }) ? [
44458
- "- Inline reply threads are enabled: use `thread-reply` to send into a real reply thread, with `threadId` set to the reply-thread chat id."
45978
+ "- Inline reply threads are enabled: use `thread-create` to create a real reply thread under the current/target chat. On inbound turns, omit `messageId` to anchor it to the current message, or pass `messageId`/`parentMessageId` explicitly.",
45979
+ "- Inline reply threads are enabled: use `thread-reply` to send into a real reply thread, with `threadId` set to the reply-thread chat id returned by `thread-create`.",
45980
+ "- Inline reply-thread turns include nearby parent-chat context by default. If that context is incomplete, call `inline_parent_context` before answering."
44459
45981
  ] : [
44460
45982
  "- Inline reply threads are disabled: `thread-reply` uses the legacy reply path and `thread-create` creates a normal chat, not a dedicated Inline reply-thread chat."
44461
45983
  ]
@@ -44821,5 +46343,5 @@ export {
44821
46343
  inlineChannelPlugin
44822
46344
  };
44823
46345
 
44824
- //# debugId=3F378342A86B5C1E64756E2164756E21
46346
+ //# debugId=8D08B1A22511109264756E2164756E21
44825
46347
  //# sourceMappingURL=channel-plugin-api.js.map