@ractive-ch/tab-mcp-client 0.23.0 → 0.24.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.md +56 -16
- package/cdn/connection-vxpnd3ex.min.js +17 -0
- package/cdn/{connection-m0e4xvcy.min.js.map → connection-vxpnd3ex.min.js.map} +5 -5
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +3 -3
- package/cdn/webmcp-jtsqzqas.min.js +4 -0
- package/cdn/webmcp-jtsqzqas.min.js.map +11 -0
- package/{connection-fnkfrvpc.js → connection-gqec88qp.js} +23 -10
- package/connection-gqec88qp.js.map +16 -0
- package/connection.d.ts +8 -4
- package/extension.d.ts +10 -0
- package/extension.js +3 -1
- package/extension.js.map +3 -3
- package/handshake.d.ts +24 -5
- package/index.js +15 -6
- package/index.js.map +3 -3
- package/mapping.d.ts +10 -1
- package/mcp.d.ts +8 -2
- package/package.json +1 -1
- package/skill/SKILL.md +13 -7
- package/skill/references/react.md +1 -1
- package/types.d.ts +22 -8
- package/{webmcp-wwma7nps.js → webmcp-ctk4bd8c.js} +7 -5
- package/webmcp-ctk4bd8c.js.map +11 -0
- package/webmcp.d.ts +4 -3
- package/cdn/connection-m0e4xvcy.min.js +0 -17
- package/cdn/webmcp-kkrmjqfh.min.js +0 -4
- package/cdn/webmcp-kkrmjqfh.min.js.map +0 -11
- package/connection-fnkfrvpc.js.map +0 -16
- package/webmcp-wwma7nps.js.map +0 -11
package/extension.js.map
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/extension.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * `@ractive-ch/tab-mcp-client/extension`: for a browser extension that is a\n * tab-mcp page itself (the tab-mcp browser extension, Sitegloss). It fills\n * in the extension's own pairing code on the relay's pairing page\n * (`/authorize`) when an AI app opens it in the same browser, after asking\n * the user (DEC-199, DEC-203). What is the same for every such extension\n * lives here, reviewed once (DEC-206); how the user is asked, where the\n * setting is kept, the permission prompt, the content script's registration\n * and holding pairing on are each extension's own, given as callbacks.\n *\n * The relay's page has no scripts (DEC-057), so it cannot call the\n * extension: a content script reads the form's `data-tab-mcp-*` hooks and\n * tells the worker who asks (the AI app's name and verified host). The\n * worker asks its user and, on Allow, hands the code to that one page over\n * its port. The content script never sees a code before that, and the\n * worker never takes a page's word for where it is: any site can copy the\n * markup, so the origin the browser reports for the port is the check.\n *\n * An entry of its own that a web page never loads, out of the core. It\n * imports nothing of the rest of the library at run time and touches no\n * `window` or `document` until called, so a service worker and a content\n * script can both import it; a content script's bundle keeps only the page\n * side (`runPairingPage` and what it uses). No `chrome` types: the browser's\n * ports and senders are taken as the small structural types below.\n *\n * ```ts\n * // The content script, registered for the relay's /authorize page:\n * import { PAIRING_PORT, runPairingPage } from \"@ractive-ch/tab-mcp-client/extension\";\n * runPairingPage({ app: \"my-app\", connect: () => chrome.runtime.connect({ name: PAIRING_PORT }) });\n *\n * // The worker:\n * import { CodeFiller, PAIRING_PORT, pagePort } from \"@ractive-ch/tab-mcp-client/extension\";\n * const filler = new CodeFiller({ extensionId: chrome.runtime.id, app: \"my-app\", ... });\n * chrome.runtime.onConnect.addListener((port) => {\n * if (port.name === PAIRING_PORT) void filler.page(pagePort(port));\n * });\n * ```\n */\n\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type { PairingCode } from \"./types.ts\";\n\n// --- What the content script and the worker say to each other ---\n\n/** The name of the port a pairing page's content script opens. */\nexport const PAIRING_PORT = \"pairing-page\";\n\n/** The relay's pairing page. */\nexport const PAIRING_PATH = \"/authorize\";\n\n/** What the content script says once, on its page's port. */\nexport interface PairingHello {\n\ttype: \"pairing-page\";\n\t/** This page load's own: the code comes back only with it. */\n\tnonce: string;\n\t/** `data-app`: the app the AI app asks to connect to. */\n\tapp: string;\n\t/** `data-client-name`: the AI app's name for itself. */\n\tclientName: string;\n\t/** `data-client-host`: the host the relay verified for the AI app. */\n\tclientHost: string;\n\t/**\n\t * The form's hidden `request_id`: the relay's id of this authorization\n\t * request, the same on its page again after a wrong code. The one fill\n\t * without a question is for this request only.\n\t */\n\trequestId: string;\n}\n\n/** What the worker sends after the user's Allow: the code to fill in and submit. */\nexport interface FillMessage {\n\ttype: \"fill\";\n\tnonce: string;\n\tcode: string;\n}\n\n/** The longest name and host a hello may carry (the relay's own limits are lower). */\nexport const MAX_CLIENT_NAME = 200;\nexport const MAX_CLIENT_HOST = 253;\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\n\n/**\n * The content script's hello, checked; `undefined` for anything else. The\n * name and host are what the relay's page says, kept as they are: the\n * extension's question must show invisible characters escaped (`./visible`).\n */\nexport function parseHello(message: unknown): PairingHello | undefined {\n\tif (typeof message !== \"object\" || message === null) return undefined;\n\tconst m = message as Record<string, unknown>;\n\tif (\n\t\tm[\"type\"] !== \"pairing-page\" ||\n\t\t!isString(m[\"nonce\"]) ||\n\t\t!/^[\\w-]{16,64}$/.test(m[\"nonce\"]) ||\n\t\t!isString(m[\"app\"]) ||\n\t\t!isString(m[\"clientName\"]) ||\n\t\t!isString(m[\"clientHost\"]) ||\n\t\tm[\"clientHost\"] === \"\" ||\n\t\t!isString(m[\"requestId\"]) ||\n\t\t!/^[\\w-]{1,128}$/.test(m[\"requestId\"]) ||\n\t\tm[\"clientName\"].length > MAX_CLIENT_NAME ||\n\t\tm[\"clientHost\"].length > MAX_CLIENT_HOST\n\t)\n\t\treturn undefined;\n\treturn {\n\t\ttype: \"pairing-page\",\n\t\tnonce: m[\"nonce\"],\n\t\tapp: m[\"app\"],\n\t\tclientName: m[\"clientName\"],\n\t\tclientHost: m[\"clientHost\"],\n\t\trequestId: m[\"requestId\"],\n\t};\n}\n\n/** The worker's fill message, checked against this page's nonce. */\nexport function parseFill(\n\tmessage: unknown,\n\tnonce: string,\n): FillMessage | undefined {\n\tif (typeof message !== \"object\" || message === null) return undefined;\n\tconst m = message as Record<string, unknown>;\n\treturn m[\"type\"] === \"fill\" &&\n\t\tm[\"nonce\"] === nonce &&\n\t\tisString(m[\"code\"]) &&\n\t\tm[\"code\"] !== \"\"\n\t\t? { type: \"fill\", nonce, code: m[\"code\"] }\n\t\t: undefined;\n}\n\n// --- Where the relay's pages are ---\n\n/**\n * The origin of the relay's web pages for the relay address `relay`: its\n * `ws:`/`wss:` forms are the same server's `http:`/`https:`. `undefined` for\n * anything that is not one.\n */\nexport function relayPageOrigin(relay: string): string | undefined {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(relay);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tconst scheme =\n\t\turl.protocol === \"wss:\"\n\t\t\t? \"https:\"\n\t\t\t: url.protocol === \"ws:\"\n\t\t\t\t? \"http:\"\n\t\t\t\t: url.protocol;\n\tif (scheme !== \"https:\" && scheme !== \"http:\") return undefined;\n\treturn `${scheme}//${url.host}`;\n}\n\n/**\n * The match pattern for the relay's host, without its port: Firefox's\n * patterns take none, and Chrome's without one match every port. The exact\n * origin, port and all, is checked in the content script and in the worker.\n * The host in lower case without a trailing dot; one that is no plain name\n * or IPv4 address (an IPv6 literal, say) gives no pattern, as the browsers\n * do not agree on one for it.\n */\nfunction hostPattern(relay: string, path: string): string | undefined {\n\tconst origin = relayPageOrigin(relay);\n\tif (origin === undefined) return undefined;\n\tconst { protocol, hostname } = new URL(origin);\n\tconst host = hostname.toLowerCase().replace(/\\.$/, \"\");\n\tif (!/^[a-z0-9-]+(\\.[a-z0-9-]+)*$/.test(host)) return undefined;\n\treturn `${protocol}//${host}${path}`;\n}\n\n/**\n * The host permission for the relay's site (`<scheme>://<host>/*`), the one\n * origin to ask for (`permissions.request({ origins: [it] })`) before the\n * extension can see the pairing page. `undefined` for an address that has\n * no pattern: the user types the code.\n */\nexport function relaySitePattern(relay: string): string | undefined {\n\treturn hostPattern(relay, \"/*\");\n}\n\n/** The match pattern of the relay's pairing page, for a content script's `matches`. */\nexport function pairingPagePattern(relay: string): string | undefined {\n\treturn hostPattern(relay, `${PAIRING_PATH}*`);\n}\n\n// --- The content script on the relay's page ---\n\n/** The page's pairing form, as far as filling it in needs it. */\nexport interface PairingForm {\n\tform: HTMLFormElement;\n\tfield: HTMLInputElement;\n\tbutton: HTMLButtonElement;\n\tapp: string;\n\tclientName: string;\n\tclientHost: string;\n\t/** The relay's id of this request (the form's hidden `request_id`). */\n\trequestId: string;\n}\n\n/**\n * The pairing form of app `app` on `doc`, if this is a top-level page at\n * `/authorize` with exactly one such form that has a code field and a\n * Connect button (DEC-199's hooks, version 1). The worker checks the origin\n * itself; this only spares it the pages that are not one. A page that pairs\n * by sign-in only has no code field.\n */\nexport function findPairingForm(\n\tdoc: Document,\n\twhere: { topLevel: boolean; pathname: string },\n\tapp: string,\n): PairingForm | undefined {\n\tif (!where.topLevel || where.pathname !== PAIRING_PATH) return undefined;\n\tconst forms = doc.querySelectorAll<HTMLFormElement>(\n\t\t'form[data-tab-mcp-pairing=\"1\"]',\n\t);\n\tconst [form] = forms;\n\tif (forms.length !== 1 || form === undefined) return undefined;\n\tif (form.dataset[\"app\"] !== app) return undefined;\n\tconst field = form.querySelector<HTMLInputElement>(\n\t\t'input[data-tab-mcp-field=\"code\"]',\n\t);\n\tconst button = form.querySelector<HTMLButtonElement>(\n\t\t'button[data-tab-mcp-action=\"connect\"]',\n\t);\n\tconst clientName = form.dataset[\"clientName\"];\n\tconst clientHost = form.dataset[\"clientHost\"];\n\tconst requestId = form.querySelector<HTMLInputElement>(\n\t\t'input[type=\"hidden\"][name=\"request_id\"]',\n\t)?.value;\n\tif (\n\t\tfield === null ||\n\t\tbutton === null ||\n\t\tclientName === undefined ||\n\t\tclientHost === undefined ||\n\t\tclientHost === \"\" ||\n\t\t!requestId\n\t)\n\t\treturn undefined;\n\treturn { form, field, button, app, clientName, clientHost, requestId };\n}\n\n/**\n * Write `code` into the form's field and submit it with its Connect button:\n * the page's own post, as if the user had typed it and clicked.\n */\nexport function fillIn(found: PairingForm, code: string): void {\n\tfound.field.value = code;\n\t// The document's own Event (a test's DOM need not be the global one).\n\tconst Input = found.field.ownerDocument.defaultView?.Event ?? Event;\n\tfound.field.dispatchEvent(new Input(\"input\", { bubbles: true }));\n\tfound.form.requestSubmit(found.button);\n}\n\n/** The hello for `found`, with this page load's nonce. */\nexport function helloFor(found: PairingForm, nonce: string): PairingHello {\n\treturn {\n\t\ttype: \"pairing-page\",\n\t\tnonce,\n\t\tapp: found.app,\n\t\tclientName: found.clientName,\n\t\tclientHost: found.clientHost,\n\t\trequestId: found.requestId,\n\t};\n}\n\n/** The content script's end of its port (`chrome.runtime.Port` is one). */\nexport interface ContentPort {\n\tpostMessage(message: unknown): void;\n\treadonly onMessage: {\n\t\taddListener(listener: (message: unknown) => void): void;\n\t};\n}\n\n/**\n * The content script of the relay's pairing page: if the page has app\n * `app`'s pairing form, open a port to the worker (`connect`, with the name\n * PAIRING_PORT), say who asks, and wait. Only the worker's fill with this\n * page load's nonce is taken, once: its code is written into the field and\n * the form submitted. Once per document, also if the script is put in again\n * (after the user gave access with the page already open). Whether the\n * page has the form. `page` is the content script's own page unless a test\n * gives one.\n */\nexport function runPairingPage(options: {\n\tapp: string;\n\tconnect: () => ContentPort;\n\tpage?: { document: Document; topLevel: boolean; pathname: string };\n}): boolean {\n\tconst flag = \"__tabMcpPairingPage\";\n\t// A content script put in again runs in the same isolated world, so its\n\t// global marks the document. The document a test gives carries the mark\n\t// itself: two such pages in one test are independent.\n\tconst scope = (options.page?.document ?? globalThis) as unknown as Record<\n\t\tstring,\n\t\tunknown\n\t>;\n\tif (scope[flag] === true) return false;\n\tscope[flag] = true;\n\tconst page = options.page ?? {\n\t\tdocument,\n\t\ttopLevel: window.top === window,\n\t\tpathname: location.pathname,\n\t};\n\tconst found = findPairingForm(page.document, page, options.app);\n\tif (found === undefined) return false;\n\tconst nonce = crypto.randomUUID();\n\tconst port = options.connect();\n\tlet filled = false;\n\tport.onMessage.addListener((message) => {\n\t\tconst fill = parseFill(message, nonce);\n\t\t// One fill per page load: the page posts and goes.\n\t\tif (fill === undefined || filled) return;\n\t\tfilled = true;\n\t\tfillIn(found, fill.code);\n\t});\n\tport.postMessage(helloFor(found, nonce));\n\treturn true;\n}\n\n// --- The worker ---\n\n/** The sender of a port, as far as the check needs it (`chrome.runtime.MessageSender`). */\nexport interface PageSender {\n\tid?: string;\n\turl?: string;\n\t/** Chrome gives the document's origin; Firefox may not. */\n\torigin?: string;\n\ttab?: unknown;\n\tframeId?: number;\n}\n\n/**\n * A port from the pairing page of the relay at `relayOrigin`: this\n * extension's content script, in a tab, in its top frame, on a page whose\n * origin is exactly the relay's (port included) and whose path is\n * `/authorize`. A page anywhere else can carry the same markup: it is\n * ignored.\n */\nexport function isPairingSender(\n\tsender: PageSender,\n\textensionId: string,\n\trelayOrigin: string | undefined,\n): boolean {\n\tif (relayOrigin === undefined) return false;\n\tif (sender.id !== extensionId) return false;\n\tif (sender.tab === undefined || sender.frameId !== 0) return false;\n\t// Where the browser gives the document's origin, it is the one to trust\n\t// (a URL can be a `blob:` or `about:` of another origin's making).\n\tif (sender.origin !== undefined && sender.origin !== relayOrigin)\n\t\treturn false;\n\ttry {\n\t\tconst url = new URL(sender.url ?? \"\");\n\t\treturn url.origin === relayOrigin && url.pathname === PAIRING_PATH;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** A page will not say who asks in this time: it is dropped. */\nexport const HELLO_WAIT_MS = 5_000;\n/**\n * The same request's page in the same tab within this time after a fill is\n * the relay's answer to it: the code was not taken.\n */\nexport const RETRY_WINDOW_MS = 30_000;\n/** `takeCode`: how long to wait for the next code. */\nexport const CODE_WAIT_MS = 10_000;\n/** `takeCode`: a code with less time left than this is not used, the next one is. */\nexport const MIN_CODE_LEFT_MS = 5_000;\n/**\n * A filled-in page's port is closed this long after the fill: the page has\n * posted by then, and its answer, if any, is a new document with a port of\n * its own.\n */\nexport const FILLED_CLOSE_MS = 5_000;\n\n/** The worker's end of a page's port (`chrome.runtime.Port` is one). */\nexport interface WorkerPort {\n\treadonly sender?: PageSender;\n\tpostMessage(message: unknown): void;\n\tdisconnect(): void;\n\treadonly onMessage: {\n\t\taddListener(listener: (message: unknown) => void): void;\n\t\tremoveListener(listener: (message: unknown) => void): void;\n\t};\n\treadonly onDisconnect: { addListener(listener: () => void): void };\n}\n\n/**\n * A pairing page's port in the worker. Its first message and its end are\n * taken from the moment it connects: the worker may still be starting, and\n * Chrome hands a message only to the listeners there are.\n */\nexport interface PagePort {\n\treadonly sender: PageSender;\n\t/** The first message; `undefined` if the port went before one came. */\n\treadonly hello: Promise<unknown>;\n\t/** Aborted when the page goes (or the worker closes the port). */\n\treadonly signal: AbortSignal;\n\tsend(message: FillMessage): void;\n\tclose(): void;\n}\n\n/**\n * `port`, taken over at once (see PagePort): call it in `onConnect` itself,\n * before any `await`.\n */\nexport function pagePort(port: WorkerPort): PagePort {\n\tconst gone = new AbortController();\n\tlet first: (message: unknown) => void = () => {};\n\tconst hello = new Promise<unknown>((resolve) => {\n\t\tfirst = resolve;\n\t});\n\tconst take = (message: unknown) => {\n\t\tport.onMessage.removeListener(take);\n\t\tfirst(message);\n\t};\n\tport.onMessage.addListener(take);\n\tport.onDisconnect.addListener(() => {\n\t\tgone.abort();\n\t\tfirst(undefined);\n\t});\n\treturn {\n\t\tsender: port.sender ?? {},\n\t\thello,\n\t\tsignal: gone.signal,\n\t\tsend: (message) => {\n\t\t\ttry {\n\t\t\t\tport.postMessage(message);\n\t\t\t} catch {\n\t\t\t\t// The page went meanwhile.\n\t\t\t}\n\t\t},\n\t\tclose: () => {\n\t\t\tif (gone.signal.aborted) return;\n\t\t\t// Our own `disconnect()` fires no `onDisconnect` here.\n\t\t\tgone.abort();\n\t\t\tfirst(undefined);\n\t\t\ttry {\n\t\t\t\tport.disconnect();\n\t\t\t} catch {\n\t\t\t\t// Gone already.\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * The user's answer to \"Connect <name> (<host>)?\": only `allow` fills in.\n * `busy`: the extension could not ask (too many questions wait); the page is\n * reported (`failed(\"busy\")`), not dropped unseen.\n */\nexport type FillAnswer = \"allow\" | \"deny\" | \"timeout\" | \"busy\";\n\n/** Why a page that asked got no code: the extension tells its user. */\nexport type FillFailure =\n\t/** It could not be asked about (`ask` answered `busy`). */\n\t| \"busy\"\n\t/** Allow, but no code came from the relay (`code` gave none). */\n\t| \"no-code\";\n\n/** The page a fill is for: its tab and the AI app that asks there. */\nexport interface FillContext {\n\ttabId: number;\n\t/** The AI app's own name (may be `\"\"`) and the host the relay verified, as `ask` gets them. */\n\tclient: { name: string; host: string };\n}\n\n/** What `CodeFiller` needs from the extension: its parts of the fill-in. */\nexport interface FillHost {\n\t/** This extension's id (`chrome.runtime.id`): only its own content script speaks. */\n\textensionId: string;\n\t/** The app id of the extension's page: only forms with this `data-app`. */\n\tapp: string;\n\t/**\n\t * The origin of the relay's pages (`relayPageOrigin`) whose pairing page\n\t * may be filled in; `undefined` for none (another relay than the one the\n\t * extension fills in for).\n\t */\n\trelayOrigin(): string | undefined;\n\t/** AI access is on: connected, or on its way. Off, nothing is asked. */\n\taiOn(): boolean;\n\t/** The user turned filling in on, for this relay (opt-in, off by default). */\n\tenabled(): boolean;\n\t/**\n\t * Ask the user whether to connect the AI app `client` (its own name for\n\t * itself and the host the relay verified, both to be shown with invisible\n\t * characters escaped) in tab `tabId`. `signal` withdraws the question:\n\t * the page went, AI access or the setting went off, the relay changed,\n\t * or the AI app connected meanwhile; answer then with anything but\n\t * `allow`.\n\t */\n\task(\n\t\ttabId: number,\n\t\tclient: { name: string; host: string },\n\t\tsignal: AbortSignal,\n\t): Promise<FillAnswer>;\n\t/**\n\t * The code to fill in now on the page `context`, with pairing held on for\n\t * the relay to check it (`takeCode`); `undefined` if none came or\n\t * `signal` aborted (the page went, or the fill was withdrawn as a\n\t * question is). Even with a code, nothing is sent if what holds for\n\t * asking no longer does.\n\t */\n\tcode(signal: AbortSignal, context: FillContext): Promise<string | undefined>;\n\t/**\n\t * No fill needs pairing held on any more: a filled-in code paired its AI\n\t * app, or a fill ended without sending its code (withdrawn, the page\n\t * went, no code) while no other fill is under way or waits for the\n\t * relay's check. It may come again with nothing held: ignore it then.\n\t */\n\trelease(): void;\n\t/** The page `context` filled in nothing for `why`, or was not asked about: say so. */\n\tfailed(why: FillFailure, context: FillContext): void;\n\t/** The clock (`Date.now`; a test's own). */\n\tnow(): number;\n}\n\n/** A page whose question waits. */\ninterface Waiting {\n\thost: string;\n\twithdraw: AbortController;\n}\n\n/** The last fill in a tab. */\ninterface Filled {\n\t/** The relay's id of the request filled in. */\n\trequestId: string;\n\thost: string;\n\t/** Fills for it so far: 1 after Allow, 2 after the one more. */\n\tcount: number;\n\tat: number;\n}\n\nconst tabIdOf = (sender: PageSender): number | undefined => {\n\tconst id = (sender.tab as { id?: unknown } | undefined)?.id;\n\treturn typeof id === \"number\" ? id : undefined;\n};\n\nfunction within<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\treturn Promise.race([\n\t\tpromise,\n\t\tnew Promise<undefined>((resolve) => {\n\t\t\ttimer = setTimeout(() => resolve(undefined), ms);\n\t\t}),\n\t]).finally(() => clearTimeout(timer));\n}\n\n/**\n * The worker's side of filling in the code (DEC-199, DEC-203): a page's port\n * is taken only from this extension's content script in the top frame of a\n * tab at exactly the relay's origin, and only while AI access is on and the\n * user turned filling in on. Then the user is asked, with the AI app's\n * verified host; on Allow the code goes to that one page, which fills it in\n * and submits.\n *\n * No loops: one question per page load (one port per document, one hello\n * per port). When the same tab shows the page of the same request (the\n * relay's `request_id`) again soon after a fill, it is the relay's answer\n * that the code was not taken (it had just changed): filled once more with\n * the code of then, without asking; the time after, nothing. Any other\n * request asks. With `retry: false` that page is asked about like any\n * other: every fill has a yes of its own. Don't allow, a timeout, the page\n * going, AI access or the setting going off, another relay or the AI app\n * connecting meanwhile fill nothing, and typing by hand works as before.\n */\nexport class CodeFiller {\n\treadonly #host: FillHost;\n\treadonly #waiting = new Set<Waiting>();\n\t/**\n\t * By tab: what was filled in there last, or is being filled in (marked\n\t * before the wait for the code, so that a page of the same request\n\t * meanwhile counts it).\n\t */\n\treadonly #filled = new Map<number, Filled>();\n\t/**\n\t * The grants seen so far: a new one is an AI app that just connected.\n\t * `undefined` until the first list, which is taken as it is: a worker\n\t * that starts before its connection is up has none to compare with.\n\t */\n\t#grants: Set<string> | undefined;\n\treadonly #closeAfterMs: number;\n\treadonly #retry: boolean;\n\n\t/**\n\t * `grants`: the ids of the grants there are already, if the extension kept\n\t * them between worker starts (not new when listed again); without them,\n\t * the first `grantsChanged` is taken as the list there is, nothing in it\n\t * new. `retry`: the one more fill without asking when the same request's\n\t * page comes back to the same tab soon after a fill (on unless `false`;\n\t * off, that page is asked about like any other, one question per page\n\t * load, and never filled without a yes). `closeAfterMs`: FILLED_CLOSE_MS\n\t * unless a test's is shorter.\n\t */\n\tconstructor(\n\t\thost: FillHost,\n\t\toptions: {\n\t\t\tgrants?: Iterable<string>;\n\t\t\tretry?: boolean;\n\t\t\tcloseAfterMs?: number;\n\t\t} = {},\n\t) {\n\t\tthis.#host = host;\n\t\tthis.#grants =\n\t\t\toptions.grants === undefined ? undefined : new Set(options.grants);\n\t\tthis.#retry = options.retry ?? true;\n\t\tthis.#closeAfterMs = options.closeAfterMs ?? FILLED_CLOSE_MS;\n\t}\n\n\t/**\n\t * A pairing page's port: checked, then asked about and maybe filled in.\n\t * Never rejects: a host callback that throws fills nothing, closes the\n\t * port and is logged.\n\t */\n\tasync page(port: PagePort): Promise<void> {\n\t\ttry {\n\t\t\tawait this.#page(port);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"tab-mcp: pairing page\", error);\n\t\t\tport.close();\n\t\t}\n\t}\n\n\tasync #page(port: PagePort): Promise<void> {\n\t\tconst host = this.#host;\n\t\tconst tabId = tabIdOf(port.sender);\n\t\tif (\n\t\t\ttabId === undefined ||\n\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin())\n\t\t) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tconst hello = parseHello(await within(port.hello, HELLO_WAIT_MS));\n\t\t// Only this extension's own app, only if the user turned filling in\n\t\t// on, only while AI access is on, and only while the relay is still\n\t\t// the one the page is of (it may have changed during the wait for\n\t\t// the hello): otherwise they have not asked for it.\n\t\tif (\n\t\t\thello === undefined ||\n\t\t\thello.app !== host.app ||\n\t\t\tport.signal.aborted ||\n\t\t\t!host.enabled() ||\n\t\t\t!host.aiOn() ||\n\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin())\n\t\t) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tconst context: FillContext = {\n\t\t\ttabId,\n\t\t\tclient: { name: hello.clientName, host: hello.clientHost },\n\t\t};\n\t\tconst before = this.#lastFill(tabId);\n\t\tif (this.#retry && before?.requestId === hello.requestId) {\n\t\t\t// The same request's page again after a fill: the code was not\n\t\t\t// taken. Once more with the code of now, then never again for it.\n\t\t\tif (before.count === 1) await this.#fill(port, context, hello, 2);\n\t\t\telse port.close();\n\t\t\treturn;\n\t\t}\n\t\tconst waiting: Waiting = {\n\t\t\thost: hello.clientHost,\n\t\t\twithdraw: new AbortController(),\n\t\t};\n\t\tthis.#waiting.add(waiting);\n\t\tconst signal = AbortSignal.any([port.signal, waiting.withdraw.signal]);\n\t\tlet answer: FillAnswer;\n\t\ttry {\n\t\t\tanswer = await host.ask(tabId, { ...context.client }, signal);\n\t\t} finally {\n\t\t\tthis.#waiting.delete(waiting);\n\t\t}\n\t\t// Too many questions wait: not dropped unseen.\n\t\tif (answer === \"busy\") host.failed(\"busy\", context);\n\t\tif (\n\t\t\tanswer !== \"allow\" ||\n\t\t\tsignal.aborted ||\n\t\t\t!host.enabled() ||\n\t\t\t!host.aiOn() ||\n\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin())\n\t\t) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tawait this.#fill(port, context, hello, 1);\n\t}\n\n\t/**\n\t * Whether a fill is under way or was sent recently enough for the relay\n\t * to be checking its code (the tabs' last fills, the stale ones dropped).\n\t */\n\t#anyFill(): boolean {\n\t\tthis.#dropStale();\n\t\treturn this.#filled.size > 0;\n\t}\n\n\t/** The last fill in `tabId`, if it is recent enough to be answered by this page. */\n\t#lastFill(tabId: number): Filled | undefined {\n\t\tthis.#dropStale();\n\t\treturn this.#filled.get(tabId);\n\t}\n\n\t#dropStale(): void {\n\t\tconst now = this.#host.now();\n\t\tfor (const [id, filled] of this.#filled)\n\t\t\tif (now - filled.at > RETRY_WINDOW_MS) this.#filled.delete(id);\n\t}\n\n\t/**\n\t * Fill `count` (1 after Allow, 2 the one more) of `hello`'s request in\n\t * `tabId`. The wait for the code is withdrawn like a question, and what\n\t * holds for asking is checked again once the code is there.\n\t */\n\tasync #fill(\n\t\tport: PagePort,\n\t\tcontext: FillContext,\n\t\thello: PairingHello,\n\t\tcount: number,\n\t): Promise<void> {\n\t\tconst host = this.#host;\n\t\tconst { tabId } = context;\n\t\tconst before = this.#filled.get(tabId);\n\t\t// Marked before the wait: a page of the same request that comes\n\t\t// meanwhile sees this count, so there is never a third fill.\n\t\tconst mark: Filled = {\n\t\t\trequestId: hello.requestId,\n\t\t\thost: hello.clientHost,\n\t\t\tcount,\n\t\t\tat: host.now(),\n\t\t};\n\t\tthis.#filled.set(tabId, mark);\n\t\tconst waiting: Waiting = {\n\t\t\thost: hello.clientHost,\n\t\t\twithdraw: new AbortController(),\n\t\t};\n\t\tthis.#waiting.add(waiting);\n\t\tconst signal = AbortSignal.any([port.signal, waiting.withdraw.signal]);\n\t\tlet sent = false;\n\t\t// A page that went or a code that did not come leaves the tab's last\n\t\t// fill as it was; a withdrawal leaves nothing to fill once more.\n\t\tlet keepBefore = true;\n\t\ttry {\n\t\t\tconst code = await host.code(signal, {\n\t\t\t\ttabId,\n\t\t\t\tclient: { ...context.client },\n\t\t\t});\n\t\t\tconst off =\n\t\t\t\twaiting.withdraw.signal.aborted ||\n\t\t\t\t!host.enabled() ||\n\t\t\t\t!host.aiOn() ||\n\t\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin());\n\t\t\tif (off) keepBefore = false;\n\t\t\tif (off || port.signal.aborted) return;\n\t\t\tif (code === undefined) {\n\t\t\t\thost.failed(\"no-code\", { tabId, client: { ...context.client } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tmark.at = host.now();\n\t\t\tport.send({ type: \"fill\", nonce: hello.nonce, code });\n\t\t\tsent = true;\n\t\t\tsetTimeout(() => port.close(), this.#closeAfterMs);\n\t\t} finally {\n\t\t\tthis.#waiting.delete(waiting);\n\t\t\tif (!sent) {\n\t\t\t\tport.close();\n\t\t\t\tif (this.#filled.get(tabId) === mark) {\n\t\t\t\t\tif (keepBefore && before !== undefined)\n\t\t\t\t\t\tthis.#filled.set(tabId, before);\n\t\t\t\t\telse this.#filled.delete(tabId);\n\t\t\t\t}\n\t\t\t\t// `code` may have held pairing on for this fill: with no other\n\t\t\t\t// fill to hold it for, the host need not keep it on.\n\t\t\t\tif (!this.#anyFill()) host.release();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The relay's list of grants (`grantschange`): an AI app that just\n\t * connected (typed by hand, or filled in) withdraws the questions for its\n\t * host, and its fills are done with.\n\t */\n\tgrantsChanged(grants: readonly { grantId: string; host: string }[]): void {\n\t\tif (this.#grants === undefined) {\n\t\t\t// The first list without a seed: the grants there are, none new.\n\t\t\tthis.#grants = new Set(grants.map((grant) => grant.grantId));\n\t\t\treturn;\n\t\t}\n\t\tconst connected = new Set<string>();\n\t\tfor (const grant of grants)\n\t\t\tif (!this.#grants.has(grant.grantId)) {\n\t\t\t\tthis.#grants.add(grant.grantId);\n\t\t\t\tconnected.add(grant.host);\n\t\t\t}\n\t\tif (connected.size === 0) return;\n\t\tfor (const waiting of this.#waiting)\n\t\t\tif (connected.has(waiting.host)) waiting.withdraw.abort();\n\t\tlet done = false;\n\t\tfor (const [tabId, filled] of this.#filled)\n\t\t\tif (connected.has(filled.host)) {\n\t\t\t\tthis.#filled.delete(tabId);\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t// Another AI app's fill may still be under way or wait for the relay's\n\t\t// check: stopping pairing now would void its code.\n\t\tif (done && !this.#anyFill()) this.#host.release();\n\t}\n\n\t/**\n\t * AI access off, or filling in turned off: the questions waiting are\n\t * withdrawn and no page gets the one more fill.\n\t */\n\twithdrawAll(): void {\n\t\tfor (const waiting of this.#waiting) waiting.withdraw.abort();\n\t\tthis.#filled.clear();\n\t}\n\n\t/**\n\t * Another relay: no page of the one before is asked about or filled in,\n\t * and the new relay's first list of grants is taken as it is.\n\t */\n\treset(): void {\n\t\tthis.withdrawAll();\n\t\tthis.#grants = undefined;\n\t}\n}\n\n/** Where the pairing codes come from (`pairingCodes(mcp)`). */\nexport interface CodeSource {\n\tcurrent(): PairingCode | undefined;\n\t/** Call `listener` on every new code (or none); returns how to stop. */\n\tonChange(listener: () => void): () => void;\n}\n\n/** The pairing codes of the extension's `TabMcp`, for `takeCode`. */\nexport function pairingCodes(\n\tmcp: Pick<TabMcp, \"pairingCode\" | \"addEventListener\" | \"removeEventListener\">,\n): CodeSource {\n\treturn {\n\t\tcurrent: () => mcp.pairingCode,\n\t\tonChange: (listener) => {\n\t\t\tmcp.addEventListener(\"pairingcode\", listener);\n\t\t\treturn () => mcp.removeEventListener(\"pairingcode\", listener);\n\t\t},\n\t};\n}\n\n/**\n * The code to fill in. The current one if it has `minLeftMs` left by this\n * clock (or an expiry that cannot be read); else the next one the relay\n * sends, which is fresh whatever the clocks say. The same code sent again\n * is not the next one: the relay answers each `pairing.start` with the code\n * it shows, so `startPairing()` with pairing on already brings back the\n * code that is about to change; it counts only if its expiry now leaves\n * `minLeftMs`. If no next one comes within `waitMs`, the current one after\n * all: with this clock ahead every code would look expired, so the fill\n * then waits the whole `waitMs` before it gets that code. The relay\n * refuses a code that has expired; the one more fill for the same request\n * covers that, or with `retry: false` a new question. `undefined` only\n * without any code, or when `signal` aborts. Pairing must be on\n * (`startPairing()`) for codes to come.\n */\nexport function takeCode(\n\tsource: CodeSource,\n\tsignal: AbortSignal,\n\toptions: { now: number; waitMs?: number; minLeftMs?: number },\n): Promise<string | undefined> {\n\tconst { waitMs = CODE_WAIT_MS, minLeftMs = MIN_CODE_LEFT_MS } = options;\n\t// `now` is the caller's clock; the time since is the real one's.\n\tconst started = Date.now();\n\tconst leaves = (code: PairingCode) =>\n\t\t!(\n\t\t\tDate.parse(code.expiresAt) - (options.now + Date.now() - started) <\n\t\t\tminLeftMs\n\t\t);\n\tconst current = source.current();\n\tif (current !== undefined && leaves(current))\n\t\treturn Promise.resolve(current.code);\n\tif (signal.aborted) return Promise.resolve(undefined);\n\treturn new Promise((resolve) => {\n\t\tconst done = (code: string | undefined) => {\n\t\t\tclearTimeout(timer);\n\t\t\tstop();\n\t\t\tsignal.removeEventListener(\"abort\", aborted);\n\t\t\tresolve(code);\n\t\t};\n\t\tconst stop = source.onChange(() => {\n\t\t\tconst next = source.current();\n\t\t\tif (next !== undefined && (next.code !== current?.code || leaves(next)))\n\t\t\t\tdone(next.code);\n\t\t});\n\t\tconst aborted = () => done(undefined);\n\t\tconst timer = setTimeout(() => done(source.current()?.code), waitMs);\n\t\tsignal.addEventListener(\"abort\", aborted, { once: true });\n\t});\n}\n"
|
|
5
|
+
"/**\n * `@ractive-ch/tab-mcp-client/extension`: for a browser extension that is a\n * tab-mcp page itself (the tab-mcp browser extension, Sitegloss). It fills\n * in the extension's own pairing code on the relay's pairing page\n * (`/authorize`) when an AI app opens it in the same browser, after asking\n * the user (DEC-199, DEC-203). What is the same for every such extension\n * lives here, reviewed once (DEC-206); how the user is asked, where the\n * setting is kept, the permission prompt, the content script's registration\n * and holding pairing on are each extension's own, given as callbacks.\n *\n * The relay's page has no scripts (DEC-057), so it cannot call the\n * extension: a content script reads the form's `data-tab-mcp-*` hooks and\n * tells the worker who asks (the AI app's name and verified host). The\n * worker asks its user and, on Allow, hands the code to that one page over\n * its port. The content script never sees a code before that, and the\n * worker never takes a page's word for where it is: any site can copy the\n * markup, so the origin the browser reports for the port is the check.\n *\n * An entry of its own that a web page never loads, out of the core. It\n * imports nothing of the rest of the library at run time and touches no\n * `window` or `document` until called, so a service worker and a content\n * script can both import it; a content script's bundle keeps only the page\n * side (`runPairingPage` and what it uses). No `chrome` types: the browser's\n * ports and senders are taken as the small structural types below.\n *\n * ```ts\n * // The content script, registered for the relay's /authorize page:\n * import { PAIRING_PORT, runPairingPage } from \"@ractive-ch/tab-mcp-client/extension\";\n * runPairingPage({ app: \"my-app\", connect: () => chrome.runtime.connect({ name: PAIRING_PORT }) });\n *\n * // The worker:\n * import { CodeFiller, PAIRING_PORT, pagePort } from \"@ractive-ch/tab-mcp-client/extension\";\n * const filler = new CodeFiller({ extensionId: chrome.runtime.id, app: \"my-app\", ... });\n * chrome.runtime.onConnect.addListener((port) => {\n * if (port.name === PAIRING_PORT) void filler.page(pagePort(port));\n * });\n * ```\n */\n\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type { PairingCode } from \"./types.ts\";\n\n/**\n * The event a script dispatches on `document` (a plain `Event`, no\n * `detail`) once it has given the page `document.modelContext` after the\n * page's scripts ran: the tab-mcp browser extension at a click on its icon\n * (DEC-223). A `TabMcp` that found no WebMCP when it was made reads\n * `Document.prototype`'s getter again then, and mirrors its tools if it\n * finds one. The core spells the name out itself (`tab-mcp.ts`), so that it\n * imports nothing of this entry; a test checks both are the same.\n */\nexport const WEBMCP_EVENT = \"tab-mcp-webmcp\";\n\n// --- What the content script and the worker say to each other ---\n\n/** The name of the port a pairing page's content script opens. */\nexport const PAIRING_PORT = \"pairing-page\";\n\n/** The relay's pairing page. */\nexport const PAIRING_PATH = \"/authorize\";\n\n/** What the content script says once, on its page's port. */\nexport interface PairingHello {\n\ttype: \"pairing-page\";\n\t/** This page load's own: the code comes back only with it. */\n\tnonce: string;\n\t/** `data-app`: the app the AI app asks to connect to. */\n\tapp: string;\n\t/** `data-client-name`: the AI app's name for itself. */\n\tclientName: string;\n\t/** `data-client-host`: the host the relay verified for the AI app. */\n\tclientHost: string;\n\t/**\n\t * The form's hidden `request_id`: the relay's id of this authorization\n\t * request, the same on its page again after a wrong code. The one fill\n\t * without a question is for this request only.\n\t */\n\trequestId: string;\n}\n\n/** What the worker sends after the user's Allow: the code to fill in and submit. */\nexport interface FillMessage {\n\ttype: \"fill\";\n\tnonce: string;\n\tcode: string;\n}\n\n/** The longest name and host a hello may carry (the relay's own limits are lower). */\nexport const MAX_CLIENT_NAME = 200;\nexport const MAX_CLIENT_HOST = 253;\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\n\n/**\n * The content script's hello, checked; `undefined` for anything else. The\n * name and host are what the relay's page says, kept as they are: the\n * extension's question must show invisible characters escaped (`./visible`).\n */\nexport function parseHello(message: unknown): PairingHello | undefined {\n\tif (typeof message !== \"object\" || message === null) return undefined;\n\tconst m = message as Record<string, unknown>;\n\tif (\n\t\tm[\"type\"] !== \"pairing-page\" ||\n\t\t!isString(m[\"nonce\"]) ||\n\t\t!/^[\\w-]{16,64}$/.test(m[\"nonce\"]) ||\n\t\t!isString(m[\"app\"]) ||\n\t\t!isString(m[\"clientName\"]) ||\n\t\t!isString(m[\"clientHost\"]) ||\n\t\tm[\"clientHost\"] === \"\" ||\n\t\t!isString(m[\"requestId\"]) ||\n\t\t!/^[\\w-]{1,128}$/.test(m[\"requestId\"]) ||\n\t\tm[\"clientName\"].length > MAX_CLIENT_NAME ||\n\t\tm[\"clientHost\"].length > MAX_CLIENT_HOST\n\t)\n\t\treturn undefined;\n\treturn {\n\t\ttype: \"pairing-page\",\n\t\tnonce: m[\"nonce\"],\n\t\tapp: m[\"app\"],\n\t\tclientName: m[\"clientName\"],\n\t\tclientHost: m[\"clientHost\"],\n\t\trequestId: m[\"requestId\"],\n\t};\n}\n\n/** The worker's fill message, checked against this page's nonce. */\nexport function parseFill(\n\tmessage: unknown,\n\tnonce: string,\n): FillMessage | undefined {\n\tif (typeof message !== \"object\" || message === null) return undefined;\n\tconst m = message as Record<string, unknown>;\n\treturn m[\"type\"] === \"fill\" &&\n\t\tm[\"nonce\"] === nonce &&\n\t\tisString(m[\"code\"]) &&\n\t\tm[\"code\"] !== \"\"\n\t\t? { type: \"fill\", nonce, code: m[\"code\"] }\n\t\t: undefined;\n}\n\n// --- Where the relay's pages are ---\n\n/**\n * The origin of the relay's web pages for the relay address `relay`: its\n * `ws:`/`wss:` forms are the same server's `http:`/`https:`. `undefined` for\n * anything that is not one.\n */\nexport function relayPageOrigin(relay: string): string | undefined {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(relay);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tconst scheme =\n\t\turl.protocol === \"wss:\"\n\t\t\t? \"https:\"\n\t\t\t: url.protocol === \"ws:\"\n\t\t\t\t? \"http:\"\n\t\t\t\t: url.protocol;\n\tif (scheme !== \"https:\" && scheme !== \"http:\") return undefined;\n\treturn `${scheme}//${url.host}`;\n}\n\n/**\n * The match pattern for the relay's host, without its port: Firefox's\n * patterns take none, and Chrome's without one match every port. The exact\n * origin, port and all, is checked in the content script and in the worker.\n * The host in lower case without a trailing dot; one that is no plain name\n * or IPv4 address (an IPv6 literal, say) gives no pattern, as the browsers\n * do not agree on one for it.\n */\nfunction hostPattern(relay: string, path: string): string | undefined {\n\tconst origin = relayPageOrigin(relay);\n\tif (origin === undefined) return undefined;\n\tconst { protocol, hostname } = new URL(origin);\n\tconst host = hostname.toLowerCase().replace(/\\.$/, \"\");\n\tif (!/^[a-z0-9-]+(\\.[a-z0-9-]+)*$/.test(host)) return undefined;\n\treturn `${protocol}//${host}${path}`;\n}\n\n/**\n * The host permission for the relay's site (`<scheme>://<host>/*`), the one\n * origin to ask for (`permissions.request({ origins: [it] })`) before the\n * extension can see the pairing page. `undefined` for an address that has\n * no pattern: the user types the code.\n */\nexport function relaySitePattern(relay: string): string | undefined {\n\treturn hostPattern(relay, \"/*\");\n}\n\n/** The match pattern of the relay's pairing page, for a content script's `matches`. */\nexport function pairingPagePattern(relay: string): string | undefined {\n\treturn hostPattern(relay, `${PAIRING_PATH}*`);\n}\n\n// --- The content script on the relay's page ---\n\n/** The page's pairing form, as far as filling it in needs it. */\nexport interface PairingForm {\n\tform: HTMLFormElement;\n\tfield: HTMLInputElement;\n\tbutton: HTMLButtonElement;\n\tapp: string;\n\tclientName: string;\n\tclientHost: string;\n\t/** The relay's id of this request (the form's hidden `request_id`). */\n\trequestId: string;\n}\n\n/**\n * The pairing form of app `app` on `doc`, if this is a top-level page at\n * `/authorize` with exactly one such form that has a code field and a\n * Connect button (DEC-199's hooks, version 1). The worker checks the origin\n * itself; this only spares it the pages that are not one. A page that pairs\n * by sign-in only has no code field.\n */\nexport function findPairingForm(\n\tdoc: Document,\n\twhere: { topLevel: boolean; pathname: string },\n\tapp: string,\n): PairingForm | undefined {\n\tif (!where.topLevel || where.pathname !== PAIRING_PATH) return undefined;\n\tconst forms = doc.querySelectorAll<HTMLFormElement>(\n\t\t'form[data-tab-mcp-pairing=\"1\"]',\n\t);\n\tconst [form] = forms;\n\tif (forms.length !== 1 || form === undefined) return undefined;\n\tif (form.dataset[\"app\"] !== app) return undefined;\n\tconst field = form.querySelector<HTMLInputElement>(\n\t\t'input[data-tab-mcp-field=\"code\"]',\n\t);\n\tconst button = form.querySelector<HTMLButtonElement>(\n\t\t'button[data-tab-mcp-action=\"connect\"]',\n\t);\n\tconst clientName = form.dataset[\"clientName\"];\n\tconst clientHost = form.dataset[\"clientHost\"];\n\tconst requestId = form.querySelector<HTMLInputElement>(\n\t\t'input[type=\"hidden\"][name=\"request_id\"]',\n\t)?.value;\n\tif (\n\t\tfield === null ||\n\t\tbutton === null ||\n\t\tclientName === undefined ||\n\t\tclientHost === undefined ||\n\t\tclientHost === \"\" ||\n\t\t!requestId\n\t)\n\t\treturn undefined;\n\treturn { form, field, button, app, clientName, clientHost, requestId };\n}\n\n/**\n * Write `code` into the form's field and submit it with its Connect button:\n * the page's own post, as if the user had typed it and clicked.\n */\nexport function fillIn(found: PairingForm, code: string): void {\n\tfound.field.value = code;\n\t// The document's own Event (a test's DOM need not be the global one).\n\tconst Input = found.field.ownerDocument.defaultView?.Event ?? Event;\n\tfound.field.dispatchEvent(new Input(\"input\", { bubbles: true }));\n\tfound.form.requestSubmit(found.button);\n}\n\n/** The hello for `found`, with this page load's nonce. */\nexport function helloFor(found: PairingForm, nonce: string): PairingHello {\n\treturn {\n\t\ttype: \"pairing-page\",\n\t\tnonce,\n\t\tapp: found.app,\n\t\tclientName: found.clientName,\n\t\tclientHost: found.clientHost,\n\t\trequestId: found.requestId,\n\t};\n}\n\n/** The content script's end of its port (`chrome.runtime.Port` is one). */\nexport interface ContentPort {\n\tpostMessage(message: unknown): void;\n\treadonly onMessage: {\n\t\taddListener(listener: (message: unknown) => void): void;\n\t};\n}\n\n/**\n * The content script of the relay's pairing page: if the page has app\n * `app`'s pairing form, open a port to the worker (`connect`, with the name\n * PAIRING_PORT), say who asks, and wait. Only the worker's fill with this\n * page load's nonce is taken, once: its code is written into the field and\n * the form submitted. Once per document, also if the script is put in again\n * (after the user gave access with the page already open). Whether the\n * page has the form. `page` is the content script's own page unless a test\n * gives one.\n */\nexport function runPairingPage(options: {\n\tapp: string;\n\tconnect: () => ContentPort;\n\tpage?: { document: Document; topLevel: boolean; pathname: string };\n}): boolean {\n\tconst flag = \"__tabMcpPairingPage\";\n\t// A content script put in again runs in the same isolated world, so its\n\t// global marks the document. The document a test gives carries the mark\n\t// itself: two such pages in one test are independent.\n\tconst scope = (options.page?.document ?? globalThis) as unknown as Record<\n\t\tstring,\n\t\tunknown\n\t>;\n\tif (scope[flag] === true) return false;\n\tscope[flag] = true;\n\tconst page = options.page ?? {\n\t\tdocument,\n\t\ttopLevel: window.top === window,\n\t\tpathname: location.pathname,\n\t};\n\tconst found = findPairingForm(page.document, page, options.app);\n\tif (found === undefined) return false;\n\tconst nonce = crypto.randomUUID();\n\tconst port = options.connect();\n\tlet filled = false;\n\tport.onMessage.addListener((message) => {\n\t\tconst fill = parseFill(message, nonce);\n\t\t// One fill per page load: the page posts and goes.\n\t\tif (fill === undefined || filled) return;\n\t\tfilled = true;\n\t\tfillIn(found, fill.code);\n\t});\n\tport.postMessage(helloFor(found, nonce));\n\treturn true;\n}\n\n// --- The worker ---\n\n/** The sender of a port, as far as the check needs it (`chrome.runtime.MessageSender`). */\nexport interface PageSender {\n\tid?: string;\n\turl?: string;\n\t/** Chrome gives the document's origin; Firefox may not. */\n\torigin?: string;\n\ttab?: unknown;\n\tframeId?: number;\n}\n\n/**\n * A port from the pairing page of the relay at `relayOrigin`: this\n * extension's content script, in a tab, in its top frame, on a page whose\n * origin is exactly the relay's (port included) and whose path is\n * `/authorize`. A page anywhere else can carry the same markup: it is\n * ignored.\n */\nexport function isPairingSender(\n\tsender: PageSender,\n\textensionId: string,\n\trelayOrigin: string | undefined,\n): boolean {\n\tif (relayOrigin === undefined) return false;\n\tif (sender.id !== extensionId) return false;\n\tif (sender.tab === undefined || sender.frameId !== 0) return false;\n\t// Where the browser gives the document's origin, it is the one to trust\n\t// (a URL can be a `blob:` or `about:` of another origin's making).\n\tif (sender.origin !== undefined && sender.origin !== relayOrigin)\n\t\treturn false;\n\ttry {\n\t\tconst url = new URL(sender.url ?? \"\");\n\t\treturn url.origin === relayOrigin && url.pathname === PAIRING_PATH;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** A page will not say who asks in this time: it is dropped. */\nexport const HELLO_WAIT_MS = 5_000;\n/**\n * The same request's page in the same tab within this time after a fill is\n * the relay's answer to it: the code was not taken.\n */\nexport const RETRY_WINDOW_MS = 30_000;\n/** `takeCode`: how long to wait for the next code. */\nexport const CODE_WAIT_MS = 10_000;\n/** `takeCode`: a code with less time left than this is not used, the next one is. */\nexport const MIN_CODE_LEFT_MS = 5_000;\n/**\n * A filled-in page's port is closed this long after the fill: the page has\n * posted by then, and its answer, if any, is a new document with a port of\n * its own.\n */\nexport const FILLED_CLOSE_MS = 5_000;\n\n/** The worker's end of a page's port (`chrome.runtime.Port` is one). */\nexport interface WorkerPort {\n\treadonly sender?: PageSender;\n\tpostMessage(message: unknown): void;\n\tdisconnect(): void;\n\treadonly onMessage: {\n\t\taddListener(listener: (message: unknown) => void): void;\n\t\tremoveListener(listener: (message: unknown) => void): void;\n\t};\n\treadonly onDisconnect: { addListener(listener: () => void): void };\n}\n\n/**\n * A pairing page's port in the worker. Its first message and its end are\n * taken from the moment it connects: the worker may still be starting, and\n * Chrome hands a message only to the listeners there are.\n */\nexport interface PagePort {\n\treadonly sender: PageSender;\n\t/** The first message; `undefined` if the port went before one came. */\n\treadonly hello: Promise<unknown>;\n\t/** Aborted when the page goes (or the worker closes the port). */\n\treadonly signal: AbortSignal;\n\tsend(message: FillMessage): void;\n\tclose(): void;\n}\n\n/**\n * `port`, taken over at once (see PagePort): call it in `onConnect` itself,\n * before any `await`.\n */\nexport function pagePort(port: WorkerPort): PagePort {\n\tconst gone = new AbortController();\n\tlet first: (message: unknown) => void = () => {};\n\tconst hello = new Promise<unknown>((resolve) => {\n\t\tfirst = resolve;\n\t});\n\tconst take = (message: unknown) => {\n\t\tport.onMessage.removeListener(take);\n\t\tfirst(message);\n\t};\n\tport.onMessage.addListener(take);\n\tport.onDisconnect.addListener(() => {\n\t\tgone.abort();\n\t\tfirst(undefined);\n\t});\n\treturn {\n\t\tsender: port.sender ?? {},\n\t\thello,\n\t\tsignal: gone.signal,\n\t\tsend: (message) => {\n\t\t\ttry {\n\t\t\t\tport.postMessage(message);\n\t\t\t} catch {\n\t\t\t\t// The page went meanwhile.\n\t\t\t}\n\t\t},\n\t\tclose: () => {\n\t\t\tif (gone.signal.aborted) return;\n\t\t\t// Our own `disconnect()` fires no `onDisconnect` here.\n\t\t\tgone.abort();\n\t\t\tfirst(undefined);\n\t\t\ttry {\n\t\t\t\tport.disconnect();\n\t\t\t} catch {\n\t\t\t\t// Gone already.\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * The user's answer to \"Connect <name> (<host>)?\": only `allow` fills in.\n * `busy`: the extension could not ask (too many questions wait); the page is\n * reported (`failed(\"busy\")`), not dropped unseen.\n */\nexport type FillAnswer = \"allow\" | \"deny\" | \"timeout\" | \"busy\";\n\n/** Why a page that asked got no code: the extension tells its user. */\nexport type FillFailure =\n\t/** It could not be asked about (`ask` answered `busy`). */\n\t| \"busy\"\n\t/** Allow, but no code came from the relay (`code` gave none). */\n\t| \"no-code\";\n\n/** The page a fill is for: its tab and the AI app that asks there. */\nexport interface FillContext {\n\ttabId: number;\n\t/** The AI app's own name (may be `\"\"`) and the host the relay verified, as `ask` gets them. */\n\tclient: { name: string; host: string };\n}\n\n/** What `CodeFiller` needs from the extension: its parts of the fill-in. */\nexport interface FillHost {\n\t/** This extension's id (`chrome.runtime.id`): only its own content script speaks. */\n\textensionId: string;\n\t/** The app id of the extension's page: only forms with this `data-app`. */\n\tapp: string;\n\t/**\n\t * The origin of the relay's pages (`relayPageOrigin`) whose pairing page\n\t * may be filled in; `undefined` for none (another relay than the one the\n\t * extension fills in for).\n\t */\n\trelayOrigin(): string | undefined;\n\t/** AI access is on: connected, or on its way. Off, nothing is asked. */\n\taiOn(): boolean;\n\t/** The user turned filling in on, for this relay (opt-in, off by default). */\n\tenabled(): boolean;\n\t/**\n\t * Ask the user whether to connect the AI app `client` (its own name for\n\t * itself and the host the relay verified, both to be shown with invisible\n\t * characters escaped) in tab `tabId`. `signal` withdraws the question:\n\t * the page went, AI access or the setting went off, the relay changed,\n\t * or the AI app connected meanwhile; answer then with anything but\n\t * `allow`.\n\t */\n\task(\n\t\ttabId: number,\n\t\tclient: { name: string; host: string },\n\t\tsignal: AbortSignal,\n\t): Promise<FillAnswer>;\n\t/**\n\t * The code to fill in now on the page `context`, with pairing held on for\n\t * the relay to check it (`takeCode`); `undefined` if none came or\n\t * `signal` aborted (the page went, or the fill was withdrawn as a\n\t * question is). Even with a code, nothing is sent if what holds for\n\t * asking no longer does.\n\t */\n\tcode(signal: AbortSignal, context: FillContext): Promise<string | undefined>;\n\t/**\n\t * No fill needs pairing held on any more: a filled-in code paired its AI\n\t * app, or a fill ended without sending its code (withdrawn, the page\n\t * went, no code) while no other fill is under way or waits for the\n\t * relay's check. It may come again with nothing held: ignore it then.\n\t */\n\trelease(): void;\n\t/** The page `context` filled in nothing for `why`, or was not asked about: say so. */\n\tfailed(why: FillFailure, context: FillContext): void;\n\t/** The clock (`Date.now`; a test's own). */\n\tnow(): number;\n}\n\n/** A page whose question waits. */\ninterface Waiting {\n\thost: string;\n\twithdraw: AbortController;\n}\n\n/** The last fill in a tab. */\ninterface Filled {\n\t/** The relay's id of the request filled in. */\n\trequestId: string;\n\thost: string;\n\t/** Fills for it so far: 1 after Allow, 2 after the one more. */\n\tcount: number;\n\tat: number;\n}\n\nconst tabIdOf = (sender: PageSender): number | undefined => {\n\tconst id = (sender.tab as { id?: unknown } | undefined)?.id;\n\treturn typeof id === \"number\" ? id : undefined;\n};\n\nfunction within<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\treturn Promise.race([\n\t\tpromise,\n\t\tnew Promise<undefined>((resolve) => {\n\t\t\ttimer = setTimeout(() => resolve(undefined), ms);\n\t\t}),\n\t]).finally(() => clearTimeout(timer));\n}\n\n/**\n * The worker's side of filling in the code (DEC-199, DEC-203): a page's port\n * is taken only from this extension's content script in the top frame of a\n * tab at exactly the relay's origin, and only while AI access is on and the\n * user turned filling in on. Then the user is asked, with the AI app's\n * verified host; on Allow the code goes to that one page, which fills it in\n * and submits.\n *\n * No loops: one question per page load (one port per document, one hello\n * per port). When the same tab shows the page of the same request (the\n * relay's `request_id`) again soon after a fill, it is the relay's answer\n * that the code was not taken (it had just changed): filled once more with\n * the code of then, without asking; the time after, nothing. Any other\n * request asks. With `retry: false` that page is asked about like any\n * other: every fill has a yes of its own. Don't allow, a timeout, the page\n * going, AI access or the setting going off, another relay or the AI app\n * connecting meanwhile fill nothing, and typing by hand works as before.\n */\nexport class CodeFiller {\n\treadonly #host: FillHost;\n\treadonly #waiting = new Set<Waiting>();\n\t/**\n\t * By tab: what was filled in there last, or is being filled in (marked\n\t * before the wait for the code, so that a page of the same request\n\t * meanwhile counts it).\n\t */\n\treadonly #filled = new Map<number, Filled>();\n\t/**\n\t * The grants seen so far: a new one is an AI app that just connected.\n\t * `undefined` until the first list, which is taken as it is: a worker\n\t * that starts before its connection is up has none to compare with.\n\t */\n\t#grants: Set<string> | undefined;\n\treadonly #closeAfterMs: number;\n\treadonly #retry: boolean;\n\n\t/**\n\t * `grants`: the ids of the grants there are already, if the extension kept\n\t * them between worker starts (not new when listed again); without them,\n\t * the first `grantsChanged` is taken as the list there is, nothing in it\n\t * new. `retry`: the one more fill without asking when the same request's\n\t * page comes back to the same tab soon after a fill (on unless `false`;\n\t * off, that page is asked about like any other, one question per page\n\t * load, and never filled without a yes). `closeAfterMs`: FILLED_CLOSE_MS\n\t * unless a test's is shorter.\n\t */\n\tconstructor(\n\t\thost: FillHost,\n\t\toptions: {\n\t\t\tgrants?: Iterable<string>;\n\t\t\tretry?: boolean;\n\t\t\tcloseAfterMs?: number;\n\t\t} = {},\n\t) {\n\t\tthis.#host = host;\n\t\tthis.#grants =\n\t\t\toptions.grants === undefined ? undefined : new Set(options.grants);\n\t\tthis.#retry = options.retry ?? true;\n\t\tthis.#closeAfterMs = options.closeAfterMs ?? FILLED_CLOSE_MS;\n\t}\n\n\t/**\n\t * A pairing page's port: checked, then asked about and maybe filled in.\n\t * Never rejects: a host callback that throws fills nothing, closes the\n\t * port and is logged.\n\t */\n\tasync page(port: PagePort): Promise<void> {\n\t\ttry {\n\t\t\tawait this.#page(port);\n\t\t} catch (error) {\n\t\t\tconsole.warn(\"tab-mcp: pairing page\", error);\n\t\t\tport.close();\n\t\t}\n\t}\n\n\tasync #page(port: PagePort): Promise<void> {\n\t\tconst host = this.#host;\n\t\tconst tabId = tabIdOf(port.sender);\n\t\tif (\n\t\t\ttabId === undefined ||\n\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin())\n\t\t) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tconst hello = parseHello(await within(port.hello, HELLO_WAIT_MS));\n\t\t// Only this extension's own app, only if the user turned filling in\n\t\t// on, only while AI access is on, and only while the relay is still\n\t\t// the one the page is of (it may have changed during the wait for\n\t\t// the hello): otherwise they have not asked for it.\n\t\tif (\n\t\t\thello === undefined ||\n\t\t\thello.app !== host.app ||\n\t\t\tport.signal.aborted ||\n\t\t\t!host.enabled() ||\n\t\t\t!host.aiOn() ||\n\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin())\n\t\t) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tconst context: FillContext = {\n\t\t\ttabId,\n\t\t\tclient: { name: hello.clientName, host: hello.clientHost },\n\t\t};\n\t\tconst before = this.#lastFill(tabId);\n\t\tif (this.#retry && before?.requestId === hello.requestId) {\n\t\t\t// The same request's page again after a fill: the code was not\n\t\t\t// taken. Once more with the code of now, then never again for it.\n\t\t\tif (before.count === 1) await this.#fill(port, context, hello, 2);\n\t\t\telse port.close();\n\t\t\treturn;\n\t\t}\n\t\tconst waiting: Waiting = {\n\t\t\thost: hello.clientHost,\n\t\t\twithdraw: new AbortController(),\n\t\t};\n\t\tthis.#waiting.add(waiting);\n\t\tconst signal = AbortSignal.any([port.signal, waiting.withdraw.signal]);\n\t\tlet answer: FillAnswer;\n\t\ttry {\n\t\t\tanswer = await host.ask(tabId, { ...context.client }, signal);\n\t\t} finally {\n\t\t\tthis.#waiting.delete(waiting);\n\t\t}\n\t\t// Too many questions wait: not dropped unseen.\n\t\tif (answer === \"busy\") host.failed(\"busy\", context);\n\t\tif (\n\t\t\tanswer !== \"allow\" ||\n\t\t\tsignal.aborted ||\n\t\t\t!host.enabled() ||\n\t\t\t!host.aiOn() ||\n\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin())\n\t\t) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tawait this.#fill(port, context, hello, 1);\n\t}\n\n\t/**\n\t * Whether a fill is under way or was sent recently enough for the relay\n\t * to be checking its code (the tabs' last fills, the stale ones dropped).\n\t */\n\t#anyFill(): boolean {\n\t\tthis.#dropStale();\n\t\treturn this.#filled.size > 0;\n\t}\n\n\t/** The last fill in `tabId`, if it is recent enough to be answered by this page. */\n\t#lastFill(tabId: number): Filled | undefined {\n\t\tthis.#dropStale();\n\t\treturn this.#filled.get(tabId);\n\t}\n\n\t#dropStale(): void {\n\t\tconst now = this.#host.now();\n\t\tfor (const [id, filled] of this.#filled)\n\t\t\tif (now - filled.at > RETRY_WINDOW_MS) this.#filled.delete(id);\n\t}\n\n\t/**\n\t * Fill `count` (1 after Allow, 2 the one more) of `hello`'s request in\n\t * `tabId`. The wait for the code is withdrawn like a question, and what\n\t * holds for asking is checked again once the code is there.\n\t */\n\tasync #fill(\n\t\tport: PagePort,\n\t\tcontext: FillContext,\n\t\thello: PairingHello,\n\t\tcount: number,\n\t): Promise<void> {\n\t\tconst host = this.#host;\n\t\tconst { tabId } = context;\n\t\tconst before = this.#filled.get(tabId);\n\t\t// Marked before the wait: a page of the same request that comes\n\t\t// meanwhile sees this count, so there is never a third fill.\n\t\tconst mark: Filled = {\n\t\t\trequestId: hello.requestId,\n\t\t\thost: hello.clientHost,\n\t\t\tcount,\n\t\t\tat: host.now(),\n\t\t};\n\t\tthis.#filled.set(tabId, mark);\n\t\tconst waiting: Waiting = {\n\t\t\thost: hello.clientHost,\n\t\t\twithdraw: new AbortController(),\n\t\t};\n\t\tthis.#waiting.add(waiting);\n\t\tconst signal = AbortSignal.any([port.signal, waiting.withdraw.signal]);\n\t\tlet sent = false;\n\t\t// A page that went or a code that did not come leaves the tab's last\n\t\t// fill as it was; a withdrawal leaves nothing to fill once more.\n\t\tlet keepBefore = true;\n\t\ttry {\n\t\t\tconst code = await host.code(signal, {\n\t\t\t\ttabId,\n\t\t\t\tclient: { ...context.client },\n\t\t\t});\n\t\t\tconst off =\n\t\t\t\twaiting.withdraw.signal.aborted ||\n\t\t\t\t!host.enabled() ||\n\t\t\t\t!host.aiOn() ||\n\t\t\t\t!isPairingSender(port.sender, host.extensionId, host.relayOrigin());\n\t\t\tif (off) keepBefore = false;\n\t\t\tif (off || port.signal.aborted) return;\n\t\t\tif (code === undefined) {\n\t\t\t\thost.failed(\"no-code\", { tabId, client: { ...context.client } });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tmark.at = host.now();\n\t\t\tport.send({ type: \"fill\", nonce: hello.nonce, code });\n\t\t\tsent = true;\n\t\t\tsetTimeout(() => port.close(), this.#closeAfterMs);\n\t\t} finally {\n\t\t\tthis.#waiting.delete(waiting);\n\t\t\tif (!sent) {\n\t\t\t\tport.close();\n\t\t\t\tif (this.#filled.get(tabId) === mark) {\n\t\t\t\t\tif (keepBefore && before !== undefined)\n\t\t\t\t\t\tthis.#filled.set(tabId, before);\n\t\t\t\t\telse this.#filled.delete(tabId);\n\t\t\t\t}\n\t\t\t\t// `code` may have held pairing on for this fill: with no other\n\t\t\t\t// fill to hold it for, the host need not keep it on.\n\t\t\t\tif (!this.#anyFill()) host.release();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The relay's list of grants (`grantschange`): an AI app that just\n\t * connected (typed by hand, or filled in) withdraws the questions for its\n\t * host, and its fills are done with.\n\t */\n\tgrantsChanged(grants: readonly { grantId: string; host: string }[]): void {\n\t\tif (this.#grants === undefined) {\n\t\t\t// The first list without a seed: the grants there are, none new.\n\t\t\tthis.#grants = new Set(grants.map((grant) => grant.grantId));\n\t\t\treturn;\n\t\t}\n\t\tconst connected = new Set<string>();\n\t\tfor (const grant of grants)\n\t\t\tif (!this.#grants.has(grant.grantId)) {\n\t\t\t\tthis.#grants.add(grant.grantId);\n\t\t\t\tconnected.add(grant.host);\n\t\t\t}\n\t\tif (connected.size === 0) return;\n\t\tfor (const waiting of this.#waiting)\n\t\t\tif (connected.has(waiting.host)) waiting.withdraw.abort();\n\t\tlet done = false;\n\t\tfor (const [tabId, filled] of this.#filled)\n\t\t\tif (connected.has(filled.host)) {\n\t\t\t\tthis.#filled.delete(tabId);\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t// Another AI app's fill may still be under way or wait for the relay's\n\t\t// check: stopping pairing now would void its code.\n\t\tif (done && !this.#anyFill()) this.#host.release();\n\t}\n\n\t/**\n\t * AI access off, or filling in turned off: the questions waiting are\n\t * withdrawn and no page gets the one more fill.\n\t */\n\twithdrawAll(): void {\n\t\tfor (const waiting of this.#waiting) waiting.withdraw.abort();\n\t\tthis.#filled.clear();\n\t}\n\n\t/**\n\t * Another relay: no page of the one before is asked about or filled in,\n\t * and the new relay's first list of grants is taken as it is.\n\t */\n\treset(): void {\n\t\tthis.withdrawAll();\n\t\tthis.#grants = undefined;\n\t}\n}\n\n/** Where the pairing codes come from (`pairingCodes(mcp)`). */\nexport interface CodeSource {\n\tcurrent(): PairingCode | undefined;\n\t/** Call `listener` on every new code (or none); returns how to stop. */\n\tonChange(listener: () => void): () => void;\n}\n\n/** The pairing codes of the extension's `TabMcp`, for `takeCode`. */\nexport function pairingCodes(\n\tmcp: Pick<TabMcp, \"pairingCode\" | \"addEventListener\" | \"removeEventListener\">,\n): CodeSource {\n\treturn {\n\t\tcurrent: () => mcp.pairingCode,\n\t\tonChange: (listener) => {\n\t\t\tmcp.addEventListener(\"pairingcode\", listener);\n\t\t\treturn () => mcp.removeEventListener(\"pairingcode\", listener);\n\t\t},\n\t};\n}\n\n/**\n * The code to fill in. The current one if it has `minLeftMs` left by this\n * clock (or an expiry that cannot be read); else the next one the relay\n * sends, which is fresh whatever the clocks say. The same code sent again\n * is not the next one: the relay answers each `pairing.start` with the code\n * it shows, so `startPairing()` with pairing on already brings back the\n * code that is about to change; it counts only if its expiry now leaves\n * `minLeftMs`. If no next one comes within `waitMs`, the current one after\n * all: with this clock ahead every code would look expired, so the fill\n * then waits the whole `waitMs` before it gets that code. The relay\n * refuses a code that has expired; the one more fill for the same request\n * covers that, or with `retry: false` a new question. `undefined` only\n * without any code, or when `signal` aborts. Pairing must be on\n * (`startPairing()`) for codes to come.\n */\nexport function takeCode(\n\tsource: CodeSource,\n\tsignal: AbortSignal,\n\toptions: { now: number; waitMs?: number; minLeftMs?: number },\n): Promise<string | undefined> {\n\tconst { waitMs = CODE_WAIT_MS, minLeftMs = MIN_CODE_LEFT_MS } = options;\n\t// `now` is the caller's clock; the time since is the real one's.\n\tconst started = Date.now();\n\tconst leaves = (code: PairingCode) =>\n\t\t!(\n\t\t\tDate.parse(code.expiresAt) - (options.now + Date.now() - started) <\n\t\t\tminLeftMs\n\t\t);\n\tconst current = source.current();\n\tif (current !== undefined && leaves(current))\n\t\treturn Promise.resolve(current.code);\n\tif (signal.aborted) return Promise.resolve(undefined);\n\treturn new Promise((resolve) => {\n\t\tconst done = (code: string | undefined) => {\n\t\t\tclearTimeout(timer);\n\t\t\tstop();\n\t\t\tsignal.removeEventListener(\"abort\", aborted);\n\t\t\tresolve(code);\n\t\t};\n\t\tconst stop = source.onChange(() => {\n\t\t\tconst next = source.current();\n\t\t\tif (next !== undefined && (next.code !== current?.code || leaves(next)))\n\t\t\t\tdone(next.code);\n\t\t});\n\t\tconst aborted = () => done(undefined);\n\t\tconst timer = setTimeout(() => done(source.current()?.code), waitMs);\n\t\tsignal.addEventListener(\"abort\", aborted, { once: true });\n\t});\n}\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": ";
|
|
8
|
-
"debugId": "
|
|
7
|
+
"mappings": ";AAmDO,IAAM,eAAe;AAKrB,IAAM,eAAe;AAGrB,IAAM,eAAe;AA6BrB,IAAM,kBAAkB;AACxB,IAAM,kBAAkB;AAE/B,IAAM,WAAW,CAAC,UAAoC,OAAO,UAAU;AAOhE,SAAS,UAAU,CAAC,SAA4C;AAAA,EACtE,IAAI,OAAO,YAAY,YAAY,YAAY;AAAA,IAAM;AAAA,EACrD,MAAM,IAAI;AAA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A;AAAA,IAEb,MAAM,OAAO,OAAO,SAAS,MAAM;AAAA,MAClC,MAAM,OAAO,OAAO,QAAQ;AAAA,MAC5B,IAAI,SAAS,cAAc,KAAK,SAAS,SAAS,QAAQ,OAAO,IAAI;AAAA,QACpE,KAAK,KAAK,IAAI;AAAA,KACf;AAAA,IACD,MAAM,UAAU,MAAM,KAAK,SAAS;AAAA,IACpC,MAAM,QAAQ,WAAW,MAAM,KAAK,OAAO,QAAQ,GAAG,IAAI,GAAG,MAAM;AAAA,IACnE,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,GACxD;AAAA;",
|
|
8
|
+
"debugId": "946C89A7C36F4C3964756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/handshake.d.ts
CHANGED
|
@@ -20,8 +20,14 @@
|
|
|
20
20
|
* - The extension says what it is and which AI apps are connected to it
|
|
21
21
|
* (`hello`, `update`), and, right before it runs a page tool the user
|
|
22
22
|
* allowed there, `vouch`: the tool, the exact arguments, a nonce and the
|
|
23
|
-
* AI app;
|
|
24
|
-
*
|
|
23
|
+
* AI app; right before one it runs without asking (read-only for it),
|
|
24
|
+
* `claim` with the same fields (DEC-224); once that call ended or failed,
|
|
25
|
+
* `withdraw` with the nonce, and one still unused is dropped. With
|
|
26
|
+
* `result: "mcp"` on either, the call resolves with the whole MCP result
|
|
27
|
+
* (pictures too), which the extension passes on; without it (an older
|
|
28
|
+
* extension), with the value any WebMCP caller gets. A `claim` only
|
|
29
|
+
* names the caller and asks for the whole result: `onConfirm` decides as
|
|
30
|
+
* for any WebMCP call. It speaks only while it serves the
|
|
25
31
|
* page (DEC-221): while its AI access is off the page hears nothing, as
|
|
26
32
|
* without the extension, except `on: false` once if it was told "on".
|
|
27
33
|
* - Each side cuts the other's list of AI apps to 64 and sends no more.
|
|
@@ -60,6 +66,19 @@ export interface VouchedBy {
|
|
|
60
66
|
name: string;
|
|
61
67
|
host: string;
|
|
62
68
|
}
|
|
69
|
+
/** A call the extension announced, as its WebMCP call takes it. */
|
|
70
|
+
export interface Vouched {
|
|
71
|
+
app: VouchedBy;
|
|
72
|
+
/**
|
|
73
|
+
* The user allowed it in the extension (`vouch`): it runs without
|
|
74
|
+
* `onConfirm`. `false` for a `claim`, a call the extension made without
|
|
75
|
+
* asking (it took the tool for read-only): `onConfirm` decides as for
|
|
76
|
+
* any WebMCP call.
|
|
77
|
+
*/
|
|
78
|
+
allowed: boolean;
|
|
79
|
+
/** The extension takes the whole MCP result (`result: "mcp"`, DEC-224). */
|
|
80
|
+
whole: boolean;
|
|
81
|
+
}
|
|
63
82
|
/**
|
|
64
83
|
* `value` as JSON with the keys of every object sorted: two argument
|
|
65
84
|
* objects are equal when their canonical forms are.
|
|
@@ -70,10 +89,10 @@ declare class Handshake {
|
|
|
70
89
|
constructor(doc: Document);
|
|
71
90
|
join(page: HandshakePage): void;
|
|
72
91
|
/**
|
|
73
|
-
* The vouch for this call of `tool` with `input`, used up;
|
|
74
|
-
* if there is none (the call is
|
|
92
|
+
* The vouch or claim for this call of `tool` with `input`, used up;
|
|
93
|
+
* `undefined` if there is none (the call is any WebMCP call).
|
|
75
94
|
*/
|
|
76
|
-
take(tool: RegisteredTool, input: unknown):
|
|
95
|
+
take(tool: RegisteredTool, input: unknown): Vouched | undefined;
|
|
77
96
|
}
|
|
78
97
|
/**
|
|
79
98
|
* The handshake of the page's top-level document, which `page` joins; the
|
package/index.js
CHANGED
|
@@ -233,7 +233,7 @@ class SecretStore {
|
|
|
233
233
|
}
|
|
234
234
|
}
|
|
235
235
|
// package.json
|
|
236
|
-
var version = "0.
|
|
236
|
+
var version = "0.24.0-rc.1";
|
|
237
237
|
|
|
238
238
|
// src/version.ts
|
|
239
239
|
var LIBRARY_NAME = "@ractive-ch/tab-mcp-client";
|
|
@@ -397,9 +397,18 @@ class TabMcp extends EventTarget {
|
|
|
397
397
|
this.#tabs = options.storage === null ? undefined : `${key}#tabs`;
|
|
398
398
|
}
|
|
399
399
|
this.#registry.onChange(() => this.#emit("toolschange", { tools: this.tools }));
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
400
|
+
if (options.webmcp === false)
|
|
401
|
+
return;
|
|
402
|
+
const look = () => {
|
|
403
|
+
const context = nativeContext();
|
|
404
|
+
if (context === undefined)
|
|
405
|
+
return;
|
|
406
|
+
globalThis.document?.removeEventListener("tab-mcp-webmcp", look);
|
|
407
|
+
mirrorIn(context);
|
|
408
|
+
};
|
|
409
|
+
globalThis.document?.addEventListener("tab-mcp-webmcp", look);
|
|
410
|
+
const mirrorIn = (context) => import("./webmcp-ctk4bd8c.js").then((m) => m.mirror(this.#registry, context, (tool, input, signal, by) => this.#load().then((lazy) => lazy.callFromWebMcp(this.#calls, tool, input, signal, by)), this, app, options, VERSION), (error) => console.warn("tab-mcp: no tools are offered through WebMCP:", error));
|
|
411
|
+
look();
|
|
403
412
|
}
|
|
404
413
|
registerTool(tool, options = {}) {
|
|
405
414
|
try {
|
|
@@ -524,7 +533,7 @@ class TabMcp extends EventTarget {
|
|
|
524
533
|
return connecting;
|
|
525
534
|
}
|
|
526
535
|
async#load() {
|
|
527
|
-
const lazy = await import("./connection-
|
|
536
|
+
const lazy = await import("./connection-gqec88qp.js");
|
|
528
537
|
for (const error of lazy.compileRegistry(this.#registry))
|
|
529
538
|
this.#emit("error", { error });
|
|
530
539
|
this.#lazy = lazy;
|
|
@@ -884,5 +893,5 @@ export {
|
|
|
884
893
|
VERSION
|
|
885
894
|
};
|
|
886
895
|
|
|
887
|
-
//# debugId=
|
|
896
|
+
//# debugId=FBBB2C8C4ADD424364756E2164756E21
|
|
888
897
|
//# sourceMappingURL=index.js.map
|