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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +849 -0
  2. package/README.md +102 -74
  3. package/address.d.ts +8 -8
  4. package/cdn/{confirm-y30cx7e1.min.js → confirm-mqmvsxg1.min.js} +2 -2
  5. package/cdn/{connect-bbhj2y7w.min.js → connect-c7wn48yp.min.js} +2 -2
  6. package/cdn/{connect-bbhj2y7w.min.js.map → connect-c7wn48yp.min.js.map} +1 -1
  7. package/cdn/{connection-w97tf22a.min.js → connection-0xqwz17v.min.js} +7 -7
  8. package/cdn/{connection-w97tf22a.min.js.map → connection-0xqwz17v.min.js.map} +5 -5
  9. package/cdn/{index-vt5zk9me.min.js → index-t33bb2g4.min.js} +4 -4
  10. package/cdn/{index-vt5zk9me.min.js.map → index-t33bb2g4.min.js.map} +4 -4
  11. package/cdn/tab-mcp-client.min.js +3 -3
  12. package/cdn/tab-mcp-client.min.js.map +4 -4
  13. package/{confirm-fgnjgd08.js → confirm-vj2zbq4w.js} +2 -2
  14. package/{connect-8jpb0k29.js → connect-9pefy0xe.js} +2 -2
  15. package/{connect-8jpb0k29.js.map → connect-9pefy0xe.js.map} +1 -1
  16. package/{connection-g91xjjgm.js → connection-gang7f5x.js} +10 -23
  17. package/{connection-g91xjjgm.js.map → connection-gang7f5x.js.map} +5 -5
  18. package/connection.d.ts +2 -2
  19. package/index-dmh5vm5m.js.map +1 -1
  20. package/{index-jnz7w9xa.js → index-qw8qy5ed.js} +11 -11
  21. package/{index-jnz7w9xa.js.map → index-qw8qy5ed.js.map} +2 -2
  22. package/index.js +24 -26
  23. package/index.js.map +4 -4
  24. package/internal.d.ts +2 -0
  25. package/package.json +1 -1
  26. package/protocol.d.ts +6 -7
  27. package/secret.d.ts +1 -1
  28. package/strings.d.ts +1 -1
  29. package/tab-mcp.d.ts +10 -1
  30. package/types.d.ts +16 -2
  31. package/visible.d.ts +1 -1
  32. /package/cdn/{confirm-y30cx7e1.min.js.map → confirm-mqmvsxg1.min.js.map} +0 -0
  33. /package/{confirm-fgnjgd08.js.map → confirm-vj2zbq4w.js.map} +0 -0
@@ -3,11 +3,11 @@
3
3
  "sources": ["../../src/registry.ts", "../../src/secret.ts", "../../src/version.ts", "../../src/tab-mcp.ts"],
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\tToolCaller,\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 outputSchema?: JsonSchema | undefined;\n\treadonly annotations: ToolAnnotations;\n\treadonly execute: Tool[\"execute\"];\n\t/**\n\t * `RegisterToolOptions.callers`, copied; `undefined`: the default, which\n\t * `toolsFor` (serve.ts, the relay and a port) and `mirror` (webmcp.ts) apply.\n\t */\n\treadonly callers?: readonly ToolCaller[] | undefined;\n\t/** `RegisterToolOptions.exposedTo`, passed on to the native registration. */\n\treadonly exposedTo?: string[] | 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/** Keywords whose values are data, not schemas (CC 13). */\nconst DATA = /^(default|examples|const|enum)$/;\n/** Keywords whose values map names to schemas: the names are not keywords. */\nconst NAMED =\n\t/^(properties|patternProperties|\\$defs|definitions|dependentSchemas)$/;\n\n/**\n * Calls `visit` for every schema object in `node`, itself included. The\n * values of `default`, `examples`, `const` and `enum` are data and are\n * skipped. An array, or the map under `properties` and the like (`map`), is\n * not a schema itself: its values are, and its keys are names, not keywords.\n */\nfunction eachSchema(\n\tnode: unknown,\n\tvisit: (schema: Record<string, unknown>) => void,\n\tdepth = 0,\n\tmap = false,\n): void {\n\tif (depth > 64 || typeof node !== \"object\" || node === null) return;\n\tmap ||= Array.isArray(node);\n\tif (!map) visit(node as Record<string, unknown>);\n\tfor (const [key, value] of Object.entries(node))\n\t\tif (map || !DATA.test(key))\n\t\t\teachSchema(value, visit, depth + 1, !map && NAMED.test(key));\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\tlet key: string;\n\t\ttry {\n\t\t\tkey = decodeURIComponent(raw);\n\t\t} catch {\n\t\t\treturn undefined; // a malformed `%`\n\t\t}\n\t\tkey = key.replaceAll(\"~1\", \"/\").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 * Also `x-mcp-header`, which makes the relay validate headers it does not\n * know; not supported in v1.\n */\nfunction schemaProblem(root: unknown): string | undefined {\n\tconst anchors = new Set<string>();\n\tconst refs: string[] = [];\n\tconst patterns: string[] = [];\n\tlet header = false;\n\teachSchema(root, (o) => {\n\t\tif (typeof o[\"$anchor\"] === \"string\") anchors.add(o[\"$anchor\"]);\n\t\tif (typeof o[\"$ref\"] === \"string\") refs.push(o[\"$ref\"]);\n\t\tif (typeof o[\"pattern\"] === \"string\") patterns.push(o[\"pattern\"]);\n\t\tconst pp = o[\"patternProperties\"];\n\t\tif (isPlainObject(pp)) patterns.push(...Object.keys(pp));\n\t\tif (\"x-mcp-header\" in o) header = true;\n\t});\n\tif (header) return \"x-mcp-header is not supported by tab-mcp\";\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 {\n\t\tname,\n\t\ttitle,\n\t\tdescription,\n\t\tinputSchema,\n\t\toutputSchema,\n\t\texecute,\n\t\tannotations,\n\t} = 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\t/**\n\t * An object schema (MCP wants `\"type\": \"object\"`), copied as JSON and\n\t * checked by `schemaProblem`: an AI app compiles the output schema too.\n\t */\n\tconst copy = (schema: unknown, what: string): JsonSchema => {\n\t\tif (!isPlainObject(schema) || schema[\"type\"] !== \"object\") {\n\t\t\tthrow new TypeError(\n\t\t\t\t`registerTool: the ${what} of ${name} must be a JSON Schema object with \"type\": \"object\"`,\n\t\t\t);\n\t\t}\n\t\tlet copied: JsonSchema;\n\t\ttry {\n\t\t\tcopied = JSON.parse(JSON.stringify(schema)) as JsonSchema;\n\t\t} catch {\n\t\t\tthrow new TypeError(`registerTool: the ${what} of ${name} must be JSON`);\n\t\t}\n\t\tconst problem = schemaProblem(copied);\n\t\tif (problem !== undefined)\n\t\t\tthrow new TypeError(`registerTool: the ${what} of ${name}: ${problem}`);\n\t\treturn copied;\n\t};\n\tconst copied = copy(inputSchema ?? { type: \"object\" }, \"inputSchema\");\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\t// A hint that is not a boolean is refused, not dropped: a dropped\n\t// `consequentialHint: \"true\"` would run the tool without asking (CC 2).\n\t// Every key ending in `Hint`, and `debugging`, counts as a hint, also\n\t// one tab-mcp does not know (a later draft's, or a misspelt one); other\n\t// keys that are not booleans are ignored.\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\telse if (value !== undefined && /Hint$|^debugging$/.test(key))\n\t\t\tthrow new TypeError(`registerTool: ${key} of ${name} must be a boolean`);\n\t}\n\treturn {\n\t\tname,\n\t\ttitle,\n\t\tdescription,\n\t\tinputSchema: copied,\n\t\toutputSchema:\n\t\t\toutputSchema === undefined\n\t\t\t\t? undefined\n\t\t\t\t: copy(outputSchema, \"outputSchema\"),\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, an\n\t * `InvalidStateError` `DOMException` for a duplicate name and the abort\n\t * reason for an aborted signal (as WebMCP).\n\t */\n\tregister(tool: Tool, options: RegisterToolOptions = {}): void {\n\t\tconst { signal, exposedTo } = options;\n\t\t// A copy: the page's array may change later, what was registered does\n\t\t// not. Not a list: the spread throws a `TypeError` itself.\n\t\tconst callers = options.callers && [...options.callers];\n\t\t// The option of 0.15 and before, refused rather than ignored: an ignored\n\t\t// `webmcp: false` would put the tool into WebMCP (DEC-165).\n\t\tif (\n\t\t\t\"webmcp\" in options ||\n\t\t\tcallers?.some((c) => !/^(relay|local|webmcp)$/.test(c))\n\t\t)\n\t\t\tthrow new TypeError(\n\t\t\t\t'registerTool: callers must be \"relay\", \"local\" or \"webmcp\"; option webmcp is gone',\n\t\t\t);\n\t\tconst registered: RegisteredTool = {\n\t\t\t...validateTool(tool),\n\t\t\tcallers,\n\t\t\texposedTo,\n\t\t};\n\t\tsignal?.throwIfAborted();\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
- "/**\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/**\n\t * The current secret, or `undefined` while this page has none (none made\n\t * yet); storage first, so a rotation in another tab is seen.\n\t */\n\tcurrent(): string | undefined {\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;\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",
6
+ "/**\n * The address secret (DEC-027): 32 random bytes as base64url without padding,\n * kept in `localStorage`. The relay derives the stable address from it.\n */\n\nimport type { SecretStorage } from \"./types.ts\";\n\nconst SECRET = /^[A-Za-z0-9_-]{43}$/;\n/** base64url without padding. */\nexport function base64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\n\nexport function newSecret(): string {\n\treturn base64url(crypto.getRandomValues(new Uint8Array(32)));\n}\n\nexport function isSecret(value: unknown): value is string {\n\treturn typeof value === \"string\" && SECRET.test(value);\n}\n\n/** `localStorage`, or `null` where it is missing or blocked. */\nfunction defaultStorage(): SecretStorage | null {\n\ttry {\n\t\tconst storage = (globalThis as { localStorage?: SecretStorage })\n\t\t\t.localStorage;\n\t\treturn storage ?? null;\n\t} catch {\n\t\treturn null; // SecurityError: storage blocked for this page\n\t}\n}\n\n/** Reads, creates and rotates the secret; falls back to memory without storage. */\nexport class SecretStore {\n\treadonly #storage: SecretStorage | null;\n\treadonly #key: string;\n\t#memory: string | undefined;\n\n\tconstructor(storage: SecretStorage | null | undefined, key: string) {\n\t\tthis.#storage = storage === undefined ? defaultStorage() : storage;\n\t\tthis.#key = key;\n\t}\n\n\t/**\n\t * The current secret, or `undefined` while this page has none (none made\n\t * yet); storage first, so a rotation in another tab is seen.\n\t */\n\tcurrent(): string | undefined {\n\t\tlet stored: string | null = null;\n\t\ttry {\n\t\t\tstored = this.#storage?.getItem(this.#key) ?? null;\n\t\t} catch {\n\t\t\t// unreadable: use a page-lifetime secret\n\t\t}\n\t\tif (isSecret(stored)) {\n\t\t\tthis.#memory = stored;\n\t\t\treturn stored;\n\t\t}\n\t\treturn this.#memory;\n\t}\n\n\t/** Make and keep a new secret (a new address). */\n\trotate(): string {\n\t\tconst secret = newSecret();\n\t\tthis.#memory = secret;\n\t\ttry {\n\t\t\tthis.#storage?.setItem(this.#key, secret);\n\t\t} catch {\n\t\t\t// quota or blocked: the secret lives as long as the page\n\t\t}\n\t\treturn secret;\n\t}\n}\n",
7
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
- "/**\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, TabMessage } 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\tDialogOptions,\n\tDisconnectReason,\n\tGrant,\n\tIdentityAssertionHandler,\n\tIdentityState,\n\tPairingCode,\n\tReconnectingInfo,\n\tRegisterToolOptions,\n\tRelayClient,\n\tServeHandle,\n\tServeOptions,\n\tServerInfo,\n\tSessionInfo,\n\tTabMcpEventMap,\n\tTabMcpOptions,\n\tTool,\n\tToolCallClient,\n\tTunnelPort,\n} from \"./types.ts\";\nimport { LIBRARY_NAME, VERSION } from \"./version.ts\";\nimport type { ModelContext } from \"./webmcp.ts\";\n\n/**\n * The browser's own `ModelContext` of this document, read when a `TabMcp` is\n * made, through `Document.prototype`'s getter: never an own\n * `document.modelContext` (a polyfill such as `@mcp-b/global`, or any page\n * script; DEC-115). `undefined` without native WebMCP or a document. In the\n * core; the mirror itself is a chunk of its own (DEC-171).\n */\nfunction nativeContext(): ModelContext | undefined {\n\ttry {\n\t\treturn Object.getOwnPropertyDescriptor(\n\t\t\tDocument.prototype,\n\t\t\t\"modelContext\",\n\t\t)?.get?.call(document);\n\t} catch {\n\t\treturn undefined; // no document\n\t}\n}\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/**\n * The library's waits, in milliseconds: constants for pages (CU 17), which\n * only tests change. `reconnectDelaysMs`: before each reconnect attempt,\n * the last one repeating. `answerTimeoutMs`: for an identity assertion and\n * the relay's answer to it, and for the relay's answer to `revoke()` and\n * `signOut()`.\n */\nexport const timing: {\n\treconnectDelaysMs: number[];\n\tanswerTimeoutMs: number;\n} = {\n\treconnectDelaysMs: [5_000, 10_000, 20_000, 40_000, 60_000],\n\tanswerTimeoutMs: 15_000,\n};\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\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\n/** What `connect()`, `showConnectDialog()` and `newAddress()` reject with without a relay. */\nfunction noRelay(): Promise<never> {\n\treturn Promise.reject(new TypeError(\"TabMcp: this TabMcp has no relay\"));\n}\n\n/**\n * A rejection of `newAddress()`: `addressChanged` says whether the address\n * changed (only connecting with the new one failed) or not (the old one\n * could not be taken back and is kept, with its grants).\n */\nfunction changed(error: unknown, addressChanged: boolean): unknown {\n\treturn Object.assign(Object(error), { addressChanged });\n}\n\n/** What a method that asks the relay rejects with while it cannot. */\nfunction notConnected(): Promise<never> {\n\treturn Promise.reject(\n\t\tnew DOMException(\"TabMcp: not connected\", \"InvalidStateError\"),\n\t);\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 (and, without\n * `relay`, only through `serve` and WebMCP).\n *\n * ```ts\n * const mcp = new TabMcp({ relay: \"https://relay.example\", server: { name: \"Calculator\", version: \"1.0.0\" } });\n * await 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 #alwaysAllow: boolean;\n\treadonly #ui: DialogOptions | undefined;\n\t/** `undefined` without a relay: tools only through `serve` and WebMCP. */\n\treadonly #relayUrl: string | undefined;\n\treadonly #secrets: SecretStore | undefined;\n\t/** The channel of the tabs that share the secret (DEC-095). */\n\treadonly #tabs: string | undefined;\n\t/**\n\t * The page was on when a takeover ended its session (or when a\n\t * `newAddress()` failed), and nothing was ended since: the next\n\t * `newAddress()` connects with the new address. Only that; whether it\n\t * takes the old address back does not depend on it (DEC-136).\n\t */\n\t#stayOn = false;\n\t/** The running `newAddress()`: a second call returns it, `connect()` waits for it. */\n\t#renewing: Promise<void> | undefined;\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\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\treadonly #reconnect: boolean;\n\t#reconnecting: ReconnectingInfo | undefined;\n\t#reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\t#unwatch: (() => void) | undefined;\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\townConfirm: () => !!this.#onConfirm,\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 { server, appName } = options;\n\t\tconst relay =\n\t\t\toptions.relay === undefined ? undefined : tabUrl(options.relay);\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 = relay?.url;\n\t\tthis.#server = { ...server };\n\t\tthis.#appName = appName;\n\t\tthis.#onConfirm = options.onConfirm;\n\t\tthis.#alwaysAllow = options.alwaysAllow === true;\n\t\tthis.#ui = options.ui;\n\t\tthis.#identityAssertion = options.identityAssertion;\n\t\tthis.#reconnect = options.reconnect !== false;\n\t\tif (relay !== undefined) {\n\t\t\t// One address per relay and page (server name); the default of 0.4 and\n\t\t\t// older, per relay only, is moved over once (DEC-083).\n\t\t\tconst key =\n\t\t\t\toptions.storageKey ??\n\t\t\t\t`tab-mcp:secret:${relay.origin}:${encodeURIComponent(server.name)}`;\n\t\t\tthis.#secrets = new SecretStore(\n\t\t\t\toptions.storage,\n\t\t\t\tkey,\n\t\t\t\toptions.storageKey === undefined\n\t\t\t\t\t? `tab-mcp:secret:${relay.origin}`\n\t\t\t\t\t: undefined,\n\t\t\t);\n\t\t\t// Tabs that share the secret share this channel; with `storage: null`\n\t\t\t// every tab has an address of its own (DEC-095).\n\t\t\tthis.#tabs = options.storage === null ? undefined : `${key}#tabs`;\n\t\t}\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. The getter\n\t\t// is read now (WM 10); the mirror loads only then (DEC-171).\n\t\tconst context = options.webmcp === true ? nativeContext() : undefined;\n\t\tif (context !== undefined)\n\t\t\timport(\"./webmcp.ts\").then(\n\t\t\t\t(m) =>\n\t\t\t\t\tm.mirror(this.#registry, context, (tool, input, signal) =>\n\t\t\t\t\t\tthis.#load().then((lazy) =>\n\t\t\t\t\t\t\tlazy.callFromWebMcp(this.#calls, tool, input, signal),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t// Like a failed registration: warned, the relay unaffected.\n\t\t\t\t(error: unknown) =>\n\t\t\t\t\tconsole.warn(\"tab-mcp: no tools are offered through WebMCP:\", error),\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 (the\n\t * tool is registered, or refused, before it returns); await it or catch\n\t * the rejection (DEC-010).\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: its `address` is the one to give to AI apps. */\n\tget session(): SessionInfo | undefined {\n\t\treturn this.#session;\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 `state` is `reconnecting`: the next (or running) attempt and when\n\t * 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 with the outcome, the\n\t * new `identity`: `bound` once the relay accepted it, `refused`, or `none`\n\t * when nobody is signed in or no answer came in time. Rejects with an\n\t * `InvalidStateError` while not connected, and with a `TypeError` without\n\t * the hook.\n\t */\n\trefreshIdentity(): Promise<IdentityState> {\n\t\tconst session = this.#session;\n\t\tconst ask = this.#identityAssertion;\n\t\tif (ask === undefined)\n\t\t\treturn Promise.reject(new TypeError(\"TabMcp: no identityAssertion\"));\n\t\tif (session === undefined) return notConnected();\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}, timing.answerTimeoutMs);\n\t\treturn new Promise<IdentityState>((resolve) => {\n\t\t\tconst settle = (event: TabMcpEventMap[\"identitychange\"]) => {\n\t\t\t\tconst { identity } = event.detail;\n\t\t\t\tif (identity === \"pending\") return;\n\t\t\t\tthis.removeEventListener(\"identitychange\", settle);\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(identity);\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 * `identity` goes to `none` at once. Resolves once the relay removed the\n\t * grants; rejects with an `InvalidStateError` while not connected to a\n\t * relay that pairs by sign-in (`session.pairing` is `oidc`), and with a\n\t * `NetworkError` when the session ends first. Grants that stay work only while a page signed in\n\t * as the same person is open.\n\t */\n\tsignOut(): Promise<void> {\n\t\tthis.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\treturn this.#session?.pairing === \"oidc\"\n\t\t\t? this.#ask({ type: \"identity.logout\" }, () => !this.#grants.length)\n\t\t\t: notConnected();\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`, it makes the next attempt at once.\n\t */\n\tconnect(options: ConnectOptions = {}): Promise<SessionInfo> {\n\t\tif (this.#relayUrl === undefined) return noRelay();\n\t\tif (this.#state === \"connected\" && this.#session !== undefined) {\n\t\t\treturn Promise.resolve(this.#session);\n\t\t}\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tif (this.#reconnecting !== undefined) return this.#attemptReconnect();\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\t// While `newAddress()` runs: afterwards, with the new address.\n\t\treturn this.#renewing\n\t\t\t? this.#renewing.then(() => this.connect({ resume: true }))\n\t\t\t: this.#start();\n\t}\n\n\t/** Open the page's connection; a reconnect attempt stays `reconnecting`. */\n\t#start(): Promise<SessionInfo> {\n\t\tif (!this.#reconnecting) this.#setState(\"connecting\");\n\t\tconst connecting = this.#open(this.#generation);\n\t\tthis.#connecting = connecting;\n\t\tconnecting.then(\n\t\t\t() => {\n\t\t\t\tif (this.#connecting === connecting) this.#connecting = undefined;\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (this.#connecting !== connecting) return; // superseded\n\t\t\t\tthis.#connecting = undefined;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\t// A failed attempt: the next one is scheduled, or it stops.\n\t\t\t\tif (!this.#reconnecting) this.#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\t/**\n\t * Open a connection. `takeBack`: the secret of an address to take back\n\t * (`hello.revokeAll`, DEC-095); that connection is never current, so its\n\t * session and events stay unseen, but `#end` closes it.\n\t */\n\tasync #open(generation: number, takeBack?: string): Promise<SessionInfo> {\n\t\tconst { openConnection, addressIdOf, withAddress } = await this.#load();\n\t\tconst relayUrl = this.#relayUrl;\n\t\tif (relayUrl === undefined || this.#secrets === undefined) return noRelay();\n\t\tconst secret =\n\t\t\ttakeBack ?? this.#secrets.current() ?? this.#secrets.rotate();\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(relayUrl, address),\n\t\t\tsecret,\n\t\t\t{ address, revokeAll: !!takeBack },\n\t\t);\n\t\tif (!takeBack) ref.connection = connection;\n\t\tthis.#connection = connection;\n\t\treturn connection.ready;\n\t}\n\n\t/** Whether this `TabMcp` has a relay; without one, `connect()` rejects. */\n\tget hasRelay(): boolean {\n\t\treturn this.#relayUrl !== undefined;\n\t}\n\n\t/**\n\t * Serve the tools over a port, without a relay: for this site's own\n\t * assistant, e.g. a chat in an iframe whose backend calls the tools through\n\t * `createTunnelFetch` (`@ractive-ch/tab-mcp-client/tunnel`). The port\n\t * carries the relay's `http.*` messages as plain objects; a `MessagePort`\n\t * fits. Whoever holds the other end calls the tools without pairing, as\n\t * `options.client` (`kind: \"local\"`): hand it out only to a frame whose\n\t * origin you checked. Consequential tools still ask: `options.onConfirm`\n\t * for this port's calls (in the site's chat, say), else the page's\n\t * `onConfirm` or dialog. Each request may take `options.requestTimeoutMs`\n\t * (300 s). Only tools whose `callers` include `\"local\"` (by default all)\n\t * are listed and callable. Resolves once the port\n\t * is served; may be called for several ports. Rejects with a `TypeError`\n\t * for options it cannot use.\n\t */\n\tserve(port: TunnelPort, options: ServeOptions): Promise<ServeHandle> {\n\t\treturn this.#load().then((lazy) =>\n\t\t\tlazy.servePort(\n\t\t\t\t{\n\t\t\t\t\t...this.#calls,\n\t\t\t\t\tserver: this.#server,\n\t\t\t\t\terror: (error) => this.#emit(\"error\", { error }),\n\t\t\t\t},\n\t\t\t\tport,\n\t\t\t\toptions,\n\t\t\t),\n\t\t);\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. If the page has one already, it first takes it back: it\n\t * connects with the old secret and the relay revokes every grant of it in\n\t * the same step (`hello.revokeAll`, DEC-095, DEC-136), connected or not,\n\t * taken over or not. Then it makes a new secret and connects with it if\n\t * the page was connected, connecting or reconnecting, and resolves once\n\t * that is done (the new session is `session`). Rejects, and keeps the old\n\t * secret so that a retry takes it back again, when the old address could\n\t * not be taken back (relay unreachable, taken over again first). With a\n\t * relay, every rejection has `addressChanged`: `false` then, `true` when\n\t * only connecting with the new address failed (without one: a\n\t * `TypeError`). Call it from a user action.\n\t */\n\tnewAddress(): Promise<void> {\n\t\t// Without a relay there is no secret store.\n\t\tconst secrets = this.#secrets;\n\t\tif (!secrets) return noRelay();\n\t\t// biome-ignore lint/suspicious/noAssignInExpressions: one promise per run\n\t\treturn (this.#renewing ??= this.#renew(secrets).finally(() => {\n\t\t\tthis.#renewing = undefined;\n\t\t}));\n\t}\n\n\tasync #renew(secrets: SecretStore): Promise<void> {\n\t\tconst wasOn = this.#state !== \"disconnected\" || this.#stayOn;\n\t\t// Read now, also when the page is off or was taken over (CC 4). Another\n\t\t// tab that rotated the secret since took the address it had back itself.\n\t\tconst old = secrets.current();\n\t\tthis.#end(\"new_address\");\n\t\tconst generation = this.#generation;\n\t\tif (old) {\n\t\t\tthis.#setState(\"connecting\");\n\t\t\ttry {\n\t\t\t\tawait this.#open(generation, old);\n\t\t\t} catch (error) {\n\t\t\t\tif (generation === this.#generation) {\n\t\t\t\t\tthis.#setState(\"disconnected\");\n\t\t\t\t\tthis.#stayOn = wasOn; // a retry does the same\n\t\t\t\t}\n\t\t\t\tthrow changed(error, false);\n\t\t\t} finally {\n\t\t\t\t// The take-back connection, unless `#end` closed it already.\n\t\t\t\tif (generation === this.#generation) {\n\t\t\t\t\tthis.#connection?.close(\"new_address\");\n\t\t\t\t\tthis.#connection = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsecrets.rotate();\n\t\t// The relay revoked them (CC 14).\n\t\tthis.#setGrants([]);\n\t\t// It was on: the user chose that already, as for a reconnect.\n\t\tif (wasOn)\n\t\t\tawait this.#start().catch((error: unknown) => {\n\t\t\t\tthrow changed(error, true);\n\t\t\t});\n\t\telse this.#setState(\"disconnected\");\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.#stayOn = false;\n\t\tthis.#generation++;\n\t\tconst connection = this.#connection;\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\t// With the reason also when it ended connecting or reconnecting: the\n\t\t// page turned it off (or got a new address) all the same.\n\t\tthis.#setState(\"disconnected\", reason);\n\t}\n\n\t/**\n\t * Wait, then connect again (attempt `attempt`, from 1); `state` is\n\t * `reconnecting`, and `statechange` says so for each attempt.\n\t */\n\t#scheduleReconnect(reason: DisconnectReason, attempt: number): void {\n\t\tconst delays = timing.reconnectDelaysMs;\n\t\t// Up to 20 % either way, so that the tabs a relay restart disconnected\n\t\t// do not all come back at the same moment (CC 11).\n\t\tconst delay =\n\t\t\t(delays[Math.min(attempt, delays.length) - 1] ?? 0) *\n\t\t\t(0.8 + 0.4 * Math.random());\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.#setState(\"reconnecting\", attempt > 1 ? undefined : reason);\n\t}\n\n\t/** Make the next reconnect attempt now; on failure, schedule the one after. */\n\t#attemptReconnect(): Promise<SessionInfo> {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tconst attempt = this.#start();\n\t\tattempt.catch((error: unknown) => {\n\t\t\t// Read now, not when the attempt started: a listener before this may\n\t\t\t// have ended it all or started the next attempt, which then owns the\n\t\t\t// next step (CC 10).\n\t\t\tconst info = this.#reconnecting;\n\t\t\tif (info === undefined || this.#connecting !== undefined) 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, and `error` says why, before `statechange`.\n\t\t\t// The state is `disconnected` already, so that a `connect()` from\n\t\t\t// the listener starts afresh (with the user-activation check).\n\t\t\tthis.#stopReconnecting();\n\t\t\tthis.#state = \"disconnected\";\n\t\t\tthis.#emit(\"error\", {\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t});\n\t\t\tif (this.#state === \"disconnected\")\n\t\t\t\tthis.#emit(\"statechange\", { state: \"disconnected\" });\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/** Stop reconnecting; the caller sets the state that follows. */\n\t#stopReconnecting(): void {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tthis.#unwatch?.();\n\t\tthis.#unwatch = undefined;\n\t\tthis.#reconnecting = undefined;\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. Resolves once\n\t * the relay removed the grant (at once for one that is not in `grants`,\n\t * and when the relay no longer knows it: it leaves `grants` then).\n\t * Rejects with an `InvalidStateError` while not connected (only the relay\n\t * can do it), a `NetworkError` when the session ends before the answer,\n\t * and with the relay's error when it refuses (its `code` is\n\t * `store_unavailable` when it could not save the change: try again).\n\t */\n\trevoke(grantId: string): Promise<void> {\n\t\tconst gone = () => !this.#grants.some((g) => g.grantId === grantId);\n\t\treturn gone()\n\t\t\t? Promise.resolve()\n\t\t\t: this.#ask({ type: \"grant.revoke\", grantId }, gone);\n\t}\n\n\t/**\n\t * Send `message` to the relay and resolve once `done()` holds (it is\n\t * checked on each change of the grants). Rejects with an\n\t * `InvalidStateError` when it cannot send, a `NetworkError` when the\n\t * session ends first, the relay's refusal of this message\n\t * (`store_unavailable`: it could not save the change; `unknown_id`), and a\n\t * `TimeoutError` when none of that happened within\n\t * `timing.answerTimeoutMs`.\n\t */\n\t#ask(\n\t\tmessage: TabMessage & { grantId?: string },\n\t\tdone: () => boolean,\n\t): Promise<void> {\n\t\tif (!this.#session || this.#connection?.send(message) !== true)\n\t\t\treturn notConnected();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst types = [\"grantschange\", \"statechange\", \"error\"];\n\t\t\tconst settle = (error?: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tfor (const type of types) this.removeEventListener(type, check);\n\t\t\t\tif (error) reject(error);\n\t\t\t\telse resolve();\n\t\t\t};\n\t\t\tconst check = (event?: Event) => {\n\t\t\t\tconst error = (event as Partial<TabMcpEventMap[\"error\"]>)?.detail\n\t\t\t\t\t?.error as\n\t\t\t\t\t| { code?: string; for?: string; grantId?: string }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (done()) settle();\n\t\t\t\telse if (\n\t\t\t\t\t(error?.code === \"store_unavailable\" ||\n\t\t\t\t\t\terror?.code === \"unknown_id\") &&\n\t\t\t\t\t// It names the message it answers (relay 0.10.2); an older\n\t\t\t\t\t// relay's answers every pending one (DEC-168).\n\t\t\t\t\t(error.for === undefined ||\n\t\t\t\t\t\t(error.for === message.type && error.grantId === message.grantId))\n\t\t\t\t)\n\t\t\t\t\tsettle(error);\n\t\t\t\telse if (this.#state !== \"connected\")\n\t\t\t\t\t// Sent, but the answer cannot come: it may or may not have\n\t\t\t\t\t// happened.\n\t\t\t\t\tsettle(\n\t\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\t\"TabMcp: the session ended before the relay answered\",\n\t\t\t\t\t\t\t\"NetworkError\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t};\n\t\t\tconst timer = setTimeout(\n\t\t\t\t() =>\n\t\t\t\t\tsettle(\n\t\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\t\"TabMcp: the relay did not answer\",\n\t\t\t\t\t\t\t\"TimeoutError\",\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\ttiming.answerTimeoutMs,\n\t\t\t);\n\t\t\tfor (const type of types) this.addEventListener(type, check);\n\t\t\tcheck();\n\t\t});\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\tif (this.#relayUrl === undefined) return noRelay();\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(\"./connect.ts\");\n\t\tawait showConnectDialog(this, connecting, doc, this.#server.name, this.#ui);\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/** A new state; `reconnecting` again means the next attempt was scheduled. */\n\t#setState(state: ConnectionState, reason?: DisconnectReason): void {\n\t\tif (this.#state === state && state !== \"reconnecting\") return;\n\t\tthis.#state = state;\n\t\tthis.#emit(\"statechange\", reason ? { state, reason } : { state });\n\t}\n\n\t#setIdentity(identity: IdentityState, message?: string): void {\n\t\tif (this.#identity === identity && message === undefined) return;\n\t\tthis.#identity = identity;\n\t\tthis.#identityMessage = identity === \"refused\" ? message : undefined;\n\t\tthis.#emit(\"identitychange\", {\n\t\t\tidentity,\n\t\t\tidentityMessage: this.#identityMessage,\n\t\t});\n\t}\n\n\t#setPairingCode(pairingCode: PairingCode | undefined): void {\n\t\tif (this.#pairingCode === undefined && pairingCode === undefined) return;\n\t\tthis.#pairingCode = pairingCode;\n\t\tthis.#emit(\"pairingcode\", { pairingCode });\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 Allow until reload with `alwaysAllow: true` (what runs\n\t * without `onConfirm`), in `options.document` (default: the global one).\n\t * An `onConfirm` may hand some calls to it. Resolves `false` where there\n\t * is no document.\n\t */\n\tconfirmInPage(\n\t\trequest: ConfirmRequest,\n\t\toptions: { document?: Document } = {},\n\t): Promise<boolean> {\n\t\tconst doc = options.document ?? globalThis.document;\n\t\tif (doc === undefined) return Promise.resolve(false); // nobody to ask: decline\n\t\t// The tools allowed until reload live in the dialogs' chunks too: only they add them.\n\t\treturn import(\"./confirm.ts\").then((ui) =>\n\t\t\tui.confirmInPage(this, request, doc, {\n\t\t\t\talwaysAllow: this.#alwaysAllow,\n\t\t\t\tui: this.#ui,\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.#stayOn = false;\n\t\t\t\tthis.#stopReconnecting();\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.#setState(\"connected\");\n\t\t\t\tif (session.pairing === \"oidc\" && this.#identityAssertion)\n\t\t\t\t\tvoid 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) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tif (reason === \"replaced\") this.#stayOn = replacedHere = true;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\tthis.#session = undefined;\n\t\t\t\t// Any listener of these may end it all (`disconnect()`,\n\t\t\t\t// `newAddress()`): that bumps the generation.\n\t\t\t\tconst generation = this.#generation;\n\t\t\t\tthis.#setPairingCode(undefined);\n\t\t\t\tthis.#identityRound++;\n\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\tif (generation !== this.#generation) return;\n\t\t\t\t// Reconnecting is decided before the page hears of it, so its\n\t\t\t\t// listener sees `reconnecting` (or calls `connect()`, which then\n\t\t\t\t// makes the first attempt at once).\n\t\t\t\tif (this.#reconnect && RECONNECT_REASONS.has(reason))\n\t\t\t\t\tthis.#scheduleReconnect(reason, 1);\n\t\t\t\telse this.#setState(\"disconnected\", reason);\n\t\t\t},\n\t\t};\n\t}\n}\n"
8
+ "/**\n * `TabMcp`: the eagerly loaded core (DEC-035). It holds the tool registry, the\n * events, the pairing state and the address secret; `connect()` loads the\n * connection and the MCP handler with a dynamic `import()`.\n */\n\nimport type { CallHost, ConnectionHandle, ConnectionHost } from \"./internal.ts\";\nimport type { GrantRef, SessionMessage, TabMessage } 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\tDialogOptions,\n\tDisconnectReason,\n\tGrant,\n\tIdentityAssertionHandler,\n\tIdentityState,\n\tPairingCode,\n\tReconnectingInfo,\n\tRegisterToolOptions,\n\tRelayClient,\n\tServeHandle,\n\tServeOptions,\n\tServerInfo,\n\tSessionInfo,\n\tTabMcpEventMap,\n\tTabMcpOptions,\n\tTool,\n\tToolCallClient,\n\tTunnelPort,\n} from \"./types.ts\";\nimport { LIBRARY_NAME, VERSION } from \"./version.ts\";\nimport type { ModelContext } from \"./webmcp.ts\";\n\n/**\n * The browser's own `ModelContext` of this document, read when a `TabMcp` is\n * made, through `Document.prototype`'s getter: never an own\n * `document.modelContext` (a polyfill such as `@mcp-b/global`, or any page\n * script; DEC-115). `undefined` without native WebMCP or a document. In the\n * core; the mirror itself is a chunk of its own (DEC-171).\n */\nfunction nativeContext(): ModelContext | undefined {\n\ttry {\n\t\treturn Object.getOwnPropertyDescriptor(\n\t\t\tDocument.prototype,\n\t\t\t\"modelContext\",\n\t\t)?.get?.call(document);\n\t} catch {\n\t\treturn undefined; // no document\n\t}\n}\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/**\n * The library's waits, in milliseconds: constants for pages (CU 17), which\n * only tests change. `reconnectDelaysMs`: before each reconnect attempt,\n * the last one repeating. `answerTimeoutMs`: for an identity assertion and\n * the relay's answer to it, and for the relay's answer to `revoke()` and\n * `signOut()`.\n */\nexport const timing: {\n\treconnectDelaysMs: number[];\n\tanswerTimeoutMs: number;\n} = {\n\treconnectDelaysMs: [5_000, 10_000, 20_000, 40_000, 60_000],\n\tanswerTimeoutMs: 15_000,\n};\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\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/** An app id as the relay takes it (DEC-196). */\nconst APP_ID = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;\n\n/**\n * The app id a server name gives: lower case, letters without their marks,\n * each run of anything but a-z and 0-9 as one `-`, none at either end, at\n * most 32 characters; `\"\"` when nothing is left.\n */\nexport function appIdOf(name: string): string {\n\treturn name\n\t\t.normalize(\"NFKD\")\n\t\t.replace(/\\p{M}/gu, \"\")\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\")\n\t\t.slice(0, 32)\n\t\t.replace(/-$/, \"\");\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\n/** What `connect()`, `showConnectDialog()` and `newAddress()` reject with without a relay. */\nfunction noRelay(): Promise<never> {\n\treturn Promise.reject(new TypeError(\"TabMcp: this TabMcp has no relay\"));\n}\n\n/**\n * A rejection of `newAddress()`: `addressChanged` says whether the address\n * changed (only connecting with the new one failed) or not (the old one\n * could not be taken back and is kept, with its grants).\n */\nfunction changed(error: unknown, addressChanged: boolean): unknown {\n\treturn Object.assign(Object(error), { addressChanged });\n}\n\n/** What a method that asks the relay rejects with while it cannot. */\nfunction notConnected(): Promise<never> {\n\treturn Promise.reject(\n\t\tnew DOMException(\"TabMcp: not connected\", \"InvalidStateError\"),\n\t);\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 (and, without\n * `relay`, only through `serve` and WebMCP).\n *\n * ```ts\n * const mcp = new TabMcp({ relay: \"https://relay.example\", server: { name: \"Calculator\", version: \"1.0.0\" } });\n * await 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 #app: string;\n\treadonly #appName: string | undefined;\n\treadonly #onConfirm: ConfirmHandler | undefined;\n\treadonly #alwaysAllow: boolean;\n\treadonly #ui: DialogOptions | undefined;\n\t/** `undefined` without a relay: tools only through `serve` and WebMCP. */\n\treadonly #relayUrl: string | undefined;\n\treadonly #secrets: SecretStore | undefined;\n\t/** The channel of the tabs that share the secret (DEC-095). */\n\treadonly #tabs: string | undefined;\n\t/**\n\t * The page was on when a takeover ended its session (or when a\n\t * `newAddress()` failed), and nothing was ended since: the next\n\t * `newAddress()` connects with the new address. Only that; whether it\n\t * takes the old address back does not depend on it (DEC-136).\n\t */\n\t#stayOn = false;\n\t/** The running `newAddress()`: a second call returns it, `connect()` waits for it. */\n\t#renewing: Promise<void> | undefined;\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\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\treadonly #reconnect: boolean;\n\t#reconnecting: ReconnectingInfo | undefined;\n\t#reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\t#unwatch: (() => void) | undefined;\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\townConfirm: () => !!this.#onConfirm,\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 { server, appName } = options;\n\t\tconst relay =\n\t\t\toptions.relay === undefined ? undefined : tabUrl(options.relay);\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\tconst app = options.app ?? appIdOf(server.name);\n\t\tif (\n\t\t\toptions.app !== undefined\n\t\t\t\t? typeof app !== \"string\" || !APP_ID.test(app)\n\t\t\t\t: relay && app === \"\"\n\t\t) {\n\t\t\tthrow new TypeError(\n\t\t\t\toptions.app !== undefined\n\t\t\t\t\t? \"TabMcp: app must be 1-32 characters of a-z, 0-9 and -, not starting or ending with -\"\n\t\t\t\t\t: \"TabMcp: server.name has no letter a-z and no digit to make the address of: set app\",\n\t\t\t);\n\t\t}\n\t\tthis.#app = app;\n\t\tthis.#relayUrl = relay?.url;\n\t\tthis.#server = { ...server };\n\t\tthis.#appName = appName;\n\t\tthis.#onConfirm = options.onConfirm;\n\t\tthis.#alwaysAllow = options.alwaysAllow === true;\n\t\tthis.#ui = options.ui;\n\t\tthis.#identityAssertion = options.identityAssertion;\n\t\tthis.#reconnect = options.reconnect !== false;\n\t\tif (relay !== undefined) {\n\t\t\t// One address per relay and page (server name, DEC-083).\n\t\t\tconst key =\n\t\t\t\toptions.storageKey ??\n\t\t\t\t`tab-mcp:secret:${relay.origin}:${encodeURIComponent(server.name)}`;\n\t\t\tthis.#secrets = new SecretStore(options.storage, key);\n\t\t\t// Tabs that share the secret share this channel; with `storage: null`\n\t\t\t// every tab has an address of its own (DEC-095).\n\t\t\tthis.#tabs = options.storage === null ? undefined : `${key}#tabs`;\n\t\t}\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. The getter\n\t\t// is read now (WM 10); the mirror loads only then (DEC-171).\n\t\tconst context = options.webmcp === true ? nativeContext() : undefined;\n\t\tif (context !== undefined)\n\t\t\timport(\"./webmcp.ts\").then(\n\t\t\t\t(m) =>\n\t\t\t\t\tm.mirror(this.#registry, context, (tool, input, signal) =>\n\t\t\t\t\t\tthis.#load().then((lazy) =>\n\t\t\t\t\t\t\tlazy.callFromWebMcp(this.#calls, tool, input, signal),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t// Like a failed registration: warned, the relay unaffected.\n\t\t\t\t(error: unknown) =>\n\t\t\t\t\tconsole.warn(\"tab-mcp: no tools are offered through WebMCP:\", error),\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 (the\n\t * tool is registered, or refused, before it returns); await it or catch\n\t * the rejection (DEC-010).\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: its `address` is the one to give to AI apps. */\n\tget session(): SessionInfo | undefined {\n\t\treturn this.#session;\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 `state` is `reconnecting`: the next (or running) attempt and when\n\t * 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 with the outcome, the\n\t * new `identity`: `bound` once the relay accepted it, `refused`, or `none`\n\t * when nobody is signed in or no answer came in time. Rejects with an\n\t * `InvalidStateError` while not connected, and with a `TypeError` without\n\t * the hook.\n\t */\n\trefreshIdentity(): Promise<IdentityState> {\n\t\tconst session = this.#session;\n\t\tconst ask = this.#identityAssertion;\n\t\tif (ask === undefined)\n\t\t\treturn Promise.reject(new TypeError(\"TabMcp: no identityAssertion\"));\n\t\tif (session === undefined) return notConnected();\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}, timing.answerTimeoutMs);\n\t\treturn new Promise<IdentityState>((resolve) => {\n\t\t\tconst settle = (event: TabMcpEventMap[\"identitychange\"]) => {\n\t\t\t\tconst { identity } = event.detail;\n\t\t\t\tif (identity === \"pending\") return;\n\t\t\t\tthis.removeEventListener(\"identitychange\", settle);\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(identity);\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 * `identity` goes to `none` at once. Resolves once the relay removed the\n\t * grants; rejects with an `InvalidStateError` while not connected to a\n\t * relay that pairs by sign-in (`session.pairing` is `oidc`), and with a\n\t * `NetworkError` when the session ends first. Grants that stay work only while a page signed in\n\t * as the same person is open.\n\t */\n\tsignOut(): Promise<void> {\n\t\tthis.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\treturn this.#session?.pairing === \"oidc\"\n\t\t\t? this.#ask({ type: \"identity.logout\" }, () => !this.#grants.length)\n\t\t\t: notConnected();\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`, it makes the next attempt at once.\n\t */\n\tconnect(options: ConnectOptions = {}): Promise<SessionInfo> {\n\t\tif (this.#relayUrl === undefined) return noRelay();\n\t\tif (this.#state === \"connected\" && this.#session !== undefined) {\n\t\t\treturn Promise.resolve(this.#session);\n\t\t}\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tif (this.#reconnecting !== undefined) return this.#attemptReconnect();\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\t// While `newAddress()` runs: afterwards, with the new address.\n\t\treturn this.#renewing\n\t\t\t? this.#renewing.then(() => this.connect({ resume: true }))\n\t\t\t: this.#start();\n\t}\n\n\t/** Open the page's connection; a reconnect attempt stays `reconnecting`. */\n\t#start(): Promise<SessionInfo> {\n\t\tif (!this.#reconnecting) this.#setState(\"connecting\");\n\t\tconst connecting = this.#open(this.#generation);\n\t\tthis.#connecting = connecting;\n\t\tconnecting.then(\n\t\t\t() => {\n\t\t\t\tif (this.#connecting === connecting) this.#connecting = undefined;\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (this.#connecting !== connecting) return; // superseded\n\t\t\t\tthis.#connecting = undefined;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\t// A failed attempt: the next one is scheduled, or it stops.\n\t\t\t\tif (!this.#reconnecting) this.#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\t/**\n\t * Open a connection. `takeBack`: the secret of an address to take back\n\t * (`hello.revokeAll`, DEC-095); that connection is never current, so its\n\t * session and events stay unseen, but `#end` closes it.\n\t */\n\tasync #open(generation: number, takeBack?: string): Promise<SessionInfo> {\n\t\tconst { openConnection, addressIdOf } = await this.#load();\n\t\tconst relayUrl = this.#relayUrl;\n\t\tif (relayUrl === undefined || this.#secrets === undefined) return noRelay();\n\t\tconst secret =\n\t\t\ttakeBack ?? this.#secrets.current() ?? this.#secrets.rotate();\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(this.#host(ref), relayUrl, secret, {\n\t\t\taddress,\n\t\t\trevokeAll: !!takeBack,\n\t\t});\n\t\tif (!takeBack) ref.connection = connection;\n\t\tthis.#connection = connection;\n\t\treturn connection.ready;\n\t}\n\n\t/** Whether this `TabMcp` has a relay; without one, `connect()` rejects. */\n\tget hasRelay(): boolean {\n\t\treturn this.#relayUrl !== undefined;\n\t}\n\n\t/**\n\t * Serve the tools over a port, without a relay: for this site's own\n\t * assistant, e.g. a chat in an iframe whose backend calls the tools through\n\t * `createTunnelFetch` (`@ractive-ch/tab-mcp-client/tunnel`). The port\n\t * carries the relay's `http.*` messages as plain objects; a `MessagePort`\n\t * fits. Whoever holds the other end calls the tools without pairing, as\n\t * `options.client` (`kind: \"local\"`): hand it out only to a frame whose\n\t * origin you checked. Consequential tools still ask: `options.onConfirm`\n\t * for this port's calls (in the site's chat, say), else the page's\n\t * `onConfirm` or dialog. Each request may take `options.requestTimeoutMs`\n\t * (300 s). Only tools whose `callers` include `\"local\"` (by default all)\n\t * are listed and callable. Resolves once the port\n\t * is served; may be called for several ports. Rejects with a `TypeError`\n\t * for options it cannot use.\n\t */\n\tserve(port: TunnelPort, options: ServeOptions): Promise<ServeHandle> {\n\t\treturn this.#load().then((lazy) =>\n\t\t\tlazy.servePort(\n\t\t\t\t{\n\t\t\t\t\t...this.#calls,\n\t\t\t\t\tserver: this.#server,\n\t\t\t\t\terror: (error) => this.#emit(\"error\", { error }),\n\t\t\t\t},\n\t\t\t\tport,\n\t\t\t\toptions,\n\t\t\t),\n\t\t);\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 * Disconnect every AI app and start over with a new secret. The address\n\t * people add to an AI app names the app and stays the same (DEC-196);\n\t * what changes is the page behind it, so every AI app has to pair again.\n\t * If the page has a secret already, it first takes its address back: it\n\t * connects with the old secret and the relay revokes every grant of it in\n\t * the same step (`hello.revokeAll`, DEC-095, DEC-136), connected or not,\n\t * taken over or not. Then it makes a new secret and connects with it if\n\t * the page was connected, connecting or reconnecting, and resolves once\n\t * that is done (the new session is `session`). Rejects, and keeps the old\n\t * secret so that a retry takes it back again, when the old address could\n\t * not be taken back (relay unreachable, taken over again first). With a\n\t * relay, every rejection has `addressChanged`: `false` then, `true` when\n\t * only connecting with the new address failed (without one: a\n\t * `TypeError`). Call it from a user action.\n\t */\n\tnewAddress(): Promise<void> {\n\t\t// Without a relay there is no secret store.\n\t\tconst secrets = this.#secrets;\n\t\tif (!secrets) return noRelay();\n\t\t// biome-ignore lint/suspicious/noAssignInExpressions: one promise per run\n\t\treturn (this.#renewing ??= this.#renew(secrets).finally(() => {\n\t\t\tthis.#renewing = undefined;\n\t\t}));\n\t}\n\n\tasync #renew(secrets: SecretStore): Promise<void> {\n\t\tconst wasOn = this.#state !== \"disconnected\" || this.#stayOn;\n\t\t// Read now, also when the page is off or was taken over (CC 4). Another\n\t\t// tab that rotated the secret since took the address it had back itself.\n\t\tconst old = secrets.current();\n\t\tthis.#end(\"new_address\");\n\t\tconst generation = this.#generation;\n\t\tif (old) {\n\t\t\tthis.#setState(\"connecting\");\n\t\t\ttry {\n\t\t\t\tawait this.#open(generation, old);\n\t\t\t} catch (error) {\n\t\t\t\tif (generation === this.#generation) {\n\t\t\t\t\tthis.#setState(\"disconnected\");\n\t\t\t\t\tthis.#stayOn = wasOn; // a retry does the same\n\t\t\t\t}\n\t\t\t\tthrow changed(error, false);\n\t\t\t} finally {\n\t\t\t\t// The take-back connection, unless `#end` closed it already.\n\t\t\t\tif (generation === this.#generation) {\n\t\t\t\t\tthis.#connection?.close(\"new_address\");\n\t\t\t\t\tthis.#connection = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsecrets.rotate();\n\t\t// The relay revoked them (CC 14).\n\t\tthis.#setGrants([]);\n\t\t// It was on: the user chose that already, as for a reconnect.\n\t\tif (wasOn)\n\t\t\tawait this.#start().catch((error: unknown) => {\n\t\t\t\tthrow changed(error, true);\n\t\t\t});\n\t\telse this.#setState(\"disconnected\");\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.#stayOn = false;\n\t\tthis.#generation++;\n\t\tconst connection = this.#connection;\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\t// With the reason also when it ended connecting or reconnecting: the\n\t\t// page turned it off (or got a new address) all the same.\n\t\tthis.#setState(\"disconnected\", reason);\n\t}\n\n\t/**\n\t * Wait, then connect again (attempt `attempt`, from 1); `state` is\n\t * `reconnecting`, and `statechange` says so for each attempt.\n\t */\n\t#scheduleReconnect(reason: DisconnectReason, attempt: number): void {\n\t\tconst delays = timing.reconnectDelaysMs;\n\t\t// Up to 20 % either way, so that the tabs a relay restart disconnected\n\t\t// do not all come back at the same moment (CC 11).\n\t\tconst delay =\n\t\t\t(delays[Math.min(attempt, delays.length) - 1] ?? 0) *\n\t\t\t(0.8 + 0.4 * Math.random());\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.#setState(\"reconnecting\", attempt > 1 ? undefined : reason);\n\t}\n\n\t/** Make the next reconnect attempt now; on failure, schedule the one after. */\n\t#attemptReconnect(): Promise<SessionInfo> {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tconst attempt = this.#start();\n\t\tattempt.catch((error: unknown) => {\n\t\t\t// Read now, not when the attempt started: a listener before this may\n\t\t\t// have ended it all or started the next attempt, which then owns the\n\t\t\t// next step (CC 10).\n\t\t\tconst info = this.#reconnecting;\n\t\t\tif (info === undefined || this.#connecting !== undefined) 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, and `error` says why, before `statechange`.\n\t\t\t// The state is `disconnected` already, so that a `connect()` from\n\t\t\t// the listener starts afresh (with the user-activation check).\n\t\t\tthis.#stopReconnecting();\n\t\t\tthis.#state = \"disconnected\";\n\t\t\tthis.#emit(\"error\", {\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t});\n\t\t\tif (this.#state === \"disconnected\")\n\t\t\t\tthis.#emit(\"statechange\", { state: \"disconnected\" });\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/** Stop reconnecting; the caller sets the state that follows. */\n\t#stopReconnecting(): void {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tthis.#unwatch?.();\n\t\tthis.#unwatch = undefined;\n\t\tthis.#reconnecting = undefined;\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. Resolves once\n\t * the relay removed the grant (at once for one that is not in `grants`,\n\t * and when the relay no longer knows it: it leaves `grants` then).\n\t * Rejects with an `InvalidStateError` while not connected (only the relay\n\t * can do it), a `NetworkError` when the session ends before the answer,\n\t * and with the relay's error when it refuses (its `code` is\n\t * `store_unavailable` when it could not save the change: try again).\n\t */\n\trevoke(grantId: string): Promise<void> {\n\t\tconst gone = () => !this.#grants.some((g) => g.grantId === grantId);\n\t\treturn gone()\n\t\t\t? Promise.resolve()\n\t\t\t: this.#ask({ type: \"grant.revoke\", grantId }, gone);\n\t}\n\n\t/**\n\t * Send `message` to the relay and resolve once `done()` holds (it is\n\t * checked on each change of the grants). Rejects with an\n\t * `InvalidStateError` when it cannot send, a `NetworkError` when the\n\t * session ends first, the relay's refusal of this message\n\t * (`store_unavailable`: it could not save the change; `unknown_id`), and a\n\t * `TimeoutError` when none of that happened within\n\t * `timing.answerTimeoutMs`.\n\t */\n\t#ask(\n\t\tmessage: TabMessage & { grantId?: string },\n\t\tdone: () => boolean,\n\t): Promise<void> {\n\t\tif (!this.#session || this.#connection?.send(message) !== true)\n\t\t\treturn notConnected();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst types = [\"grantschange\", \"statechange\", \"error\"];\n\t\t\tconst settle = (error?: unknown) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tfor (const type of types) this.removeEventListener(type, check);\n\t\t\t\tif (error) reject(error);\n\t\t\t\telse resolve();\n\t\t\t};\n\t\t\tconst check = (event?: Event) => {\n\t\t\t\tconst error = (event as Partial<TabMcpEventMap[\"error\"]>)?.detail\n\t\t\t\t\t?.error as\n\t\t\t\t\t| { code?: string; for?: string; grantId?: string }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (done()) settle();\n\t\t\t\telse if (\n\t\t\t\t\t(error?.code === \"store_unavailable\" ||\n\t\t\t\t\t\terror?.code === \"unknown_id\") &&\n\t\t\t\t\t// It names the message it answers (relay 0.10.2); an older\n\t\t\t\t\t// relay's answers every pending one (DEC-168).\n\t\t\t\t\t(error.for === undefined ||\n\t\t\t\t\t\t(error.for === message.type && error.grantId === message.grantId))\n\t\t\t\t)\n\t\t\t\t\tsettle(error);\n\t\t\t\telse if (this.#state !== \"connected\")\n\t\t\t\t\t// Sent, but the answer cannot come: it may or may not have\n\t\t\t\t\t// happened.\n\t\t\t\t\tsettle(\n\t\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\t\"TabMcp: the session ended before the relay answered\",\n\t\t\t\t\t\t\t\"NetworkError\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t};\n\t\t\tconst timer = setTimeout(\n\t\t\t\t() =>\n\t\t\t\t\tsettle(\n\t\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\t\"TabMcp: the relay did not answer\",\n\t\t\t\t\t\t\t\"TimeoutError\",\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\ttiming.answerTimeoutMs,\n\t\t\t);\n\t\t\tfor (const type of types) this.addEventListener(type, check);\n\t\t\tcheck();\n\t\t});\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\tif (this.#relayUrl === undefined) return noRelay();\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(\"./connect.ts\");\n\t\tawait showConnectDialog(this, connecting, doc, this.#server.name, this.#ui);\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/** A new state; `reconnecting` again means the next attempt was scheduled. */\n\t#setState(state: ConnectionState, reason?: DisconnectReason): void {\n\t\tif (this.#state === state && state !== \"reconnecting\") return;\n\t\tthis.#state = state;\n\t\tthis.#emit(\"statechange\", reason ? { state, reason } : { state });\n\t}\n\n\t#setIdentity(identity: IdentityState, message?: string): void {\n\t\tif (this.#identity === identity && message === undefined) return;\n\t\tthis.#identity = identity;\n\t\tthis.#identityMessage = identity === \"refused\" ? message : undefined;\n\t\tthis.#emit(\"identitychange\", {\n\t\t\tidentity,\n\t\t\tidentityMessage: this.#identityMessage,\n\t\t});\n\t}\n\n\t#setPairingCode(pairingCode: PairingCode | undefined): void {\n\t\tif (this.#pairingCode === undefined && pairingCode === undefined) return;\n\t\tthis.#pairingCode = pairingCode;\n\t\tthis.#emit(\"pairingcode\", { pairingCode });\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 Allow until reload with `alwaysAllow: true` (what runs\n\t * without `onConfirm`), in `options.document` (default: the global one).\n\t * An `onConfirm` may hand some calls to it. Resolves `false` where there\n\t * is no document.\n\t */\n\tconfirmInPage(\n\t\trequest: ConfirmRequest,\n\t\toptions: { document?: Document } = {},\n\t): Promise<boolean> {\n\t\tconst doc = options.document ?? globalThis.document;\n\t\tif (doc === undefined) return Promise.resolve(false); // nobody to ask: decline\n\t\t// The tools allowed until reload live in the dialogs' chunks too: only they add them.\n\t\treturn import(\"./confirm.ts\").then((ui) =>\n\t\t\tui.confirmInPage(this, request, doc, {\n\t\t\t\talwaysAllow: this.#alwaysAllow,\n\t\t\t\tui: this.#ui,\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\tapp: this.#app,\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.#stayOn = false;\n\t\t\t\tthis.#stopReconnecting();\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.#setState(\"connected\");\n\t\t\t\tif (session.pairing === \"oidc\" && this.#identityAssertion)\n\t\t\t\t\tvoid 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) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tif (reason === \"replaced\") this.#stayOn = replacedHere = true;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\tthis.#session = undefined;\n\t\t\t\t// Any listener of these may end it all (`disconnect()`,\n\t\t\t\t// `newAddress()`): that bumps the generation.\n\t\t\t\tconst generation = this.#generation;\n\t\t\t\tthis.#setPairingCode(undefined);\n\t\t\t\tthis.#identityRound++;\n\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\tif (generation !== this.#generation) return;\n\t\t\t\t// Reconnecting is decided before the page hears of it, so its\n\t\t\t\t// listener sees `reconnecting` (or calls `connect()`, which then\n\t\t\t\t// makes the first attempt at once).\n\t\t\t\tif (this.#reconnect && RECONNECT_REASONS.has(reason))\n\t\t\t\t\tthis.#scheduleReconnect(reason, 1);\n\t\t\t\telse this.#setState(\"disconnected\", reason);\n\t\t\t},\n\t\t};\n\t}\n}\n"
9
9
  ],
10
- "mappings": ";AAaA,IAAM,EAAO,0BAoBb,SAAS,CAAa,CAAC,EAA0C,CAChE,OAAO,OAAO,IAAM,UAAY,IAAM,MAAQ,CAAC,MAAM,QAAQ,CAAC,EAI/D,IAAM,EAAO,kCAEP,EACL,uEAQD,SAAS,CAAU,CAClB,EACA,EACA,EAAQ,EACR,EAAM,GACC,CACP,GAAI,EAAQ,IAAM,OAAO,IAAS,UAAY,IAAS,KAAM,OAE7D,GADA,IAAQ,MAAM,QAAQ,CAAI,EACtB,CAAC,EAAK,EAAM,CAA+B,EAC/C,QAAY,EAAK,KAAU,OAAO,QAAQ,CAAI,EAC7C,GAAI,GAAO,CAAC,EAAK,KAAK,CAAG,EACxB,EAAW,EAAO,EAAO,EAAQ,EAAG,CAAC,GAAO,EAAM,KAAK,CAAG,CAAC,EAI9D,SAAS,CAAc,CAAC,EAAe,EAA0B,CAChE,IAAI,EAAgB,EACpB,QAAW,KAAO,EAAQ,MAAM,GAAG,EAAE,MAAM,CAAC,EAAG,CAC9C,IAAI,EACJ,GAAI,CACH,EAAM,mBAAmB,CAAG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E,OAAM,CAAC,GAE7C,OAAQ,CAAC,IAA6B,CACrC,GAAI,CAAC,EAAQ,EAAG,OAChB,GAAI,IAAW,WAAY,KAAK,GAAU,EAAe,GACzD,KAAK,GAAc,OACnB,KAAK,GAAW,OAGhB,IAAM,EAAa,KAAK,GAIxB,GAHA,KAAK,GAAgB,MAAS,EAC9B,KAAK,KACL,KAAK,GAAa,MAAM,EACpB,IAAe,KAAK,GAAa,OAIrC,GAAI,KAAK,IAAc,EAAkB,IAAI,CAAM,EAClD,KAAK,GAAmB,EAAQ,CAAC,EAClC,KAAK,KAAK,GAAU,eAAgB,CAAM,EAE5C,EAEF",
11
+ "debugId": "854CB25207A5CCB264756E2164756E21",
12
12
  "names": []
13
13
  }
@@ -8,7 +8,7 @@ import {
8
8
  visible,
9
9
  clientLabel,
10
10
  newDialog
11
- } from "./index-jnz7w9xa.js";
11
+ } from "./index-qw8qy5ed.js";
12
12
  import"./index-dmh5vm5m.js";
13
13
 
14
14
  // src/confirm.ts
@@ -260,4 +260,4 @@ export {
260
260
  };
261
261
 
262
262
  //# debugId=75D3F22D19548B9A64756E2164756E21
263
- //# sourceMappingURL=confirm-fgnjgd08.js.map
263
+ //# sourceMappingURL=confirm-vj2zbq4w.js.map
@@ -11,7 +11,7 @@ import {
11
11
  listOf,
12
12
  newDialog,
13
13
  copyButton
14
- } from "./index-jnz7w9xa.js";
14
+ } from "./index-qw8qy5ed.js";
15
15
  import"./index-dmh5vm5m.js";
16
16
  import {
17
17
  SETUP_GUIDE2,
@@ -481,4 +481,4 @@ export {
481
481
  };
482
482
 
483
483
  //# debugId=7DE523796225AEC064756E2164756E21
484
- //# sourceMappingURL=connect-8jpb0k29.js.map
484
+ //# sourceMappingURL=connect-9pefy0xe.js.map
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/connect.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * The \"Connect your AI app\" dialog (DEC-028) and the notice that the page\n * lost its address, loaded on demand when a page opens the dialog.\n */\n\nimport { allowedFor } from \"./always-allowed.ts\";\nimport {\n\tbutton,\n\tclientLabel,\n\tcopyButton,\n\tel,\n\tfill,\n\tformat,\n\tlistOf,\n\tnewDialog,\n\tnextId,\n\tstringsOf,\n\tvisible,\n} from \"./dialog.ts\";\nimport { SETUP_GUIDE, setupInstructions } from \"./setup.ts\";\nimport type { DialogStrings } from \"./strings.ts\";\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type {\n\tDialogOptions,\n\tDisconnectReason,\n\tGrant,\n\tPairingCode,\n\tSessionInfo,\n\tStateChangeDetail,\n} from \"./types.ts\";\n\n/**\n * The labels of the apps behind these grants, each once: an app can hold\n * more than one grant (paired twice), and is still one app.\n */\nfunction appLabels(grants: readonly Grant[], s: DialogStrings): string[] {\n\treturn [...new Set(grants.map((g) => clientLabel(g.client, s)))];\n}\n\n/**\n * Why connecting failed, in the user's words (CU 4). The error itself, with\n * the relay's wording, goes to the console. Without a `reason` it never\n * started (no user action, cancelled): just not connected.\n */\nfunction connectFailure(error: unknown, s: DialogStrings): string {\n\tconsole.warn(\"tab-mcp: could not connect.\", error);\n\tconst reason = (error as { reason?: DisconnectReason } | null)?.reason;\n\tif (reason === undefined) return s.notConnected;\n\tif (reason === \"network\") return s.unreachable;\n\tif (reason === \"rate_limited\") return s.rateLimited;\n\treturn s.refused;\n}\n\n/** Why the page was disconnected, in the user's words (CU 4). */\nfunction disconnectedText(reason: DisconnectReason, s: DialogStrings): string {\n\tswitch (reason) {\n\t\tcase \"expired\":\n\t\tcase \"idle\":\n\t\t\treturn s.ended;\n\t\tcase \"user\":\n\t\t\treturn s.disconnected;\n\t\tcase \"network\":\n\t\tcase \"heartbeat\":\n\t\tcase \"shutdown\":\n\t\t\treturn s.lost;\n\t\tcase \"rate_limited\":\n\t\t\treturn s.rateLimited;\n\t\tdefault:\n\t\t\treturn s.closed;\n\t}\n}\n\n/**\n * With identity binding: what stands between the user and the address until\n * the relay knows who is signed in (CU 7). `undefined` once it does.\n */\nfunction signInText(mcp: TabMcp, s: DialogStrings): string | undefined {\n\tswitch (mcp.identity) {\n\t\tcase \"bound\":\n\t\t\treturn undefined;\n\t\tcase \"pending\":\n\t\t\treturn s.checkingSignIn;\n\t\tcase \"refused\":\n\t\t\treturn mcp.identityMessage\n\t\t\t\t? format(s.signInRefusedWhy, { reason: mcp.identityMessage })\n\t\t\t\t: s.signInRefused;\n\t\tdefault:\n\t\t\treturn s.signInFirst;\n\t}\n}\n\n/** The document and texts of the connect dialog per `TabMcp`, once it was opened. */\nconst watched = new WeakMap<TabMcp, { doc: Document; ui?: DialogOptions }>();\n\n/**\n * Once a page has opened the connect dialog, the default UI also says when\n * the page loses its address (`replaced`), in that dialog's document.\n */\nfunction watchReplaced(mcp: TabMcp, doc: Document, ui?: DialogOptions): void {\n\tconst known = watched.has(mcp);\n\twatched.set(mcp, ui === undefined ? { doc } : { doc, ui });\n\tif (known) return;\n\tmcp.addEventListener(\"replaced\", (event) => {\n\t\tconst current = watched.get(mcp);\n\t\t// Not when the page already went on (a New address or connect since).\n\t\tif (current !== undefined && mcp.state === \"disconnected\")\n\t\t\treplacedNotice(mcp, current.doc, event.detail.sibling, current.ui);\n\t});\n}\n\n/**\n * Says that the page lost its address (`replaced`, DEC-095). A sibling tab\n * that announced it: \"Opened in another tab\", nothing to do. Otherwise a\n * warning that another tab or program took over, with \"New address\", which\n * takes the address back, disconnects its apps, connects with a new one and\n * opens the connect dialog to add it to the AI apps again.\n */\nexport function replacedNotice(\n\tmcp: TabMcp,\n\tdoc: Document,\n\tsibling: boolean,\n\tui?: DialogOptions,\n): void {\n\tconst s = stringsOf(ui);\n\t(\n\t\tdoc.querySelector(\"dialog.tab-mcp-replaced\") as HTMLDialogElement | null\n\t)?.close();\n\tconst { dialog } = newDialog(\n\t\tdoc,\n\t\t\"tab-mcp-replaced\",\n\t\ts,\n\t\tsibling ? s.replacedSiblingTitle : s.replacedTitle,\n\t);\n\tconst status = el(doc, \"p\", { className: \"tab-mcp-status\" });\n\tstatus.setAttribute(\"role\", \"status\");\n\tstatus.hidden = true;\n\tconst close = button(\n\t\tdoc,\n\t\ts.close,\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-replaced-close\",\n\t\tsibling ? \"primary\" : undefined,\n\t);\n\tconst actions = el(doc, \"div\", { className: \"tab-mcp-actions\" }, close);\n\tlet first = close;\n\tif (!sibling) {\n\t\tconst fresh = button(\n\t\t\tdoc,\n\t\t\ts.newAddress,\n\t\t\t() => {\n\t\t\t\tfresh.disabled = true;\n\t\t\t\tstatus.hidden = false;\n\t\t\t\tstatus.textContent = s.gettingNewAddress;\n\t\t\t\tmcp.newAddress().then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tdialog.close();\n\t\t\t\t\t\tmcp.showConnectDialog({ document: doc }).catch(() => {});\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tfresh.disabled = false;\n\t\t\t\t\t\tstatus.textContent =\n\t\t\t\t\t\t\t(error as { reason?: unknown } | null)?.reason === \"replaced\"\n\t\t\t\t\t\t\t\t? s.takenOverAgain\n\t\t\t\t\t\t\t\t: format(s.tryAgainOrClose, {\n\t\t\t\t\t\t\t\t\t\treason: connectFailure(error, s),\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t},\n\t\t\t\"tab-mcp-new-address\",\n\t\t\t\"primary\",\n\t\t);\n\t\tactions.append(\" \", fresh);\n\t\tfirst = fresh;\n\t}\n\tdialog.append(\n\t\tel(doc, \"p\", {\n\t\t\tclassName: \"tab-mcp-description\",\n\t\t\ttext: sibling ? s.replacedSibling : s.replaced,\n\t\t}),\n\t\tstatus,\n\t\tactions,\n\t);\n\tdialog.addEventListener(\"close\", () => dialog.remove(), { once: true });\n\tdoc.body.append(dialog);\n\tdialog.showModal();\n\tfirst.focus();\n}\n\n/**\n * How long a used code stays \"Code used\" before its replacement is shown: the\n * AI app connects a moment after the code was entered (its token request), and\n * a new code in plain view meanwhile looks as if it did not work. Only when\n * the relay says the code was used (`reason: \"used\"`); a relay that does not\n * say why gets the new code shown at once.\n */\nexport const CODE_USED_WAIT_MS = 10_000;\n\n/**\n * The \"Connect your AI app\" dialog: the address with Copy, how to add it,\n * the pairing code (with Copy) while the relay sends one, New address, and\n * the connected apps with Disconnect (and the tools allowed until reload\n * for each, with Ask again). Pairing is on while it is open, so closing it\n * ends the code; the connection and the address stay. Until an app is\n * connected, only a small Close (and Escape) close it. Once one is, a\n * confirmation leads, the setup moves behind \"Connect another app\" and\n * Done is the primary button. New address asks first when it would\n * disconnect connected apps. When the page loses its address (`replaced`),\n * this dialog closes and `replacedNotice` says why, from then on also while\n * it is closed.\n *\n * Its nodes are built once; one `render()` derives what is shown from `mcp`\n * and a few flags of its own after every change, so nothing flickers and\n * focus stays, or moves to the next step when its control was hidden.\n */\nexport function showConnectDialog(\n\tmcp: TabMcp,\n\tconnecting: Promise<SessionInfo>,\n\tdoc: Document,\n\tserverName = \"tools\",\n\tui?: DialogOptions,\n): Promise<void> {\n\tconst s = stringsOf(ui);\n\tconst allowed = allowedFor(mcp);\n\tconst { dialog } = newDialog(doc, \"tab-mcp-connect\", s, s.connectTitle);\n\t// Focusable from script only, for the moment before the address is shown.\n\tdialog.tabIndex = -1;\n\tconst status = el(doc, \"p\", { className: \"tab-mcp-status\" });\n\tstatus.setAttribute(\"role\", \"status\");\n\t// What a Copy did, for assistive technology only; out of sight, also\n\t// without the stylesheet. The same message twice is still a change.\n\tconst live = el(doc, \"span\", { className: \"tab-mcp-announce\" });\n\tlive.setAttribute(\"aria-live\", \"polite\");\n\tfor (const [property, value] of [\n\t\t[\"position\", \"absolute\"],\n\t\t[\"width\", \"1px\"],\n\t\t[\"height\", \"1px\"],\n\t\t[\"overflow\", \"hidden\"],\n\t\t[\"clip-path\", \"inset(50%)\"],\n\t\t[\"white-space\", \"nowrap\"],\n\t] as const)\n\t\tlive.style.setProperty(property, value);\n\tconst announce = (text: string) => {\n\t\tlive.textContent = live.textContent === text ? `${text} ` : text;\n\t};\n\n\t// The confirmation once an app is connected: what happened, what next.\n\tconst successId = `${nextId()}-success`;\n\tconst successTitle = el(doc, \"p\", { className: \"tab-mcp-success-title\" });\n\tconst successNext = el(doc, \"p\", { className: \"tab-mcp-success-next\" });\n\t// A check mark in a tinted disk, drawn by the stylesheet (CU 19).\n\tconst check = el(doc, \"span\", { className: \"tab-mcp-success-icon\" });\n\tcheck.setAttribute(\"aria-hidden\", \"true\");\n\tconst success = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-success\", id: successId },\n\t\tcheck,\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-success-text\" },\n\t\t\tsuccessTitle,\n\t\t\tsuccessNext,\n\t\t),\n\t);\n\n\tconst addressId = `${nextId()}-address`;\n\tconst label = el(doc, \"label\", { text: s.addressLabel });\n\tlabel.htmlFor = addressId;\n\tconst address = el(doc, \"input\", {\n\t\tid: addressId,\n\t\tclassName: \"tab-mcp-address-input\",\n\t});\n\taddress.readOnly = true;\n\t// Copying the address is the first step: the primary button, until an\n\t// app is connected (then Done is).\n\tconst { button: copy, reset: resetCopy } = copyButton(\n\t\tdoc,\n\t\ts,\n\t\ts.copyAddress,\n\t\t() => address.value,\n\t\t() => address.select(),\n\t\tannounce,\n\t\t\"tab-mcp-address-copy\",\n\t\t\"primary\",\n\t);\n\tconst addressBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-address\" },\n\t\tlabel,\n\t\taddress,\n\t\t\" \",\n\t\tcopy,\n\t);\n\n\t// Not next to Copy, and saying what it does (CU 23): with no app connected\n\t// it changes the address at once, also one just pasted into an AI app.\n\tconst fresh = button(\n\t\tdoc,\n\t\ts.newAddress,\n\t\t() => askNewAddress(),\n\t\t\"tab-mcp-new-address\",\n\t);\n\tconst freshBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-new-address-row\" },\n\t\tel(doc, \"small\", { text: s.newAddressNote }),\n\t\t\" \",\n\t\tfresh,\n\t);\n\t// Asked in the dialog before New address disconnects connected apps.\n\tconst questionId = `${nextId()}-new-address`;\n\tconst questionText = el(doc, \"p\", { id: questionId });\n\tconst cancelNew = button(doc, s.cancel, () => {\n\t\tasking = false;\n\t\trender();\n\t\tfresh.focus();\n\t});\n\tconst confirmNew = button(\n\t\tdoc,\n\t\ts.newAddressConfirm,\n\t\t() => getNewAddress(),\n\t\t\"tab-mcp-new-address-confirm\",\n\t\t\"danger\",\n\t);\n\tconst question = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-new-address-question\" },\n\t\tquestionText,\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-actions\" },\n\t\t\tcancelNew,\n\t\t\t\" \",\n\t\t\tconfirmNew,\n\t\t),\n\t);\n\tquestion.setAttribute(\"role\", \"group\");\n\tquestion.setAttribute(\"aria-labelledby\", questionId);\n\n\t// Large, in a monospace font: a new code takes the same room.\n\tconst code = el(doc, \"strong\", { className: \"tab-mcp-code-value\" });\n\t// One click selects the whole code; it stays plain, selectable text.\n\tcode.style.setProperty(\"user-select\", \"all\");\n\tcode.style.setProperty(\"-webkit-user-select\", \"all\");\n\t// Reads the code shown at click time, so a rotated code is copied as shown.\n\tconst { button: copyCode, reset: resetCopyCode } = copyButton(\n\t\tdoc,\n\t\ts,\n\t\ts.copyCode,\n\t\t() => code.textContent ?? \"\",\n\t\t() => doc.getSelection()?.selectAllChildren(code),\n\t\tannounce,\n\t\t\"tab-mcp-code-copy\",\n\t);\n\t// Only the sentence with the code is announced when the code changes,\n\t// not its Copy button's \"Copied\".\n\tconst codeSentence = el(\n\t\tdoc,\n\t\t\"span\",\n\t\t{},\n\t\t...fill(doc, s.codeSentence, { code }),\n\t);\n\tcodeSentence.setAttribute(\"aria-live\", \"polite\");\n\t// In the code's place while the AI app finishes connecting with it.\n\tconst codeUsed = el(doc, \"span\", { className: \"tab-mcp-code-used\" });\n\tconst codeLine = el(\n\t\tdoc,\n\t\t\"p\",\n\t\t{ className: \"tab-mcp-code\" },\n\t\tcodeSentence,\n\t\tcodeUsed,\n\t\t\" \",\n\t\tcopyCode,\n\t\tel(doc, \"br\"),\n\t\tel(doc, \"small\", { className: \"tab-mcp-code-note\", text: s.codeNote }),\n\t);\n\t// Identity binding: no code, the same account at the AI app's sign-in.\n\tconst signInLine = el(doc, \"p\", {\n\t\tclassName: \"tab-mcp-sign-in\",\n\t\ttext: s.signIn,\n\t});\n\n\tconst steps = el(doc, \"ul\");\n\tconst help = el(\n\t\tdoc,\n\t\t\"details\",\n\t\t{ className: \"tab-mcp-help\" },\n\t\tel(doc, \"summary\", { text: s.help }),\n\t\tsteps,\n\t);\n\tconst guideUrl =\n\t\tui?.setup?.guide === undefined ? SETUP_GUIDE : ui.setup.guide;\n\tif (guideUrl !== null) {\n\t\tconst guide = el(doc, \"a\", { text: s.guide });\n\t\tguide.href = guideUrl;\n\t\tguide.target = \"_blank\";\n\t\tguide.rel = \"noopener noreferrer\";\n\t\thelp.append(el(doc, \"p\", { className: \"tab-mcp-guide\" }, guide));\n\t}\n\tconst instructions = ui?.setup?.instructions ?? setupInstructions;\n\n\t// Everything for adding the page to an AI app. Once one is connected, it\n\t// is behind \"Connect another app\", closed: the next code is not news.\n\t// Where to paste the address comes right after it, the code after that\n\t// (CU 23); New address last. The help stays closed (DEC-147).\n\tconst setupId = `${nextId()}-setup`;\n\tconst setup = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-setup\", id: setupId },\n\t\taddressBox,\n\t\thelp,\n\t\tcodeLine,\n\t\tsignInLine,\n\t\tfreshBox,\n\t\tquestion,\n\t);\n\tconst setupToggle = button(\n\t\tdoc,\n\t\ts.connectAnother,\n\t\t() => {\n\t\t\texpanded = !expanded;\n\t\t\trender();\n\t\t},\n\t\t\"tab-mcp-setup-toggle\",\n\t);\n\tsetupToggle.setAttribute(\"aria-controls\", setupId);\n\n\tconst appList = el(doc, \"ul\");\n\tconst appsNote = el(doc, \"p\", { className: \"tab-mcp-apps-note\" });\n\tappsNote.setAttribute(\"role\", \"status\");\n\tconst apps = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-apps\" },\n\t\tel(doc, \"h3\", { text: s.connectedHeading }),\n\t\tappList,\n\t\tappsNote,\n\t);\n\n\t// Until an app is connected, closing it is not the next step: a small\n\t// Close at the end, saying what closing does (the code stops, the address\n\t// stays). Once one is, a prominent Done replaces both.\n\tconst closeNote = el(doc, \"small\", {\n\t\tclassName: \"tab-mcp-close-note\",\n\t\ttext: s.closeNote,\n\t});\n\tconst close = button(doc, s.close, () => dialog.close(), \"tab-mcp-close\");\n\tconst done = button(\n\t\tdoc,\n\t\ts.done,\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-done\",\n\t\t\"primary\",\n\t);\n\t// While not connected (it failed, the session ended, it reconnects): the\n\t// next step, from a click, so it has the user action it needs (CU 4).\n\t// While reconnecting, connect() makes the next attempt at once.\n\tconst retry = button(\n\t\tdoc,\n\t\ts.connectAgain,\n\t\t() => {\n\t\t\tmessage = undefined;\n\t\t\tmcp.connect().then(\n\t\t\t\t() => {\n\t\t\t\t\tif (doc.activeElement === close) start().focus();\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tmessage = connectFailure(error, s);\n\t\t\t\t\trender();\n\t\t\t\t\t// Focus went to Close while it connected: back to Connect\n\t\t\t\t\t// again, so a second Enter tries again instead of closing.\n\t\t\t\t\tif (doc.activeElement === close && !retry.hidden) retry.focus();\n\t\t\t\t},\n\t\t\t);\n\t\t\trender();\n\t\t},\n\t\t\"tab-mcp-retry\",\n\t\t\"primary\",\n\t);\n\tconst actions = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-actions\" },\n\t\tcloseNote,\n\t\t\" \",\n\t\tclose,\n\t\tretry,\n\t\tdone,\n\t);\n\tdialog.append(success, status, apps, setupToggle, setup, actions, live);\n\n\t// The dialog's own state; the rest is read from `mcp` in `render()`.\n\t/** The setup is open while an app is connected. */\n\tlet expanded = false;\n\t/** The New address question is open. */\n\tlet asking = false;\n\t/** New address waits for the new session. */\n\tlet renewing = false;\n\t/** New address got its session; until an app pairs or it disconnects. */\n\tlet renewed = false;\n\t/** Why it is not connected, in the user's words, while it is not. */\n\tlet message: string | undefined;\n\t/** Why the last Disconnect failed, while connected. */\n\tlet appsProblem: string | undefined;\n\t/** The grants of the last render: a new one is an app that just paired. */\n\tlet grantsSeen = new Set(mcp.grants.map((g) => g.grantId));\n\t/** The address the help's steps were made for. */\n\tlet stepsFor: string | undefined;\n\t/** The code shown, and the wait after it was used (until the app connects). */\n\tlet shownCode: PairingCode | undefined;\n\tlet usedTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Shown in the connected state. */\n\tlet connectedView = false;\n\n\t// Where focus goes when its control was hidden: the next step (Done or\n\t// Connect again), else Close.\n\tconst closer = () => (connectedView ? done : retry.hidden ? close : retry);\n\t// Where focus starts: Done once connected, else the address's Copy.\n\tconst start = () => (connectedView ? done : copy);\n\n\t// One item per grant, kept while the grant is: a focused Disconnect keeps\n\t// its focus. Under it, the tools allowed until reload, with Ask again.\n\tconst items = new Map<\n\t\tstring,\n\t\t{\n\t\t\titem: HTMLLIElement;\n\t\t\tdisconnect: HTMLButtonElement;\n\t\t\tallowedText: HTMLElement;\n\t\t\tallowedBox: HTMLElement;\n\t\t}\n\t>();\n\tconst appItem = (grant: Grant) => {\n\t\tconst app = clientLabel(grant.client, s);\n\t\tconst disconnect = button(\n\t\t\tdoc,\n\t\t\ts.disconnect,\n\t\t\t() => {\n\t\t\t\tappsProblem = undefined;\n\t\t\t\tmcp.revoke(grant.grantId).catch((error: unknown) => {\n\t\t\t\t\t// Not connected any more: the note says so already.\n\t\t\t\t\tif (mcp.state === \"connected\")\n\t\t\t\t\t\tappsProblem =\n\t\t\t\t\t\t\t(error as { code?: unknown } | null)?.code === \"store_unavailable\"\n\t\t\t\t\t\t\t\t? s.storeUnavailable\n\t\t\t\t\t\t\t\t: s.disconnectFailed;\n\t\t\t\t\trender();\n\t\t\t\t});\n\t\t\t\trender();\n\t\t\t},\n\t\t\t\"tab-mcp-disconnect\",\n\t\t\t\"danger\",\n\t\t);\n\t\t// One name per button: each list item has its own Disconnect.\n\t\tdisconnect.setAttribute(\"aria-label\", format(s.disconnectApp, { app }));\n\t\tconst askAgain = button(\n\t\t\tdoc,\n\t\t\ts.askAgain,\n\t\t\t() => allowed.forget(grant.grantId),\n\t\t\t\"tab-mcp-ask-again\",\n\t\t);\n\t\taskAgain.setAttribute(\"aria-label\", format(s.askAgainApp, { app }));\n\t\tconst allowedText = el(doc, \"span\");\n\t\tconst allowedBox = el(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-allowed\" },\n\t\t\tallowedText,\n\t\t\t\" \",\n\t\t\taskAgain,\n\t\t);\n\t\tconst item = el(\n\t\t\tdoc,\n\t\t\t\"li\",\n\t\t\t{},\n\t\t\tel(\n\t\t\t\tdoc,\n\t\t\t\t\"span\",\n\t\t\t\t{ className: \"tab-mcp-app\" },\n\t\t\t\tformat(s.appConnected, { app }),\n\t\t\t),\n\t\t\t\" \",\n\t\t\tdisconnect,\n\t\t\tallowedBox,\n\t\t);\n\t\treturn { item, disconnect, allowedText, allowedBox };\n\t};\n\n\t/** The steps for `address` in the help, made again when it changes. */\n\tconst renderSteps = (session: SessionInfo) => {\n\t\tif (stepsFor === session.address) return;\n\t\tstepsFor = session.address;\n\t\tsteps.replaceChildren(\n\t\t\t...instructions(serverName, session.address).map(\n\t\t\t\t({ app, text: how, command, note }) => {\n\t\t\t\t\tconst item = el(\n\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\"li\",\n\t\t\t\t\t\t{},\n\t\t\t\t\t\tel(doc, \"strong\", { text: `${app}:` }),\n\t\t\t\t\t\t` ${how}`,\n\t\t\t\t\t);\n\t\t\t\t\tif (command !== undefined) {\n\t\t\t\t\t\t// A block with its own Copy, like the code.\n\t\t\t\t\t\tconst text = el(doc, \"pre\", { text: command });\n\t\t\t\t\t\ttext.dir = \"ltr\";\n\t\t\t\t\t\tconst { button: copyCommand } = copyButton(\n\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\ts,\n\t\t\t\t\t\t\tformat(s.copyCommand, { app }),\n\t\t\t\t\t\t\t() => text.textContent ?? \"\",\n\t\t\t\t\t\t\t() => doc.getSelection()?.selectAllChildren(text),\n\t\t\t\t\t\t\tannounce,\n\t\t\t\t\t\t\t\"tab-mcp-command-copy\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"div\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command\" },\n\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\tcopyCommand,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (note !== undefined)\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"small\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command-note\" },\n\t\t\t\t\t\t\t\t...note.map((part) =>\n\t\t\t\t\t\t\t\t\t\"code\" in part\n\t\t\t\t\t\t\t\t\t\t? el(doc, \"code\", { text: part.code })\n\t\t\t\t\t\t\t\t\t\t: part.text,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\treturn item;\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t};\n\n\t/** The pairing code, or \"Code used\" in its place while the AI app connects. */\n\tconst renderCode = (paired: boolean) => {\n\t\tconst current = mcp.pairingCode;\n\t\tif (current === undefined || paired) {\n\t\t\t// None any more, or the app connected: the next code shows.\n\t\t\tclearTimeout(usedTimer);\n\t\t\tusedTimer = undefined;\n\t\t} else if (current.code !== shownCode?.code) {\n\t\t\tif (current.reason === \"used\") {\n\t\t\t\t// Entered just now: no new code in plain view while the AI app\n\t\t\t\t// connects; it shows if none does.\n\t\t\t\tif (usedTimer === undefined) {\n\t\t\t\t\tusedTimer = setTimeout(() => {\n\t\t\t\t\t\t// No app came: the code shows (unless another came meanwhile).\n\t\t\t\t\t\tusedTimer = undefined;\n\t\t\t\t\t\tshownCode = mcp.pairingCode;\n\t\t\t\t\t\trender();\n\t\t\t\t\t}, CODE_USED_WAIT_MS);\n\t\t\t\t\tannounce(s.codeUsed);\n\t\t\t\t}\n\t\t\t} else if (usedTimer !== undefined) {\n\t\t\t\t// Locked or expired meanwhile: the user needs this one now.\n\t\t\t\tclearTimeout(usedTimer);\n\t\t\t\tusedTimer = undefined;\n\t\t\t}\n\t\t}\n\t\tconst used = usedTimer !== undefined;\n\t\tif (!used) {\n\t\t\t// A new code is not copied yet.\n\t\t\tif (code.textContent !== (current?.code ?? \"\")) resetCopyCode();\n\t\t\tcode.textContent = current?.code ?? \"\";\n\t\t\tshownCode = current;\n\t\t}\n\t\tcodeSentence.hidden = used;\n\t\tcopyCode.hidden = used;\n\t\tcodeUsed.hidden = !used;\n\t\tcodeUsed.textContent = used ? s.codeUsed : \"\";\n\t\treturn current !== undefined;\n\t};\n\n\t/** Shows what `mcp` and the flags say; keeps the focus on a shown control. */\n\tconst render = () => {\n\t\tconst focused = doc.activeElement;\n\t\tconst { state, session, grants } = mcp;\n\t\tconst connected = state === \"connected\";\n\t\tconst oidc = session?.pairing === \"oidc\";\n\t\t// With identity binding, the address is of no use until the relay\n\t\t// knows who is signed in to the page: the status says what is missing.\n\t\tconst signIn = oidc ? signInText(mcp, s) : undefined;\n\t\tconst shown = session !== undefined && signIn === undefined;\n\n\t\t// An app that paired just now: the setup closes again (unless the New\n\t\t// address question is open in it), and the confirmation is announced.\n\t\tconst ids = new Set(grants.map((g) => g.grantId));\n\t\tconst paired = connected && grants.some((g) => !grantsSeen.has(g.grantId));\n\t\tgrantsSeen = ids;\n\t\tif (paired) {\n\t\t\trenewed = false;\n\t\t\tif (!asking) expanded = false;\n\t\t}\n\t\t// Nobody left to disconnect: no question needed.\n\t\tconst names = appLabels(grants, s);\n\t\tif (names.length === 0 || !shown) asking = false;\n\n\t\tconnectedView = !renewing && connected && grants.length > 0;\n\t\tconst one = names.length === 1;\n\t\tsuccessTitle.textContent = format(one ? s.connectedOne : s.connectedMany, {\n\t\t\tapps: listOf(names, s),\n\t\t});\n\t\tsuccessNext.textContent = one ? s.connectedNextOne : s.connectedNextMany;\n\t\tif (connectedView) dialog.setAttribute(\"aria-describedby\", successId);\n\t\telse dialog.removeAttribute(\"aria-describedby\");\n\t\tsuccess.hidden = !connectedView;\n\n\t\t// The status line is for the setup; the confirmation says it otherwise.\n\t\tif (connected) message = undefined;\n\t\tconst appName = session?.appName;\n\t\tstatus.textContent = renewing\n\t\t\t? s.gettingNewAddress\n\t\t\t: state === \"connecting\"\n\t\t\t\t? s.connecting\n\t\t\t\t: state === \"reconnecting\"\n\t\t\t\t\t? s.reconnecting\n\t\t\t\t\t: !connected\n\t\t\t\t\t\t? (message ?? s.notConnected)\n\t\t\t\t\t\t: (signIn ??\n\t\t\t\t\t\t\t(renewed\n\t\t\t\t\t\t\t\t? s.newAddressDone\n\t\t\t\t\t\t\t\t: appName !== undefined\n\t\t\t\t\t\t\t\t\t? format(s.readyApp, { app: appName })\n\t\t\t\t\t\t\t\t\t: s.readyPage));\n\t\tstatus.hidden = connectedView;\n\n\t\t// The address, its help and New address.\n\t\tconst addressShownBefore = !addressBox.hidden;\n\t\tif (shown && address.value !== session.address) {\n\t\t\taddress.value = session.address;\n\t\t\tresetCopy();\n\t\t}\n\t\tif (shown) renderSteps(session);\n\t\taddressBox.hidden = help.hidden = freshBox.hidden = !shown;\n\t\tfresh.disabled = !connected;\n\t\tquestion.hidden = !asking;\n\t\tif (asking)\n\t\t\tquestionText.textContent = format(\n\t\t\t\tone ? s.newAddressQuestionOne : s.newAddressQuestionMany,\n\t\t\t\t{ apps: listOf(names, s) },\n\t\t\t);\n\t\tconst hasCode = renderCode(paired);\n\t\tcodeLine.hidden = oidc || !hasCode || !connected;\n\t\tsignInLine.hidden = !oidc || mcp.identity !== \"bound\";\n\n\t\tsetupToggle.hidden = !connectedView;\n\t\tsetupToggle.setAttribute(\"aria-expanded\", String(expanded));\n\t\tsetup.hidden = connectedView && !expanded;\n\t\tcopy.classList.toggle(\"tab-mcp-primary\", !connectedView);\n\n\t\t// The connected apps; only the relay can revoke, so only while connected.\n\t\tfor (const [id, { item }] of items) {\n\t\t\tif (ids.has(id)) continue;\n\t\t\titem.remove();\n\t\t\titems.delete(id);\n\t\t}\n\t\tgrants.forEach((grant, i) => {\n\t\t\tlet entry = items.get(grant.grantId);\n\t\t\tif (entry === undefined) {\n\t\t\t\tentry = appItem(grant);\n\t\t\t\titems.set(grant.grantId, entry);\n\t\t\t}\n\t\t\tentry.disconnect.disabled = !connected;\n\t\t\tconst tools = allowed.list(grant.grantId);\n\t\t\tentry.allowedBox.hidden = tools.length === 0;\n\t\t\tentry.allowedText.textContent = format(s.runsWithoutAsking, {\n\t\t\t\ttools: tools.map(visible).join(\", \"),\n\t\t\t});\n\t\t\tif (appList.children[i] !== entry.item)\n\t\t\t\tappList.insertBefore(entry.item, appList.children[i] ?? null);\n\t\t});\n\t\tappsNote.textContent = connected ? (appsProblem ?? \"\") : s.disconnectNote;\n\t\tappsNote.hidden = connected && appsProblem === undefined;\n\t\tapps.hidden = grants.length === 0;\n\n\t\t// The note is about the code: only while one is shown and none connected.\n\t\tcloseNote.hidden = connectedView || codeLine.hidden;\n\t\tclose.hidden = connectedView;\n\t\tdone.hidden = !connectedView;\n\t\tretry.hidden =\n\t\t\trenewing || (state !== \"disconnected\" && state !== \"reconnecting\");\n\n\t\t// Focus never stays on a control that was hidden or removed; from the\n\t\t// New address question that closed, back to New address.\n\t\tif (\n\t\t\tfocused !== null &&\n\t\t\tfocused !== dialog &&\n\t\t\tfocused !== doc.body &&\n\t\t\t(!focused.isConnected ||\n\t\t\t\t(dialog.contains(focused) && focused.closest(\"[hidden]\") !== null))\n\t\t)\n\t\t\t(question.contains(focused) && !freshBox.hidden\n\t\t\t\t? fresh\n\t\t\t\t: closer()\n\t\t\t).focus();\n\t\t// The address showed only now: start there (or at Done), or, after a\n\t\t// New address, at its Copy.\n\t\telse if (doc.activeElement === dialog && (connectedView || shown))\n\t\t\tstart().focus();\n\t\telse if (\n\t\t\trenewed &&\n\t\t\tshown &&\n\t\t\t!addressShownBefore &&\n\t\t\tdoc.activeElement === close\n\t\t)\n\t\t\tcopy.focus();\n\t\tif (paired && connectedView)\n\t\t\tannounce(`${successTitle.textContent}. ${successNext.textContent}`);\n\t};\n\n\tconst askNewAddress = () => {\n\t\tif (mcp.state !== \"connected\") return;\n\t\tif (mcp.grants.length === 0) {\n\t\t\tgetNewAddress();\n\t\t\treturn;\n\t\t}\n\t\tasking = true;\n\t\trender();\n\t\tcancelNew.focus(); // the safe choice is the default\n\t};\n\tconst getNewAddress = () => {\n\t\trenewing = true;\n\t\trenewed = false;\n\t\t// Focus moves before the focused control is hidden.\n\t\tclose.focus();\n\t\tasking = false;\n\t\trender();\n\t\t// Called from the click, so the reconnect has the user action it needs.\n\t\tmcp.newAddress().then(\n\t\t\t() => {\n\t\t\t\trenewing = false;\n\t\t\t\trenewed = true;\n\t\t\t\trender();\n\t\t\t\t// At its Copy once the new address shows (with identity binding\n\t\t\t\t// maybe only later: `render()` moves it then).\n\t\t\t\tif (!addressBox.hidden) copy.focus();\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\trenewing = false;\n\t\t\t\tmessage = connectFailure(error, s);\n\t\t\t\trender();\n\t\t\t\tcloser().focus();\n\t\t\t},\n\t\t);\n\t};\n\n\t// A refusal that stops reconnecting comes as `error` (with its `reason`)\n\t// just before the `statechange` to `disconnected`: that says why it stopped.\n\tlet stoppedBy: unknown;\n\tlet wasReconnecting = mcp.state === \"reconnecting\";\n\tconst onError = (event: CustomEvent<{ error: Error }>) => {\n\t\tconst { error } = event.detail;\n\t\tif (wasReconnecting && (error as { reason?: unknown }).reason !== undefined)\n\t\t\tstoppedBy = error;\n\t};\n\tconst onState = (event: CustomEvent<StateChangeDetail>) => {\n\t\tconst { state, reason } = event.detail;\n\t\tif (reason !== undefined && reason !== \"new_address\") {\n\t\t\tmessage = disconnectedText(reason, s);\n\t\t\trenewed = false;\n\t\t}\n\t\t// Refused, or ended by the page (`disconnect()`) while it waited.\n\t\tif (state === \"disconnected\" && wasReconnecting)\n\t\t\tmessage =\n\t\t\t\tstoppedBy === undefined ? s.disconnected : connectFailure(stoppedBy, s);\n\t\twasReconnecting = state === \"reconnecting\";\n\t\tstoppedBy = undefined;\n\t\trender();\n\t};\n\n\t// The address was taken over: the notice says so instead of this dialog.\n\tconst onReplaced = () => dialog.close();\n\twatchReplaced(mcp, doc, ui);\n\tconst stopAllowed = allowed.onChange(render);\n\tmcp.addEventListener(\"statechange\", onState);\n\tmcp.addEventListener(\"pairingcode\", render);\n\tmcp.addEventListener(\"grantschange\", render);\n\tmcp.addEventListener(\"identitychange\", render);\n\tmcp.addEventListener(\"error\", onError);\n\tmcp.addEventListener(\"replaced\", onReplaced);\n\tdoc.body.append(dialog);\n\tmcp.startPairing();\n\trender();\n\tconnecting.then(render, (error: unknown) => {\n\t\tmessage = connectFailure(error, s);\n\t\trender();\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tdialog.addEventListener(\n\t\t\t\"close\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(usedTimer);\n\t\t\t\tmcp.stopPairing();\n\t\t\t\tstopAllowed();\n\t\t\t\tmcp.removeEventListener(\"statechange\", onState);\n\t\t\t\tmcp.removeEventListener(\"pairingcode\", render);\n\t\t\t\tmcp.removeEventListener(\"grantschange\", render);\n\t\t\t\tmcp.removeEventListener(\"identitychange\", render);\n\t\t\t\tmcp.removeEventListener(\"error\", onError);\n\t\t\t\tmcp.removeEventListener(\"replaced\", onReplaced);\n\t\t\t\tdialog.remove();\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\tdialog.showModal();\n\t\t// Start at Done once connected, else at the address's Copy; until the\n\t\t// address is there, at the dialog itself (its title is read out), not\n\t\t// at Close.\n\t\tif (connectedView || !addressBox.hidden) start().focus();\n\t\telse dialog.focus();\n\t});\n}\n"
5
+ "/**\n * The \"Connect your AI app\" dialog (DEC-028) and the notice that the page\n * lost its address, loaded on demand when a page opens the dialog.\n */\n\nimport { allowedFor } from \"./always-allowed.ts\";\nimport {\n\tbutton,\n\tclientLabel,\n\tcopyButton,\n\tel,\n\tfill,\n\tformat,\n\tlistOf,\n\tnewDialog,\n\tnextId,\n\tstringsOf,\n\tvisible,\n} from \"./dialog.ts\";\nimport { SETUP_GUIDE, setupInstructions } from \"./setup.ts\";\nimport type { DialogStrings } from \"./strings.ts\";\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type {\n\tDialogOptions,\n\tDisconnectReason,\n\tGrant,\n\tPairingCode,\n\tSessionInfo,\n\tStateChangeDetail,\n} from \"./types.ts\";\n\n/**\n * The labels of the apps behind these grants, each once: an app can hold\n * more than one grant (paired twice), and is still one app.\n */\nfunction appLabels(grants: readonly Grant[], s: DialogStrings): string[] {\n\treturn [...new Set(grants.map((g) => clientLabel(g.client, s)))];\n}\n\n/**\n * Why connecting failed, in the user's words (CU 4). The error itself, with\n * the relay's wording, goes to the console. Without a `reason` it never\n * started (no user action, cancelled): just not connected.\n */\nfunction connectFailure(error: unknown, s: DialogStrings): string {\n\tconsole.warn(\"tab-mcp: could not connect.\", error);\n\tconst reason = (error as { reason?: DisconnectReason } | null)?.reason;\n\tif (reason === undefined) return s.notConnected;\n\tif (reason === \"network\") return s.unreachable;\n\tif (reason === \"rate_limited\") return s.rateLimited;\n\treturn s.refused;\n}\n\n/** Why the page was disconnected, in the user's words (CU 4). */\nfunction disconnectedText(reason: DisconnectReason, s: DialogStrings): string {\n\tswitch (reason) {\n\t\tcase \"expired\":\n\t\tcase \"idle\":\n\t\t\treturn s.ended;\n\t\tcase \"user\":\n\t\t\treturn s.disconnected;\n\t\tcase \"network\":\n\t\tcase \"heartbeat\":\n\t\tcase \"shutdown\":\n\t\t\treturn s.lost;\n\t\tcase \"rate_limited\":\n\t\t\treturn s.rateLimited;\n\t\tdefault:\n\t\t\treturn s.closed;\n\t}\n}\n\n/**\n * With identity binding: what stands between the user and the address until\n * the relay knows who is signed in (CU 7). `undefined` once it does.\n */\nfunction signInText(mcp: TabMcp, s: DialogStrings): string | undefined {\n\tswitch (mcp.identity) {\n\t\tcase \"bound\":\n\t\t\treturn undefined;\n\t\tcase \"pending\":\n\t\t\treturn s.checkingSignIn;\n\t\tcase \"refused\":\n\t\t\treturn mcp.identityMessage\n\t\t\t\t? format(s.signInRefusedWhy, { reason: mcp.identityMessage })\n\t\t\t\t: s.signInRefused;\n\t\tdefault:\n\t\t\treturn s.signInFirst;\n\t}\n}\n\n/** The document and texts of the connect dialog per `TabMcp`, once it was opened. */\nconst watched = new WeakMap<TabMcp, { doc: Document; ui?: DialogOptions }>();\n\n/**\n * Once a page has opened the connect dialog, the default UI also says when\n * the page loses its address (`replaced`), in that dialog's document.\n */\nfunction watchReplaced(mcp: TabMcp, doc: Document, ui?: DialogOptions): void {\n\tconst known = watched.has(mcp);\n\twatched.set(mcp, ui === undefined ? { doc } : { doc, ui });\n\tif (known) return;\n\tmcp.addEventListener(\"replaced\", (event) => {\n\t\tconst current = watched.get(mcp);\n\t\t// Not when the page already went on (a New address or connect since).\n\t\tif (current !== undefined && mcp.state === \"disconnected\")\n\t\t\treplacedNotice(mcp, current.doc, event.detail.sibling, current.ui);\n\t});\n}\n\n/**\n * Says that the page lost its address (`replaced`, DEC-095). A sibling tab\n * that announced it: \"Opened in another tab\", nothing to do. Otherwise a\n * warning that another tab or program took over, with \"New address\", which\n * takes the address back, disconnects its apps, connects with a new one and\n * opens the connect dialog to add it to the AI apps again.\n */\nexport function replacedNotice(\n\tmcp: TabMcp,\n\tdoc: Document,\n\tsibling: boolean,\n\tui?: DialogOptions,\n): void {\n\tconst s = stringsOf(ui);\n\t(\n\t\tdoc.querySelector(\"dialog.tab-mcp-replaced\") as HTMLDialogElement | null\n\t)?.close();\n\tconst { dialog } = newDialog(\n\t\tdoc,\n\t\t\"tab-mcp-replaced\",\n\t\ts,\n\t\tsibling ? s.replacedSiblingTitle : s.replacedTitle,\n\t);\n\tconst status = el(doc, \"p\", { className: \"tab-mcp-status\" });\n\tstatus.setAttribute(\"role\", \"status\");\n\tstatus.hidden = true;\n\tconst close = button(\n\t\tdoc,\n\t\ts.close,\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-replaced-close\",\n\t\tsibling ? \"primary\" : undefined,\n\t);\n\tconst actions = el(doc, \"div\", { className: \"tab-mcp-actions\" }, close);\n\tlet first = close;\n\tif (!sibling) {\n\t\tconst fresh = button(\n\t\t\tdoc,\n\t\t\ts.newAddress,\n\t\t\t() => {\n\t\t\t\tfresh.disabled = true;\n\t\t\t\tstatus.hidden = false;\n\t\t\t\tstatus.textContent = s.gettingNewAddress;\n\t\t\t\tmcp.newAddress().then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tdialog.close();\n\t\t\t\t\t\tmcp.showConnectDialog({ document: doc }).catch(() => {});\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tfresh.disabled = false;\n\t\t\t\t\t\tstatus.textContent =\n\t\t\t\t\t\t\t(error as { reason?: unknown } | null)?.reason === \"replaced\"\n\t\t\t\t\t\t\t\t? s.takenOverAgain\n\t\t\t\t\t\t\t\t: format(s.tryAgainOrClose, {\n\t\t\t\t\t\t\t\t\t\treason: connectFailure(error, s),\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t},\n\t\t\t\"tab-mcp-new-address\",\n\t\t\t\"primary\",\n\t\t);\n\t\tactions.append(\" \", fresh);\n\t\tfirst = fresh;\n\t}\n\tdialog.append(\n\t\tel(doc, \"p\", {\n\t\t\tclassName: \"tab-mcp-description\",\n\t\t\ttext: sibling ? s.replacedSibling : s.replaced,\n\t\t}),\n\t\tstatus,\n\t\tactions,\n\t);\n\tdialog.addEventListener(\"close\", () => dialog.remove(), { once: true });\n\tdoc.body.append(dialog);\n\tdialog.showModal();\n\tfirst.focus();\n}\n\n/**\n * How long a used code stays \"Code used\" before its replacement is shown: the\n * AI app connects a moment after the code was entered (its token request), and\n * a new code in plain view meanwhile looks as if it did not work. Only when\n * the relay says the code was used (`reason: \"used\"`); a relay that does not\n * say why gets the new code shown at once.\n */\nexport const CODE_USED_WAIT_MS = 10_000;\n\n/**\n * The \"Connect your AI app\" dialog: the address with Copy, how to add it,\n * the pairing code (with Copy) while the relay sends one, New address, and\n * the connected apps with Disconnect (and the tools allowed until reload\n * for each, with Ask again). Pairing is on while it is open, so closing it\n * ends the code; the connection and the address stay. Until an app is\n * connected, only a small Close (and Escape) close it. Once one is, a\n * confirmation leads, the setup moves behind \"Connect another app\" and\n * Done is the primary button. New address asks first when it would\n * disconnect connected apps. When the page loses its address (`replaced`),\n * this dialog closes and `replacedNotice` says why, from then on also while\n * it is closed.\n *\n * Its nodes are built once; one `render()` derives what is shown from `mcp`\n * and a few flags of its own after every change, so nothing flickers and\n * focus stays, or moves to the next step when its control was hidden.\n */\nexport function showConnectDialog(\n\tmcp: TabMcp,\n\tconnecting: Promise<SessionInfo>,\n\tdoc: Document,\n\tserverName = \"tools\",\n\tui?: DialogOptions,\n): Promise<void> {\n\tconst s = stringsOf(ui);\n\tconst allowed = allowedFor(mcp);\n\tconst { dialog } = newDialog(doc, \"tab-mcp-connect\", s, s.connectTitle);\n\t// Focusable from script only, for the moment before the address is shown.\n\tdialog.tabIndex = -1;\n\tconst status = el(doc, \"p\", { className: \"tab-mcp-status\" });\n\tstatus.setAttribute(\"role\", \"status\");\n\t// What a Copy did, for assistive technology only; out of sight, also\n\t// without the stylesheet. The same message twice is still a change.\n\tconst live = el(doc, \"span\", { className: \"tab-mcp-announce\" });\n\tlive.setAttribute(\"aria-live\", \"polite\");\n\tfor (const [property, value] of [\n\t\t[\"position\", \"absolute\"],\n\t\t[\"width\", \"1px\"],\n\t\t[\"height\", \"1px\"],\n\t\t[\"overflow\", \"hidden\"],\n\t\t[\"clip-path\", \"inset(50%)\"],\n\t\t[\"white-space\", \"nowrap\"],\n\t] as const)\n\t\tlive.style.setProperty(property, value);\n\tconst announce = (text: string) => {\n\t\tlive.textContent = live.textContent === text ? `${text} ` : text;\n\t};\n\n\t// The confirmation once an app is connected: what happened, what next.\n\tconst successId = `${nextId()}-success`;\n\tconst successTitle = el(doc, \"p\", { className: \"tab-mcp-success-title\" });\n\tconst successNext = el(doc, \"p\", { className: \"tab-mcp-success-next\" });\n\t// A check mark in a tinted disk, drawn by the stylesheet (CU 19).\n\tconst check = el(doc, \"span\", { className: \"tab-mcp-success-icon\" });\n\tcheck.setAttribute(\"aria-hidden\", \"true\");\n\tconst success = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-success\", id: successId },\n\t\tcheck,\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-success-text\" },\n\t\t\tsuccessTitle,\n\t\t\tsuccessNext,\n\t\t),\n\t);\n\n\tconst addressId = `${nextId()}-address`;\n\tconst label = el(doc, \"label\", { text: s.addressLabel });\n\tlabel.htmlFor = addressId;\n\tconst address = el(doc, \"input\", {\n\t\tid: addressId,\n\t\tclassName: \"tab-mcp-address-input\",\n\t});\n\taddress.readOnly = true;\n\t// Copying the address is the first step: the primary button, until an\n\t// app is connected (then Done is).\n\tconst { button: copy, reset: resetCopy } = copyButton(\n\t\tdoc,\n\t\ts,\n\t\ts.copyAddress,\n\t\t() => address.value,\n\t\t() => address.select(),\n\t\tannounce,\n\t\t\"tab-mcp-address-copy\",\n\t\t\"primary\",\n\t);\n\tconst addressBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-address\" },\n\t\tlabel,\n\t\taddress,\n\t\t\" \",\n\t\tcopy,\n\t);\n\n\t// Not next to Copy, and saying what it does (CU 23): with no app connected\n\t// it changes the address at once, also one just pasted into an AI app.\n\tconst fresh = button(\n\t\tdoc,\n\t\ts.newAddress,\n\t\t() => askNewAddress(),\n\t\t\"tab-mcp-new-address\",\n\t);\n\tconst freshBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-new-address-row\" },\n\t\tel(doc, \"small\", { text: s.newAddressNote }),\n\t\t\" \",\n\t\tfresh,\n\t);\n\t// Asked in the dialog before New address disconnects connected apps.\n\tconst questionId = `${nextId()}-new-address`;\n\tconst questionText = el(doc, \"p\", { id: questionId });\n\tconst cancelNew = button(doc, s.cancel, () => {\n\t\tasking = false;\n\t\trender();\n\t\tfresh.focus();\n\t});\n\tconst confirmNew = button(\n\t\tdoc,\n\t\ts.newAddressConfirm,\n\t\t() => getNewAddress(),\n\t\t\"tab-mcp-new-address-confirm\",\n\t\t\"danger\",\n\t);\n\tconst question = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-new-address-question\" },\n\t\tquestionText,\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-actions\" },\n\t\t\tcancelNew,\n\t\t\t\" \",\n\t\t\tconfirmNew,\n\t\t),\n\t);\n\tquestion.setAttribute(\"role\", \"group\");\n\tquestion.setAttribute(\"aria-labelledby\", questionId);\n\n\t// Large, in a monospace font: a new code takes the same room.\n\tconst code = el(doc, \"strong\", { className: \"tab-mcp-code-value\" });\n\t// One click selects the whole code; it stays plain, selectable text.\n\tcode.style.setProperty(\"user-select\", \"all\");\n\tcode.style.setProperty(\"-webkit-user-select\", \"all\");\n\t// Reads the code shown at click time, so a rotated code is copied as shown.\n\tconst { button: copyCode, reset: resetCopyCode } = copyButton(\n\t\tdoc,\n\t\ts,\n\t\ts.copyCode,\n\t\t() => code.textContent ?? \"\",\n\t\t() => doc.getSelection()?.selectAllChildren(code),\n\t\tannounce,\n\t\t\"tab-mcp-code-copy\",\n\t);\n\t// Only the sentence with the code is announced when the code changes,\n\t// not its Copy button's \"Copied\".\n\tconst codeSentence = el(\n\t\tdoc,\n\t\t\"span\",\n\t\t{},\n\t\t...fill(doc, s.codeSentence, { code }),\n\t);\n\tcodeSentence.setAttribute(\"aria-live\", \"polite\");\n\t// In the code's place while the AI app finishes connecting with it.\n\tconst codeUsed = el(doc, \"span\", { className: \"tab-mcp-code-used\" });\n\tconst codeLine = el(\n\t\tdoc,\n\t\t\"p\",\n\t\t{ className: \"tab-mcp-code\" },\n\t\tcodeSentence,\n\t\tcodeUsed,\n\t\t\" \",\n\t\tcopyCode,\n\t\tel(doc, \"br\"),\n\t\tel(doc, \"small\", { className: \"tab-mcp-code-note\", text: s.codeNote }),\n\t);\n\t// Identity binding: no code, the same account at the AI app's sign-in.\n\tconst signInLine = el(doc, \"p\", {\n\t\tclassName: \"tab-mcp-sign-in\",\n\t\ttext: s.signIn,\n\t});\n\n\tconst steps = el(doc, \"ul\");\n\tconst help = el(\n\t\tdoc,\n\t\t\"details\",\n\t\t{ className: \"tab-mcp-help\" },\n\t\tel(doc, \"summary\", { text: s.help }),\n\t\tsteps,\n\t);\n\tconst guideUrl =\n\t\tui?.setup?.guide === undefined ? SETUP_GUIDE : ui.setup.guide;\n\tif (guideUrl !== null) {\n\t\tconst guide = el(doc, \"a\", { text: s.guide });\n\t\tguide.href = guideUrl;\n\t\tguide.target = \"_blank\";\n\t\tguide.rel = \"noopener noreferrer\";\n\t\thelp.append(el(doc, \"p\", { className: \"tab-mcp-guide\" }, guide));\n\t}\n\tconst instructions = ui?.setup?.instructions ?? setupInstructions;\n\n\t// Everything for adding the page to an AI app. Once one is connected, it\n\t// is behind \"Connect another app\", closed: the next code is not news.\n\t// Where to paste the address comes right after it, the code after that\n\t// (CU 23); New address last. The help stays closed (DEC-147).\n\tconst setupId = `${nextId()}-setup`;\n\tconst setup = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-setup\", id: setupId },\n\t\taddressBox,\n\t\thelp,\n\t\tcodeLine,\n\t\tsignInLine,\n\t\tfreshBox,\n\t\tquestion,\n\t);\n\tconst setupToggle = button(\n\t\tdoc,\n\t\ts.connectAnother,\n\t\t() => {\n\t\t\texpanded = !expanded;\n\t\t\trender();\n\t\t},\n\t\t\"tab-mcp-setup-toggle\",\n\t);\n\tsetupToggle.setAttribute(\"aria-controls\", setupId);\n\n\tconst appList = el(doc, \"ul\");\n\tconst appsNote = el(doc, \"p\", { className: \"tab-mcp-apps-note\" });\n\tappsNote.setAttribute(\"role\", \"status\");\n\tconst apps = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-apps\" },\n\t\tel(doc, \"h3\", { text: s.connectedHeading }),\n\t\tappList,\n\t\tappsNote,\n\t);\n\n\t// Until an app is connected, closing it is not the next step: a small\n\t// Close at the end, saying what closing does (the code stops, the address\n\t// stays). Once one is, a prominent Done replaces both.\n\tconst closeNote = el(doc, \"small\", {\n\t\tclassName: \"tab-mcp-close-note\",\n\t\ttext: s.closeNote,\n\t});\n\tconst close = button(doc, s.close, () => dialog.close(), \"tab-mcp-close\");\n\tconst done = button(\n\t\tdoc,\n\t\ts.done,\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-done\",\n\t\t\"primary\",\n\t);\n\t// While not connected (it failed, the session ended, it reconnects): the\n\t// next step, from a click, so it has the user action it needs (CU 4).\n\t// While reconnecting, connect() makes the next attempt at once.\n\tconst retry = button(\n\t\tdoc,\n\t\ts.connectAgain,\n\t\t() => {\n\t\t\tmessage = undefined;\n\t\t\tmcp.connect().then(\n\t\t\t\t() => {\n\t\t\t\t\tif (doc.activeElement === close) start().focus();\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tmessage = connectFailure(error, s);\n\t\t\t\t\trender();\n\t\t\t\t\t// Focus went to Close while it connected: back to Connect\n\t\t\t\t\t// again, so a second Enter tries again instead of closing.\n\t\t\t\t\tif (doc.activeElement === close && !retry.hidden) retry.focus();\n\t\t\t\t},\n\t\t\t);\n\t\t\trender();\n\t\t},\n\t\t\"tab-mcp-retry\",\n\t\t\"primary\",\n\t);\n\tconst actions = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-actions\" },\n\t\tcloseNote,\n\t\t\" \",\n\t\tclose,\n\t\tretry,\n\t\tdone,\n\t);\n\tdialog.append(success, status, apps, setupToggle, setup, actions, live);\n\n\t// The dialog's own state; the rest is read from `mcp` in `render()`.\n\t/** The setup is open while an app is connected. */\n\tlet expanded = false;\n\t/** The New address question is open. */\n\tlet asking = false;\n\t/** New address waits for the new session. */\n\tlet renewing = false;\n\t/** New address got its session; until an app pairs or it disconnects. */\n\tlet renewed = false;\n\t/** Why it is not connected, in the user's words, while it is not. */\n\tlet message: string | undefined;\n\t/** Why the last Disconnect failed, while connected. */\n\tlet appsProblem: string | undefined;\n\t/** The grants of the last render: a new one is an app that just paired. */\n\tlet grantsSeen = new Set(mcp.grants.map((g) => g.grantId));\n\t/** The address the help's steps were made for. */\n\tlet stepsFor: string | undefined;\n\t/** The code shown, and the wait after it was used (until the app connects). */\n\tlet shownCode: PairingCode | undefined;\n\tlet usedTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Shown in the connected state. */\n\tlet connectedView = false;\n\n\t// Where focus goes when its control was hidden: the next step (Done or\n\t// Connect again), else Close.\n\tconst closer = () => (connectedView ? done : retry.hidden ? close : retry);\n\t// Where focus starts: Done once connected, else the address's Copy.\n\tconst start = () => (connectedView ? done : copy);\n\n\t// One item per grant, kept while the grant is: a focused Disconnect keeps\n\t// its focus. Under it, the tools allowed until reload, with Ask again.\n\tconst items = new Map<\n\t\tstring,\n\t\t{\n\t\t\titem: HTMLLIElement;\n\t\t\tdisconnect: HTMLButtonElement;\n\t\t\tallowedText: HTMLElement;\n\t\t\tallowedBox: HTMLElement;\n\t\t}\n\t>();\n\tconst appItem = (grant: Grant) => {\n\t\tconst app = clientLabel(grant.client, s);\n\t\tconst disconnect = button(\n\t\t\tdoc,\n\t\t\ts.disconnect,\n\t\t\t() => {\n\t\t\t\tappsProblem = undefined;\n\t\t\t\tmcp.revoke(grant.grantId).catch((error: unknown) => {\n\t\t\t\t\t// Not connected any more: the note says so already.\n\t\t\t\t\tif (mcp.state === \"connected\")\n\t\t\t\t\t\tappsProblem =\n\t\t\t\t\t\t\t(error as { code?: unknown } | null)?.code === \"store_unavailable\"\n\t\t\t\t\t\t\t\t? s.storeUnavailable\n\t\t\t\t\t\t\t\t: s.disconnectFailed;\n\t\t\t\t\trender();\n\t\t\t\t});\n\t\t\t\trender();\n\t\t\t},\n\t\t\t\"tab-mcp-disconnect\",\n\t\t\t\"danger\",\n\t\t);\n\t\t// One name per button: each list item has its own Disconnect.\n\t\tdisconnect.setAttribute(\"aria-label\", format(s.disconnectApp, { app }));\n\t\tconst askAgain = button(\n\t\t\tdoc,\n\t\t\ts.askAgain,\n\t\t\t() => allowed.forget(grant.grantId),\n\t\t\t\"tab-mcp-ask-again\",\n\t\t);\n\t\taskAgain.setAttribute(\"aria-label\", format(s.askAgainApp, { app }));\n\t\tconst allowedText = el(doc, \"span\");\n\t\tconst allowedBox = el(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-allowed\" },\n\t\t\tallowedText,\n\t\t\t\" \",\n\t\t\taskAgain,\n\t\t);\n\t\tconst item = el(\n\t\t\tdoc,\n\t\t\t\"li\",\n\t\t\t{},\n\t\t\tel(\n\t\t\t\tdoc,\n\t\t\t\t\"span\",\n\t\t\t\t{ className: \"tab-mcp-app\" },\n\t\t\t\tformat(s.appConnected, { app }),\n\t\t\t),\n\t\t\t\" \",\n\t\t\tdisconnect,\n\t\t\tallowedBox,\n\t\t);\n\t\treturn { item, disconnect, allowedText, allowedBox };\n\t};\n\n\t/** The steps for `address` in the help, made again when it changes. */\n\tconst renderSteps = (session: SessionInfo) => {\n\t\tif (stepsFor === session.address) return;\n\t\tstepsFor = session.address;\n\t\tsteps.replaceChildren(\n\t\t\t...instructions(serverName, session.address).map(\n\t\t\t\t({ app, text: how, command, note }) => {\n\t\t\t\t\tconst item = el(\n\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\"li\",\n\t\t\t\t\t\t{},\n\t\t\t\t\t\tel(doc, \"strong\", { text: `${app}:` }),\n\t\t\t\t\t\t` ${how}`,\n\t\t\t\t\t);\n\t\t\t\t\tif (command !== undefined) {\n\t\t\t\t\t\t// A block with its own Copy, like the code.\n\t\t\t\t\t\tconst text = el(doc, \"pre\", { text: command });\n\t\t\t\t\t\ttext.dir = \"ltr\";\n\t\t\t\t\t\tconst { button: copyCommand } = copyButton(\n\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\ts,\n\t\t\t\t\t\t\tformat(s.copyCommand, { app }),\n\t\t\t\t\t\t\t() => text.textContent ?? \"\",\n\t\t\t\t\t\t\t() => doc.getSelection()?.selectAllChildren(text),\n\t\t\t\t\t\t\tannounce,\n\t\t\t\t\t\t\t\"tab-mcp-command-copy\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"div\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command\" },\n\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\tcopyCommand,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (note !== undefined)\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"small\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command-note\" },\n\t\t\t\t\t\t\t\t...note.map((part) =>\n\t\t\t\t\t\t\t\t\t\"code\" in part\n\t\t\t\t\t\t\t\t\t\t? el(doc, \"code\", { text: part.code })\n\t\t\t\t\t\t\t\t\t\t: part.text,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\treturn item;\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t};\n\n\t/** The pairing code, or \"Code used\" in its place while the AI app connects. */\n\tconst renderCode = (paired: boolean) => {\n\t\tconst current = mcp.pairingCode;\n\t\tif (current === undefined || paired) {\n\t\t\t// None any more, or the app connected: the next code shows.\n\t\t\tclearTimeout(usedTimer);\n\t\t\tusedTimer = undefined;\n\t\t} else if (current.code !== shownCode?.code) {\n\t\t\tif (current.reason === \"used\") {\n\t\t\t\t// Entered just now: no new code in plain view while the AI app\n\t\t\t\t// connects; it shows if none does.\n\t\t\t\tif (usedTimer === undefined) {\n\t\t\t\t\tusedTimer = setTimeout(() => {\n\t\t\t\t\t\t// No app came: the code shows (unless another came meanwhile).\n\t\t\t\t\t\tusedTimer = undefined;\n\t\t\t\t\t\tshownCode = mcp.pairingCode;\n\t\t\t\t\t\trender();\n\t\t\t\t\t}, CODE_USED_WAIT_MS);\n\t\t\t\t\tannounce(s.codeUsed);\n\t\t\t\t}\n\t\t\t} else if (usedTimer !== undefined) {\n\t\t\t\t// Expired meanwhile: the user needs this one now.\n\t\t\t\tclearTimeout(usedTimer);\n\t\t\t\tusedTimer = undefined;\n\t\t\t}\n\t\t}\n\t\tconst used = usedTimer !== undefined;\n\t\tif (!used) {\n\t\t\t// A new code is not copied yet.\n\t\t\tif (code.textContent !== (current?.code ?? \"\")) resetCopyCode();\n\t\t\tcode.textContent = current?.code ?? \"\";\n\t\t\tshownCode = current;\n\t\t}\n\t\tcodeSentence.hidden = used;\n\t\tcopyCode.hidden = used;\n\t\tcodeUsed.hidden = !used;\n\t\tcodeUsed.textContent = used ? s.codeUsed : \"\";\n\t\treturn current !== undefined;\n\t};\n\n\t/** Shows what `mcp` and the flags say; keeps the focus on a shown control. */\n\tconst render = () => {\n\t\tconst focused = doc.activeElement;\n\t\tconst { state, session, grants } = mcp;\n\t\tconst connected = state === \"connected\";\n\t\tconst oidc = session?.pairing === \"oidc\";\n\t\t// With identity binding, the address is of no use until the relay\n\t\t// knows who is signed in to the page: the status says what is missing.\n\t\tconst signIn = oidc ? signInText(mcp, s) : undefined;\n\t\tconst shown = session !== undefined && signIn === undefined;\n\n\t\t// An app that paired just now: the setup closes again (unless the New\n\t\t// address question is open in it), and the confirmation is announced.\n\t\tconst ids = new Set(grants.map((g) => g.grantId));\n\t\tconst paired = connected && grants.some((g) => !grantsSeen.has(g.grantId));\n\t\tgrantsSeen = ids;\n\t\tif (paired) {\n\t\t\trenewed = false;\n\t\t\tif (!asking) expanded = false;\n\t\t}\n\t\t// Nobody left to disconnect: no question needed.\n\t\tconst names = appLabels(grants, s);\n\t\tif (names.length === 0 || !shown) asking = false;\n\n\t\tconnectedView = !renewing && connected && grants.length > 0;\n\t\tconst one = names.length === 1;\n\t\tsuccessTitle.textContent = format(one ? s.connectedOne : s.connectedMany, {\n\t\t\tapps: listOf(names, s),\n\t\t});\n\t\tsuccessNext.textContent = one ? s.connectedNextOne : s.connectedNextMany;\n\t\tif (connectedView) dialog.setAttribute(\"aria-describedby\", successId);\n\t\telse dialog.removeAttribute(\"aria-describedby\");\n\t\tsuccess.hidden = !connectedView;\n\n\t\t// The status line is for the setup; the confirmation says it otherwise.\n\t\tif (connected) message = undefined;\n\t\tconst appName = session?.appName;\n\t\tstatus.textContent = renewing\n\t\t\t? s.gettingNewAddress\n\t\t\t: state === \"connecting\"\n\t\t\t\t? s.connecting\n\t\t\t\t: state === \"reconnecting\"\n\t\t\t\t\t? s.reconnecting\n\t\t\t\t\t: !connected\n\t\t\t\t\t\t? (message ?? s.notConnected)\n\t\t\t\t\t\t: (signIn ??\n\t\t\t\t\t\t\t(renewed\n\t\t\t\t\t\t\t\t? s.newAddressDone\n\t\t\t\t\t\t\t\t: appName !== undefined\n\t\t\t\t\t\t\t\t\t? format(s.readyApp, { app: appName })\n\t\t\t\t\t\t\t\t\t: s.readyPage));\n\t\tstatus.hidden = connectedView;\n\n\t\t// The address, its help and New address.\n\t\tconst addressShownBefore = !addressBox.hidden;\n\t\tif (shown && address.value !== session.address) {\n\t\t\taddress.value = session.address;\n\t\t\tresetCopy();\n\t\t}\n\t\tif (shown) renderSteps(session);\n\t\taddressBox.hidden = help.hidden = freshBox.hidden = !shown;\n\t\tfresh.disabled = !connected;\n\t\tquestion.hidden = !asking;\n\t\tif (asking)\n\t\t\tquestionText.textContent = format(\n\t\t\t\tone ? s.newAddressQuestionOne : s.newAddressQuestionMany,\n\t\t\t\t{ apps: listOf(names, s) },\n\t\t\t);\n\t\tconst hasCode = renderCode(paired);\n\t\tcodeLine.hidden = oidc || !hasCode || !connected;\n\t\tsignInLine.hidden = !oidc || mcp.identity !== \"bound\";\n\n\t\tsetupToggle.hidden = !connectedView;\n\t\tsetupToggle.setAttribute(\"aria-expanded\", String(expanded));\n\t\tsetup.hidden = connectedView && !expanded;\n\t\tcopy.classList.toggle(\"tab-mcp-primary\", !connectedView);\n\n\t\t// The connected apps; only the relay can revoke, so only while connected.\n\t\tfor (const [id, { item }] of items) {\n\t\t\tif (ids.has(id)) continue;\n\t\t\titem.remove();\n\t\t\titems.delete(id);\n\t\t}\n\t\tgrants.forEach((grant, i) => {\n\t\t\tlet entry = items.get(grant.grantId);\n\t\t\tif (entry === undefined) {\n\t\t\t\tentry = appItem(grant);\n\t\t\t\titems.set(grant.grantId, entry);\n\t\t\t}\n\t\t\tentry.disconnect.disabled = !connected;\n\t\t\tconst tools = allowed.list(grant.grantId);\n\t\t\tentry.allowedBox.hidden = tools.length === 0;\n\t\t\tentry.allowedText.textContent = format(s.runsWithoutAsking, {\n\t\t\t\ttools: tools.map(visible).join(\", \"),\n\t\t\t});\n\t\t\tif (appList.children[i] !== entry.item)\n\t\t\t\tappList.insertBefore(entry.item, appList.children[i] ?? null);\n\t\t});\n\t\tappsNote.textContent = connected ? (appsProblem ?? \"\") : s.disconnectNote;\n\t\tappsNote.hidden = connected && appsProblem === undefined;\n\t\tapps.hidden = grants.length === 0;\n\n\t\t// The note is about the code: only while one is shown and none connected.\n\t\tcloseNote.hidden = connectedView || codeLine.hidden;\n\t\tclose.hidden = connectedView;\n\t\tdone.hidden = !connectedView;\n\t\tretry.hidden =\n\t\t\trenewing || (state !== \"disconnected\" && state !== \"reconnecting\");\n\n\t\t// Focus never stays on a control that was hidden or removed; from the\n\t\t// New address question that closed, back to New address.\n\t\tif (\n\t\t\tfocused !== null &&\n\t\t\tfocused !== dialog &&\n\t\t\tfocused !== doc.body &&\n\t\t\t(!focused.isConnected ||\n\t\t\t\t(dialog.contains(focused) && focused.closest(\"[hidden]\") !== null))\n\t\t)\n\t\t\t(question.contains(focused) && !freshBox.hidden\n\t\t\t\t? fresh\n\t\t\t\t: closer()\n\t\t\t).focus();\n\t\t// The address showed only now: start there (or at Done), or, after a\n\t\t// New address, at its Copy.\n\t\telse if (doc.activeElement === dialog && (connectedView || shown))\n\t\t\tstart().focus();\n\t\telse if (\n\t\t\trenewed &&\n\t\t\tshown &&\n\t\t\t!addressShownBefore &&\n\t\t\tdoc.activeElement === close\n\t\t)\n\t\t\tcopy.focus();\n\t\tif (paired && connectedView)\n\t\t\tannounce(`${successTitle.textContent}. ${successNext.textContent}`);\n\t};\n\n\tconst askNewAddress = () => {\n\t\tif (mcp.state !== \"connected\") return;\n\t\tif (mcp.grants.length === 0) {\n\t\t\tgetNewAddress();\n\t\t\treturn;\n\t\t}\n\t\tasking = true;\n\t\trender();\n\t\tcancelNew.focus(); // the safe choice is the default\n\t};\n\tconst getNewAddress = () => {\n\t\trenewing = true;\n\t\trenewed = false;\n\t\t// Focus moves before the focused control is hidden.\n\t\tclose.focus();\n\t\tasking = false;\n\t\trender();\n\t\t// Called from the click, so the reconnect has the user action it needs.\n\t\tmcp.newAddress().then(\n\t\t\t() => {\n\t\t\t\trenewing = false;\n\t\t\t\trenewed = true;\n\t\t\t\trender();\n\t\t\t\t// At its Copy once the new address shows (with identity binding\n\t\t\t\t// maybe only later: `render()` moves it then).\n\t\t\t\tif (!addressBox.hidden) copy.focus();\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\trenewing = false;\n\t\t\t\tmessage = connectFailure(error, s);\n\t\t\t\trender();\n\t\t\t\tcloser().focus();\n\t\t\t},\n\t\t);\n\t};\n\n\t// A refusal that stops reconnecting comes as `error` (with its `reason`)\n\t// just before the `statechange` to `disconnected`: that says why it stopped.\n\tlet stoppedBy: unknown;\n\tlet wasReconnecting = mcp.state === \"reconnecting\";\n\tconst onError = (event: CustomEvent<{ error: Error }>) => {\n\t\tconst { error } = event.detail;\n\t\tif (wasReconnecting && (error as { reason?: unknown }).reason !== undefined)\n\t\t\tstoppedBy = error;\n\t};\n\tconst onState = (event: CustomEvent<StateChangeDetail>) => {\n\t\tconst { state, reason } = event.detail;\n\t\tif (reason !== undefined && reason !== \"new_address\") {\n\t\t\tmessage = disconnectedText(reason, s);\n\t\t\trenewed = false;\n\t\t}\n\t\t// Refused, or ended by the page (`disconnect()`) while it waited.\n\t\tif (state === \"disconnected\" && wasReconnecting)\n\t\t\tmessage =\n\t\t\t\tstoppedBy === undefined ? s.disconnected : connectFailure(stoppedBy, s);\n\t\twasReconnecting = state === \"reconnecting\";\n\t\tstoppedBy = undefined;\n\t\trender();\n\t};\n\n\t// The address was taken over: the notice says so instead of this dialog.\n\tconst onReplaced = () => dialog.close();\n\twatchReplaced(mcp, doc, ui);\n\tconst stopAllowed = allowed.onChange(render);\n\tmcp.addEventListener(\"statechange\", onState);\n\tmcp.addEventListener(\"pairingcode\", render);\n\tmcp.addEventListener(\"grantschange\", render);\n\tmcp.addEventListener(\"identitychange\", render);\n\tmcp.addEventListener(\"error\", onError);\n\tmcp.addEventListener(\"replaced\", onReplaced);\n\tdoc.body.append(dialog);\n\tmcp.startPairing();\n\trender();\n\tconnecting.then(render, (error: unknown) => {\n\t\tmessage = connectFailure(error, s);\n\t\trender();\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tdialog.addEventListener(\n\t\t\t\"close\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(usedTimer);\n\t\t\t\tmcp.stopPairing();\n\t\t\t\tstopAllowed();\n\t\t\t\tmcp.removeEventListener(\"statechange\", onState);\n\t\t\t\tmcp.removeEventListener(\"pairingcode\", render);\n\t\t\t\tmcp.removeEventListener(\"grantschange\", render);\n\t\t\t\tmcp.removeEventListener(\"identitychange\", render);\n\t\t\t\tmcp.removeEventListener(\"error\", onError);\n\t\t\t\tmcp.removeEventListener(\"replaced\", onReplaced);\n\t\t\t\tdialog.remove();\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\tdialog.showModal();\n\t\t// Start at Done once connected, else at the address's Copy; until the\n\t\t// address is there, at the dialog itself (its title is read out), not\n\t\t// at Close.\n\t\tif (connectedView || !addressBox.hidden) start().focus();\n\t\telse dialog.focus();\n\t});\n}\n"
6
6
  ],
7
7
  "mappings": ";;;;;;;;;;;;;;;;;;;;;AAmCA,SAAS,SAAS,CAAC,QAA0B,GAA4B;AAAA,EACxE,OAAO,CAAC,GAAG,IAAI,IAAI,OAAO,IAAI,CAAC,MAAM,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;AAAA;AAQhE,SAAS,cAAc,CAAC,OAAgB,GAA0B;AAAA,EACjE,QAAQ,KAAK,+BAA+B,KAAK;AAAA,EACjD,MAAM,SAAU,OAAgD;AAAA,EAChE,IAAI,WAAW;AAAA,IAAW,OAAO,EAAE;AAAA,EACnC,IAAI,WAAW;AAAA,IAAW,OAAO,EAAE;AAAA,EACnC,IAAI,WAAW;AAAA,IAAgB,OAAO,EAAE;AAAA,EACxC,OAAO,EAAE;AAAA;AAIV,SAAS,gBAAgB,CAAC,QAA0B,GAA0B;AAAA,EAC7E,Q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