@ractive-ch/tab-mcp-client 0.15.0 → 0.16.1

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 (59) hide show
  1. package/README.md +481 -148
  2. package/always-allowed.d.ts +25 -6
  3. package/cdn/confirm-y30cx7e1.min.js +4 -0
  4. package/cdn/confirm-y30cx7e1.min.js.map +10 -0
  5. package/cdn/connect-bbhj2y7w.min.js +6 -0
  6. package/cdn/connect-bbhj2y7w.min.js.map +12 -0
  7. package/cdn/connection-w97tf22a.min.js +17 -0
  8. package/cdn/connection-w97tf22a.min.js.map +22 -0
  9. package/cdn/index-vt5zk9me.min.js +91 -0
  10. package/cdn/index-vt5zk9me.min.js.map +13 -0
  11. package/cdn/tab-mcp-client.min.js +3 -3
  12. package/cdn/tab-mcp-client.min.js.map +6 -7
  13. package/cdn/webmcp-khy4f5rj.min.js +4 -0
  14. package/cdn/webmcp-khy4f5rj.min.js.map +10 -0
  15. package/confirm-fgnjgd08.js +263 -0
  16. package/confirm-fgnjgd08.js.map +10 -0
  17. package/confirm.d.ts +54 -0
  18. package/connect-8jpb0k29.js +484 -0
  19. package/connect-8jpb0k29.js.map +10 -0
  20. package/connect.d.ts +40 -0
  21. package/{connection-g6wk37yd.js → connection-g91xjjgm.js} +252 -126
  22. package/connection-g91xjjgm.js.map +16 -0
  23. package/connection.d.ts +7 -4
  24. package/dialog.d.ts +83 -0
  25. package/{index-nmn1j689.js → index-5jyqehpk.js} +14 -10
  26. package/index-5jyqehpk.js.map +11 -0
  27. package/index-jnz7w9xa.js +392 -0
  28. package/index-jnz7w9xa.js.map +12 -0
  29. package/index.d.ts +1 -1
  30. package/index.js +234 -263
  31. package/index.js.map +6 -7
  32. package/internal.d.ts +2 -0
  33. package/mapping.d.ts +37 -4
  34. package/mcp.d.ts +28 -8
  35. package/package.json +1 -1
  36. package/protocol.d.ts +8 -0
  37. package/react.d.ts +8 -10
  38. package/react.js +18 -14
  39. package/react.js.map +3 -3
  40. package/registry.d.ts +12 -5
  41. package/secret.d.ts +5 -2
  42. package/serve.d.ts +26 -4
  43. package/setup.d.ts +15 -25
  44. package/setup.js +1 -1
  45. package/strings.d.ts +107 -0
  46. package/tab-mcp.d.ts +63 -35
  47. package/types.d.ts +146 -68
  48. package/webmcp-zq1enyz0.js +57 -0
  49. package/webmcp-zq1enyz0.js.map +10 -0
  50. package/webmcp.d.ts +13 -24
  51. package/cdn/connection-hgt931xk.min.js +0 -12
  52. package/cdn/connection-hgt931xk.min.js.map +0 -22
  53. package/cdn/ui-2nv84ry7.min.js +0 -86
  54. package/cdn/ui-2nv84ry7.min.js.map +0 -14
  55. package/connection-g6wk37yd.js.map +0 -16
  56. package/index-nmn1j689.js.map +0 -11
  57. package/ui-04mwfxm9.js +0 -783
  58. package/ui-04mwfxm9.js.map +0 -11
  59. package/ui.d.ts +0 -83
package/index.js CHANGED
@@ -3,17 +3,28 @@ var NAME = /^[A-Za-z0-9_.-]{1,128}$/;
3
3
  function isPlainObject(v) {
4
4
  return typeof v === "object" && v !== null && !Array.isArray(v);
5
5
  }
6
- function usesMcpHeader(schema, depth = 0) {
7
- if (depth > 64 || typeof schema !== "object" || schema === null)
8
- return false;
9
- if (!Array.isArray(schema) && "x-mcp-header" in schema)
10
- return true;
11
- return Object.values(schema).some((v) => usesMcpHeader(v, depth + 1));
6
+ var DATA = /^(default|examples|const|enum)$/;
7
+ var NAMED = /^(properties|patternProperties|\$defs|definitions|dependentSchemas)$/;
8
+ function eachSchema(node, visit, depth = 0, map = false) {
9
+ if (depth > 64 || typeof node !== "object" || node === null)
10
+ return;
11
+ map ||= Array.isArray(node);
12
+ if (!map)
13
+ visit(node);
14
+ for (const [key, value] of Object.entries(node))
15
+ if (map || !DATA.test(key))
16
+ eachSchema(value, visit, depth + 1, !map && NAMED.test(key));
12
17
  }
13
18
  function resolvePointer(root, pointer) {
14
19
  let node = root;
15
20
  for (const raw of pointer.split("/").slice(1)) {
16
- const key = decodeURIComponent(raw).replaceAll("~1", "/").replaceAll("~0", "~");
21
+ let key;
22
+ try {
23
+ key = decodeURIComponent(raw);
24
+ } catch {
25
+ return;
26
+ }
27
+ key = key.replaceAll("~1", "/").replaceAll("~0", "~");
17
28
  if (typeof node !== "object" || node === null || !Object.hasOwn(node, key))
18
29
  return;
19
30
  node = node[key];
@@ -24,25 +35,22 @@ function schemaProblem(root) {
24
35
  const anchors = new Set;
25
36
  const refs = [];
26
37
  const patterns = [];
27
- const walk = (node, depth) => {
28
- if (depth > 64 || typeof node !== "object" || node === null)
29
- return;
30
- if (!Array.isArray(node)) {
31
- const o = node;
32
- if (typeof o["$anchor"] === "string")
33
- anchors.add(o["$anchor"]);
34
- if (typeof o["$ref"] === "string")
35
- refs.push(o["$ref"]);
36
- if (typeof o["pattern"] === "string")
37
- patterns.push(o["pattern"]);
38
- const pp = o["patternProperties"];
39
- if (typeof pp === "object" && pp !== null)
40
- patterns.push(...Object.keys(pp));
41
- }
42
- for (const v of Object.values(node))
43
- walk(v, depth + 1);
44
- };
45
- walk(root, 0);
38
+ let header = false;
39
+ eachSchema(root, (o) => {
40
+ if (typeof o["$anchor"] === "string")
41
+ anchors.add(o["$anchor"]);
42
+ if (typeof o["$ref"] === "string")
43
+ refs.push(o["$ref"]);
44
+ if (typeof o["pattern"] === "string")
45
+ patterns.push(o["pattern"]);
46
+ const pp = o["patternProperties"];
47
+ if (isPlainObject(pp))
48
+ patterns.push(...Object.keys(pp));
49
+ if ("x-mcp-header" in o)
50
+ header = true;
51
+ });
52
+ if (header)
53
+ return "x-mcp-header is not supported by tab-mcp";
46
54
  for (const p of patterns) {
47
55
  try {
48
56
  new RegExp(p, "u");
@@ -63,7 +71,15 @@ function schemaProblem(root) {
63
71
  function validateTool(tool) {
64
72
  if (!isPlainObject(tool))
65
73
  throw new TypeError("registerTool: the tool must be an object");
66
- const { name, title, description, inputSchema, execute, annotations } = tool;
74
+ const {
75
+ name,
76
+ title,
77
+ description,
78
+ inputSchema,
79
+ outputSchema,
80
+ execute,
81
+ annotations
82
+ } = tool;
67
83
  if (typeof name !== "string" || !NAME.test(name)) {
68
84
  throw new TypeError(`registerTool: the name must be 1–128 characters of A–Z, a–z, 0–9, "_", "-" or "." (got ${JSON.stringify(name)})`);
69
85
  }
@@ -76,23 +92,22 @@ function validateTool(tool) {
76
92
  if (typeof execute !== "function") {
77
93
  throw new TypeError(`registerTool: tool ${name} needs an execute function`);
78
94
  }
79
- const schema = inputSchema ?? { type: "object" };
80
- if (!isPlainObject(schema) || schema["type"] !== "object") {
81
- throw new TypeError(`registerTool: the inputSchema of ${name} must be a JSON Schema object with "type": "object"`);
82
- }
83
- if (usesMcpHeader(schema)) {
84
- throw new TypeError(`registerTool: ${name} uses x-mcp-header, which tab-mcp does not support`);
85
- }
86
- const problem = schemaProblem(schema);
87
- if (problem !== undefined) {
88
- throw new TypeError(`registerTool: the inputSchema of ${name}: ${problem}`);
89
- }
90
- let copied;
91
- try {
92
- copied = JSON.parse(JSON.stringify(schema));
93
- } catch {
94
- throw new TypeError(`registerTool: the inputSchema of ${name} must be JSON`);
95
- }
95
+ const copy = (schema, what) => {
96
+ if (!isPlainObject(schema) || schema["type"] !== "object") {
97
+ throw new TypeError(`registerTool: the ${what} of ${name} must be a JSON Schema object with "type": "object"`);
98
+ }
99
+ let copied;
100
+ try {
101
+ copied = JSON.parse(JSON.stringify(schema));
102
+ } catch {
103
+ throw new TypeError(`registerTool: the ${what} of ${name} must be JSON`);
104
+ }
105
+ const problem = schemaProblem(copied);
106
+ if (problem !== undefined)
107
+ throw new TypeError(`registerTool: the ${what} of ${name}: ${problem}`);
108
+ return copied;
109
+ };
110
+ const copied = copy(inputSchema ?? { type: "object" }, "inputSchema");
96
111
  if (annotations !== undefined && !isPlainObject(annotations)) {
97
112
  throw new TypeError(`registerTool: the annotations of ${name} must be an object`);
98
113
  }
@@ -100,12 +115,15 @@ function validateTool(tool) {
100
115
  for (const [key, value] of Object.entries(annotations ?? {})) {
101
116
  if (typeof value === "boolean")
102
117
  hints[key] = value;
118
+ else if (value !== undefined && /Hint$|^debugging$/.test(key))
119
+ throw new TypeError(`registerTool: ${key} of ${name} must be a boolean`);
103
120
  }
104
121
  return {
105
122
  name,
106
123
  title,
107
124
  description,
108
125
  inputSchema: copied,
126
+ outputSchema: outputSchema === undefined ? undefined : copy(outputSchema, "outputSchema"),
109
127
  annotations: hints,
110
128
  execute
111
129
  };
@@ -116,10 +134,16 @@ class ToolRegistry {
116
134
  #listeners = new Set;
117
135
  #compile;
118
136
  register(tool, options = {}) {
119
- const { signal, webmcp } = options;
120
- const registered = { ...validateTool(tool), webmcp };
121
- if (signal?.aborted)
122
- return;
137
+ const { signal, exposedTo } = options;
138
+ const callers = options.callers && [...options.callers];
139
+ if ("webmcp" in options || callers?.some((c) => !/^(relay|local|webmcp)$/.test(c)))
140
+ throw new TypeError('registerTool: callers must be "relay", "local" or "webmcp"; option webmcp is gone');
141
+ const registered = {
142
+ ...validateTool(tool),
143
+ callers,
144
+ exposedTo
145
+ };
146
+ signal?.throwIfAborted();
123
147
  if (this.#tools.has(registered.name)) {
124
148
  throw new DOMException(`registerTool: a tool named ${registered.name} is already registered`, "InvalidStateError");
125
149
  }
@@ -187,7 +211,7 @@ class SecretStore {
187
211
  this.#oldKey = oldKey;
188
212
  this.#claimKey = oldKey === undefined ? undefined : `${oldKey}#moved`;
189
213
  }
190
- get() {
214
+ current() {
191
215
  let stored = null;
192
216
  try {
193
217
  stored = this.#storage?.getItem(this.#key) ?? null;
@@ -203,7 +227,7 @@ class SecretStore {
203
227
  this.#memory = stored;
204
228
  return stored;
205
229
  }
206
- return this.#memory ?? this.rotate();
230
+ return this.#memory;
207
231
  }
208
232
  rotate() {
209
233
  const secret = newSecret();
@@ -220,123 +244,30 @@ class SecretStore {
220
244
  }
221
245
  }
222
246
  // package.json
223
- var version = "0.15.0";
247
+ var version = "0.16.1";
224
248
 
225
249
  // src/version.ts
226
250
  var LIBRARY_NAME = "@ractive-ch/tab-mcp-client";
227
251
  var VERSION = version;
228
252
 
229
- // src/webmcp.ts
230
- var g = globalThis;
231
- var getContext;
232
- var Native;
233
- function capture() {
234
- getContext = g.Document && Object.getOwnPropertyDescriptor(g.Document.prototype, "modelContext")?.get;
235
- Native = g.ModelContext;
236
- }
237
- capture();
253
+ // src/tab-mcp.ts
238
254
  function nativeContext() {
239
255
  try {
240
- const context = getContext?.call(g.document);
241
- return Native !== undefined && context instanceof Native ? context : undefined;
256
+ return Object.getOwnPropertyDescriptor(Document.prototype, "modelContext")?.get?.call(document);
242
257
  } catch {
243
258
  return;
244
259
  }
245
260
  }
246
- var HINTS = [
247
- "readOnlyHint",
248
- "untrustedContentHint",
249
- "consequentialHint",
250
- "debugging"
251
- ];
252
- var ATTRIBUTE = "data-tab-mcp-webmcp";
253
- var listed = new Set;
254
- function writeAttribute() {
255
- g.document?.documentElement?.setAttribute(ATTRIBUTE, [...listed].map((m) => m.name).join(" "));
256
- }
257
- function mirror(registry, context, offered, call) {
258
- const mirrors = new Map;
259
- const warned = new Set;
260
- const register = (tool, entry, retry) => {
261
- const annotations = {};
262
- for (const key of HINTS) {
263
- const value = tool.annotations[key];
264
- if (value !== undefined)
265
- annotations[key] = value;
266
- }
267
- const native = {
268
- name: tool.name,
269
- title: tool.title,
270
- description: tool.description,
271
- inputSchema: tool.inputSchema,
272
- annotations,
273
- execute: (input, options) => call(tool, input, options?.signal)
274
- };
275
- const { signal } = entry.controller;
276
- Promise.resolve().then(() => signal.aborted || context.registerTool(native, { signal })).catch((error) => {
277
- if (signal.aborted)
278
- return;
279
- if (retry) {
280
- setTimeout(() => register(tool, entry, false));
281
- return;
282
- }
283
- listed.delete(entry);
284
- writeAttribute();
285
- if (warned.has(tool.name))
286
- return;
287
- warned.add(tool.name);
288
- console.warn(`tab-mcp: ${tool.name} is not offered through WebMCP:`, error);
289
- });
290
- };
291
- const sync = () => {
292
- for (const [tool, entry] of mirrors) {
293
- if (registry.get(tool.name) === tool)
294
- continue;
295
- entry.controller.abort();
296
- mirrors.delete(tool);
297
- listed.delete(entry);
298
- }
299
- for (const tool of registry.list()) {
300
- if (mirrors.has(tool) || !offered(tool))
301
- continue;
302
- const entry = { name: tool.name, controller: new AbortController };
303
- mirrors.set(tool, entry);
304
- listed.add(entry);
305
- register(tool, entry, true);
306
- }
307
- writeAttribute();
308
- };
309
- registry.onChange(sync);
310
- sync();
311
- }
312
-
313
- // src/tab-mcp.ts
314
261
  var LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
315
- var RECONNECT_DELAYS_MS = [5000, 1e4, 20000, 40000, 60000];
262
+ var timing = {
263
+ reconnectDelaysMs: [5000, 1e4, 20000, 40000, 60000],
264
+ answerTimeoutMs: 15000
265
+ };
316
266
  var RECONNECT_REASONS = new Set([
317
267
  "network",
318
268
  "heartbeat",
319
269
  "shutdown"
320
270
  ]);
321
- function reconnectDelays(option) {
322
- if (option === false)
323
- return;
324
- if (option === undefined || option === true)
325
- return RECONNECT_DELAYS_MS;
326
- const delays = option.delaysMs ?? RECONNECT_DELAYS_MS;
327
- if (!Array.isArray(delays) || delays.length === 0 || !delays.every((d) => typeof d === "number" && d >= 0 && d < 2 ** 31)) {
328
- throw new TypeError("TabMcp: reconnect.delaysMs: a non-empty list of ms");
329
- }
330
- return [...delays];
331
- }
332
- function delayOption(name, value) {
333
- if (value === undefined)
334
- return;
335
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value >= 2 ** 31) {
336
- throw new TypeError(`TabMcp: ${name} must be a number of milliseconds`);
337
- }
338
- return value;
339
- }
340
271
  function frozenGrant(grant) {
341
272
  return Object.freeze({
342
273
  ...grant,
@@ -394,23 +325,29 @@ function sessionInfo(m) {
394
325
  function noRelay() {
395
326
  return Promise.reject(new TypeError("TabMcp: this TabMcp has no relay"));
396
327
  }
328
+ function changed(error, addressChanged) {
329
+ return Object.assign(Object(error), { addressChanged });
330
+ }
331
+ function notConnected() {
332
+ return Promise.reject(new DOMException("TabMcp: not connected", "InvalidStateError"));
333
+ }
397
334
 
398
335
  class TabMcp extends EventTarget {
399
336
  #registry = new ToolRegistry;
400
337
  #server;
401
338
  #appName;
402
339
  #onConfirm;
403
- #confirmDelayMs;
404
340
  #alwaysAllow;
341
+ #ui;
405
342
  #relayUrl;
406
343
  #secrets;
407
344
  #tabs;
408
- #takenOver = false;
345
+ #stayOn = false;
346
+ #renewing;
409
347
  #identityAssertion;
410
348
  #identity = "none";
411
349
  #identityMessage;
412
350
  #identityRound = 0;
413
- #identityTimeoutMs;
414
351
  #state = "disconnected";
415
352
  #session;
416
353
  #grants = Object.freeze([]);
@@ -419,15 +356,15 @@ class TabMcp extends EventTarget {
419
356
  #connection;
420
357
  #connecting;
421
358
  #generation = 0;
422
- #reconnectDelays;
359
+ #reconnect;
423
360
  #reconnecting;
424
361
  #reconnectTimer;
425
362
  #unwatch;
426
- #pageWaits = false;
427
363
  #connectDialog;
428
364
  #calls = {
429
365
  registry: this.#registry,
430
366
  confirm: (request) => this.#confirm(request),
367
+ ownConfirm: () => !!this.#onConfirm,
431
368
  toolCallStarted: (call) => this.#emit("toolcall", call),
432
369
  toolCallEnded: (call) => this.#emit("toolcallend", call)
433
370
  };
@@ -445,11 +382,10 @@ class TabMcp extends EventTarget {
445
382
  this.#server = { ...server };
446
383
  this.#appName = appName;
447
384
  this.#onConfirm = options.onConfirm;
448
- this.#confirmDelayMs = delayOption("confirmDelayMs", options.confirmDelayMs);
449
385
  this.#alwaysAllow = options.alwaysAllow === true;
386
+ this.#ui = options.ui;
450
387
  this.#identityAssertion = options.identityAssertion;
451
- this.#identityTimeoutMs = delayOption("identityTimeoutMs", options.identityTimeoutMs) ?? 15000;
452
- this.#reconnectDelays = reconnectDelays(options.reconnect);
388
+ this.#reconnect = options.reconnect !== false;
453
389
  if (relay !== undefined) {
454
390
  const key = options.storageKey ?? `tab-mcp:secret:${relay.origin}:${encodeURIComponent(server.name)}`;
455
391
  this.#secrets = new SecretStore(options.storage, key, options.storageKey === undefined ? `tab-mcp:secret:${relay.origin}` : undefined);
@@ -458,7 +394,7 @@ class TabMcp extends EventTarget {
458
394
  this.#registry.onChange(() => this.#emit("toolschange", { tools: this.tools }));
459
395
  const context = options.webmcp === true ? nativeContext() : undefined;
460
396
  if (context !== undefined)
461
- mirror(this.#registry, context, (tool) => tool.webmcp ?? tool.annotations.consequentialHint !== true, (tool, input, signal) => this.#load().then((lazy) => lazy.callFromWebMcp(this.#calls, tool, input, signal)));
397
+ import("./webmcp-zq1enyz0.js").then((m) => m.mirror(this.#registry, context, (tool, input, signal) => this.#load().then((lazy) => lazy.callFromWebMcp(this.#calls, tool, input, signal))), (error) => console.warn("tab-mcp: no tools are offered through WebMCP:", error));
462
398
  }
463
399
  registerTool(tool, options = {}) {
464
400
  try {
@@ -477,12 +413,6 @@ class TabMcp extends EventTarget {
477
413
  get session() {
478
414
  return this.#session;
479
415
  }
480
- get address() {
481
- return this.#session?.address;
482
- }
483
- get appName() {
484
- return this.#session?.appName ?? this.#appName;
485
- }
486
416
  get grants() {
487
417
  return this.#grants;
488
418
  }
@@ -498,9 +428,10 @@ class TabMcp extends EventTarget {
498
428
  refreshIdentity() {
499
429
  const session = this.#session;
500
430
  const ask = this.#identityAssertion;
501
- if (this.#state !== "connected" || session === undefined || ask === undefined) {
502
- return Promise.resolve(false);
503
- }
431
+ if (ask === undefined)
432
+ return Promise.reject(new TypeError("TabMcp: no identityAssertion"));
433
+ if (session === undefined)
434
+ return notConnected();
504
435
  const round = ++this.#identityRound;
505
436
  const connection = this.#connection;
506
437
  this.#setIdentity("pending");
@@ -509,14 +440,15 @@ class TabMcp extends EventTarget {
509
440
  return;
510
441
  this.#identityRound++;
511
442
  this.#setIdentity("none");
512
- }, this.#identityTimeoutMs);
443
+ }, timing.answerTimeoutMs);
513
444
  return new Promise((resolve) => {
514
445
  const settle = (event) => {
515
- if (event.detail.state === "pending")
446
+ const { identity } = event.detail;
447
+ if (identity === "pending")
516
448
  return;
517
449
  this.removeEventListener("identitychange", settle);
518
450
  clearTimeout(timer);
519
- resolve(event.detail.state === "bound");
451
+ resolve(identity);
520
452
  };
521
453
  this.addEventListener("identitychange", settle);
522
454
  Promise.resolve().then(() => ask({ address: session.address, sessionId: session.sessionId })).then((assertion) => {
@@ -542,12 +474,7 @@ class TabMcp extends EventTarget {
542
474
  signOut() {
543
475
  this.#identityRound++;
544
476
  this.#setIdentity("none");
545
- if (this.#state !== "connected")
546
- return false;
547
- return this.#connection?.send({ type: "identity.logout" }) === true;
548
- }
549
- get pairing() {
550
- return this.#pairing;
477
+ return this.#session?.pairing === "oidc" ? this.#ask({ type: "identity.logout" }, () => !this.#grants.length) : notConnected();
551
478
  }
552
479
  get pairingCode() {
553
480
  return this.#pairingCode;
@@ -558,22 +485,20 @@ class TabMcp extends EventTarget {
558
485
  if (this.#state === "connected" && this.#session !== undefined) {
559
486
  return Promise.resolve(this.#session);
560
487
  }
561
- if (this.#connecting !== undefined) {
562
- if (this.#reconnecting !== undefined)
563
- this.#pageWaits = true;
488
+ if (this.#connecting !== undefined)
564
489
  return this.#connecting;
565
- }
566
490
  if (this.#reconnecting !== undefined)
567
- return this.#attemptReconnect(true);
491
+ return this.#attemptReconnect();
568
492
  const activation = globalThis.navigator?.userActivation;
569
493
  if (options.resume !== true && activation !== undefined && !activation.isActive) {
570
494
  return Promise.reject(new DOMException("connect() must be called from a user action, such as a click", "NotAllowedError"));
571
495
  }
572
- return this.#start();
496
+ return this.#renewing ? this.#renewing.then(() => this.connect({ resume: true })) : this.#start();
573
497
  }
574
- #start(revokeAll) {
575
- this.#setState("connecting");
576
- const connecting = this.#open(this.#generation, revokeAll);
498
+ #start() {
499
+ if (!this.#reconnecting)
500
+ this.#setState("connecting");
501
+ const connecting = this.#open(this.#generation);
577
502
  this.#connecting = connecting;
578
503
  connecting.then(() => {
579
504
  if (this.#connecting === connecting)
@@ -583,29 +508,31 @@ class TabMcp extends EventTarget {
583
508
  return;
584
509
  this.#connecting = undefined;
585
510
  this.#connection = undefined;
586
- this.#setState("disconnected");
511
+ if (!this.#reconnecting)
512
+ this.#setState("disconnected");
587
513
  });
588
514
  return connecting;
589
515
  }
590
516
  async#load() {
591
- const lazy = await import("./connection-g6wk37yd.js");
517
+ const lazy = await import("./connection-g91xjjgm.js");
592
518
  for (const error of lazy.compileRegistry(this.#registry))
593
519
  this.#emit("error", { error });
594
520
  return lazy;
595
521
  }
596
- async#open(generation, revokeAll) {
522
+ async#open(generation, takeBack) {
597
523
  const { openConnection, addressIdOf, withAddress } = await this.#load();
598
524
  const relayUrl = this.#relayUrl;
599
525
  if (relayUrl === undefined || this.#secrets === undefined)
600
526
  return noRelay();
601
- const secret = this.#secrets.get();
527
+ const secret = takeBack ?? this.#secrets.current() ?? this.#secrets.rotate();
602
528
  const address = await addressIdOf(secret);
603
529
  if (generation !== this.#generation) {
604
530
  throw new DOMException("The connection was cancelled", "AbortError");
605
531
  }
606
532
  const ref = {};
607
- const connection = openConnection(this.#host(ref), withAddress(relayUrl, address), secret, revokeAll);
608
- ref.connection = connection;
533
+ const connection = openConnection(this.#host(ref), withAddress(relayUrl, address), secret, { address, revokeAll: !!takeBack });
534
+ if (!takeBack)
535
+ ref.connection = connection;
609
536
  this.#connection = connection;
610
537
  return connection.ready;
611
538
  }
@@ -623,31 +550,49 @@ class TabMcp extends EventTarget {
623
550
  this.#end("user");
624
551
  }
625
552
  newAddress() {
626
- if (this.#relayUrl === undefined)
553
+ const secrets = this.#secrets;
554
+ if (!secrets)
627
555
  return noRelay();
628
- if (this.#takenOver) {
629
- this.#end("new_address");
630
- return this.#start(true).then(() => this.#renew(true), (error) => {
631
- this.#takenOver = true;
632
- throw error;
633
- });
634
- }
635
- return this.#renew(false);
556
+ return this.#renewing ??= this.#renew(secrets).finally(() => {
557
+ this.#renewing = undefined;
558
+ });
636
559
  }
637
- #renew(on) {
638
- const wasOn = on || this.#state !== "disconnected" || this.#reconnecting !== undefined;
639
- if (this.#state === "connected")
640
- this.#connection?.send({ type: "grants.revokeAll" });
560
+ async#renew(secrets) {
561
+ const wasOn = this.#state !== "disconnected" || this.#stayOn;
562
+ const old = secrets.current();
641
563
  this.#end("new_address");
642
- this.#secrets?.rotate();
643
- this.#takenOver = false;
644
- return wasOn ? this.connect({ resume: true }) : Promise.resolve(undefined);
564
+ const generation = this.#generation;
565
+ if (old) {
566
+ this.#setState("connecting");
567
+ try {
568
+ await this.#open(generation, old);
569
+ } catch (error) {
570
+ if (generation === this.#generation) {
571
+ this.#setState("disconnected");
572
+ this.#stayOn = wasOn;
573
+ }
574
+ throw changed(error, false);
575
+ } finally {
576
+ if (generation === this.#generation) {
577
+ this.#connection?.close("new_address");
578
+ this.#connection = undefined;
579
+ }
580
+ }
581
+ }
582
+ secrets.rotate();
583
+ this.#setGrants([]);
584
+ if (wasOn)
585
+ await this.#start().catch((error) => {
586
+ throw changed(error, true);
587
+ });
588
+ else
589
+ this.#setState("disconnected");
645
590
  }
646
591
  #end(reason) {
647
592
  this.#stopReconnecting();
593
+ this.#stayOn = false;
648
594
  this.#generation++;
649
595
  const connection = this.#connection;
650
- const wasConnected = this.#state === "connected";
651
596
  this.#connection = undefined;
652
597
  this.#connecting = undefined;
653
598
  connection?.close(reason);
@@ -657,42 +602,41 @@ class TabMcp extends EventTarget {
657
602
  this.#setPairingCode(undefined);
658
603
  this.#identityRound++;
659
604
  this.#setIdentity("none");
660
- this.#setState("disconnected");
661
- if (wasConnected)
662
- this.#emit("disconnected", { reason, code: 1000 });
605
+ this.#setState("disconnected", reason);
663
606
  }
664
607
  #scheduleReconnect(reason, attempt) {
665
- const delays = this.#reconnectDelays;
666
- if (delays === undefined)
667
- return;
668
- const delay = delays[Math.min(attempt, delays.length) - 1] ?? 0;
608
+ const delays = timing.reconnectDelaysMs;
609
+ const delay = (delays[Math.min(attempt, delays.length) - 1] ?? 0) * (0.8 + 0.4 * Math.random());
669
610
  clearTimeout(this.#reconnectTimer);
670
611
  this.#reconnectTimer = setTimeout(() => {
671
612
  this.#attemptReconnect().catch(() => {});
672
613
  }, delay);
673
614
  this.#watch();
674
615
  this.#reconnecting = { reason, attempt, at: Date.now() + delay };
675
- this.#emit("reconnecting", this.#reconnecting);
616
+ this.#setState("reconnecting", attempt > 1 ? undefined : reason);
676
617
  }
677
- #attemptReconnect(byPage = false) {
618
+ #attemptReconnect() {
678
619
  clearTimeout(this.#reconnectTimer);
679
620
  this.#reconnectTimer = undefined;
680
621
  if (this.#connecting !== undefined)
681
622
  return this.#connecting;
682
- const info = this.#reconnecting;
683
- this.#pageWaits = byPage;
684
623
  const attempt = this.#start();
685
624
  attempt.catch((error) => {
686
- const pageWaits = this.#pageWaits;
687
- this.#pageWaits = false;
688
- if (info === undefined || this.#reconnecting !== info)
625
+ const info = this.#reconnecting;
626
+ if (info === undefined || this.#connecting !== undefined)
689
627
  return;
690
628
  const reason = error?.reason;
691
629
  if (reason === undefined || RECONNECT_REASONS.has(reason)) {
692
630
  this.#scheduleReconnect(info.reason, info.attempt + 1);
693
631
  return;
694
632
  }
695
- this.#stopReconnecting(pageWaits ? undefined : error instanceof Error ? error : new Error(String(error)));
633
+ this.#stopReconnecting();
634
+ this.#state = "disconnected";
635
+ this.#emit("error", {
636
+ error: error instanceof Error ? error : new Error(String(error))
637
+ });
638
+ if (this.#state === "disconnected")
639
+ this.#emit("statechange", { state: "disconnected" });
696
640
  });
697
641
  return attempt;
698
642
  }
@@ -716,17 +660,12 @@ class TabMcp extends EventTarget {
716
660
  g.removeEventListener?.("online", now);
717
661
  };
718
662
  }
719
- #stopReconnecting(why) {
663
+ #stopReconnecting() {
720
664
  clearTimeout(this.#reconnectTimer);
721
665
  this.#reconnectTimer = undefined;
722
666
  this.#unwatch?.();
723
667
  this.#unwatch = undefined;
724
- if (this.#reconnecting === undefined)
725
- return;
726
668
  this.#reconnecting = undefined;
727
- if (why !== undefined)
728
- this.#emit("error", { error: why });
729
- this.#emit("reconnecting", null);
730
669
  }
731
670
  startPairing() {
732
671
  if (this.#pairing)
@@ -744,9 +683,37 @@ class TabMcp extends EventTarget {
744
683
  this.#setPairingCode(undefined);
745
684
  }
746
685
  revoke(grantId) {
747
- if (this.#state !== "connected")
748
- return false;
749
- return this.#connection?.send({ type: "grant.revoke", grantId }) === true;
686
+ const gone = () => !this.#grants.some((g) => g.grantId === grantId);
687
+ return gone() ? Promise.resolve() : this.#ask({ type: "grant.revoke", grantId }, gone);
688
+ }
689
+ #ask(message, done) {
690
+ if (!this.#session || this.#connection?.send(message) !== true)
691
+ return notConnected();
692
+ return new Promise((resolve, reject) => {
693
+ const types = ["grantschange", "statechange", "error"];
694
+ const settle = (error) => {
695
+ clearTimeout(timer);
696
+ for (const type of types)
697
+ this.removeEventListener(type, check);
698
+ if (error)
699
+ reject(error);
700
+ else
701
+ resolve();
702
+ };
703
+ const check = (event) => {
704
+ const error = event?.detail?.error;
705
+ if (done())
706
+ settle();
707
+ else if ((error?.code === "store_unavailable" || error?.code === "unknown_id") && (error.for === undefined || error.for === message.type && error.grantId === message.grantId))
708
+ settle(error);
709
+ else if (this.#state !== "connected")
710
+ settle(new DOMException("TabMcp: the session ended before the relay answered", "NetworkError"));
711
+ };
712
+ const timer = setTimeout(() => settle(new DOMException("TabMcp: the relay did not answer", "TimeoutError")), timing.answerTimeoutMs);
713
+ for (const type of types)
714
+ this.addEventListener(type, check);
715
+ check();
716
+ });
750
717
  }
751
718
  showConnectDialog(options = {}) {
752
719
  if (this.#relayUrl === undefined)
@@ -766,8 +733,8 @@ class TabMcp extends EventTarget {
766
733
  async#showConnectDialog(doc) {
767
734
  const connecting = this.connect();
768
735
  connecting.catch(() => {});
769
- const { showConnectDialog } = await import("./ui-04mwfxm9.js");
770
- await showConnectDialog(this, connecting, doc, this.#server.name);
736
+ const { showConnectDialog } = await import("./connect-8jpb0k29.js");
737
+ await showConnectDialog(this, connecting, doc, this.#server.name, this.#ui);
771
738
  }
772
739
  addEventListener(type, listener, options) {
773
740
  super.addEventListener(type, listener, options);
@@ -778,24 +745,27 @@ class TabMcp extends EventTarget {
778
745
  #emit(type, detail) {
779
746
  this.dispatchEvent(new CustomEvent(type, { detail }));
780
747
  }
781
- #setState(state) {
782
- if (this.#state === state)
748
+ #setState(state, reason) {
749
+ if (this.#state === state && state !== "reconnecting")
783
750
  return;
784
751
  this.#state = state;
785
- this.#emit("statechange", { state });
752
+ this.#emit("statechange", reason ? { state, reason } : { state });
786
753
  }
787
- #setIdentity(state, message) {
788
- if (this.#identity === state && message === undefined)
754
+ #setIdentity(identity, message) {
755
+ if (this.#identity === identity && message === undefined)
789
756
  return;
790
- this.#identity = state;
791
- this.#identityMessage = state === "refused" ? message : undefined;
792
- this.#emit("identitychange", message === undefined ? { state } : { state, message });
757
+ this.#identity = identity;
758
+ this.#identityMessage = identity === "refused" ? message : undefined;
759
+ this.#emit("identitychange", {
760
+ identity,
761
+ identityMessage: this.#identityMessage
762
+ });
793
763
  }
794
- #setPairingCode(code) {
795
- if (this.#pairingCode === undefined && code === undefined)
764
+ #setPairingCode(pairingCode) {
765
+ if (this.#pairingCode === undefined && pairingCode === undefined)
796
766
  return;
797
- this.#pairingCode = code;
798
- this.#emit("pairingcode", code ?? null);
767
+ this.#pairingCode = pairingCode;
768
+ this.#emit("pairingcode", { pairingCode });
799
769
  }
800
770
  #setGrants(grants) {
801
771
  this.#grants = Object.freeze(grants.map(frozenGrant));
@@ -808,13 +778,13 @@ class TabMcp extends EventTarget {
808
778
  }
809
779
  return this.confirmInPage(request);
810
780
  }
811
- confirmInPage(request) {
812
- const doc = globalThis.document;
781
+ confirmInPage(request, options = {}) {
782
+ const doc = options.document ?? globalThis.document;
813
783
  if (doc === undefined)
814
784
  return Promise.resolve(false);
815
- return import("./ui-04mwfxm9.js").then((ui) => ui.confirmInPage(this, request, doc, {
816
- allowDelayMs: this.#confirmDelayMs,
817
- alwaysAllow: this.#alwaysAllow
785
+ return import("./confirm-fgnjgd08.js").then((ui) => ui.confirmInPage(this, request, doc, {
786
+ alwaysAllow: this.#alwaysAllow,
787
+ ui: this.#ui
818
788
  }));
819
789
  }
820
790
  #host(ref) {
@@ -843,14 +813,13 @@ class TabMcp extends EventTarget {
843
813
  if (!current())
844
814
  return session;
845
815
  this.#session = session;
846
- this.#takenOver = false;
816
+ this.#stayOn = false;
847
817
  this.#stopReconnecting();
848
- this.#setState("connected");
849
818
  this.#setGrants([...m.grants]);
850
819
  if (this.#pairing)
851
820
  this.#connection?.send({ type: "pairing.start" });
852
- this.#emit("connected", session);
853
- if (session.pairing === "oidc")
821
+ this.#setState("connected");
822
+ if (session.pairing === "oidc" && this.#identityAssertion)
854
823
  this.refreshIdentity();
855
824
  return session;
856
825
  },
@@ -889,21 +858,23 @@ class TabMcp extends EventTarget {
889
858
  if (current())
890
859
  this.#emit("error", { error });
891
860
  },
892
- closed: (reason, code) => {
861
+ closed: (reason) => {
893
862
  if (!current())
894
863
  return;
895
864
  if (reason === "replaced")
896
- this.#takenOver = replacedHere = true;
897
- const generation = this.#generation;
865
+ this.#stayOn = replacedHere = true;
898
866
  this.#connection = undefined;
899
867
  this.#session = undefined;
868
+ const generation = this.#generation;
900
869
  this.#setPairingCode(undefined);
901
870
  this.#identityRound++;
902
871
  this.#setIdentity("none");
903
- this.#setState("disconnected");
904
- this.#emit("disconnected", { reason, code });
905
- if (RECONNECT_REASONS.has(reason) && this.#generation === generation && this.#state === "disconnected" && this.#connecting === undefined)
872
+ if (generation !== this.#generation)
873
+ return;
874
+ if (this.#reconnect && RECONNECT_REASONS.has(reason))
906
875
  this.#scheduleReconnect(reason, 1);
876
+ else
877
+ this.#setState("disconnected", reason);
907
878
  }
908
879
  };
909
880
  }
@@ -913,5 +884,5 @@ export {
913
884
  VERSION
914
885
  };
915
886
 
916
- //# debugId=DD8CA08955DA711064756E2164756E21
887
+ //# debugId=D030C918FD0C08F264756E2164756E21
917
888
  //# sourceMappingURL=index.js.map