@ractive-ch/tab-mcp-client 0.0.0-stage → 0.1.0-alpha.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.
package/index.js ADDED
@@ -0,0 +1,543 @@
1
+ var __chunkGraphs;
2
+ var __chunkSeen;
3
+ var __chunkNonce;
4
+ var __preload = (id, seenOnly) => {
5
+ for (var [base, graph, ids] of __chunkGraphs || [])
6
+ for (var stack = [id], g = globalThis, d = g.document, head, j, node, k, link;j = stack.pop(); )
7
+ if (!__chunkSeen[j] && (node = graph[j])) {
8
+ __chunkSeen[j] = 1;
9
+ for (k = 1;k < node.length; k++)
10
+ stack.push(ids[node[k]]);
11
+ if (!seenOnly && j !== id && (head = d && d.head)) {
12
+ if (__chunkNonce === undefined)
13
+ __chunkNonce = (k = d.querySelector("meta[property=csp-nonce]")) && (k.nonce || k.getAttribute("nonce")) || "";
14
+ link = d.createElement("link");
15
+ link.rel = "modulepreload";
16
+ link.crossOrigin = "";
17
+ if (__chunkNonce)
18
+ link.nonce = __chunkNonce;
19
+ link.href = new g.URL(node[0], base);
20
+ head.appendChild(link);
21
+ }
22
+ }
23
+ };
24
+ var __chunks = (base, ids, nodes, entry) => {
25
+ for (var graph = {}, i = 0;i < ids.length; i++)
26
+ graph[ids[i]] = nodes[i];
27
+ (__chunkGraphs ||= []).push([base, graph, ids]);
28
+ __chunkSeen ||= {};
29
+ __preload(ids[entry], 1);
30
+ };
31
+ __chunks(import.meta.url,["tzd7tzfz","1gf7vqz2","168746sb"],[["./index.js"],["./connection-1gf7vqz2.js"],["./ui-168746sb.js"]],0);
32
+
33
+ // src/registry.ts
34
+ var NAME = /^[A-Za-z0-9_.-]{1,128}$/;
35
+ function isPlainObject(v) {
36
+ return typeof v === "object" && v !== null && !Array.isArray(v);
37
+ }
38
+ function usesMcpHeader(schema, depth = 0) {
39
+ if (depth > 64 || typeof schema !== "object" || schema === null)
40
+ return false;
41
+ if (!Array.isArray(schema) && "x-mcp-header" in schema)
42
+ return true;
43
+ return Object.values(schema).some((v) => usesMcpHeader(v, depth + 1));
44
+ }
45
+ function resolvePointer(root, pointer) {
46
+ let node = root;
47
+ for (const raw of pointer.split("/").slice(1)) {
48
+ const key = decodeURIComponent(raw).replaceAll("~1", "/").replaceAll("~0", "~");
49
+ if (typeof node !== "object" || node === null || !Object.hasOwn(node, key))
50
+ return;
51
+ node = node[key];
52
+ }
53
+ return node;
54
+ }
55
+ function schemaProblem(root) {
56
+ const anchors = new Set;
57
+ const refs = [];
58
+ const patterns = [];
59
+ const walk = (node, depth) => {
60
+ if (depth > 64 || typeof node !== "object" || node === null)
61
+ return;
62
+ if (!Array.isArray(node)) {
63
+ const o = node;
64
+ if (typeof o["$anchor"] === "string")
65
+ anchors.add(o["$anchor"]);
66
+ if (typeof o["$ref"] === "string")
67
+ refs.push(o["$ref"]);
68
+ if (typeof o["pattern"] === "string")
69
+ patterns.push(o["pattern"]);
70
+ const pp = o["patternProperties"];
71
+ if (typeof pp === "object" && pp !== null)
72
+ patterns.push(...Object.keys(pp));
73
+ }
74
+ for (const v of Object.values(node))
75
+ walk(v, depth + 1);
76
+ };
77
+ walk(root, 0);
78
+ for (const p of patterns) {
79
+ try {
80
+ new RegExp(p, "u");
81
+ } catch {
82
+ return `pattern ${JSON.stringify(p)} is not a valid regular expression`;
83
+ }
84
+ }
85
+ for (const ref of refs) {
86
+ if (!ref.startsWith("#"))
87
+ return `$ref ${JSON.stringify(ref)} points outside the schema`;
88
+ const target = ref.slice(1);
89
+ const found = target === "" || (target.startsWith("/") ? resolvePointer(root, target) !== undefined : anchors.has(target));
90
+ if (!found)
91
+ return `$ref ${JSON.stringify(ref)} does not resolve`;
92
+ }
93
+ return;
94
+ }
95
+ function validateTool(tool) {
96
+ if (!isPlainObject(tool))
97
+ throw new TypeError("registerTool: the tool must be an object");
98
+ const { name, title, description, inputSchema, execute, annotations } = tool;
99
+ if (typeof name !== "string" || !NAME.test(name)) {
100
+ throw new TypeError(`registerTool: the name must be 1–128 characters of A–Z, a–z, 0–9, "_", "-" or "." (got ${JSON.stringify(name)})`);
101
+ }
102
+ if (typeof description !== "string" || description.trim() === "") {
103
+ throw new TypeError(`registerTool: tool ${name} needs a description`);
104
+ }
105
+ if (title !== undefined && typeof title !== "string") {
106
+ throw new TypeError(`registerTool: the title of ${name} must be a string`);
107
+ }
108
+ if (typeof execute !== "function") {
109
+ throw new TypeError(`registerTool: tool ${name} needs an execute function`);
110
+ }
111
+ const schema = inputSchema ?? { type: "object" };
112
+ if (!isPlainObject(schema) || schema["type"] !== "object") {
113
+ throw new TypeError(`registerTool: the inputSchema of ${name} must be a JSON Schema object with "type": "object"`);
114
+ }
115
+ if (usesMcpHeader(schema)) {
116
+ throw new TypeError(`registerTool: ${name} uses x-mcp-header, which tab-mcp does not support`);
117
+ }
118
+ const problem = schemaProblem(schema);
119
+ if (problem !== undefined) {
120
+ throw new TypeError(`registerTool: the inputSchema of ${name}: ${problem}`);
121
+ }
122
+ let copied;
123
+ try {
124
+ copied = JSON.parse(JSON.stringify(schema));
125
+ } catch {
126
+ throw new TypeError(`registerTool: the inputSchema of ${name} must be JSON`);
127
+ }
128
+ if (annotations !== undefined && !isPlainObject(annotations)) {
129
+ throw new TypeError(`registerTool: the annotations of ${name} must be an object`);
130
+ }
131
+ const hints = {};
132
+ for (const [key, value] of Object.entries(annotations ?? {})) {
133
+ if (typeof value === "boolean")
134
+ hints[key] = value;
135
+ }
136
+ return {
137
+ name,
138
+ title,
139
+ description,
140
+ inputSchema: copied,
141
+ annotations: hints,
142
+ execute
143
+ };
144
+ }
145
+
146
+ class ToolRegistry {
147
+ #tools = new Map;
148
+ #listeners = new Set;
149
+ register(tool, options = {}) {
150
+ const registered = validateTool(tool);
151
+ const { signal } = options;
152
+ if (signal?.aborted)
153
+ return;
154
+ if (this.#tools.has(registered.name)) {
155
+ throw new DOMException(`registerTool: a tool named ${registered.name} is already registered`, "InvalidStateError");
156
+ }
157
+ this.#tools.set(registered.name, registered);
158
+ signal?.addEventListener("abort", () => {
159
+ if (this.#tools.get(registered.name) === registered) {
160
+ this.#tools.delete(registered.name);
161
+ this.#changed();
162
+ }
163
+ }, { once: true });
164
+ this.#changed();
165
+ }
166
+ get(name) {
167
+ return this.#tools.get(name);
168
+ }
169
+ list() {
170
+ return [...this.#tools.values()];
171
+ }
172
+ onChange(listener) {
173
+ this.#listeners.add(listener);
174
+ return () => this.#listeners.delete(listener);
175
+ }
176
+ #changed() {
177
+ for (const listener of [...this.#listeners])
178
+ listener();
179
+ }
180
+ }
181
+
182
+ // src/secret.ts
183
+ var SECRET = /^[A-Za-z0-9_-]{43}$/;
184
+ function base64url(bytes) {
185
+ return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
186
+ }
187
+ function newSecret() {
188
+ return base64url(crypto.getRandomValues(new Uint8Array(32)));
189
+ }
190
+ function isSecret(value) {
191
+ return typeof value === "string" && SECRET.test(value);
192
+ }
193
+ function defaultStorage() {
194
+ try {
195
+ const storage = globalThis.localStorage;
196
+ return storage ?? null;
197
+ } catch {
198
+ return null;
199
+ }
200
+ }
201
+
202
+ class SecretStore {
203
+ #storage;
204
+ #key;
205
+ #memory;
206
+ constructor(storage, key) {
207
+ this.#storage = storage === undefined ? defaultStorage() : storage;
208
+ this.#key = key;
209
+ }
210
+ get() {
211
+ let stored = null;
212
+ try {
213
+ stored = this.#storage?.getItem(this.#key) ?? null;
214
+ } catch {}
215
+ if (isSecret(stored)) {
216
+ this.#memory = stored;
217
+ return stored;
218
+ }
219
+ return this.#memory ?? this.rotate();
220
+ }
221
+ rotate() {
222
+ const secret = newSecret();
223
+ this.#memory = secret;
224
+ try {
225
+ this.#storage?.setItem(this.#key, secret);
226
+ } catch {}
227
+ return secret;
228
+ }
229
+ }
230
+
231
+ // src/version.ts
232
+ var LIBRARY_NAME = "@ractive-ch/tab-mcp-client";
233
+ var VERSION = "0.1.0-alpha.1";
234
+
235
+ // src/tab-mcp.ts
236
+ var LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
237
+ function tabUrl(relay) {
238
+ let u;
239
+ try {
240
+ u = new URL(relay);
241
+ } catch {
242
+ throw new TypeError(`TabMcp: relay is not a URL: ${relay}`);
243
+ }
244
+ const secure = u.protocol === "https:" || u.protocol === "wss:";
245
+ if (!secure && u.protocol !== "http:" && u.protocol !== "ws:") {
246
+ throw new TypeError(`TabMcp: relay must be an https: or wss: URL: ${relay}`);
247
+ }
248
+ if (!secure && !LOOPBACK.has(u.hostname)) {
249
+ throw new TypeError(`TabMcp: relay must use https: or wss: (http: only for localhost): ${relay}`);
250
+ }
251
+ const origin = `${secure ? "https:" : "http:"}//${u.host}`;
252
+ const path = u.pathname.replace(/\/+$/, "");
253
+ u.protocol = secure ? "wss:" : "ws:";
254
+ u.pathname = path.endsWith("/tab") ? path : `${path}/tab`;
255
+ u.search = "";
256
+ u.hash = "";
257
+ return { url: u.href, origin };
258
+ }
259
+ function hostOf(url) {
260
+ try {
261
+ return new URL(url).host;
262
+ } catch {
263
+ return "";
264
+ }
265
+ }
266
+ function sessionInfo(m) {
267
+ const info = {
268
+ sessionId: m.sessionId,
269
+ address: m.address,
270
+ origin: m.origin,
271
+ expiresAt: m.expiresAt,
272
+ limits: m.limits
273
+ };
274
+ if (m.appName !== undefined)
275
+ info.appName = m.appName;
276
+ return info;
277
+ }
278
+
279
+ class TabMcp extends EventTarget {
280
+ #registry = new ToolRegistry;
281
+ #server;
282
+ #appName;
283
+ #onConfirm;
284
+ #confirmDelayMs;
285
+ #relayUrl;
286
+ #secrets;
287
+ #state = "disconnected";
288
+ #session;
289
+ #grants = [];
290
+ #pairing = false;
291
+ #pairingCode;
292
+ #connection;
293
+ #connecting;
294
+ #generation = 0;
295
+ constructor(options) {
296
+ super();
297
+ const { url, origin } = tabUrl(options.relay);
298
+ const { server, appName } = options;
299
+ if (typeof server?.name !== "string" || typeof server.version !== "string") {
300
+ throw new TypeError("TabMcp: server needs a name and a version");
301
+ }
302
+ if (appName !== undefined && (typeof appName !== "string" || appName.length > 64)) {
303
+ throw new TypeError("TabMcp: appName must be a string of at most 64 characters");
304
+ }
305
+ this.#relayUrl = url;
306
+ this.#server = { ...server };
307
+ this.#appName = appName;
308
+ this.#onConfirm = options.onConfirm;
309
+ this.#confirmDelayMs = options.confirmDelayMs;
310
+ this.#secrets = new SecretStore(options.storage, options.storageKey ?? `tab-mcp:secret:${origin}`);
311
+ this.#registry.onChange(() => this.#emit("toolschange", { tools: this.tools }));
312
+ }
313
+ registerTool(tool, options = {}) {
314
+ try {
315
+ this.#registry.register(tool, options);
316
+ } catch (error) {
317
+ return Promise.reject(error);
318
+ }
319
+ return Promise.resolve();
320
+ }
321
+ get tools() {
322
+ return this.#registry.list().map((t) => t.name);
323
+ }
324
+ get state() {
325
+ return this.#state;
326
+ }
327
+ get session() {
328
+ return this.#session;
329
+ }
330
+ get address() {
331
+ return this.#session?.address;
332
+ }
333
+ get appName() {
334
+ return this.#session?.appName ?? this.#appName;
335
+ }
336
+ get grants() {
337
+ return this.#grants;
338
+ }
339
+ get pairing() {
340
+ return this.#pairing;
341
+ }
342
+ get pairingCode() {
343
+ return this.#pairingCode;
344
+ }
345
+ connect(options = {}) {
346
+ if (this.#state === "connected" && this.#session !== undefined) {
347
+ return Promise.resolve(this.#session);
348
+ }
349
+ if (this.#connecting !== undefined)
350
+ return this.#connecting;
351
+ const activation = globalThis.navigator?.userActivation;
352
+ if (options.resume !== true && activation !== undefined && !activation.isActive) {
353
+ return Promise.reject(new DOMException("connect() must be called from a user action, such as a click", "NotAllowedError"));
354
+ }
355
+ this.#setState("connecting");
356
+ const connecting = this.#open(this.#generation);
357
+ this.#connecting = connecting;
358
+ connecting.then(() => {
359
+ if (this.#connecting === connecting)
360
+ this.#connecting = undefined;
361
+ }, () => {
362
+ if (this.#connecting !== connecting)
363
+ return;
364
+ this.#connecting = undefined;
365
+ this.#connection = undefined;
366
+ this.#setState("disconnected");
367
+ });
368
+ return connecting;
369
+ }
370
+ async#open(generation) {
371
+ const { openConnection } = await (__preload("1gf7vqz2"), import("./connection-1gf7vqz2.js"));
372
+ if (generation !== this.#generation) {
373
+ throw new DOMException("The connection was cancelled", "AbortError");
374
+ }
375
+ const ref = {};
376
+ const connection = openConnection(this.#host(ref), this.#relayUrl, this.#secrets.get());
377
+ ref.connection = connection;
378
+ this.#connection = connection;
379
+ return connection.ready;
380
+ }
381
+ disconnect() {
382
+ this.#end("user");
383
+ }
384
+ newAddress() {
385
+ const wasOn = this.#state !== "disconnected";
386
+ if (this.#state === "connected")
387
+ this.#connection?.send({ type: "grants.revokeAll" });
388
+ this.#end("new_address");
389
+ this.#secrets.rotate();
390
+ return wasOn ? this.connect() : Promise.resolve(undefined);
391
+ }
392
+ #end(reason) {
393
+ this.#generation++;
394
+ const connection = this.#connection;
395
+ const wasConnected = this.#state === "connected";
396
+ this.#connection = undefined;
397
+ this.#connecting = undefined;
398
+ connection?.close(reason);
399
+ if (this.#state === "disconnected")
400
+ return;
401
+ this.#session = undefined;
402
+ this.#setPairingCode(undefined);
403
+ this.#setState("disconnected");
404
+ if (wasConnected)
405
+ this.#emit("disconnected", { reason, code: 1000 });
406
+ }
407
+ startPairing() {
408
+ if (this.#pairing)
409
+ return;
410
+ this.#pairing = true;
411
+ if (this.#state === "connected")
412
+ this.#connection?.send({ type: "pairing.start" });
413
+ }
414
+ stopPairing() {
415
+ if (!this.#pairing)
416
+ return;
417
+ this.#pairing = false;
418
+ if (this.#state === "connected")
419
+ this.#connection?.send({ type: "pairing.stop" });
420
+ this.#setPairingCode(undefined);
421
+ }
422
+ revoke(grantId) {
423
+ if (this.#state !== "connected")
424
+ return false;
425
+ return this.#connection?.send({ type: "grant.revoke", grantId }) === true;
426
+ }
427
+ async showConnectDialog(options = {}) {
428
+ const connecting = this.connect();
429
+ connecting.catch(() => {});
430
+ const { showConnectDialog } = await (__preload("168746sb"), import("./ui-168746sb.js"));
431
+ await showConnectDialog(this, connecting, options.document ?? globalThis.document);
432
+ }
433
+ addEventListener(type, listener, options) {
434
+ super.addEventListener(type, listener, options);
435
+ }
436
+ removeEventListener(type, listener, options) {
437
+ super.removeEventListener(type, listener, options);
438
+ }
439
+ #emit(type, detail) {
440
+ this.dispatchEvent(new CustomEvent(type, { detail }));
441
+ }
442
+ #setState(state) {
443
+ if (this.#state === state)
444
+ return;
445
+ this.#state = state;
446
+ this.#emit("statechange", { state });
447
+ }
448
+ #setPairingCode(code) {
449
+ if (this.#pairingCode === undefined && code === undefined)
450
+ return;
451
+ this.#pairingCode = code;
452
+ this.#emit("pairingcode", code ?? null);
453
+ }
454
+ #setGrants(grants) {
455
+ this.#grants = grants;
456
+ this.#emit("grantschange", { grants });
457
+ }
458
+ #confirm(request) {
459
+ if (this.#onConfirm !== undefined) {
460
+ const ask = this.#onConfirm;
461
+ return Promise.resolve().then(() => ask(request)).then((allowed) => allowed === true);
462
+ }
463
+ const doc = globalThis.document;
464
+ if (doc === undefined)
465
+ return Promise.resolve(false);
466
+ const delay = this.#confirmDelayMs;
467
+ return (__preload("168746sb"), import("./ui-168746sb.js")).then((ui) => ui.confirmDialog(request, doc, delay === undefined ? {} : { allowDelayMs: delay }));
468
+ }
469
+ #host(ref) {
470
+ const current = () => ref.connection !== undefined && this.#connection === ref.connection;
471
+ return {
472
+ registry: this.#registry,
473
+ server: this.#server,
474
+ appName: this.#appName,
475
+ library: { name: LIBRARY_NAME, version: VERSION },
476
+ confirm: (request) => this.#confirm(request),
477
+ clientFor: (grant) => {
478
+ const known = this.#grants.find((g) => g.grantId === grant.grantId);
479
+ const client = {
480
+ grantId: grant.grantId,
481
+ id: grant.clientId,
482
+ host: hostOf(grant.clientId)
483
+ };
484
+ if (known !== undefined)
485
+ client.name = known.client.name;
486
+ return client;
487
+ },
488
+ sessionStarted: (m) => {
489
+ const session = sessionInfo(m);
490
+ if (!current())
491
+ return session;
492
+ this.#session = session;
493
+ this.#setState("connected");
494
+ this.#setGrants([...m.grants]);
495
+ if (this.#pairing)
496
+ this.#connection?.send({ type: "pairing.start" });
497
+ this.#emit("connected", session);
498
+ return session;
499
+ },
500
+ pairingCode: (code) => {
501
+ if (current() && this.#pairing)
502
+ this.#setPairingCode(code);
503
+ },
504
+ grantAdded: (grant) => {
505
+ if (!current())
506
+ return;
507
+ this.#setGrants([
508
+ ...this.#grants.filter((g) => g.grantId !== grant.grantId),
509
+ grant
510
+ ]);
511
+ },
512
+ grantRemoved: (grantId) => {
513
+ if (!current())
514
+ return;
515
+ this.#setGrants(this.#grants.filter((g) => g.grantId !== grantId));
516
+ },
517
+ replaced: () => {
518
+ if (current())
519
+ this.#emit("replaced", null);
520
+ },
521
+ error: (error) => {
522
+ if (current())
523
+ this.#emit("error", { error });
524
+ },
525
+ closed: (reason, code) => {
526
+ if (!current())
527
+ return;
528
+ this.#connection = undefined;
529
+ this.#session = undefined;
530
+ this.#setPairingCode(undefined);
531
+ this.#setState("disconnected");
532
+ this.#emit("disconnected", { reason, code });
533
+ }
534
+ };
535
+ }
536
+ }
537
+ export {
538
+ TabMcp,
539
+ VERSION
540
+ };
541
+
542
+ //# debugId=B477DA9C3F7079C964756E2164756E21
543
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/registry.ts", "../src/secret.ts", "../src/version.ts", "../src/tab-mcp.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * The tool registry, mirroring WebMCP's `registerTool(tool, { signal })`\n * (DEC-010). Part of the eagerly loaded core.\n */\n\nimport type {\n\tJsonSchema,\n\tRegisterToolOptions,\n\tTool,\n\tToolAnnotations,\n} from \"./types.ts\";\n\nconst NAME = /^[A-Za-z0-9_.-]{1,128}$/;\n\n/** A validated tool as the registry keeps it. */\nexport interface RegisteredTool {\n\treadonly name: string;\n\treadonly title: string | undefined;\n\treadonly description: string;\n\treadonly inputSchema: JsonSchema;\n\treadonly annotations: ToolAnnotations;\n\treadonly execute: Tool[\"execute\"];\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** `x-mcp-header` makes the relay validate headers it does not know; not supported in v1. */\nfunction usesMcpHeader(schema: unknown, depth = 0): boolean {\n\tif (depth > 64 || typeof schema !== \"object\" || schema === null) return false;\n\tif (!Array.isArray(schema) && \"x-mcp-header\" in schema) return true;\n\treturn Object.values(schema).some((v) => usesMcpHeader(v, depth + 1));\n}\n\n/** A JSON pointer (`/a/b~1c`) inside `root`, or `undefined`. */\nfunction resolvePointer(root: unknown, pointer: string): unknown {\n\tlet node: unknown = root;\n\tfor (const raw of pointer.split(\"/\").slice(1)) {\n\t\tconst key = decodeURIComponent(raw)\n\t\t\t.replaceAll(\"~1\", \"/\")\n\t\t\t.replaceAll(\"~0\", \"~\");\n\t\tif (typeof node !== \"object\" || node === null || !Object.hasOwn(node, key))\n\t\t\treturn undefined;\n\t\tnode = (node as Record<string, unknown>)[key];\n\t}\n\treturn node;\n}\n\n/**\n * What the validator (loaded only on `connect()`) would throw on later, found\n * now so that a bad schema fails registration: patterns that are not\n * regular expressions, and `$ref`s that do not resolve inside the schema.\n */\nfunction schemaProblem(root: unknown): string | undefined {\n\tconst anchors = new Set<string>();\n\tconst refs: string[] = [];\n\tconst patterns: string[] = [];\n\tconst walk = (node: unknown, depth: number): void => {\n\t\tif (depth > 64 || typeof node !== \"object\" || node === null) return;\n\t\tif (!Array.isArray(node)) {\n\t\t\tconst o = node as Record<string, unknown>;\n\t\t\tif (typeof o[\"$anchor\"] === \"string\") anchors.add(o[\"$anchor\"]);\n\t\t\tif (typeof o[\"$ref\"] === \"string\") refs.push(o[\"$ref\"]);\n\t\t\tif (typeof o[\"pattern\"] === \"string\") patterns.push(o[\"pattern\"]);\n\t\t\tconst pp = o[\"patternProperties\"];\n\t\t\tif (typeof pp === \"object\" && pp !== null)\n\t\t\t\tpatterns.push(...Object.keys(pp));\n\t\t}\n\t\tfor (const v of Object.values(node)) walk(v, depth + 1);\n\t};\n\twalk(root, 0);\n\tfor (const p of patterns) {\n\t\ttry {\n\t\t\tnew RegExp(p, \"u\");\n\t\t} catch {\n\t\t\treturn `pattern ${JSON.stringify(p)} is not a valid regular expression`;\n\t\t}\n\t}\n\tfor (const ref of refs) {\n\t\tif (!ref.startsWith(\"#\"))\n\t\t\treturn `$ref ${JSON.stringify(ref)} points outside the schema`;\n\t\tconst target = ref.slice(1);\n\t\tconst found =\n\t\t\ttarget === \"\" ||\n\t\t\t(target.startsWith(\"/\")\n\t\t\t\t? resolvePointer(root, target) !== undefined\n\t\t\t\t: anchors.has(target));\n\t\tif (!found) return `$ref ${JSON.stringify(ref)} does not resolve`;\n\t}\n\treturn undefined;\n}\n\n/** Validate a tool; throws a `TypeError` naming the problem. */\nexport function validateTool(tool: Tool): RegisteredTool {\n\tif (!isPlainObject(tool))\n\t\tthrow new TypeError(\"registerTool: the tool must be an object\");\n\tconst { name, title, description, inputSchema, execute, annotations } = tool;\n\tif (typeof name !== \"string\" || !NAME.test(name)) {\n\t\tthrow new TypeError(\n\t\t\t`registerTool: the name must be 1–128 characters of A–Z, a–z, 0–9, \"_\", \"-\" or \".\" (got ${JSON.stringify(name)})`,\n\t\t);\n\t}\n\tif (typeof description !== \"string\" || description.trim() === \"\") {\n\t\tthrow new TypeError(`registerTool: tool ${name} needs a description`);\n\t}\n\tif (title !== undefined && typeof title !== \"string\") {\n\t\tthrow new TypeError(`registerTool: the title of ${name} must be a string`);\n\t}\n\tif (typeof execute !== \"function\") {\n\t\tthrow new TypeError(`registerTool: tool ${name} needs an execute function`);\n\t}\n\tconst schema = inputSchema ?? { type: \"object\" };\n\tif (!isPlainObject(schema) || schema[\"type\"] !== \"object\") {\n\t\tthrow new TypeError(\n\t\t\t`registerTool: the inputSchema of ${name} must be a JSON Schema object with \"type\": \"object\"`,\n\t\t);\n\t}\n\tif (usesMcpHeader(schema)) {\n\t\tthrow new TypeError(\n\t\t\t`registerTool: ${name} uses x-mcp-header, which tab-mcp does not support`,\n\t\t);\n\t}\n\tconst problem = schemaProblem(schema);\n\tif (problem !== undefined) {\n\t\tthrow new TypeError(`registerTool: the inputSchema of ${name}: ${problem}`);\n\t}\n\tlet copied: JsonSchema;\n\ttry {\n\t\tcopied = JSON.parse(JSON.stringify(schema)) as JsonSchema;\n\t} catch {\n\t\tthrow new TypeError(\n\t\t\t`registerTool: the inputSchema of ${name} must be JSON`,\n\t\t);\n\t}\n\tif (annotations !== undefined && !isPlainObject(annotations)) {\n\t\tthrow new TypeError(\n\t\t\t`registerTool: the annotations of ${name} must be an object`,\n\t\t);\n\t}\n\tconst hints: ToolAnnotations = {};\n\tfor (const [key, value] of Object.entries(annotations ?? {})) {\n\t\tif (typeof value === \"boolean\")\n\t\t\t(hints as Record<string, boolean>)[key] = value;\n\t}\n\treturn {\n\t\tname,\n\t\ttitle,\n\t\tdescription,\n\t\tinputSchema: copied,\n\t\tannotations: hints,\n\t\texecute,\n\t};\n}\n\nexport class ToolRegistry {\n\treadonly #tools = new Map<string, RegisteredTool>();\n\treadonly #listeners = new Set<() => void>();\n\n\t/**\n\t * Register a tool; throws `TypeError` for an invalid tool and an\n\t * `InvalidStateError` `DOMException` for a duplicate name.\n\t */\n\tregister(tool: Tool, options: RegisterToolOptions = {}): void {\n\t\tconst registered = validateTool(tool);\n\t\tconst { signal } = options;\n\t\tif (signal?.aborted) return;\n\t\tif (this.#tools.has(registered.name)) {\n\t\t\tthrow new DOMException(\n\t\t\t\t`registerTool: a tool named ${registered.name} is already registered`,\n\t\t\t\t\"InvalidStateError\",\n\t\t\t);\n\t\t}\n\t\tthis.#tools.set(registered.name, registered);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tif (this.#tools.get(registered.name) === registered) {\n\t\t\t\t\tthis.#tools.delete(registered.name);\n\t\t\t\t\tthis.#changed();\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\tthis.#changed();\n\t}\n\n\tget(name: string): RegisteredTool | undefined {\n\t\treturn this.#tools.get(name);\n\t}\n\n\t/** Tools in registration order. */\n\tlist(): RegisteredTool[] {\n\t\treturn [...this.#tools.values()];\n\t}\n\n\t/** Listen for changes; returns a function that stops listening. */\n\tonChange(listener: () => void): () => void {\n\t\tthis.#listeners.add(listener);\n\t\treturn () => this.#listeners.delete(listener);\n\t}\n\n\t#changed(): void {\n\t\tfor (const listener of [...this.#listeners]) listener();\n\t}\n}\n",
6
+ "/**\n * The address secret (DEC-027): 32 random bytes as base64url without padding,\n * kept in `localStorage`. The relay derives the stable address from it.\n */\n\nimport type { SecretStorage } from \"./types.ts\";\n\nconst SECRET = /^[A-Za-z0-9_-]{43}$/;\n/** base64url without padding. */\nexport function base64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\n\nexport function newSecret(): string {\n\treturn base64url(crypto.getRandomValues(new Uint8Array(32)));\n}\n\nexport function isSecret(value: unknown): value is string {\n\treturn typeof value === \"string\" && SECRET.test(value);\n}\n\n/** `localStorage`, or `null` where it is missing or blocked. */\nfunction defaultStorage(): SecretStorage | null {\n\ttry {\n\t\tconst storage = (globalThis as { localStorage?: SecretStorage })\n\t\t\t.localStorage;\n\t\treturn storage ?? null;\n\t} catch {\n\t\treturn null; // SecurityError: storage blocked for this page\n\t}\n}\n\n/** Reads, creates and rotates the secret; falls back to memory without storage. */\nexport class SecretStore {\n\treadonly #storage: SecretStorage | null;\n\treadonly #key: string;\n\t#memory: string | undefined;\n\n\tconstructor(storage: SecretStorage | null | undefined, key: string) {\n\t\tthis.#storage = storage === undefined ? defaultStorage() : storage;\n\t\tthis.#key = key;\n\t}\n\n\t/** The current secret; storage first, so a rotation in another tab is seen. */\n\tget(): string {\n\t\tlet stored: string | null = null;\n\t\ttry {\n\t\t\tstored = this.#storage?.getItem(this.#key) ?? null;\n\t\t} catch {\n\t\t\t// unreadable: use a page-lifetime secret\n\t\t}\n\t\tif (isSecret(stored)) {\n\t\t\tthis.#memory = stored;\n\t\t\treturn stored;\n\t\t}\n\t\treturn this.#memory ?? this.rotate();\n\t}\n\n\t/** Make and keep a new secret (a new address). */\n\trotate(): string {\n\t\tconst secret = newSecret();\n\t\tthis.#memory = secret;\n\t\ttry {\n\t\t\tthis.#storage?.setItem(this.#key, secret);\n\t\t} catch {\n\t\t\t// quota or blocked: the secret lives as long as the page\n\t\t}\n\t\treturn secret;\n\t}\n}\n",
7
+ "/** The library's name and version, sent in `hello` (a test keeps it equal to package.json). */\nexport const LIBRARY_NAME = \"@ractive-ch/tab-mcp-client\";\nexport const VERSION = \"0.1.0-alpha.1\";\n",
8
+ "/**\n * `TabMcp`: the eagerly loaded core (DEC-035). It holds the tool registry, the\n * events, the pairing state and the address secret; `connect()` loads the\n * connection and the MCP handler with a dynamic `import()`.\n */\n\nimport type { ConnectionHandle, ConnectionHost } from \"./internal.ts\";\nimport type { GrantRef, SessionMessage } from \"./protocol.ts\";\nimport { ToolRegistry } from \"./registry.ts\";\nimport { SecretStore } from \"./secret.ts\";\nimport type {\n\tConfirmHandler,\n\tConfirmRequest,\n\tConnectionState,\n\tConnectOptions,\n\tDisconnectReason,\n\tGrant,\n\tPairingCode,\n\tRegisterToolOptions,\n\tServerInfo,\n\tSessionInfo,\n\tTabMcpEventMap,\n\tTabMcpOptions,\n\tTool,\n\tToolCallClient,\n} from \"./types.ts\";\nimport { LIBRARY_NAME, VERSION } from \"./version.ts\";\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/** `wss://host/tab` for a relay given as `https://host`, `wss://host` or with `/tab`. */\nexport function tabUrl(relay: string): { url: string; origin: string } {\n\tlet u: URL;\n\ttry {\n\t\tu = new URL(relay);\n\t} catch {\n\t\tthrow new TypeError(`TabMcp: relay is not a URL: ${relay}`);\n\t}\n\tconst secure = u.protocol === \"https:\" || u.protocol === \"wss:\";\n\tif (!secure && u.protocol !== \"http:\" && u.protocol !== \"ws:\") {\n\t\tthrow new TypeError(\n\t\t\t`TabMcp: relay must be an https: or wss: URL: ${relay}`,\n\t\t);\n\t}\n\t// The secret travels in hello: never in clear text beyond this machine.\n\tif (!secure && !LOOPBACK.has(u.hostname)) {\n\t\tthrow new TypeError(\n\t\t\t`TabMcp: relay must use https: or wss: (http: only for localhost): ${relay}`,\n\t\t);\n\t}\n\tconst origin = `${secure ? \"https:\" : \"http:\"}//${u.host}`;\n\tconst path = u.pathname.replace(/\\/+$/, \"\");\n\tu.protocol = secure ? \"wss:\" : \"ws:\";\n\tu.pathname = path.endsWith(\"/tab\") ? path : `${path}/tab`;\n\tu.search = \"\";\n\tu.hash = \"\";\n\treturn { url: u.href, origin };\n}\n\nfunction hostOf(url: string): string {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction sessionInfo(m: SessionMessage): SessionInfo {\n\tconst info: SessionInfo = {\n\t\tsessionId: m.sessionId,\n\t\taddress: m.address,\n\t\torigin: m.origin,\n\t\texpiresAt: m.expiresAt,\n\t\tlimits: m.limits,\n\t};\n\tif (m.appName !== undefined) info.appName = m.appName;\n\treturn info;\n}\n\ntype Listener<K extends keyof TabMcpEventMap> = (\n\tevent: TabMcpEventMap[K],\n) => void;\n\n/**\n * Offers a page's tools to AI apps through a tab-mcp relay.\n *\n * ```ts\n * const mcp = new TabMcp({ relay: \"https://relay.example\", server: { name: \"Calculator\", version: \"1.0.0\" } });\n * mcp.registerTool({ name: \"add\", description: \"Add two numbers\", execute: ({ a, b }) => Number(a) + Number(b) });\n * button.onclick = () => mcp.showConnectDialog();\n * ```\n */\nexport class TabMcp extends EventTarget {\n\treadonly #registry = new ToolRegistry();\n\treadonly #server: ServerInfo;\n\treadonly #appName: string | undefined;\n\treadonly #onConfirm: ConfirmHandler | undefined;\n\treadonly #confirmDelayMs: number | undefined;\n\treadonly #relayUrl: string;\n\treadonly #secrets: SecretStore;\n\t#state: ConnectionState = \"disconnected\";\n\t#session: SessionInfo | undefined;\n\t#grants: Grant[] = [];\n\t#pairing = false;\n\t#pairingCode: PairingCode | undefined;\n\t#connection: ConnectionHandle | undefined;\n\t#connecting: Promise<SessionInfo> | undefined;\n\t/** Incremented when a connection ends or is cancelled. */\n\t#generation = 0;\n\n\tconstructor(options: TabMcpOptions) {\n\t\tsuper();\n\t\tconst { url, origin } = tabUrl(options.relay);\n\t\tconst { server, appName } = options;\n\t\tif (\n\t\t\ttypeof server?.name !== \"string\" ||\n\t\t\ttypeof server.version !== \"string\"\n\t\t) {\n\t\t\tthrow new TypeError(\"TabMcp: server needs a name and a version\");\n\t\t}\n\t\tif (\n\t\t\tappName !== undefined &&\n\t\t\t(typeof appName !== \"string\" || appName.length > 64)\n\t\t) {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"TabMcp: appName must be a string of at most 64 characters\",\n\t\t\t);\n\t\t}\n\t\tthis.#relayUrl = url;\n\t\tthis.#server = { ...server };\n\t\tthis.#appName = appName;\n\t\tthis.#onConfirm = options.onConfirm;\n\t\tthis.#confirmDelayMs = options.confirmDelayMs;\n\t\tthis.#secrets = new SecretStore(\n\t\t\toptions.storage,\n\t\t\toptions.storageKey ?? `tab-mcp:secret:${origin}`,\n\t\t);\n\t\tthis.#registry.onChange(() =>\n\t\t\tthis.#emit(\"toolschange\", { tools: this.tools }),\n\t\t);\n\t}\n\n\t/**\n\t * Register a tool (WebMCP shape). Allowed before and after `connect()`;\n\t * aborting `options.signal` unregisters it. Rejects with a `TypeError` for\n\t * an invalid tool and an `InvalidStateError` for a duplicate name.\n\t */\n\tregisterTool(tool: Tool, options: RegisterToolOptions = {}): Promise<void> {\n\t\ttry {\n\t\t\tthis.#registry.register(tool, options);\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\treturn Promise.resolve();\n\t}\n\n\t/** Names of the registered tools. */\n\tget tools(): readonly string[] {\n\t\treturn this.#registry.list().map((t) => t.name);\n\t}\n\n\tget state(): ConnectionState {\n\t\treturn this.#state;\n\t}\n\n\t/** The current session, while connected. */\n\tget session(): SessionInfo | undefined {\n\t\treturn this.#session;\n\t}\n\n\t/** The MCP address to give to AI apps, while connected. */\n\tget address(): string | undefined {\n\t\treturn this.#session?.address;\n\t}\n\n\t/** The app name AI apps see when pairing: the relay's (`session.appName`), else the page's own. */\n\tget appName(): string | undefined {\n\t\treturn this.#session?.appName ?? this.#appName;\n\t}\n\n\t/** The AI apps connected to this address. */\n\tget grants(): readonly Grant[] {\n\t\treturn this.#grants;\n\t}\n\n\t/** Whether pairing is on (`startPairing()`). */\n\tget pairing(): boolean {\n\t\treturn this.#pairing;\n\t}\n\n\t/** The pairing code to show, if the relay sent one. */\n\tget pairingCode(): PairingCode | undefined {\n\t\treturn this.#pairingCode;\n\t}\n\n\t/**\n\t * Connect to the relay: loads the connection and MCP handler, opens the\n\t * WebSocket, resolves with the session. Call it from a user action (a\n\t * click): where browsers track user activation it is refused otherwise,\n\t * unless `options.resume` says the user already chose to keep AI access on.\n\t * Never reconnects by itself.\n\t */\n\tconnect(options: ConnectOptions = {}): Promise<SessionInfo> {\n\t\tif (this.#state === \"connected\" && this.#session !== undefined) {\n\t\t\treturn Promise.resolve(this.#session);\n\t\t}\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tconst activation = (\n\t\t\tglobalThis.navigator as\n\t\t\t\t| { userActivation?: { isActive: boolean } }\n\t\t\t\t| undefined\n\t\t)?.userActivation;\n\t\tif (\n\t\t\toptions.resume !== true &&\n\t\t\tactivation !== undefined &&\n\t\t\t!activation.isActive\n\t\t) {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew DOMException(\n\t\t\t\t\t\"connect() must be called from a user action, such as a click\",\n\t\t\t\t\t\"NotAllowedError\",\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tthis.#setState(\"connecting\");\n\t\tconst connecting = this.#open(this.#generation);\n\t\tthis.#connecting = connecting;\n\t\tconnecting.then(\n\t\t\t() => {\n\t\t\t\tif (this.#connecting === connecting) this.#connecting = undefined;\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (this.#connecting !== connecting) return; // superseded\n\t\t\t\tthis.#connecting = undefined;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\tthis.#setState(\"disconnected\");\n\t\t\t},\n\t\t);\n\t\treturn connecting;\n\t}\n\n\tasync #open(generation: number): Promise<SessionInfo> {\n\t\tconst { openConnection } = await import(\"./connection.ts\");\n\t\tif (generation !== this.#generation) {\n\t\t\tthrow new DOMException(\"The connection was cancelled\", \"AbortError\");\n\t\t}\n\t\tconst ref: { connection?: ConnectionHandle } = {};\n\t\tconst connection = openConnection(\n\t\t\tthis.#host(ref),\n\t\t\tthis.#relayUrl,\n\t\t\tthis.#secrets.get(),\n\t\t);\n\t\tref.connection = connection;\n\t\tthis.#connection = connection;\n\t\treturn connection.ready;\n\t}\n\n\t/** End the session (`bye`). Grants stay: AI apps work again after the next `connect()`. */\n\tdisconnect(): void {\n\t\tthis.#end(\"user\");\n\t}\n\n\t/**\n\t * A new address: revokes every connected app of the old one (while\n\t * connected), makes a new secret, and connects again if it was connected or\n\t * connecting. Call it from a user action.\n\t */\n\tnewAddress(): Promise<SessionInfo | undefined> {\n\t\tconst wasOn = this.#state !== \"disconnected\";\n\t\tif (this.#state === \"connected\")\n\t\t\tthis.#connection?.send({ type: \"grants.revokeAll\" });\n\t\tthis.#end(\"new_address\");\n\t\tthis.#secrets.rotate();\n\t\treturn wasOn ? this.connect() : Promise.resolve(undefined);\n\t}\n\n\t/** Close the connection (or cancel connecting) and report it at once. */\n\t#end(reason: DisconnectReason): void {\n\t\tthis.#generation++;\n\t\tconst connection = this.#connection;\n\t\tconst wasConnected = this.#state === \"connected\";\n\t\tthis.#connection = undefined;\n\t\tthis.#connecting = undefined;\n\t\tconnection?.close(reason); // its callbacks are stale from here on\n\t\tif (this.#state === \"disconnected\") return;\n\t\tthis.#session = undefined;\n\t\tthis.#setPairingCode(undefined);\n\t\tthis.#setState(\"disconnected\");\n\t\tif (wasConnected) this.#emit(\"disconnected\", { reason, code: 1000 });\n\t}\n\n\t/** The pairing dialog opened: ask the relay for codes (DEC-028). */\n\tstartPairing(): void {\n\t\tif (this.#pairing) return;\n\t\tthis.#pairing = true;\n\t\tif (this.#state === \"connected\")\n\t\t\tthis.#connection?.send({ type: \"pairing.start\" });\n\t}\n\n\t/** The pairing dialog closed: the code becomes invalid. */\n\tstopPairing(): void {\n\t\tif (!this.#pairing) return;\n\t\tthis.#pairing = false;\n\t\tif (this.#state === \"connected\")\n\t\t\tthis.#connection?.send({ type: \"pairing.stop\" });\n\t\tthis.#setPairingCode(undefined);\n\t}\n\n\t/**\n\t * Disconnect one AI app: its tokens stop working at once. Works only while\n\t * connected (the relay does it); returns `false` when it could not be sent.\n\t */\n\trevoke(grantId: string): boolean {\n\t\tif (this.#state !== \"connected\") return false;\n\t\treturn this.#connection?.send({ type: \"grant.revoke\", grantId }) === true;\n\t}\n\n\t/**\n\t * Open the default \"Connect your AI tool\" dialog; connects first if needed\n\t * (call it from a click). Resolves when the dialog closes. Pages with their\n\t * own UI use the events and methods instead.\n\t */\n\tasync showConnectDialog(\n\t\toptions: { document?: Document } = {},\n\t): Promise<void> {\n\t\tconst connecting = this.connect();\n\t\tconnecting.catch(() => {}); // the dialog shows the error\n\t\tconst { showConnectDialog } = await import(\"./ui.ts\");\n\t\tawait showConnectDialog(\n\t\t\tthis,\n\t\t\tconnecting,\n\t\t\toptions.document ?? globalThis.document,\n\t\t);\n\t}\n\n\toverride addEventListener<K extends keyof TabMcpEventMap>(\n\t\ttype: K,\n\t\tlistener: Listener<K> | null,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\toverride addEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\toverride addEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void {\n\t\tsuper.addEventListener(type, listener, options);\n\t}\n\n\toverride removeEventListener<K extends keyof TabMcpEventMap>(\n\t\ttype: K,\n\t\tlistener: Listener<K> | null,\n\t\toptions?: boolean | EventListenerOptions,\n\t): void;\n\toverride removeEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | EventListenerOptions,\n\t): void;\n\toverride removeEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | EventListenerOptions,\n\t): void {\n\t\tsuper.removeEventListener(type, listener, options);\n\t}\n\n\t#emit<K extends keyof TabMcpEventMap>(\n\t\ttype: K,\n\t\tdetail: TabMcpEventMap[K][\"detail\"],\n\t): void {\n\t\tthis.dispatchEvent(new CustomEvent(type, { detail }));\n\t}\n\n\t#setState(state: ConnectionState): void {\n\t\tif (this.#state === state) return;\n\t\tthis.#state = state;\n\t\tthis.#emit(\"statechange\", { state });\n\t}\n\n\t#setPairingCode(code: PairingCode | undefined): void {\n\t\tif (this.#pairingCode === undefined && code === undefined) return;\n\t\tthis.#pairingCode = code;\n\t\tthis.#emit(\"pairingcode\", code ?? null);\n\t}\n\n\t#setGrants(grants: Grant[]): void {\n\t\tthis.#grants = grants;\n\t\tthis.#emit(\"grantschange\", { grants });\n\t}\n\n\t#confirm(request: ConfirmRequest): Promise<boolean> {\n\t\tif (this.#onConfirm !== undefined) {\n\t\t\tconst ask = this.#onConfirm;\n\t\t\treturn Promise.resolve()\n\t\t\t\t.then(() => ask(request))\n\t\t\t\t.then((allowed) => allowed === true);\n\t\t}\n\t\tconst doc = globalThis.document as Document | undefined;\n\t\tif (doc === undefined) return Promise.resolve(false); // nobody to ask: decline\n\t\tconst delay = this.#confirmDelayMs;\n\t\treturn import(\"./ui.ts\").then((ui) =>\n\t\t\tui.confirmDialog(\n\t\t\t\trequest,\n\t\t\t\tdoc,\n\t\t\t\tdelay === undefined ? {} : { allowDelayMs: delay },\n\t\t\t),\n\t\t);\n\t}\n\n\t/** The callbacks of one connection; once it is not current they are ignored. */\n\t#host(ref: { connection?: ConnectionHandle }): ConnectionHost {\n\t\tconst current = () =>\n\t\t\tref.connection !== undefined && this.#connection === ref.connection;\n\t\treturn {\n\t\t\tregistry: this.#registry,\n\t\t\tserver: this.#server,\n\t\t\tappName: this.#appName,\n\t\t\tlibrary: { name: LIBRARY_NAME, version: VERSION },\n\t\t\tconfirm: (request) => this.#confirm(request),\n\t\t\tclientFor: (grant: GrantRef): ToolCallClient => {\n\t\t\t\tconst known = this.#grants.find((g) => g.grantId === grant.grantId);\n\t\t\t\tconst client: ToolCallClient = {\n\t\t\t\t\tgrantId: grant.grantId,\n\t\t\t\t\tid: grant.clientId,\n\t\t\t\t\thost: hostOf(grant.clientId),\n\t\t\t\t};\n\t\t\t\tif (known !== undefined) client.name = known.client.name;\n\t\t\t\treturn client;\n\t\t\t},\n\t\t\tsessionStarted: (m) => {\n\t\t\t\tconst session = sessionInfo(m);\n\t\t\t\tif (!current()) return session;\n\t\t\t\tthis.#session = session;\n\t\t\t\tthis.#setState(\"connected\");\n\t\t\t\tthis.#setGrants([...m.grants]);\n\t\t\t\tif (this.#pairing) this.#connection?.send({ type: \"pairing.start\" });\n\t\t\t\tthis.#emit(\"connected\", session);\n\t\t\t\treturn session;\n\t\t\t},\n\t\t\tpairingCode: (code) => {\n\t\t\t\tif (current() && this.#pairing) this.#setPairingCode(code);\n\t\t\t},\n\t\t\tgrantAdded: (grant) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tthis.#setGrants([\n\t\t\t\t\t...this.#grants.filter((g) => g.grantId !== grant.grantId),\n\t\t\t\t\tgrant,\n\t\t\t\t]);\n\t\t\t},\n\t\t\tgrantRemoved: (grantId) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tthis.#setGrants(this.#grants.filter((g) => g.grantId !== grantId));\n\t\t\t},\n\t\t\treplaced: () => {\n\t\t\t\tif (current()) this.#emit(\"replaced\", null);\n\t\t\t},\n\t\t\terror: (error) => {\n\t\t\t\tif (current()) this.#emit(\"error\", { error });\n\t\t\t},\n\t\t\tclosed: (reason: DisconnectReason, code: number) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\tthis.#session = undefined;\n\t\t\t\tthis.#setPairingCode(undefined);\n\t\t\t\tthis.#setState(\"disconnected\");\n\t\t\t\tthis.#emit(\"disconnected\", { reason, code });\n\t\t\t},\n\t\t};\n\t}\n}\n"
9
+ ],
10
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,IAAM,OAAO;AAYb,SAAS,aAAa,CAAC,GAA0C;AAAA,EAChE,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAAA;AAI/D,SAAS,aAAa,CAAC,QAAiB,QAAQ,GAAY;AAAA,EAC3D,IAAI,QAAQ,MAAM,OAAO,WAAW,YAAY,WAAW;AAAA,IAAM,OAAO;AAAA,EACxE,IAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,kBAAkB;AAAA,IAAQ,OAAO;AAAA,EAC/D,OAAO,OAAO,OAAO,MAAM,EAAE,KAAK,CAAC,MAAM,cAAc,GAAG,QAAQ,CAAC,CAAC;AAAA;AAIrE,SAAS,cAAc,CAAC,MAAe,SAA0B;AAAA,EAChE,IAAI,OAAgB;AAAA,EACpB,WAAW,OAAO,QAAQ,MAAM,GAAG,EAAE,MAAM,CAAC,GAAG;AAAA,IAC9C,MAAM,MAAM,mBAAmB,GAAG,EAChC,WAAW,MAAM,GAAG,EACpB,WAAW,MAAM,GAAG;AAAA,IACtB,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,CAAC,OAAO,OAAO,MAAM,GAAG;AAAA,MACxE;AAAA,IACD,OAAQ,KAAiC;AAAA,EAC1C;AAAA,EACA,OAAO;AAAA;AAQR,SAAS,aA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AAA,QACnB,KAAK,WAAW;AAAA,QAChB,KAAK,gBAAgB,SAAS;AAAA,QAC9B,KAAK,UAAU,cAAc;AAAA,QAC7B,KAAK,MAAM,gBAAgB,EAAE,QAAQ,KAAK,CAAC;AAAA;AAAA,IAE7C;AAAA;AAEF;",
11
+ "debugId": "B477DA9C3F7079C964756E2164756E21",
12
+ "names": []
13
+ }
package/internal.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The seam between the eager core (`tab-mcp.ts`) and the lazily loaded
3
+ * connection (`connection.ts`). Types only, so importing it costs nothing.
4
+ */
5
+ import type { GrantRef, SessionMessage, TabMessage } from "./protocol.js";
6
+ import type { ToolRegistry } from "./registry.js";
7
+ import type { ConfirmRequest, DisconnectReason, Grant, PairingCode, ServerInfo, SessionInfo, ToolCallClient } from "./types.js";
8
+ /** What a connection needs from the `TabMcp` that opened it. */
9
+ export interface ConnectionHost {
10
+ readonly registry: ToolRegistry;
11
+ readonly server: ServerInfo;
12
+ readonly appName: string | undefined;
13
+ /** Sent in `hello`. */
14
+ readonly library: {
15
+ name: string;
16
+ version: string;
17
+ };
18
+ /** Ask the user about a consequential tool call. */
19
+ confirm(request: ConfirmRequest): Promise<boolean>;
20
+ /** The caller of a tunnelled request, with the name from the grants list. */
21
+ clientFor(grant: GrantRef): ToolCallClient;
22
+ /** The relay accepted the session; returns what `connect()` resolves with. */
23
+ sessionStarted(session: SessionMessage): SessionInfo;
24
+ pairingCode(code: PairingCode): void;
25
+ grantAdded(grant: Grant): void;
26
+ grantRemoved(grantId: string): void;
27
+ replaced(): void;
28
+ error(error: Error): void;
29
+ /** The session is over (only after `sessionStarted`). */
30
+ closed(reason: DisconnectReason, code: number): void;
31
+ }
32
+ /** The core's handle on an open connection. */
33
+ export interface ConnectionHandle {
34
+ /** Resolves with the session, rejects if the connection fails first. */
35
+ readonly ready: Promise<SessionInfo>;
36
+ send(message: TabMessage): boolean;
37
+ /** Say `bye` and close. */
38
+ close(reason: DisconnectReason): void;
39
+ }