@ractive-ch/tab-mcp-client 0.13.0 → 0.14.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.
- package/README.md +39 -20
- package/cdn/connection-dweyrdbn.min.js +12 -0
- package/cdn/{connection-bjvxzxer.min.js.map → connection-dweyrdbn.min.js.map} +3 -3
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +4 -4
- package/{connection-axx7m1x0.js → connection-eqsag07j.js} +29 -20
- package/connection-eqsag07j.js.map +15 -0
- package/index.d.ts +1 -1
- package/index.js +6 -4
- package/index.js.map +4 -4
- package/internal.d.ts +2 -2
- package/mcp.d.ts +13 -13
- package/package.json +1 -1
- package/types.d.ts +13 -4
- package/version.d.ts +1 -2
- package/cdn/connection-bjvxzxer.min.js +0 -12
- package/connection-axx7m1x0.js.map +0 -15
package/index.js.map
CHANGED
|
@@ -4,11 +4,11 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
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\t/** `RegisterToolOptions.webmcp`: offered through WebMCP even if consequential, or never. */\n\treadonly webmcp?: boolean | undefined;\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 * Without `$id`s; once the validator is loaded, it checks too (`setCompiler`).\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\n/** The validator's check of a schema: throws a `TypeError` naming the problem. */\nexport type SchemaCompiler = (tool: RegisteredTool) => void;\n\nexport class ToolRegistry {\n\treadonly #tools = new Map<string, RegisteredTool>();\n\treadonly #listeners = new Set<() => void>();\n\t#compile: SchemaCompiler | undefined;\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 { signal, webmcp } = options;\n\t\tconst registered: RegisteredTool = { ...validateTool(tool), webmcp };\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.#compile?.(registered);\n\t\tthis.#tools.set(registered.name, registered);\n\t\tsignal?.addEventListener(\"abort\", () => this.remove(registered), {\n\t\t\tonce: true,\n\t\t});\n\t\tthis.#changed();\n\t}\n\n\t/**\n\t * The validator is loaded: from now on each schema is compiled when it is\n\t * registered, and a tool it refuses is refused (DEC-086).\n\t */\n\tsetCompiler(compile: SchemaCompiler): void {\n\t\tthis.#compile ??= compile;\n\t}\n\n\t/** Unregister this tool, if it still is. */\n\tremove(tool: RegisteredTool): void {\n\t\tif (this.#tools.get(tool.name) !== tool) return;\n\t\tthis.#tools.delete(tool.name);\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
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/** A key the secret may still be under (the default of 0.4 and older). */\n\treadonly #oldKey: string | undefined;\n\t/** Set once a page of this origin took over the old key's secret. */\n\treadonly #claimKey: string | undefined;\n\t#memory: string | undefined;\n\n\tconstructor(\n\t\tstorage: SecretStorage | null | undefined,\n\t\tkey: string,\n\t\toldKey?: string,\n\t) {\n\t\tthis.#storage = storage === undefined ? defaultStorage() : storage;\n\t\tthis.#key = key;\n\t\tthis.#oldKey = oldKey;\n\t\tthis.#claimKey = oldKey === undefined ? undefined : `${oldKey}#moved`;\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\t// The old shared key's secret is copied once (DEC-083): the first page\n\t\t\t// keeps the address and marks it taken, so the next page gets its own.\n\t\t\t// The old key stays, for pages still on 0.4 and for a rollback.\n\t\t\tif (\n\t\t\t\t!isSecret(stored) &&\n\t\t\t\tthis.#oldKey !== undefined &&\n\t\t\t\tthis.#claimKey !== undefined &&\n\t\t\t\tthis.#storage?.getItem(this.#claimKey) == null\n\t\t\t) {\n\t\t\t\tconst old = this.#storage?.getItem(this.#oldKey) ?? null;\n\t\t\t\tif (isSecret(old)) {\n\t\t\t\t\tstored = old; // kept for this page even if the writes below fail\n\t\t\t\t\tthis.#claim(old);\n\t\t\t\t}\n\t\t\t}\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\t// Also marks the old shared secret taken: an address abandoned with \"New\n\t\t// address\" is not picked up again by another page of the site.\n\t\tthis.#claim(secret);\n\t\treturn secret;\n\t}\n\n\t#claim(secret: string): void {\n\t\ttry {\n\t\t\tthis.#storage?.setItem(this.#key, secret);\n\t\t\tif (this.#claimKey !== undefined)\n\t\t\t\tthis.#storage?.setItem(this.#claimKey, this.#key);\n\t\t} catch {\n\t\t\t// quota or blocked: the secret lives as long as the page\n\t\t}\n\t}\n}\n",
|
|
7
|
-
"/** The library's name and version, sent in `hello
|
|
7
|
+
"/** The library's name and version, sent in `hello`; the version is package.json's. */\nimport { version } from \"../package.json\" with { type: \"json\" };\n\nexport const LIBRARY_NAME = \"@ractive-ch/tab-mcp-client\";\nexport const VERSION: string = version;\n",
|
|
8
8
|
"/**\n * Mirroring the tools into the browser's own WebMCP (iteration 25, DEC-115,\n * DEC-119): with `webmcp: true`, each tool that is offered there is also\n * registered with `document.modelContext.registerTool()`, under its own\n * `AbortController`, aborted when the tool leaves the registry. Part of the\n * core: only the detection, the registrations and the `<html>` attribute;\n * a call loads the lazy chunk, which checks, confirms and runs it.\n */\n\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\n\n/** What the library uses of the browser's `ModelContext`. */\nexport interface ModelContext {\n\tregisterTool(tool: object, options: { signal: AbortSignal }): unknown;\n}\n\n/** Runs a call of a mirrored tool; `signal` is the browser's, if it gives one. */\nexport type WebMcpCall = (\n\ttool: RegisteredTool,\n\tinput: unknown,\n\tsignal: unknown,\n) => Promise<unknown>;\n\nconst g = globalThis as {\n\tDocument?: { prototype: object };\n\tModelContext?: abstract new () => object;\n\tdocument?: Document;\n};\nlet getContext: (() => unknown) | undefined;\nlet Native: (abstract new () => object) | undefined;\n\n/**\n * Capture `Document.prototype`'s `modelContext` getter and `ModelContext`,\n * when the library loads: a page script that runs later cannot put its own\n * object in their place (DEC-115). Called again only by the tests.\n */\nexport function capture(): void {\n\tgetContext =\n\t\tg.Document &&\n\t\tObject.getOwnPropertyDescriptor(g.Document.prototype, \"modelContext\")?.get;\n\tNative = g.ModelContext;\n}\ncapture();\n\n/**\n * The browser's own `ModelContext` of this document, through\n * `Document.prototype`'s getter: never an own `document.modelContext` (a\n * polyfill such as `@mcp-b/global`, or any page script). `undefined` without\n * native WebMCP.\n */\nexport function nativeContext(): ModelContext | undefined {\n\ttry {\n\t\tconst context: unknown = getContext?.call(g.document);\n\t\treturn Native !== undefined && context instanceof Native\n\t\t\t? (context as ModelContext)\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined; // no document\n\t}\n}\n\n/** The WebMCP hints; the MCP-only ones are left out. */\nconst HINTS = [\n\t\"readOnlyHint\",\n\t\"untrustedContentHint\",\n\t\"consequentialHint\",\n\t\"debugging\",\n] as const;\n\n/** `<html data-tab-mcp-webmcp=\"…\">`: the names mirrored, for tab-mcp for Chrome. */\nconst ATTRIBUTE = \"data-tab-mcp-webmcp\";\n\n/** The mirrors registered (or being registered) by every `TabMcp` of the page. */\nconst listed = new Set<{ readonly name: string }>();\n\nfunction writeAttribute(): void {\n\tg.document?.documentElement?.setAttribute(\n\t\tATTRIBUTE,\n\t\t[...listed].map((m) => m.name).join(\" \"),\n\t);\n}\n\n/**\n * Mirror `registry`'s tools that `offered` accepts into `context`, now and\n * whenever the registry changes. Every failure of the native\n * `registerTool()` stays here: warned once per name, the tool still offered\n * through the relay. A failed registration is tried once more a task later\n * (a duplicate right after an abort may be one still on its way out).\n */\nexport function mirror(\n\tregistry: ToolRegistry,\n\tcontext: ModelContext,\n\toffered: (tool: RegisteredTool) => boolean,\n\tcall: WebMcpCall,\n): void {\n\tconst mirrors = new Map<\n\t\tRegisteredTool,\n\t\t{ name: string; controller: AbortController }\n\t>();\n\tconst warned = new Set<string>();\n\tconst register = (\n\t\ttool: RegisteredTool,\n\t\tentry: { name: string; controller: AbortController },\n\t\tretry: boolean,\n\t): void => {\n\t\tconst annotations: Record<string, boolean> = {};\n\t\tfor (const key of HINTS) {\n\t\t\tconst value = tool.annotations[key];\n\t\t\tif (value !== undefined) annotations[key] = value;\n\t\t}\n\t\tconst native = {\n\t\t\tname: tool.name,\n\t\t\t// A WebIDL dictionary: `undefined` is the same as left out.\n\t\t\ttitle: tool.title,\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: tool.inputSchema,\n\t\t\tannotations,\n\t\t\texecute: (input: unknown, options?: { signal?: unknown }) =>\n\t\t\t\tcall(tool, input, options?.signal),\n\t\t};\n\t\tconst { signal } = entry.controller;\n\t\tPromise.resolve()\n\t\t\t// Not once unmirrored, also for a retry: whatever the browser does\n\t\t\t// with an aborted signal.\n\t\t\t.then(() => signal.aborted || context.registerTool(native, { signal }))\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tif (signal.aborted) return; // unmirrored meanwhile\n\t\t\t\tif (retry) {\n\t\t\t\t\t// Once more after a task: a duplicate right after an abort may\n\t\t\t\t\t// be a registration still on its way out (React's `useTool`).\n\t\t\t\t\tsetTimeout(() => register(tool, entry, false));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlisted.delete(entry);\n\t\t\t\twriteAttribute();\n\t\t\t\tif (warned.has(tool.name)) return;\n\t\t\t\twarned.add(tool.name);\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`tab-mcp: ${tool.name} is not offered through WebMCP:`,\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t});\n\t};\n\tconst sync = (): void => {\n\t\tfor (const [tool, entry] of mirrors) {\n\t\t\tif (registry.get(tool.name) === tool) continue;\n\t\t\tentry.controller.abort();\n\t\t\tmirrors.delete(tool);\n\t\t\tlisted.delete(entry);\n\t\t}\n\t\tfor (const tool of registry.list()) {\n\t\t\tif (mirrors.has(tool) || !offered(tool)) continue;\n\t\t\tconst entry = { name: tool.name, controller: new AbortController() };\n\t\t\tmirrors.set(tool, entry);\n\t\t\tlisted.add(entry);\n\t\t\tregister(tool, entry, true);\n\t\t}\n\t\t// Listed before the browser has them, unlisted after it dropped them:\n\t\t// the extension never sees a mirrored tool as the page's own.\n\t\twriteAttribute();\n\t};\n\tregistry.onChange(sync);\n\tsync();\n}\n",
|
|
9
|
-
"/**\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 { CallHost, 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\tIdentityAssertionHandler,\n\tIdentityState,\n\tPairingCode,\n\tReconnectingInfo,\n\tRegisterToolOptions,\n\tRelayClient,\n\tServerInfo,\n\tSessionInfo,\n\tTabMcpEventMap,\n\tTabMcpOptions,\n\tTool,\n\tToolCallClient,\n} from \"./types.ts\";\nimport { LIBRARY_NAME, VERSION } from \"./version.ts\";\nimport { mirror, nativeContext } from \"./webmcp.ts\";\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/** The default waits before each reconnect attempt; the last one repeats. */\nconst RECONNECT_DELAYS_MS = [5_000, 10_000, 20_000, 40_000, 60_000];\n/** Reasons after which the library connects again by itself. */\nconst RECONNECT_REASONS = new Set<DisconnectReason>([\n\t\"network\",\n\t\"heartbeat\",\n\t\"shutdown\",\n]);\n\nfunction reconnectDelays(\n\toption: TabMcpOptions[\"reconnect\"],\n): readonly number[] | undefined {\n\tif (option === false) return undefined;\n\tif (option === undefined || option === true) return RECONNECT_DELAYS_MS;\n\tconst delays = option.delaysMs ?? RECONNECT_DELAYS_MS;\n\tif (\n\t\t!Array.isArray(delays) ||\n\t\tdelays.length === 0 ||\n\t\t!delays.every((d) => typeof d === \"number\" && d >= 0 && d < 2 ** 31)\n\t) {\n\t\tthrow new TypeError(\"TabMcp: reconnect.delaysMs: a non-empty list of ms\");\n\t}\n\treturn [...delays];\n}\n\n/** A delay option: `undefined`, or a whole wait `setTimeout` can keep (below 2^31 ms). */\nfunction delayOption(name: string, value: unknown): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (\n\t\ttypeof value !== \"number\" ||\n\t\t!Number.isFinite(value) ||\n\t\tvalue < 0 ||\n\t\tvalue >= 2 ** 31\n\t) {\n\t\tthrow new TypeError(`TabMcp: ${name} must be a number of milliseconds`);\n\t}\n\treturn value;\n}\n\n/** A grant as the page sees it: frozen, so a page cannot change what decides Always allow. */\nfunction frozenGrant(grant: Grant): Grant {\n\treturn Object.freeze({\n\t\t...grant,\n\t\tclient: Object.freeze({ ...grant.client }),\n\t});\n}\n\n/** What the relay accepts as `hello.app.name` (protocol: session). */\nfunction isAppName(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.trim().length > 0 &&\n\t\tvalue.length <= 64 &&\n\t\t![...value].some((ch) => {\n\t\t\tconst c = ch.codePointAt(0) ?? 0;\n\t\t\treturn c < 0x20 || (c >= 0x7f && c <= 0x9f);\n\t\t})\n\t);\n}\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\tpairing: m.pairing === \"oidc\" ? \"oidc\" : \"code\",\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 #alwaysAllow: boolean;\n\treadonly #relayUrl: string;\n\treadonly #secrets: SecretStore;\n\t/** The channel of the tabs that share the secret (DEC-095). */\n\treadonly #tabs: string | undefined;\n\t/** Replaced since the last session: `newAddress()` takes the address back first. */\n\t#takenOver = false;\n\treadonly #identityAssertion: IdentityAssertionHandler | undefined;\n\t#identity: IdentityState = \"none\";\n\t#identityMessage: string | undefined;\n\t/** Incremented per identity request, so a late answer of an older one is dropped. */\n\t#identityRound = 0;\n\treadonly #identityTimeoutMs: number;\n\t#state: ConnectionState = \"disconnected\";\n\t#session: SessionInfo | undefined;\n\t#grants: readonly Grant[] = Object.freeze([]);\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\t/** Waits between reconnect attempts; `undefined`: reconnecting is off. */\n\treadonly #reconnectDelays: readonly number[] | undefined;\n\t#reconnecting: ReconnectingInfo | undefined;\n\t#reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\t#unwatch: (() => void) | undefined;\n\t/** The page's `connect()` waits on the running reconnect attempt: its promise tells it. */\n\t#pageWaits = false;\n\t/** The open \"Connect your AI app\" dialog: one at a time. */\n\t#connectDialog: { doc: Document; shown: Promise<void> } | undefined;\n\t/**\n\t * What a tool call needs, through the relay and WebMCP alike. The events\n\t * always, even from a connection that is no longer current: a call that\n\t * started must end, and every end has its start.\n\t */\n\treadonly #calls: CallHost = {\n\t\tregistry: this.#registry,\n\t\tconfirm: (request) => this.#confirm(request),\n\t\ttoolCallStarted: (call) => this.#emit(\"toolcall\", call),\n\t\ttoolCallEnded: (call) => this.#emit(\"toolcallend\", call),\n\t};\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 (appName !== undefined && !isAppName(appName)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"TabMcp: appName must be 1-64 characters without control 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 = delayOption(\n\t\t\t\"confirmDelayMs\",\n\t\t\toptions.confirmDelayMs,\n\t\t);\n\t\tthis.#alwaysAllow = options.alwaysAllow === true;\n\t\tthis.#identityAssertion = options.identityAssertion;\n\t\tthis.#identityTimeoutMs =\n\t\t\tdelayOption(\"identityTimeoutMs\", options.identityTimeoutMs) ?? 15_000;\n\t\tthis.#reconnectDelays = reconnectDelays(options.reconnect);\n\t\t// One address per relay and page (server name); the default of 0.4 and\n\t\t// older, per relay only, is moved over once (DEC-083).\n\t\tconst key =\n\t\t\toptions.storageKey ??\n\t\t\t`tab-mcp:secret:${origin}:${encodeURIComponent(server.name)}`;\n\t\tthis.#secrets = new SecretStore(\n\t\t\toptions.storage,\n\t\t\tkey,\n\t\t\toptions.storageKey === undefined ? `tab-mcp:secret:${origin}` : undefined,\n\t\t);\n\t\t// Tabs that share the secret share this channel; with `storage: null`\n\t\t// every tab has an address of its own (DEC-095).\n\t\tthis.#tabs = options.storage === null ? undefined : `${key}#tabs`;\n\t\tthis.#registry.onChange(() =>\n\t\t\tthis.#emit(\"toolschange\", { tools: this.tools }),\n\t\t);\n\t\t// Also through the browser's own WebMCP, where it has it (DEC-115):\n\t\t// consequential tools only when their registration says so.\n\t\tconst context = options.webmcp === true ? nativeContext() : undefined;\n\t\tif (context !== undefined)\n\t\t\tmirror(\n\t\t\t\tthis.#registry,\n\t\t\t\tcontext,\n\t\t\t\t(tool) => tool.webmcp ?? tool.annotations.consequentialHint !== true,\n\t\t\t\t(tool, input, signal) =>\n\t\t\t\t\tthis.#load().then((lazy) =>\n\t\t\t\t\t\tlazy.callFromWebMcp(this.#calls, tool, input, signal),\n\t\t\t\t\t),\n\t\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<Input extends object = Record<string, unknown>>(\n\t\ttool: Tool<Input>,\n\t\toptions: RegisterToolOptions = {},\n\t): Promise<void> {\n\t\ttry {\n\t\t\t// The arguments are checked against `inputSchema` before `execute` runs.\n\t\t\tthis.#registry.register(tool as unknown as 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 (frozen; a new array when they change). */\n\tget grants(): readonly Grant[] {\n\t\treturn this.#grants;\n\t}\n\n\t/**\n\t * While the library connects again by itself after the connection broke:\n\t * the next attempt and when it starts. `undefined` otherwise.\n\t */\n\tget reconnecting(): ReconnectingInfo | undefined {\n\t\treturn this.#reconnecting;\n\t}\n\n\t/** Who the relay knows as the page's user (identity binding). */\n\tget identity(): IdentityState {\n\t\treturn this.#identity;\n\t}\n\n\t/** Why the relay refused the identity, while `identity` is `refused`. */\n\tget identityMessage(): string | undefined {\n\t\treturn this.#identityMessage;\n\t}\n\n\t/**\n\t * Ask the `identityAssertion` hook again and send the result, e.g. after\n\t * the user signed in without a page load. Resolves `true` once the relay\n\t * accepted it; `false` when nobody is signed in, it was refused, or the\n\t * page is not connected.\n\t */\n\trefreshIdentity(): Promise<boolean> {\n\t\tconst session = this.#session;\n\t\tconst ask = this.#identityAssertion;\n\t\tif (\n\t\t\tthis.#state !== \"connected\" ||\n\t\t\tsession === undefined ||\n\t\t\task === undefined\n\t\t) {\n\t\t\treturn Promise.resolve(false);\n\t\t}\n\t\tconst round = ++this.#identityRound;\n\t\tconst connection = this.#connection;\n\t\tthis.#setIdentity(\"pending\");\n\t\t// No answer in time, from the hook or the relay (an old relay, a lost\n\t\t// message, a hook that never settles): give up.\n\t\tconst timer = setTimeout(() => {\n\t\t\tif (round !== this.#identityRound || this.#identity !== \"pending\") return;\n\t\t\tthis.#identityRound++; // a late answer is dropped\n\t\t\tthis.#setIdentity(\"none\");\n\t\t}, this.#identityTimeoutMs);\n\t\treturn new Promise<boolean>((resolve) => {\n\t\t\tconst settle = (event: TabMcpEventMap[\"identitychange\"]) => {\n\t\t\t\tif (event.detail.state === \"pending\") return;\n\t\t\t\tthis.removeEventListener(\"identitychange\", settle);\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(event.detail.state === \"bound\");\n\t\t\t};\n\t\t\tthis.addEventListener(\"identitychange\", settle);\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() =>\n\t\t\t\t\task({ address: session.address, sessionId: session.sessionId }),\n\t\t\t\t)\n\t\t\t\t.then(\n\t\t\t\t\t(assertion) => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tround !== this.#identityRound ||\n\t\t\t\t\t\t\tthis.#connection !== connection\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t// Superseded (a newer request, a sign-out, a new connection): that one settles the state.\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof assertion !== \"string\" || assertion === \"\") {\n\t\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tconnection?.send({ type: \"identity\", assertion, round }) !== true\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tif (round !== this.#identityRound) return;\n\t\t\t\t\t\tthis.#emit(\"error\", {\n\t\t\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * The page's user signed out: the relay ends every AI connection of this\n\t * address at once (identity binding). Call it from the web app's logout.\n\t * Returns `false` when it could not be sent (not connected); the grants\n\t * then stay, but work only while a page signed in as the same person is\n\t * open.\n\t */\n\tsignOut(): boolean {\n\t\tthis.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\tif (this.#state !== \"connected\") return false;\n\t\treturn this.#connection?.send({ type: \"identity.logout\" }) === true;\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 * While reconnecting (`reconnecting`), it makes the next attempt at once.\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) {\n\t\t\tif (this.#reconnecting !== undefined) this.#pageWaits = true;\n\t\t\treturn this.#connecting;\n\t\t}\n\t\tif (this.#reconnecting !== undefined) return this.#attemptReconnect(true);\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\treturn this.#start();\n\t}\n\n\t#start(revokeAll?: boolean): Promise<SessionInfo> {\n\t\tthis.#setState(\"connecting\");\n\t\tconst connecting = this.#open(this.#generation, revokeAll);\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\t/**\n\t * The lazy chunk (on `connect()` or the first WebMCP call). The validator\n\t * is loaded with it: it checks the schemas from now on (DEC-086).\n\t */\n\tasync #load(): Promise<typeof import(\"./connection.ts\")> {\n\t\tconst lazy = await import(\"./connection.ts\");\n\t\tfor (const error of lazy.compileRegistry(this.#registry))\n\t\t\tthis.#emit(\"error\", { error });\n\t\treturn lazy;\n\t}\n\n\tasync #open(generation: number, revokeAll?: boolean): Promise<SessionInfo> {\n\t\tconst { openConnection, addressIdOf, withAddress } = await this.#load();\n\t\tconst secret = this.#secrets.get();\n\t\tconst address = await addressIdOf(secret);\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\twithAddress(this.#relayUrl, address),\n\t\t\tsecret,\n\t\t\trevokeAll,\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. After `replaced`, it first connects with the old address\n\t * again, so that the relay disconnects the apps that now talk to whoever\n\t * took it over (DEC-095), then connects with the new one. Call it from a\n\t * user action.\n\t */\n\tnewAddress(): Promise<SessionInfo | undefined> {\n\t\tif (this.#takenOver) {\n\t\t\t// `hello.revokeAll`: the relay revokes as it hands the address back, and\n\t\t\t// the connection resolves only once no grant is left. Taken over again\n\t\t\t// first: reject, keep the secret, so that a retry takes it back again.\n\t\t\tthis.#end(\"new_address\");\n\t\t\treturn this.#start(true).then(\n\t\t\t\t() => this.#renew(true),\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tthis.#takenOver = true;\n\t\t\t\t\tthrow error;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\treturn this.#renew(false);\n\t}\n\n\t#renew(on: boolean): Promise<SessionInfo | undefined> {\n\t\tconst wasOn =\n\t\t\ton || this.#state !== \"disconnected\" || this.#reconnecting !== undefined;\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\tthis.#takenOver = false; // nobody else has the new secret\n\t\t// It was on: the user chose that already, as for a reconnect.\n\t\treturn wasOn ? this.connect({ resume: true }) : 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.#stopReconnecting();\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.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\tthis.#setState(\"disconnected\");\n\t\tif (wasConnected) this.#emit(\"disconnected\", { reason, code: 1000 });\n\t}\n\n\t/** Wait, then connect again (attempt `attempt`, from 1). */\n\t#scheduleReconnect(reason: DisconnectReason, attempt: number): void {\n\t\tconst delays = this.#reconnectDelays;\n\t\tif (delays === undefined) return;\n\t\tconst delay = delays[Math.min(attempt, delays.length) - 1] ?? 0;\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = setTimeout(() => {\n\t\t\tthis.#attemptReconnect().catch(() => {}); // the next one is scheduled\n\t\t}, delay);\n\t\tthis.#watch();\n\t\tthis.#reconnecting = { reason, attempt, at: Date.now() + delay };\n\t\tthis.#emit(\"reconnecting\", this.#reconnecting);\n\t}\n\n\t/**\n\t * Make the next reconnect attempt now; on failure, schedule the one after.\n\t * `byPage`: from `connect()`, whose promise tells the page why it failed.\n\t */\n\t#attemptReconnect(byPage = false): Promise<SessionInfo> {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tconst info = this.#reconnecting;\n\t\tthis.#pageWaits = byPage;\n\t\tconst attempt = this.#start();\n\t\tattempt.catch((error: unknown) => {\n\t\t\tconst pageWaits = this.#pageWaits;\n\t\t\tthis.#pageWaits = false;\n\t\t\tif (info === undefined || this.#reconnecting !== info) return;\n\t\t\t// Only what may get better: an unreachable relay (network), a\n\t\t\t// heartbeat or a shutdown; a refusal stops it (DEC-082).\n\t\t\tconst reason = (error as { reason?: DisconnectReason } | null)?.reason;\n\t\t\tif (reason === undefined || RECONNECT_REASONS.has(reason)) {\n\t\t\t\tthis.#scheduleReconnect(info.reason, info.attempt + 1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A refusal stops it. Without a connect() of the page's waiting on this\n\t\t\t// attempt, nothing else tells the page why: `error` does, before `null`.\n\t\t\tthis.#stopReconnecting(\n\t\t\t\tpageWaits\n\t\t\t\t\t? undefined\n\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t? error\n\t\t\t\t\t\t: new Error(String(error)),\n\t\t\t);\n\t\t});\n\t\treturn attempt;\n\t}\n\n\t/** Back to the front, or online again: try at once instead of waiting. */\n\t#watch(): void {\n\t\tif (this.#unwatch !== undefined) return;\n\t\tconst g = globalThis as Partial<EventTarget>;\n\t\tconst doc = (globalThis as { document?: Document }).document;\n\t\tconst now = () => {\n\t\t\t// Only while waiting: an attempt that is running is not doubled.\n\t\t\tif (this.#reconnectTimer !== undefined)\n\t\t\t\tthis.#attemptReconnect().catch(() => {});\n\t\t};\n\t\tconst visible = () => {\n\t\t\tif (doc?.visibilityState !== \"hidden\") now();\n\t\t};\n\t\tdoc?.addEventListener(\"visibilitychange\", visible);\n\t\tg.addEventListener?.(\"online\", now);\n\t\tthis.#unwatch = () => {\n\t\t\tdoc?.removeEventListener(\"visibilitychange\", visible);\n\t\t\tg.removeEventListener?.(\"online\", now);\n\t\t};\n\t}\n\n\t/**\n\t * Stop reconnecting. `why` (a refusal) goes out as `error` before the\n\t * `null`, once the state is clear: a listener that calls `connect()` then\n\t * starts afresh, with the user-activation check.\n\t */\n\t#stopReconnecting(why?: Error): void {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tthis.#unwatch?.();\n\t\tthis.#unwatch = undefined;\n\t\tif (this.#reconnecting === undefined) return;\n\t\tthis.#reconnecting = undefined;\n\t\tif (why !== undefined) this.#emit(\"error\", { error: why });\n\t\tthis.#emit(\"reconnecting\", null);\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 app\" dialog; connects first if needed\n\t * (call it from a click). Resolves when the dialog closes. One dialog at\n\t * a time (they would share one pairing): while it is open, a call for the\n\t * same document opens no second one and resolves with it, and a call for\n\t * another document rejects with an `InvalidStateError`. Pages with their\n\t * own UI use the events and methods instead.\n\t */\n\tshowConnectDialog(options: { document?: Document } = {}): Promise<void> {\n\t\tconst doc = options.document ?? globalThis.document;\n\t\tconst open = this.#connectDialog;\n\t\tif (open !== undefined) {\n\t\t\treturn open.doc === doc\n\t\t\t\t? open.shown\n\t\t\t\t: Promise.reject(\n\t\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\t\"showConnectDialog: the dialog is already open in another document\",\n\t\t\t\t\t\t\t\"InvalidStateError\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t}\n\t\tconst shown = this.#showConnectDialog(doc).finally(() => {\n\t\t\tif (this.#connectDialog?.shown === shown) this.#connectDialog = undefined;\n\t\t});\n\t\tthis.#connectDialog = { doc, shown };\n\t\treturn shown;\n\t}\n\n\tasync #showConnectDialog(doc: Document): 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(this, connecting, doc, this.#server.name);\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#setIdentity(state: IdentityState, message?: string): void {\n\t\tif (this.#identity === state && message === undefined) return;\n\t\tthis.#identity = state;\n\t\tthis.#identityMessage = state === \"refused\" ? message : undefined;\n\t\tthis.#emit(\n\t\t\t\"identitychange\",\n\t\t\tmessage === undefined ? { state } : { state, message },\n\t\t);\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: readonly Grant[]): void {\n\t\tthis.#grants = Object.freeze(grants.map(frozenGrant));\n\t\tthis.#emit(\"grantschange\", { grants: this.#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\treturn this.confirmInPage(request);\n\t}\n\n\t/**\n\t * The library's own confirmation: the dialog in the page with Don't allow\n\t * and Allow, and Always allow with `alwaysAllow: true` (what runs without\n\t * `onConfirm`). An `onConfirm`\n\t * may hand some calls to it. Resolves `false` where there is no document.\n\t */\n\tconfirmInPage(request: ConfirmRequest): Promise<boolean> {\n\t\tconst doc = globalThis.document as Document | undefined;\n\t\tif (doc === undefined) return Promise.resolve(false); // nobody to ask: decline\n\t\t// The tools allowed always live in the UI chunk too: only it adds them.\n\t\treturn import(\"./ui.ts\").then((ui) =>\n\t\t\tui.confirmInPage(this, request, doc, {\n\t\t\t\tallowDelayMs: this.#confirmDelayMs,\n\t\t\t\talwaysAllow: this.#alwaysAllow,\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\tlet replacedHere = false;\n\t\treturn {\n\t\t\t...this.#calls,\n\t\t\tserver: this.#server,\n\t\t\tappName: this.#appName,\n\t\t\ttabs: this.#tabs,\n\t\t\tlibrary: { name: LIBRARY_NAME, version: VERSION },\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: RelayClient = {\n\t\t\t\t\tkind: \"relay\",\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.#takenOver = false;\n\t\t\t\tthis.#stopReconnecting();\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\tif (session.pairing === \"oidc\") void this.refreshIdentity();\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\t// After `closed`, so no longer current: only a connection that was\n\t\t\t// current when it was replaced reports it.\n\t\t\treplaced: (detail) => {\n\t\t\t\tif (replacedHere) this.#emit(\"replaced\", detail);\n\t\t\t},\n\t\t\tidentityResult: (bound, round, message) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\t// Only the answer to the newest assertion counts: the relay echoes\n\t\t\t\t// its round, so a lost or late answer cannot pass for a newer one.\n\t\t\t\tif (round !== this.#identityRound) return;\n\t\t\t\tif (bound) this.#setIdentity(\"bound\");\n\t\t\t\telse this.#setIdentity(\"refused\", message ?? \"\");\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\t// Taken over: `newAddress()` takes it back first, whatever runs by\n\t\t\t\t// then (review of PR 39).\n\t\t\t\tif (reason === \"replaced\") this.#takenOver = replacedHere = true;\n\t\t\t\t// Any listener below may end it all (`disconnect()`, `newAddress()`):\n\t\t\t\t// that bumps the generation, and then nothing is scheduled.\n\t\t\t\tconst generation = this.#generation;\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.#identityRound++;\n\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\tthis.#setState(\"disconnected\");\n\t\t\t\tthis.#emit(\"disconnected\", { reason, code });\n\t\t\t\t// After the page heard of it: its listener may have connected or ended it.\n\t\t\t\tif (\n\t\t\t\t\tRECONNECT_REASONS.has(reason) &&\n\t\t\t\t\tthis.#generation === generation &&\n\t\t\t\t\tthis.#state === \"disconnected\" &&\n\t\t\t\t\tthis.#connecting === undefined\n\t\t\t\t)\n\t\t\t\t\tthis.#scheduleReconnect(reason, 1);\n\t\t\t},\n\t\t};\n\t}\n}\n"
|
|
9
|
+
"/**\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 { CallHost, 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\tConfirmAnswer,\n\tConfirmHandler,\n\tConfirmRequest,\n\tConnectionState,\n\tConnectOptions,\n\tDisconnectReason,\n\tGrant,\n\tIdentityAssertionHandler,\n\tIdentityState,\n\tPairingCode,\n\tReconnectingInfo,\n\tRegisterToolOptions,\n\tRelayClient,\n\tServerInfo,\n\tSessionInfo,\n\tTabMcpEventMap,\n\tTabMcpOptions,\n\tTool,\n\tToolCallClient,\n} from \"./types.ts\";\nimport { LIBRARY_NAME, VERSION } from \"./version.ts\";\nimport { mirror, nativeContext } from \"./webmcp.ts\";\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/** The default waits before each reconnect attempt; the last one repeats. */\nconst RECONNECT_DELAYS_MS = [5_000, 10_000, 20_000, 40_000, 60_000];\n/** Reasons after which the library connects again by itself. */\nconst RECONNECT_REASONS = new Set<DisconnectReason>([\n\t\"network\",\n\t\"heartbeat\",\n\t\"shutdown\",\n]);\n\nfunction reconnectDelays(\n\toption: TabMcpOptions[\"reconnect\"],\n): readonly number[] | undefined {\n\tif (option === false) return undefined;\n\tif (option === undefined || option === true) return RECONNECT_DELAYS_MS;\n\tconst delays = option.delaysMs ?? RECONNECT_DELAYS_MS;\n\tif (\n\t\t!Array.isArray(delays) ||\n\t\tdelays.length === 0 ||\n\t\t!delays.every((d) => typeof d === \"number\" && d >= 0 && d < 2 ** 31)\n\t) {\n\t\tthrow new TypeError(\"TabMcp: reconnect.delaysMs: a non-empty list of ms\");\n\t}\n\treturn [...delays];\n}\n\n/** A delay option: `undefined`, or a whole wait `setTimeout` can keep (below 2^31 ms). */\nfunction delayOption(name: string, value: unknown): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (\n\t\ttypeof value !== \"number\" ||\n\t\t!Number.isFinite(value) ||\n\t\tvalue < 0 ||\n\t\tvalue >= 2 ** 31\n\t) {\n\t\tthrow new TypeError(`TabMcp: ${name} must be a number of milliseconds`);\n\t}\n\treturn value;\n}\n\n/** A grant as the page sees it: frozen, so a page cannot change what decides Always allow. */\nfunction frozenGrant(grant: Grant): Grant {\n\treturn Object.freeze({\n\t\t...grant,\n\t\tclient: Object.freeze({ ...grant.client }),\n\t});\n}\n\n/** What the relay accepts as `hello.app.name` (protocol: session). */\nfunction isAppName(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.trim().length > 0 &&\n\t\tvalue.length <= 64 &&\n\t\t![...value].some((ch) => {\n\t\t\tconst c = ch.codePointAt(0) ?? 0;\n\t\t\treturn c < 0x20 || (c >= 0x7f && c <= 0x9f);\n\t\t})\n\t);\n}\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\tpairing: m.pairing === \"oidc\" ? \"oidc\" : \"code\",\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 #alwaysAllow: boolean;\n\treadonly #relayUrl: string;\n\treadonly #secrets: SecretStore;\n\t/** The channel of the tabs that share the secret (DEC-095). */\n\treadonly #tabs: string | undefined;\n\t/** Replaced since the last session: `newAddress()` takes the address back first. */\n\t#takenOver = false;\n\treadonly #identityAssertion: IdentityAssertionHandler | undefined;\n\t#identity: IdentityState = \"none\";\n\t#identityMessage: string | undefined;\n\t/** Incremented per identity request, so a late answer of an older one is dropped. */\n\t#identityRound = 0;\n\treadonly #identityTimeoutMs: number;\n\t#state: ConnectionState = \"disconnected\";\n\t#session: SessionInfo | undefined;\n\t#grants: readonly Grant[] = Object.freeze([]);\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\t/** Waits between reconnect attempts; `undefined`: reconnecting is off. */\n\treadonly #reconnectDelays: readonly number[] | undefined;\n\t#reconnecting: ReconnectingInfo | undefined;\n\t#reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\t#unwatch: (() => void) | undefined;\n\t/** The page's `connect()` waits on the running reconnect attempt: its promise tells it. */\n\t#pageWaits = false;\n\t/** The open \"Connect your AI app\" dialog: one at a time. */\n\t#connectDialog: { doc: Document; shown: Promise<void> } | undefined;\n\t/**\n\t * What a tool call needs, through the relay and WebMCP alike. The events\n\t * always, even from a connection that is no longer current: a call that\n\t * started must end, and every end has its start.\n\t */\n\treadonly #calls: CallHost = {\n\t\tregistry: this.#registry,\n\t\tconfirm: (request) => this.#confirm(request),\n\t\ttoolCallStarted: (call) => this.#emit(\"toolcall\", call),\n\t\ttoolCallEnded: (call) => this.#emit(\"toolcallend\", call),\n\t};\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 (appName !== undefined && !isAppName(appName)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"TabMcp: appName must be 1-64 characters without control 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 = delayOption(\n\t\t\t\"confirmDelayMs\",\n\t\t\toptions.confirmDelayMs,\n\t\t);\n\t\tthis.#alwaysAllow = options.alwaysAllow === true;\n\t\tthis.#identityAssertion = options.identityAssertion;\n\t\tthis.#identityTimeoutMs =\n\t\t\tdelayOption(\"identityTimeoutMs\", options.identityTimeoutMs) ?? 15_000;\n\t\tthis.#reconnectDelays = reconnectDelays(options.reconnect);\n\t\t// One address per relay and page (server name); the default of 0.4 and\n\t\t// older, per relay only, is moved over once (DEC-083).\n\t\tconst key =\n\t\t\toptions.storageKey ??\n\t\t\t`tab-mcp:secret:${origin}:${encodeURIComponent(server.name)}`;\n\t\tthis.#secrets = new SecretStore(\n\t\t\toptions.storage,\n\t\t\tkey,\n\t\t\toptions.storageKey === undefined ? `tab-mcp:secret:${origin}` : undefined,\n\t\t);\n\t\t// Tabs that share the secret share this channel; with `storage: null`\n\t\t// every tab has an address of its own (DEC-095).\n\t\tthis.#tabs = options.storage === null ? undefined : `${key}#tabs`;\n\t\tthis.#registry.onChange(() =>\n\t\t\tthis.#emit(\"toolschange\", { tools: this.tools }),\n\t\t);\n\t\t// Also through the browser's own WebMCP, where it has it (DEC-115):\n\t\t// consequential tools only when their registration says so.\n\t\tconst context = options.webmcp === true ? nativeContext() : undefined;\n\t\tif (context !== undefined)\n\t\t\tmirror(\n\t\t\t\tthis.#registry,\n\t\t\t\tcontext,\n\t\t\t\t(tool) => tool.webmcp ?? tool.annotations.consequentialHint !== true,\n\t\t\t\t(tool, input, signal) =>\n\t\t\t\t\tthis.#load().then((lazy) =>\n\t\t\t\t\t\tlazy.callFromWebMcp(this.#calls, tool, input, signal),\n\t\t\t\t\t),\n\t\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<Input extends object = Record<string, unknown>>(\n\t\ttool: Tool<Input>,\n\t\toptions: RegisterToolOptions = {},\n\t): Promise<void> {\n\t\ttry {\n\t\t\t// The arguments are checked against `inputSchema` before `execute` runs.\n\t\t\tthis.#registry.register(tool as unknown as 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 (frozen; a new array when they change). */\n\tget grants(): readonly Grant[] {\n\t\treturn this.#grants;\n\t}\n\n\t/**\n\t * While the library connects again by itself after the connection broke:\n\t * the next attempt and when it starts. `undefined` otherwise.\n\t */\n\tget reconnecting(): ReconnectingInfo | undefined {\n\t\treturn this.#reconnecting;\n\t}\n\n\t/** Who the relay knows as the page's user (identity binding). */\n\tget identity(): IdentityState {\n\t\treturn this.#identity;\n\t}\n\n\t/** Why the relay refused the identity, while `identity` is `refused`. */\n\tget identityMessage(): string | undefined {\n\t\treturn this.#identityMessage;\n\t}\n\n\t/**\n\t * Ask the `identityAssertion` hook again and send the result, e.g. after\n\t * the user signed in without a page load. Resolves `true` once the relay\n\t * accepted it; `false` when nobody is signed in, it was refused, or the\n\t * page is not connected.\n\t */\n\trefreshIdentity(): Promise<boolean> {\n\t\tconst session = this.#session;\n\t\tconst ask = this.#identityAssertion;\n\t\tif (\n\t\t\tthis.#state !== \"connected\" ||\n\t\t\tsession === undefined ||\n\t\t\task === undefined\n\t\t) {\n\t\t\treturn Promise.resolve(false);\n\t\t}\n\t\tconst round = ++this.#identityRound;\n\t\tconst connection = this.#connection;\n\t\tthis.#setIdentity(\"pending\");\n\t\t// No answer in time, from the hook or the relay (an old relay, a lost\n\t\t// message, a hook that never settles): give up.\n\t\tconst timer = setTimeout(() => {\n\t\t\tif (round !== this.#identityRound || this.#identity !== \"pending\") return;\n\t\t\tthis.#identityRound++; // a late answer is dropped\n\t\t\tthis.#setIdentity(\"none\");\n\t\t}, this.#identityTimeoutMs);\n\t\treturn new Promise<boolean>((resolve) => {\n\t\t\tconst settle = (event: TabMcpEventMap[\"identitychange\"]) => {\n\t\t\t\tif (event.detail.state === \"pending\") return;\n\t\t\t\tthis.removeEventListener(\"identitychange\", settle);\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(event.detail.state === \"bound\");\n\t\t\t};\n\t\t\tthis.addEventListener(\"identitychange\", settle);\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() =>\n\t\t\t\t\task({ address: session.address, sessionId: session.sessionId }),\n\t\t\t\t)\n\t\t\t\t.then(\n\t\t\t\t\t(assertion) => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tround !== this.#identityRound ||\n\t\t\t\t\t\t\tthis.#connection !== connection\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t// Superseded (a newer request, a sign-out, a new connection): that one settles the state.\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof assertion !== \"string\" || assertion === \"\") {\n\t\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tconnection?.send({ type: \"identity\", assertion, round }) !== true\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tif (round !== this.#identityRound) return;\n\t\t\t\t\t\tthis.#emit(\"error\", {\n\t\t\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * The page's user signed out: the relay ends every AI connection of this\n\t * address at once (identity binding). Call it from the web app's logout.\n\t * Returns `false` when it could not be sent (not connected); the grants\n\t * then stay, but work only while a page signed in as the same person is\n\t * open.\n\t */\n\tsignOut(): boolean {\n\t\tthis.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\tif (this.#state !== \"connected\") return false;\n\t\treturn this.#connection?.send({ type: \"identity.logout\" }) === true;\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 * While reconnecting (`reconnecting`), it makes the next attempt at once.\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) {\n\t\t\tif (this.#reconnecting !== undefined) this.#pageWaits = true;\n\t\t\treturn this.#connecting;\n\t\t}\n\t\tif (this.#reconnecting !== undefined) return this.#attemptReconnect(true);\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\treturn this.#start();\n\t}\n\n\t#start(revokeAll?: boolean): Promise<SessionInfo> {\n\t\tthis.#setState(\"connecting\");\n\t\tconst connecting = this.#open(this.#generation, revokeAll);\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\t/**\n\t * The lazy chunk (on `connect()` or the first WebMCP call). The validator\n\t * is loaded with it: it checks the schemas from now on (DEC-086).\n\t */\n\tasync #load(): Promise<typeof import(\"./connection.ts\")> {\n\t\tconst lazy = await import(\"./connection.ts\");\n\t\tfor (const error of lazy.compileRegistry(this.#registry))\n\t\t\tthis.#emit(\"error\", { error });\n\t\treturn lazy;\n\t}\n\n\tasync #open(generation: number, revokeAll?: boolean): Promise<SessionInfo> {\n\t\tconst { openConnection, addressIdOf, withAddress } = await this.#load();\n\t\tconst secret = this.#secrets.get();\n\t\tconst address = await addressIdOf(secret);\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\twithAddress(this.#relayUrl, address),\n\t\t\tsecret,\n\t\t\trevokeAll,\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. After `replaced`, it first connects with the old address\n\t * again, so that the relay disconnects the apps that now talk to whoever\n\t * took it over (DEC-095), then connects with the new one. Call it from a\n\t * user action.\n\t */\n\tnewAddress(): Promise<SessionInfo | undefined> {\n\t\tif (this.#takenOver) {\n\t\t\t// `hello.revokeAll`: the relay revokes as it hands the address back, and\n\t\t\t// the connection resolves only once no grant is left. Taken over again\n\t\t\t// first: reject, keep the secret, so that a retry takes it back again.\n\t\t\tthis.#end(\"new_address\");\n\t\t\treturn this.#start(true).then(\n\t\t\t\t() => this.#renew(true),\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tthis.#takenOver = true;\n\t\t\t\t\tthrow error;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\treturn this.#renew(false);\n\t}\n\n\t#renew(on: boolean): Promise<SessionInfo | undefined> {\n\t\tconst wasOn =\n\t\t\ton || this.#state !== \"disconnected\" || this.#reconnecting !== undefined;\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\tthis.#takenOver = false; // nobody else has the new secret\n\t\t// It was on: the user chose that already, as for a reconnect.\n\t\treturn wasOn ? this.connect({ resume: true }) : 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.#stopReconnecting();\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.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\tthis.#setState(\"disconnected\");\n\t\tif (wasConnected) this.#emit(\"disconnected\", { reason, code: 1000 });\n\t}\n\n\t/** Wait, then connect again (attempt `attempt`, from 1). */\n\t#scheduleReconnect(reason: DisconnectReason, attempt: number): void {\n\t\tconst delays = this.#reconnectDelays;\n\t\tif (delays === undefined) return;\n\t\tconst delay = delays[Math.min(attempt, delays.length) - 1] ?? 0;\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = setTimeout(() => {\n\t\t\tthis.#attemptReconnect().catch(() => {}); // the next one is scheduled\n\t\t}, delay);\n\t\tthis.#watch();\n\t\tthis.#reconnecting = { reason, attempt, at: Date.now() + delay };\n\t\tthis.#emit(\"reconnecting\", this.#reconnecting);\n\t}\n\n\t/**\n\t * Make the next reconnect attempt now; on failure, schedule the one after.\n\t * `byPage`: from `connect()`, whose promise tells the page why it failed.\n\t */\n\t#attemptReconnect(byPage = false): Promise<SessionInfo> {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tconst info = this.#reconnecting;\n\t\tthis.#pageWaits = byPage;\n\t\tconst attempt = this.#start();\n\t\tattempt.catch((error: unknown) => {\n\t\t\tconst pageWaits = this.#pageWaits;\n\t\t\tthis.#pageWaits = false;\n\t\t\tif (info === undefined || this.#reconnecting !== info) return;\n\t\t\t// Only what may get better: an unreachable relay (network), a\n\t\t\t// heartbeat or a shutdown; a refusal stops it (DEC-082).\n\t\t\tconst reason = (error as { reason?: DisconnectReason } | null)?.reason;\n\t\t\tif (reason === undefined || RECONNECT_REASONS.has(reason)) {\n\t\t\t\tthis.#scheduleReconnect(info.reason, info.attempt + 1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A refusal stops it. Without a connect() of the page's waiting on this\n\t\t\t// attempt, nothing else tells the page why: `error` does, before `null`.\n\t\t\tthis.#stopReconnecting(\n\t\t\t\tpageWaits\n\t\t\t\t\t? undefined\n\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t? error\n\t\t\t\t\t\t: new Error(String(error)),\n\t\t\t);\n\t\t});\n\t\treturn attempt;\n\t}\n\n\t/** Back to the front, or online again: try at once instead of waiting. */\n\t#watch(): void {\n\t\tif (this.#unwatch !== undefined) return;\n\t\tconst g = globalThis as Partial<EventTarget>;\n\t\tconst doc = (globalThis as { document?: Document }).document;\n\t\tconst now = () => {\n\t\t\t// Only while waiting: an attempt that is running is not doubled.\n\t\t\tif (this.#reconnectTimer !== undefined)\n\t\t\t\tthis.#attemptReconnect().catch(() => {});\n\t\t};\n\t\tconst visible = () => {\n\t\t\tif (doc?.visibilityState !== \"hidden\") now();\n\t\t};\n\t\tdoc?.addEventListener(\"visibilitychange\", visible);\n\t\tg.addEventListener?.(\"online\", now);\n\t\tthis.#unwatch = () => {\n\t\t\tdoc?.removeEventListener(\"visibilitychange\", visible);\n\t\t\tg.removeEventListener?.(\"online\", now);\n\t\t};\n\t}\n\n\t/**\n\t * Stop reconnecting. `why` (a refusal) goes out as `error` before the\n\t * `null`, once the state is clear: a listener that calls `connect()` then\n\t * starts afresh, with the user-activation check.\n\t */\n\t#stopReconnecting(why?: Error): void {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tthis.#unwatch?.();\n\t\tthis.#unwatch = undefined;\n\t\tif (this.#reconnecting === undefined) return;\n\t\tthis.#reconnecting = undefined;\n\t\tif (why !== undefined) this.#emit(\"error\", { error: why });\n\t\tthis.#emit(\"reconnecting\", null);\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 app\" dialog; connects first if needed\n\t * (call it from a click). Resolves when the dialog closes. One dialog at\n\t * a time (they would share one pairing): while it is open, a call for the\n\t * same document opens no second one and resolves with it, and a call for\n\t * another document rejects with an `InvalidStateError`. Pages with their\n\t * own UI use the events and methods instead.\n\t */\n\tshowConnectDialog(options: { document?: Document } = {}): Promise<void> {\n\t\tconst doc = options.document ?? globalThis.document;\n\t\tconst open = this.#connectDialog;\n\t\tif (open !== undefined) {\n\t\t\treturn open.doc === doc\n\t\t\t\t? open.shown\n\t\t\t\t: Promise.reject(\n\t\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\t\"showConnectDialog: the dialog is already open in another document\",\n\t\t\t\t\t\t\t\"InvalidStateError\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t}\n\t\tconst shown = this.#showConnectDialog(doc).finally(() => {\n\t\t\tif (this.#connectDialog?.shown === shown) this.#connectDialog = undefined;\n\t\t});\n\t\tthis.#connectDialog = { doc, shown };\n\t\treturn shown;\n\t}\n\n\tasync #showConnectDialog(doc: Document): 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(this, connecting, doc, this.#server.name);\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#setIdentity(state: IdentityState, message?: string): void {\n\t\tif (this.#identity === state && message === undefined) return;\n\t\tthis.#identity = state;\n\t\tthis.#identityMessage = state === \"refused\" ? message : undefined;\n\t\tthis.#emit(\n\t\t\t\"identitychange\",\n\t\t\tmessage === undefined ? { state } : { state, message },\n\t\t);\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: readonly Grant[]): void {\n\t\tthis.#grants = Object.freeze(grants.map(frozenGrant));\n\t\tthis.#emit(\"grantschange\", { grants: this.#grants });\n\t}\n\n\t#confirm(request: ConfirmRequest): Promise<ConfirmAnswer> {\n\t\tif (this.#onConfirm !== undefined) {\n\t\t\tconst ask = this.#onConfirm;\n\t\t\t// Anything but true or \"unanswered\" is a refusal.\n\t\t\treturn Promise.resolve()\n\t\t\t\t.then(() => ask(request))\n\t\t\t\t.then((answer) => (answer === \"unanswered\" ? answer : answer === true));\n\t\t}\n\t\treturn this.confirmInPage(request);\n\t}\n\n\t/**\n\t * The library's own confirmation: the dialog in the page with Don't allow\n\t * and Allow, and Always allow with `alwaysAllow: true` (what runs without\n\t * `onConfirm`). An `onConfirm`\n\t * may hand some calls to it. Resolves `false` where there is no document.\n\t */\n\tconfirmInPage(request: ConfirmRequest): Promise<boolean> {\n\t\tconst doc = globalThis.document as Document | undefined;\n\t\tif (doc === undefined) return Promise.resolve(false); // nobody to ask: decline\n\t\t// The tools allowed always live in the UI chunk too: only it adds them.\n\t\treturn import(\"./ui.ts\").then((ui) =>\n\t\t\tui.confirmInPage(this, request, doc, {\n\t\t\t\tallowDelayMs: this.#confirmDelayMs,\n\t\t\t\talwaysAllow: this.#alwaysAllow,\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\tlet replacedHere = false;\n\t\treturn {\n\t\t\t...this.#calls,\n\t\t\tserver: this.#server,\n\t\t\tappName: this.#appName,\n\t\t\ttabs: this.#tabs,\n\t\t\tlibrary: { name: LIBRARY_NAME, version: VERSION },\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: RelayClient = {\n\t\t\t\t\tkind: \"relay\",\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.#takenOver = false;\n\t\t\t\tthis.#stopReconnecting();\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\tif (session.pairing === \"oidc\") void this.refreshIdentity();\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\t// After `closed`, so no longer current: only a connection that was\n\t\t\t// current when it was replaced reports it.\n\t\t\treplaced: (detail) => {\n\t\t\t\tif (replacedHere) this.#emit(\"replaced\", detail);\n\t\t\t},\n\t\t\tidentityResult: (bound, round, message) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\t// Only the answer to the newest assertion counts: the relay echoes\n\t\t\t\t// its round, so a lost or late answer cannot pass for a newer one.\n\t\t\t\tif (round !== this.#identityRound) return;\n\t\t\t\tif (bound) this.#setIdentity(\"bound\");\n\t\t\t\telse this.#setIdentity(\"refused\", message ?? \"\");\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\t// Taken over: `newAddress()` takes it back first, whatever runs by\n\t\t\t\t// then (review of PR 39).\n\t\t\t\tif (reason === \"replaced\") this.#takenOver = replacedHere = true;\n\t\t\t\t// Any listener below may end it all (`disconnect()`, `newAddress()`):\n\t\t\t\t// that bumps the generation, and then nothing is scheduled.\n\t\t\t\tconst generation = this.#generation;\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.#identityRound++;\n\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\tthis.#setState(\"disconnected\");\n\t\t\t\tthis.#emit(\"disconnected\", { reason, code });\n\t\t\t\t// After the page heard of it: its listener may have connected or ended it.\n\t\t\t\tif (\n\t\t\t\t\tRECONNECT_REASONS.has(reason) &&\n\t\t\t\t\tthis.#generation === generation &&\n\t\t\t\t\tthis.#state === \"disconnected\" &&\n\t\t\t\t\tthis.#connecting === undefined\n\t\t\t\t)\n\t\t\t\t\tthis.#scheduleReconnect(reason, 1);\n\t\t\t},\n\t\t};\n\t}\n}\n"
|
|
10
10
|
],
|
|
11
|
-
"mappings": ";AAYA,IAAM,OAAO;AAcb,SAAS,aAAa,CAAC,GAA0C;AAAA,EAChE,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAAA;AAI/D,SA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M;AAAA,QACxB,KAAK,UAAU,cAAc;AAAA,QAC7B,KAAK,MAAM,gBAAgB,EAAE,QAAQ,KAAK,CAAC;AAAA,QAE3C,IACC,kBAAkB,IAAI,MAAM,KAC5B,KAAK,gBAAgB,cACrB,KAAK,WAAW,kBAChB,KAAK,gBAAgB;AAAA,UAErB,KAAK,mBAAmB,QAAQ,CAAC;AAAA;AAAA,IAEpC;AAAA;AAEF;",
|
|
12
|
+
"debugId": "44223BB9C5F01CE164756E2164756E21",
|
|
13
13
|
"names": []
|
|
14
14
|
}
|
package/internal.d.ts
CHANGED
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import type { GrantRef, SessionMessage, TabMessage } from "./protocol.js";
|
|
6
6
|
import type { ToolRegistry } from "./registry.js";
|
|
7
|
-
import type { ConfirmRequest, DisconnectReason, Grant, PairingCode, ReplacedDetail, ServerInfo, SessionInfo, ToolCallClient, ToolCallEnd, ToolCallStart } from "./types.js";
|
|
7
|
+
import type { ConfirmAnswer, ConfirmRequest, DisconnectReason, Grant, PairingCode, ReplacedDetail, ServerInfo, SessionInfo, ToolCallClient, ToolCallEnd, ToolCallStart } from "./types.js";
|
|
8
8
|
/** What a tool call needs from the `TabMcp`, through the relay or WebMCP. */
|
|
9
9
|
export interface CallHost {
|
|
10
10
|
readonly registry: ToolRegistry;
|
|
11
11
|
/** Ask the user about a consequential tool call. */
|
|
12
|
-
confirm(request: ConfirmRequest): Promise<
|
|
12
|
+
confirm(request: ConfirmRequest): Promise<ConfirmAnswer>;
|
|
13
13
|
/** A tool call started or ended (the `toolcall` and `toolcallend` events). */
|
|
14
14
|
toolCallStarted(call: ToolCallStart): void;
|
|
15
15
|
toolCallEnded(call: ToolCallEnd): void;
|
package/mcp.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { type OutputUnit } from "@cfworker/json-schema";
|
|
|
12
12
|
import { type CallToolResult } from "./mapping.js";
|
|
13
13
|
import type { GrantRef } from "./protocol.js";
|
|
14
14
|
import type { RegisteredTool, ToolRegistry } from "./registry.js";
|
|
15
|
-
import type { ConfirmRequest, ServerInfo, ToolCallClient, ToolCallEnd, ToolCallOutcome, ToolCallStart } from "./types.js";
|
|
15
|
+
import type { ConfirmAnswer, ConfirmRequest, ServerInfo, ToolCallClient, ToolCallEnd, ToolCallOutcome, ToolCallStart } from "./types.js";
|
|
16
16
|
export declare const MCP_PROTOCOL_VERSION = "2026-07-28";
|
|
17
17
|
type Json = Record<string, unknown>;
|
|
18
18
|
export interface ToolSource {
|
|
@@ -23,7 +23,7 @@ export interface ToolSource {
|
|
|
23
23
|
export interface CallContext {
|
|
24
24
|
tools: ToolSource;
|
|
25
25
|
/** Ask the user before a consequential tool runs. */
|
|
26
|
-
confirm(request: ConfirmRequest): Promise<
|
|
26
|
+
confirm(request: ConfirmRequest): Promise<ConfirmAnswer>;
|
|
27
27
|
/** Told about every call of a known tool, as it starts and as it ends. */
|
|
28
28
|
observe?: {
|
|
29
29
|
start(call: ToolCallStart): void;
|
|
@@ -71,20 +71,17 @@ export interface McpHandler {
|
|
|
71
71
|
/** Decode the `=?base64?…?=` sentinel of SEP-2243 headers; `undefined` if malformed. */
|
|
72
72
|
export declare function decodeHeaderValue(value: string): string | undefined;
|
|
73
73
|
/**
|
|
74
|
-
* How a call ended. `stop`: it did not run to its end
|
|
75
|
-
*
|
|
76
|
-
* `returned`: what `execute` returned
|
|
74
|
+
* How a call ended. `stop`: why it did not run to its end: invalid
|
|
75
|
+
* arguments, declined by the user, not answered by the user, cancelled, or
|
|
76
|
+
* its tool gone. `returned`: what `execute` returned.
|
|
77
77
|
*/
|
|
78
78
|
export interface CallRun {
|
|
79
79
|
outcome: ToolCallOutcome;
|
|
80
80
|
result: CallToolResult;
|
|
81
|
-
stop?: "
|
|
81
|
+
stop?: "invalid" | "declined" | "unanswered" | "cancelled" | "gone";
|
|
82
82
|
returned?: {
|
|
83
83
|
value: unknown;
|
|
84
84
|
};
|
|
85
|
-
thrown?: {
|
|
86
|
-
error: unknown;
|
|
87
|
-
};
|
|
88
85
|
}
|
|
89
86
|
/**
|
|
90
87
|
* One call of a known tool, from an AI app through the relay or from an
|
|
@@ -96,10 +93,13 @@ export declare function runCall(context: CallContext, tool: RegisteredTool, raw:
|
|
|
96
93
|
/**
|
|
97
94
|
* A call from an agent in the browser (WebMCP) of the mirrored `tool`: the
|
|
98
95
|
* same path as an AI app's call (`runCall`), its outcome as WebMCP has it.
|
|
99
|
-
* Resolves with what `execute` returned
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
96
|
+
* Resolves with what `execute` returned. Every failure the agent should read
|
|
97
|
+
* resolves too, as `{ error: "<message>" }`: invalid arguments, "Don't
|
|
98
|
+
* allow", a question not answered, a tool that is gone, what `execute`
|
|
99
|
+
* threw, an `isError` result.
|
|
100
|
+
* Chrome 156 turns a rejection into a bare `UnknownError`, so the agent
|
|
101
|
+
* would learn neither why nor what to change (DEC-120). Only a call the
|
|
102
|
+
* browser cancelled rejects (`AbortError`): its caller has gone already.
|
|
103
103
|
*/
|
|
104
104
|
export declare function webMcpCall(context: CallContext, tool: RegisteredTool, input: unknown, signal: unknown): Promise<unknown>;
|
|
105
105
|
export declare function createMcpHandler(options: McpHandlerOptions): McpHandler;
|
package/package.json
CHANGED
package/types.d.ts
CHANGED
|
@@ -126,8 +126,14 @@ export interface ConfirmRequest {
|
|
|
126
126
|
/** Aborted when the call is cancelled; close the question then. */
|
|
127
127
|
signal: AbortSignal;
|
|
128
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* The answer to a consequential tool call: `true` runs it, `false` is a
|
|
131
|
+
* refusal, `"unanswered"` says the user was asked and did not answer (e.g. a
|
|
132
|
+
* question of your own that timed out). The AI app is told which.
|
|
133
|
+
*/
|
|
134
|
+
export type ConfirmAnswer = boolean | "unanswered";
|
|
129
135
|
/** Decides whether a consequential tool may run. */
|
|
130
|
-
export type ConfirmHandler = (request: ConfirmRequest) =>
|
|
136
|
+
export type ConfirmHandler = (request: ConfirmRequest) => ConfirmAnswer | Promise<ConfirmAnswer>;
|
|
131
137
|
/** Where the address secret is kept (`localStorage` by default). */
|
|
132
138
|
export interface SecretStorage {
|
|
133
139
|
getItem(key: string): string | null;
|
|
@@ -344,8 +350,11 @@ export interface ToolCallStart {
|
|
|
344
350
|
arguments: Record<string, unknown>;
|
|
345
351
|
client: ToolCallClient;
|
|
346
352
|
}
|
|
347
|
-
/**
|
|
348
|
-
|
|
353
|
+
/**
|
|
354
|
+
* How a tool call ended: `declined` by the user, `unanswered` (the user was
|
|
355
|
+
* asked and did not answer, see `ConfirmAnswer`), `cancelled` by the AI app.
|
|
356
|
+
*/
|
|
357
|
+
export type ToolCallOutcome = "ok" | "error" | "declined" | "unanswered" | "cancelled";
|
|
349
358
|
/** The MCP result of a tool call, as the AI app gets it. */
|
|
350
359
|
export interface ToolCallResult {
|
|
351
360
|
content: unknown[];
|
|
@@ -402,6 +411,6 @@ export interface TabMcpEventMap {
|
|
|
402
411
|
reconnecting: CustomEvent<ReconnectingInfo | null>;
|
|
403
412
|
/** An AI app called a tool (before any confirmation). */
|
|
404
413
|
toolcall: CustomEvent<ToolCallStart>;
|
|
405
|
-
/** That call ended; also when the user declined it or the AI app cancelled it. */
|
|
414
|
+
/** That call ended; also when the user declined it, did not answer, or the AI app cancelled it. */
|
|
406
415
|
toolcallend: CustomEvent<ToolCallEnd>;
|
|
407
416
|
}
|
package/version.d.ts
CHANGED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
var $t=/^(?:\d{1,4}x\d{1,4}|any)$/;function bt(e){let{src:t,mimeType:r,sizes:o,theme:s}=e;if(typeof t!=="string")return;let i=/^https?:/i.test(t)&&t.length<=2048,n=/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon)[;,]/i.test(t)&&t.length<=16384;if(!i&&!n)return;let a={src:t};if(typeof r==="string"&&/^image\/[\w.+-]+$/i.test(r))a.mimeType=r.toLowerCase();let c=Array.isArray(o)?o.map((S)=>String(S).toLowerCase()).filter((S)=>$t.test(S)):[];if(c.length>0)a.sizes=c;if(s==="light"||s==="dark")a.theme=s;return a}function ve(e){let t=[];for(let r of e){let o=typeof r==="object"&&r!==null?bt(r):void 0;if(o!==void 0)t.push(o);if(t.length===8)break}return t}function qe(e=globalThis.document){try{let t=e?.querySelectorAll('link[rel~="icon" i], link[rel~="apple-touch-icon" i]');return ve([...t??[]].filter((r)=>r.getAttribute("href")?.trim()).map((r)=>{let o={src:r.href};if(r.type)o.mimeType=r.type;let s=r.getAttribute("sizes");if(s)o.sizes=s.trim().split(/\s+/);let i=/prefers-color-scheme:\s*(light|dark)/i.exec(r.media);if(i)o.theme=i[1]?.toLowerCase();return o}))}catch{return[]}}function ae(e,t){let r=typeof e;if(r!==typeof t)return!1;let o=Array.isArray(e),s=Array.isArray(t);if(o!==s)return!1;if(o){let i=e.length;if(i!==t.length)return!1;for(let n=0;n<i;n++)if(!ae(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(let c of i){if(!Object.prototype.hasOwnProperty.call(t,c))return!1;if(!ae(e[c],t[c]))return!1}return!0}return e===t}function J(e){return encodeURI(wt(e)).replace(/#/g,"%23")}function wt(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var xt=/^[A-Za-z0-9._~!$&'()*+,;=:@/?-]$/,Rt=/^%[0-9A-Fa-f]{2}$/,kt=/^[A-Za-z0-9._~-]$/;function It(e){let t="";for(let r=0;r<e.length;){let o=e[r],s=e.slice(r,r+3);if(o==="%"&&Rt.test(s)){let n=String.fromCharCode(parseInt(s.slice(1),16));t+=kt.test(n)?n:s.toUpperCase(),r+=3;continue}let i=String.fromCodePoint(e.codePointAt(r));t+=xt.test(i)?i:encodeURIComponent(i),r+=i.length}return t}function be(e,t){let r=new URL(e,t.href);return r.hash=r.hash?It(r.hash.slice(1)):"",r}var Tt={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},vt={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},St={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,dependentRequired:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},_t=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function ee(e,t=Object.create(null),r=_t,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let n=be(i,r);if(n.hash.length>1)t[n.href]=e;else if(n.hash="",o==="")r=n;else ee(e,t,r)}}else if(e!==!0&&e!==!1)return t;let s=r.href+(o?"#"+o:"");if(t[s]!==void 0&&t[s]!==e)throw Error(`Duplicate schema URI "${s}".`);if(t[s]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:s});if(e.$ref&&e.__absolute_ref__===void 0){let i=be(e.$ref,r);Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=be(e.$recursiveRef,r);Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=be("#"+e.$anchor,r);t[i.href]=e}for(let i in e){if(St[i])continue;let n=`${o}/${J(i)}`,a=e[i];if(Array.isArray(a)){if(Tt[i]){let c=a.length;for(let S=0;S<c;S++)ee(a[S],t,r,`${n}/${S}`)}}else if(vt[i])for(let c in a)ee(a[c],t,r,`${n}/${J(c)}`);else ee(a,t,r,n)}return t}var Et=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Mt=[0,31,28,31,30,31,30,31,31,30,31,30,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_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,zt=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Ht=/^("(?:[\x20-\x21\x23-\x5b\x5d-\x7e]|\\[\x20-\x7e])*"|[a-z0-9.!#$%&'*+/=?^_`{|}~-]+)@(.+)$/i,Jt=(e)=>{let t=e.match(Ht);if(!t)return!1;let r=t[1],o=t[2];if(!r||!o||r.length>64||o.length>253)return!1;if(r[0]!=='"'&&(r[0]==="."||r.endsWith(".")||r.includes("..")))return!1;if(o.startsWith("[")&&o.endsWith("]")){let s=o.slice(1,-1);if(/^ipv6:/i.test(s))return Je.test(s.slice(5));return He.test(s)}return ze.test(o)},He=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Je=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Ut=(e)=>/^P(?:\d+W|(?:(?:\d+Y(?:\d+M(?:\d+D)?)?|\d+M(?:\d+D)?|\d+D)(?:T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S))?|T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S)))$/.test(e);function K(e){return e.test.bind(e)}var Se={date:Ue,time:Be.bind(void 0,!0),"date-time":Vt,duration:Ut,uri:Ft,"uri-reference":K(Ot),"uri-template":K(Ct),url:K(Pt),email:Jt,hostname:K(ze),ipv4:K(He),ipv6:K(Je),regex:Yt,uuid:K(Nt),"json-pointer":K(jt),"json-pointer-uri-fragment":K(qt),"relative-json-pointer":K(zt)};function Bt(e){return e%4===0&&(e%100!==0||e%400===0)}function Ue(e){let t=e.match(Et);if(!t)return!1;let r=t[1],o=t[2],s=t[3];if(!r||!o||!s)return!1;let i=+r,n=+o,a=+s,c=n==2&&Bt(i)?29:Mt[n];return n>=1&&n<=12&&a>=1&&c!==void 0&&a<=c}function Be(e,t){let r=t.match(At);if(!r)return!1;let o=r[1],s=r[2],i=r[3];if(!o||!s||!i)return!1;let n=+o,a=+s,c=+i,S=r[5],I=r[6],N=+(r[7]??0),D=+(r[8]??0);if(n>23||a>59||c>60||N>23||D>59||e&&S===void 0)return!1;if(c<60)return!0;let U=I==="+"?1:I==="-"?-1:0;return(n*60+a-U*(N*60+D)+1440)%1440===1439}var Dt=/t|\s/i;function Vt(e){let[t,r,o]=e.split(Dt);return t!==void 0&&r!==void 0&&o===void 0&&Ue(t)&&Be(!0,r)}var Gt=/\/|:/,Wt=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Ft(e){return Gt.test(e)&&Wt.test(e)}var Kt=/[^\\]\\Z/;function Yt(e){if(Kt.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function De(e){let t=0,r=e.length,o=0,s;while(o<r)if(t++,s=e.charCodeAt(o++),s>=55296&&s<=56319&&o<r){if(s=e.charCodeAt(o),(s&64512)==56320)o++}return t}function se(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ve(e){let t=Math.abs(e).toString().split("e"),r=t[0],o=t[1]??"0",s=r.indexOf("."),i=s===-1?0:r.length-s-1;return[BigInt(r.replace(".","")),Number(o)-i]}function Zt(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return!1;let[r,o]=Ve(e),[s,i]=Ve(t),n=o-i;if(n>=0)return r*10n**BigInt(n)%s===0n;return r%(s*10n**BigInt(-n))===0n}function A(e,t,r="2019-09",o=ee(t),s=!0,i=null,n="#",a="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:n,keyword:"false",keywordLocation:n,error:"False boolean schema."}]};let S=typeof e,I;switch(S){case"boolean":case"number":case"string":I=S;break;case"object":if(e===null)I="null";else if(Array.isArray(e))I="array";else I="object";break;default:throw Error(`Instances of "${S}" type are not supported.`)}let{$ref:N,$recursiveRef:D,$recursiveAnchor:U,type:C,const:G,enum:B,required:L,not:m,anyOf:y,allOf:T,oneOf:v,if:R,then:_,else:O,format:d,properties:k,patternProperties:w,additionalProperties:j,unevaluatedProperties:E,minProperties:z,maxProperties:H,propertyNames:W,dependentRequired:Z,dependentSchemas:V,dependencies:F,prefixItems:ce,items:re,additionalItems:Ae,unevaluatedItems:Oe,contains:Ce,minContains:X,maxContains:Re,minItems:ke,maxItems:Ie,uniqueItems:gt,minimum:ne,maximum:oe,exclusiveMinimum:pe,exclusiveMaximum:me,multipleOf:Te,minLength:ye,maxLength:ge,pattern:Pe,__absolute_ref__:he,__absolute_recursive_ref__:ht}=t,l=[];if(U===!0&&i===null)i=t;if(D==="#"){let b=i===null?o[ht]:i,p=`${a}/$recursiveRef`,x=A(e,i===null?t:i,r,o,s,b,n,p,c);if(!x.valid)l.push({instanceLocation:n,keyword:"$recursiveRef",keywordLocation:p,error:"A subschema had errors."},...x.errors)}if(N!==void 0){let p=o[he||N];if(p===void 0){let u=`Unresolved $ref "${N}".`;if(he&&he!==N)u+=` Absolute URI "${he}".`;throw u+=`
|
|
2
|
-
Known schemas:
|
|
3
|
-
- ${Object.keys(o).join(`
|
|
4
|
-
- `)}`,Error(u)}let x=`${a}/$ref`,f=A(e,p,r,o,s,i,n,x,c);if(!f.valid)l.push({instanceLocation:n,keyword:"$ref",keywordLocation:x,error:"A subschema had errors."},...f.errors);if(r==="4"||r==="7")return{valid:l.length===0,errors:l}}if(Array.isArray(C)){let b=C.length,p=!1;for(let x=0;x<b;x++)if(I===C[x]||C[x]==="integer"&&I==="number"&&e%1===0&&e===e){p=!0;break}if(!p)l.push({instanceLocation:n,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${I}" is invalid. Expected "${C.join('", "')}".`})}else if(C==="integer"){if(I!=="number"||e%1||e!==e)l.push({instanceLocation:n,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${I}" is invalid. Expected "${C}".`})}else if(C!==void 0&&I!==C)l.push({instanceLocation:n,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${I}" is invalid. Expected "${C}".`});if(G!==void 0){if(I==="object"||I==="array"){if(!ae(e,G))l.push({instanceLocation:n,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(G)}.`})}else if(e!==G)l.push({instanceLocation:n,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(G)}.`})}if(B!==void 0){if(I==="object"||I==="array"){if(!B.some((b)=>ae(e,b)))l.push({instanceLocation:n,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(B)}.`})}else if(!B.some((b)=>e===b))l.push({instanceLocation:n,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(B)}.`})}if(m!==void 0){let b=`${a}/not`;if(A(e,m,r,o,s,i,n,b).valid)l.push({instanceLocation:n,keyword:"not",keywordLocation:b,error:'Instance matched "not" schema.'})}let $e=[];if(y!==void 0){let b=`${a}/anyOf`,p=l.length,x=!1;for(let[f,u]of y.entries()){let h=Object.create(c),g=A(e,u,r,o,s,U===!0?i:null,n,`${b}/${f}`,h);if(l.push(...g.errors),x=x||g.valid,g.valid)$e.push(h)}if(x)l.length=p;else l.splice(p,0,{instanceLocation:n,keyword:"anyOf",keywordLocation:b,error:"Instance does not match any subschemas."})}if(T!==void 0){let b=`${a}/allOf`,p=l.length,x=!0;for(let[f,u]of T.entries()){let h=Object.create(c),g=A(e,u,r,o,s,U===!0?i:null,n,`${b}/${f}`,h);if(l.push(...g.errors),x=x&&g.valid,g.valid)$e.push(h)}if(x)l.length=p;else l.splice(p,0,{instanceLocation:n,keyword:"allOf",keywordLocation:b,error:"Instance does not match every subschema."})}if(v!==void 0){let b=`${a}/oneOf`,p=l.length,x=v.filter((f,u)=>{let h=Object.create(c),g=A(e,f,r,o,s,U===!0?i:null,n,`${b}/${u}`,h);if(l.push(...g.errors),g.valid)$e.push(h);return g.valid}).length;if(x===1)l.length=p;else l.splice(p,0,{instanceLocation:n,keyword:"oneOf",keywordLocation:b,error:`Instance does not match exactly one subschema (${x} matches).`})}if(I==="object"||I==="array")Object.assign(c,...$e);if(R!==void 0){let b=`${a}/if`,p=Object.create(null);if(A(e,R,r,o,s,i,n,b,p).valid){if(Object.assign(c,p),_!==void 0){let f=A(e,_,r,o,s,i,n,`${a}/then`,c);if(!f.valid)l.push({instanceLocation:n,keyword:"if",keywordLocation:b,error:'Instance does not match "then" schema.'},...f.errors)}}else if(O!==void 0){let f=A(e,O,r,o,s,i,n,`${a}/else`,c);if(!f.valid)l.push({instanceLocation:n,keyword:"if",keywordLocation:b,error:'Instance does not match "else" schema.'},...f.errors)}}if(I==="object"){if(L!==void 0){for(let f of L)if(!se(e,f))l.push({instanceLocation:n,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${f}".`})}let b=Object.keys(e);if(z!==void 0&&b.length<z)l.push({instanceLocation:n,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${z} properties.`});if(H!==void 0&&b.length>H)l.push({instanceLocation:n,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${H} properties.`});if(W!==void 0){let f=`${a}/propertyNames`;for(let u in e){let h=`${n}/${J(u)}`,g=A(u,W,r,o,s,i,h,f);if(!g.valid)l.push({instanceLocation:n,keyword:"propertyNames",keywordLocation:f,error:`Property name "${u}" does not match schema.`},...g.errors)}}if(Z!==void 0){let f=`${a}/dependantRequired`;for(let u in Z)if(se(e,u)){let h=Z[u];for(let g of h)if(!se(e,g))l.push({instanceLocation:n,keyword:"dependentRequired",keywordLocation:f,error:`Instance has "${u}" but does not have "${g}".`})}}if(V!==void 0)for(let[f,u]of Object.entries(V)){let h=`${a}/dependentSchemas`;if(se(e,f)){let g=A(e,u,r,o,s,i,n,`${h}/${J(f)}`,c);if(!g.valid)l.push({instanceLocation:n,keyword:"dependentSchemas",keywordLocation:h,error:`Instance has "${f}" but does not match dependant schema.`},...g.errors)}}if(F!==void 0){let f=`${a}/dependencies`;for(let u in F)if(se(e,u)){let h=F[u];if(Array.isArray(h)){for(let g of h)if(!se(e,g))l.push({instanceLocation:n,keyword:"dependencies",keywordLocation:f,error:`Instance has "${u}" but does not have "${g}".`})}else{let g=A(e,h,r,o,s,i,n,`${f}/${J(u)}`);if(!g.valid)l.push({instanceLocation:n,keyword:"dependencies",keywordLocation:f,error:`Instance has "${u}" but does not match dependant schema.`},...g.errors)}}}let p=Object.create(null),x=!1;if(k!==void 0){let f=`${a}/properties`;for(let[u,h]of Object.entries(k)){if(!se(e,u))continue;let g=`${n}/${J(u)}`,P=A(e[u],h,r,o,s,i,g,`${f}/${J(u)}`);if(p[u]=!0,P.valid)c[u]=!0;else if(x=s,l.push({instanceLocation:n,keyword:"properties",keywordLocation:f,error:`Property "${u}" does not match schema.`},...P.errors),x)break}}if(!x&&w!==void 0){let f=`${a}/patternProperties`;for(let[u,h]of Object.entries(w)){let g=new RegExp(u,"u");for(let P in e){if(!g.test(P))continue;let Ne=`${n}/${J(P)}`,je=A(e[P],h,r,o,s,i,Ne,`${f}/${J(u)}`);if(p[P]=!0,je.valid)c[P]=!0;else x=s,l.push({instanceLocation:n,keyword:"patternProperties",keywordLocation:f,error:`Property "${P}" matches pattern "${u}" but does not match associated schema.`},...je.errors)}}}if(!x&&j!==void 0){let f=`${a}/additionalProperties`;for(let u in e){if(p[u])continue;let h=`${n}/${J(u)}`,g=A(e[u],j,r,o,s,i,h,f);if(g.valid)c[u]=!0;else x=s,l.push({instanceLocation:n,keyword:"additionalProperties",keywordLocation:f,error:`Property "${u}" does not match additional properties schema.`},...g.errors)}}else if(!x&&E!==void 0){let f=`${a}/unevaluatedProperties`;for(let u in e)if(!c[u]){let h=`${n}/${J(u)}`,g=A(e[u],E,r,o,s,i,h,f);if(g.valid)c[u]=!0;else l.push({instanceLocation:n,keyword:"unevaluatedProperties",keywordLocation:f,error:`Property "${u}" does not match unevaluated properties schema.`},...g.errors)}}}else if(I==="array"){if(Ie!==void 0&&e.length>Ie)l.push({instanceLocation:n,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Ie}).`});if(ke!==void 0&&e.length<ke)l.push({instanceLocation:n,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${ke}).`});let b=e.length,p=0,x=!1;if(ce!==void 0){let f=`${a}/prefixItems`,u=Math.min(ce.length,b);for(;p<u;p++){let h=A(e[p],ce[p],r,o,s,i,`${n}/${p}`,`${f}/${p}`);if(c[p]=!0,!h.valid){if(x=s,l.push({instanceLocation:n,keyword:"prefixItems",keywordLocation:f,error:"Items did not match schema."},...h.errors),x)break}}}if(re!==void 0){let f=`${a}/items`;if(Array.isArray(re)){let u=Math.min(re.length,b);for(;p<u;p++){let h=A(e[p],re[p],r,o,s,i,`${n}/${p}`,`${f}/${p}`);if(c[p]=!0,!h.valid){if(x=s,l.push({instanceLocation:n,keyword:"items",keywordLocation:f,error:"Items did not match schema."},...h.errors),x)break}}}else for(;p<b;p++){let u=A(e[p],re,r,o,s,i,`${n}/${p}`,f);if(c[p]=!0,!u.valid){if(x=s,l.push({instanceLocation:n,keyword:"items",keywordLocation:f,error:"Items did not match schema."},...u.errors),x)break}}if(!x&&Ae!==void 0){let u=`${a}/additionalItems`;for(;p<b;p++){let h=A(e[p],Ae,r,o,s,i,`${n}/${p}`,u);if(c[p]=!0,!h.valid)x=s,l.push({instanceLocation:n,keyword:"additionalItems",keywordLocation:u,error:"Items did not match additional items schema."},...h.errors)}}}if(Ce!==void 0)if(b===0&&X===void 0)l.push({instanceLocation:n,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(X!==void 0&&b<X)l.push({instanceLocation:n,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${b}) than minContains (${X}).`});else{let f=`${a}/contains`,u=l.length,h=0;for(let g=0;g<b;g++){let P=A(e[g],Ce,r,o,s,i,`${n}/${g}`,f);if(P.valid)c[g]=!0,h++;else l.push(...P.errors)}if(h>=(X||0))l.length=u;if(X===void 0&&h===0)l.splice(u,0,{instanceLocation:n,keyword:"contains",keywordLocation:f,error:"Array does not contain item matching schema."});else if(X!==void 0&&h<X)l.push({instanceLocation:n,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${X} items matching schema. Only ${h} items were found.`});else if(Re!==void 0&&h>Re)l.push({instanceLocation:n,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Re} items matching schema. ${h} items were found.`})}if(!x&&Oe!==void 0){let f=`${a}/unevaluatedItems`;for(p;p<b;p++){if(c[p])continue;let u=A(e[p],Oe,r,o,s,i,`${n}/${p}`,f);if(c[p]=!0,!u.valid)l.push({instanceLocation:n,keyword:"unevaluatedItems",keywordLocation:f,error:"Items did not match unevaluated items schema."},...u.errors)}}if(gt)for(let f=0;f<b;f++){let u=e[f],h=typeof u==="object"&&u!==null;for(let g=0;g<b;g++){if(f===g)continue;let P=e[g];if(u===P||h&&(typeof P==="object"&&P!==null)&&ae(u,P))l.push({instanceLocation:n,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${f} and ${g}.`}),f=Number.MAX_SAFE_INTEGER,g=Number.MAX_SAFE_INTEGER}}}else if(I==="number"){if(r==="4"){if(ne!==void 0&&(pe===!0&&e<=ne||e<ne))l.push({instanceLocation:n,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${pe?"or equal to ":""} ${ne}.`});if(oe!==void 0&&(me===!0&&e>=oe||e>oe))l.push({instanceLocation:n,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${me?"or equal to ":""} ${oe}.`})}else{if(ne!==void 0&&e<ne)l.push({instanceLocation:n,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${ne}.`});if(oe!==void 0&&e>oe)l.push({instanceLocation:n,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${oe}.`});if(pe!==void 0&&e<=pe)l.push({instanceLocation:n,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${pe}.`});if(me!==void 0&&e>=me)l.push({instanceLocation:n,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})}if(Te!==void 0){if(!Zt(e,Te))l.push({instanceLocation:n,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Te}.`})}}else if(I==="string"){let b=ye===void 0&&ge===void 0?0:De(e);if(ye!==void 0&&b<ye)l.push({instanceLocation:n,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${b} < ${ye}).`});if(ge!==void 0&&b>ge)l.push({instanceLocation:n,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${b} > ${ge}).`});if(Pe!==void 0&&!new RegExp(Pe,"u").test(e))l.push({instanceLocation:n,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(d!==void 0&&Se[d]&&!Se[d](e))l.push({instanceLocation:n,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${d}".`})}return{valid:l.length===0,errors:l}}var We="ch.ractive.tab-mcp/annotations",Xt=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"],Qt=["destructiveHint","idempotentHint","openWorldHint"];function Fe(e){let t={};if(e.readOnlyHint===!0)t.readOnlyHint=!0,t.destructiveHint=!1;else if(e.readOnlyHint===!1)t.readOnlyHint=!1;if(e.consequentialHint===!0)t.destructiveHint=!0;if(e.untrustedContentHint===!0)t.openWorldHint=!0;for(let s of Qt){let i=e[s];if(i!==void 0)t[s]=i}let r={};for(let s of Xt){let i=e[s];if(i!==void 0)r[s]=i}let o={};if(Object.keys(t).length>0)o.annotations=t;if(Object.keys(r).length>0)o.meta=r;return o}function ue(e){return{content:[{type:"text",text:e}],isError:!0}}function Ge(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Ke(e){if(typeof e==="string")return{content:[{type:"text",text:e}]};if(e===void 0)return{content:[]};if(Ge(e)&&Array.isArray(e.content))return e;let t;try{t=JSON.stringify(e)}catch{}if(t===void 0)return ue("The tool returned a value that is not JSON.");let r={content:[{type:"text",text:t}]};if(Ge(e))r.structuredContent=e;return r}function Ye(e){let t=e instanceof Error?e.message:String(e);return ue(t||"The tool failed.")}var ie="2026-07-28",te="io.modelcontextprotocol/protocolVersion",we="io.modelcontextprotocol/clientCapabilities",Ze="io.modelcontextprotocol/clientInfo",Xe="io.modelcontextprotocol/serverInfo",_e="io.modelcontextprotocol/subscriptionId",Lt=-32020,Qe=-32022,er=0,Le=new WeakMap;function Ee(e){let t=Le.get(e);if(t!==void 0)return t;let r=e.inputSchema,o;try{o=ee(r)}catch(i){let n=i instanceof Error?i.message:String(i);throw Error(n.split(`
|
|
5
|
-
`)[0])}for(let i of Object.values(o)){if(typeof i!=="object"||i.$ref===void 0)continue;let n=i.__absolute_ref__;if(o[n??i.$ref]===void 0)throw Error(`$ref ${JSON.stringify(i.$ref)} does not resolve`)}let s=(i)=>A(i,r,"2020-12",o,!1);return Le.set(e,s),s}function et(e,t,r=""){let o=t instanceof Error?t.message:String(t);return TypeError(`registerTool: the inputSchema of ${e}: ${o}${r}`)}function tr(e){let t=[];for(let r of e.list())try{Ee(r)}catch(o){e.remove(r),t.push(et(r.name,o,"; the tool was unregistered"))}return e.setCompiler((r)=>{try{Ee(r)}catch(o){throw et(r.name,o)}}),t}function tt(e){try{return structuredClone(e)}catch{return e}}var rr=new TextEncoder;function Q(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Me(e,t){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}})}function q(e,t,r,o,s){let i={code:r,message:o};if(s!==void 0)i.data=s;return Me(e,{jsonrpc:"2.0",id:t,error:i})}function Y(e,t,r){return q(400,e,Lt,`Bad Request: the request headers and body disagree: ${r}`,{mismatch:{header:t,body:r}})}function le(e){return rr.encode(`event: message
|
|
6
|
-
data: ${JSON.stringify(e)}
|
|
7
|
-
|
|
8
|
-
`)}var rt={"content-type":"text/event-stream","cache-control":"no-cache"};function nr(e){return(e??"").split(";")[0]?.trim().toLowerCase()==="application/json"}function or(e){if(!(e.startsWith("=?base64?")&&e.endsWith("?=")))return e;let t=e.slice(9,-2);if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return;try{let r=atob(t),o=Uint8Array.from(r,(s)=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{return}}function sr(e){if(!(te in e))return{key:te,problem:"missing"};if(!(we in e))return{key:we,problem:"missing"};if(typeof e[te]!=="string")return{key:te,problem:"expected a protocol version string"};if(!Q(e[we]))return{key:we,problem:"expected an object"};let t=e[Ze];if(t!==void 0&&!(Q(t)&&typeof t.name==="string"&&typeof t.version==="string"))return{key:Ze,problem:"expected {name, version}"};return}function ir(e){let t=e.notifications;return Q(t)&&t.toolsListChanged===!0?{toolsListChanged:!0}:{}}function dr(e,t){let r;try{r=Ee(e)(t)}catch(s){let i=s instanceof Error?s.message:String(s);return`The input schema of tool ${e.name} cannot be used: ${i}`}if(r.valid)return;let o=r.errors.filter((s)=>s.keyword!=="properties"&&s.keyword!=="$ref").map((s)=>`${s.instanceLocation} ${s.error}`).slice(0,5).join("; ");return`Input validation error: Invalid arguments for tool ${e.name}: ${o||"the arguments do not match the schema"}`}async function ot(e,t,r,o,s){let i={id:++er,tool:t.name,arguments:tt(r),client:{...s}};if(t.title!==void 0)i.title=t.title;let n=Date.now();e.observe?.start(i);let a={outcome:"error",result:ue("Internal error")};try{a=await ar(e,t,r,o,s)}finally{e.observe?.end({id:i.id,tool:t.name,client:{...s},outcome:a.outcome,result:tt(a.result),durationMs:Date.now()-n})}return a}async function ar(e,t,r,o,s){let i=(c,S,I)=>({outcome:c,result:ue(S),stop:I}),n=dr(t,r);if(n!==void 0)return i("error",n,"TypeError");if(t.annotations.consequentialHint===!0){let c={tool:{name:t.name,description:t.description},arguments:r,client:s,signal:o};if(t.title!==void 0)c.tool.title=t.title;let S=!1;try{S=await e.confirm(c)}catch{S=!1}if(!S)return o.aborted?i("cancelled","The user declined","AbortError"):i("declined","The user declined","NotAllowedError")}if(o.aborted)return i("cancelled","Cancelled","AbortError");if(e.tools.get(t.name)!==t)return i("error","The tool is no longer available","InvalidStateError");let a;try{let c=await t.execute(r,{signal:o,client:s});a={outcome:"ok",result:Ke(c),returned:{value:c}}}catch(c){a={outcome:"error",result:Ye(c),thrown:{error:c}}}if(o.aborted)return{...a,outcome:"cancelled",stop:"AbortError"};if(a.result.isError===!0)a.outcome="error";return a}async function st(e,t,r,o){let s=(n,a)=>n==="TypeError"?TypeError(a):new DOMException(a,n);if(e.tools.get(t.name)!==t)throw s("InvalidStateError",`The tool ${t.name} is no longer available`);if(!Q(r))throw s("TypeError","The input must be an object");let i=await ot(e,t,r,o instanceof AbortSignal?o:new AbortController().signal,{kind:"webmcp"});if(i.stop!==void 0)throw s(i.stop,i.stop==="AbortError"?"Cancelled":nt(i.result));if(i.thrown!==void 0)throw i.thrown.error;if(i.result.isError===!0)throw Error(nt(i.result)||"The tool failed.");return i.returned?.value}function nt(e){return e.content.map((t)=>Q(t)&&t.type==="text"&&typeof t.text==="string"?t.text:"").filter((t)=>t!=="").join(`
|
|
9
|
-
`)}function it(e){let{tools:t,server:r}=e,o={name:r.name,version:r.version};if(r.title!==void 0)o.title=r.title;let s=ve(r.icons??[]),i=s.length>0?{...o,icons:s}:o,n=new Set,a=!1,c=(m={})=>({...m,[Xe]:o});function S(m,y,T=c()){return{jsonrpc:"2.0",id:m,result:{...y,resultType:"complete",_meta:T}}}function I(){return t.list().map((m)=>{let y={name:m.name};if(m.title!==void 0)y.title=m.title;y.description=m.description,y.inputSchema=m.inputSchema;let{annotations:T,meta:v}=Fe(m.annotations);if(T!==void 0)y.annotations=T;if(v!==void 0)y._meta={[We]:v};return y})}let N=(m)=>({kind:"invalid",message:m});async function D(m,y,T){let v=m.name;if(typeof v!=="string")return N("Invalid params: name must be a string");let R=t.get(v);if(R===void 0)return N(`Tool ${v} not found`);let _=m.arguments??{};if(!Q(_))return N("Invalid params: arguments must be an object");return{kind:"result",result:(await ot(e,R,_,y,e.client(T))).result}}function U(m,y,T,v){let R=new ReadableStream({start:(_)=>{let O=(d)=>{if(T.aborted)return;let k;try{k=le(d)}catch{k=le(S(m,ue("The tool returned a result that is not JSON.")))}try{_.enqueue(k),_.close()}catch{}};D(y,T,v).then((d)=>O(d.kind==="invalid"?{jsonrpc:"2.0",id:m,error:{code:-32602,message:d.message}}:S(m,d.result)),()=>O({jsonrpc:"2.0",id:m,error:{code:-32603,message:"Internal error"}}))}});return new Response(R,{status:200,headers:rt})}function C(m,y,T){let v=ir(y),R={jsonrpc:"2.0",id:m,result:{resultType:"complete",_meta:c({[_e]:m})}},_,O=new ReadableStream({start:(d)=>{if(d.enqueue(le({jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{notifications:v,_meta:{[_e]:m}}})),Object.keys(v).length===0){d.enqueue(le(R)),d.close();return}let k={id:m,send:(w)=>{try{d.enqueue(le(w))}catch{n.delete(k)}},end:()=>{n.delete(k);try{d.enqueue(le(R)),d.close()}catch{}}};_=k,n.add(k),T.addEventListener("abort",()=>{n.delete(k);try{d.close()}catch{}})},cancel:()=>{if(_!==void 0)n.delete(_)}});return new Response(O,{status:200,headers:rt})}function G(m,y){if(Array.isArray(y))return q(400,null,-32600,"Bad Request: JSON-RPC batches are not supported by this endpoint");if(!Q(y)||y.jsonrpc!=="2.0")return q(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let{method:T,id:v}=y;if(typeof T!=="string")return"result"in y||"error"in y?q(400,null,-32600,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):q(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let R=m.headers.get("mcp-protocol-version"),_=m.headers.get("mcp-method"),O=Q(y.params)?y.params:{},d=Q(O._meta)?O._meta:void 0,k=d!==void 0&&te in d,w=typeof d?.[te]==="string"?d[te]:void 0,j=R!==null&&R>=ie;if(v===void 0){if(w!==void 0&&R!==null&&R!==w)return Y(null,R,`the notification envelope names protocol version ${w} but the MCP-Protocol-Version header names ${R}`);if((k||j)&&_!==null&&_!==T)return Y(null,_,`the notification body names method ${T} but the Mcp-Method header names ${_}`);return"notification"}if(typeof v!=="string"&&typeof v!=="number")return q(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let E=v;if(!k||T==="initialize"&&(w===void 0||w<ie)){if(T==="initialize"){if(j)return Y(E,R,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let H=typeof O.protocolVersion==="string"?O.protocolVersion:void 0;return B(E,H)}if(j){let H=d===void 0?["_meta"]:[te];return q(400,E,-32602,`Invalid params: the MCP-Protocol-Version header names protocol revision ${R}, but the request is missing the required per-request envelope key(s): ${H.join(", ")}`,{envelope:{missing:H}})}return B(E,R??void 0)}let z=sr(d);if(z!==void 0)return q(400,E,-32602,`Invalid _meta envelope for protocol revision ${ie}: ${z.key}: ${z.problem}`,{envelope:z});if(R!==null&&w!==void 0&&R!==w)return Y(E,R,`the body envelope names protocol version ${w} but the MCP-Protocol-Version header names ${R}`);if(_!==null&&_!==T)return Y(E,_,`the body names method ${T} but the Mcp-Method header names ${_}`);if(w!==ie)return B(E,w);if(R===null)return Y(E,"(missing)",`the body envelope names protocol version ${w} but the required MCP-Protocol-Version header is absent`);if(_===null)return Y(E,"(missing)",`the body names method ${T} but the required Mcp-Method header is absent`);if(T==="tools/call"&&typeof O.name==="string"){let H=O.name,W=m.headers.get("mcp-name");if(W===null)return Y(E,"(missing)",`the body carries params.name="${H}" but the required Mcp-Name header is absent`);let Z=or(W);if(Z===void 0)return Y(E,W,"the Mcp-Name header carries an invalid Base64 sentinel value");if(Z!==H)return Y(E,W,`the body carries params.name="${H}" but the Mcp-Name header names "${Z}"`)}return{id:E,method:T,params:O}}function B(m,y){return y===void 0?q(400,m,Qe,"Unsupported protocol version: the request did not name a protocol version",{supported:[ie]}):q(400,m,Qe,`Unsupported protocol version: ${y}`,{supported:[ie],requested:y})}async function L(m,y){if(m.method.toUpperCase()!=="POST")return q(405,null,-32000,"Method not allowed.");if(!nr(m.headers.get("content-type")))return q(415,null,-32000,"Unsupported Media Type: Content-Type must be application/json");let T;try{T=JSON.parse(y.body??await m.text())}catch{return q(400,null,-32700,"Parse error: the request body is not valid JSON")}let v=G(m,T);if(v instanceof Response)return v;if(v==="notification")return new Response(null,{status:202});let{id:R,method:_,params:O}=v;switch(_){case"server/discover":{let d={supportedVersions:[ie],capabilities:{tools:{listChanged:!0}}};if(r.instructions!==void 0)d.instructions=r.instructions;return d.ttlMs=0,d.cacheScope="private",Me(200,S(R,d,{[Xe]:i}))}case"tools/list":return Me(200,S(R,{tools:I(),ttlMs:0,cacheScope:"private"}));case"tools/call":return U(R,O,m.signal,y.grant);case"subscriptions/listen":return C(R,O,m.signal);default:return q(404,R,-32601,"Method not found")}}return{handle:(m,y)=>L(m,y).catch(()=>q(500,null,-32603,"Internal server error")),toolsChanged(){if(a)return;a=!0,queueMicrotask(()=>{a=!1;for(let m of[...n])m.send({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:{_meta:{[_e]:m.id}}})})},close(){for(let m of[...n])m.end()}}}var xe="tab-mcp.v1",ur=new Set(["start","used","locked","expired"]);function fe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var M=(e)=>typeof e==="string";function dt(e){if(!fe(e)||!M(e.grantId)||!M(e.createdAt))return!1;let t=e.client;return fe(t)&&M(t.id)&&M(t.name)&&M(t.host)}function lr(e){if(!fe(e))return!1;return["maxMessageBytes","maxBodyBytes","requestTimeoutMs","idleTimeoutMs","heartbeatMs","keepAliveMs","maxConcurrentRequests"].every((t)=>typeof e[t]==="number")}function fr(e){return fe(e)&&Object.values(e).every(M)}function at(e){let t;try{t=JSON.parse(e)}catch{return}if(!fe(t))return;switch(t.type){case"session":return M(t.sessionId)&&M(t.address)&&M(t.origin)&&M(t.expiresAt)&&lr(t.limits)&&Array.isArray(t.grants)&&t.grants.every(dt)&&(t.appName===void 0||M(t.appName))&&(t.pairing===void 0||M(t.pairing))?t:void 0;case"ping":return typeof t.t==="number"?t:void 0;case"bye":return{type:"bye",reason:M(t.reason)?t.reason:""};case"http.request":return M(t.id)&&M(t.method)&&M(t.path)&&fr(t.headers)&&M(t.body)&&fe(t.grant)&&M(t.grant.grantId)&&M(t.grant.clientId)?t:void 0;case"http.cancel":return M(t.id)?t:void 0;case"pairing.code":{if(!M(t.code)||!M(t.expiresAt))return;let r={type:"pairing.code",code:t.code,expiresAt:t.expiresAt},o=t.reason;if(typeof o==="string"&&ur.has(o))r.reason=o;return r}case"grant.added":return dt(t.grant)?t:void 0;case"grant.removed":return M(t.grantId)?{type:"grant.removed",grantId:t.grantId,reason:M(t.reason)?t.reason:""}:void 0;case"identity.bound":return typeof t.round==="number"?{type:"identity.bound",round:t.round}:{type:"identity.bound"};case"error":return M(t.code)?t:void 0;default:return}}function cr(e){let t="",r=0,o=0;for(let s of e){r=r<<8|s,o+=8;while(o>=5)o-=5,t+="abcdefghijklmnopqrstuvwxyz234567"[r>>>o&31];r&=(1<<o)-1}if(o>0)t+="abcdefghijklmnopqrstuvwxyz234567"[r<<5-o&31];return t}async function pr(e,t=globalThis.crypto?.subtle??null){if(t===null)return;try{let r=await t.digest("SHA-256",new TextEncoder().encode(e));return cr(new Uint8Array(r))}catch{return}}function mr(e,t){if(t===void 0)return e;let r=new URL(e);return r.searchParams.set("a",t),r.href}function ct(e){return{tools:e.registry,confirm:(t)=>e.confirm(t),observe:{start:(t)=>e.toolCallStarted(t),end:(t)=>e.toolCallEnded(t)}}}function Kr(e,t,r,o){return st(ct(e),t,r,o)}var yr=15000,ut={1000:"closed",1008:"policy",1009:"too_large",4001:"expired",4002:"idle",4003:"heartbeat",4004:"shutdown",4005:"replaced",4008:"rate_limited",4009:"policy"},lt={replaced:"replaced",expired:"expired",idle:"idle",shutdown:"shutdown"};function de(e,t){return Object.assign(Error(e),{reason:t})}var gr=["content-type","cache-control"];function hr(){let e=globalThis.document?.title;return typeof e==="string"?e.slice(0,300):""}function $r(e){try{let t=JSON.parse(e);if(typeof t!=="object"||t===null||typeof t.type!=="string")return;return typeof t.id==="string"?{type:t.type,id:t.id}:{type:t.type}}catch{return}}var br=new Set(["session","ping","bye","http.request","http.cancel","pairing.code","grant.added","grant.removed","identity.bound","error"]),pt=512,mt=6,yt=64,wr=pt+mt*yt;function xr(e){let t=Math.floor((e-pt)/mt);return t>=yt?t:void 0}function*ft(e,t){let r=0;while(r<e.length){let o=Math.min(r+t,e.length),s=e.charCodeAt(o-1);if(o<e.length&&s>=55296&&s<=56319)o+=o-1>r?-1:1;yield e.slice(r,o),r=o}}var Rr=1e4,kr=1000;function Ir(e){let t,r=Number.NEGATIVE_INFINITY,o;try{if(e!==void 0&&typeof BroadcastChannel==="function")t=new BroadcastChannel(e),t.onmessage=(s)=>{if(s.data?.type!=="claimed")return;r=Date.now(),o?.()}}catch{t=void 0}return{claimed(){try{t?.postMessage({type:"claimed"})}catch{}},heard(){if(Date.now()-r<=Rr)return Promise.resolve(!0);if(t===void 0)return Promise.resolve(!1);return new Promise((s)=>{let i=setTimeout(()=>s(!1),kr);o=()=>{clearTimeout(i),s(!0)}})},close(){t?.close()}}}function Yr(e,t,r,o=!1){let s=new WebSocket(t,xe),i=new Map,n="opening",a,c=65536,S,I=0,N=Ir(e.tabs),D,U,C,G=new Promise((d,k)=>{U=d,C=k});G.catch(()=>{});let B=setTimeout(()=>{v(de("The relay did not answer in time.","network"))},yr),L=it({...ct(e),server:{...e.server,icons:e.server.icons??qe()},client:(d)=>e.clientFor(d)}),m=e.registry.onChange(()=>L.toolsChanged());function y(d){if(s.readyState!==WebSocket.OPEN)return!1;try{return s.send(JSON.stringify(d)),!0}catch{return!1}}function T(){if(I<=0)return;clearTimeout(S),S=setTimeout(()=>{a??="heartbeat",R(4003);try{s.close()}catch{}},I*2.5)}function v(d){if(n!=="opening")return;R(0),C(d);try{s.close()}catch{}}function R(d){if(n==="closed")return;let k=n==="ready";n="closed",clearTimeout(B),clearTimeout(S),m();for(let w of i.values())w.abort();if(i.clear(),L.close(),k){let w=a??ut[d]??(d===1006?"network":"closed");if(C(de("The address was taken over again before its AI apps were disconnected.",w)),e.closed(w,d),w==="replaced"){N.heard().then((j)=>{N.close(),e.replaced({sibling:j})});return}}N.close()}async function _(d){let k=new AbortController;i.set(d.id,k);let w=()=>n==="ready"&&i.get(d.id)===k&&!k.signal.aborted;try{let j=new Request(`https://tab.invalid${d.path}`,{method:d.method,headers:d.headers,signal:k.signal}),E=await L.handle(j,{grant:d.grant,body:d.body});if(!w()){await E.body?.cancel().catch(()=>{});return}let z={};for(let V of gr){let F=E.headers.get(V);if(F!==null)z[V]=F}if(!(z["content-type"]??"").startsWith("text/event-stream")||E.body===null){let V=await E.text();if(!w())return;if(V.length<=c){y({type:"http.response",id:d.id,status:E.status,headers:z,body:V});return}y({type:"http.response.start",id:d.id,status:E.status,headers:z});for(let F of ft(V,c)){if(!w())break;y({type:"http.response.chunk",id:d.id,data:F})}if(w())y({type:"http.response.end",id:d.id});return}y({type:"http.response.start",id:d.id,status:E.status,headers:z});let W=E.body.getReader(),Z=new TextDecoder;k.signal.addEventListener("abort",()=>{W.cancel().catch(()=>{})});for(;;){let{done:V,value:F}=await W.read();if(V||!w())break;let ce=Z.decode(F,{stream:!0});for(let re of ft(ce,c))y({type:"http.response.chunk",id:d.id,data:re})}if(w())y({type:"http.response.end",id:d.id})}catch(j){if(w())e.error(j instanceof Error?j:Error(String(j))),y({type:"http.response",id:d.id,status:500,headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"Internal server error"}})})}finally{if(i.get(d.id)===k)i.delete(d.id)}}function O(d){if(n==="opening"){if(d.type==="session"){let k=xr(d.limits.maxMessageBytes);if(k===void 0){v(de(`The relay's message limit (${d.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${wr}.`,"policy"));return}c=k,n="ready",clearTimeout(B),I=d.limits.heartbeatMs,T(),N.claimed();let w=e.sessionStarted(d);if(o&&d.grants.length>0){D={left:new Set(d.grants.map((j)=>j.grantId)),session:w},y({type:"grants.revokeAll"});return}U(w)}else if(d.type==="error")v(de(`The relay refused the connection: ${d.message||d.code}`,d.code==="rate_limited"?"rate_limited":"policy"));else if(d.type==="bye")v(de(`The relay ended the connection: ${d.reason}`,lt[d.reason]??"closed"));return}if(n!=="ready")return;switch(d.type){case"ping":T(),y({type:"pong",t:d.t});return;case"http.request":_(d);return;case"http.cancel":i.get(d.id)?.abort(),i.delete(d.id);return;case"pairing.code":e.pairingCode(d.reason===void 0?{code:d.code,expiresAt:d.expiresAt}:{code:d.code,expiresAt:d.expiresAt,reason:d.reason});return;case"grant.added":e.grantAdded(d.grant);return;case"grant.removed":if(e.grantRemoved(d.grantId),D?.left.delete(d.grantId),D?.left.size===0)U(D.session);return;case"identity.bound":e.identityResult(!0,d.round);return;case"bye":if(a=lt[d.reason]??"closed",a==="replaced")R(4005);return;case"error":if(d.code==="identity_refused"){e.identityResult(!1,typeof d.round==="number"?d.round:void 0,d.message);return}e.error(Error(`Relay error ${d.code}: ${d.message}`));return;case"session":return}}return s.addEventListener("open",()=>{if(s.protocol!==""&&s.protocol!==xe){v(de(`The relay speaks ${s.protocol}, not ${xe}.`,"policy"));return}let d={type:"hello",library:e.library,page:{title:hr()},secret:r};if(e.appName!==void 0)d.app={name:e.appName};if(o)d.revokeAll=!0;y(d)}),s.addEventListener("message",(d)=>{if(typeof d.data!=="string")return;let k=at(d.data);if(k!==void 0){if(n==="ready")T();O(k);return}let w=$r(d.data);if(w?.id!==void 0)y(br.has(w.type)?{type:"error",code:"bad_message",message:`malformed ${w.type}`,id:w.id}:{type:"error",code:"unknown_type",message:`unknown type ${w.type}`,id:w.id})}),s.addEventListener("close",(d)=>{if(n==="opening"){R(d.code);let k=d.code===1006||d.code===1002;C(de(k?"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).":`The relay closed the connection (${d.code}${d.reason?`: ${d.reason}`:""}).`,ut[d.code]??(k?"network":"closed")));return}R(d.code)}),{ready:G,send:y,close(d){if(n==="closed")return;if(n==="opening"){v(new DOMException("The connection was cancelled","AbortError"));return}a=d,y({type:"bye",reason:"user"}),R(1000);try{s.close(1000,"bye")}catch{}}}}export{wr as MIN_MESSAGE_BYTES,kr as SIBLING_GRACE_MS,Rr as SIBLING_WINDOW_MS,pr as addressIdOf,Kr as callFromWebMcp,xr as chunkSize,tr as compileRegistry,Yr as openConnection,ft as pieces,mr as withAddress};
|
|
10
|
-
|
|
11
|
-
//# debugId=92C3A49EE24D628064756E2164756E21
|
|
12
|
-
//# sourceMappingURL=connection-bjvxzxer.min.js.map
|