@ractive-ch/tab-mcp-client 0.18.1 → 0.19.0-rc.2

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 (86) hide show
  1. package/CHANGELOG.md +175 -0
  2. package/README.md +360 -68
  3. package/allowed.d.ts +2 -2
  4. package/allowed.js.map +1 -1
  5. package/always-allowed.d.ts +15 -15
  6. package/cdn/allowed.min.js +2 -2
  7. package/cdn/allowed.min.js.map +2 -2
  8. package/cdn/confirm-ba3dkf9p.min.js +4 -0
  9. package/cdn/confirm-ba3dkf9p.min.js.map +10 -0
  10. package/cdn/connect-my0pbqd7.min.js +6 -0
  11. package/cdn/connect-my0pbqd7.min.js.map +12 -0
  12. package/cdn/connection-yf2x9zz2.min.js +17 -0
  13. package/cdn/{connection-0xqwz17v.min.js.map → connection-yf2x9zz2.min.js.map} +5 -5
  14. package/cdn/strings.min.js +4 -0
  15. package/cdn/strings.min.js.map +9 -0
  16. package/cdn/{tab-mcp-client-2vx9mcww.min.js → tab-mcp-client-8r6h3wza.min.js} +9 -8
  17. package/cdn/tab-mcp-client-8r6h3wza.min.js.map +11 -0
  18. package/cdn/tab-mcp-client-nnxcwrxp.min.js +5 -0
  19. package/cdn/tab-mcp-client-nnxcwrxp.min.js.map +11 -0
  20. package/cdn/{tab-mcp-client-5j3brdf3.min.js → tab-mcp-client-q758jr4g.min.js} +4 -4
  21. package/cdn/tab-mcp-client-q758jr4g.min.js.map +10 -0
  22. package/cdn/tab-mcp-client.min.js +3 -3
  23. package/cdn/tab-mcp-client.min.js.map +4 -4
  24. package/cdn/webmcp-84k58gsw.min.js +4 -0
  25. package/cdn/webmcp-84k58gsw.min.js.map +11 -0
  26. package/{confirm-bqfdrx3f.js → confirm-hymzwx3b.js} +7 -5
  27. package/confirm-hymzwx3b.js.map +10 -0
  28. package/confirm.d.ts +2 -2
  29. package/{connect-ztsgybpq.js → connect-fhtjdmf3.js} +75 -37
  30. package/connect-fhtjdmf3.js.map +10 -0
  31. package/connect.d.ts +7 -6
  32. package/{connection-gang7f5x.js → connection-73fbg99k.js} +70 -8
  33. package/connection-73fbg99k.js.map +16 -0
  34. package/connection.d.ts +23 -2
  35. package/dialog.d.ts +19 -9
  36. package/extension.d.ts +373 -0
  37. package/extension.js +415 -0
  38. package/extension.js.map +10 -0
  39. package/handshake.d.ts +82 -0
  40. package/index-00p8b969.js +221 -0
  41. package/index-00p8b969.js.map +11 -0
  42. package/index-1tssct09.js +58 -0
  43. package/index-1tssct09.js.map +11 -0
  44. package/{index-c1c266tm.js → index-7qqhn3zv.js} +28 -110
  45. package/index-7qqhn3zv.js.map +10 -0
  46. package/index-s31xrfa2.js.map +1 -1
  47. package/index.d.ts +1 -1
  48. package/index.js +59 -64
  49. package/index.js.map +4 -4
  50. package/internal.d.ts +2 -0
  51. package/mcp.d.ts +5 -3
  52. package/package.json +11 -2
  53. package/protocol.d.ts +11 -1
  54. package/react.d.ts +11 -4
  55. package/react.js +57 -10
  56. package/react.js.map +5 -4
  57. package/secret.d.ts +1 -1
  58. package/setup.d.ts +4 -1
  59. package/setup.js +3 -2
  60. package/setup.js.map +1 -1
  61. package/strings.d.ts +149 -28
  62. package/strings.js +13 -0
  63. package/strings.js.map +9 -0
  64. package/tab-mcp.d.ts +30 -7
  65. package/text.d.ts +39 -0
  66. package/types.d.ts +76 -17
  67. package/webmcp-d2ec3v3g.js +221 -0
  68. package/webmcp-d2ec3v3g.js.map +11 -0
  69. package/webmcp.d.ts +17 -4
  70. package/cdn/confirm-d722a9eb.min.js +0 -4
  71. package/cdn/confirm-d722a9eb.min.js.map +0 -10
  72. package/cdn/connect-x6ws6wqt.min.js +0 -6
  73. package/cdn/connect-x6ws6wqt.min.js.map +0 -12
  74. package/cdn/connection-0xqwz17v.min.js +0 -17
  75. package/cdn/tab-mcp-client-2vx9mcww.min.js.map +0 -12
  76. package/cdn/tab-mcp-client-5j3brdf3.min.js.map +0 -10
  77. package/cdn/webmcp-khy4f5rj.min.js +0 -4
  78. package/cdn/webmcp-khy4f5rj.min.js.map +0 -10
  79. package/confirm-bqfdrx3f.js.map +0 -10
  80. package/connect-ztsgybpq.js.map +0 -10
  81. package/connection-gang7f5x.js.map +0 -16
  82. package/index-5jyqehpk.js +0 -63
  83. package/index-5jyqehpk.js.map +0 -11
  84. package/index-c1c266tm.js.map +0 -11
  85. package/webmcp-zq1enyz0.js +0 -57
  86. package/webmcp-zq1enyz0.js.map +0 -10
@@ -1,10 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/webmcp.ts"],
4
- "sourcesContent": [
5
- "/**\n * Mirroring the tools into the browser's own WebMCP (iteration 25, DEC-115,\n * DEC-119, DEC-143): with `webmcp: true`, each tool that is offered there is\n * also registered with `document.modelContext.registerTool()`, under its own\n * `AbortController`, aborted when the tool leaves the registry. A chunk of\n * its own (DEC-171), loaded by a `TabMcp` whose constructor found native\n * WebMCP (`nativeContext` in the core); a call loads the connection chunk,\n * which checks, confirms and runs it.\n */\n\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\n\n/** What the library uses of the browser's `ModelContext`. */\nexport interface ModelContext {\n\tregisterTool(\n\t\ttool: object,\n\t\toptions: { signal: AbortSignal; exposedTo: string[] | undefined },\n\t): unknown;\n}\n\n/** Runs a call of a mirrored tool; `signal` is the browser's, if it gives one. */\nexport type WebMcpCall = (\n\ttool: RegisteredTool,\n\tinput: unknown,\n\tsignal: unknown,\n) => Promise<unknown>;\n\n/** The WebMCP hints; the MCP-only ones are left out. */\nconst HINTS = [\n\t\"readOnlyHint\",\n\t\"untrustedContentHint\",\n\t\"consequentialHint\",\n\t\"debugging\",\n] as const;\n\n/**\n * Mirror `registry`'s tools into `context`, now and whenever the registry\n * changes: those whose `callers` list `\"webmcp\"`, and without `callers` those\n * not marked consequential, where MCP's `destructiveHint` counts as\n * `consequentialHint` (DEC-143, DEC-165). Every failure of the native `registerTool()`\n * stays here: warned once per name, the tool still offered through the relay.\n */\nexport function mirror(\n\tregistry: ToolRegistry,\n\tcontext: ModelContext,\n\tcall: WebMcpCall,\n): void {\n\tconst mirrors = new Map<RegisteredTool, AbortController>();\n\tconst warned = new Set<string>();\n\tconst sync = (): void => {\n\t\tfor (const [tool, controller] of mirrors) {\n\t\t\tif (registry.get(tool.name) === tool) continue;\n\t\t\tcontroller.abort();\n\t\t\tmirrors.delete(tool);\n\t\t}\n\t\tfor (const tool of registry.list()) {\n\t\t\tconst { annotations, callers } = tool;\n\t\t\tconst consequential =\n\t\t\t\tannotations.consequentialHint ?? annotations.destructiveHint;\n\t\t\t// The one place of the rule for WebMCP (the relay and a port: `toolsFor`).\n\t\t\tif (mirrors.has(tool) || !(callers?.includes(\"webmcp\") ?? !consequential))\n\t\t\t\tcontinue;\n\t\t\tconst controller = new AbortController();\n\t\t\tmirrors.set(tool, controller);\n\t\t\tconst hints: Record<string, boolean | undefined> = {\n\t\t\t\tconsequentialHint: consequential,\n\t\t\t};\n\t\t\tfor (const key of HINTS) hints[key] ??= annotations[key];\n\t\t\tconst { signal } = controller;\n\t\t\tPromise.resolve()\n\t\t\t\t// Not once unmirrored: whatever the browser does with an aborted\n\t\t\t\t// signal.\n\t\t\t\t.then(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tsignal.aborted ||\n\t\t\t\t\t\tcontext.registerTool(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\t\t\t// WebIDL dictionaries: `undefined` is the same as left out.\n\t\t\t\t\t\t\t\ttitle: tool.title,\n\t\t\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\t\t\tinputSchema: tool.inputSchema,\n\t\t\t\t\t\t\t\toutputSchema: tool.outputSchema,\n\t\t\t\t\t\t\t\tannotations: hints,\n\t\t\t\t\t\t\t\texecute: (input: unknown, options?: { signal?: unknown }) =>\n\t\t\t\t\t\t\t\t\tcall(tool, input, options?.signal),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{ signal, exposedTo: tool.exposedTo },\n\t\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\tif (signal.aborted) return; // unmirrored meanwhile\n\t\t\t\t\tif (warned.has(tool.name)) return;\n\t\t\t\t\twarned.add(tool.name);\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`tab-mcp: ${tool.name} is not offered through WebMCP:`,\n\t\t\t\t\t\terror,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t}\n\t};\n\tregistry.onChange(sync);\n\tsync();\n}\n"
6
- ],
7
- "mappings": "AA4BA,IAAM,EAAQ,CACb,eACA,uBACA,oBACA,WACD,EASO,SAAS,CAAM,CACrB,EACA,EACA,EACO,CACP,IAAM,EAAU,IAAI,IACd,EAAS,IAAI,IACb,EAAO,IAAY,CACxB,QAAY,EAAM,KAAe,EAAS,CACzC,GAAI,EAAS,IAAI,EAAK,IAAI,IAAM,EAAM,SACtC,EAAW,MAAM,EACjB,EAAQ,OAAO,CAAI,EAEpB,QAAW,KAAQ,EAAS,KAAK,EAAG,CACnC,IAAQ,cAAa,WAAY,EAC3B,EACL,EAAY,mBAAqB,EAAY,gBAE9C,GAAI,EAAQ,IAAI,CAAI,GAAK,EAAE,GAAS,SAAS,QAAQ,GAAK,CAAC,GAC1D,SACD,IAAM,EAAa,IAAI,gBACvB,EAAQ,IAAI,EAAM,CAAU,EAC5B,IAAM,EAA6C,CAClD,kBAAmB,CACpB,EACA,QAAW,KAAO,EAAO,EAAM,KAAS,EAAY,GACpD,IAAQ,UAAW,EACnB,QAAQ,QAAQ,EAGd,KACA,IACC,EAAO,SACP,EAAQ,aACP,CACC,KAAM,EAAK,KAEX,MAAO,EAAK,MACZ,YAAa,EAAK,YAClB,YAAa,EAAK,YAClB,aAAc,EAAK,aACnB,YAAa,EACb,QAAS,CAAC,EAAgB,IACzB,EAAK,EAAM,EAAO,GAAS,MAAM,CACnC,EACA,CAAE,SAAQ,UAAW,EAAK,SAAU,CACrC,CACF,EACC,MAAM,CAAC,IAAmB,CAC1B,GAAI,EAAO,QAAS,OACpB,GAAI,EAAO,IAAI,EAAK,IAAI,EAAG,OAC3B,EAAO,IAAI,EAAK,IAAI,EACpB,QAAQ,KACP,YAAY,EAAK,sCACjB,CACD,EACA,IAGJ,EAAS,SAAS,CAAI,EACtB,EAAK",
8
- "debugId": "33366FD84702071E64756E2164756E21",
9
- "names": []
10
- }
@@ -1,10 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/confirm.ts"],
4
- "sourcesContent": [
5
- "/**\n * The confirmation of consequential tools, loaded on demand: a `<dialog>`\n * per call, one shown at a time per document, and Always allow (or Allow\n * until reload) for the tools a user allows (`always-allowed.ts`).\n */\n\nimport { allowedFor, type ConfirmHost } from \"./always-allowed.ts\";\nimport {\n\tbutton,\n\tclientLabel,\n\tel,\n\tfill,\n\tformat,\n\tnewDialog,\n\tstringsOf,\n\tvisible,\n} from \"./dialog.ts\";\nimport type { DialogStrings } from \"./strings.ts\";\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type {\n\tConfirmAnswer,\n\tConfirmHandler,\n\tConfirmRequest,\n\tDialogOptions,\n} from \"./types.ts\";\n\n/**\n * The arguments as text, in full: what the user approves must be visible.\n * (The relay caps a request at 1 MiB, so this stays bounded.) Invisible and\n * direction characters are shown as escapes, so the text is still JSON for\n * the same arguments; the tool gets them unchanged. `undefined` when they\n * cannot be shown, and then \"Allow\" is not offered.\n */\nfunction showArguments(args: Record<string, unknown>): string | undefined {\n\ttry {\n\t\treturn visible(JSON.stringify(args, null, 2));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * How long \"Allow\" stays disabled after the confirmation is shown, while the\n * page is visible and focused (CU 17: a constant; tests pass `allowDelayMs`).\n */\nexport const ALLOW_DELAY_MS = 750;\n\n/** The user's answer: \"always\" allows this tool for this AI app (Always allow, or until reload). */\nexport type DialogAnswer = \"allow\" | \"always\" | \"deny\";\n\n/** Arguments up to this many characters are read out with the question. */\nconst DESCRIBED_ARGUMENTS = 500;\n\n/** Options of `confirmDialog`. */\nexport interface ConfirmDialogOptions {\n\t/** Tests only: another delay than {@link ALLOW_DELAY_MS}. */\n\tallowDelayMs?: number | undefined;\n\t/**\n\t * Offer a third button: `true` \"Always allow\" (kept until the app is\n\t * disconnected), `\"until-reload\"` \"Allow until reload\" (kept in memory).\n\t */\n\talwaysAllow?: boolean | \"until-reload\" | undefined;\n\t/** Asked when a waiting call's turn comes: `true` answers \"allow\" unseen. */\n\tallowedNow?: () => boolean;\n\tstrings?: DialogStrings;\n}\n\n/**\n * The confirmations of one document: one is shown at a time, the others\n * wait in order, so that the click that answered one cannot answer the next\n * (each starts its own delay when it is shown).\n */\ninterface ConfirmQueue {\n\tshown: boolean;\n\twaiting: (() => void)[];\n\t/** Updates the shown dialog's line about the calls that wait. */\n\tchanged?: (() => void) | undefined;\n}\n\nconst queues = new WeakMap<Document, ConfirmQueue>();\n\n/**\n * Ask whether a consequential tool may run. \"Always allow\" (or \"Allow until\n * reload\") is offered only with `alwaysAllow` (DEC-096, DEC-200); never\n * \"allow everything\": that is a deliberate act in the connect dialog, not\n * an answer to one question. One confirmation is shown at a time per\n * document; the others wait their turn, and a call cancelled while it waits\n * is never shown. \"Allow\" and \"Always allow\" stay disabled until the\n * page has been visible and focused for 750 ms while the dialog is open and\n * is the top one, so a click meant for the page, the click that brings the\n * tab or window back, or the one that closed another dialog, cannot\n * approve; leaving the page disables them again. They also wait until the\n * arguments have been scrolled to their end. Before the delay has run out,\n * Enter or Space on a button and Escape are ignored, so typing meant for the\n * page cannot refuse either. Everything else (Don't allow, Escape, an\n * aborted call) is \"deny\". `allowedNow` is asked when a waiting call's turn\n * comes: `true` (the user allowed it meanwhile) answers \"allow\"\n * without showing it.\n */\nexport function confirmDialog(\n\trequest: ConfirmRequest,\n\tdoc: Document,\n\toptions: ConfirmDialogOptions = {},\n): Promise<DialogAnswer> {\n\tif (request.signal.aborted) return Promise.resolve(\"deny\");\n\tlet queue = queues.get(doc);\n\tif (queue === undefined) {\n\t\tqueue = { shown: false, waiting: [] };\n\t\tqueues.set(doc, queue);\n\t}\n\tconst q = queue;\n\t/** The shown confirmation closed: the next one, if any. */\n\tconst next = () => {\n\t\tconst start = q.waiting.shift();\n\t\tq.shown = start !== undefined;\n\t\tstart?.();\n\t\tq.changed?.();\n\t};\n\tconst show = () => {\n\t\ttry {\n\t\t\treturn showConfirm(request, doc, options, q, next);\n\t\t} catch (error) {\n\t\t\tnext(); // not shown: the queue goes on\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t};\n\tif (!q.shown) {\n\t\tq.shown = true;\n\t\treturn show();\n\t}\n\treturn new Promise((resolve) => {\n\t\tconst start = () => {\n\t\t\trequest.signal.removeEventListener(\"abort\", onAbort);\n\t\t\tif (options.allowedNow?.() === true) {\n\t\t\t\tresolve(\"allow\");\n\t\t\t\tnext();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(show());\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tq.waiting.splice(q.waiting.indexOf(start), 1);\n\t\t\tq.changed?.();\n\t\t\tresolve(\"deny\");\n\t\t};\n\t\trequest.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tq.waiting.push(start);\n\t\tq.changed?.();\n\t});\n}\n\n/** `confirmDialog` once it is this request's turn; calls `next` when it closes. */\nfunction showConfirm(\n\trequest: ConfirmRequest,\n\tdoc: Document,\n\toptions: ConfirmDialogOptions,\n\tqueue: ConfirmQueue,\n\tnext: () => void,\n): Promise<DialogAnswer> {\n\tconst s = options.strings ?? stringsOf(undefined);\n\tconst delay = options.allowDelayMs ?? ALLOW_DELAY_MS;\n\tconst tool = request.tool.title ?? request.tool.name;\n\tconst client = clientLabel(request.client, s);\n\tconst names = { tool, client };\n\tconst { dialog, id } = newDialog(\n\t\tdoc,\n\t\t\"tab-mcp-confirm\",\n\t\ts,\n\t\t...fill(doc, s.confirmTitle, names),\n\t);\n\tconst waiting = el(doc, \"p\", { className: \"tab-mcp-waiting\" });\n\tconst showWaiting = () => {\n\t\tconst n = queue.waiting.length;\n\t\twaiting.hidden = n === 0;\n\t\twaiting.textContent =\n\t\t\tn === 1 ? s.waitingOne : format(s.waitingMany, { n: String(n) });\n\t};\n\tqueue.changed = showWaiting;\n\tshowWaiting();\n\t// The safe choice is the default: focused, and the one that stands out.\n\tconst deny = button(\n\t\tdoc,\n\t\ts.deny,\n\t\t() => dialog.close(\"deny\"),\n\t\t\"tab-mcp-deny\",\n\t\t\"primary\",\n\t);\n\tconst approving = (text: string, answer: DialogAnswer, className: string) => {\n\t\tconst node = button(\n\t\t\tdoc,\n\t\t\ttext,\n\t\t\t() => {\n\t\t\t\tif (!node.disabled) dialog.close(answer);\n\t\t\t},\n\t\t\tclassName,\n\t\t);\n\t\treturn node;\n\t};\n\t// The approving buttons: Allow, and Always allow (or Allow until reload)\n\t// when the page offers it, saying how long it lasts.\n\tconst approve = [approving(s.allow, \"allow\", \"tab-mcp-allow\")];\n\tconst extra: HTMLElement[] = [];\n\tconst mode = options.alwaysAllow;\n\tif (mode === true || mode === \"until-reload\") {\n\t\tconst kept = mode === true;\n\t\t// Left of Allow: not where most platforms put the default (CU 11).\n\t\tapprove.unshift(\n\t\t\tapproving(\n\t\t\t\tkept ? s.alwaysAllow : s.allowUntilReload,\n\t\t\t\t\"always\",\n\t\t\t\t\"tab-mcp-always\",\n\t\t\t),\n\t\t);\n\t\textra.push(\n\t\t\tel(\n\t\t\t\tdoc,\n\t\t\t\t\"p\",\n\t\t\t\t{ className: \"tab-mcp-always-note\" },\n\t\t\t\t...fill(doc, kept ? s.alwaysAllowNote : s.allowUntilReloadNote, names),\n\t\t\t),\n\t\t);\n\t}\n\tconst actions = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-actions\" },\n\t\tdeny,\n\t\t...approve.flatMap((b) => [\" \", b]),\n\t);\n\t// Approving needs both: the delay ran out while the user saw the page\n\t// (`settled`), and the arguments were seen to their end (`seen`).\n\tlet settled = false;\n\tlet seen = false;\n\tconst enable = () => {\n\t\tfor (const b of approve) b.disabled = !(settled && seen);\n\t};\n\tenable();\n\tconst shown = showArguments(request.arguments);\n\tconst args = el(doc, \"pre\", {\n\t\tclassName: \"tab-mcp-arguments\",\n\t\tid: `${id}-arguments`,\n\t\ttext: shown ?? s.argumentsHidden,\n\t});\n\tif (shown === undefined) {\n\t\tfor (const node of [...approve, ...extra]) node.hidden = true;\n\t}\n\targs.dir = \"ltr\";\n\t// Inline, so the arguments stay readable in full without the stylesheet:\n\t// wrapped (also a long word, at 360 px), scrolling when long.\n\targs.style.setProperty(\"white-space\", \"pre-wrap\");\n\targs.style.setProperty(\"overflow-wrap\", \"anywhere\");\n\targs.style.setProperty(\n\t\t\"max-height\",\n\t\t\"var(--tab-mcp-arguments-height, min(50vh, 24rem))\",\n\t);\n\targs.style.setProperty(\"overflow\", \"auto\");\n\targs.hidden = Object.keys(request.arguments).length === 0;\n\t// The caller chooses the order of the keys, so what matters may come\n\t// last: below the end of the box, the user is told, and Allow waits.\n\tconst scrollNote = el(doc, \"p\", {\n\t\tclassName: \"tab-mcp-scroll-note\",\n\t\ttext: s.scrollToAllow,\n\t});\n\tscrollNote.hidden = true;\n\tconst who = el(\n\t\tdoc,\n\t\t\"p\",\n\t\t{ id: `${id}-who` },\n\t\t...fill(doc, s.confirmWho, names),\n\t);\n\tdialog.setAttribute(\n\t\t\"aria-describedby\",\n\t\tshown !== undefined && !args.hidden && shown.length <= DESCRIBED_ARGUMENTS\n\t\t\t? `${who.id} ${args.id}`\n\t\t\t: who.id,\n\t);\n\tdialog.append(\n\t\twho,\n\t\tel(doc, \"p\", {\n\t\t\tclassName: \"tab-mcp-description\",\n\t\t\ttext: request.tool.description,\n\t\t}),\n\t\targs,\n\t\tscrollNote,\n\t\tactions,\n\t\t...extra,\n\t\twaiting,\n\t);\n\tdoc.body.append(dialog);\n\tconst view = doc.defaultView;\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => dialog.close(\"deny\");\n\t\trequest.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t// In a hidden tab, the tab's title says that the page asks (CU 9): the\n\t\t// AI app waits meanwhile. Put back when the tab is shown or the dialog\n\t\t// closes, unless the page changed its title since.\n\t\tlet title: { page: string; shown: string } | undefined;\n\t\tconst untitle = () => {\n\t\t\tif (title !== undefined && doc.title === title.shown)\n\t\t\t\tdoc.title = title.page;\n\t\t\ttitle = undefined;\n\t\t};\n\t\tconst retitle = () => {\n\t\t\tif (doc.visibilityState !== \"hidden\") untitle();\n\t\t\telse if (title === undefined) {\n\t\t\t\ttitle = { page: doc.title, shown: `${s.titlePrefix}${doc.title}` };\n\t\t\t\tdoc.title = title.shown;\n\t\t\t}\n\t\t};\n\t\t// The delay counts only while the user can see the page: tools are\n\t\t// called while the user is in the AI app, so the dialog often opens in\n\t\t// a background tab or window. Any change starts it again from zero\n\t\t// (DEC-087), and so does another dialog of the page that closes over\n\t\t// this one.\n\t\tconst arm = (event?: Event) => {\n\t\t\tif (event?.type === \"close\" && event.target === dialog) return;\n\t\t\tretitle();\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = undefined;\n\t\t\tsettled = false;\n\t\t\tenable();\n\t\t\tif (\n\t\t\t\tevent?.type === \"blur\" ||\n\t\t\t\tdoc.visibilityState === \"hidden\" ||\n\t\t\t\t!doc.hasFocus()\n\t\t\t)\n\t\t\t\treturn;\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\tsettled = true;\n\t\t\t\tenable();\n\t\t\t}, delay);\n\t\t};\n\t\t// Scrolled to the end, or nothing to scroll (also without layout).\n\t\tconst check = () => {\n\t\t\tif (seen) return;\n\t\t\tif (args.scrollTop + args.clientHeight < args.scrollHeight - 2) {\n\t\t\t\tscrollNote.hidden = false;\n\t\t\t\targs.tabIndex = 0; // to scroll it with the keyboard\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tseen = true;\n\t\t\tscrollNote.hidden = true;\n\t\t\tenable();\n\t\t};\n\t\t// Not answered by a key before the delay has run out.\n\t\tconst guard = (event: KeyboardEvent) => {\n\t\t\tif (settled) return;\n\t\t\tconst onButton = (event.target as Element | null)?.localName === \"button\";\n\t\t\tif (\n\t\t\t\tevent.key === \"Escape\" ||\n\t\t\t\t(onButton && (event.key === \"Enter\" || event.key === \" \"))\n\t\t\t)\n\t\t\t\tevent.preventDefault();\n\t\t};\n\t\tconst onCancel = (event: Event) => {\n\t\t\tif (!settled) event.preventDefault();\n\t\t};\n\t\tdoc.addEventListener(\"visibilitychange\", arm);\n\t\tdoc.addEventListener(\"close\", arm, true); // `close` does not bubble\n\t\tview?.addEventListener(\"focus\", arm);\n\t\tview?.addEventListener(\"blur\", arm);\n\t\tview?.addEventListener(\"resize\", check);\n\t\targs.addEventListener(\"scroll\", check);\n\t\tdialog.addEventListener(\"keydown\", guard);\n\t\tdialog.addEventListener(\"keyup\", guard);\n\t\tdialog.addEventListener(\"cancel\", onCancel);\n\t\tconst cleanup = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tuntitle();\n\t\t\tdoc.removeEventListener(\"visibilitychange\", arm);\n\t\t\tdoc.removeEventListener(\"close\", arm, true);\n\t\t\tview?.removeEventListener(\"focus\", arm);\n\t\t\tview?.removeEventListener(\"blur\", arm);\n\t\t\tview?.removeEventListener(\"resize\", check);\n\t\t\trequest.signal.removeEventListener(\"abort\", onAbort);\n\t\t\tdialog.remove();\n\t\t\tif (queue.changed === showWaiting) queue.changed = undefined;\n\t\t};\n\t\tdialog.addEventListener(\n\t\t\t\"close\",\n\t\t\t() => {\n\t\t\t\tconst value = dialog.returnValue;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value === \"allow\" || value === \"always\" ? value : \"deny\");\n\t\t\t\tnext();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\ttry {\n\t\t\tdialog.showModal();\n\t\t} catch (error) {\n\t\t\t// Never shown, so never closed: the queue must not wait for it.\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t\tnext();\n\t\t\treturn;\n\t\t}\n\t\tdeny.focus(); // the safe choice is the default\n\t\t// Counted from when the dialog is shown, not from when it was built.\n\t\tarm();\n\t\tcheck();\n\t});\n}\n\n/** Options of this chunk's `confirmInPage`. */\nexport interface ConfirmInPageOptions {\n\t/**\n\t * The third button, for an AI app through the relay (`kind: \"relay\"`):\n\t * `true` \"Always allow\" (kept in the `TabMcp`'s `storage`; \"Allow until\n\t * reload\" where it is kept in memory, as for a stand-in), `\"until-reload\"`\n\t * \"Allow until reload\", `false` none. Default: the `TabMcp`'s\n\t * `alwaysAllow`; none for a stand-in.\n\t */\n\talwaysAllow?: boolean | \"until-reload\" | undefined;\n\t/** Texts of the dialog, as `TabMcpOptions.ui`. */\n\tui?: DialogOptions | undefined;\n\t/** Tests only: another delay than {@link ALLOW_DELAY_MS}. */\n\tallowDelayMs?: number | undefined;\n}\n\n/**\n * `TabMcp.confirmInPage`: the confirmation, and the tools the user allowed\n * (`always-allowed.ts`), which run unasked. Only for an AI app through the\n * relay: an agent in the browser and a served port have no identity to\n * remember an answer for (DEC-115, DEC-124).\n *\n * Code that loads this chunk itself may pass a stand-in of its own for\n * `mcp` (`ConfirmHost`: `grants`, optionally `grantschange` events). Its\n * allowances live in memory, for its grants only, until the page is\n * reloaded, and exist only where the caller offers them with\n * `options.alwaysAllow`; without it nothing is allowed and nothing is kept.\n */\nexport function confirmInPage(\n\tmcp: TabMcp | ConfirmHost,\n\trequest: ConfirmRequest,\n\tdoc: Document,\n\toptions: ConfirmInPageOptions = {},\n): Promise<boolean> {\n\tconst { client } = request;\n\tconst strings = stringsOf(options.ui);\n\tconst { allowDelayMs } = options;\n\tif (client.kind !== \"relay\")\n\t\treturn confirmDialog(request, doc, { strings, allowDelayMs }).then(\n\t\t\t(answer) => answer === \"allow\",\n\t\t);\n\tconst { grantId } = client;\n\tconst allowed = allowedFor(mcp);\n\tconst allowedNow = () => allowed.allows(grantId, request.tool);\n\tif (allowedNow()) return Promise.resolve(true);\n\tconst offer = options.alwaysAllow ?? allowed.offered;\n\t// Asked again when its turn comes: the call before it in the queue may\n\t// have been allowed meanwhile.\n\treturn confirmDialog(request, doc, {\n\t\tstrings,\n\t\tallowDelayMs,\n\t\t// \"Always\" only where it outlives a reload.\n\t\talwaysAllow:\n\t\t\toffer !== false &&\n\t\t\t(offer === true && allowed.kept ? true : \"until-reload\"),\n\t\tallowedNow,\n\t}).then((answer) => {\n\t\t// Only while the grant is still there: a revoked app gets nothing\n\t\t// (`keep` checks).\n\t\tif (answer === \"always\") allowed.keep(grantId, request.tool);\n\t\treturn answer !== \"deny\";\n\t});\n}\n\n/**\n * The core's question about a consequential call: an AI app's call that the\n * user allowed runs without asking, with the dialog and with the page's own\n * `onConfirm` alike; any other goes to `onConfirm`, else to the dialog.\n * Only AI apps through the relay have a grant to allow for.\n */\nexport function confirmCall(\n\tmcp: TabMcp,\n\trequest: ConfirmRequest,\n\tonConfirm: ConfirmHandler | undefined,\n): Promise<ConfirmAnswer> {\n\tconst { client } = request;\n\tif (\n\t\tclient.kind === \"relay\" &&\n\t\tallowedFor(mcp).allows(client.grantId, request.tool)\n\t)\n\t\treturn Promise.resolve(true);\n\tif (onConfirm === undefined) return mcp.confirmInPage(request);\n\t// Anything but true or \"unanswered\" is a refusal.\n\treturn Promise.resolve()\n\t\t.then(() => onConfirm(request))\n\t\t.then((answer) => (answer === \"unanswered\" ? answer : answer === true));\n}\n"
6
- ],
7
- "mappings": ";;;;;;;;;;;;;;;;AAiCA,SAAS,aAAa,CAAC,MAAmD;AAAA,EACzE,IAAI;AAAA,IACH,OAAO,QAAQ,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA,IAC3C,MAAM;AAAA,IACP;AAAA;AAAA;AAQK,IAAM,iBAAiB;AAM9B,IAAM,sBAAsB;AA4B5B,IAAM,SAAS,IAAI;AAoBZ,SAAS,aAAa,CAC5B,SACA,KACA,UAAgC,CAAC,GACT;AAAA,E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U,UACT,UAAU,QAAQ,QAAQ,OAAO,OAAO;AAAA,IAC1C;AAAA,EACD,CAAC,EAAE,KAAK,CAAC,WAAW;AAAA,IAGnB,IAAI,WAAW;AAAA,MAAU,QAAQ,KAAK,SAAS,QAAQ,IAAI;AAAA,IAC3D,OAAO,WAAW;AAAA,GAClB;AAAA;AASK,SAAS,WAAW,CAC1B,KACA,SACA,WACyB;AAAA,EACzB,QAAQ,WAAW;AAAA,EACnB,IACC,OAAO,SAAS,WAChB,WAAW,GAAG,EAAE,OAAO,OAAO,SAAS,QAAQ,IAAI;AAAA,IAEnD,OAAO,QAAQ,QAAQ,IAAI;AAAA,EAC5B,IAAI,cAAc;AAAA,IAAW,OAAO,IAAI,cAAc,OAAO;AAAA,EAE7D,OAAO,QAAQ,QAAQ,EACrB,KAAK,MAAM,UAAU,OAAO,CAAC,EAC7B,KAAK,CAAC,WAAY,WAAW,eAAe,SAAS,WAAW,IAAK;AAAA;",
8
- "debugId": "8F959EEDFC1026A364756E2164756E21",
9
- "names": []
10
- }
@@ -1,10 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/connect.ts"],
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 { type Allowances, 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/** A switch: a checkbox with `role=\"switch\"` in its label, which a click on the text turns too. */\nfunction switchOf(\n\tdoc: Document,\n\ttext: HTMLElement,\n\tonToggle: (on: boolean) => void,\n): { label: HTMLLabelElement; input: HTMLInputElement } {\n\tconst input = el(doc, \"input\");\n\tinput.type = \"checkbox\";\n\tinput.setAttribute(\"role\", \"switch\");\n\tinput.addEventListener(\"change\", () => onToggle(input.checked));\n\tconst label = el(doc, \"label\", { className: \"tab-mcp-switch\" }, input, text);\n\treturn { label, input };\n}\n\n/**\n * Under a connected app, the switches for what runs without asking. With\n * `alwaysAllow` (`offered`): a switch per tool that asks (its title or\n * name, destructive ones marked) and \"Allow everything, no questions asked\"\n * with what it means. Without it, only what is allowed now, as switches that\n * can only be turned off (\"everything\" only while it is on): the user sees\n * what runs without asking and can end it, and is never offered more than\n * the page chose to offer. Tools allowed but not registered right now are\n * listed by name, also only to turn off. Each switch's accessible name names\n * the app: the list has one set per app. `render` updates it in place, so a\n * focused switch keeps its focus.\n */\nfunction allowedSwitches(\n\tdoc: Document,\n\ts: DialogStrings,\n\tallowed: Allowances,\n\tgrantId: string,\n\tapp: string,\n): { box: HTMLElement; render: () => void } {\n\tconst title = el(doc, \"p\", {\n\t\tclassName: \"tab-mcp-allowed-title\",\n\t\tid: `${nextId()}-allowed`,\n\t\ttext: s.runsWithoutAsking,\n\t});\n\tconst list = el(doc, \"div\", { className: \"tab-mcp-switches\" });\n\t// Turning on only where the page offers it; the store decides the rest.\n\tconst all = switchOf(\n\t\tdoc,\n\t\tel(doc, \"span\", { text: s.allowEverything }),\n\t\t(on) => {\n\t\t\tif (!on || allowed.offered) allowed.setEverything(grantId, on);\n\t\t\trender();\n\t\t},\n\t);\n\tall.label.classList.add(\"tab-mcp-everything\");\n\tall.input.setAttribute(\"aria-label\", format(s.allowEverythingApp, { app }));\n\tconst note = el(\n\t\tdoc,\n\t\t\"small\",\n\t\t{ className: \"tab-mcp-everything-note\", id: `${title.id}-note` },\n\t\t...fill(doc, s.allowEverythingNote, { app }),\n\t);\n\tall.input.setAttribute(\"aria-describedby\", note.id);\n\t// Filled when first shown: a page without it has no switches in its DOM.\n\tconst box = el(doc, \"div\", { className: \"tab-mcp-allowed\" });\n\tbox.setAttribute(\"role\", \"group\");\n\tbox.setAttribute(\"aria-labelledby\", title.id);\n\tconst switches = new Map<\n\t\tstring,\n\t\tReturnType<typeof switchOf> & {\n\t\t\tname: HTMLElement;\n\t\t\tmark: HTMLElement;\n\t\t\toffOnly: boolean;\n\t\t}\n\t>();\n\tconst render = () => {\n\t\tconst everything = allowed.everything(grantId);\n\t\tconst listed = allowed.list(grantId);\n\t\tconst on = new Set(listed);\n\t\tconst asking = new Map(allowed.tools().map((t) => [t.name, t]));\n\t\tconst rows: {\n\t\t\tname: string;\n\t\t\tshown: string;\n\t\t\tdestructive: boolean;\n\t\t\toffOnly: boolean;\n\t\t}[] = [];\n\t\tif (allowed.offered)\n\t\t\tfor (const t of asking.values())\n\t\t\t\trows.push({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tshown: t.title ?? t.name,\n\t\t\t\t\tdestructive: t.destructive,\n\t\t\t\t\toffOnly: false,\n\t\t\t\t});\n\t\tfor (const name of listed) {\n\t\t\tif (allowed.offered && asking.has(name)) continue;\n\t\t\tconst t = asking.get(name);\n\t\t\trows.push({\n\t\t\t\tname,\n\t\t\t\tshown: t?.title ?? name,\n\t\t\t\tdestructive: t?.destructive === true,\n\t\t\t\toffOnly: true,\n\t\t\t});\n\t\t}\n\t\tconst showAll = allowed.offered || everything;\n\t\tbox.hidden = rows.length === 0 && !everything;\n\t\tif (box.hidden) return;\n\t\tif (!box.hasChildNodes()) box.append(title, list, all.label, note);\n\t\tconst names = new Set(rows.map((r) => r.name));\n\t\tfor (const [name, { label }] of switches) {\n\t\t\tif (names.has(name)) continue;\n\t\t\tlabel.remove();\n\t\t\tswitches.delete(name);\n\t\t}\n\t\trows.forEach((row, i) => {\n\t\t\tlet entry = switches.get(row.name);\n\t\t\tif (entry === undefined) {\n\t\t\t\tconst name = el(doc, \"span\");\n\t\t\t\tconst mark = el(doc, \"small\", {\n\t\t\t\t\tclassName: \"tab-mcp-destructive\",\n\t\t\t\t\ttext: s.destructive,\n\t\t\t\t});\n\t\t\t\tconst made = switchOf(\n\t\t\t\t\tdoc,\n\t\t\t\t\tel(doc, \"span\", {}, name, \" \", mark),\n\t\t\t\t\t(turnedOn) => {\n\t\t\t\t\t\tif (!turnedOn) allowed.ask(grantId, row.name);\n\t\t\t\t\t\telse if (switches.get(row.name)?.offOnly === false)\n\t\t\t\t\t\t\tallowed.allow(grantId, row.name);\n\t\t\t\t\t\trender(); // also when nothing changed: the switch says the truth\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tentry = { ...made, name, mark, offOnly: row.offOnly };\n\t\t\t\tswitches.set(row.name, entry);\n\t\t\t}\n\t\t\tentry.offOnly = row.offOnly;\n\t\t\tconst shown = visible(row.shown);\n\t\t\tentry.name.textContent = shown;\n\t\t\tentry.mark.hidden = !row.destructive;\n\t\t\tentry.input.setAttribute(\n\t\t\t\t\"aria-label\",\n\t\t\t\tformat(row.destructive ? s.allowDestructiveToolApp : s.allowToolApp, {\n\t\t\t\t\ttool: shown,\n\t\t\t\t\tapp,\n\t\t\t\t}),\n\t\t\t);\n\t\t\t// What runs without asking now: also every tool under \"everything\".\n\t\t\tentry.input.checked = everything || on.has(row.name);\n\t\t\tentry.input.disabled = everything;\n\t\t\tif (list.children[i] !== entry.label)\n\t\t\t\tlist.insertBefore(entry.label, list.children[i] ?? null);\n\t\t});\n\t\tall.label.hidden = note.hidden = !showAll;\n\t\tall.input.checked = everything;\n\t};\n\treturn { box, render };\n}\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, for each, switches for the tools\n * that run without asking). 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 switches for what runs without asking.\n\tconst items = new Map<\n\t\tstring,\n\t\t{\n\t\t\titem: HTMLLIElement;\n\t\t\tdisconnect: HTMLButtonElement;\n\t\t\trenderAllowed: () => void;\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 switches = allowedSwitches(doc, s, allowed, grant.grantId, app);\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\tswitches.box,\n\t\t);\n\t\treturn { item, disconnect, renderAllowed: switches.render };\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\tentry.renderAllowed();\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
- ],
7
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAS,QAAQ,CAChB,KACA,MACA,UACuD;AAAA,EACvD,MAAM,QAAQ,GAAG,KAAK,OAAO;AAAA,EAC7B,MAAM,OAAO;AAAA,EACb,MAAM,aAAa,QAAQ,QAAQ;AAAA,EACnC,MAAM,iBAAiB,UAAU,MAAM,SAAS,MAAM,OAAO,CAAC;AAAA,EAC9D,MAAM,QAAQ,GAAG,KAAK,SAAS,EAAE,WAAW,iBAAiB,GAAG,OAAO,IAAI;AAAA,EAC3E,OAAO,EAAE,OAAO,MAAM;AAAA;AAevB,SAAS,eAAe,CACvB,KACA,GACA,SACA,SACA,KAC2C;AAAA,EAC3C,MAAM,QAAQ,GAAG,KAAK,KAAK;AAAA,IAC1B,WAAW;AAAA,IACX,IAAI,GAAG,OAAO;AAAA,IACd,MAAM,EAAE;AAAA,EACT,CAAC;AAAA,EACD,MAAM,OAAO,GAAG,KAAK,OAAO,EAAE,WAAW,mBAAmB,CAAC;AAAA,EAE7D,MAAM,MAAM,SACX,KACA,GAAG,KAAK,QAAQ,EAAE,MAAM,EAAE,gBAAgB,CAAC,GAC3C,CAAC,OAAO;AAAA,IACP,IAAI,CAAC,MAAM,QAAQ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O,UAAU;AAAA,IAIjB,IAAI,iBAAiB,CAAC,WAAW;AAAA,MAAQ,MAAM,EAAE,MAAM;AAAA,IACvD;AAAA,MAAK,OAAO,MAAM;AAAA,GAClB;AAAA;",
8
- "debugId": "90A68AE264A1104964756E2164756E21",
9
- "names": []
10
- }
@@ -1,16 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/icons.ts", "../src/mcp.ts", "../src/mapping.ts", "../src/protocol.ts", "../src/serve.ts", "../src/address.ts", "../src/connection.ts"],
4
- "sourcesContent": [
5
- "/**\n * The page's icons for `serverInfo.icons` (MCP `Icon`): the AI app may show\n * them for this page's connector. Loaded with the connection, not the core.\n */\n\nimport type { Icon } from \"./types.ts\";\n\n/** At most this many icons; a URL up to 2 KiB, a `data:` URI up to 16 KiB. */\nconst MAX_ICONS = 8;\nconst MAX_URL = 2048;\nconst MAX_DATA = 16_384;\nconst SIZE = /^(?:\\d{1,4}x\\d{1,4}|any)$/;\n\n/**\n * An icon worth sending, with clean fields: an http(s) URL (rendering an SVG\n * safely is the AI app's job, as MCP says), or a raster `data:` URI; never\n * an inline SVG, which the app might put into its own page.\n */\nfunction clean(icon: Icon): Icon | undefined {\n\tconst { src, mimeType, sizes, theme } = icon;\n\tif (typeof src !== \"string\") return undefined;\n\tconst url = /^https?:/i.test(src) && src.length <= MAX_URL;\n\tconst data =\n\t\t/^data:image\\/(?:png|jpeg|gif|webp|x-icon|vnd\\.microsoft\\.icon)[;,]/i.test(\n\t\t\tsrc,\n\t\t) && src.length <= MAX_DATA;\n\tif (!url && !data) return undefined;\n\tconst out: Icon = { src };\n\tif (typeof mimeType === \"string\" && /^image\\/[\\w.+-]+$/i.test(mimeType)) {\n\t\tout.mimeType = mimeType.toLowerCase();\n\t}\n\tconst valid = Array.isArray(sizes)\n\t\t? sizes.map((s) => String(s).toLowerCase()).filter((s) => SIZE.test(s))\n\t\t: [];\n\tif (valid.length > 0) out.sizes = valid;\n\tif (theme === \"light\" || theme === \"dark\") out.theme = theme;\n\treturn out;\n}\n\n/** Icons as given (`server.icons`), cleaned and capped. */\nexport function cleanIcons(icons: readonly Icon[]): Icon[] {\n\tconst out: Icon[] = [];\n\tfor (const icon of icons) {\n\t\tconst c =\n\t\t\ttypeof icon === \"object\" && icon !== null ? clean(icon) : undefined;\n\t\tif (c !== undefined) out.push(c);\n\t\tif (out.length === MAX_ICONS) break;\n\t}\n\treturn out;\n}\n\n/**\n * The document's `<link rel=\"icon\">` and `<link rel=\"apple-touch-icon\">`,\n * with their `type`, `sizes` and a `prefers-color-scheme` media query as the\n * theme. Empty without a document.\n */\nexport function pageIcons(\n\tdoc: Document | undefined = globalThis.document,\n): Icon[] {\n\t// Icons are optional: whatever the document is, connecting goes on.\n\ttry {\n\t\tconst links = doc?.querySelectorAll<HTMLLinkElement>(\n\t\t\t'link[rel~=\"icon\" i], link[rel~=\"apple-touch-icon\" i]',\n\t\t);\n\t\treturn cleanIcons(\n\t\t\t// An empty href resolves to the page itself: no icon.\n\t\t\t[...(links ?? [])]\n\t\t\t\t.filter((link) => link.getAttribute(\"href\")?.trim())\n\t\t\t\t.map((link) => {\n\t\t\t\t\tconst icon: Icon = { src: link.href };\n\t\t\t\t\tif (link.type) icon.mimeType = link.type;\n\t\t\t\t\tconst sizes = link.getAttribute(\"sizes\");\n\t\t\t\t\tif (sizes) icon.sizes = sizes.trim().split(/\\s+/);\n\t\t\t\t\tconst scheme = /prefers-color-scheme:\\s*(light|dark)/i.exec(\n\t\t\t\t\t\tlink.media,\n\t\t\t\t\t);\n\t\t\t\t\tif (scheme) icon.theme = scheme[1]?.toLowerCase() as \"light\" | \"dark\";\n\t\t\t\t\treturn icon;\n\t\t\t\t}),\n\t\t);\n\t} catch {\n\t\treturn [];\n\t}\n}\n",
6
- "/**\n * The tab's MCP server: the stateless 2026-07-28 subset tab-mcp needs\n * (DEC-049), written for the page instead of bundling the SDK. It answers\n * `server/discover`, `tools/list`, `tools/call` (as SSE, DEC-020) and\n * `subscriptions/listen`, and applies the request checks of the 2026-07-28\n * Streamable HTTP transport (content type, JSON-RPC shape, `_meta` envelope,\n * `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name`). Status codes and error\n * codes follow the MCP TypeScript SDK's `createMcpHandler`; the conformance\n * tests compare the two.\n */\n\nimport {\n\tdereference,\n\ttype OutputUnit,\n\ttype Schema,\n\tvalidate as validateSchema,\n} from \"@cfworker/json-schema\";\nimport { cleanIcons } from \"./icons.ts\";\nimport {\n\tANNOTATIONS_META_KEY,\n\ttype CallToolResult,\n\terrorResult,\n\tmapAnnotations,\n\tmarkUntrusted,\n\tresultText,\n\tthrownResult,\n\ttoCallToolResult,\n\twebMcpValue,\n} from \"./mapping.ts\";\nimport type { GrantRef } from \"./protocol.ts\";\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\nimport type {\n\tConfirmAnswer,\n\tConfirmRequest,\n\tServerInfo,\n\tToolCallClient,\n\tToolCallEnd,\n\tToolCallOutcome,\n\tToolCallStart,\n} from \"./types.ts\";\n\nexport const MCP_PROTOCOL_VERSION = \"2026-07-28\";\nconst META_VERSION = \"io.modelcontextprotocol/protocolVersion\";\nconst META_CAPABILITIES = \"io.modelcontextprotocol/clientCapabilities\";\nconst META_CLIENT_INFO = \"io.modelcontextprotocol/clientInfo\";\nconst META_SERVER_INFO = \"io.modelcontextprotocol/serverInfo\";\nconst META_SUBSCRIPTION = \"io.modelcontextprotocol/subscriptionId\";\n\nconst HEADER_MISMATCH = -32020;\nconst UNSUPPORTED_VERSION = -32022;\n\n/** After the description of a consequential tool in `tools/list`. */\nexport const CONFIRMED_IN_TAB =\n\t\"The page may ask the user to allow each call, usually in the page's browser tab.\";\n\ntype Id = string | number;\ntype Json = Record<string, unknown>;\n\nexport interface ToolSource {\n\tlist(): RegisteredTool[];\n\tget(name: string): RegisteredTool | undefined;\n}\n\n/** What a tool call needs, through the relay or through WebMCP. */\nexport interface CallContext {\n\ttools: ToolSource;\n\t/** Ask the user before a consequential tool runs. */\n\tconfirm(request: ConfirmRequest): Promise<ConfirmAnswer>;\n\t/**\n\t * `confirm` is an own `onConfirm` (the page's, or a serve's), which may\n\t * ask anywhere: `tools/list` then does not say where (DEC-169).\n\t */\n\townConfirm?: boolean;\n\t/** Told about every call of a known tool, as it starts and as it ends. */\n\tobserve?: {\n\t\tstart(call: ToolCallStart): void;\n\t\tend(call: ToolCallEnd): void;\n\t};\n}\n\nexport interface McpHandlerOptions extends CallContext {\n\tserver: ServerInfo;\n\t/** The caller of a request, from its grant. */\n\tclient(grant: GrantRef): ToolCallClient;\n\t/**\n\t * The largest response body the relay passes on (`limits.maxBodyBytes`);\n\t * `undefined`: no limit. A larger tool result is answered as an error\n\t * result instead (CC 7).\n\t */\n\tmaxBodyBytes?: () => number | undefined;\n}\n\n/** Tool call ids, unique in the page. */\nlet lastCallId = 0;\n\n/** Checks arguments against a tool's input schema. */\nexport type ArgumentValidator = (args: unknown) => {\n\tvalid: boolean;\n\terrors: OutputUnit[];\n};\n\nconst compiled = new WeakMap<RegisteredTool, ArgumentValidator>();\n\n/**\n * The validator of a tool's input schema, built once per tool. Throws what\n * the validator would throw at call time: a `$ref` that does not resolve\n * (the validator resolves one only when an argument reaches it, against the\n * base of the nearest `$id`), an `$id` that is not a URL, a duplicate one.\n * `compileRegistry` makes the registry call it at registration (DEC-086).\n */\nexport function compileTool(tool: RegisteredTool): ArgumentValidator {\n\tconst known = compiled.get(tool);\n\tif (known !== undefined) return known;\n\tconst schema = tool.inputSchema as Schema;\n\tlet lookup: Record<string, Schema | boolean>;\n\ttry {\n\t\tlookup = dereference(schema);\n\t} catch (error) {\n\t\t// Only the first line: the validator appends the URIs it knows.\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthrow new Error(message.split(\"\\n\")[0]);\n\t}\n\tfor (const node of Object.values(lookup)) {\n\t\tif (typeof node !== \"object\" || node.$ref === undefined) continue;\n\t\tconst absolute = (node as { __absolute_ref__?: string }).__absolute_ref__;\n\t\tif (lookup[absolute ?? node.$ref] === undefined)\n\t\t\tthrow new Error(`$ref ${JSON.stringify(node.$ref)} does not resolve`);\n\t}\n\tconst validator: ArgumentValidator = (args) =>\n\t\tvalidateSchema(args, schema, \"2020-12\", lookup, false);\n\tcompiled.set(tool, validator);\n\treturn validator;\n}\n\nfunction schemaError(name: string, error: unknown, suffix = \"\"): TypeError {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn new TypeError(\n\t\t`registerTool: the inputSchema of ${name}: ${message}${suffix}`,\n\t);\n}\n\n/**\n * The validator is loaded (on `connect()`): compile the schemas of the tools\n * registered so far, before any AI app lists them, and from now on at\n * registration, so that `registerTool` rejects a schema the validator cannot\n * use. A tool registered before that it refuses is unregistered; the errors\n * are for the page's `error` event.\n */\nexport function compileRegistry(registry: ToolRegistry): TypeError[] {\n\tconst refused: TypeError[] = [];\n\tfor (const tool of registry.list()) {\n\t\ttry {\n\t\t\tcompileTool(tool);\n\t\t} catch (error) {\n\t\t\tregistry.remove(tool);\n\t\t\trefused.push(\n\t\t\t\tschemaError(tool.name, error, \"; the tool was unregistered\"),\n\t\t\t);\n\t\t}\n\t}\n\tregistry.setCompiler((tool) => {\n\t\ttry {\n\t\t\tcompileTool(tool);\n\t\t} catch (error) {\n\t\t\tthrow schemaError(tool.name, error);\n\t\t}\n\t});\n\treturn refused;\n}\n\n/** A deep copy for an event; the value itself when it cannot be cloned. */\nfunction copy<T>(value: T): T {\n\ttry {\n\t\treturn structuredClone(value);\n\t} catch {\n\t\treturn value;\n\t}\n}\n\nexport interface McpRequestContext {\n\tgrant: GrantRef;\n\t/** The body as text when the caller already has it. */\n\tbody?: string;\n}\n\nexport interface McpHandler {\n\thandle(request: Request, context: McpRequestContext): Promise<Response>;\n\t/** The tool list changed: tell the listen streams. */\n\ttoolsChanged(): void;\n\t/** End every listen stream (the session is over). */\n\tclose(): void;\n}\n\nconst encoder = new TextEncoder();\n\nfunction isObject(v: unknown): v is Json {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction json(status: number, value: unknown): Response {\n\treturn new Response(JSON.stringify(value), {\n\t\tstatus,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t});\n}\n\nfunction rpcError(\n\tstatus: number,\n\tid: Id | null,\n\tcode: number,\n\tmessage: string,\n\tdata?: unknown,\n): Response {\n\tconst error: Json = { code, message };\n\tif (data !== undefined) error[\"data\"] = data;\n\treturn json(status, { jsonrpc: \"2.0\", id, error });\n}\n\nfunction mismatch(id: Id | null, header: string, body: string): Response {\n\treturn rpcError(\n\t\t400,\n\t\tid,\n\t\tHEADER_MISMATCH,\n\t\t`Bad Request: the request headers and body disagree: ${body}`,\n\t\t{\n\t\t\tmismatch: { header, body },\n\t\t},\n\t);\n}\n\nfunction sseEvent(message: unknown): Uint8Array {\n\treturn encoder.encode(`event: message\\ndata: ${JSON.stringify(message)}\\n\\n`);\n}\n\nconst SSE_HEADERS = {\n\t\"content-type\": \"text/event-stream\",\n\t\"cache-control\": \"no-cache\",\n};\n\n/** `application/json`, with or without parameters. */\nfunction isJsonContentType(value: string | null): boolean {\n\treturn (\n\t\t(value ?? \"\").split(\";\")[0]?.trim().toLowerCase() === \"application/json\"\n\t);\n}\n\n/** Decode the `=?base64?…?=` sentinel of SEP-2243 headers; `undefined` if malformed. */\nexport function decodeHeaderValue(value: string): string | undefined {\n\tif (!(value.startsWith(\"=?base64?\") && value.endsWith(\"?=\"))) return value;\n\tconst b64 = value.slice(9, -2);\n\tif (\n\t\t!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(\n\t\t\tb64,\n\t\t)\n\t)\n\t\treturn undefined;\n\ttry {\n\t\tconst bin = atob(b64);\n\t\tconst bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));\n\t\treturn new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The first problem of a 2026-07-28 `_meta` envelope, or `undefined`. */\nfunction envelopeIssue(\n\tmeta: Json,\n): { key: string; problem: string } | undefined {\n\tif (!(META_VERSION in meta)) return { key: META_VERSION, problem: \"missing\" };\n\tif (!(META_CAPABILITIES in meta))\n\t\treturn { key: META_CAPABILITIES, problem: \"missing\" };\n\tif (typeof meta[META_VERSION] !== \"string\") {\n\t\treturn { key: META_VERSION, problem: \"expected a protocol version string\" };\n\t}\n\tif (!isObject(meta[META_CAPABILITIES]))\n\t\treturn { key: META_CAPABILITIES, problem: \"expected an object\" };\n\tconst info = meta[META_CLIENT_INFO];\n\tif (\n\t\tinfo !== undefined &&\n\t\t!(\n\t\t\tisObject(info) &&\n\t\t\ttypeof info[\"name\"] === \"string\" &&\n\t\t\ttypeof info[\"version\"] === \"string\"\n\t\t)\n\t) {\n\t\treturn { key: META_CLIENT_INFO, problem: \"expected {name, version}\" };\n\t}\n\treturn undefined;\n}\n\n/** Listen streams honour only the tool list (the tab has nothing else). */\nfunction honoured(params: Json): Json {\n\tconst requested = params[\"notifications\"];\n\treturn isObject(requested) && requested[\"toolsListChanged\"] === true\n\t\t? { toolsListChanged: true }\n\t\t: {};\n}\n\nfunction validate(tool: RegisteredTool, args: Json): string | undefined {\n\tlet outcome: ReturnType<ArgumentValidator>;\n\ttry {\n\t\toutcome = compileTool(tool)(args);\n\t} catch (error) {\n\t\t// Refused at registration through `TabMcp`; this is for any other registry.\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\treturn `The input schema of tool ${tool.name} cannot be used: ${message}`;\n\t}\n\tif (outcome.valid) return undefined;\n\tconst detail = outcome.errors\n\t\t.filter((e) => e.keyword !== \"properties\" && e.keyword !== \"$ref\")\n\t\t.map((e) => `${e.instanceLocation} ${e.error}`)\n\t\t.slice(0, 5)\n\t\t.join(\"; \");\n\treturn `Input validation error: Invalid arguments for tool ${tool.name}: ${detail || \"the arguments do not match the schema\"}`;\n}\n\n/**\n * How a call ended. `stop`: why it did not run to its end: invalid\n * arguments, declined by the user, not answered by the user, cancelled, or\n * its tool gone. `returned`: what `execute` returned.\n */\nexport interface CallRun {\n\toutcome: ToolCallOutcome;\n\tresult: CallToolResult;\n\tstop?: \"invalid\" | \"declined\" | \"unanswered\" | \"cancelled\" | \"gone\";\n\treturned?: { value: unknown };\n}\n\n/**\n * One call of a known tool, from an AI app through the relay or from an\n * agent in the browser through WebMCP: the `toolcall` and `toolcallend`\n * events around the argument check, the confirmation of a consequential\n * tool and `execute`. The one path for both callers, so they cannot drift.\n */\nexport async function runCall(\n\tcontext: CallContext,\n\ttool: RegisteredTool,\n\traw: Json,\n\tsignal: AbortSignal,\n\tclient: ToolCallClient,\n\t/**\n\t * Whether the caller can be sent this result: `undefined` if so, else an\n\t * error result to send instead. Before `toolcallend`, so that the event\n\t * says what the caller gets.\n\t */\n\tdeliverable?: (result: CallToolResult) => CallToolResult | undefined,\n): Promise<CallRun> {\n\t// Copies: a listener cannot change what the tool gets or the caller receives.\n\tconst call: ToolCallStart = {\n\t\tid: ++lastCallId,\n\t\ttool: tool.name,\n\t\targuments: copy(raw),\n\t\tclient: { ...client },\n\t};\n\tif (tool.title !== undefined) call.title = tool.title;\n\tconst started = Date.now();\n\tcontext.observe?.start(call);\n\t// Every start has its end, also when something fails outside the tool.\n\tlet run: CallRun = {\n\t\toutcome: \"error\",\n\t\tresult: errorResult(\"Internal error\"),\n\t};\n\ttry {\n\t\trun = await decideAndRun(context, tool, raw, signal, client);\n\t\t// The caller learns per result, not only from tools/list, that this\n\t\t// text is not the page's (DEC-166).\n\t\tif (tool.annotations.untrustedContentHint === true)\n\t\t\trun.result = markUntrusted(run.result);\n\t\tconst instead = signal.aborted ? undefined : deliverable?.(run.result);\n\t\tif (instead !== undefined) run = { outcome: \"error\", result: instead };\n\t} finally {\n\t\tcontext.observe?.end({\n\t\t\tid: call.id,\n\t\t\ttool: tool.name,\n\t\t\tclient: { ...client },\n\t\t\toutcome: run.outcome,\n\t\t\tresult: copy(run.result),\n\t\t\tdurationMs: Date.now() - started,\n\t\t});\n\t}\n\treturn run;\n}\n\n/** What the AI app reads when the user was asked and did not answer. */\nconst UNANSWERED = \"The user was asked and did not answer.\";\n\n/** Validate, confirm and run one call. */\nasync function decideAndRun(\n\tcontext: CallContext,\n\ttool: RegisteredTool,\n\traw: Json,\n\tsignal: AbortSignal,\n\tclient: ToolCallClient,\n): Promise<CallRun> {\n\tconst stopped = (\n\t\toutcome: ToolCallOutcome,\n\t\tmessage: string,\n\t\tstop: NonNullable<CallRun[\"stop\"]>,\n\t): CallRun => ({ outcome, result: errorResult(message), stop });\n\tconst invalid = validate(tool, raw);\n\tif (invalid !== undefined) return stopped(\"error\", invalid, \"invalid\");\n\t// Rejects once the call is cancelled (or timed out): the call ends then,\n\t// also when a question or a tool does not heed the signal, and what they\n\t// answer later is dropped (DEC-167).\n\tconst cancelled = new Promise<never>((_, reject) => {\n\t\tif (signal.aborted) reject(signal.reason);\n\t\tsignal.addEventListener(\"abort\", () => reject(signal.reason));\n\t});\n\tcancelled.catch(() => {});\n\tif (tool.annotations.consequentialHint === true) {\n\t\tconst question: ConfirmRequest = {\n\t\t\ttool: { name: tool.name, description: tool.description },\n\t\t\targuments: raw,\n\t\t\tclient,\n\t\t\tsignal,\n\t\t};\n\t\tif (tool.title !== undefined) question.tool.title = tool.title;\n\t\tlet answer: ConfirmAnswer = false;\n\t\ttry {\n\t\t\tanswer = await Promise.race([context.confirm(question), cancelled]);\n\t\t} catch {\n\t\t\tanswer = false; // a failing question is a refusal\n\t\t}\n\t\tif (answer !== true) {\n\t\t\tif (signal.aborted)\n\t\t\t\treturn stopped(\"cancelled\", \"The user declined\", \"cancelled\");\n\t\t\treturn answer === \"unanswered\"\n\t\t\t\t? stopped(\"unanswered\", UNANSWERED, \"unanswered\")\n\t\t\t\t: stopped(\"declined\", \"The user declined\", \"declined\");\n\t\t}\n\t}\n\tif (signal.aborted) return stopped(\"cancelled\", \"Cancelled\", \"cancelled\");\n\t// Unregistered (or replaced) while the user was asked: not the tool\n\t// the user allowed, or one the page still offers.\n\tif (context.tools.get(tool.name) !== tool)\n\t\treturn stopped(\"error\", \"The tool is no longer available\", \"gone\");\n\tlet run: CallRun;\n\ttry {\n\t\tconst value = await Promise.race([\n\t\t\ttool.execute(raw, { signal, client }),\n\t\t\tcancelled,\n\t\t]);\n\t\trun = {\n\t\t\toutcome: \"ok\",\n\t\t\tresult: toCallToolResult(value),\n\t\t\treturned: { value },\n\t\t};\n\t} catch (error) {\n\t\trun = { outcome: \"error\", result: thrownResult(error) };\n\t}\n\t// Cancelled is cancelled, however the tool answered the abort.\n\tif (signal.aborted)\n\t\treturn { ...run, outcome: \"cancelled\", stop: \"cancelled\" };\n\tif (run.result.isError === true) run.outcome = \"error\";\n\treturn run;\n}\n\n/**\n * A call from an agent in the browser (WebMCP) of the mirrored `tool`: the\n * same path as an AI app's call (`runCall`), its outcome as WebMCP has it.\n * Resolves with what `execute` returned, as `webMcpValue` maps it. Every\n * failure the agent should read resolves too, as `{ error: \"<message>\" }`:\n * invalid arguments, \"Don't allow\", a question not answered, a tool that is\n * gone, what `execute` threw, an `isError` result.\n * WebMCP hands the agent a rejection without its message (the draft: an\n * `OperationError`; Chrome 156: `UnknownError`), so the agent would learn\n * neither why nor what to change (DEC-120). Only a call the browser\n * cancelled rejects (`AbortError`): its caller has gone already.\n */\nexport async function webMcpCall(\n\tcontext: CallContext,\n\ttool: RegisteredTool,\n\tinput: unknown,\n\tsignal: unknown,\n): Promise<unknown> {\n\tconst failed = (error: string) => ({ error });\n\tconst gone = `The tool ${tool.name} is no longer available.`;\n\t// Gone already, e.g. refused by the validator just loaded: no call.\n\tif (context.tools.get(tool.name) !== tool) return failed(gone);\n\tif (!isObject(input)) return failed(\"The input must be an object.\");\n\tconst run = await runCall(\n\t\tcontext,\n\t\ttool,\n\t\tinput,\n\t\tsignal instanceof AbortSignal ? signal : new AbortController().signal,\n\t\t{ kind: \"webmcp\" },\n\t);\n\tif (run.stop === \"cancelled\")\n\t\tthrow new DOMException(\"Cancelled\", \"AbortError\");\n\tif (run.stop === \"declined\")\n\t\treturn failed(`The user did not allow ${tool.name} to run.`);\n\tif (run.stop === \"unanswered\")\n\t\treturn failed(`The user did not answer whether ${tool.name} may run.`);\n\tif (run.stop === \"gone\") return failed(gone);\n\tif (run.result.isError === true)\n\t\treturn failed(resultText(run.result) || \"The tool failed.\");\n\treturn webMcpValue(run.returned?.value);\n}\n\nexport function createMcpHandler(options: McpHandlerOptions): McpHandler {\n\tconst { tools, server } = options;\n\tconst serverInfo: Json = { name: server.name, version: server.version };\n\tif (server.title !== undefined) serverInfo[\"title\"] = server.title;\n\t// The icons only in server/discover: every other result carries\n\t// serverInfo too, and the app needs them once.\n\tconst icons = cleanIcons(server.icons ?? []);\n\tconst discoverInfo: Json =\n\t\ticons.length > 0 ? { ...serverInfo, icons } : serverInfo;\n\tconst listeners = new Set<{\n\t\tid: Id;\n\t\tsend(message: unknown): void;\n\t\tend(): void;\n\t}>();\n\tlet changeQueued = false;\n\n\tconst resultMeta = (extra: Json = {}) => ({\n\t\t...extra,\n\t\t[META_SERVER_INFO]: serverInfo,\n\t});\n\n\tfunction result(id: Id, value: Json, meta: Json = resultMeta()): Json {\n\t\treturn {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tresult: { ...value, resultType: \"complete\", _meta: meta },\n\t\t};\n\t}\n\n\tfunction listTools(): Json[] {\n\t\treturn tools.list().map((tool) => {\n\t\t\tconst entry: Json = { name: tool.name };\n\t\t\tif (tool.title !== undefined) entry[\"title\"] = tool.title;\n\t\t\t// The AI app waits while the page asks: it can tell the user where\n\t\t\t// (CU 9). Not with an own `onConfirm`, which may ask elsewhere (a\n\t\t\t// side panel, the site's chat; DEC-169). The tool's own description\n\t\t\t// is unchanged elsewhere.\n\t\t\tentry[\"description\"] =\n\t\t\t\ttool.annotations.consequentialHint === true && !options.ownConfirm\n\t\t\t\t\t? `${tool.description} ${CONFIRMED_IN_TAB}`\n\t\t\t\t\t: tool.description;\n\t\t\tentry[\"inputSchema\"] = tool.inputSchema;\n\t\t\tif (tool.outputSchema !== undefined)\n\t\t\t\tentry[\"outputSchema\"] = tool.outputSchema;\n\t\t\tconst { annotations, meta } = mapAnnotations(tool.annotations);\n\t\t\tif (annotations !== undefined) entry[\"annotations\"] = annotations;\n\t\t\tif (meta !== undefined) entry[\"_meta\"] = { [ANNOTATIONS_META_KEY]: meta };\n\t\t\treturn entry;\n\t\t});\n\t}\n\n\t/**\n\t * A call's outcome: a JSON-RPC error (`invalid`) or a result. Tagged, so\n\t * that a result's own keys never decide which (a tool may return any).\n\t */\n\ttype RunOutcome =\n\t\t| { kind: \"invalid\"; message: string }\n\t\t| { kind: \"result\"; result: CallToolResult };\n\n\tconst invalidParams = (message: string): RunOutcome => ({\n\t\tkind: \"invalid\",\n\t\tmessage,\n\t});\n\n\tasync function runTool(\n\t\tparams: Json,\n\t\tsignal: AbortSignal,\n\t\tgrant: GrantRef,\n\t\tdeliverable: (result: CallToolResult) => CallToolResult | undefined,\n\t): Promise<RunOutcome> {\n\t\tconst name = params[\"name\"];\n\t\tif (typeof name !== \"string\")\n\t\t\treturn invalidParams(\"Invalid params: name must be a string\");\n\t\tconst tool = tools.get(name);\n\t\tif (tool === undefined) return invalidParams(`Tool ${name} not found`);\n\t\tconst raw = params[\"arguments\"] ?? {};\n\t\tif (!isObject(raw))\n\t\t\treturn invalidParams(\"Invalid params: arguments must be an object\");\n\t\tconst run = await runCall(\n\t\t\toptions,\n\t\t\ttool,\n\t\t\traw,\n\t\t\tsignal,\n\t\t\toptions.client(grant),\n\t\t\tdeliverable,\n\t\t);\n\t\treturn { kind: \"result\", result: run.result };\n\t}\n\n\tfunction callTool(\n\t\tid: Id,\n\t\tparams: Json,\n\t\tsignal: AbortSignal,\n\t\tgrant: GrantRef,\n\t): Response {\n\t\t/** The answer's event; the tool's own `_meta` is kept, next to serverInfo. */\n\t\tconst answer = (value: CallToolResult): Uint8Array =>\n\t\t\tsseEvent(result(id, value, resultMeta(value._meta)));\n\t\t/** The event of the result checked last, so that it is encoded once. */\n\t\tlet checked: { result: CallToolResult; event: Uint8Array } | undefined;\n\t\t/** A result the caller cannot get: not JSON, or more than the relay passes on (CC 7). */\n\t\tconst deliverable = (value: CallToolResult): CallToolResult | undefined => {\n\t\t\tlet event: Uint8Array;\n\t\t\ttry {\n\t\t\t\tevent = answer(value);\n\t\t\t} catch {\n\t\t\t\t// e.g. a BigInt or a cycle inside a passed-through result\n\t\t\t\treturn errorResult(\"The tool returned a result that is not JSON.\");\n\t\t\t}\n\t\t\tconst max = options.maxBodyBytes?.();\n\t\t\tif (max !== undefined && event.byteLength > max) {\n\t\t\t\treturn errorResult(\n\t\t\t\t\t`The result is ${event.byteLength} bytes; the relay passes on at most ${max}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tchecked = { result: value, event };\n\t\t\treturn undefined;\n\t\t};\n\t\tconst stream = new ReadableStream<Uint8Array>({\n\t\t\tstart: (controller) => {\n\t\t\t\t/**\n\t\t\t\t * Send the one answer and end the stream, whatever happens. Encoded\n\t\t\t\t * only if someone listens: a cancelled call's result was not checked.\n\t\t\t\t */\n\t\t\t\tconst finish = (event: () => Uint8Array) => {\n\t\t\t\t\tif (signal.aborted) return; // nobody listens any more\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontroller.enqueue(event());\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// the stream was cancelled meanwhile\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\trunTool(params, signal, grant, deliverable).then(\n\t\t\t\t\t(outcome) =>\n\t\t\t\t\t\tfinish(() =>\n\t\t\t\t\t\t\toutcome.kind === \"invalid\"\n\t\t\t\t\t\t\t\t? sseEvent({\n\t\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\terror: { code: -32602, message: outcome.message },\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t: outcome.result === checked?.result\n\t\t\t\t\t\t\t\t\t? checked.event\n\t\t\t\t\t\t\t\t\t: answer(outcome.result),\n\t\t\t\t\t\t),\n\t\t\t\t\t() =>\n\t\t\t\t\t\tfinish(() =>\n\t\t\t\t\t\t\tsseEvent({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\terror: { code: -32603, message: \"Internal error\" },\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\t\treturn new Response(stream, { status: 200, headers: SSE_HEADERS });\n\t}\n\n\tfunction listen(id: Id, params: Json, signal: AbortSignal): Response {\n\t\tconst notifications = honoured(params);\n\t\tconst finalResult = {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tresult: {\n\t\t\t\tresultType: \"complete\",\n\t\t\t\t_meta: resultMeta({ [META_SUBSCRIPTION]: id }),\n\t\t\t},\n\t\t};\n\t\t// This stream's own listener: two AI apps may both use the same id.\n\t\tlet own: { id: Id; send(m: unknown): void; end(): void } | undefined;\n\t\tconst stream = new ReadableStream<Uint8Array>({\n\t\t\tstart: (controller) => {\n\t\t\t\tcontroller.enqueue(\n\t\t\t\t\tsseEvent({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tmethod: \"notifications/subscriptions/acknowledged\",\n\t\t\t\t\t\tparams: { notifications, _meta: { [META_SUBSCRIPTION]: id } },\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t\tif (Object.keys(notifications).length === 0) {\n\t\t\t\t\tcontroller.enqueue(sseEvent(finalResult));\n\t\t\t\t\tcontroller.close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst listener = {\n\t\t\t\t\tid,\n\t\t\t\t\tsend: (message: unknown) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.enqueue(sseEvent(message));\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tlisteners.delete(listener);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tend: () => {\n\t\t\t\t\t\tlisteners.delete(listener);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcontroller.enqueue(sseEvent(finalResult));\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// already cancelled\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\town = listener;\n\t\t\t\tlisteners.add(listener);\n\t\t\t\tsignal.addEventListener(\"abort\", () => {\n\t\t\t\t\tlisteners.delete(listener);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// already closed\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tcancel: () => {\n\t\t\t\tif (own !== undefined) listeners.delete(own);\n\t\t\t},\n\t\t});\n\t\treturn new Response(stream, { status: 200, headers: SSE_HEADERS });\n\t}\n\n\t/** The request checks; a `Response` when the request is refused. */\n\tfunction check(\n\t\trequest: Request,\n\t\tbody: unknown,\n\t): Response | { id: Id; method: string; params: Json } | \"notification\" {\n\t\tif (Array.isArray(body)) {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32600,\n\t\t\t\t\"Bad Request: JSON-RPC batches are not supported by this endpoint\",\n\t\t\t);\n\t\t}\n\t\tif (!isObject(body) || body[\"jsonrpc\"] !== \"2.0\") {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32600,\n\t\t\t\t\"Bad Request: the request body is not a valid JSON-RPC message\",\n\t\t\t);\n\t\t}\n\t\tconst method = body[\"method\"];\n\t\tconst rawId = body[\"id\"];\n\t\tif (typeof method !== \"string\") {\n\t\t\treturn \"result\" in body || \"error\" in body\n\t\t\t\t? rpcError(\n\t\t\t\t\t\t400,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t-32600,\n\t\t\t\t\t\t\"Bad Request: JSON-RPC responses cannot be posted to this endpoint\",\n\t\t\t\t\t)\n\t\t\t\t: rpcError(\n\t\t\t\t\t\t400,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t-32600,\n\t\t\t\t\t\t\"Bad Request: the request body is not a valid JSON-RPC message\",\n\t\t\t\t\t);\n\t\t}\n\t\tconst headerVersion = request.headers.get(\"mcp-protocol-version\");\n\t\tconst headerMethod = request.headers.get(\"mcp-method\");\n\t\tconst params = isObject(body[\"params\"]) ? body[\"params\"] : {};\n\t\tconst meta = isObject(params[\"_meta\"]) ? params[\"_meta\"] : undefined;\n\t\tconst claim = meta !== undefined && META_VERSION in meta;\n\t\tconst claimed =\n\t\t\ttypeof meta?.[META_VERSION] === \"string\"\n\t\t\t\t? (meta[META_VERSION] as string)\n\t\t\t\t: undefined;\n\t\tconst headerModern =\n\t\t\theaderVersion !== null && headerVersion >= MCP_PROTOCOL_VERSION;\n\n\t\tif (rawId === undefined) {\n\t\t\t// A notification: nothing to answer, but the headers must agree.\n\t\t\tif (\n\t\t\t\tclaimed !== undefined &&\n\t\t\t\theaderVersion !== null &&\n\t\t\t\theaderVersion !== claimed\n\t\t\t) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tnull,\n\t\t\t\t\theaderVersion,\n\t\t\t\t\t`the notification envelope names protocol version ${claimed} but the MCP-Protocol-Version header names ${headerVersion}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t(claim || headerModern) &&\n\t\t\t\theaderMethod !== null &&\n\t\t\t\theaderMethod !== method\n\t\t\t) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tnull,\n\t\t\t\t\theaderMethod,\n\t\t\t\t\t`the notification body names method ${method} but the Mcp-Method header names ${headerMethod}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn \"notification\";\n\t\t}\n\t\tif (typeof rawId !== \"string\" && typeof rawId !== \"number\") {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32600,\n\t\t\t\t\"Bad Request: the request body is not a valid JSON-RPC message\",\n\t\t\t);\n\t\t}\n\t\tconst id = rawId;\n\t\tif (\n\t\t\t!claim ||\n\t\t\t(method === \"initialize\" &&\n\t\t\t\t(claimed === undefined || claimed < MCP_PROTOCOL_VERSION))\n\t\t) {\n\t\t\tif (method === \"initialize\") {\n\t\t\t\tif (headerModern) {\n\t\t\t\t\treturn mismatch(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\theaderVersion,\n\t\t\t\t\t\t\"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst requested =\n\t\t\t\t\ttypeof params[\"protocolVersion\"] === \"string\"\n\t\t\t\t\t\t? params[\"protocolVersion\"]\n\t\t\t\t\t\t: undefined;\n\t\t\t\treturn unsupported(id, requested);\n\t\t\t}\n\t\t\tif (headerModern) {\n\t\t\t\tconst missing = meta === undefined ? [\"_meta\"] : [META_VERSION];\n\t\t\t\treturn rpcError(\n\t\t\t\t\t400,\n\t\t\t\t\tid,\n\t\t\t\t\t-32602,\n\t\t\t\t\t`Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(\", \")}`,\n\t\t\t\t\t{ envelope: { missing } },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn unsupported(id, headerVersion ?? undefined);\n\t\t}\n\t\tconst issue = envelopeIssue(meta);\n\t\tif (issue !== undefined) {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tid,\n\t\t\t\t-32602,\n\t\t\t\t`Invalid _meta envelope for protocol revision ${MCP_PROTOCOL_VERSION}: ${issue.key}: ${issue.problem}`,\n\t\t\t\t{ envelope: issue },\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\theaderVersion !== null &&\n\t\t\tclaimed !== undefined &&\n\t\t\theaderVersion !== claimed\n\t\t) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\theaderVersion,\n\t\t\t\t`the body envelope names protocol version ${claimed} but the MCP-Protocol-Version header names ${headerVersion}`,\n\t\t\t);\n\t\t}\n\t\tif (headerMethod !== null && headerMethod !== method) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\theaderMethod,\n\t\t\t\t`the body names method ${method} but the Mcp-Method header names ${headerMethod}`,\n\t\t\t);\n\t\t}\n\t\tif (claimed !== MCP_PROTOCOL_VERSION) return unsupported(id, claimed);\n\t\tif (headerVersion === null) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\t\"(missing)\",\n\t\t\t\t`the body envelope names protocol version ${claimed} but the required MCP-Protocol-Version header is absent`,\n\t\t\t);\n\t\t}\n\t\tif (headerMethod === null) {\n\t\t\treturn mismatch(\n\t\t\t\tid,\n\t\t\t\t\"(missing)\",\n\t\t\t\t`the body names method ${method} but the required Mcp-Method header is absent`,\n\t\t\t);\n\t\t}\n\t\tif (method === \"tools/call\" && typeof params[\"name\"] === \"string\") {\n\t\t\tconst name = params[\"name\"];\n\t\t\tconst header = request.headers.get(\"mcp-name\");\n\t\t\tif (header === null) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tid,\n\t\t\t\t\t\"(missing)\",\n\t\t\t\t\t`the body carries params.name=\"${name}\" but the required Mcp-Name header is absent`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst decoded = decodeHeaderValue(header);\n\t\t\tif (decoded === undefined) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tid,\n\t\t\t\t\theader,\n\t\t\t\t\t\"the Mcp-Name header carries an invalid Base64 sentinel value\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (decoded !== name) {\n\t\t\t\treturn mismatch(\n\t\t\t\t\tid,\n\t\t\t\t\theader,\n\t\t\t\t\t`the body carries params.name=\"${name}\" but the Mcp-Name header names \"${decoded}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn { id, method, params };\n\t}\n\n\tfunction unsupported(id: Id, requested: string | undefined): Response {\n\t\treturn requested === undefined\n\t\t\t? rpcError(\n\t\t\t\t\t400,\n\t\t\t\t\tid,\n\t\t\t\t\tUNSUPPORTED_VERSION,\n\t\t\t\t\t\"Unsupported protocol version: the request did not name a protocol version\",\n\t\t\t\t\t{ supported: [MCP_PROTOCOL_VERSION] },\n\t\t\t\t)\n\t\t\t: rpcError(\n\t\t\t\t\t400,\n\t\t\t\t\tid,\n\t\t\t\t\tUNSUPPORTED_VERSION,\n\t\t\t\t\t`Unsupported protocol version: ${requested}`,\n\t\t\t\t\t{ supported: [MCP_PROTOCOL_VERSION], requested },\n\t\t\t\t);\n\t}\n\n\tasync function handle(\n\t\trequest: Request,\n\t\tcontext: McpRequestContext,\n\t): Promise<Response> {\n\t\tif (request.method.toUpperCase() !== \"POST\")\n\t\t\treturn rpcError(405, null, -32000, \"Method not allowed.\");\n\t\tif (!isJsonContentType(request.headers.get(\"content-type\"))) {\n\t\t\treturn rpcError(\n\t\t\t\t415,\n\t\t\t\tnull,\n\t\t\t\t-32000,\n\t\t\t\t\"Unsupported Media Type: Content-Type must be application/json\",\n\t\t\t);\n\t\t}\n\t\tlet body: unknown;\n\t\ttry {\n\t\t\tbody = JSON.parse(context.body ?? (await request.text()));\n\t\t} catch {\n\t\t\treturn rpcError(\n\t\t\t\t400,\n\t\t\t\tnull,\n\t\t\t\t-32700,\n\t\t\t\t\"Parse error: the request body is not valid JSON\",\n\t\t\t);\n\t\t}\n\t\tconst checked = check(request, body);\n\t\tif (checked instanceof Response) return checked;\n\t\tif (checked === \"notification\") return new Response(null, { status: 202 });\n\t\tconst { id, method, params } = checked;\n\t\tswitch (method) {\n\t\t\tcase \"server/discover\": {\n\t\t\t\tconst discover: Json = {\n\t\t\t\t\tsupportedVersions: [MCP_PROTOCOL_VERSION],\n\t\t\t\t\tcapabilities: { tools: { listChanged: true } },\n\t\t\t\t};\n\t\t\t\tif (server.instructions !== undefined)\n\t\t\t\t\tdiscover[\"instructions\"] = server.instructions;\n\t\t\t\tdiscover[\"ttlMs\"] = 0;\n\t\t\t\tdiscover[\"cacheScope\"] = \"private\";\n\t\t\t\treturn json(\n\t\t\t\t\t200,\n\t\t\t\t\tresult(id, discover, { [META_SERVER_INFO]: discoverInfo }),\n\t\t\t\t);\n\t\t\t}\n\t\t\tcase \"tools/list\":\n\t\t\t\treturn json(\n\t\t\t\t\t200,\n\t\t\t\t\tresult(id, { tools: listTools(), ttlMs: 0, cacheScope: \"private\" }),\n\t\t\t\t);\n\t\t\tcase \"tools/call\":\n\t\t\t\treturn callTool(id, params, request.signal, context.grant);\n\t\t\tcase \"subscriptions/listen\":\n\t\t\t\treturn listen(id, params, request.signal);\n\t\t\tdefault:\n\t\t\t\treturn rpcError(404, id, -32601, \"Method not found\");\n\t\t}\n\t}\n\n\treturn {\n\t\thandle: (request, context) =>\n\t\t\thandle(request, context).catch(() =>\n\t\t\t\trpcError(500, null, -32603, \"Internal server error\"),\n\t\t\t),\n\t\ttoolsChanged() {\n\t\t\tif (changeQueued) return;\n\t\t\tchangeQueued = true;\n\t\t\t// Several registrations in one task produce one notification.\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tchangeQueued = false;\n\t\t\t\tfor (const listener of [...listeners]) {\n\t\t\t\t\tlistener.send({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tmethod: \"notifications/tools/list_changed\",\n\t\t\t\t\t\tparams: { _meta: { [META_SUBSCRIPTION]: listener.id } },\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tfor (const listener of [...listeners]) listener.end();\n\t\t},\n\t};\n}\n",
7
- "/**\n * WebMCP → MCP mapping of annotations (DEC-022) and results (DEC-023).\n */\n\nimport type { ToolAnnotations } from \"./types.ts\";\n\n/** `_meta` key that keeps the original WebMCP hints. */\nexport const ANNOTATIONS_META_KEY = \"ch.ractive.tab-mcp/annotations\";\n\nconst WEBMCP_HINTS = [\n\t\"readOnlyHint\",\n\t\"untrustedContentHint\",\n\t\"consequentialHint\",\n\t\"debugging\",\n] as const;\nconst MCP_ONLY_HINTS = [\n\t\"destructiveHint\",\n\t\"idempotentHint\",\n\t\"openWorldHint\",\n] as const;\n\nexport interface McpToolAnnotations {\n\tannotations?: Record<string, boolean>;\n\tmeta?: Record<string, boolean>;\n}\n\n/** MCP annotations plus the WebMCP originals for `_meta`. */\nexport function mapAnnotations(hints: ToolAnnotations): McpToolAnnotations {\n\tconst annotations: Record<string, boolean> = {};\n\tif (hints.readOnlyHint === true) {\n\t\tannotations[\"readOnlyHint\"] = true;\n\t\tannotations[\"destructiveHint\"] = false;\n\t} else if (hints.readOnlyHint === false) {\n\t\tannotations[\"readOnlyHint\"] = false;\n\t}\n\tif (hints.consequentialHint === true) annotations[\"destructiveHint\"] = true;\n\tif (hints.untrustedContentHint === true) annotations[\"openWorldHint\"] = true;\n\tfor (const key of MCP_ONLY_HINTS) {\n\t\tconst value = hints[key];\n\t\tif (value !== undefined) annotations[key] = value; // MCP hints win\n\t}\n\tconst meta: Record<string, boolean> = {};\n\tfor (const key of WEBMCP_HINTS) {\n\t\tconst value = hints[key];\n\t\tif (value !== undefined) meta[key] = value;\n\t}\n\tconst out: McpToolAnnotations = {};\n\tif (Object.keys(annotations).length > 0) out.annotations = annotations;\n\tif (Object.keys(meta).length > 0) out.meta = meta;\n\treturn out;\n}\n\nexport interface CallToolResult {\n\tcontent: unknown[];\n\tstructuredContent?: Record<string, unknown>;\n\tisError?: boolean;\n\t_meta?: Record<string, unknown>;\n\t[key: string]: unknown;\n}\n\n/**\n * `result` with `_meta[\"ch.ractive.tab-mcp/annotations\"].untrustedContentHint`\n * set, for every result of a tool marked `untrustedContentHint` (DEC-166):\n * MCP has no such hint, and `openWorldHint` in `tools/list` says something\n * else. The tool's own `_meta` is kept; `result` is not changed.\n */\nexport function markUntrusted(result: CallToolResult): CallToolResult {\n\tconst meta = result._meta ?? {};\n\tconst own = meta[ANNOTATIONS_META_KEY];\n\treturn {\n\t\t...result,\n\t\t_meta: {\n\t\t\t...meta,\n\t\t\t[ANNOTATIONS_META_KEY]: {\n\t\t\t\t...(isObject(own) ? own : {}),\n\t\t\t\tuntrustedContentHint: true,\n\t\t\t},\n\t\t},\n\t};\n}\n\nexport function errorResult(message: string): CallToolResult {\n\treturn { content: [{ type: \"text\", text: message }], isError: true };\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nconst isString = (v: unknown): v is string => typeof v === \"string\";\n\n/**\n * Whether `block` is an MCP 2026-07-28 content block with the fields its\n * type requires: `text` a string `text`; `image` and `audio` string `data`\n * and `mimeType`; `resource_link` string `uri` and `name`; `resource` a\n * `resource` object with a string `uri`.\n */\nfunction isContentBlock(block: unknown): boolean {\n\tif (!isObject(block)) return false;\n\tswitch (block[\"type\"]) {\n\t\tcase \"text\":\n\t\t\treturn isString(block[\"text\"]);\n\t\tcase \"image\":\n\t\tcase \"audio\":\n\t\t\treturn isString(block[\"data\"]) && isString(block[\"mimeType\"]);\n\t\tcase \"resource_link\":\n\t\t\treturn isString(block[\"uri\"]) && isString(block[\"name\"]);\n\t\tcase \"resource\":\n\t\t\treturn isObject(block[\"resource\"]) && isString(block[\"resource\"][\"uri\"]);\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** The keys of a `CallToolResult` (`resultType` is set by the server). */\nconst RESULT_KEYS = new Set([\n\t\"content\",\n\t\"structuredContent\",\n\t\"isError\",\n\t\"_meta\",\n\t\"resultType\",\n]);\n\n/**\n * Whether `value` is an MCP `CallToolResult`: an object whose `content` is an\n * array of MCP content blocks (`isContentBlock`), with `isError` a boolean\n * and `structuredContent` and `_meta` objects where present. Domain data\n * that happens to have a `content` array (a ProseMirror document,\n * `{ title, content: [\"…\"] }`, a chat message with its own blocks) is not\n * one (CC 3). Other keys are allowed next to blocks, as MCP allows them on a\n * result; with an empty `content` they are not, so that `{ title, content:\n * [] }` is data, not an empty result.\n */\nexport function isCallToolResult(value: unknown): value is CallToolResult {\n\tif (!isObject(value) || !Array.isArray(value[\"content\"])) return false;\n\tconst { content, isError, structuredContent, _meta } = value;\n\treturn (\n\t\t(content.length > 0\n\t\t\t? content.every(isContentBlock)\n\t\t\t: Object.keys(value).every((key) => RESULT_KEYS.has(key))) &&\n\t\t(isError === undefined || typeof isError === \"boolean\") &&\n\t\t(structuredContent === undefined || isObject(structuredContent)) &&\n\t\t(_meta === undefined || isObject(_meta))\n\t);\n}\n\n/**\n * What `execute` returned → a `CallToolResult`: a string is one text block; a\n * `CallToolResult` (`isCallToolResult`) passes through; `undefined` is an\n * empty result; any other JSON value is a text block with its JSON, plus\n * that JSON as `structuredContent` when it is an object (so a `Date` or a\n * `URL`, whose JSON is a string, has none).\n */\nexport function toCallToolResult(value: unknown): CallToolResult {\n\tif (typeof value === \"string\")\n\t\treturn { content: [{ type: \"text\", text: value }] };\n\tif (value === undefined) return { content: [] };\n\tif (isCallToolResult(value)) return value;\n\tlet text: string | undefined;\n\ttry {\n\t\ttext = JSON.stringify(value);\n\t} catch {\n\t\t// cyclic or BigInt\n\t}\n\tif (text === undefined)\n\t\treturn errorResult(\"The tool returned a value that is not JSON.\");\n\tconst result: CallToolResult = { content: [{ type: \"text\", text }] };\n\t// What the text says, not the value: `toJSON` applied, no class instances.\n\tconst parsed: unknown = JSON.parse(text);\n\tif (isObject(parsed)) result.structuredContent = parsed;\n\treturn result;\n}\n\n/**\n * The text blocks of a result, one per line. With `noted`, each other block\n * (an image, a resource) is a line that says it was left out, naming its type.\n */\nexport function resultText(result: CallToolResult, noted = false): string {\n\treturn result.content\n\t\t.map((block) =>\n\t\t\tisObject(block) &&\n\t\t\tblock[\"type\"] === \"text\" &&\n\t\t\ttypeof block[\"text\"] === \"string\"\n\t\t\t\t? block[\"text\"]\n\t\t\t\t: noted\n\t\t\t\t\t? `[${isObject(block) ? String(block[\"type\"]) : \"A\"} content left out: WebMCP results are text.]`\n\t\t\t\t\t: \"\",\n\t\t)\n\t\t.filter((text) => text !== \"\")\n\t\t.join(\"\\n\");\n}\n\n/**\n * What a WebMCP caller gets for what `execute` returned (WM 4, WM 6): an MCP\n * result as its `structuredContent` if it has one, else as its text\n * (`resultText`, other blocks noted); `undefined` (which a browser cannot\n * serialize as JSON, so the call would fail) and an empty MCP result as\n * \"Done.\"; any other value as it is.\n */\nexport function webMcpValue(value: unknown): unknown {\n\tif (isCallToolResult(value))\n\t\treturn value.structuredContent ?? (resultText(value, true) || \"Done.\");\n\treturn value === undefined ? \"Done.\" : value;\n}\n\n/** A thrown value → an `isError` result with its message. */\nexport function thrownResult(error: unknown): CallToolResult {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn errorResult(message || \"The tool failed.\");\n}\n",
8
- "/**\n * The tab↔relay protocol, version 1, as the tab speaks it\n * (`docs/protocol.md`, normative). Internal: not part of the public API.\n */\n\nimport type { Grant, Limits } from \"./types.ts\";\n\nexport const SUBPROTOCOL = \"tab-mcp.v1\";\n\n/** Who is calling a tunnelled request (the relay's view of the grant). */\nexport interface GrantRef {\n\tgrantId: string;\n\tclientId: string;\n\tscopes: string[];\n}\n\n// Relay → tab\n\nexport interface SessionMessage {\n\ttype: \"session\";\n\tsessionId: string;\n\taddress: string;\n\torigin: string;\n\tappName?: string;\n\t/** How AI apps pair: `code` or `oidc` (identity binding). Older relays omit it. */\n\tpairing?: \"code\" | \"oidc\";\n\texpiresAt: string;\n\tlimits: Limits;\n\tgrants: Grant[];\n}\nexport interface PingMessage {\n\ttype: \"ping\";\n\tt: number;\n}\nexport interface ByeMessage {\n\ttype: \"bye\";\n\treason: string;\n}\nexport interface HttpRequestMessage {\n\ttype: \"http.request\";\n\tid: string;\n\tmethod: string;\n\tpath: string;\n\theaders: Record<string, string>;\n\tbody: string;\n\tgrant: GrantRef;\n}\nexport interface HttpCancelMessage {\n\ttype: \"http.cancel\";\n\tid: string;\n\treason: string;\n}\nexport interface PairingCodeMessage {\n\ttype: \"pairing.code\";\n\tcode: string;\n\texpiresAt: string;\n\t/** Why it came; left out when it is not one of these. */\n\treason?: \"start\" | \"used\" | \"expired\";\n}\n\nconst CODE_REASONS = new Set([\"start\", \"used\", \"expired\"]);\nexport interface GrantAddedMessage {\n\ttype: \"grant.added\";\n\tgrant: Grant;\n}\nexport interface GrantRemovedMessage {\n\ttype: \"grant.removed\";\n\tgrantId: string;\n\treason: string;\n}\nexport interface IdentityBoundMessage {\n\ttype: \"identity.bound\";\n\t/** The `round` of the `identity` this answers. */\n\tround?: number;\n}\nexport interface ErrorMessage {\n\ttype: \"error\";\n\tcode: string;\n\tmessage: string;\n\tid?: string;\n\t/** On `identity_refused`: the `round` of the `identity` it answers. */\n\tround?: number;\n\t/**\n\t * On `unknown_id` and `store_unavailable` from relay 0.10.2: the type of\n\t * the page's message it answers (`grant.revoke`, `grants.revokeAll`,\n\t * `identity.logout`); older relays leave it out.\n\t */\n\tfor?: unknown;\n\t/** With `for: \"grant.revoke\"`: that message's grant. */\n\tgrantId?: unknown;\n}\nexport type RelayMessage =\n\t| SessionMessage\n\t| PingMessage\n\t| ByeMessage\n\t| HttpRequestMessage\n\t| HttpCancelMessage\n\t| PairingCodeMessage\n\t| GrantAddedMessage\n\t| GrantRemovedMessage\n\t| IdentityBoundMessage\n\t| ErrorMessage;\n\n// Tab → relay\n\nexport type TabMessage =\n\t| {\n\t\t\ttype: \"hello\";\n\t\t\tlibrary: { name: string; version: string };\n\t\t\t/** `id`: the `<app>` of the address `/s/<app>/mcp` (DEC-196). */\n\t\t\tapp: { id: string; name?: string };\n\t\t\tsecret: string;\n\t\t\t/** Take the address back: the relay revokes its grants as it claims it (DEC-095). */\n\t\t\trevokeAll?: true;\n\t }\n\t| { type: \"pong\"; t: number }\n\t| { type: \"bye\"; reason: string }\n\t| {\n\t\t\ttype: \"http.response\";\n\t\t\tid: string;\n\t\t\tstatus: number;\n\t\t\theaders: Record<string, string>;\n\t\t\tbody: string;\n\t }\n\t| {\n\t\t\ttype: \"http.response.start\";\n\t\t\tid: string;\n\t\t\tstatus: number;\n\t\t\theaders: Record<string, string>;\n\t }\n\t| { type: \"http.response.chunk\"; id: string; data: string }\n\t| { type: \"http.response.end\"; id: string }\n\t| { type: \"pairing.start\" }\n\t| { type: \"pairing.stop\" }\n\t| { type: \"grant.revoke\"; grantId: string }\n\t| { type: \"grants.revokeAll\" }\n\t| { type: \"identity\"; assertion: string; round: number }\n\t| { type: \"identity.logout\" }\n\t| { type: \"error\"; code: string; message: string; id?: string };\n\ntype Json = Record<string, unknown>;\n\nfunction isObject(v: unknown): v is Json {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nconst str = (v: unknown): v is string => typeof v === \"string\";\n\nfunction isGrant(v: unknown): v is Grant {\n\tif (!isObject(v) || !str(v[\"grantId\"]) || !str(v[\"createdAt\"])) return false;\n\tconst c = v[\"client\"];\n\treturn isObject(c) && str(c[\"id\"]) && str(c[\"name\"]) && str(c[\"host\"]);\n}\n\nfunction isLimits(v: unknown): v is Limits {\n\tif (!isObject(v)) return false;\n\treturn [\n\t\t\"maxMessageBytes\",\n\t\t\"maxBodyBytes\",\n\t\t\"requestTimeoutMs\",\n\t\t\"idleTimeoutMs\",\n\t\t\"heartbeatMs\",\n\t\t\"keepAliveMs\",\n\t\t\"maxConcurrentRequests\",\n\t].every((k) => typeof v[k] === \"number\");\n}\n\nfunction isStringRecord(v: unknown): v is Record<string, string> {\n\treturn isObject(v) && Object.values(v).every(str);\n}\n\n/**\n * Parse one frame from the relay. Returns `undefined` for anything malformed\n * or unknown; the caller ignores it (forward compatibility).\n */\nexport function parseRelayMessage(text: string): RelayMessage | undefined {\n\tlet v: unknown;\n\ttry {\n\t\tv = JSON.parse(text);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (!isObject(v)) return undefined;\n\tswitch (v[\"type\"]) {\n\t\tcase \"session\":\n\t\t\treturn str(v[\"sessionId\"]) &&\n\t\t\t\tstr(v[\"address\"]) &&\n\t\t\t\tstr(v[\"origin\"]) &&\n\t\t\t\tstr(v[\"expiresAt\"]) &&\n\t\t\t\tisLimits(v[\"limits\"]) &&\n\t\t\t\tArray.isArray(v[\"grants\"]) &&\n\t\t\t\tv[\"grants\"].every(isGrant) &&\n\t\t\t\t(v[\"appName\"] === undefined || str(v[\"appName\"])) &&\n\t\t\t\t(v[\"pairing\"] === undefined || str(v[\"pairing\"]))\n\t\t\t\t? (v as unknown as SessionMessage)\n\t\t\t\t: undefined;\n\t\tcase \"ping\":\n\t\t\treturn typeof v[\"t\"] === \"number\"\n\t\t\t\t? (v as unknown as PingMessage)\n\t\t\t\t: undefined;\n\t\tcase \"bye\":\n\t\t\treturn { type: \"bye\", reason: str(v[\"reason\"]) ? v[\"reason\"] : \"\" };\n\t\tcase \"http.request\":\n\t\t\treturn str(v[\"id\"]) &&\n\t\t\t\tstr(v[\"method\"]) &&\n\t\t\t\tstr(v[\"path\"]) &&\n\t\t\t\tisStringRecord(v[\"headers\"]) &&\n\t\t\t\tstr(v[\"body\"]) &&\n\t\t\t\tisObject(v[\"grant\"]) &&\n\t\t\t\tstr(v[\"grant\"][\"grantId\"]) &&\n\t\t\t\tstr(v[\"grant\"][\"clientId\"])\n\t\t\t\t? (v as unknown as HttpRequestMessage)\n\t\t\t\t: undefined;\n\t\tcase \"http.cancel\":\n\t\t\treturn str(v[\"id\"]) ? (v as unknown as HttpCancelMessage) : undefined;\n\t\tcase \"pairing.code\": {\n\t\t\tif (!str(v[\"code\"]) || !str(v[\"expiresAt\"])) return undefined;\n\t\t\tconst message: PairingCodeMessage = {\n\t\t\t\ttype: \"pairing.code\",\n\t\t\t\tcode: v[\"code\"],\n\t\t\t\texpiresAt: v[\"expiresAt\"],\n\t\t\t};\n\t\t\t// An unknown reason (a newer relay) counts as none.\n\t\t\tconst reason = v[\"reason\"];\n\t\t\tif (typeof reason === \"string\" && CODE_REASONS.has(reason))\n\t\t\t\tmessage.reason = reason as NonNullable<PairingCodeMessage[\"reason\"]>;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"grant.added\":\n\t\t\treturn isGrant(v[\"grant\"])\n\t\t\t\t? (v as unknown as GrantAddedMessage)\n\t\t\t\t: undefined;\n\t\tcase \"grant.removed\":\n\t\t\treturn str(v[\"grantId\"])\n\t\t\t\t? {\n\t\t\t\t\t\ttype: \"grant.removed\",\n\t\t\t\t\t\tgrantId: v[\"grantId\"],\n\t\t\t\t\t\treason: str(v[\"reason\"]) ? v[\"reason\"] : \"\",\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tcase \"identity.bound\":\n\t\t\treturn typeof v[\"round\"] === \"number\"\n\t\t\t\t? { type: \"identity.bound\", round: v[\"round\"] }\n\t\t\t\t: { type: \"identity.bound\" };\n\t\tcase \"error\":\n\t\t\treturn str(v[\"code\"]) ? (v as unknown as ErrorMessage) : undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n",
9
- "/**\n * The page's end of the HTTP tunnel (`docs/protocol.md`, \"Tunnelled MCP\n * requests\"): `http.request` and `http.cancel` in, `http.response*` out. The\n * relay connection uses it (`connection.ts`), and so does `TabMcp.serve`,\n * which answers the same messages over a port, without a relay\n * (iteration 28). Part of the lazily loaded chunk.\n */\n\nimport { pageIcons } from \"./icons.ts\";\nimport type { CallHost } from \"./internal.ts\";\nimport {\n\ttype CallContext,\n\tcreateMcpHandler,\n\ttype McpHandler,\n\ttype ToolSource,\n} from \"./mcp.ts\";\nimport type { GrantRef, HttpRequestMessage, TabMessage } from \"./protocol.ts\";\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\nimport type {\n\tConfirmAnswer,\n\tLocalClient,\n\tServeHandle,\n\tServeOptions,\n\tServerInfo,\n\tToolCaller,\n\tTunnelPort,\n} from \"./types.ts\";\n\n/**\n * The tools that callers of `kind` see (`RegisterToolOptions.callers`): to\n * the others a tool they cannot see does not exist, in `tools/list` and in\n * `tools/call` alike. Without `callers`, the relay and a port see every tool.\n * The rule for WebMCP lives in the core's `mirror` (webmcp.ts), and WebMCP\n * calls come only for the tools it mirrored. Not one shared helper: a module\n * the core and this chunk both import would split the core in two.\n */\nexport function toolsFor(\n\tregistry: ToolRegistry,\n\tkind: \"relay\" | \"local\",\n): ToolSource {\n\tconst sees = (tool: RegisteredTool | undefined) =>\n\t\ttool && (tool.callers?.includes(kind) ?? true);\n\treturn {\n\t\tlist: () => registry.list().filter(sees),\n\t\tget: (name) => {\n\t\t\tconst tool = registry.get(name);\n\t\t\treturn sees(tool) ? tool : undefined;\n\t\t},\n\t};\n}\n\n/**\n * Calls `changed` when the list that `tools` gives changed, not on every\n * change of the registry: a tool another kind of caller sees is no news to\n * this one (`list_changed` per caller). Returns a function that stops.\n */\nexport function watchTools(\n\tregistry: ToolRegistry,\n\ttools: ToolSource,\n\tchanged: () => void,\n): () => void {\n\tlet last = tools.list();\n\treturn registry.onChange(() => {\n\t\tconst now = tools.list();\n\t\tif (now.length === last.length && now.every((t, i) => t === last[i]))\n\t\t\treturn;\n\t\tlast = now;\n\t\tchanged();\n\t});\n}\n\n/** What a call of `kind` through the relay, a port or WebMCP needs (`mcp.ts`), from the core's host. */\nexport function callContext(host: CallHost, kind: ToolCaller): CallContext {\n\treturn {\n\t\ttools: kind === \"webmcp\" ? host.registry : toolsFor(host.registry, kind),\n\t\tconfirm: (request) => host.confirm(request),\n\t\townConfirm: host.ownConfirm(),\n\t\tobserve: {\n\t\t\tstart: (call) => host.toolCallStarted(call),\n\t\t\tend: (call) => host.toolCallEnded(call),\n\t\t},\n\t};\n}\n\n/** Response headers that are passed on (the relay drops the rest). */\nconst RESPONSE_HEADERS = [\"content-type\", \"cache-control\"];\n\n/**\n * Split text into pieces of at most `max` UTF-16 units, never between the two\n * halves of a surrogate pair (a lone half would not survive JSON and UTF-8).\n */\nexport function* pieces(text: string, max: number): Generator<string> {\n\tlet i = 0;\n\twhile (i < text.length) {\n\t\tlet end = Math.min(i + max, text.length);\n\t\tconst last = text.charCodeAt(end - 1);\n\t\tif (end < text.length && last >= 0xd800 && last <= 0xdbff) {\n\t\t\tend += end - 1 > i ? -1 : 1; // keep the pair together\n\t\t}\n\t\tyield text.slice(i, end);\n\t\ti = end;\n\t}\n}\n\n/** The relay's JSON-RPC error for a request that took too long, as `createTunnelFetch` sends it. */\nconst TIMEOUT = -31002;\nconst TIMED_OUT = \"The page did not answer in time.\";\n\n/** The JSON-RPC id of a request body, for the error that answers it. */\nfunction rpcId(body: string): string | number | null {\n\ttry {\n\t\tconst id: unknown = JSON.parse(body)?.id;\n\t\treturn typeof id === \"string\" || typeof id === \"number\" ? id : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** The requests in flight of one channel (a relay session or a port). */\nexport interface Tunnel {\n\t/** Answer one request; nothing is sent for it once it is cancelled or the tunnel closed. */\n\trequest(message: HttpRequestMessage): void;\n\tcancel(id: string): void;\n\t/** Abort every request in flight; later requests are ignored. */\n\tclose(): void;\n}\n\nexport function createTunnel(options: {\n\thandler: McpHandler;\n\tsend(message: TabMessage): boolean;\n\t/** The largest piece of body text in one message (UTF-16 units), read per answer. */\n\tmaxChunk(): number;\n\t/** Something failed outside the handler. */\n\terror(error: Error): void;\n\t/**\n\t * How long a request may take until its answer has ended\n\t * (`ServeOptions.requestTimeoutMs`); none for the relay's session, whose\n\t * relay has its own. A `subscriptions/listen` stream is not limited.\n\t */\n\ttimeoutMs?: number;\n}): Tunnel {\n\tconst { handler, send, timeoutMs } = options;\n\tconst inflight = new Map<string, AbortController>();\n\tlet closed = false;\n\n\tasync function run(msg: HttpRequestMessage): Promise<void> {\n\t\tconst controller = new AbortController();\n\t\t// An id that is still in flight (a relay never sends one; another end\n\t\t// of a port may): the earlier request ends here, so that it does not\n\t\t// run on unheard, out of reach of `http.cancel`.\n\t\tinflight.get(msg.id)?.abort();\n\t\tinflight.set(msg.id, controller);\n\t\tconst live = () =>\n\t\t\t!closed &&\n\t\t\tinflight.get(msg.id) === controller &&\n\t\t\t!controller.signal.aborted;\n\t\t/**\n\t\t * Whether an event stream has started, for the time limit's error (a\n\t\t * body in pieces goes out in one task, which no timer interrupts).\n\t\t */\n\t\tlet started = false;\n\t\t/** The last two characters of that stream: empty or a blank line is between two events. */\n\t\tlet tail = \"\";\n\t\t// Header names in any case, as the handler reads them (review of PR 129).\n\t\tconst listen = Object.entries(msg.headers).some(\n\t\t\t([name, value]) =>\n\t\t\t\tname.toLowerCase() === \"mcp-method\" && value === \"subscriptions/listen\",\n\t\t);\n\t\tconst timer =\n\t\t\ttimeoutMs === undefined || listen\n\t\t\t\t? undefined\n\t\t\t\t: setTimeout(() => {\n\t\t\t\t\t\tif (!live()) return;\n\t\t\t\t\t\t// The call ends as cancelled; whatever it answers later is dropped.\n\t\t\t\t\t\tcontroller.abort();\n\t\t\t\t\t\tconst error = JSON.stringify({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid: rpcId(msg.body),\n\t\t\t\t\t\t\terror: { code: TIMEOUT, message: TIMED_OUT },\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (!started) {\n\t\t\t\t\t\t\tsend({\n\t\t\t\t\t\t\t\ttype: \"http.response\",\n\t\t\t\t\t\t\t\tid: msg.id,\n\t\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\t\t\t\t\tbody: error,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// As `createTunnelFetch` does: the error as the stream's last\n\t\t\t\t\t\t// event where it stands between two events. The handler\n\t\t\t\t\t\t// (mcp.ts) enqueues whole events and each read's text goes out\n\t\t\t\t\t\t// in one task, so the timer always finds the stream between\n\t\t\t\t\t\t// two events; the check only guards against sending an event\n\t\t\t\t\t\t// into the middle of another (review of PR 129).\n\t\t\t\t\t\tif (tail === \"\" || tail === \"\\n\\n\")\n\t\t\t\t\t\t\tsend({\n\t\t\t\t\t\t\t\ttype: \"http.response.chunk\",\n\t\t\t\t\t\t\t\tid: msg.id,\n\t\t\t\t\t\t\t\tdata: `event: message\\ndata: ${error}\\n\\n`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\tsend({ type: \"http.response.end\", id: msg.id });\n\t\t\t\t\t}, timeoutMs);\n\t\ttry {\n\t\t\tconst request = new Request(`https://tab.invalid${msg.path}`, {\n\t\t\t\tmethod: msg.method,\n\t\t\t\theaders: msg.headers,\n\t\t\t\tsignal: controller.signal,\n\t\t\t});\n\t\t\tconst response = await handler.handle(request, {\n\t\t\t\tgrant: msg.grant,\n\t\t\t\tbody: msg.body,\n\t\t\t});\n\t\t\tif (!live()) {\n\t\t\t\tawait response.body?.cancel().catch(() => {});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst headers: Record<string, string> = {};\n\t\t\tfor (const name of RESPONSE_HEADERS) {\n\t\t\t\tconst value = response.headers.get(name);\n\t\t\t\tif (value !== null) headers[name] = value;\n\t\t\t}\n\t\t\tconst streamed = (headers[\"content-type\"] ?? \"\").startsWith(\n\t\t\t\t\"text/event-stream\",\n\t\t\t);\n\t\t\tconst maxChunk = options.maxChunk();\n\t\t\tif (!streamed || response.body === null) {\n\t\t\t\tconst body = await response.text();\n\t\t\t\tif (!live()) return;\n\t\t\t\tif (body.length <= maxChunk) {\n\t\t\t\t\tsend({\n\t\t\t\t\t\ttype: \"http.response\",\n\t\t\t\t\t\tid: msg.id,\n\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tbody,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Too big for one message: stream it (the relay passes it on whole).\n\t\t\t\tsend({\n\t\t\t\t\ttype: \"http.response.start\",\n\t\t\t\t\tid: msg.id,\n\t\t\t\t\tstatus: response.status,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t\tfor (const data of pieces(body, maxChunk)) {\n\t\t\t\t\tif (!live()) break;\n\t\t\t\t\tsend({ type: \"http.response.chunk\", id: msg.id, data });\n\t\t\t\t}\n\t\t\t\tif (live()) send({ type: \"http.response.end\", id: msg.id });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsend({\n\t\t\t\ttype: \"http.response.start\",\n\t\t\t\tid: msg.id,\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders,\n\t\t\t});\n\t\t\tstarted = true;\n\t\t\tconst reader = response.body.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tcontroller.signal.addEventListener(\"abort\", () => {\n\t\t\t\treader.cancel().catch(() => {});\n\t\t\t});\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done || !live()) break;\n\t\t\t\tconst text = decoder.decode(value, { stream: true });\n\t\t\t\tif (text !== \"\") tail = (tail + text).slice(-2);\n\t\t\t\tfor (const data of pieces(text, maxChunk)) {\n\t\t\t\t\tsend({ type: \"http.response.chunk\", id: msg.id, data });\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (live()) send({ type: \"http.response.end\", id: msg.id });\n\t\t} catch (error) {\n\t\t\tif (live()) {\n\t\t\t\toptions.error(\n\t\t\t\t\terror instanceof Error ? error : new Error(String(error)),\n\t\t\t\t);\n\t\t\t\tsend({\n\t\t\t\t\ttype: \"http.response\",\n\t\t\t\t\tid: msg.id,\n\t\t\t\t\tstatus: 500,\n\t\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid: null,\n\t\t\t\t\t\terror: { code: -32603, message: \"Internal server error\" },\n\t\t\t\t\t}),\n\t\t\t\t});\n\t\t\t}\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t\tif (inflight.get(msg.id) === controller) inflight.delete(msg.id);\n\t\t}\n\t}\n\n\treturn {\n\t\trequest(message) {\n\t\t\tif (!closed) void run(message);\n\t\t},\n\t\tcancel(id) {\n\t\t\tinflight.get(id)?.abort();\n\t\t\tinflight.delete(id);\n\t\t},\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tfor (const controller of inflight.values()) controller.abort();\n\t\t\tinflight.clear();\n\t\t},\n\t};\n}\n\n/** What `serve` needs from the `TabMcp`. */\nexport interface ServeHost extends CallHost {\n\treadonly server: ServerInfo;\n\terror(error: Error): void;\n}\n\n/** The default and the smallest `ServeOptions.maxChunk`. */\nconst MAX_CHUNK = 64 * 1024;\nconst MIN_CHUNK = 64;\n/** The default `ServeOptions.requestTimeoutMs`, as `createTunnelFetch`'s and the relay's. */\nconst REQUEST_TIMEOUT_MS = 300_000;\n/** The longest request id, as between relay and tab. */\nconst MAX_ID = 128;\n\n/** The ports being served now. */\nconst served = new WeakSet<object>();\n\n/** One per `serve` call: the `n` of its grant id `local:<n>`. */\nlet lastPort = 0;\n\nconst str = (v: unknown): v is string => typeof v === \"string\";\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * `TabMcp.serve`: answer the tunnel's messages on `port` until `close()` or\n * `options.signal`. Every request runs as `options.client` (`kind: \"local\"`),\n * whatever `grant` it carries: the other end cannot pose as an AI app of the\n * relay. Throws a `TypeError` for options it cannot use.\n */\nexport function servePort(\n\thost: ServeHost,\n\tport: TunnelPort,\n\toptions: ServeOptions,\n): ServeHandle {\n\tconst who = options?.client;\n\tif (\n\t\t!isObject(who) ||\n\t\t!str(who.id) ||\n\t\twho.id === \"\" ||\n\t\t(who.name !== undefined && !str(who.name))\n\t) {\n\t\tthrow new TypeError(\"serve: client needs an id (and may have a name)\");\n\t}\n\tconst maxChunk = options.maxChunk ?? MAX_CHUNK;\n\tif (!Number.isInteger(maxChunk) || maxChunk < MIN_CHUNK) {\n\t\tthrow new TypeError(\n\t\t\t`serve: maxChunk must be a whole number of at least ${MIN_CHUNK}`,\n\t\t);\n\t}\n\tconst timeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;\n\t// What `setTimeout` can keep: beyond it (and for Infinity) it fires at once.\n\tif (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || timeoutMs >= 2 ** 31)\n\t\tthrow new TypeError(\n\t\t\t\"serve: requestTimeoutMs must be milliseconds above 0 and below 2^31\",\n\t\t);\n\tconst ask = options.onConfirm;\n\tif (ask !== undefined && typeof ask !== \"function\")\n\t\tthrow new TypeError(\"serve: onConfirm must be a function\");\n\tif (\n\t\ttypeof port?.postMessage !== \"function\" ||\n\t\t!(\"onmessage\" in (port as object))\n\t) {\n\t\tthrow new TypeError(\"serve: the port needs postMessage and onmessage\");\n\t}\n\t// A second serve would take `onmessage` from the first, whose calls in\n\t// flight would then run on unheard and unanswered.\n\tif (served.has(port)) {\n\t\tthrow new DOMException(\n\t\t\t\"serve: this port is served already; close that first\",\n\t\t\t\"InvalidStateError\",\n\t\t);\n\t}\n\tconst client: LocalClient = { kind: \"local\", id: who.id };\n\tif (who.name !== undefined && who.name !== \"\") client.name = who.name;\n\tconst grant: GrantRef = {\n\t\tgrantId: `local:${++lastPort}`,\n\t\tclientId: who.id,\n\t\tscopes: [\"tools\"],\n\t};\n\tlet closed = false;\n\n\tconst send = (message: TabMessage): boolean => {\n\t\tif (closed) return false;\n\t\ttry {\n\t\t\tport.postMessage(message);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t};\n\tconst context = callContext(host, \"local\");\n\t// This port's own question, in place of the page's (DEC-164). Normalised\n\t// as the page's: anything but `true` or \"unanswered\" is a refusal, and a\n\t// throw too (`runCall`).\n\tif (ask !== undefined) {\n\t\tcontext.confirm = (request) =>\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() => ask(request))\n\t\t\t\t.then(\n\t\t\t\t\t(answer): ConfirmAnswer =>\n\t\t\t\t\t\tanswer === \"unanswered\" ? answer : answer === true,\n\t\t\t\t);\n\t\tcontext.ownConfirm = true;\n\t}\n\tconst handler = createMcpHandler({\n\t\t...context,\n\t\t// Without `icons`, the page's own <link rel=\"icon\">, read now.\n\t\tserver: { ...host.server, icons: host.server.icons ?? pageIcons() },\n\t\tclient: () => ({ ...client }),\n\t});\n\tconst stopWatching = watchTools(host.registry, context.tools, () =>\n\t\thandler.toolsChanged(),\n\t);\n\tconst tunnel = createTunnel({\n\t\thandler,\n\t\tsend,\n\t\tmaxChunk: () => maxChunk,\n\t\terror: (error) => host.error(error),\n\t\ttimeoutMs,\n\t});\n\n\tconst bad = (message: string, id?: unknown): void => {\n\t\tconst error: TabMessage = { type: \"error\", code: \"bad_message\", message };\n\t\tif (str(id) && id.length <= MAX_ID) error.id = id;\n\t\tsend(error);\n\t};\n\tconst onMessage = (event: { data: unknown }): void => {\n\t\tif (closed) return;\n\t\tconst m = event?.data;\n\t\tif (!isObject(m) || !str(m[\"type\"])) {\n\t\t\tbad(\"not a message\");\n\t\t\treturn;\n\t\t}\n\t\tconst id = m[\"id\"];\n\t\tswitch (m[\"type\"]) {\n\t\t\tcase \"http.request\": {\n\t\t\t\tconst { method, path, headers, body } = m;\n\t\t\t\tif (\n\t\t\t\t\t!str(id) ||\n\t\t\t\t\tid === \"\" ||\n\t\t\t\t\tid.length > MAX_ID ||\n\t\t\t\t\t!str(method) ||\n\t\t\t\t\t!str(path) ||\n\t\t\t\t\t!path.startsWith(\"/\") ||\n\t\t\t\t\t!isObject(headers) ||\n\t\t\t\t\t!Object.values(headers).every(str) ||\n\t\t\t\t\t!str(body)\n\t\t\t\t) {\n\t\t\t\t\tbad(\"malformed http.request\", id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttunnel.request({\n\t\t\t\t\ttype: \"http.request\",\n\t\t\t\t\tid,\n\t\t\t\t\tmethod,\n\t\t\t\t\tpath,\n\t\t\t\t\theaders: headers as Record<string, string>,\n\t\t\t\t\tbody,\n\t\t\t\t\tgrant, // never the one in the message\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"http.cancel\":\n\t\t\t\tif (str(id)) tunnel.cancel(id);\n\t\t\t\telse bad(\"malformed http.cancel\");\n\t\t\t\treturn;\n\t\t\tcase \"error\":\n\t\t\t\treturn; // never answered, so that two ends cannot answer each other for ever\n\t\t\tdefault:\n\t\t\t\tbad(`unexpected ${m[\"type\"].slice(0, 64)}`, id);\n\t\t}\n\t};\n\n\t// A `MessagePort` fires `close` when its other end is gone (closed, or its\n\t// frame unloaded), where the browser has the event: the calls, listen\n\t// streams and an open confirmation end then too, not only on `close()`.\n\tconst events = port as Partial<\n\t\tPick<EventTarget, \"addEventListener\" | \"removeEventListener\">\n\t>;\n\tconst close = (): void => {\n\t\tif (closed) return;\n\t\toptions.signal?.removeEventListener(\"abort\", close);\n\t\tevents.removeEventListener?.(\"close\", close);\n\t\tstopWatching();\n\t\ttunnel.close();\n\t\thandler.close();\n\t\t// The other end is told, so that its requests end now and not with\n\t\t// their timeout; a port that was never served hears nothing.\n\t\tif (served.delete(port)) send({ type: \"bye\", reason: \"closed\" });\n\t\tclosed = true;\n\t\tif (port.onmessage === onMessage) port.onmessage = null;\n\t};\n\tif (options.signal?.aborted === true) {\n\t\tclose();\n\t\treturn { close };\n\t}\n\toptions.signal?.addEventListener(\"abort\", close);\n\tevents.addEventListener?.(\"close\", close);\n\tserved.add(port);\n\tport.onmessage = onMessage; // starts a MessagePort\n\treturn { close };\n}\n",
10
- "/**\n * A hash of the page's secret: what the tabs of one page tell each other by\n * when one of them takes over (DEC-095), in place of the secret. It is not the\n * relay's address id, which is of the app and the secret (DEC-196), and never\n * part of a URL. Part of the lazily loaded chunk\n * (DEC-035), not the core.\n */\n\nconst BASE32 = \"abcdefghijklmnopqrstuvwxyz234567\";\n\n/** RFC 4648 base32, lower case, without padding (the relay's address ids). */\nfunction base32(bytes: Uint8Array): string {\n\tlet out = \"\";\n\tlet buffer = 0;\n\tlet bits = 0;\n\tfor (const byte of bytes) {\n\t\tbuffer = (buffer << 8) | byte;\n\t\tbits += 8;\n\t\twhile (bits >= 5) {\n\t\t\tbits -= 5;\n\t\t\tout += BASE32[(buffer >>> bits) & 31];\n\t\t}\n\t\tbuffer &= (1 << bits) - 1;\n\t}\n\tif (bits > 0) out += BASE32[(buffer << (5 - bits)) & 31];\n\treturn out;\n}\n\n/**\n * The hash of a secret that the tabs of a page name it by:\n * base32(sha256(secret)). `undefined` where Web Crypto is missing (`null`: a\n * page on plain http other than localhost) or fails; a replaced tab then\n * cannot tell a sibling tab from an impostor.\n */\nexport async function addressIdOf(\n\tsecret: string,\n\tsubtle: SubtleCrypto | null = globalThis.crypto?.subtle ?? null,\n): Promise<string | undefined> {\n\tif (subtle === null) return undefined;\n\ttry {\n\t\tconst digest = await subtle.digest(\n\t\t\t\"SHA-256\",\n\t\t\tnew TextEncoder().encode(secret),\n\t\t);\n\t\treturn base32(new Uint8Array(digest));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n",
11
- "/**\n * The lazily loaded part (DEC-035): the WebSocket session with the relay, the\n * HTTP tunnel and the MCP handler. Loaded by `TabMcp.connect()`.\n */\n\nimport { pageIcons } from \"./icons.ts\";\nimport type { CallHost, ConnectionHandle, ConnectionHost } from \"./internal.ts\";\nimport { createMcpHandler, webMcpCall } from \"./mcp.ts\";\nimport {\n\tparseRelayMessage,\n\ttype RelayMessage,\n\tSUBPROTOCOL,\n\ttype TabMessage,\n} from \"./protocol.ts\";\nimport type { RegisteredTool } from \"./registry.ts\";\nimport { callContext, createTunnel, watchTools } from \"./serve.ts\";\nimport type { DisconnectReason, SessionInfo } from \"./types.ts\";\n\n/** For the core: the address id the page's tabs tell each other by (DEC-095). */\nexport { addressIdOf } from \"./address.ts\";\n/** For the core: compiles the schemas once this chunk (and the validator) is loaded. */\nexport { compileRegistry } from \"./mcp.ts\";\n/** For the core: `TabMcp.serve`, the tunnel over a port (iteration 28). */\nexport { pieces, servePort } from \"./serve.ts\";\n\n/**\n * For the core: a WebMCP call of a mirrored tool (iteration 25), on the\n * same path as an AI app's (`webMcpCall` in `mcp.ts`).\n */\nexport function callFromWebMcp(\n\thost: CallHost,\n\ttool: RegisteredTool,\n\tinput: unknown,\n\tsignal: unknown,\n): Promise<unknown> {\n\treturn webMcpCall(callContext(host, \"webmcp\"), tool, input, signal);\n}\n\n/** How long `connect()` waits for the relay's `session`. */\nconst CONNECT_TIMEOUT_MS = 15_000;\n\nconst CLOSE_REASONS: Record<number, DisconnectReason> = {\n\t1000: \"closed\",\n\t/**\n\t * Going away, internal error, service restart, try again later: what a\n\t * proxy or platform in front of the relay sends when the relay behind it\n\t * restarts without its own `bye`. Reconnecting may help.\n\t */\n\t1001: \"shutdown\",\n\t1008: \"policy\",\n\t1009: \"too_large\",\n\t1011: \"shutdown\",\n\t1012: \"shutdown\",\n\t1013: \"shutdown\",\n\t4001: \"expired\",\n\t4002: \"idle\",\n\t4003: \"heartbeat\",\n\t4004: \"shutdown\",\n\t4005: \"replaced\",\n\t4008: \"rate_limited\",\n};\n\nconst BYE_REASONS: Record<string, DisconnectReason> = {\n\treplaced: \"replaced\",\n\texpired: \"expired\",\n\tidle: \"idle\",\n\tshutdown: \"shutdown\",\n};\n\n/**\n * An error of `ready` that says why the connection did not open, so that\n * reconnecting retries only what may get better (DEC-082).\n */\nfunction refused(message: string, reason: DisconnectReason): Error {\n\treturn Object.assign(new Error(message), { reason });\n}\n\n/**\n * Room for a message's envelope (`http.response` with its headers, or a\n * chunk) with an id of up to 128 characters (protocol limit).\n */\nconst ENVELOPE_BYTES = 512;\n/** Worst case per UTF-16 unit once JSON-encoded as UTF-8: `\\u0001` is 6 bytes. */\nconst WORST_BYTES_PER_UNIT = 6;\nconst MIN_CHUNK_UNITS = 64;\nexport const MIN_MESSAGE_BYTES: number =\n\tENVELOPE_BYTES + WORST_BYTES_PER_UNIT * MIN_CHUNK_UNITS;\n\n/**\n * The largest piece of body text (UTF-16 units) whose message cannot exceed\n * the relay's `maxMessageBytes`; `undefined` if the limit is too small to\n * frame anything useful.\n */\nexport function chunkSize(maxMessageBytes: number): number | undefined {\n\tconst units = Math.floor(\n\t\t(maxMessageBytes - ENVELOPE_BYTES) / WORST_BYTES_PER_UNIT,\n\t);\n\treturn units >= MIN_CHUNK_UNITS ? units : undefined;\n}\n\n/**\n * How long after a sibling tab's `claimed` a `replaced` counts as caused by\n * it (DEC-095). That tab posts it when the relay accepted its session, which\n * is when the relay ended this one.\n */\nexport const SIBLING_WINDOW_MS = 10_000;\n\n/**\n * How long a replaced tab that heard no `claimed` yet waits for one before it\n * reports `replaced`: the sibling's session and this tab's `bye` leave the\n * relay at about the same time, so the message usually comes after the `bye`.\n */\nexport const SIBLING_GRACE_MS = 1_000;\n\n/**\n * The tabs of one page (same relay, same storage key) tell each other on a\n * `BroadcastChannel` when the relay accepted their claim of an address\n * (`claimed`, once their `session` arrived), so that a replaced tab can tell\n * a sibling from an impostor. A sibling whose `hello` failed says nothing.\n * The message carries the address id of the secret (`addressIdOf`; never the\n * secret), and\n * only a claim of this tab's own address, heard after this tab's own\n * `session`, counts: one heard while this tab was still connecting, or from\n * a tab on another address (after `newAddress()` there), cannot have caused\n * the replacement (CC 5). A claim without an address counts for any. Without\n * `BroadcastChannel` nothing is heard, and every `replaced` counts as unknown.\n */\nfunction siblingTabs(\n\tname: string | undefined,\n\taddress: string | undefined,\n): {\n\t/** The own session arrived: say so, and listen to the others from now on. */\n\tclaimed(): void;\n\t/** `true` once `claimed` was heard in the window, `false` after the grace. */\n\theard(): Promise<boolean>;\n\tclose(): void;\n} {\n\tlet channel: BroadcastChannel | undefined;\n\tlet listening = false;\n\tlet at = Number.NEGATIVE_INFINITY;\n\tlet onClaim: (() => void) | undefined;\n\ttry {\n\t\tif (name !== undefined && typeof BroadcastChannel === \"function\") {\n\t\t\tchannel = new BroadcastChannel(name);\n\t\t\tchannel.onmessage = (event: MessageEvent) => {\n\t\t\t\tconst data = event.data as { type?: unknown; address?: unknown } | null;\n\t\t\t\t// No address: a tab with a library up to 0.15, while both run.\n\t\t\t\tif (\n\t\t\t\t\t!listening ||\n\t\t\t\t\tdata?.type !== \"claimed\" ||\n\t\t\t\t\t(data.address !== undefined && data.address !== address)\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\tat = Date.now();\n\t\t\t\tonClaim?.();\n\t\t\t};\n\t\t}\n\t} catch {\n\t\tchannel = undefined; // e.g. an opaque origin\n\t}\n\treturn {\n\t\tclaimed() {\n\t\t\tlistening = true;\n\t\t\ttry {\n\t\t\t\tchannel?.postMessage({ type: \"claimed\", address });\n\t\t\t} catch {\n\t\t\t\t// closed or not allowed: the other tab counts it as unknown\n\t\t\t}\n\t\t},\n\t\theard() {\n\t\t\tif (Date.now() - at <= SIBLING_WINDOW_MS) return Promise.resolve(true);\n\t\t\tif (channel === undefined) return Promise.resolve(false);\n\t\t\treturn new Promise((resolve) => {\n\t\t\t\tconst timer = setTimeout(() => resolve(false), SIBLING_GRACE_MS);\n\t\t\t\tonClaim = () => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(true);\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tchannel?.close();\n\t\t},\n\t};\n}\n\n/**\n * Open the WebSocket and run the session. `address`: the secret's address id\n * (`addressIdOf`). `revokeAll`: take the address back (DEC-095); the relay\n * revokes every grant as it claims the address, and its `session` lists none.\n */\nexport function openConnection(\n\thost: ConnectionHost,\n\turl: string,\n\tsecret: string,\n\toptions: { address?: string | undefined; revokeAll?: boolean } = {},\n): ConnectionHandle {\n\tconst revokeAll = options.revokeAll === true;\n\tconst ws = new WebSocket(url, SUBPROTOCOL);\n\tlet state: \"opening\" | \"ready\" | \"closed\" = \"opening\";\n\tlet byeReason: DisconnectReason | undefined;\n\tlet maxChunk = 64 * 1024;\n\t/** The relay's limit on a response body (CC 7); known once `session` came. */\n\tlet maxBodyBytes: number | undefined;\n\tlet heartbeat: ReturnType<typeof setTimeout> | undefined;\n\tlet heartbeatMs = 0;\n\tconst siblings = siblingTabs(host.tabs, options.address);\n\n\tlet resolveReady!: (session: SessionInfo) => void;\n\tlet rejectReady!: (error: Error) => void;\n\tconst ready = new Promise<SessionInfo>((resolve, reject) => {\n\t\tresolveReady = resolve;\n\t\trejectReady = reject;\n\t});\n\tready.catch(() => {}); // the caller handles it; never an unhandled rejection here\n\tconst connectTimer = setTimeout(() => {\n\t\tfail(refused(\"The relay did not answer in time.\", \"network\"));\n\t}, CONNECT_TIMEOUT_MS);\n\n\tconst context = callContext(host, \"relay\");\n\tconst handler = createMcpHandler({\n\t\t...context,\n\t\t// Without `icons`, the page's own <link rel=\"icon\">, read now.\n\t\tserver: { ...host.server, icons: host.server.icons ?? pageIcons() },\n\t\tclient: (grant) => host.clientFor(grant),\n\t\tmaxBodyBytes: () => maxBodyBytes,\n\t});\n\tconst stopWatching = watchTools(host.registry, context.tools, () =>\n\t\thandler.toolsChanged(),\n\t);\n\n\tfunction send(message: TabMessage): boolean {\n\t\tif (ws.readyState !== WebSocket.OPEN) return false;\n\t\ttry {\n\t\t\tws.send(JSON.stringify(message));\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/** Two missed pings mean the connection is dead (protocol: heartbeat). */\n\tfunction armHeartbeat(): void {\n\t\tif (heartbeatMs <= 0) return;\n\t\tclearTimeout(heartbeat);\n\t\theartbeat = setTimeout(() => {\n\t\t\tbyeReason ??= \"heartbeat\";\n\t\t\tfinish(4003);\n\t\t\ttry {\n\t\t\t\tws.close();\n\t\t\t} catch {\n\t\t\t\t// already closing\n\t\t\t}\n\t\t}, heartbeatMs * 2.5);\n\t}\n\n\tfunction fail(error: Error): void {\n\t\tif (state !== \"opening\") return;\n\t\tfinish(0);\n\t\trejectReady(error);\n\t\ttry {\n\t\t\tws.close();\n\t\t} catch {\n\t\t\t// already closed\n\t\t}\n\t}\n\n\t/** The session is over: clean up once and tell the host. */\n\tfunction finish(code: number): void {\n\t\tif (state === \"closed\") return;\n\t\tconst wasReady = state === \"ready\";\n\t\tstate = \"closed\";\n\t\tclearTimeout(connectTimer);\n\t\tclearTimeout(heartbeat);\n\t\tstopWatching();\n\t\ttunnel.close();\n\t\thandler.close();\n\t\tif (wasReady) {\n\t\t\tconst reason =\n\t\t\t\tbyeReason ??\n\t\t\t\tCLOSE_REASONS[code] ??\n\t\t\t\t(code === 1006 ? \"network\" : \"closed\");\n\t\t\t// Over at once; only the detail of `replaced` waits for a sibling's\n\t\t\t// `claimed`, which comes a moment after the `bye` (DEC-095).\n\t\t\thost.closed(reason, code);\n\t\t\tif (reason === \"replaced\") {\n\t\t\t\tvoid siblings.heard().then((sibling) => {\n\t\t\t\t\tsiblings.close();\n\t\t\t\t\thost.replaced({ sibling });\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tsiblings.close();\n\t}\n\n\tconst tunnel = createTunnel({\n\t\thandler,\n\t\tsend,\n\t\tmaxChunk: () => maxChunk,\n\t\terror: (error) => host.error(error),\n\t});\n\n\tfunction onMessage(message: RelayMessage): void {\n\t\tif (state === \"opening\") {\n\t\t\tif (message.type === \"session\") {\n\t\t\t\tconst chunk = chunkSize(message.limits.maxMessageBytes);\n\t\t\t\tif (chunk === undefined) {\n\t\t\t\t\tfail(\n\t\t\t\t\t\trefused(\n\t\t\t\t\t\t\t`The relay's message limit (${message.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${MIN_MESSAGE_BYTES}.`,\n\t\t\t\t\t\t\t\"policy\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (revokeAll && message.grants.length > 0) {\n\t\t\t\t\t// A relay older than 0.5 ignores hello.revokeAll and lists the\n\t\t\t\t\t// grants: the address was not taken back (DEC-136).\n\t\t\t\t\tfail(\n\t\t\t\t\t\trefused(\n\t\t\t\t\t\t\t\"The relay did not revoke the address's grants (it needs tab-mcp 0.5 or later).\",\n\t\t\t\t\t\t\t\"policy\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmaxChunk = chunk;\n\t\t\t\tmaxBodyBytes = message.limits.maxBodyBytes;\n\t\t\t\tstate = \"ready\";\n\t\t\t\tclearTimeout(connectTimer);\n\t\t\t\theartbeatMs = message.limits.heartbeatMs;\n\t\t\t\tarmHeartbeat();\n\t\t\t\tsiblings.claimed();\n\t\t\t\tresolveReady(host.sessionStarted(message));\n\t\t\t} else if (message.type === \"error\") {\n\t\t\t\tfail(\n\t\t\t\t\trefused(\n\t\t\t\t\t\t`The relay refused the connection: ${message.message || message.code}`,\n\t\t\t\t\t\tmessage.code === \"rate_limited\" ? \"rate_limited\" : \"policy\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else if (message.type === \"bye\") {\n\t\t\t\tfail(\n\t\t\t\t\trefused(\n\t\t\t\t\t\t`The relay ended the connection: ${message.reason}`,\n\t\t\t\t\t\tBYE_REASONS[message.reason] ?? \"closed\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (state !== \"ready\") return;\n\t\tswitch (message.type) {\n\t\t\tcase \"ping\":\n\t\t\t\tarmHeartbeat();\n\t\t\t\tsend({ type: \"pong\", t: message.t });\n\t\t\t\treturn;\n\t\t\tcase \"http.request\":\n\t\t\t\ttunnel.request(message);\n\t\t\t\treturn;\n\t\t\tcase \"http.cancel\":\n\t\t\t\ttunnel.cancel(message.id);\n\t\t\t\treturn;\n\t\t\tcase \"pairing.code\":\n\t\t\t\thost.pairingCode(\n\t\t\t\t\tmessage.reason === undefined\n\t\t\t\t\t\t? { code: message.code, expiresAt: message.expiresAt }\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tcode: message.code,\n\t\t\t\t\t\t\t\texpiresAt: message.expiresAt,\n\t\t\t\t\t\t\t\treason: message.reason,\n\t\t\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\tcase \"grant.added\":\n\t\t\t\thost.grantAdded(message.grant);\n\t\t\t\treturn;\n\t\t\tcase \"grant.removed\":\n\t\t\t\thost.grantRemoved(message.grantId);\n\t\t\t\treturn;\n\t\t\tcase \"identity.bound\":\n\t\t\t\thost.identityResult(true, message.round);\n\t\t\t\treturn;\n\t\t\tcase \"bye\":\n\t\t\t\tbyeReason = BYE_REASONS[message.reason] ?? \"closed\";\n\t\t\t\t// Taken over: over at once, not when the socket closes (review of PR 39).\n\t\t\t\tif (byeReason === \"replaced\") finish(4005);\n\t\t\t\treturn;\n\t\t\tcase \"error\":\n\t\t\t\tif (message.code === \"identity_refused\") {\n\t\t\t\t\thost.identityResult(\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\ttypeof message.round === \"number\" ? message.round : undefined,\n\t\t\t\t\t\tmessage.message,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// The relay does not know a grant the page lists: it is gone (it\n\t\t\t\t// expired), and a `revoke()` of it resolves (DEC-168).\n\t\t\t\tif (\n\t\t\t\t\tmessage.code === \"unknown_id\" &&\n\t\t\t\t\tmessage.for === \"grant.revoke\" &&\n\t\t\t\t\ttypeof message.grantId === \"string\"\n\t\t\t\t)\n\t\t\t\t\thost.grantRemoved(message.grantId);\n\t\t\t\t// With its `code`, and what it answers (relay 0.10.2), so that\n\t\t\t\t// only the pending `revoke()` or `signOut()` it answers settles\n\t\t\t\t// (`store_unavailable`, `unknown_id`).\n\t\t\t\thost.error(\n\t\t\t\t\tObject.assign(\n\t\t\t\t\t\tnew Error(`Relay error ${message.code}: ${message.message}`),\n\t\t\t\t\t\t{ code: message.code },\n\t\t\t\t\t\ttypeof message.for === \"string\" ? { for: message.for } : {},\n\t\t\t\t\t\ttypeof message.grantId === \"string\"\n\t\t\t\t\t\t\t? { grantId: message.grantId }\n\t\t\t\t\t\t\t: {},\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\tcase \"session\":\n\t\t\t\treturn; // only once\n\t\t}\n\t}\n\n\tws.addEventListener(\"open\", () => {\n\t\tif (ws.protocol !== \"\" && ws.protocol !== SUBPROTOCOL) {\n\t\t\tfail(\n\t\t\t\trefused(\n\t\t\t\t\t`The relay speaks ${ws.protocol}, not ${SUBPROTOCOL}.`,\n\t\t\t\t\t\"policy\",\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tsend({\n\t\t\ttype: \"hello\",\n\t\t\tlibrary: host.library,\n\t\t\tapp:\n\t\t\t\thost.appName === undefined\n\t\t\t\t\t? { id: host.app }\n\t\t\t\t\t: { id: host.app, name: host.appName },\n\t\t\tsecret,\n\t\t\t...(revokeAll ? { revokeAll: true } : {}),\n\t\t});\n\t});\n\tws.addEventListener(\"message\", (event: MessageEvent) => {\n\t\tif (typeof event.data !== \"string\") return;\n\t\t// A frame the tab cannot read is dropped without an answer (CC 15): the\n\t\t// relay only logged one, and its request ends at its own timeout.\n\t\tconst message = parseRelayMessage(event.data);\n\t\tif (message === undefined) return;\n\t\tif (state === \"ready\") armHeartbeat(); // any traffic shows the link is alive\n\t\tonMessage(message);\n\t});\n\tws.addEventListener(\"close\", (event: CloseEvent) => {\n\t\tif (state === \"opening\") {\n\t\t\tfinish(event.code);\n\t\t\t// No WebSocket at all: browsers say 1006, Bun 1002. The page cannot\n\t\t\t// tell a refused origin from an unreachable relay (DEC-082).\n\t\t\tconst unreachable = event.code === 1006 || event.code === 1002;\n\t\t\trejectReady(\n\t\t\t\trefused(\n\t\t\t\t\tunreachable\n\t\t\t\t\t\t? \"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).\"\n\t\t\t\t\t\t: `The relay closed the connection (${event.code}${event.reason ? `: ${event.reason}` : \"\"}).`,\n\t\t\t\t\tCLOSE_REASONS[event.code] ?? (unreachable ? \"network\" : \"closed\"),\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tfinish(event.code);\n\t});\n\n\treturn {\n\t\tready,\n\t\tsend,\n\t\tclose(reason: DisconnectReason) {\n\t\t\tif (state === \"closed\") return;\n\t\t\tif (state === \"opening\") {\n\t\t\t\tfail(\n\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\"The connection was cancelled\",\n\t\t\t\t\t\t\"AbortError\",\n\t\t\t\t\t) as Error,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbyeReason = reason;\n\t\t\tsend({ type: \"bye\", reason: \"user\" });\n\t\t\tfinish(1000);\n\t\t\ttry {\n\t\t\t\tws.close(1000, \"bye\");\n\t\t\t} catch {\n\t\t\t\t// already closed\n\t\t\t}\n\t\t},\n\t};\n}\n"
12
- ],
13
- "mappings": ";AAQA,IAAM,YAAY;AAClB,IAAM,UAAU;AAChB,IAAM,WAAW;AACjB,IAAM,OAAO;AAOb,SAAS,KAAK,CAAC,MAA8B;AAAA,EAC5C,QAAQ,KAAK,UAAU,OAAO,UAAU;AAAA,EACxC,IAAI,OAAO,QAAQ;AAAA,IAAU;AAAA,EAC7B,MAAM,MAAM,YAAY,KAAK,GAAG,KAAK,IAAI,UAAU;AAAA,EACnD,MAAM,OACL,sEAAsE,KACrE,GACD,KAAK,IAAI,UAAU;AAAA,EACpB,IAAI,CAAC,OAAO,CAAC;AAAA,IAAM;AAAA,EACnB,MAAM,MAAY,EAAE,IAAI;AAAA,EACxB,IAAI,OAAO,aAAa,YAAY,qBAAqB,KAAK,QAAQ,GAAG;AAAA,IACxE,IAAI,WAAW,SAAS,YAAY;AAAA,EACrC;AAAA,EACA,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAC9B,MAAM,IAAI,CAAC,MAAM,OAAO,CAAC,EAAE,YAAY,CAAC,EAAE,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC,IACpE,CAAC;AAAA,EACJ,IAAI,MAAM,SAAS;AAAA,IAAG,IAAI,QAAQ;AAAA,EAClC,IAAI,UAAU,WAAW,UAAU;AAAA,IAAQ,IAAI,QAA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