@webex/internal-plugin-llm 3.12.0-next.67 → 3.12.0-next.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/llm.js CHANGED
@@ -1,35 +1,27 @@
1
1
  "use strict";
2
2
 
3
3
  var _Reflect$construct = require("@babel/runtime-corejs2/core-js/reflect/construct");
4
- var _Array$from = require("@babel/runtime-corejs2/core-js/array/from");
5
- var _Symbol = require("@babel/runtime-corejs2/core-js/symbol");
6
- var _Symbol$iterator = require("@babel/runtime-corejs2/core-js/symbol/iterator");
7
- var _Array$isArray = require("@babel/runtime-corejs2/core-js/array/is-array");
8
4
  var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
9
5
  var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
10
6
  _Object$defineProperty(exports, "__esModule", {
11
7
  value: true
12
8
  });
13
9
  exports.default = exports.config = void 0;
14
- var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));
15
- var _map = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/map"));
16
10
  var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));
17
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/slicedToArray"));
11
+ var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));
18
12
  var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/asyncToGenerator"));
19
13
  var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/classCallCheck"));
20
14
  var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/createClass"));
21
15
  var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/possibleConstructorReturn"));
22
16
  var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/getPrototypeOf"));
17
+ var _get2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/get"));
23
18
  var _inherits2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/inherits"));
24
- var _defineProperty3 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
19
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs2/helpers/defineProperty"));
25
20
  var _internalPluginMercury = _interopRequireDefault(require("@webex/internal-plugin-mercury"));
26
21
  var _constants = require("./constants");
27
- var _llm = require("./llm.types");
28
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && r[_Symbol$iterator] || r["@@iterator"]; if (!t) { if (_Array$isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
29
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
30
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
31
22
  function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? _Reflect$construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
32
- function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(_Reflect$construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } /* eslint-disable consistent-return */ // eslint-disable-next-line no-unused-vars
23
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(_Reflect$construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
24
+ function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; } /* eslint-disable consistent-return */
33
25
  var config = exports.config = {
34
26
  llm: {
35
27
  /**
@@ -62,7 +54,11 @@ var config = exports.config = {
62
54
  };
63
55
 
64
56
  /**
65
- * LLMChannel to provide socket connections
57
+ * LLMChannel — a single WebSocket connection to the LLM data channel.
58
+ *
59
+ * Created via `webex.internal.llm.createChannel()`. The caller owns the
60
+ * channel and is responsible for its lifecycle (connect, disconnect, cleanup).
61
+ * Multiple LLMChannels can exist simultaneously for different meetings.
66
62
  */
67
63
  var LLMChannel = exports.default = /*#__PURE__*/function (_ref) {
68
64
  function LLMChannel() {
@@ -72,34 +68,27 @@ var LLMChannel = exports.default = /*#__PURE__*/function (_ref) {
72
68
  args[_key] = arguments[_key];
73
69
  }
74
70
  _this = _callSuper(this, LLMChannel, [].concat(args));
75
- (0, _defineProperty3.default)(_this, "namespace", _constants.LLM);
76
- (0, _defineProperty3.default)(_this, "defaultSessionId", _constants.LLM_DEFAULT_SESSION);
77
- /**
78
- * Map to store connection-specific data for multiple LLM connections
79
- * Key: sessionId
80
- * @private
81
- * @type {Map<string, {webSocketUrl?: string; binding?: string; locusUrl?: string; datachannelUrl?: string}>}
82
- */
83
- (0, _defineProperty3.default)(_this, "connections", new _map.default());
84
- // Session-keyed token cache is intentionally decoupled from connection state.
85
- // Disconnecting a socket session must not implicitly wipe token cache.
86
- (0, _defineProperty3.default)(_this, "datachannelTokens", (0, _defineProperty3.default)((0, _defineProperty3.default)({}, _llm.DataChannelTokenType.Default, undefined), _llm.DataChannelTokenType.PracticeSession, undefined));
71
+ (0, _defineProperty2.default)(_this, "namespace", _constants.LLM);
72
+ (0, _defineProperty2.default)(_this, "webSocketUrl", void 0);
73
+ (0, _defineProperty2.default)(_this, "binding", void 0);
74
+ (0, _defineProperty2.default)(_this, "locusUrl", void 0);
75
+ (0, _defineProperty2.default)(_this, "datachannelUrl", void 0);
76
+ (0, _defineProperty2.default)(_this, "datachannelToken", void 0);
77
+ (0, _defineProperty2.default)(_this, "refreshHandler", void 0);
78
+ /** In-flight connection promise for deduplication. */
79
+ (0, _defineProperty2.default)(_this, "connectingPromise", void 0);
87
80
  /**
88
81
  * Register to the websocket
89
82
  * @param {string} llmSocketUrl
90
83
  * @param {string} datachannelToken
91
- * @param {string} sessionId - Connection identifier
92
- * @returns {Promise<void>}
84
+ * @returns {Promise<object>} Promise resolving to {webSocketUrl, binding}
93
85
  */
94
- (0, _defineProperty3.default)(_this, "register", /*#__PURE__*/function () {
86
+ (0, _defineProperty2.default)(_this, "register", /*#__PURE__*/function () {
95
87
  var _ref2 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(llmSocketUrl, datachannelToken) {
96
- var sessionId,
97
- isDataChannelTokenEnabled,
98
- _args = arguments;
88
+ var isDataChannelTokenEnabled;
99
89
  return _regenerator.default.wrap(function (_context) {
100
90
  while (1) switch (_context.prev = _context.next) {
101
91
  case 0:
102
- sessionId = _args.length > 2 && _args[2] !== undefined ? _args[2] : _constants.LLM_DEFAULT_SESSION;
103
92
  _context.next = 1;
104
93
  return _this.isDataChannelTokenEnabled();
105
94
  case 1:
@@ -114,13 +103,9 @@ var LLMChannel = exports.default = /*#__PURE__*/function (_ref) {
114
103
  'Data-Channel-Auth-Token': datachannelToken
115
104
  } : {}
116
105
  }).then(function (res) {
117
- // Get or create connection data
118
- var sessionData = _this.connections.get(sessionId) || {};
119
- sessionData.webSocketUrl = res.body.webSocketUrl;
120
- sessionData.binding = res.body.binding;
121
- _this.connections.set(sessionId, sessionData);
106
+ return res.body;
122
107
  }).catch(function (error) {
123
- _this.logger.error("Error connecting to websocket for ".concat(sessionId, ": ").concat(error));
108
+ _this.logger.error("Error connecting to websocket for : ".concat(error));
124
109
  throw error;
125
110
  }));
126
111
  case 2:
@@ -134,382 +119,196 @@ var LLMChannel = exports.default = /*#__PURE__*/function (_ref) {
134
119
  };
135
120
  }());
136
121
  /**
137
- * Register and connect to the websocket
122
+ * Register and connect to the websocket.
123
+ * Handles deduplication: returns existing promise if connection in progress,
124
+ * or resolves immediately if already connected to the same URLs.
138
125
  * @param {string} locusUrl
139
126
  * @param {string} datachannelUrl
140
127
  * @param {string} datachannelToken
141
- * @param {string} sessionId - Connection identifier
142
- * @returns {Promise<void>}
128
+ * @returns {Promise<RegisterAndConnectTiming | void>}
143
129
  */
144
- (0, _defineProperty3.default)(_this, "registerAndConnect", function (locusUrl, datachannelUrl, datachannelToken) {
145
- var sessionId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _constants.LLM_DEFAULT_SESSION;
146
- var registerStart = performance.now();
130
+ (0, _defineProperty2.default)(_this, "registerAndConnect", function (locusUrl, datachannelUrl, datachannelToken) {
131
+ // Deduplicate concurrent calls while a connection is in-flight
132
+ if (_this.connectingPromise) {
133
+ return _this.connectingPromise;
134
+ }
147
135
 
148
- // Pre-populate locusUrl and datachannelUrl before register() fires the
149
- // HTTP POST, so that any token refresh triggered during registration can
150
- // be routed via connections without falling back to a locusInfo URL scan.
151
- if (locusUrl && datachannelUrl) {
152
- var sessionData = _this.connections.get(sessionId) || {};
153
- sessionData.locusUrl = locusUrl;
154
- sessionData.datachannelUrl = datachannelUrl;
155
- _this.connections.set(sessionId, sessionData);
136
+ // If already connected to the exact same datachannel URL, avoid triggering
137
+ // a reconnect that would cause the server to replace with 4000 Replaced
138
+ if (_this.isConnected() && _this.datachannelUrl === datachannelUrl && _this.locusUrl === locusUrl) {
139
+ return _promise.default.resolve();
156
140
  }
157
- return _this.register(datachannelUrl, datachannelToken, sessionId).then(/*#__PURE__*/(0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2() {
158
- var clientLLMDatachannelResponseTime, sessionData, error, isDataChannelTokenEnabled, connectUrl, connectStart, clientLLMWebSocketConnectTime, _t;
159
- return _regenerator.default.wrap(function (_context2) {
160
- while (1) switch (_context2.prev = _context2.next) {
161
- case 0:
162
- if (!(!locusUrl || !datachannelUrl)) {
163
- _context2.next = 1;
164
- break;
165
- }
166
- return _context2.abrupt("return", undefined);
167
- case 1:
168
- clientLLMDatachannelResponseTime = Math.round(performance.now() - registerStart); // locusUrl and datachannelUrl were pre-populated before register(); here
169
- // we only need to read the existing session data to get webSocketUrl/binding
170
- // that register() filled in.
171
- sessionData = _this.connections.get(sessionId) || {};
172
- if (sessionData.webSocketUrl) {
141
+ _this.locusUrl = locusUrl;
142
+ _this.datachannelUrl = datachannelUrl;
143
+ var registerStart = performance.now();
144
+ var connectionPromise = _this.register(datachannelUrl, datachannelToken).then(/*#__PURE__*/function () {
145
+ var _ref4 = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2(_ref3) {
146
+ var webSocketUrl, binding, clientLLMDatachannelResponseTime, isDataChannelTokenEnabled, connectUrl, connectStart, clientLLMWebSocketConnectTime, _t;
147
+ return _regenerator.default.wrap(function (_context2) {
148
+ while (1) switch (_context2.prev = _context2.next) {
149
+ case 0:
150
+ webSocketUrl = _ref3.webSocketUrl, binding = _ref3.binding;
151
+ if (!(_this.connectingPromise !== connectionPromise)) {
152
+ _context2.next = 1;
153
+ break;
154
+ }
155
+ return _context2.abrupt("return");
156
+ case 1:
157
+ _this.webSocketUrl = webSocketUrl;
158
+ _this.binding = binding;
159
+ clientLLMDatachannelResponseTime = Math.round(performance.now() - registerStart);
173
160
  _context2.next = 2;
161
+ return _this.isDataChannelTokenEnabled();
162
+ case 2:
163
+ isDataChannelTokenEnabled = _context2.sent;
164
+ if (!(_this.connectingPromise !== connectionPromise)) {
165
+ _context2.next = 3;
166
+ break;
167
+ }
168
+ return _context2.abrupt("return");
169
+ case 3:
170
+ connectUrl = isDataChannelTokenEnabled && _this.webSocketUrl ? LLMChannel.buildUrlWithAwareSubchannels(_this.webSocketUrl, _constants.AWARE_DATA_CHANNEL) : _this.webSocketUrl;
171
+ connectStart = performance.now();
172
+ _context2.prev = 4;
173
+ _context2.next = 5;
174
+ return _this.connect(connectUrl);
175
+ case 5:
176
+ _context2.next = 7;
174
177
  break;
175
- }
176
- // register() succeeded but the response carried no websocket URL. Attach the measured
177
- // datachannel time so callers don't misreport a registration that completed as time 0.
178
- error = new Error("LLM registration for ".concat(sessionId, " returned no websocket URL"));
179
- error.timing = {
180
- clientLLMDatachannelResponseTime: clientLLMDatachannelResponseTime
181
- };
182
- throw error;
183
- case 2:
184
- _context2.next = 3;
185
- return _this.isDataChannelTokenEnabled();
186
- case 3:
187
- isDataChannelTokenEnabled = _context2.sent;
188
- connectUrl = isDataChannelTokenEnabled ? LLMChannel.buildUrlWithAwareSubchannels(sessionData.webSocketUrl, _constants.AWARE_DATA_CHANNEL) : sessionData.webSocketUrl;
189
- connectStart = performance.now();
190
- _context2.prev = 4;
191
- _context2.next = 5;
192
- return _this.connect(connectUrl, sessionId);
193
- case 5:
194
- _context2.next = 7;
195
- break;
196
- case 6:
197
- _context2.prev = 6;
198
- _t = _context2["catch"](4);
199
- // register() succeeded; only connect() failed. Attach the measured datachannel time so
200
- // callers don't misreport a websocket failure as a registration that never completed.
201
- // @ts-ignore
202
- _t.timing = {
203
- clientLLMDatachannelResponseTime: clientLLMDatachannelResponseTime
204
- };
205
- throw _t;
206
- case 7:
207
- clientLLMWebSocketConnectTime = Math.round(performance.now() - connectStart);
208
- return _context2.abrupt("return", {
209
- clientLLMDatachannelResponseTime: clientLLMDatachannelResponseTime,
210
- clientLLMWebSocketConnectTime: clientLLMWebSocketConnectTime
211
- });
212
- case 8:
213
- case "end":
214
- return _context2.stop();
215
- }
216
- }, _callee2, null, [[4, 6]]);
217
- })));
178
+ case 6:
179
+ _context2.prev = 6;
180
+ _t = _context2["catch"](4);
181
+ // register() succeeded; only connect() failed. Attach the measured datachannel time so
182
+ // callers don't misreport a websocket failure as a registration that never completed.
183
+ // @ts-ignore
184
+ _t.timing = {
185
+ clientLLMDatachannelResponseTime: clientLLMDatachannelResponseTime
186
+ };
187
+ throw _t;
188
+ case 7:
189
+ clientLLMWebSocketConnectTime = Math.round(performance.now() - connectStart);
190
+ return _context2.abrupt("return", {
191
+ clientLLMDatachannelResponseTime: clientLLMDatachannelResponseTime,
192
+ clientLLMWebSocketConnectTime: clientLLMWebSocketConnectTime
193
+ });
194
+ case 8:
195
+ case "end":
196
+ return _context2.stop();
197
+ }
198
+ }, _callee2, null, [[4, 6]]);
199
+ }));
200
+ return function (_x3) {
201
+ return _ref4.apply(this, arguments);
202
+ };
203
+ }()).finally(function () {
204
+ // Only clear if this operation is still current
205
+ if (_this.connectingPromise === connectionPromise) {
206
+ _this.connectingPromise = undefined;
207
+ }
208
+ });
209
+ _this.connectingPromise = connectionPromise;
210
+ return _this.connectingPromise;
218
211
  });
219
212
  /**
220
213
  * Tells if LLM socket is connected
221
- * @param {string} sessionId - Connection identifier
222
214
  * @returns {boolean} connected
223
215
  */
224
- (0, _defineProperty3.default)(_this, "isConnected", function () {
225
- var sessionId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _constants.LLM_DEFAULT_SESSION;
226
- var socket = _this.getSocket(sessionId);
227
- return socket ? socket.connected : false;
216
+ (0, _defineProperty2.default)(_this, "isConnected", function () {
217
+ return _this.connected;
228
218
  });
229
219
  /**
230
220
  * Tells if LLM socket is binding
231
- * @param {string} sessionId - Connection identifier
232
- * @returns {string} binding
221
+ * @returns {string | undefined} binding
233
222
  */
234
- (0, _defineProperty3.default)(_this, "getBinding", function () {
235
- var sessionId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _constants.LLM_DEFAULT_SESSION;
236
- var sessionData = _this.connections.get(sessionId);
237
- return sessionData === null || sessionData === void 0 ? void 0 : sessionData.binding;
223
+ (0, _defineProperty2.default)(_this, "getBinding", function () {
224
+ return _this.binding;
238
225
  });
239
226
  /**
240
227
  * Get Locus URL for the connection
241
- * @param {string} sessionId - Connection identifier
242
- * @returns {string} locus Url
228
+ * @returns {string | undefined} locus Url
243
229
  */
244
- (0, _defineProperty3.default)(_this, "getLocusUrl", function () {
245
- var sessionId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _constants.LLM_DEFAULT_SESSION;
246
- var sessionData = _this.connections.get(sessionId);
247
- return sessionData === null || sessionData === void 0 ? void 0 : sessionData.locusUrl;
230
+ (0, _defineProperty2.default)(_this, "getLocusUrl", function () {
231
+ return _this.locusUrl;
248
232
  });
249
233
  /**
250
234
  * Get data channel URL for the connection
251
- * @param {string} sessionId - Connection identifier
252
- * @returns {string} data channel Url
235
+ * @returns {string | undefined} data channel Url
253
236
  */
254
- (0, _defineProperty3.default)(_this, "getDatachannelUrl", function () {
255
- var sessionId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _constants.LLM_DEFAULT_SESSION;
256
- var sessionData = _this.connections.get(sessionId);
257
- return sessionData === null || sessionData === void 0 ? void 0 : sessionData.datachannelUrl;
237
+ (0, _defineProperty2.default)(_this, "getDatachannelUrl", function () {
238
+ return _this.datachannelUrl;
258
239
  });
259
240
  /**
260
- * Get WebSocket URL for the connection
261
- * @param {string} sessionId - Connection identifier
262
- * @returns {string | undefined} WebSocket URL
241
+ * Get data channel token for this connection.
242
+ * @returns {string | undefined}
263
243
  */
264
- (0, _defineProperty3.default)(_this, "getWebSocketUrl", function () {
265
- var sessionId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _constants.LLM_DEFAULT_SESSION;
266
- var sessionData = _this.connections.get(sessionId);
267
- return sessionData === null || sessionData === void 0 ? void 0 : sessionData.webSocketUrl;
244
+ (0, _defineProperty2.default)(_this, "getDatachannelToken", function () {
245
+ return _this.datachannelToken;
268
246
  });
269
247
  /**
270
- * Set the owner meeting ID for a given LLM session. Used by the meetings
271
- * plugin to tag which Meeting instance currently owns the (default) LLM
272
- * connection so that other Meeting instances can avoid disconnecting or
273
- * re-initializing a connection they do not own.
274
- *
275
- * Does NOT create a connections entry if one does not already exist — this
276
- * method is a no-op when there is no active session data. Callers should
277
- * invoke it after a successful `registerAndConnect` or during an explicit
278
- * ownership handoff.
279
- *
280
- * @param {string | undefined} ownerMeetingId - Meeting ID (or undefined to clear)
281
- * @param {string} sessionId - Connection identifier (defaults to default session)
248
+ * Store the data channel token for this connection.
249
+ * @param {string} token
282
250
  * @returns {void}
283
251
  */
284
- (0, _defineProperty3.default)(_this, "setOwnerMeetingId", function (ownerMeetingId) {
285
- var sessionId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _constants.LLM_DEFAULT_SESSION;
286
- var sessionData = _this.connections.get(sessionId);
287
- if (!sessionData) {
288
- return;
289
- }
290
- sessionData.ownerMeetingId = ownerMeetingId;
291
- _this.connections.set(sessionId, sessionData);
252
+ (0, _defineProperty2.default)(_this, "setDatachannelToken", function (token) {
253
+ _this.datachannelToken = token;
292
254
  });
293
255
  /**
294
- * Get the owner meeting ID currently associated with an LLM session.
295
- * Returns undefined when no owner has been assigned (e.g. before the
296
- * first successful `registerAndConnect`, or after `disconnectLLM`).
297
- *
298
- * @param {string} sessionId - Connection identifier (defaults to default session)
299
- * @returns {string | undefined} ownerMeetingId
300
- */
301
- (0, _defineProperty3.default)(_this, "getOwnerMeetingId", function () {
302
- var sessionId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _constants.LLM_DEFAULT_SESSION;
303
- var sessionData = _this.connections.get(sessionId);
304
- return sessionData === null || sessionData === void 0 ? void 0 : sessionData.ownerMeetingId;
305
- });
306
- /**
307
- * Resolve ownership information for an LLM session.
308
- *
309
- * Rules:
310
- * - no current owner => caller may proceed
311
- * - caller has no identity to assert => treat as owner
312
- * - otherwise caller must match current owner
313
- *
314
- * @param {string | undefined} ownerMeetingId - Candidate owner to evaluate
315
- * @param {string} sessionId - Connection identifier (defaults to default session)
316
- * @returns {{currentOwner: (string|undefined), isOwner: boolean}}
317
- */
318
- (0, _defineProperty3.default)(_this, "resolveSessionOwnership", function (ownerMeetingId) {
319
- var sessionId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _constants.LLM_DEFAULT_SESSION;
320
- var currentOwner = _this.getOwnerMeetingId(sessionId);
321
- var isOwner = !currentOwner || !ownerMeetingId || currentOwner === ownerMeetingId;
322
- return {
323
- currentOwner: currentOwner,
324
- isOwner: isOwner
325
- };
326
- });
327
- /**
328
- * Get data channel token for the connection
329
- * @param {DataChannelTokenType|string} tokenKey
330
- * @param {string | undefined} ownerMeetingId - Meeting id asserting read ownership
331
- * @returns {string | undefined} data channel token
332
- */
333
- (0, _defineProperty3.default)(_this, "getDatachannelToken", function (tokenKey, ownerMeetingId) {
334
- var resolvedTokenKey = tokenKey !== null && tokenKey !== void 0 ? tokenKey : _llm.DataChannelTokenType.Default;
335
- var _this$resolveSessionO = _this.resolveSessionOwnership(ownerMeetingId, resolvedTokenKey),
336
- currentOwner = _this$resolveSessionO.currentOwner,
337
- isOwner = _this$resolveSessionO.isOwner;
338
- if (!isOwner) {
339
- _this.logger.info("llm#getDatachannelToken --> skip read for session ".concat(resolvedTokenKey, "; owned by ").concat(currentOwner, ", candidate ").concat(ownerMeetingId));
340
- return undefined;
341
- }
342
- return _this.datachannelTokens[resolvedTokenKey];
343
- });
344
- /**
345
- * Set data channel token for the connection
346
- * @param {string} datachannelToken - data channel token
347
- * @param {DataChannelTokenType|string} [tokenKey]
348
- * @param {string | undefined} ownerMeetingId - Meeting id asserting write ownership
256
+ * Clear the data channel token for this connection.
349
257
  * @returns {void}
350
258
  */
351
- (0, _defineProperty3.default)(_this, "setDatachannelToken", function (datachannelToken, tokenKey, ownerMeetingId) {
352
- var resolvedTokenKey = tokenKey !== null && tokenKey !== void 0 ? tokenKey : _llm.DataChannelTokenType.Default;
353
- var _this$resolveSessionO2 = _this.resolveSessionOwnership(ownerMeetingId, resolvedTokenKey),
354
- currentOwner = _this$resolveSessionO2.currentOwner,
355
- isOwner = _this$resolveSessionO2.isOwner;
356
- if (!isOwner) {
357
- _this.logger.info("llm#setDatachannelToken --> skip write for session ".concat(resolvedTokenKey, "; owned by ").concat(currentOwner, ", candidate ").concat(ownerMeetingId));
358
- return;
359
- }
360
- _this.datachannelTokens[resolvedTokenKey] = datachannelToken;
259
+ (0, _defineProperty2.default)(_this, "clearDatachannelToken", function () {
260
+ _this.datachannelToken = undefined;
361
261
  });
362
262
  /**
363
- * Clears a single session's data channel token.
364
- * @param {DataChannelTokenType|string} tokenKey
365
- * @param {string} ownerMeetingId - Meeting id asserting delete ownership
263
+ * Set the handler used to refresh the DataChannel token.
264
+ * @param {function} handler
366
265
  * @returns {void}
367
266
  */
368
- (0, _defineProperty3.default)(_this, "clearDatachannelToken", function (tokenKey, ownerMeetingId) {
369
- var resolvedTokenKey = tokenKey;
370
- var _this$resolveSessionO3 = _this.resolveSessionOwnership(ownerMeetingId, resolvedTokenKey),
371
- currentOwner = _this$resolveSessionO3.currentOwner,
372
- isOwner = _this$resolveSessionO3.isOwner;
373
- if (!isOwner) {
374
- _this.logger.info("llm#clearDatachannelToken --> skip clear for session ".concat(resolvedTokenKey, "; owned by ").concat(currentOwner, ", candidate ").concat(ownerMeetingId));
375
- return;
376
- }
377
- _this.datachannelTokens[resolvedTokenKey] = undefined;
378
- delete _this.datachannelTokens[resolvedTokenKey];
379
- });
380
- /**
381
- * Disconnects websocket connection
382
- * @param {{code: number, reason: string}} options - The disconnect option object with code and reason
383
- * @param {string} sessionId - Connection identifier
384
- * @param {string} ownerMeetingId - Meeting id asserting disconnect ownership
385
- * @returns {Promise<boolean>} True when disconnect was performed, false when skipped
386
- */
387
- (0, _defineProperty3.default)(_this, "disconnectLLM", function (options, sessionId, ownerMeetingId) {
388
- var resolvedSessionId = sessionId !== null && sessionId !== void 0 ? sessionId : _constants.LLM_DEFAULT_SESSION;
389
-
390
- // Backward-compat path: historically callers could omit ownerMeetingId
391
- // (and sometimes sessionId). Reuse current owner when available so legacy
392
- // calls remain best-effort without throwing at teardown time.
393
- var resolvedOwnerMeetingId = ownerMeetingId || _this.getOwnerMeetingId(resolvedSessionId);
394
- if (!ownerMeetingId) {
395
- _this.logger.warn("llm#disconnectLLM --> ownerMeetingId is omitted for session ".concat(resolvedSessionId, "; using legacy compatibility path"));
396
- }
397
- var _this$resolveSessionO4 = _this.resolveSessionOwnership(resolvedOwnerMeetingId, resolvedSessionId),
398
- currentOwner = _this$resolveSessionO4.currentOwner,
399
- isOwner = _this$resolveSessionO4.isOwner;
400
- if (!isOwner) {
401
- _this.logger.info("llm#disconnectLLM --> skip disconnect for session ".concat(resolvedSessionId, "; owned by ").concat(currentOwner, ", candidate ").concat(resolvedOwnerMeetingId));
402
- return _promise.default.resolve(false);
403
- }
404
- return _this.disconnect(options, resolvedSessionId).then(function () {
405
- // Clear owner tag before cleanup to ensure it's not lingering
406
- // if another meeting claimed it during disconnect
407
- _this.setOwnerMeetingId(undefined, resolvedSessionId);
408
-
409
- // Clean up sessions data
410
- _this.connections.delete(resolvedSessionId);
411
- return true;
412
- });
413
- });
414
- /**
415
- * Disconnects all LLM websocket connections
416
- * @param {{code: number, reason: string}} options - The disconnect option object with code and reason
417
- * @returns {Promise<void>}
418
- */
419
- (0, _defineProperty3.default)(_this, "disconnectAllLLM", function (options) {
420
- return _this.disconnectAll(options).then(function () {
421
- // Clean up all connection data
422
- _this.connections.clear();
423
- });
424
- });
425
- /**
426
- * Get all active LLM connections
427
- * @returns {Map} Map of sessionId to session data
428
- */
429
- (0, _defineProperty3.default)(_this, "getAllConnections", function () {
430
- return new _map.default(_this.connections);
267
+ (0, _defineProperty2.default)(_this, "setRefreshHandler", function (handler) {
268
+ _this.refreshHandler = handler;
431
269
  });
432
270
  return _this;
433
271
  }
434
272
  (0, _inherits2.default)(LLMChannel, _ref);
435
273
  return (0, _createClass2.default)(LLMChannel, [{
436
- key: "setRefreshHandler",
274
+ key: "isConnecting",
437
275
  value:
438
276
  /**
439
- * Set the handler used to refresh the DataChannel token
440
- *
441
- * @param {function} handler - Function that returns a refreshed token
442
- * @param {string} [sessionId] - Connection identifier
443
- * @param {string | undefined} ownerMeetingId - Meeting id asserting refresh-handler ownership
444
- * @returns {void}
277
+ * Check if a connection is currently in progress.
278
+ * @returns {boolean} True if connecting
445
279
  */
446
- function setRefreshHandler(handler, sessionId, ownerMeetingId) {
447
- var resolvedSessionId = sessionId !== null && sessionId !== void 0 ? sessionId : _constants.LLM_DEFAULT_SESSION;
448
- var _this$resolveSessionO5 = this.resolveSessionOwnership(ownerMeetingId, resolvedSessionId),
449
- currentOwner = _this$resolveSessionO5.currentOwner,
450
- isOwner = _this$resolveSessionO5.isOwner;
451
- if (!isOwner) {
452
- this.logger.info("llm#setRefreshHandler --> skip write for session ".concat(resolvedSessionId, "; owned by ").concat(currentOwner, ", candidate ").concat(ownerMeetingId));
453
- return;
454
- }
455
- var sessionData = this.connections.get(resolvedSessionId);
456
- if (sessionData) {
457
- sessionData.refreshHandler = handler;
458
- if (ownerMeetingId) {
459
- sessionData.ownerMeetingId = ownerMeetingId;
460
- }
461
- return;
462
- }
463
-
464
- // Intentionally allow a pre-connection session shape here.
465
- // Some flows inject refreshHandler before register/connect so token refresh
466
- // is already wired when the socket lifecycle starts. register()/
467
- // registerAndConnect() will later fill webSocketUrl/binding/locusUrl/
468
- // datachannelUrl into this same session entry.
469
- this.connections.set(resolvedSessionId, {
470
- refreshHandler: handler,
471
- ownerMeetingId: ownerMeetingId
472
- });
280
+ function isConnecting() {
281
+ return !!this.connectingPromise;
473
282
  }
474
-
283
+ }, {
284
+ key: "refreshDataChannelToken",
285
+ value: (
475
286
  /**
476
287
  * Refresh the data channel token using the injected handler.
477
- * Logs a descriptive error if the handler is missing or fails.
478
- * @param {string} sessionId - Connection identifier (defaults to default session)
479
- * @returns {Promise<string>} The refreshed token.
288
+ * @returns {Promise<object | null>}
480
289
  */
481
- }, {
482
- key: "refreshDataChannelToken",
483
- value: (function () {
290
+ function () {
484
291
  var _refreshDataChannelToken = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee3() {
485
- var _this$connections$get;
486
- var sessionId,
487
- refreshHandler,
488
- res,
489
- _args3 = arguments,
490
- _t2;
292
+ var _t2;
491
293
  return _regenerator.default.wrap(function (_context3) {
492
294
  while (1) switch (_context3.prev = _context3.next) {
493
295
  case 0:
494
- sessionId = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : _constants.LLM_DEFAULT_SESSION;
495
- refreshHandler = (_this$connections$get = this.connections.get(sessionId)) === null || _this$connections$get === void 0 ? void 0 : _this$connections$get.refreshHandler;
496
- if (refreshHandler) {
296
+ if (this.refreshHandler) {
497
297
  _context3.next = 1;
498
298
  break;
499
299
  }
500
- this.logger.warn("llm#refreshDataChannelToken --> LLM refreshHandler is not set for session ".concat(sessionId, ", skipping token refresh"));
300
+ this.logger.warn('llm#refreshDataChannelToken --> LLM refreshHandler is not set, skipping token refresh');
501
301
  return _context3.abrupt("return", null);
502
302
  case 1:
503
303
  _context3.prev = 1;
504
304
  _context3.next = 2;
505
- return refreshHandler();
305
+ return this.refreshHandler();
506
306
  case 2:
507
- res = _context3.sent;
508
- return _context3.abrupt("return", res);
307
+ return _context3.abrupt("return", _context3.sent);
509
308
  case 3:
510
309
  _context3.prev = 3;
511
310
  _t2 = _context3["catch"](1);
512
- this.logger.warn("llm#refreshDataChannelToken --> DataChannel token refresh failed (likely locus changed or participant left): ".concat((_t2 === null || _t2 === void 0 ? void 0 : _t2.message) || _t2));
311
+ this.logger.warn("llm#refreshDataChannelToken --> DataChannel token refresh failed: ".concat((_t2 === null || _t2 === void 0 ? void 0 : _t2.message) || _t2));
513
312
  return _context3.abrupt("return", null);
514
313
  case 4:
515
314
  case "end":
@@ -521,67 +320,50 @@ var LLMChannel = exports.default = /*#__PURE__*/function (_ref) {
521
320
  return _refreshDataChannelToken.apply(this, arguments);
522
321
  }
523
322
  return refreshDataChannelToken;
524
- }())
525
- }, {
526
- key: "getLocusUrlByDatachannelUrl",
527
- value:
323
+ }()
528
324
  /**
529
- * Look up the locusUrl associated with a datachannel request URL.
530
- * Iterates all active LLM sessions and returns the locusUrl of the
531
- * session whose stored datachannelUrl is a prefix of the given request URL.
532
- *
533
- * @param {string} requestUrl - The in-flight request URL to match
534
- * @returns {string | undefined} The matching locusUrl, or undefined if not found
535
- */
536
- function getLocusUrlByDatachannelUrl(requestUrl) {
537
- var _iterator = _createForOfIteratorHelper(this.connections),
538
- _step;
539
- try {
540
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
541
- var _step$value = (0, _slicedToArray2.default)(_step.value, 2),
542
- connection = _step$value[1];
543
- if (connection.datachannelUrl && LLMChannel.matchesDatachannelRequestUrl(requestUrl, connection.datachannelUrl)) {
544
- return connection.locusUrl;
545
- }
546
- }
547
- } catch (err) {
548
- _iterator.e(err);
549
- } finally {
550
- _iterator.f();
551
- }
552
- return undefined;
553
- }
554
-
555
- /**
556
- * Look up the sessionId associated with a datachannel request URL.
557
- * Iterates all active LLM sessions and returns the sessionId whose
558
- * stored datachannelUrl is a prefix of the given request URL.
559
- *
560
- * @param {string} requestUrl - The in-flight request URL to match
561
- * @returns {string | undefined} The matching sessionId, or undefined if not found
325
+ * Disconnects the WebSocket and clears all connection state.
326
+ * Overrides Mercury's disconnect to also clear LLM-specific state.
327
+ * Clears connectingPromise first to invalidate any in-flight operations,
328
+ * then clears state before calling super.disconnect(). This ensures:
329
+ * 1. Stale register() responses won't overwrite state (they check promise identity)
330
+ * 2. No deadlock with Mercury's _connectWithBackoff() (we don't await connectingPromise)
331
+ * 3. State is cleared before 'disconnected' event fires
332
+ * @param {object} [options]
333
+ * @returns {Promise<void>}
562
334
  */
335
+ )
563
336
  }, {
564
- key: "getSessionIdByDatachannelUrl",
565
- value: function getSessionIdByDatachannelUrl(requestUrl) {
566
- var _iterator2 = _createForOfIteratorHelper(this.connections),
567
- _step2;
568
- try {
569
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
570
- var _step2$value = (0, _slicedToArray2.default)(_step2.value, 2),
571
- sessionId = _step2$value[0],
572
- connection = _step2$value[1];
573
- if (connection.datachannelUrl && LLMChannel.matchesDatachannelRequestUrl(requestUrl, connection.datachannelUrl)) {
574
- return sessionId;
337
+ key: "disconnect",
338
+ value: (function () {
339
+ var _disconnect = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee4(options) {
340
+ return _regenerator.default.wrap(function (_context4) {
341
+ while (1) switch (_context4.prev = _context4.next) {
342
+ case 0:
343
+ // Clear connectingPromise first to invalidate any in-flight operations.
344
+ // Their promise identity checks will detect they've been superseded.
345
+ this.connectingPromise = undefined;
346
+
347
+ // Clear LLM-specific state before Mercury emits 'disconnected'
348
+ this.webSocketUrl = undefined;
349
+ this.binding = undefined;
350
+ this.locusUrl = undefined;
351
+ this.datachannelUrl = undefined;
352
+ this.datachannelToken = undefined;
353
+ this.refreshHandler = undefined;
354
+ _context4.next = 1;
355
+ return _superPropGet(LLMChannel, "disconnect", this, 3)([options]);
356
+ case 1:
357
+ case "end":
358
+ return _context4.stop();
575
359
  }
576
- }
577
- } catch (err) {
578
- _iterator2.e(err);
579
- } finally {
580
- _iterator2.f();
360
+ }, _callee4, this);
361
+ }));
362
+ function disconnect(_x4) {
363
+ return _disconnect.apply(this, arguments);
581
364
  }
582
- return undefined;
583
- }
584
-
365
+ return disconnect;
366
+ }()
585
367
  /**
586
368
  * Matches a request URL to a stored datachannel registration URL.
587
369
  * Host can differ (e.g. rewritten by hostmap interceptor), so we first
@@ -590,12 +372,13 @@ var LLMChannel = exports.default = /*#__PURE__*/function (_ref) {
590
372
  * @param {string} registrationUrl
591
373
  * @returns {boolean}
592
374
  */
375
+ )
593
376
  }, {
594
377
  key: "isDataChannelTokenEnabled",
595
378
  value:
596
379
  /**
597
- * Returns true if data channel token is enabled, false otherwise
598
- * @returns {Promise<boolean>} resolves with true if data channel token is enabled
380
+ * Returns true if the data channel token feature flag is enabled.
381
+ * @returns {Promise<boolean>}
599
382
  */
600
383
  function isDataChannelTokenEnabled() {
601
384
  // @ts-ignore
@@ -604,10 +387,9 @@ var LLMChannel = exports.default = /*#__PURE__*/function (_ref) {
604
387
 
605
388
  /**
606
389
  * Builds a WebSocket URL with the `subscriptionAwareSubchannels` query parameter.
607
- *
608
- * @param {string} baseUrl - The original WebSocket URL.
609
- * @param {string[]} subchannels - List of subchannels to declare as subscription-aware.
610
- * @returns {string} The final URL with updated query parameters.
390
+ * @param {string} baseUrl
391
+ * @param {string[]} subchannels
392
+ * @returns {string}
611
393
  */
612
394
  }], [{
613
395
  key: "matchesDatachannelRequestUrl",
@@ -628,7 +410,7 @@ var LLMChannel = exports.default = /*#__PURE__*/function (_ref) {
628
410
  }
629
411
  }]);
630
412
  }(_internalPluginMercury.default);
631
- (0, _defineProperty3.default)(LLMChannel, "buildUrlWithAwareSubchannels", function (baseUrl, subchannels) {
413
+ (0, _defineProperty2.default)(LLMChannel, "buildUrlWithAwareSubchannels", function (baseUrl, subchannels) {
632
414
  var urlObj = new URL(baseUrl);
633
415
  urlObj.searchParams.set(_constants.SUBSCRIPTION_AWARE_SUBCHANNELS_PARAM, subchannels.join(','));
634
416
  return urlObj.toString();