@webex/internal-plugin-llm 3.12.0-next.7 → 3.12.0-next.71

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/src/constants.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  export const LLM = 'llm';
3
3
 
4
4
  export const LLM_DEFAULT_SESSION = 'llm-default-session';
5
+ export const LLM_PRACTICE_SESSION = 'llm-practice-session';
5
6
 
6
7
  export const DATA_CHANNEL_WITH_JWT_TOKEN = 'data-channel-with-jwt-token';
7
8
 
@@ -0,0 +1,522 @@
1
+ ---
2
+ type: Module Spec
3
+ title: 'LLM channel plugin specification'
4
+ description: Responsibilities, boundaries, design, invariants, and verification for the LLM data-channel plugin module.
5
+ tags: [module, specification]
6
+ ---
7
+ <!-- sdd-generated-metadata
8
+ doc_kind: module-spec
9
+ generated_from: module-spec@0.3.0
10
+ generated_by: claude-cowork
11
+ approved_by: akulakum@cisco.com
12
+ updated_at: 2026-10-08T10:12:58Z
13
+ validation_status: pass-with-warnings
14
+ -->
15
+
16
+ # LLM channel plugin
17
+
18
+ This source-local document at `src/docs/README.md` owns the stable specification for **the LLM
19
+ channel plugin**: the `webex.internal.llm` data-channel connection manager. Ground every claim in
20
+ package evidence and link to the [package architecture](../../docs/architecture.md) instead of
21
+ repeating broader facts. No service specification exists because this package is a library.
22
+
23
+ Related context: [documentation index](../../docs/index.md) ·
24
+ [package agent instructions](../../AGENTS.md)
25
+
26
+ ## Metadata
27
+
28
+ | Field | Value |
29
+ | ----------------- | ----- |
30
+ | Owner | @webex/web-client, @webex/web-sdk |
31
+ | Source path | `src` |
32
+ | Resource kind | package |
33
+ | Status | Draft |
34
+ | Last verified | 2026-10-07 at `d2e34dabee` |
35
+ | Module id | `internal-plugin-llm` |
36
+ | Parent spec | — |
37
+ | Doc kind | Module spec |
38
+ | Coverage score | 93.3% assessed 2026-10-07 — 14 of 15 mandatory fields PRESENT, critical 8 of 8; test strategy is WEAK because registration, `clearDatachannelToken`, refused-owner token and handler calls, `INV-003`, `INV-005`, and suffixed events are untested, two disconnect cases use a stand-in object, and no characterization baseline exists |
39
+ | Validation status | pass-with-warnings; assessed 2026-10-08 by current-session (round 3) |
40
+
41
+ ## Applicability
42
+
43
+ | Condition ID | Status | Evidence or reason | Owned section |
44
+ | ------------------------------------ | ---------- | ------------------ | ------------- |
45
+ | `module.has_tiers` | N/A | No tier policy exists in this package or its `package.json` | Tier |
46
+ | `module.has_ui` | N/A | No view or screen. The module manages sockets and session records. | UI use-case flow |
47
+ | `module.crosses_service_boundaries` | Applicable | `register` sends an HTTP POST to the data-channel URL and the inherited Mercury `connect` opens a WebSocket, both in `src/llm.ts` | Cross-boundary use-case flow |
48
+ | `module.holds_client_state` | Applicable | The private `connections` map and `datachannelTokens` record in `src/llm.ts` | Client state model |
49
+ | `module.enforces_domain_rules` | Applicable | Session-ownership checks guard token, refresh-handler, and disconnect operations in `src/llm.ts` | Business rules and invariants |
50
+ | `module.is_concurrent_async` | Applicable | Promise-based register and connect, async refresh handlers, and feature-toggle reads in `src/llm.ts` | Concurrency and reactive flow |
51
+ | `module.owns_persistence` | N/A | Nothing is written to storage. All state is in memory. | Data, schema, and migration discipline |
52
+ | `module.stateful_transitions` | Applicable | Each session entry moves from absent to pre-connection, registered, connected, and removed | State machine |
53
+ | `module.exposes_wire_protocol` | Applicable | Registration request and response fields, the auth header, and the `subscriptionAwareSubchannels` query in `src/llm.ts` and `src/constants.ts` | Protocol and wire format |
54
+ | `module.ui_multi_screen` | N/A | No UI | UI flow |
55
+ | `module.large_data_model` | N/A | One session record type and one token record; see `src/llm.types.ts` | Data model |
56
+ | `module.returns_caller_errors` | Applicable | `registerAndConnect` rejects and attaches `timing`; other methods return `false`, `null`, or `undefined` on refusal | Caller-visible failure modes |
57
+ | `module.module_specific_conventions` | Applicable | `llm#<method> -->` log prefix, the ownership-check pattern, and default-session arguments | Module-specific rules |
58
+ | `module.published_package` | Applicable | `package.json` names the package @webex/internal-plugin-llm and `deploy:npm` publishes it | Export stability |
59
+ | `module.embedded_in_host` | N/A | No host theme or embed API | Host integration and theming |
60
+ | `module.has_design_tradeoff` | Applicable | The token cache is decoupled from the connection lifecycle, and omitted owner ids are accepted for backward compatibility | Key design trade-off |
61
+ | `module.has_submodules` | N/A | Computed false by the Repo Annotation module_tree.py script: `src` has no child module | Sub-modules |
62
+
63
+ ## Evidence register
64
+
65
+ | Evidence | What it establishes |
66
+ | -------- | ------------------- |
67
+ | `src/index.ts` | Internal plugin registration as `llm` with `config`, and the public exports |
68
+ | `src/llm.ts` | `LLMChannel`: config defaults, session map, register and connect, accessors, ownership, token cache, refresh handler, disconnect, and URL lookup |
69
+ | `src/llm.types.ts` | `DataChannelTokenType`, `RegisterAndConnectTiming`, and the `ILLMChannel` interface |
70
+ | `src/constants.ts` | Namespace, session ids, feature-toggle name, query parameter name, and the subscription-aware subchannel list |
71
+ | `package.json` | Name, entry points, the Mercury dependency, and scripts |
72
+ | `process` | Package-root module exporting `{browser: true}`; nothing in `src/` imports it |
73
+ | `test/unit/spec/llm.js` | Unit cases for register and connect, timing, accessors, ownership, refresh handler, disconnect, multi-session, and URL lookup |
74
+ | Sibling package internal-plugin-mercury, files src/mercury.js and src/index.js | Superclass behavior: `connect`, `disconnect`, `disconnectAll`, `getSocket`, session-suffixed events, retries, and the `onBeforeLogout` hook registered only for `mercury` |
75
+ | Sibling package webex-core, file src/lib/webex-plugin.js | `this.config` is read from `webex.config[namespace]`, so `config.llm` reaches `LLMChannel` |
76
+ | Sibling package plugin-meetings, files src/meeting/index.ts, src/webinar/index.ts, and src/interceptors/dataChannelAuthToken.ts | Main consumer of registration, ownership, token, and refresh-handler methods |
77
+ | Sibling package internal-plugin-voicea, file src/constants.ts | Re-exports `LLM_PRACTICE_SESSION` |
78
+ | Product README | Retained product documentation, not the behavioral authority. See ADR 0001. |
79
+
80
+ ## Purpose and boundary
81
+
82
+ - Responsibility: open and track the LLM data-channel connections a meeting uses. For each session
83
+ id the module registers with the data-channel service over HTTP, opens the returned WebSocket
84
+ through the inherited Mercury connection logic, and keeps the session's URLs, binding, owner
85
+ meeting, and token-refresh handler.
86
+ - In scope: `LLMChannel` in `src/llm.ts`, its `config.llm` defaults, the session-keyed token cache,
87
+ ownership checks, data-channel URL lookup, the registration side effect in `src/index.ts`, and the
88
+ exported constants and types.
89
+ - Out of scope: the WebSocket lifecycle, authorization frame, keepalive, close-code reconnect policy,
90
+ and event routing, which `LLMChannel` inherits from sibling package internal-plugin-mercury;
91
+ obtaining or refreshing data-channel tokens, which callers supply through tokens and refresh
92
+ handlers; device registration and feature toggles, owned by sibling plugins.
93
+ - Consumers: sibling package plugin-meetings (meeting, webinar, and the data-channel auth-token
94
+ interceptor), and sibling package internal-plugin-voicea through `LLM_PRACTICE_SESSION`.
95
+
96
+ ## Structure and key files
97
+
98
+ | Path | Responsibility |
99
+ | ---- | -------------- |
100
+ | `src/index.ts` | Calls `registerInternalPlugin('llm', LLMChannel, {config})` and re-exports the default class, `DataChannelTokenType`, `LLM_DEFAULT_SESSION`, `LLM_PRACTICE_SESSION`, and the `RegisterAndConnectTiming` type |
101
+ | `src/llm.ts` | `config` object and the `LLMChannel` class, which extends Mercury |
102
+ | `src/llm.types.ts` | Token type enum, timing type, and the `ILLMChannel` interface that `LLMChannel` implements |
103
+ | `src/constants.ts` | String constants used by `src/llm.ts`, including `DATA_CHNANEL_TYPE` (spelled that way in code) |
104
+ | `test/unit/spec/llm.js` | The only test file; Mocha-style suites run by Jest |
105
+
106
+ ## Public surface
107
+
108
+ Declarations live in `src/index.ts`, `src/llm.ts`, and `src/llm.types.ts`. This section summarises
109
+ them and does not restate signatures. Session-id arguments default to the default session
110
+ (`INV-001`) unless noted.
111
+
112
+ | Surface | Consumer | Compatibility commitment | Source |
113
+ | ------- | -------- | ------------------------ | ------ |
114
+ | Registration side effect | Every importer | Importing the package installs `webex.internal.llm` (`MOD-001`) | `src/index.ts` |
115
+ | `registerAndConnect(locusUrl, datachannelUrl, datachannelToken, sessionId)` | plugin-meetings | Register over HTTP, then connect; resolves timing or `undefined` (`MOD-002` to `MOD-004`) | `src/llm.ts` |
116
+ | `isConnected`, `getBinding`, `getLocusUrl`, `getDatachannelUrl`, `getWebSocketUrl` | plugin-meetings | Read one session (`MOD-005`) | `src/llm.ts` |
117
+ | `setOwnerMeetingId`, `getOwnerMeetingId`, `resolveSessionOwnership` | plugin-meetings | Ownership per `INV-002` (`MOD-006`) | `src/llm.ts` |
118
+ | `getDatachannelToken`, `setDatachannelToken`, `clearDatachannelToken` | plugin-meetings | Token cache keyed by token key, guarded by ownership (`MOD-007`) | `src/llm.ts` |
119
+ | `setRefreshHandler`, `refreshDataChannelToken` | plugin-meetings and its interceptor | Store and call a caller-supplied refresh function (`MOD-008`, `MOD-009`) | `src/llm.ts` |
120
+ | `disconnectLLM(options, sessionId, ownerMeetingId)`, `disconnectAllLLM(options)` | plugin-meetings | Close one session when owner, or all sessions (`MOD-010`, `MOD-011`) | `src/llm.ts` |
121
+ | `getAllConnections()` | plugin-meetings | Shallow copy of the session map (`MOD-012`) | `src/llm.ts` |
122
+ | `getLocusUrlByDatachannelUrl`, `getSessionIdByDatachannelUrl`, static `matchesDatachannelRequestUrl` | data-channel auth-token interceptor | Map a request URL to its session (`MOD-013`) | `src/llm.ts` |
123
+ | `isDataChannelTokenEnabled()`, static `buildUrlWithAwareSubchannels` | Internal callers and tests | `MOD-014`, `MOD-015` | `src/llm.ts` |
124
+ | Inherited Mercury methods (`connect`, `disconnect`, `disconnectAll`, `getSocket`, and others) | Tests and advanced callers | Behavior owned by sibling package internal-plugin-mercury | `src/llm.ts` |
125
+ | Events on `webex.internal.llm` | plugin-meetings | Contract `llm-plugin-events`; naming rule `INV-001` | `src/llm.ts` |
126
+ | `config.llm` keys | SDK integrators | Defaults in `INV-005` | `src/llm.ts` |
127
+ | `DataChannelTokenType`, `LLM_DEFAULT_SESSION`, `LLM_PRACTICE_SESSION`, `RegisterAndConnectTiming` | plugin-meetings, internal-plugin-voicea | Values in `INV-001` | `src/index.ts` |
128
+
129
+ Contract `llm-sdk` is published with native artifact `package.json`. Contract `llm-plugin-events` is
130
+ published with source `src/llm.ts`. Contract `llm-datachannel-protocol` is internal with source
131
+ `src/llm.ts`. Required contracts: `mercury-plugin-base`, `webex-core-plugin-host`,
132
+ `webex-device-registration`, and `webex-feature-toggles`.
133
+
134
+ ## Dependencies
135
+
136
+ | Dependency | Why it is required | Failure behavior |
137
+ | ---------- | ------------------ | ---------------- |
138
+ | `@webex/internal-plugin-mercury` (`mercury-plugin-base`) | Superclass. Supplies `connect`, `disconnect`, `disconnectAll`, `getSocket`, event emission, retries, and the subscriptions its `initialize` adds for `featureToggle_update`, `ActiveClusterStatusEvent`, and `u2c.cache-invalidation` events | Connect failures reject `registerAndConnect` with `timing` (`MOD-004`) |
139
+ | `@webex/webex-core` (`webex-core-plugin-host`) | `registerInternalPlugin`, `this.request`, `this.logger`, and `this.config` bound to `config.llm` | A rejected `request` rejects `registerAndConnect` |
140
+ | Device plugin (`webex-device-registration`) | `webex.internal.device.url` is the registration body | An unset URL is sent as `undefined`; no check here |
141
+ | Feature plugin (`webex-feature-toggles`) | The JWT toggle read in `MOD-014` | A rejection rejects `registerAndConnect` before the POST or before connect |
142
+ | Global `performance` and `URL` | Timing and URL parsing | `URL` parse errors are caught only in `matchesDatachannelRequestUrl` |
143
+
144
+ The Mercury module specification exists only outside this branch, so this table cites Mercury
145
+ source. `@webex/webex-core` is not listed in `package.json` `dependencies`; it is resolved through the
146
+ workspace.
147
+
148
+ ## Requirements
149
+
150
+ | ID | WHAT | WHY | Source evidence | Test or example evidence | Assumptions or gaps | Confidence |
151
+ | -- | ---- | --- | --------------- | ------------------------ | ------------------- | ---------- |
152
+ | `MOD-001` | Importing the package registers `LLMChannel` as internal plugin `llm` with `config`. No `onBeforeLogout` hook is registered. | Every webex instance gets one LLM connection manager at `webex.internal.llm`. | `src/index.ts` | `test/unit/spec/llm.js` builds `MockWebex` with `llm: LLMService` | No test asserts the registration itself | Present |
153
+ | `MOD-002` | When both `locusUrl` and `datachannelUrl` are truthy, `registerAndConnect` writes them into the session entry before the registration POST. | A token refresh that fires during registration can find its session through `MOD-013`. | `src/llm.ts` | `test/unit/spec/llm.js` `tracks multiple sessions independently`, `#getLocusUrl`, `#getDatachannelUrl` | No test refreshes during registration | Present |
154
+ | `MOD-003` | Registration reads the toggle (`MOD-014`), POSTs to `datachannelUrl` with body `deviceUrl`, adds the auth header per `INV-004`, and stores `webSocketUrl` and `binding` from the response in the session entry. A request error is logged and rethrown. | The data-channel service returns the socket URL and binding for this device. | `src/llm.ts` | `test/unit/spec/llm.js` `#register` cases | The error log path has no test | Present |
155
+ | `MOD-004` | After registration: with a missing URL argument the promise resolves `undefined` and no socket opens; with no `webSocketUrl` it rejects with an error carrying `timing`; otherwise it connects through Mercury using the URL from `INV-004`, rejects with `timing` when connect fails, and resolves `RegisterAndConnectTiming` in rounded milliseconds on success. | Callers report registration and socket latency separately, including on failure. | `src/llm.ts` | `test/unit/spec/llm.js` `#registerAndConnect` cases, `#registerAndConnect timing` | Registration still runs when a URL argument is missing (see Pitfalls) | Present |
156
+ | `MOD-005` | `isConnected` returns the session socket's `connected` flag or `false`; `getBinding`, `getLocusUrl`, `getDatachannelUrl`, and `getWebSocketUrl` return the session entry's field or `undefined`. | Meetings read per-session state without touching the socket. | `src/llm.ts` | `test/unit/spec/llm.js` `#getLocusUrl`, `#getDatachannelUrl`, `#getWebSocketUrl`, `tracks multiple sessions independently` | `getBinding` is only tested for `undefined` | Present |
157
+ | `MOD-006` | `setOwnerMeetingId` sets or clears the owner only when the session entry exists; `getOwnerMeetingId` reads it; `resolveSessionOwnership` returns `currentOwner` and `isOwner` per `INV-002`. | Several meeting objects share one LLM plugin; only the owner may tear down or rewrite a session. | `src/llm.ts` | `test/unit/spec/llm.js` `#setOwnerMeetingId / #getOwnerMeetingId` cases | `resolveSessionOwnership` has no direct test | Present |
158
+ | `MOD-007` | `getDatachannelToken` and `setDatachannelToken` default the key to `DataChannelTokenType.Default`; `clearDatachannelToken` takes an explicit key. Each checks ownership with the token key as the session id; a non-owner read returns `undefined`, and a non-owner write or clear does nothing. Both cases log at info level. | Token reuse across meeting objects must not leak another meeting's token. | `src/llm.ts` | `test/unit/spec/llm.js` `#getDatachannelToken / #setDatachannelToken` | No test for `clearDatachannelToken` or for a refused read, write, or clear | Weak |
159
+ | `MOD-008` | `setRefreshHandler` refuses a non-owner (info log). When the session entry exists it stores the handler and, if given, the owner id; otherwise it creates a pre-connection entry holding only the handler and owner id. | Refresh can be wired before the socket exists. | `src/llm.ts` | `test/unit/spec/llm.js` `#setRefreshHandler` cases | Refused-owner and pre-connection-then-register paths have no test | Present |
160
+ | `MOD-009` | `refreshDataChannelToken` returns `null` with a warning when the session has no handler, returns the handler's resolved value, and returns `null` with a warning when the handler rejects. | Refresh failures (for example after a locus change) must not throw into the request pipeline. | `src/llm.ts` | `test/unit/spec/llm.js` `#refreshDataChannelToken` cases | — | Present |
161
+ | `MOD-010` | `disconnectLLM` treats a missing session id as the default session. When `ownerMeetingId` is omitted it warns and uses the current owner. A non-owner resolves `false` without disconnecting. An owner calls Mercury `disconnect(options, sessionId)`, then clears the owner, deletes the session entry, and resolves `true`; a disconnect rejection propagates and the entry stays. | Only the owning meeting tears down a shared session; old call sites keep working. | `src/llm.ts` | `test/unit/spec/llm.js` `disconnectLLM supports legacy call with options only`, `disconnectLLM supports legacy call with options and sessionId`, `disconnectLLM treats null sessionId as default session`, `disconnectLLM clears only the targeted session`, `disconnectLLM skips disconnect when ownerMeetingId does not match` | The two `#disconnectLLM` cases using a stand-in object do not exercise `LLMChannel` (see Verification) | Present |
162
+ | `MOD-011` | `disconnectAllLLM` calls Mercury `disconnectAll(options)` and then clears the session map. It does not check ownership and does not clear the token cache (`INV-003`). | Full teardown regardless of owner. | `src/llm.ts` | `test/unit/spec/llm.js` `disconnectAllLLM clears all sessions` | — | Present |
163
+ | `MOD-012` | `getAllConnections` returns a new `Map` with the same entry objects. | Callers can iterate sessions without mutating the map itself. | `src/llm.ts` | `test/unit/spec/llm.js` `tracks multiple sessions independently` | Entry objects are shared, not copied | Present |
164
+ | `MOD-013` | `getLocusUrlByDatachannelUrl` and `getSessionIdByDatachannelUrl` return the first session, in insertion order, whose stored `datachannelUrl` matches the request URL. A match is a full-string prefix, or else a pathname prefix after parsing both URLs; empty input or a parse error is no match. | A rewritten host (for example by a host-map interceptor) must still map back to its session. | `src/llm.ts` | `test/unit/spec/llm.js` `#getLocusUrlByDatachannelUrl`, `#getSessionIdByDatachannelUrl` | Parse-error path has no test | Present |
165
+ | `MOD-014` | `isDataChannelTokenEnabled` returns `webex.internal.feature.getFeature('developer', 'data-channel-with-jwt-token')`. | The JWT data-channel flow is gated by a developer toggle. | `src/llm.ts`, `src/constants.ts` | `test/unit/spec/llm.js` `#isDataChannelTokenEnabled` | — | Present |
166
+ | `MOD-015` | `buildUrlWithAwareSubchannels(baseUrl, subchannels)` parses `baseUrl`, sets the `subscriptionAwareSubchannels` query to the comma-joined list, replacing any existing value, and returns the string. | Declares which subchannels the client understands as subscription-aware. | `src/llm.ts`, `src/constants.ts` | `test/unit/spec/llm.js` `connects with subscriptionAwareSubchannels when token enabled` | Only observed through a spy; no direct case | Present |
167
+
168
+ ## Design overview
169
+
170
+ `LLMChannel` is a TypeScript class that extends the Mercury plugin. It overrides two fields:
171
+ `namespace` becomes `llm`, which makes `this.config` resolve to `config.llm` and prefixes inherited
172
+ Mercury log lines, and `defaultSessionId` becomes `llm-default-session`, which decides which
173
+ session's events are unsuffixed.
174
+
175
+ The class adds an HTTP registration step in front of Mercury's `connect`. `registerAndConnect`
176
+ records the locus and data-channel URLs, POSTs to the data-channel URL, keeps the returned socket URL
177
+ and binding, and then calls `connect` with that URL, adding the `subscriptionAwareSubchannels` query
178
+ when the JWT toggle is on. Retry, keepalive, close handling, and event emission after that point are
179
+ Mercury's.
180
+
181
+ Per-session metadata lives in a private `connections` map. Tokens live in a separate
182
+ `datachannelTokens` record so that disconnecting does not drop a token a later reconnect needs. Most
183
+ public methods are arrow-function instance fields; `setRefreshHandler`, `refreshDataChannelToken`,
184
+ the two URL-lookup methods, and `isDataChannelTokenEnabled` are prototype methods.
185
+
186
+ ## Data flow and sequence coverage
187
+
188
+ Transport: HTTP POST through `this.request` to the data-channel service; WebSocket through the
189
+ inherited Mercury `connect`; in-process calls for everything else.
190
+
191
+ | Operation group | Entry and outcome | Diagram or evidence | Failure and recovery coverage |
192
+ | --------------- | ----------------- | ------------------- | ----------------------------- |
193
+ | Register and connect | `registerAndConnect` → POST → `connect` → timing | Register-and-connect diagram below | Request error, missing socket URL, connect error with `timing` |
194
+ | Ownership and tokens | `setOwnerMeetingId`, token get/set/clear, `setRefreshHandler` | Ownership diagram below | Refused non-owner calls |
195
+ | Token refresh | `refreshDataChannelToken` → caller handler | Refresh diagram below | Missing handler or rejection returns `null` |
196
+ | Disconnect | `disconnectLLM`, `disconnectAllLLM` → Mercury `disconnect` or `disconnectAll` | Disconnect diagram below | Non-owner returns `false`; rejection propagates |
197
+ | URL lookup | `getSessionIdByDatachannelUrl`, `getLocusUrlByDatachannelUrl` | Synchronous scan, no diagram needed; `MOD-013` | No match or parse error returns `undefined` |
198
+
199
+ Register and connect:
200
+
201
+ ```mermaid
202
+ sequenceDiagram
203
+ participant Caller
204
+ participant LLM as LLMChannel
205
+ participant Feature as internal.feature
206
+ participant DC as data-channel service
207
+ participant Mercury as Mercury connect
208
+ Caller->>LLM: registerAndConnect(locusUrl, datachannelUrl, token, sessionId)
209
+ opt both URLs given
210
+ LLM->>LLM: store locusUrl and datachannelUrl
211
+ end
212
+ LLM->>Feature: getFeature(developer, data-channel-with-jwt-token)
213
+ LLM->>DC: POST datachannelUrl, body deviceUrl, header per INV-004
214
+ alt request fails
215
+ DC-->>LLM: error
216
+ LLM-->>Caller: log and reject
217
+ else response
218
+ DC-->>LLM: webSocketUrl, binding
219
+ LLM->>LLM: store webSocketUrl and binding
220
+ alt a URL argument was missing
221
+ LLM-->>Caller: resolve undefined
222
+ else no webSocketUrl
223
+ LLM-->>Caller: reject with timing
224
+ else
225
+ LLM->>Feature: getFeature again
226
+ LLM->>Mercury: connect(url per INV-004, sessionId)
227
+ alt connect rejects
228
+ LLM-->>Caller: reject with timing
229
+ else online
230
+ LLM-->>Caller: resolve both latencies
231
+ end
232
+ end
233
+ end
234
+ ```
235
+
236
+ Ownership and tokens:
237
+
238
+ ```mermaid
239
+ sequenceDiagram
240
+ participant Meeting
241
+ participant LLM as LLMChannel
242
+ Meeting->>LLM: setDatachannelToken(token, key, ownerMeetingId)
243
+ LLM->>LLM: resolveSessionOwnership(ownerMeetingId, key)
244
+ alt isOwner
245
+ LLM->>LLM: datachannelTokens[key] = token
246
+ else other owner
247
+ LLM->>LLM: info log, no write
248
+ end
249
+ Meeting->>LLM: setRefreshHandler(handler, sessionId, ownerMeetingId)
250
+ alt not owner
251
+ LLM->>LLM: info log, no write
252
+ else session entry exists
253
+ LLM->>LLM: store handler and owner id
254
+ else no entry
255
+ LLM->>LLM: create pre-connection entry
256
+ end
257
+ ```
258
+
259
+ Token refresh:
260
+
261
+ ```mermaid
262
+ sequenceDiagram
263
+ participant Interceptor as plugin-meetings interceptor
264
+ participant LLM as LLMChannel
265
+ participant Handler as refresh handler
266
+ Interceptor->>LLM: refreshDataChannelToken(sessionId)
267
+ alt no handler
268
+ LLM-->>Interceptor: warn, null
269
+ else handler set
270
+ LLM->>Handler: call
271
+ alt resolves
272
+ Handler-->>LLM: body with datachannelToken and datachannelTokenType
273
+ LLM-->>Interceptor: the response
274
+ else rejects
275
+ LLM-->>Interceptor: warn, null
276
+ end
277
+ end
278
+ ```
279
+
280
+ Disconnect:
281
+
282
+ ```mermaid
283
+ sequenceDiagram
284
+ participant Meeting
285
+ participant LLM as LLMChannel
286
+ participant Mercury as Mercury disconnect
287
+ Meeting->>LLM: disconnectLLM(options, sessionId, ownerMeetingId)
288
+ opt ownerMeetingId omitted
289
+ LLM->>LLM: warn, use current owner
290
+ end
291
+ alt not owner
292
+ LLM-->>Meeting: false
293
+ else owner
294
+ LLM->>Mercury: disconnect(options, sessionId)
295
+ alt rejects
296
+ Mercury-->>Meeting: rejection, entry kept
297
+ else resolves
298
+ LLM->>LLM: clear owner, delete entry
299
+ LLM-->>Meeting: true
300
+ end
301
+ end
302
+ Meeting->>LLM: disconnectAllLLM(options)
303
+ LLM->>Mercury: disconnectAll(options)
304
+ LLM->>LLM: clear session map, tokens kept
305
+ ```
306
+
307
+ ## Class and component relationships
308
+
309
+ ```mermaid
310
+ classDiagram
311
+ class Mercury
312
+ class LLMChannel {
313
+ +namespace
314
+ +defaultSessionId
315
+ -connections
316
+ -datachannelTokens
317
+ +registerAndConnect()
318
+ +disconnectLLM()
319
+ +disconnectAllLLM()
320
+ +setDatachannelToken()
321
+ +setRefreshHandler()
322
+ +refreshDataChannelToken()
323
+ }
324
+ class ILLMChannel
325
+ class DataChannelTokenType
326
+ Mercury <|-- LLMChannel
327
+ ILLMChannel <|.. LLMChannel
328
+ LLMChannel ..> DataChannelTokenType : token keys
329
+ ```
330
+
331
+ | Component | Relationship |
332
+ | --------- | ------------ |
333
+ | `Mercury` | Superclass from sibling package internal-plugin-mercury; owns sockets and events |
334
+ | `LLMChannel` | Adds registration, session metadata, ownership, tokens, and URL lookup |
335
+ | `ILLMChannel` | Interface in `src/llm.types.ts` that the class implements |
336
+ | `DataChannelTokenType` | Enum whose values are the default and practice session ids |
337
+
338
+ ## Use cases and flows
339
+
340
+ | Use case | Actor or caller | Primary steps and outcome | Failure or boundary behavior | Evidence |
341
+ | -------- | --------------- | ------------------------- | ---------------------------- | -------- |
342
+ | `UC-001` | Meeting join | `registerAndConnect(locusUrl, datachannelUrl, token)`; the default session registers, connects, and resolves latencies | Rejections carry `timing` | `src/llm.ts`, `test/unit/spec/llm.js` |
343
+ | `UC-002` | Webinar practice session | A second session keyed `llm-practice-session` connects; its events end in `:llm-practice-session` | Default-session state is untouched | `src/llm.ts`, `test/unit/spec/llm.js` |
344
+ | `UC-003` | Token expiry on a data-channel request | The interceptor finds the session by request URL and calls `refreshDataChannelToken`; the meeting's handler returns a new token | `null` when no handler or the handler fails | `src/llm.ts`, `test/unit/spec/llm.js` |
345
+ | `UC-004` | Meeting leave | `disconnectLLM(options, sessionId, meetingId)` closes the session if that meeting owns it | Another meeting's call resolves `false` | `src/llm.ts`, `test/unit/spec/llm.js` |
346
+ | `UC-005` | Full teardown | `disconnectAllLLM(options)` closes every session | Tokens stay cached | `src/llm.ts`, `test/unit/spec/llm.js` |
347
+
348
+ ### Cross-boundary use-case flow
349
+
350
+ | Boundary | Transport | Ordering | Timeout and retry | Recovery |
351
+ | -------- | --------- | -------- | ----------------- | -------- |
352
+ | Data-channel service | HTTP POST through `this.request` | Before any socket for the session | No retry here | Caller calls `registerAndConnect` again |
353
+ | LLM WebSocket service | WebSocket through Mercury | After a successful registration | Mercury backoff; no retry cap in `config.llm` | Mercury close-code policy |
354
+ | Feature toggles | `webex.internal.feature` | Read before the POST and again before connect | None | Rejection rejects the call |
355
+ | Caller refresh handler | In-process promise | On demand | None | `null` on failure (`MOD-009`) |
356
+
357
+ ## Client state model
358
+
359
+ | State or slice | Owner | Initial state | Transition triggers | Reset or persistence boundary |
360
+ | -------------- | ----- | ------------- | ------------------- | ----------------------------- |
361
+ | `connections` entry fields `locusUrl`, `datachannelUrl` | `LLMChannel` | absent | `registerAndConnect` with both URLs | Deleted by `disconnectLLM`; cleared by `disconnectAllLLM` |
362
+ | `connections` entry fields `webSocketUrl`, `binding` | `LLMChannel` | absent | Registration response | Same as above |
363
+ | `connections` entry fields `ownerMeetingId`, `refreshHandler` | `LLMChannel` | absent | `setOwnerMeetingId`, `setRefreshHandler` | Same as above |
364
+ | `datachannelTokens` | `LLMChannel` | default and practice keys set to `undefined` | `setDatachannelToken`, `clearDatachannelToken` | Survives disconnects (`INV-003`); in memory per webex instance |
365
+ | Socket per session | Mercury superclass | none | `connect`, close, disconnect | Owned by Mercury |
366
+
367
+ ## Business rules and invariants
368
+
369
+ | ID | Invariant | WHY | Enforcement source | Test evidence |
370
+ | -- | --------- | --- | ------------------ | ------------- |
371
+ | `INV-001` | The default session id is `llm-default-session` and the practice session id is `llm-practice-session`; `LLM_DEFAULT_SESSION`, `LLM_PRACTICE_SESSION`, and the two `DataChannelTokenType` values use these strings. Default-session events are unsuffixed; other sessions' events end in `:<sessionId>`. | Token keys and session ids line up for the two built-in sessions, and default listeners keep plain event names. | `src/constants.ts`, `src/llm.types.ts`, `src/llm.ts` | `test/unit/spec/llm.js` default-session cases; gap: no test listens for a suffixed event |
372
+ | `INV-002` | A candidate is the owner when the session has no current owner, when the candidate gives no id, or when the ids are equal. | Unowned sessions stay usable and old call sites without ids keep working. | `src/llm.ts` `resolveSessionOwnership` | `test/unit/spec/llm.js` `disconnectLLM skips disconnect when ownerMeetingId does not match` |
373
+ | `INV-003` | Disconnects never clear `datachannelTokens`; only `clearDatachannelToken` removes a token. | A reconnect after disconnect can reuse the cached token. | `src/llm.ts` | Gap: no test sets a token, disconnects, and reads it back |
374
+ | `INV-004` | With the JWT toggle from `MOD-014` on, the registration POST carries the token header when a token is given, and the connect URL carries `subscriptionAwareSubchannels`. With it off, neither is sent. | The JWT flow and subscription-aware subchannels ship together behind one toggle. | `src/llm.ts` | `test/unit/spec/llm.js` `#register` cases and the three `subscriptionAwareSubchannels` cases |
375
+ | `INV-005` | `config.llm` defaults: `pingInterval` 15000, `pongTimeout` 14000, `backoffTimeMax` 32000, `backoffTimeReset` 1000, `forceCloseDelay` 2000 (ms). Each can be overridden by the `MERCURY_*` environment variable named in `src/llm.ts`. | Keepalive and retry timing for LLM sockets. | `src/llm.ts` `config` | Gap: no test asserts the defaults |
376
+
377
+ ## Concurrency and reactive flow
378
+
379
+ - Execution model: single JavaScript event loop; promises for registration, connect, disconnect, and
380
+ refresh.
381
+ - Ordering guarantees: within one `registerAndConnect`, the POST finishes before `connect` starts.
382
+ Nothing orders two calls for the same session.
383
+ - Idempotency and retry: Mercury's `connect` deduplicates per session, but each `registerAndConnect`
384
+ sends its own POST and overwrites `webSocketUrl` and `binding`. This module does not retry
385
+ registration.
386
+ - Shared-state protection: ownership checks only (`INV-002`); no locks.
387
+ - Blocking restrictions: a refresh handler that never settles leaves `refreshDataChannelToken`
388
+ pending.
389
+
390
+ ## State machine
391
+
392
+ Per-session entry in `connections`.
393
+
394
+ ```mermaid
395
+ stateDiagram-v2
396
+ [*] --> Absent
397
+ Absent --> PreConnection: setRefreshHandler
398
+ Absent --> Pending: registerAndConnect with both URLs
399
+ PreConnection --> Pending: registerAndConnect with both URLs
400
+ Pending --> Registered: POST response stored
401
+ Pending --> Pending: POST rejects, entry kept
402
+ Registered --> Connected: connect resolves
403
+ Registered --> Registered: no webSocketUrl or connect rejects
404
+ Connected --> Removed: disconnectLLM by owner
405
+ Registered --> Removed: disconnectLLM by owner
406
+ Connected --> Connected: disconnectLLM by non-owner returns false
407
+ Connected --> Removed: disconnectAllLLM
408
+ Removed --> [*]
409
+ ```
410
+
411
+ Rejected transitions: `setOwnerMeetingId` on an absent session does nothing. A session closed by the
412
+ server stays in `connections` while Mercury reconnects it.
413
+
414
+ ## Protocol and wire format
415
+
416
+ | Message or frame | Version | Producer or serializer | Consumer or parser | Compatibility and ordering rule |
417
+ | ---------------- | ------- | ---------------------- | ------------------ | ------------------------------- |
418
+ | Registration request | Unversioned | `src/llm.ts` `register` | Data-channel service | `POST <datachannelUrl>` with JSON body `deviceUrl`; header `Data-Channel-Auth-Token: <token>` per `INV-004` |
419
+ | Registration response | Unversioned | Data-channel service | `src/llm.ts` `register` | Reads `body.webSocketUrl` and `body.binding`; other fields are ignored |
420
+ | Connect URL query | Unversioned | `src/llm.ts` `buildUrlWithAwareSubchannels` | LLM WebSocket service | `subscriptionAwareSubchannels=transcription` per `INV-004`; Mercury then adds its own query keys |
421
+ | Refresh handler result | Unversioned | Caller handler | Caller of `refreshDataChannelToken` | Declared shape `body.datachannelToken` and `body.datachannelTokenType`; returned unchanged |
422
+ | `RegisterAndConnectTiming` and `error.timing` | Unversioned | `src/llm.ts` | plugin-meetings | `clientLLMDatachannelResponseTime` and `clientLLMWebSocketConnectTime`, integer ms; errors carry only the first |
423
+
424
+ ## Caller-visible failure modes
425
+
426
+ | Condition | Signal or result | Caller behavior | Retry or recovery | Evidence |
427
+ | --------- | ---------------- | --------------- | ----------------- | -------- |
428
+ | Registration request fails | `registerAndConnect` rejects with the request error, no `timing` | Report and retry if wanted | None here | `src/llm.ts` |
429
+ | Response has no `webSocketUrl` | Rejects with `LLM registration for <sessionId> returned no websocket URL` and `timing` | Report registration latency | None | `src/llm.ts`, `test/unit/spec/llm.js` |
430
+ | Mercury `connect` rejects | Rejects with the Mercury error plus `timing` | Report | Mercury may already have retried | `src/llm.ts`, `test/unit/spec/llm.js` |
431
+ | Feature toggle read rejects | `registerAndConnect` rejects | Report | None | `src/llm.ts` |
432
+ | Not the owner | `disconnectLLM` resolves `false`; token read returns `undefined`; writes do nothing | Leave the session to its owner | — | `src/llm.ts`, `test/unit/spec/llm.js` |
433
+ | No refresh handler or handler rejects | `refreshDataChannelToken` resolves `null` | Fall back or fail the request | Set a handler | `src/llm.ts`, `test/unit/spec/llm.js` |
434
+ | Mercury `disconnect` rejects | `disconnectLLM` rejects; the entry stays | Retry teardown | — | `src/llm.ts` |
435
+
436
+ ## Pitfalls and constraints
437
+
438
+ - `registerAndConnect` with a missing `locusUrl` or `datachannelUrl` still calls `register`, which
439
+ POSTs to `datachannelUrl` even when it is `undefined`. Only the connect step is skipped. The
440
+ invalid-input unit case replaces `register` with a stub, so the POST is not exercised.
441
+ - `buildUrlWithAwareSubchannels` uses `new URL`, so an unparsable `webSocketUrl` throws when the
442
+ toggle is on. That rejection happens before the connect timer and has no `timing`.
443
+ - The toggle is read twice, once before the POST and once before connect. A change in between can send
444
+ the token header without the query parameter, or the reverse.
445
+ - Ownership for tokens uses the token key as the session id (`MOD-007`). The rule lines up only
446
+ because the built-in keys equal the built-in session ids (`INV-001`); a custom token key is checked
447
+ against a session of the same name.
448
+ - `clearDatachannelToken` deletes the key, so the default and practice keys disappear from the record
449
+ after a clear. Reads still return `undefined`.
450
+ - `disconnectAllLLM` has no ownership check, so one meeting's teardown closes sessions another
451
+ meeting owns. The omitted-owner path of `disconnectLLM` is the trade-off recorded under Key design
452
+ trade-off.
453
+ - `registerInternalPlugin('llm', …)` passes no `onBeforeLogout`. Mercury's logout hook is registered
454
+ for the `mercury` plugin only, so webex logout does not call this plugin's `disconnectAllLLM` through
455
+ registration.
456
+ - `config.llm` has no `maxRetries` or `initialConnectionMaxRetries`, so Mercury retries LLM sessions
457
+ without limit. Environment overrides arrive as strings, not numbers.
458
+ - `getAllConnections` returns entries that include `refreshHandler`, which its declared return type
459
+ omits, and the entry objects are shared with the internal map.
460
+ - `refreshDataChannelToken`'s JSDoc says it returns a string; it returns the handler response or
461
+ `null`.
462
+ - The pathname-prefix fallback in `matchesDatachannelRequestUrl` is a plain string prefix, so a
463
+ stored pathname can match a longer sibling path. The first matching session wins.
464
+ - The unit case named `connects without subscriptionAwareSubchannels when token enabled BUT token
465
+ missing` asserts that the parameter is present, which is what the code does.
466
+ - Two `#disconnectLLM` unit cases call a stand-in object defined in the test, not `LLMChannel`.
467
+
468
+ ## Module-specific rules
469
+
470
+ - Do: start log lines with `llm#<method> -->` as the existing ones do.
471
+ - Do: run `resolveSessionOwnership` before any write that a non-owner must not make, and log the
472
+ refusal at info level.
473
+ - Do: default session arguments to `LLM_DEFAULT_SESSION`, and token keys to
474
+ `DataChannelTokenType.Default`.
475
+ - Do: keep token storage out of `connections` (`INV-003`).
476
+ - Do not: add a field to `connections` entries without updating `ILLMChannel` and the
477
+ `getAllConnections` type.
478
+ - Do not: change the header name, the toggle name, or the query parameter without the consumers in
479
+ plugin-meetings.
480
+
481
+ ## Export stability
482
+
483
+ | Export or entry point | Consumer | Stability | Versioning and deprecation rule | Declaration or API report |
484
+ | --------------------- | -------- | --------- | ------------------------------- | ------------------------- |
485
+ | default export `LLMChannel` | Tests | Internal plugin | README says semver is not strictly followed | `src/index.ts` |
486
+ | `DataChannelTokenType` | plugin-meetings | Stable values | Values equal session ids (`INV-001`); changing them is breaking | `src/llm.types.ts` |
487
+ | `LLM_DEFAULT_SESSION`, `LLM_PRACTICE_SESSION` | plugin-meetings, internal-plugin-voicea | Stable values | Changing them is breaking | `src/constants.ts` |
488
+ | `RegisterAndConnectTiming` type | plugin-meetings | Stable shape | Adding optional fields is compatible | `src/llm.types.ts` |
489
+ | Registration as `llm` | Every webex instance | Stable | Required by plugins reading `webex.internal.llm` | `src/index.ts` |
490
+ | Event names (`llm-plugin-events`) | plugin-meetings | Stable | Inherited from Mercury; renaming is breaking | `src/llm.ts` |
491
+
492
+ `config` and `LLMChannel` as a named export are not exported from `src/index.ts`. Tests import the
493
+ class through the deep path `src/llm`.
494
+
495
+ ## Key design trade-off
496
+
497
+ | Chosen trade-off | Preserved invariant or benefit | Cost or limitation | Decision evidence |
498
+ | ---------------- | ------------------------------ | ------------------ | ----------------- |
499
+ | Token cache separate from the connection map | Reconnects can reuse a cached token (`INV-003`) | Tokens outlive sessions until `clearDatachannelToken` | `src/llm.ts` field comment |
500
+ | Omitted owner ids pass ownership | Old call sites keep working (`INV-002`) | Any caller without an id can tear down a session | `src/llm.ts` `disconnectLLM` comment |
501
+ | Pre-connection session entries | Refresh can be wired before registration | An entry can exist with no URLs or socket | `src/llm.ts` `setRefreshHandler` comment |
502
+
503
+ ## Verification
504
+
505
+ | Requirement or invariant | Test level | Positive evidence | Negative or boundary evidence | Gap |
506
+ | ------------------------ | ---------- | ----------------- | ----------------------------- | --- |
507
+ | `MOD-001` | Unit (indirect) | `test/unit/spec/llm.js` MockWebex setup | none found | No registration assertion |
508
+ | `MOD-002`, `MOD-004` | Unit | `test/unit/spec/llm.js` `#registerAndConnect`, `#registerAndConnect timing` | `test/unit/spec/llm.js` missing URL, no websocket URL, connect failure | Real POST with a missing URL |
509
+ | `MOD-003`, `INV-004` | Unit | `test/unit/spec/llm.js` `#register` | `test/unit/spec/llm.js` toggle off, no token | Error log path |
510
+ | `MOD-005` | Unit | `test/unit/spec/llm.js` accessor cases | `test/unit/spec/llm.js` no-connection cases | `getBinding` with a value |
511
+ | `MOD-006`, `INV-002` | Unit | `test/unit/spec/llm.js` owner cases | `test/unit/spec/llm.js` mismatched owner | `resolveSessionOwnership` direct |
512
+ | `MOD-007` | Unit | `test/unit/spec/llm.js` token cases | none found | Refused calls; `clearDatachannelToken` |
513
+ | `MOD-008`, `MOD-009` | Unit | `test/unit/spec/llm.js` refresh cases | `test/unit/spec/llm.js` no handler, rejection | Refused owner |
514
+ | `MOD-010`, `MOD-011`, `MOD-012` | Unit | `test/unit/spec/llm.js` multi-connection and legacy cases | `test/unit/spec/llm.js` mismatched owner | Rejection on the real class |
515
+ | `MOD-013` | Unit | `test/unit/spec/llm.js` URL lookup cases | `test/unit/spec/llm.js` no match, no connections | Parse error |
516
+ | `MOD-014`, `MOD-015` | Unit | `test/unit/spec/llm.js` | none found | Direct URL-builder case |
517
+ | `INV-001` | Unit (partial) | `test/unit/spec/llm.js` default-session cases | none found | Suffixed event names |
518
+ | `INV-003` | none | `src/llm.ts` | none found | Token survives disconnect |
519
+ | `INV-005` | none | `src/llm.ts` | none found | Defaults and string env values |
520
+
521
+ Unit checks run with `yarn workspace @webex/internal-plugin-llm test:unit`. The browser runner and its
522
+ current zero-file result are described in [Getting started](../../docs/getting-started.md).
package/src/index.ts CHANGED
@@ -1,10 +1,18 @@
1
1
  import * as WebexCore from '@webex/webex-core';
2
- import LLMChannel, {config} from './llm';
2
+ import LLMPlugin, {config} from './llm-plugin';
3
3
  import {DataChannelTokenType} from './llm.types';
4
4
 
5
- WebexCore.registerInternalPlugin('llm', LLMChannel, {
5
+ export type {RegisterAndConnectTiming} from './llm.types';
6
+
7
+ WebexCore.registerInternalPlugin('llm', LLMPlugin, {
6
8
  config,
9
+ onBeforeLogout() {
10
+ return this.disconnectAllChannels();
11
+ },
7
12
  });
8
13
 
9
14
  export {DataChannelTokenType};
15
+ export {LLM_DEFAULT_SESSION, LLM_PRACTICE_SESSION} from './constants';
10
16
  export {default} from './llm';
17
+ export {default as LLMPlugin} from './llm-plugin';
18
+ export type {ILLMChannel, ILLMPlugin} from './llm.types';