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

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 (53) hide show
  1. package/README.md +454 -147
  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-0y7ngtq7.min.js +17 -0
  8. package/cdn/connection-0y7ngtq7.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 -6
  13. package/confirm-fgnjgd08.js +263 -0
  14. package/confirm-fgnjgd08.js.map +10 -0
  15. package/confirm.d.ts +54 -0
  16. package/connect-8jpb0k29.js +484 -0
  17. package/connect-8jpb0k29.js.map +10 -0
  18. package/connect.d.ts +40 -0
  19. package/{connection-g6wk37yd.js → connection-1d8rxgbq.js} +247 -126
  20. package/connection-1d8rxgbq.js.map +16 -0
  21. package/connection.d.ts +7 -4
  22. package/dialog.d.ts +83 -0
  23. package/{index-nmn1j689.js → index-5jyqehpk.js} +14 -10
  24. package/index-5jyqehpk.js.map +11 -0
  25. package/index-jnz7w9xa.js +392 -0
  26. package/index-jnz7w9xa.js.map +12 -0
  27. package/index.d.ts +1 -1
  28. package/index.js +257 -240
  29. package/index.js.map +6 -6
  30. package/mapping.d.ts +37 -4
  31. package/mcp.d.ts +23 -8
  32. package/package.json +1 -1
  33. package/react.d.ts +8 -10
  34. package/react.js +18 -14
  35. package/react.js.map +3 -3
  36. package/registry.d.ts +12 -5
  37. package/secret.d.ts +5 -2
  38. package/serve.d.ts +26 -4
  39. package/setup.d.ts +15 -25
  40. package/setup.js +1 -1
  41. package/strings.d.ts +107 -0
  42. package/tab-mcp.d.ts +60 -35
  43. package/types.d.ts +146 -68
  44. package/webmcp.d.ts +13 -18
  45. package/cdn/connection-hgt931xk.min.js +0 -12
  46. package/cdn/connection-hgt931xk.min.js.map +0 -22
  47. package/cdn/ui-2nv84ry7.min.js +0 -86
  48. package/cdn/ui-2nv84ry7.min.js.map +0 -14
  49. package/connection-g6wk37yd.js.map +0 -16
  50. package/index-nmn1j689.js.map +0 -11
  51. package/ui-04mwfxm9.js +0 -783
  52. package/ui-04mwfxm9.js.map +0 -11
  53. 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,25 +244,16 @@ class SecretStore {
220
244
  }
221
245
  }
222
246
  // package.json
223
- var version = "0.15.0";
247
+ var version = "0.16.0";
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
253
  // 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();
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
  }
@@ -249,62 +264,46 @@ var HINTS = [
249
264
  "consequentialHint",
250
265
  "debugging"
251
266
  ];
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) {
267
+ function mirror(registry, context, call) {
258
268
  const mirrors = new Map;
259
269
  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
270
  const sync = () => {
292
- for (const [tool, entry] of mirrors) {
271
+ for (const [tool, controller] of mirrors) {
293
272
  if (registry.get(tool.name) === tool)
294
273
  continue;
295
- entry.controller.abort();
274
+ controller.abort();
296
275
  mirrors.delete(tool);
297
- listed.delete(entry);
298
276
  }
299
277
  for (const tool of registry.list()) {
300
- if (mirrors.has(tool) || !offered(tool))
278
+ const { annotations, callers } = tool;
279
+ const consequential = annotations.consequentialHint ?? annotations.destructiveHint;
280
+ if (mirrors.has(tool) || !(callers?.includes("webmcp") ?? !consequential))
301
281
  continue;
302
- const entry = { name: tool.name, controller: new AbortController };
303
- mirrors.set(tool, entry);
304
- listed.add(entry);
305
- register(tool, entry, true);
282
+ const controller = new AbortController;
283
+ mirrors.set(tool, controller);
284
+ const hints = {
285
+ consequentialHint: consequential
286
+ };
287
+ for (const key of HINTS)
288
+ hints[key] ??= annotations[key];
289
+ const { signal } = controller;
290
+ Promise.resolve().then(() => signal.aborted || context.registerTool({
291
+ name: tool.name,
292
+ title: tool.title,
293
+ description: tool.description,
294
+ inputSchema: tool.inputSchema,
295
+ outputSchema: tool.outputSchema,
296
+ annotations: hints,
297
+ execute: (input, options) => call(tool, input, options?.signal)
298
+ }, { signal, exposedTo: tool.exposedTo })).catch((error) => {
299
+ if (signal.aborted)
300
+ return;
301
+ if (warned.has(tool.name))
302
+ return;
303
+ warned.add(tool.name);
304
+ console.warn(`tab-mcp: ${tool.name} is not offered through WebMCP:`, error);
305
+ });
306
306
  }
307
- writeAttribute();
308
307
  };
309
308
  registry.onChange(sync);
310
309
  sync();
@@ -312,31 +311,15 @@ function mirror(registry, context, offered, call) {
312
311
 
313
312
  // src/tab-mcp.ts
314
313
  var LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
315
- var RECONNECT_DELAYS_MS = [5000, 1e4, 20000, 40000, 60000];
314
+ var timing = {
315
+ reconnectDelaysMs: [5000, 1e4, 20000, 40000, 60000],
316
+ answerTimeoutMs: 15000
317
+ };
316
318
  var RECONNECT_REASONS = new Set([
317
319
  "network",
318
320
  "heartbeat",
319
321
  "shutdown"
320
322
  ]);
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
323
  function frozenGrant(grant) {
341
324
  return Object.freeze({
342
325
  ...grant,
@@ -394,23 +377,26 @@ function sessionInfo(m) {
394
377
  function noRelay() {
395
378
  return Promise.reject(new TypeError("TabMcp: this TabMcp has no relay"));
396
379
  }
380
+ function notConnected() {
381
+ return Promise.reject(new DOMException("TabMcp: not connected", "InvalidStateError"));
382
+ }
397
383
 
398
384
  class TabMcp extends EventTarget {
399
385
  #registry = new ToolRegistry;
400
386
  #server;
401
387
  #appName;
402
388
  #onConfirm;
403
- #confirmDelayMs;
404
389
  #alwaysAllow;
390
+ #ui;
405
391
  #relayUrl;
406
392
  #secrets;
407
393
  #tabs;
408
- #takenOver = false;
394
+ #stayOn = false;
395
+ #renewing;
409
396
  #identityAssertion;
410
397
  #identity = "none";
411
398
  #identityMessage;
412
399
  #identityRound = 0;
413
- #identityTimeoutMs;
414
400
  #state = "disconnected";
415
401
  #session;
416
402
  #grants = Object.freeze([]);
@@ -419,11 +405,10 @@ class TabMcp extends EventTarget {
419
405
  #connection;
420
406
  #connecting;
421
407
  #generation = 0;
422
- #reconnectDelays;
408
+ #reconnect;
423
409
  #reconnecting;
424
410
  #reconnectTimer;
425
411
  #unwatch;
426
- #pageWaits = false;
427
412
  #connectDialog;
428
413
  #calls = {
429
414
  registry: this.#registry,
@@ -445,11 +430,10 @@ class TabMcp extends EventTarget {
445
430
  this.#server = { ...server };
446
431
  this.#appName = appName;
447
432
  this.#onConfirm = options.onConfirm;
448
- this.#confirmDelayMs = delayOption("confirmDelayMs", options.confirmDelayMs);
449
433
  this.#alwaysAllow = options.alwaysAllow === true;
434
+ this.#ui = options.ui;
450
435
  this.#identityAssertion = options.identityAssertion;
451
- this.#identityTimeoutMs = delayOption("identityTimeoutMs", options.identityTimeoutMs) ?? 15000;
452
- this.#reconnectDelays = reconnectDelays(options.reconnect);
436
+ this.#reconnect = options.reconnect !== false;
453
437
  if (relay !== undefined) {
454
438
  const key = options.storageKey ?? `tab-mcp:secret:${relay.origin}:${encodeURIComponent(server.name)}`;
455
439
  this.#secrets = new SecretStore(options.storage, key, options.storageKey === undefined ? `tab-mcp:secret:${relay.origin}` : undefined);
@@ -458,7 +442,7 @@ class TabMcp extends EventTarget {
458
442
  this.#registry.onChange(() => this.#emit("toolschange", { tools: this.tools }));
459
443
  const context = options.webmcp === true ? nativeContext() : undefined;
460
444
  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)));
445
+ mirror(this.#registry, context, (tool, input, signal) => this.#load().then((lazy) => lazy.callFromWebMcp(this.#calls, tool, input, signal)));
462
446
  }
463
447
  registerTool(tool, options = {}) {
464
448
  try {
@@ -477,12 +461,6 @@ class TabMcp extends EventTarget {
477
461
  get session() {
478
462
  return this.#session;
479
463
  }
480
- get address() {
481
- return this.#session?.address;
482
- }
483
- get appName() {
484
- return this.#session?.appName ?? this.#appName;
485
- }
486
464
  get grants() {
487
465
  return this.#grants;
488
466
  }
@@ -498,9 +476,10 @@ class TabMcp extends EventTarget {
498
476
  refreshIdentity() {
499
477
  const session = this.#session;
500
478
  const ask = this.#identityAssertion;
501
- if (this.#state !== "connected" || session === undefined || ask === undefined) {
502
- return Promise.resolve(false);
503
- }
479
+ if (ask === undefined)
480
+ return Promise.reject(new TypeError("TabMcp: no identityAssertion"));
481
+ if (session === undefined)
482
+ return notConnected();
504
483
  const round = ++this.#identityRound;
505
484
  const connection = this.#connection;
506
485
  this.#setIdentity("pending");
@@ -509,14 +488,15 @@ class TabMcp extends EventTarget {
509
488
  return;
510
489
  this.#identityRound++;
511
490
  this.#setIdentity("none");
512
- }, this.#identityTimeoutMs);
491
+ }, timing.answerTimeoutMs);
513
492
  return new Promise((resolve) => {
514
493
  const settle = (event) => {
515
- if (event.detail.state === "pending")
494
+ const { identity } = event.detail;
495
+ if (identity === "pending")
516
496
  return;
517
497
  this.removeEventListener("identitychange", settle);
518
498
  clearTimeout(timer);
519
- resolve(event.detail.state === "bound");
499
+ resolve(identity);
520
500
  };
521
501
  this.addEventListener("identitychange", settle);
522
502
  Promise.resolve().then(() => ask({ address: session.address, sessionId: session.sessionId })).then((assertion) => {
@@ -542,12 +522,7 @@ class TabMcp extends EventTarget {
542
522
  signOut() {
543
523
  this.#identityRound++;
544
524
  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;
525
+ return this.#session?.pairing === "oidc" ? this.#ask({ type: "identity.logout" }, () => !this.#grants.length) : notConnected();
551
526
  }
552
527
  get pairingCode() {
553
528
  return this.#pairingCode;
@@ -558,22 +533,20 @@ class TabMcp extends EventTarget {
558
533
  if (this.#state === "connected" && this.#session !== undefined) {
559
534
  return Promise.resolve(this.#session);
560
535
  }
561
- if (this.#connecting !== undefined) {
562
- if (this.#reconnecting !== undefined)
563
- this.#pageWaits = true;
536
+ if (this.#connecting !== undefined)
564
537
  return this.#connecting;
565
- }
566
538
  if (this.#reconnecting !== undefined)
567
- return this.#attemptReconnect(true);
539
+ return this.#attemptReconnect();
568
540
  const activation = globalThis.navigator?.userActivation;
569
541
  if (options.resume !== true && activation !== undefined && !activation.isActive) {
570
542
  return Promise.reject(new DOMException("connect() must be called from a user action, such as a click", "NotAllowedError"));
571
543
  }
572
- return this.#start();
544
+ return this.#renewing ? this.#renewing.then(() => this.connect({ resume: true })) : this.#start();
573
545
  }
574
- #start(revokeAll) {
575
- this.#setState("connecting");
576
- const connecting = this.#open(this.#generation, revokeAll);
546
+ #start() {
547
+ if (!this.#reconnecting)
548
+ this.#setState("connecting");
549
+ const connecting = this.#open(this.#generation);
577
550
  this.#connecting = connecting;
578
551
  connecting.then(() => {
579
552
  if (this.#connecting === connecting)
@@ -583,29 +556,31 @@ class TabMcp extends EventTarget {
583
556
  return;
584
557
  this.#connecting = undefined;
585
558
  this.#connection = undefined;
586
- this.#setState("disconnected");
559
+ if (!this.#reconnecting)
560
+ this.#setState("disconnected");
587
561
  });
588
562
  return connecting;
589
563
  }
590
564
  async#load() {
591
- const lazy = await import("./connection-g6wk37yd.js");
565
+ const lazy = await import("./connection-1d8rxgbq.js");
592
566
  for (const error of lazy.compileRegistry(this.#registry))
593
567
  this.#emit("error", { error });
594
568
  return lazy;
595
569
  }
596
- async#open(generation, revokeAll) {
570
+ async#open(generation, takeBack) {
597
571
  const { openConnection, addressIdOf, withAddress } = await this.#load();
598
572
  const relayUrl = this.#relayUrl;
599
573
  if (relayUrl === undefined || this.#secrets === undefined)
600
574
  return noRelay();
601
- const secret = this.#secrets.get();
575
+ const secret = takeBack ?? this.#secrets.current() ?? this.#secrets.rotate();
602
576
  const address = await addressIdOf(secret);
603
577
  if (generation !== this.#generation) {
604
578
  throw new DOMException("The connection was cancelled", "AbortError");
605
579
  }
606
580
  const ref = {};
607
- const connection = openConnection(this.#host(ref), withAddress(relayUrl, address), secret, revokeAll);
608
- ref.connection = connection;
581
+ const connection = openConnection(this.#host(ref), withAddress(relayUrl, address), secret, { address, revokeAll: !!takeBack });
582
+ if (!takeBack)
583
+ ref.connection = connection;
609
584
  this.#connection = connection;
610
585
  return connection.ready;
611
586
  }
@@ -623,31 +598,47 @@ class TabMcp extends EventTarget {
623
598
  this.#end("user");
624
599
  }
625
600
  newAddress() {
626
- if (this.#relayUrl === undefined)
601
+ const secrets = this.#secrets;
602
+ if (!secrets)
627
603
  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);
604
+ return this.#renewing ??= this.#renew(secrets).finally(() => {
605
+ this.#renewing = undefined;
606
+ });
636
607
  }
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" });
608
+ async#renew(secrets) {
609
+ const wasOn = this.#state !== "disconnected" || this.#stayOn;
610
+ const old = secrets.current();
641
611
  this.#end("new_address");
642
- this.#secrets?.rotate();
643
- this.#takenOver = false;
644
- return wasOn ? this.connect({ resume: true }) : Promise.resolve(undefined);
612
+ const generation = this.#generation;
613
+ if (old) {
614
+ this.#setState("connecting");
615
+ try {
616
+ await this.#open(generation, old);
617
+ } catch (error) {
618
+ if (generation === this.#generation) {
619
+ this.#setState("disconnected");
620
+ this.#stayOn = wasOn;
621
+ }
622
+ throw error;
623
+ } finally {
624
+ if (generation === this.#generation) {
625
+ this.#connection?.close("new_address");
626
+ this.#connection = undefined;
627
+ }
628
+ }
629
+ }
630
+ secrets.rotate();
631
+ this.#setGrants([]);
632
+ if (wasOn)
633
+ await this.#start();
634
+ else
635
+ this.#setState("disconnected");
645
636
  }
646
637
  #end(reason) {
647
638
  this.#stopReconnecting();
639
+ this.#stayOn = false;
648
640
  this.#generation++;
649
641
  const connection = this.#connection;
650
- const wasConnected = this.#state === "connected";
651
642
  this.#connection = undefined;
652
643
  this.#connecting = undefined;
653
644
  connection?.close(reason);
@@ -657,42 +648,41 @@ class TabMcp extends EventTarget {
657
648
  this.#setPairingCode(undefined);
658
649
  this.#identityRound++;
659
650
  this.#setIdentity("none");
660
- this.#setState("disconnected");
661
- if (wasConnected)
662
- this.#emit("disconnected", { reason, code: 1000 });
651
+ this.#setState("disconnected", reason);
663
652
  }
664
653
  #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;
654
+ const delays = timing.reconnectDelaysMs;
655
+ const delay = (delays[Math.min(attempt, delays.length) - 1] ?? 0) * (0.8 + 0.4 * Math.random());
669
656
  clearTimeout(this.#reconnectTimer);
670
657
  this.#reconnectTimer = setTimeout(() => {
671
658
  this.#attemptReconnect().catch(() => {});
672
659
  }, delay);
673
660
  this.#watch();
674
661
  this.#reconnecting = { reason, attempt, at: Date.now() + delay };
675
- this.#emit("reconnecting", this.#reconnecting);
662
+ this.#setState("reconnecting", attempt > 1 ? undefined : reason);
676
663
  }
677
- #attemptReconnect(byPage = false) {
664
+ #attemptReconnect() {
678
665
  clearTimeout(this.#reconnectTimer);
679
666
  this.#reconnectTimer = undefined;
680
667
  if (this.#connecting !== undefined)
681
668
  return this.#connecting;
682
- const info = this.#reconnecting;
683
- this.#pageWaits = byPage;
684
669
  const attempt = this.#start();
685
670
  attempt.catch((error) => {
686
- const pageWaits = this.#pageWaits;
687
- this.#pageWaits = false;
688
- if (info === undefined || this.#reconnecting !== info)
671
+ const info = this.#reconnecting;
672
+ if (info === undefined || this.#connecting !== undefined)
689
673
  return;
690
674
  const reason = error?.reason;
691
675
  if (reason === undefined || RECONNECT_REASONS.has(reason)) {
692
676
  this.#scheduleReconnect(info.reason, info.attempt + 1);
693
677
  return;
694
678
  }
695
- this.#stopReconnecting(pageWaits ? undefined : error instanceof Error ? error : new Error(String(error)));
679
+ this.#stopReconnecting();
680
+ this.#state = "disconnected";
681
+ this.#emit("error", {
682
+ error: error instanceof Error ? error : new Error(String(error))
683
+ });
684
+ if (this.#state === "disconnected")
685
+ this.#emit("statechange", { state: "disconnected" });
696
686
  });
697
687
  return attempt;
698
688
  }
@@ -716,17 +706,12 @@ class TabMcp extends EventTarget {
716
706
  g.removeEventListener?.("online", now);
717
707
  };
718
708
  }
719
- #stopReconnecting(why) {
709
+ #stopReconnecting() {
720
710
  clearTimeout(this.#reconnectTimer);
721
711
  this.#reconnectTimer = undefined;
722
712
  this.#unwatch?.();
723
713
  this.#unwatch = undefined;
724
- if (this.#reconnecting === undefined)
725
- return;
726
714
  this.#reconnecting = undefined;
727
- if (why !== undefined)
728
- this.#emit("error", { error: why });
729
- this.#emit("reconnecting", null);
730
715
  }
731
716
  startPairing() {
732
717
  if (this.#pairing)
@@ -744,9 +729,37 @@ class TabMcp extends EventTarget {
744
729
  this.#setPairingCode(undefined);
745
730
  }
746
731
  revoke(grantId) {
747
- if (this.#state !== "connected")
748
- return false;
749
- return this.#connection?.send({ type: "grant.revoke", grantId }) === true;
732
+ const gone = () => !this.#grants.some((g) => g.grantId === grantId);
733
+ return gone() ? Promise.resolve() : this.#ask({ type: "grant.revoke", grantId }, gone);
734
+ }
735
+ #ask(message, done) {
736
+ if (!this.#session || this.#connection?.send(message) !== true)
737
+ return notConnected();
738
+ return new Promise((resolve, reject) => {
739
+ const types = ["grantschange", "statechange", "error"];
740
+ const settle = (error) => {
741
+ clearTimeout(timer);
742
+ for (const type of types)
743
+ this.removeEventListener(type, check);
744
+ if (error)
745
+ reject(error);
746
+ else
747
+ resolve();
748
+ };
749
+ const check = (event) => {
750
+ const error = event?.detail?.error;
751
+ if (done())
752
+ settle();
753
+ else if (error?.code === "store_unavailable" || error?.code === "unknown_id")
754
+ settle(error);
755
+ else if (this.#state !== "connected")
756
+ settle(new DOMException("TabMcp: not connected", "InvalidStateError"));
757
+ };
758
+ const timer = setTimeout(() => settle(new DOMException("TabMcp: the relay did not answer", "TimeoutError")), timing.answerTimeoutMs);
759
+ for (const type of types)
760
+ this.addEventListener(type, check);
761
+ check();
762
+ });
750
763
  }
751
764
  showConnectDialog(options = {}) {
752
765
  if (this.#relayUrl === undefined)
@@ -766,8 +779,8 @@ class TabMcp extends EventTarget {
766
779
  async#showConnectDialog(doc) {
767
780
  const connecting = this.connect();
768
781
  connecting.catch(() => {});
769
- const { showConnectDialog } = await import("./ui-04mwfxm9.js");
770
- await showConnectDialog(this, connecting, doc, this.#server.name);
782
+ const { showConnectDialog } = await import("./connect-8jpb0k29.js");
783
+ await showConnectDialog(this, connecting, doc, this.#server.name, this.#ui);
771
784
  }
772
785
  addEventListener(type, listener, options) {
773
786
  super.addEventListener(type, listener, options);
@@ -778,24 +791,27 @@ class TabMcp extends EventTarget {
778
791
  #emit(type, detail) {
779
792
  this.dispatchEvent(new CustomEvent(type, { detail }));
780
793
  }
781
- #setState(state) {
782
- if (this.#state === state)
794
+ #setState(state, reason) {
795
+ if (this.#state === state && state !== "reconnecting")
783
796
  return;
784
797
  this.#state = state;
785
- this.#emit("statechange", { state });
798
+ this.#emit("statechange", reason ? { state, reason } : { state });
786
799
  }
787
- #setIdentity(state, message) {
788
- if (this.#identity === state && message === undefined)
800
+ #setIdentity(identity, message) {
801
+ if (this.#identity === identity && message === undefined)
789
802
  return;
790
- this.#identity = state;
791
- this.#identityMessage = state === "refused" ? message : undefined;
792
- this.#emit("identitychange", message === undefined ? { state } : { state, message });
803
+ this.#identity = identity;
804
+ this.#identityMessage = identity === "refused" ? message : undefined;
805
+ this.#emit("identitychange", {
806
+ identity,
807
+ identityMessage: this.#identityMessage
808
+ });
793
809
  }
794
- #setPairingCode(code) {
795
- if (this.#pairingCode === undefined && code === undefined)
810
+ #setPairingCode(pairingCode) {
811
+ if (this.#pairingCode === undefined && pairingCode === undefined)
796
812
  return;
797
- this.#pairingCode = code;
798
- this.#emit("pairingcode", code ?? null);
813
+ this.#pairingCode = pairingCode;
814
+ this.#emit("pairingcode", { pairingCode });
799
815
  }
800
816
  #setGrants(grants) {
801
817
  this.#grants = Object.freeze(grants.map(frozenGrant));
@@ -808,13 +824,13 @@ class TabMcp extends EventTarget {
808
824
  }
809
825
  return this.confirmInPage(request);
810
826
  }
811
- confirmInPage(request) {
812
- const doc = globalThis.document;
827
+ confirmInPage(request, options = {}) {
828
+ const doc = options.document ?? globalThis.document;
813
829
  if (doc === undefined)
814
830
  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
831
+ return import("./confirm-fgnjgd08.js").then((ui) => ui.confirmInPage(this, request, doc, {
832
+ alwaysAllow: this.#alwaysAllow,
833
+ ui: this.#ui
818
834
  }));
819
835
  }
820
836
  #host(ref) {
@@ -843,14 +859,13 @@ class TabMcp extends EventTarget {
843
859
  if (!current())
844
860
  return session;
845
861
  this.#session = session;
846
- this.#takenOver = false;
862
+ this.#stayOn = false;
847
863
  this.#stopReconnecting();
848
- this.#setState("connected");
849
864
  this.#setGrants([...m.grants]);
850
865
  if (this.#pairing)
851
866
  this.#connection?.send({ type: "pairing.start" });
852
- this.#emit("connected", session);
853
- if (session.pairing === "oidc")
867
+ this.#setState("connected");
868
+ if (session.pairing === "oidc" && this.#identityAssertion)
854
869
  this.refreshIdentity();
855
870
  return session;
856
871
  },
@@ -889,21 +904,23 @@ class TabMcp extends EventTarget {
889
904
  if (current())
890
905
  this.#emit("error", { error });
891
906
  },
892
- closed: (reason, code) => {
907
+ closed: (reason) => {
893
908
  if (!current())
894
909
  return;
895
910
  if (reason === "replaced")
896
- this.#takenOver = replacedHere = true;
897
- const generation = this.#generation;
911
+ this.#stayOn = replacedHere = true;
898
912
  this.#connection = undefined;
899
913
  this.#session = undefined;
914
+ const generation = this.#generation;
900
915
  this.#setPairingCode(undefined);
901
916
  this.#identityRound++;
902
917
  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)
918
+ if (generation !== this.#generation)
919
+ return;
920
+ if (this.#reconnect && RECONNECT_REASONS.has(reason))
906
921
  this.#scheduleReconnect(reason, 1);
922
+ else
923
+ this.#setState("disconnected", reason);
907
924
  }
908
925
  };
909
926
  }
@@ -913,5 +930,5 @@ export {
913
930
  VERSION
914
931
  };
915
932
 
916
- //# debugId=DD8CA08955DA711064756E2164756E21
933
+ //# debugId=6E29CB68C279C2FB64756E2164756E21
917
934
  //# sourceMappingURL=index.js.map