@ractive-ch/tab-mcp-client 0.19.0-rc.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.
- package/CHANGELOG.md +25 -10
- package/README.md +25 -13
- package/cdn/tab-mcp-client.min.js +3 -3
- package/cdn/tab-mcp-client.min.js.map +1 -1
- package/extension.d.ts +44 -18
- package/extension.js +39 -18
- package/extension.js.map +3 -3
- package/index.js +2 -2
- package/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,7 +6,7 @@ the Git tag `client-v<version>`. The format follows
|
|
|
6
6
|
[Semantic Versioning](https://semver.org/). The relay has its own
|
|
7
7
|
[changelog](https://github.com/ractive/tab-mcp/blob/main/packages/tab-mcp/CHANGELOG.md).
|
|
8
8
|
|
|
9
|
-
## [0.19.0-rc.
|
|
9
|
+
## [0.19.0-rc.2][client-0.19.0-rc.2] - 2026-11-21
|
|
10
10
|
|
|
11
11
|
### Breaking
|
|
12
12
|
|
|
@@ -33,7 +33,9 @@ alias. Search your code for the old names:
|
|
|
33
33
|
|
|
34
34
|
What the method does is unchanged, and so is the protocol (`hello.revokeAll`,
|
|
35
35
|
`grants.revokeAll`). A page's own texts under an old key are no longer used, as any
|
|
36
|
-
unknown key.
|
|
36
|
+
unknown key. The type check does not catch `addressChanged` where it is read behind a
|
|
37
|
+
cast, as from a caught error (`(error as { addressChanged?: unknown })`): search for it
|
|
38
|
+
by name.
|
|
37
39
|
|
|
38
40
|
### Added
|
|
39
41
|
|
|
@@ -91,13 +93,26 @@ unknown key.
|
|
|
91
93
|
tab-mcp page itself, filling in its own pairing code on the relay's pairing page after
|
|
92
94
|
asking its user, as the tab-mcp browser extension does (DEC-203). The content script's
|
|
93
95
|
part (`runPairingPage`), the worker's rules as one state machine (`CodeFiller`: the
|
|
94
|
-
origin check,
|
|
95
|
-
request, what withdraws a question),
|
|
96
|
-
`pairingCodes`), the relay's patterns and the
|
|
97
|
-
user is asked, its setting, the permission
|
|
98
|
-
registration. An entry of its own, out of the core,
|
|
99
|
-
script bundles less than 1 KB gzipped of it. See
|
|
100
|
-
[For browser extensions](README.md#for-browser-extensions).
|
|
96
|
+
origin check, also after the page's hello and after the answer, one question per page
|
|
97
|
+
load, the one more fill for the same tab and request, what withdraws a question),
|
|
98
|
+
which code to fill in (`takeCode`, `pairingCodes`), the relay's patterns and the
|
|
99
|
+
messages. The extension supplies how its user is asked, its setting, the permission
|
|
100
|
+
prompt and the content script's registration. An entry of its own, out of the core,
|
|
101
|
+
with no `chrome` types; a content script bundles less than 1 KB gzipped of it. See
|
|
102
|
+
[For browser extensions](README.md#for-browser-extensions). In detail:
|
|
103
|
+
- `new CodeFiller(host, { retry: false })` turns the one more fill off: the same
|
|
104
|
+
request's page back after a fill is asked about like any other page, so nothing is
|
|
105
|
+
filled in without a yes of its own. On by default.
|
|
106
|
+
- `takeCode` takes the same code sent again (the relay's answer to `startPairing()`
|
|
107
|
+
while pairing is on) as the next one only if its expiry now leaves `minLeftMs`, so
|
|
108
|
+
"`startPairing()` before `takeCode`" never fills in a code about to change.
|
|
109
|
+
- `code(signal, context)` and `failed(why, context)` get `context: FillContext`,
|
|
110
|
+
`{ tabId, client: { name, host } }`, the page's tab and AI app as `ask` gets them.
|
|
111
|
+
- `release()` is called when no fill needs pairing held any more: the AI app
|
|
112
|
+
connected, or a fill ended without sending its code (withdrawn, the page went, no
|
|
113
|
+
code) and no other fill is under way or waits for the relay's check.
|
|
114
|
+
- `runPairingPage` with a `page` (a test's) marks that page's document as run, not
|
|
115
|
+
the global: two pages in one test are independent.
|
|
101
116
|
|
|
102
117
|
### Changed
|
|
103
118
|
|
|
@@ -1066,7 +1081,7 @@ First alpha of the browser library, on the npm dist-tag `alpha`.
|
|
|
1066
1081
|
`<script type="module">` under `@ractive-ch/tab-mcp-client/cdn`.
|
|
1067
1082
|
- The connect dialog shows the pairing code from the relay.
|
|
1068
1083
|
|
|
1069
|
-
[client-0.19.0-rc.
|
|
1084
|
+
[client-0.19.0-rc.2]: https://github.com/ractive/tab-mcp/releases/tag/client-v0.19.0-rc.2
|
|
1070
1085
|
[client-0.18.1]: https://github.com/ractive/tab-mcp/releases/tag/client-v0.18.1
|
|
1071
1086
|
[client-0.18.0]: https://github.com/ractive/tab-mcp/releases/tag/client-v0.18.0
|
|
1072
1087
|
[client-0.17.0]: https://github.com/ractive/tab-mcp/releases/tag/client-v0.17.0
|
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ How the library, the relay and the tab-mcp browser extension fit together, with
|
|
|
17
17
|
picture:
|
|
18
18
|
[How the parts fit together](https://github.com/ractive/tab-mcp#how-the-parts-fit-together).
|
|
19
19
|
|
|
20
|
-
**Status: 0.19.0-rc.
|
|
20
|
+
**Status: 0.19.0-rc.2.** Until 1.0, a new minor version can still change the API. Which AI apps
|
|
21
21
|
work is listed in [compatibility](https://github.com/ractive/tab-mcp/blob/main/docs/compatibility.md).
|
|
22
22
|
|
|
23
23
|
## You need a relay
|
|
@@ -52,7 +52,7 @@ Or without a bundler, from a CDN as an ES module:
|
|
|
52
52
|
|
|
53
53
|
```html
|
|
54
54
|
<script type="module">
|
|
55
|
-
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.19.0-rc.
|
|
55
|
+
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.19.0-rc.2/cdn/tab-mcp-client.min.js";
|
|
56
56
|
</script>
|
|
57
57
|
```
|
|
58
58
|
|
|
@@ -712,8 +712,8 @@ mcp.addEventListener("grantschange", drawSwitches);
|
|
|
712
712
|
that does not import it loads nothing of it. Take both from the same version:
|
|
713
713
|
|
|
714
714
|
```js
|
|
715
|
-
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.19.0-rc.
|
|
716
|
-
import { allowedTools } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.19.0-rc.
|
|
715
|
+
import { TabMcp } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.19.0-rc.2/cdn/tab-mcp-client.min.js";
|
|
716
|
+
import { allowedTools } from "https://cdn.jsdelivr.net/npm/@ractive-ch/tab-mcp-client@0.19.0-rc.2/cdn/allowed.min.js";
|
|
717
717
|
```
|
|
718
718
|
|
|
719
719
|
**The risk.** An allowance outlives the user's attention: for up to the grant's 90 days,
|
|
@@ -1404,13 +1404,19 @@ than 1 KB gzipped of it.
|
|
|
1404
1404
|
origin (port included) and path (`isPairingSender`). One question per page load; on
|
|
1405
1405
|
Allow the code goes to that one page. The same request's page back in the same tab
|
|
1406
1406
|
within 30 s is the relay's answer that the code was not taken: filled once more
|
|
1407
|
-
without asking, never a third time; any other request asks.
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1407
|
+
without asking, never a third time; any other request asks. With
|
|
1408
|
+
`new CodeFiller(host, { retry: false })` that page is asked about like any other (one
|
|
1409
|
+
question per page load), so no code is ever filled in without a yes of its own. A
|
|
1410
|
+
question that waits is withdrawn when the page goes, AI access or the setting goes off,
|
|
1411
|
+
the relay changes (also during the page's hello), or the AI app connects meanwhile. A
|
|
1412
|
+
page that could not be asked about is reported, not dropped. `pagePort(port)` takes
|
|
1413
|
+
the browser's port over in `onConnect`.
|
|
1411
1414
|
- Which code to fill in: `takeCode(pairingCodes(mcp), signal, { now })` gives the current
|
|
1412
1415
|
code unless it is about to change, else the next one, and never fails while a code
|
|
1413
|
-
exists
|
|
1416
|
+
exists: on a computer whose clock is ahead every code would look expired, so after
|
|
1417
|
+
waiting 10 s for a next one it gives the current code. If the relay refuses that one,
|
|
1418
|
+
the one more fill covers it, or with `retry: false` a new question. The same code sent
|
|
1419
|
+
again, as the relay answers `startPairing()` while pairing is on, is not the next one.
|
|
1414
1420
|
- The relay's addresses: `relayPageOrigin(relay)`, `relaySitePattern(relay)` (the host
|
|
1415
1421
|
permission to ask for, `<scheme>://<host>/*`) and `pairingPagePattern(relay)` (a
|
|
1416
1422
|
content script's `matches`); `undefined` where an address has none (an IPv6 literal).
|
|
@@ -1421,8 +1427,12 @@ in for (`undefined` for none); whether AI access is on, and whether the user tur
|
|
|
1421
1427
|
filling in on; how the user is asked (`ask`, in its own panel or notification, the name
|
|
1422
1428
|
and host shown with invisible characters escaped, `@ractive-ch/tab-mcp-client/visible`);
|
|
1423
1429
|
the code with pairing held on (`startPairing()` before `takeCode`, kept on long enough
|
|
1424
|
-
after the fill for the relay to check the code); `release()
|
|
1425
|
-
|
|
1430
|
+
after the fill for the relay to check the code); `release()`, called when no fill needs
|
|
1431
|
+
pairing held any more (the AI app connected, or a fill ended without sending its code
|
|
1432
|
+
and no other fill is under way or waits for the relay's check); and
|
|
1433
|
+
`failed("busy" | "no-code", context)` to tell its user. `code(signal, context)` and
|
|
1434
|
+
`failed(why, context)` get the page's `context` (`FillContext`): `{ tabId, client }`,
|
|
1435
|
+
the same `client` (`{ name, host }`) that `ask` got. Besides, the extension keeps the
|
|
1426
1436
|
on/off setting, asks for the relay's site with a click
|
|
1427
1437
|
(`permissions.request({ origins: [relaySitePattern(relay)] })`, an optional host
|
|
1428
1438
|
permission), registers the content script for `pairingPagePattern(relay)` or puts it in
|
|
@@ -1458,10 +1468,12 @@ const filler = new CodeFiller({
|
|
|
1458
1468
|
holdPairing(); // mcp.startPairing(), and stopPairing() a while after
|
|
1459
1469
|
return takeCode(pairingCodes(mcp), signal, { now: Date.now() });
|
|
1460
1470
|
},
|
|
1461
|
-
release: () => releasePairing(),
|
|
1462
|
-
failed: (why) => showProblem(why), // "busy" | "no-code"
|
|
1471
|
+
release: () => releasePairing(), // no fill needs pairing held now
|
|
1472
|
+
failed: (why, { client }) => showProblem(why, client.host), // "busy" | "no-code"
|
|
1463
1473
|
now: () => Date.now(),
|
|
1464
1474
|
});
|
|
1475
|
+
// new CodeFiller(host, { retry: false }): never fill in without a yes, also not
|
|
1476
|
+
// the relay's answer to a fill.
|
|
1465
1477
|
|
|
1466
1478
|
// At the top level, so that a page's port wakes the worker; taken over at once.
|
|
1467
1479
|
// `page()` never rejects: a callback that throws closes the port and is logged.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var O,v,p,f=(e,t)=>{for(var[i,n,r]of O||[])for(var o=[e],s=globalThis,a=s.document,d,h,u,c,l;h=o.pop();)if(!v[h]&&(u=n[h])){v[h]=1;for(c=1;c<u.length;c++)o.push(r[u[c]]);if(!t&&h!==e&&(d=a&&a.head)){if(p===void 0)p=(c=a.querySelector("meta[property=csp-nonce]"))&&(c.nonce||c.getAttribute("nonce"))||"";if(l=a.createElement("link"),l.rel="modulepreload",l.crossOrigin="",p)l.nonce=p;l.href=new s.URL(u[0],i),d.appendChild(l)}}},k=(e,t,i,n)=>{for(var r={},o=0;o<t.length;o++)r[t[o]]=i[o];(O||=[]).push([e,r,t]),v||={},f(t[n],1)};k(import.meta.url,["
|
|
2
|
-
var D=/^[A-Za-z0-9_.-]{1,128}$/;function g(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var L=/^(default|examples|const|enum)$/,j=/^(properties|patternProperties|\$defs|definitions|dependentSchemas)$/;function R(e,t,i=0,n=!1){if(i>64||typeof e!=="object"||e===null)return;if(n||=Array.isArray(e),!n)t(e);for(let[r,o]of Object.entries(e))if(n||!L.test(r))R(o,t,i+1,!n&&j.test(r))}function N(e,t){let i=e;for(let n of t.split("/").slice(1)){let r;try{r=decodeURIComponent(n)}catch{return}if(r=r.replaceAll("~1","/").replaceAll("~0","~"),typeof i!=="object"||i===null||!Object.hasOwn(i,r))return;i=i[r]}return i}function H(e){let t=new Set,i=[],n=[],r=!1;if(R(e,(o)=>{if(typeof o.$anchor==="string")t.add(o.$anchor);if(typeof o.$ref==="string")i.push(o.$ref);if(typeof o.pattern==="string")n.push(o.pattern);let s=o.patternProperties;if(g(s))n.push(...Object.keys(s));if("x-mcp-header"in o)r=!0}),r)return"x-mcp-header is not supported by tab-mcp";for(let o of n)try{new RegExp(o,"u")}catch{return`pattern ${JSON.stringify(o)} is not a valid regular expression`}for(let o of i){if(!o.startsWith("#"))return`$ref ${JSON.stringify(o)} points outside the schema`;let s=o.slice(1);if(!(s===""||(s.startsWith("/")?N(e,s)!==void 0:t.has(s))))return`$ref ${JSON.stringify(o)} does not resolve`}return}function z(e){if(!g(e))throw TypeError("registerTool: the tool must be an object");let{name:t,title:i,description:n,inputSchema:r,outputSchema:o,execute:s,annotations:a}=e;if(typeof t!=="string"||!D.test(t))throw TypeError(`registerTool: the name must be 1–128 characters of A–Z, a–z, 0–9, "_", "-" or "." (got ${JSON.stringify(t)})`);if(typeof n!=="string"||n.trim()==="")throw TypeError(`registerTool: tool ${t} needs a description`);if(i!==void 0&&typeof i!=="string")throw TypeError(`registerTool: the title of ${t} must be a string`);if(typeof s!=="function")throw TypeError(`registerTool: tool ${t} needs an execute function`);let d=(c,l)=>{if(!g(c)||c.type!=="object")throw TypeError(`registerTool: the ${l} of ${t} must be a JSON Schema object with "type": "object"`);let w;try{w=JSON.parse(JSON.stringify(c))}catch{throw TypeError(`registerTool: the ${l} of ${t} must be JSON`)}let C=H(w);if(C!==void 0)throw TypeError(`registerTool: the ${l} of ${t}: ${C}`);return w},h=d(r??{type:"object"},"inputSchema");if(a!==void 0&&!g(a))throw TypeError(`registerTool: the annotations of ${t} must be an object`);let u={};for(let[c,l]of Object.entries(a??{}))if(typeof l==="boolean")u[c]=l;else if(l!==void 0&&/Hint$|^debugging$/.test(c))throw TypeError(`registerTool: ${c} of ${t} must be a boolean`);return{name:t,title:i,description:n,inputSchema:h,outputSchema:o===void 0?void 0:d(o,"outputSchema"),annotations:u,execute:s}}class b{#e=new Map;#d=new Set;#m;register(e,t={}){let{signal:i,exposedTo:n}=t,r=t.callers&&[...t.callers];if("webmcp"in t||r?.some((s)=>!/^(relay|local|webmcp)$/.test(s)))throw TypeError('registerTool: callers must be "relay", "local" or "webmcp"; option webmcp is gone');let o={...z(e),callers:r,exposedTo:n};if(i?.throwIfAborted(),this.#e.has(o.name))throw new DOMException(`registerTool: a tool named ${o.name} is already registered`,"InvalidStateError");this.#m?.(o),this.#e.set(o.name,o),i?.addEventListener("abort",()=>this.remove(o),{once:!0}),this.#y()}setCompiler(e){this.#m??=e}remove(e){if(this.#e.get(e.name)!==e)return;this.#e.delete(e.name),this.#y()}get(e){return this.#e.get(e)}list(){return[...this.#e.values()]}onChange(e){return this.#d.add(e),()=>this.#d.delete(e)}#y(){for(let e of[...this.#d])e()}}var _=/^[A-Za-z0-9_-]{43}$/;function J(e){return btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function K(){return J(crypto.getRandomValues(new Uint8Array(32)))}function G(e){return typeof e==="string"&&_.test(e)}function U(){try{return globalThis.localStorage??null}catch{return null}}class T{storage;key;#e;constructor(e,t){this.storage=e===void 0?U():e,this.key=t}current(){let e=null;try{e=this.storage?.getItem(this.key)??null}catch{}if(G(e))return this.#e=e,e;return this.#e}rotate(){let e=K();this.#e=e;try{this.storage?.setItem(this.key,e)}catch{}return e}}var I="0.19.0-rc.1";var M="@ractive-ch/tab-mcp-client",m=I;function B(){try{return Object.getOwnPropertyDescriptor(Document.prototype,"modelContext")?.get?.call(document)}catch{return}}var q=new Set(["localhost","127.0.0.1","[::1]"]),S={reconnectDelaysMs:[5000,1e4,20000,40000,60000],answerTimeoutMs:15000},P=new Set(["network","heartbeat","shutdown"]);function V(e){return Object.freeze({...e,client:Object.freeze({...e.client})})}function F(e){return typeof e==="string"&&e.trim().length>0&&e.length<=64&&![...e].some((t)=>{let i=t.codePointAt(0)??0;return i<32||i>=127&&i<=159})}var Y=/^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;function Z(e){return e.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,32).replace(/-$/,"")}function Q(e){let t;try{t=new URL(e)}catch{throw TypeError(`TabMcp: relay is not a URL: ${e}`)}let i=t.protocol==="https:"||t.protocol==="wss:";if(!i&&t.protocol!=="http:"&&t.protocol!=="ws:")throw TypeError(`TabMcp: relay must be an https: or wss: URL: ${e}`);if(!i&&!q.has(t.hostname))throw TypeError(`TabMcp: relay must use https: or wss: (http: only for localhost): ${e}`);let n=`${i?"https:":"http:"}//${t.host}`,r=t.pathname.replace(/\/+$/,"");return t.protocol=i?"wss:":"ws:",t.pathname=r.endsWith("/tab")?r:`${r}/tab`,t.search="",t.hash="",{url:t.href,origin:n}}function X(e){try{return new URL(e).host}catch{return""}}function ee(e){let t={sessionId:e.sessionId,address:e.address,origin:e.origin,pairing:e.pairing==="oidc"?"oidc":"code",expiresAt:e.expiresAt,limits:e.limits};if(e.appName!==void 0)t.appName=e.appName;return t}function y(){return Promise.reject(TypeError("TabMcp: this TabMcp has no relay"))}function x(e,t){return Object.assign(Object(e),{secretChanged:t})}function E(){return Promise.reject(new DOMException("TabMcp: not connected","InvalidStateError"))}class A extends EventTarget{#e=new b;#d;#m;#y;#R;#J;#b;#w;#g;#K;#v=!1;#T;#I;#S="none";#M;#a=0;#i="disconnected";#o;#l=Object.freeze([]);#f=!1;#P;#x;#A=!1;#k=!1;#n;#r;#h=0;#G;#u;#p;#$;#D;#E;#L={registry:this.#e,confirm:(e)=>this.#X(e),ownConfirm:()=>!!this.#R,toolCallStarted:(e)=>this.#t("toolcall",e),toolCallEnded:(e)=>this.#t("toolcallend",e)};constructor(e){super();let{server:t,appName:i}=e,n=e.relay===void 0?void 0:Q(e.relay);if(typeof t?.name!=="string"||typeof t.version!=="string")throw TypeError("TabMcp: server needs a name and a version");if(i!==void 0&&!F(i))throw TypeError("TabMcp: appName must be 1-64 characters without control characters");let r=e.app??Z(t.name);if(e.app!==void 0?typeof r!=="string"||!Y.test(r):n&&r==="")throw TypeError(e.app!==void 0?"TabMcp: app must be 1-32 characters of a-z, 0-9 and -, not starting or ending with -":"TabMcp: server.name has no letter a-z and no digit to make the address of: set app");if(this.#m=r,this.#w=n?.url,this.#d={...t},this.#y=i,this.#R=e.onConfirm,this.#J=e.alwaysAllow,this.#b=e.ui,this.#I=e.identityAssertion,this.#G=e.reconnect!==!1,n!==void 0){let s=e.storageKey??`tab-mcp:secret:${n.origin}:${encodeURIComponent(t.name)}`;this.#g=new T(e.storage,s),this.#K=e.storage===null?void 0:`${s}#tabs`}this.#e.onChange(()=>this.#t("toolschange",{tools:this.tools}));let o=e.webmcp===!0?B():void 0;if(o!==void 0)(f("84k58gsw"),import("./webmcp-84k58gsw.min.js")).then((s)=>s.mirror(this.#e,o,(a,d,h,u)=>this.#N().then((c)=>c.callFromWebMcp(this.#L,a,d,h,u)),this,r,e,m),(s)=>console.warn("tab-mcp: no tools are offered through WebMCP:",s))}registerTool(e,t={}){try{this.#e.register(e,t)}catch(i){return Promise.reject(i)}return Promise.resolve()}get tools(){return this.#e.list().map((e)=>e.name)}get state(){return this.#i}get session(){return this.#o}get grants(){return this.#l}get reconnecting(){return this.#u}get identity(){return this.#S}get identityMessage(){return this.#M}refreshIdentity(){let e=this.#o,t=this.#I;if(t===void 0)return Promise.reject(TypeError("TabMcp: no identityAssertion"));if(e===void 0)return E();let i=++this.#a,n=this.#n;this.#s("pending");let r=setTimeout(()=>{if(i!==this.#a||this.#S!=="pending")return;this.#a++,this.#s("none")},S.answerTimeoutMs);return new Promise((o)=>{let s=(a)=>{let{identity:d}=a.detail;if(d==="pending")return;this.removeEventListener("identitychange",s),clearTimeout(r),o(d)};this.addEventListener("identitychange",s),Promise.resolve().then(()=>t({address:e.address,sessionId:e.sessionId})).then((a)=>{if(i!==this.#a||this.#n!==n)return;if(typeof a!=="string"||a===""){this.#s("none");return}if(n?.send({type:"identity",assertion:a,round:i})!==!0)this.#s("none")},(a)=>{if(i!==this.#a)return;this.#t("error",{error:a instanceof Error?a:Error(String(a))}),this.#s("none")})})}signOut(){return this.#a++,this.#s("none"),this.#o?.pairing==="oidc"?this.#V({type:"identity.logout"},()=>!this.#l.length):E()}get pairingCode(){return this.#P}get pairingUntil(){return this.#x}connect(e={}){if(this.#w===void 0)return y();if(this.#i==="connected"&&this.#o!==void 0)return Promise.resolve(this.#o);if(this.#u!==void 0)return this.#k||=e.resume!==!0,this.#H();if(this.#r!==void 0)return this.#r;let t=globalThis.navigator?.userActivation;if(e.resume!==!0&&t!==void 0&&!t.isActive)return Promise.reject(new DOMException("connect() must be called from a user action, such as a click","NotAllowedError"));return this.#T?this.#T.then(()=>this.connect({resume:!0})):this.#j()}#j(){if(!this.#u)this.#c("connecting");let e=this.#U(this.#h);return this.#r=e,e.then(()=>{if(this.#r===e)this.#r=void 0},()=>{if(this.#r!==e)return;if(this.#r=void 0,this.#n=void 0,!this.#u)this.#c("disconnected")}),e}async#N(){let e=await (f("yf2x9zz2"),import("./connection-yf2x9zz2.min.js"));for(let t of e.compileRegistry(this.#e))this.#t("error",{error:t});return this.#D=e,e}async#U(e,t){let{openConnection:i,addressIdOf:n}=await this.#N(),r=this.#w;if(r===void 0||this.#g===void 0)return y();let o=t??this.#g.current()??this.#g.rotate(),s=await n(o);if(e!==this.#h)throw new DOMException("The connection was cancelled","AbortError");let a={},d=i(this.#ee(a),r,o,{address:s,revokeAll:!!t});if(!t)a.connection=d;return this.#n=d,d.ready}get hasRelay(){return this.#w!==void 0}serve(e,t){return this.#N().then((i)=>i.servePort({...this.#L,server:this.#d,error:(n)=>this.#t("error",{error:n})},e,t))}disconnect(){this.#W("user")}disconnectAll(){let e=this.#g;if(!e)return y();return this.#T??=this.#Y(e).finally(()=>{this.#T=void 0})}async#Y(e){let t=this.#i!=="disconnected"||this.#v,i=e.current();this.#W("disconnect_all");let n=this.#h;if(i){this.#c("connecting");try{await this.#U(n,i)}catch(r){if(n===this.#h)this.#c("disconnected"),this.#v=t;throw x(r,!1)}finally{if(n===this.#h)this.#n?.close("disconnect_all"),this.#n=void 0}}if(e.rotate(),this.#O([]),t)await this.#j().catch((r)=>{throw x(r,!0)});else this.#c("disconnected")}#W(e){this.#z(),this.#v=!1,this.#h++;let t=this.#n;if(this.#n=void 0,this.#r=void 0,t?.close(e),this.#i==="disconnected")return;this.#o=void 0,this.#_(),this.#a++,this.#s("none"),this.#c("disconnected",e)}#B(e,t){let i=S.reconnectDelaysMs,n=(i[Math.min(t,i.length)-1]??0)*(0.8+0.4*Math.random());clearTimeout(this.#p),this.#p=setTimeout(()=>{this.#H().catch(()=>{})},n),this.#Z(),this.#u={reason:e,attempt:t,at:Date.now()+n},this.#c("reconnecting",t>1?void 0:e)}#H(){if(clearTimeout(this.#p),this.#p=void 0,this.#r!==void 0)return this.#r;let e=this.#j();return e.catch((t)=>{let i=this.#u;if(i===void 0||this.#r!==void 0)return;let n=t?.reason;if(n===void 0||P.has(n)){this.#B(i.reason,i.attempt+1);return}if(this.#z(),this.#i="disconnected",this.#t("error",{error:t instanceof Error?t:Error(String(t))}),this.#i==="disconnected")this.#t("statechange",{state:"disconnected"})}),e}#Z(){this.#$??=this.#D?.onWake(()=>{if(this.#p!==void 0)this.#H().catch(()=>{})})}#z(){clearTimeout(this.#p),this.#p=void 0,this.#$?.(),this.#$=void 0,this.#u=void 0}startPairing(){if(this.#f=!0,this.#A=!1,this.#i==="connected")this.#q()}#q(){this.#C(void 0),this.#A=this.#o?.pairing==="oidc",this.#n?.send({type:"pairing.start"})}stopPairing(){if(!this.#f)return;if(this.#f=!1,this.#i==="connected")this.#n?.send({type:"pairing.stop"});this.#_()}#_(){this.#F(void 0),this.#C(void 0)}revoke(e){let t=()=>!this.#l.some((i)=>i.grantId===e);return t()?Promise.resolve():this.#V({type:"grant.revoke",grantId:e},t)}#V(e,t){return!this.#o||this.#n?.send(e)!==!0?E():this.#D.answer(this,e,t,()=>this.#i==="connected",S.answerTimeoutMs)}showConnectDialog(e={}){if(this.#w===void 0)return y();let t=e.document??globalThis.document,i=this.#E;if(i!==void 0)return i.doc===t?i.shown:Promise.reject(new DOMException("showConnectDialog: the dialog is already open in another document","InvalidStateError"));let n=this.#Q(t).finally(()=>{if(this.#E?.shown===n)this.#E=void 0});return this.#E={doc:t,shown:n},n}async#Q(e){let t=this.connect();t.catch(()=>{});let{showConnectDialog:i}=await (f("my0pbqd7"),import("./connect-my0pbqd7.min.js"));await i(this,t,e,this.#d.name,this.#b)}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}#t(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))}#c(e,t){if(this.#i===e&&e!=="reconnecting")return;this.#i=e,this.#t("statechange",t?{state:e,reason:t}:{state:e})}#s(e,t){if(this.#S===e&&t===void 0)return;this.#S=e,this.#M=e==="refused"?t:void 0,this.#t("identitychange",{identity:e,identityMessage:this.#M})}#F(e){if(this.#P===void 0&&e===void 0)return;this.#P=e,this.#t("pairingcode",{pairingCode:e})}#C(e){if(this.#x===e)return;this.#x=e,this.#t("pairinguntil",{pairingUntil:e})}#O(e){this.#l=Object.freeze(e.map(V)),this.#t("grantschange",{grants:this.#l})}#X(e){let t=this.#R;return (f("ba3dkf9p"),import("./confirm-ba3dkf9p.min.js")).then((i)=>i.confirmCall(this,e,t),()=>t?.(e)??!1)}get _allowed(){return[this.#e,this.#g,this.#J]}get _ui(){return this.#b}confirmInPage(e,t={}){let i=t.document??globalThis.document;if(i===void 0)return Promise.resolve(!1);return (f("ba3dkf9p"),import("./confirm-ba3dkf9p.min.js")).then((n)=>n.confirmInPage(this,e,i,{ui:this.#b}))}#ee(e){let t=()=>e.connection!==void 0&&this.#n===e.connection,i=!1;return{...this.#L,server:this.#d,app:this.#m,appName:this.#y,tabs:this.#K,library:{name:M,version:m},clientFor:(n)=>{let r=this.#l.find((s)=>s.grantId===n.grantId),o={kind:"relay",grantId:n.grantId,id:n.clientId,host:X(n.clientId)};if(r!==void 0)o.name=r.client.name;return o},sessionStarted:(n)=>{let r=ee(n);if(!t())return r;this.#o=r,this.#v=!1;let o=this.#f&&this.#u&&!this.#k&&this.#A&&r.pairing==="oidc";if(this.#k=!1,this.#z(),this.#O([...n.grants]),o)this.#C(new Date().toISOString());else if(this.#f)this.#q();if(this.#c("connected"),r.pairing==="oidc"&&this.#I)this.refreshIdentity();return r},pairingCode:(n)=>{if(t()&&this.#f)this.#F(n)},pairingOpen:(n)=>{if(t()&&this.#f)this.#C(n)},grantAdded:(n)=>{if(!t())return;this.#O([...this.#l.filter((r)=>r.grantId!==n.grantId),n])},grantRemoved:(n)=>{if(!t())return;this.#O(this.#l.filter((r)=>r.grantId!==n))},replaced:(n)=>{if(i)this.#t("replaced",n)},identityResult:(n,r,o)=>{if(!t())return;if(r!==this.#a)return;if(n)this.#s("bound");else this.#s("refused",o??"")},error:(n)=>{if(t())this.#t("error",{error:n})},closed:(n)=>{if(!t())return;if(n==="replaced")this.#v=i=!0;this.#n=void 0,this.#o=void 0;let r=this.#h;if(this.#_(),this.#a++,this.#s("none"),r!==this.#h)return;if(this.#G&&P.has(n))this.#B(n,1);else this.#c("disconnected",n)}}}}export{A as TabMcp,m as VERSION};
|
|
1
|
+
var O,v,p,f=(e,t)=>{for(var[i,n,r]of O||[])for(var o=[e],s=globalThis,a=s.document,d,h,u,c,l;h=o.pop();)if(!v[h]&&(u=n[h])){v[h]=1;for(c=1;c<u.length;c++)o.push(r[u[c]]);if(!t&&h!==e&&(d=a&&a.head)){if(p===void 0)p=(c=a.querySelector("meta[property=csp-nonce]"))&&(c.nonce||c.getAttribute("nonce"))||"";if(l=a.createElement("link"),l.rel="modulepreload",l.crossOrigin="",p)l.nonce=p;l.href=new s.URL(u[0],i),d.appendChild(l)}}},k=(e,t,i,n)=>{for(var r={},o=0;o<t.length;o++)r[t[o]]=i[o];(O||=[]).push([e,r,t]),v||={},f(t[n],1)};k(import.meta.url,["8j98c1ta","84k58gsw","yf2x9zz2","my0pbqd7","ba3dkf9p","nnxcwrxp","8r6h3wza","q758jr4g"],[["./tab-mcp-client.min.js"],["./webmcp-84k58gsw.min.js"],["./connection-yf2x9zz2.min.js"],["./connect-my0pbqd7.min.js",5,6,7],["./confirm-ba3dkf9p.min.js",5,6,7],["./tab-mcp-client-nnxcwrxp.min.js"],["./tab-mcp-client-8r6h3wza.min.js",5],["./tab-mcp-client-q758jr4g.min.js"]],0);
|
|
2
|
+
var D=/^[A-Za-z0-9_.-]{1,128}$/;function g(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var L=/^(default|examples|const|enum)$/,j=/^(properties|patternProperties|\$defs|definitions|dependentSchemas)$/;function R(e,t,i=0,n=!1){if(i>64||typeof e!=="object"||e===null)return;if(n||=Array.isArray(e),!n)t(e);for(let[r,o]of Object.entries(e))if(n||!L.test(r))R(o,t,i+1,!n&&j.test(r))}function N(e,t){let i=e;for(let n of t.split("/").slice(1)){let r;try{r=decodeURIComponent(n)}catch{return}if(r=r.replaceAll("~1","/").replaceAll("~0","~"),typeof i!=="object"||i===null||!Object.hasOwn(i,r))return;i=i[r]}return i}function H(e){let t=new Set,i=[],n=[],r=!1;if(R(e,(o)=>{if(typeof o.$anchor==="string")t.add(o.$anchor);if(typeof o.$ref==="string")i.push(o.$ref);if(typeof o.pattern==="string")n.push(o.pattern);let s=o.patternProperties;if(g(s))n.push(...Object.keys(s));if("x-mcp-header"in o)r=!0}),r)return"x-mcp-header is not supported by tab-mcp";for(let o of n)try{new RegExp(o,"u")}catch{return`pattern ${JSON.stringify(o)} is not a valid regular expression`}for(let o of i){if(!o.startsWith("#"))return`$ref ${JSON.stringify(o)} points outside the schema`;let s=o.slice(1);if(!(s===""||(s.startsWith("/")?N(e,s)!==void 0:t.has(s))))return`$ref ${JSON.stringify(o)} does not resolve`}return}function z(e){if(!g(e))throw TypeError("registerTool: the tool must be an object");let{name:t,title:i,description:n,inputSchema:r,outputSchema:o,execute:s,annotations:a}=e;if(typeof t!=="string"||!D.test(t))throw TypeError(`registerTool: the name must be 1–128 characters of A–Z, a–z, 0–9, "_", "-" or "." (got ${JSON.stringify(t)})`);if(typeof n!=="string"||n.trim()==="")throw TypeError(`registerTool: tool ${t} needs a description`);if(i!==void 0&&typeof i!=="string")throw TypeError(`registerTool: the title of ${t} must be a string`);if(typeof s!=="function")throw TypeError(`registerTool: tool ${t} needs an execute function`);let d=(c,l)=>{if(!g(c)||c.type!=="object")throw TypeError(`registerTool: the ${l} of ${t} must be a JSON Schema object with "type": "object"`);let w;try{w=JSON.parse(JSON.stringify(c))}catch{throw TypeError(`registerTool: the ${l} of ${t} must be JSON`)}let C=H(w);if(C!==void 0)throw TypeError(`registerTool: the ${l} of ${t}: ${C}`);return w},h=d(r??{type:"object"},"inputSchema");if(a!==void 0&&!g(a))throw TypeError(`registerTool: the annotations of ${t} must be an object`);let u={};for(let[c,l]of Object.entries(a??{}))if(typeof l==="boolean")u[c]=l;else if(l!==void 0&&/Hint$|^debugging$/.test(c))throw TypeError(`registerTool: ${c} of ${t} must be a boolean`);return{name:t,title:i,description:n,inputSchema:h,outputSchema:o===void 0?void 0:d(o,"outputSchema"),annotations:u,execute:s}}class b{#e=new Map;#d=new Set;#m;register(e,t={}){let{signal:i,exposedTo:n}=t,r=t.callers&&[...t.callers];if("webmcp"in t||r?.some((s)=>!/^(relay|local|webmcp)$/.test(s)))throw TypeError('registerTool: callers must be "relay", "local" or "webmcp"; option webmcp is gone');let o={...z(e),callers:r,exposedTo:n};if(i?.throwIfAborted(),this.#e.has(o.name))throw new DOMException(`registerTool: a tool named ${o.name} is already registered`,"InvalidStateError");this.#m?.(o),this.#e.set(o.name,o),i?.addEventListener("abort",()=>this.remove(o),{once:!0}),this.#y()}setCompiler(e){this.#m??=e}remove(e){if(this.#e.get(e.name)!==e)return;this.#e.delete(e.name),this.#y()}get(e){return this.#e.get(e)}list(){return[...this.#e.values()]}onChange(e){return this.#d.add(e),()=>this.#d.delete(e)}#y(){for(let e of[...this.#d])e()}}var _=/^[A-Za-z0-9_-]{43}$/;function J(e){return btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function K(){return J(crypto.getRandomValues(new Uint8Array(32)))}function G(e){return typeof e==="string"&&_.test(e)}function U(){try{return globalThis.localStorage??null}catch{return null}}class T{storage;key;#e;constructor(e,t){this.storage=e===void 0?U():e,this.key=t}current(){let e=null;try{e=this.storage?.getItem(this.key)??null}catch{}if(G(e))return this.#e=e,e;return this.#e}rotate(){let e=K();this.#e=e;try{this.storage?.setItem(this.key,e)}catch{}return e}}var I="0.19.0-rc.2";var M="@ractive-ch/tab-mcp-client",m=I;function B(){try{return Object.getOwnPropertyDescriptor(Document.prototype,"modelContext")?.get?.call(document)}catch{return}}var q=new Set(["localhost","127.0.0.1","[::1]"]),S={reconnectDelaysMs:[5000,1e4,20000,40000,60000],answerTimeoutMs:15000},P=new Set(["network","heartbeat","shutdown"]);function V(e){return Object.freeze({...e,client:Object.freeze({...e.client})})}function F(e){return typeof e==="string"&&e.trim().length>0&&e.length<=64&&![...e].some((t)=>{let i=t.codePointAt(0)??0;return i<32||i>=127&&i<=159})}var Y=/^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;function Z(e){return e.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,32).replace(/-$/,"")}function Q(e){let t;try{t=new URL(e)}catch{throw TypeError(`TabMcp: relay is not a URL: ${e}`)}let i=t.protocol==="https:"||t.protocol==="wss:";if(!i&&t.protocol!=="http:"&&t.protocol!=="ws:")throw TypeError(`TabMcp: relay must be an https: or wss: URL: ${e}`);if(!i&&!q.has(t.hostname))throw TypeError(`TabMcp: relay must use https: or wss: (http: only for localhost): ${e}`);let n=`${i?"https:":"http:"}//${t.host}`,r=t.pathname.replace(/\/+$/,"");return t.protocol=i?"wss:":"ws:",t.pathname=r.endsWith("/tab")?r:`${r}/tab`,t.search="",t.hash="",{url:t.href,origin:n}}function X(e){try{return new URL(e).host}catch{return""}}function ee(e){let t={sessionId:e.sessionId,address:e.address,origin:e.origin,pairing:e.pairing==="oidc"?"oidc":"code",expiresAt:e.expiresAt,limits:e.limits};if(e.appName!==void 0)t.appName=e.appName;return t}function y(){return Promise.reject(TypeError("TabMcp: this TabMcp has no relay"))}function x(e,t){return Object.assign(Object(e),{secretChanged:t})}function E(){return Promise.reject(new DOMException("TabMcp: not connected","InvalidStateError"))}class A extends EventTarget{#e=new b;#d;#m;#y;#R;#J;#b;#w;#g;#K;#v=!1;#T;#I;#S="none";#M;#a=0;#i="disconnected";#o;#l=Object.freeze([]);#f=!1;#P;#x;#A=!1;#k=!1;#n;#r;#h=0;#G;#u;#p;#$;#D;#E;#L={registry:this.#e,confirm:(e)=>this.#X(e),ownConfirm:()=>!!this.#R,toolCallStarted:(e)=>this.#t("toolcall",e),toolCallEnded:(e)=>this.#t("toolcallend",e)};constructor(e){super();let{server:t,appName:i}=e,n=e.relay===void 0?void 0:Q(e.relay);if(typeof t?.name!=="string"||typeof t.version!=="string")throw TypeError("TabMcp: server needs a name and a version");if(i!==void 0&&!F(i))throw TypeError("TabMcp: appName must be 1-64 characters without control characters");let r=e.app??Z(t.name);if(e.app!==void 0?typeof r!=="string"||!Y.test(r):n&&r==="")throw TypeError(e.app!==void 0?"TabMcp: app must be 1-32 characters of a-z, 0-9 and -, not starting or ending with -":"TabMcp: server.name has no letter a-z and no digit to make the address of: set app");if(this.#m=r,this.#w=n?.url,this.#d={...t},this.#y=i,this.#R=e.onConfirm,this.#J=e.alwaysAllow,this.#b=e.ui,this.#I=e.identityAssertion,this.#G=e.reconnect!==!1,n!==void 0){let s=e.storageKey??`tab-mcp:secret:${n.origin}:${encodeURIComponent(t.name)}`;this.#g=new T(e.storage,s),this.#K=e.storage===null?void 0:`${s}#tabs`}this.#e.onChange(()=>this.#t("toolschange",{tools:this.tools}));let o=e.webmcp===!0?B():void 0;if(o!==void 0)(f("84k58gsw"),import("./webmcp-84k58gsw.min.js")).then((s)=>s.mirror(this.#e,o,(a,d,h,u)=>this.#N().then((c)=>c.callFromWebMcp(this.#L,a,d,h,u)),this,r,e,m),(s)=>console.warn("tab-mcp: no tools are offered through WebMCP:",s))}registerTool(e,t={}){try{this.#e.register(e,t)}catch(i){return Promise.reject(i)}return Promise.resolve()}get tools(){return this.#e.list().map((e)=>e.name)}get state(){return this.#i}get session(){return this.#o}get grants(){return this.#l}get reconnecting(){return this.#u}get identity(){return this.#S}get identityMessage(){return this.#M}refreshIdentity(){let e=this.#o,t=this.#I;if(t===void 0)return Promise.reject(TypeError("TabMcp: no identityAssertion"));if(e===void 0)return E();let i=++this.#a,n=this.#n;this.#s("pending");let r=setTimeout(()=>{if(i!==this.#a||this.#S!=="pending")return;this.#a++,this.#s("none")},S.answerTimeoutMs);return new Promise((o)=>{let s=(a)=>{let{identity:d}=a.detail;if(d==="pending")return;this.removeEventListener("identitychange",s),clearTimeout(r),o(d)};this.addEventListener("identitychange",s),Promise.resolve().then(()=>t({address:e.address,sessionId:e.sessionId})).then((a)=>{if(i!==this.#a||this.#n!==n)return;if(typeof a!=="string"||a===""){this.#s("none");return}if(n?.send({type:"identity",assertion:a,round:i})!==!0)this.#s("none")},(a)=>{if(i!==this.#a)return;this.#t("error",{error:a instanceof Error?a:Error(String(a))}),this.#s("none")})})}signOut(){return this.#a++,this.#s("none"),this.#o?.pairing==="oidc"?this.#V({type:"identity.logout"},()=>!this.#l.length):E()}get pairingCode(){return this.#P}get pairingUntil(){return this.#x}connect(e={}){if(this.#w===void 0)return y();if(this.#i==="connected"&&this.#o!==void 0)return Promise.resolve(this.#o);if(this.#u!==void 0)return this.#k||=e.resume!==!0,this.#H();if(this.#r!==void 0)return this.#r;let t=globalThis.navigator?.userActivation;if(e.resume!==!0&&t!==void 0&&!t.isActive)return Promise.reject(new DOMException("connect() must be called from a user action, such as a click","NotAllowedError"));return this.#T?this.#T.then(()=>this.connect({resume:!0})):this.#j()}#j(){if(!this.#u)this.#c("connecting");let e=this.#U(this.#h);return this.#r=e,e.then(()=>{if(this.#r===e)this.#r=void 0},()=>{if(this.#r!==e)return;if(this.#r=void 0,this.#n=void 0,!this.#u)this.#c("disconnected")}),e}async#N(){let e=await (f("yf2x9zz2"),import("./connection-yf2x9zz2.min.js"));for(let t of e.compileRegistry(this.#e))this.#t("error",{error:t});return this.#D=e,e}async#U(e,t){let{openConnection:i,addressIdOf:n}=await this.#N(),r=this.#w;if(r===void 0||this.#g===void 0)return y();let o=t??this.#g.current()??this.#g.rotate(),s=await n(o);if(e!==this.#h)throw new DOMException("The connection was cancelled","AbortError");let a={},d=i(this.#ee(a),r,o,{address:s,revokeAll:!!t});if(!t)a.connection=d;return this.#n=d,d.ready}get hasRelay(){return this.#w!==void 0}serve(e,t){return this.#N().then((i)=>i.servePort({...this.#L,server:this.#d,error:(n)=>this.#t("error",{error:n})},e,t))}disconnect(){this.#W("user")}disconnectAll(){let e=this.#g;if(!e)return y();return this.#T??=this.#Y(e).finally(()=>{this.#T=void 0})}async#Y(e){let t=this.#i!=="disconnected"||this.#v,i=e.current();this.#W("disconnect_all");let n=this.#h;if(i){this.#c("connecting");try{await this.#U(n,i)}catch(r){if(n===this.#h)this.#c("disconnected"),this.#v=t;throw x(r,!1)}finally{if(n===this.#h)this.#n?.close("disconnect_all"),this.#n=void 0}}if(e.rotate(),this.#O([]),t)await this.#j().catch((r)=>{throw x(r,!0)});else this.#c("disconnected")}#W(e){this.#z(),this.#v=!1,this.#h++;let t=this.#n;if(this.#n=void 0,this.#r=void 0,t?.close(e),this.#i==="disconnected")return;this.#o=void 0,this.#_(),this.#a++,this.#s("none"),this.#c("disconnected",e)}#B(e,t){let i=S.reconnectDelaysMs,n=(i[Math.min(t,i.length)-1]??0)*(0.8+0.4*Math.random());clearTimeout(this.#p),this.#p=setTimeout(()=>{this.#H().catch(()=>{})},n),this.#Z(),this.#u={reason:e,attempt:t,at:Date.now()+n},this.#c("reconnecting",t>1?void 0:e)}#H(){if(clearTimeout(this.#p),this.#p=void 0,this.#r!==void 0)return this.#r;let e=this.#j();return e.catch((t)=>{let i=this.#u;if(i===void 0||this.#r!==void 0)return;let n=t?.reason;if(n===void 0||P.has(n)){this.#B(i.reason,i.attempt+1);return}if(this.#z(),this.#i="disconnected",this.#t("error",{error:t instanceof Error?t:Error(String(t))}),this.#i==="disconnected")this.#t("statechange",{state:"disconnected"})}),e}#Z(){this.#$??=this.#D?.onWake(()=>{if(this.#p!==void 0)this.#H().catch(()=>{})})}#z(){clearTimeout(this.#p),this.#p=void 0,this.#$?.(),this.#$=void 0,this.#u=void 0}startPairing(){if(this.#f=!0,this.#A=!1,this.#i==="connected")this.#q()}#q(){this.#C(void 0),this.#A=this.#o?.pairing==="oidc",this.#n?.send({type:"pairing.start"})}stopPairing(){if(!this.#f)return;if(this.#f=!1,this.#i==="connected")this.#n?.send({type:"pairing.stop"});this.#_()}#_(){this.#F(void 0),this.#C(void 0)}revoke(e){let t=()=>!this.#l.some((i)=>i.grantId===e);return t()?Promise.resolve():this.#V({type:"grant.revoke",grantId:e},t)}#V(e,t){return!this.#o||this.#n?.send(e)!==!0?E():this.#D.answer(this,e,t,()=>this.#i==="connected",S.answerTimeoutMs)}showConnectDialog(e={}){if(this.#w===void 0)return y();let t=e.document??globalThis.document,i=this.#E;if(i!==void 0)return i.doc===t?i.shown:Promise.reject(new DOMException("showConnectDialog: the dialog is already open in another document","InvalidStateError"));let n=this.#Q(t).finally(()=>{if(this.#E?.shown===n)this.#E=void 0});return this.#E={doc:t,shown:n},n}async#Q(e){let t=this.connect();t.catch(()=>{});let{showConnectDialog:i}=await (f("my0pbqd7"),import("./connect-my0pbqd7.min.js"));await i(this,t,e,this.#d.name,this.#b)}addEventListener(e,t,i){super.addEventListener(e,t,i)}removeEventListener(e,t,i){super.removeEventListener(e,t,i)}#t(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))}#c(e,t){if(this.#i===e&&e!=="reconnecting")return;this.#i=e,this.#t("statechange",t?{state:e,reason:t}:{state:e})}#s(e,t){if(this.#S===e&&t===void 0)return;this.#S=e,this.#M=e==="refused"?t:void 0,this.#t("identitychange",{identity:e,identityMessage:this.#M})}#F(e){if(this.#P===void 0&&e===void 0)return;this.#P=e,this.#t("pairingcode",{pairingCode:e})}#C(e){if(this.#x===e)return;this.#x=e,this.#t("pairinguntil",{pairingUntil:e})}#O(e){this.#l=Object.freeze(e.map(V)),this.#t("grantschange",{grants:this.#l})}#X(e){let t=this.#R;return (f("ba3dkf9p"),import("./confirm-ba3dkf9p.min.js")).then((i)=>i.confirmCall(this,e,t),()=>t?.(e)??!1)}get _allowed(){return[this.#e,this.#g,this.#J]}get _ui(){return this.#b}confirmInPage(e,t={}){let i=t.document??globalThis.document;if(i===void 0)return Promise.resolve(!1);return (f("ba3dkf9p"),import("./confirm-ba3dkf9p.min.js")).then((n)=>n.confirmInPage(this,e,i,{ui:this.#b}))}#ee(e){let t=()=>e.connection!==void 0&&this.#n===e.connection,i=!1;return{...this.#L,server:this.#d,app:this.#m,appName:this.#y,tabs:this.#K,library:{name:M,version:m},clientFor:(n)=>{let r=this.#l.find((s)=>s.grantId===n.grantId),o={kind:"relay",grantId:n.grantId,id:n.clientId,host:X(n.clientId)};if(r!==void 0)o.name=r.client.name;return o},sessionStarted:(n)=>{let r=ee(n);if(!t())return r;this.#o=r,this.#v=!1;let o=this.#f&&this.#u&&!this.#k&&this.#A&&r.pairing==="oidc";if(this.#k=!1,this.#z(),this.#O([...n.grants]),o)this.#C(new Date().toISOString());else if(this.#f)this.#q();if(this.#c("connected"),r.pairing==="oidc"&&this.#I)this.refreshIdentity();return r},pairingCode:(n)=>{if(t()&&this.#f)this.#F(n)},pairingOpen:(n)=>{if(t()&&this.#f)this.#C(n)},grantAdded:(n)=>{if(!t())return;this.#O([...this.#l.filter((r)=>r.grantId!==n.grantId),n])},grantRemoved:(n)=>{if(!t())return;this.#O(this.#l.filter((r)=>r.grantId!==n))},replaced:(n)=>{if(i)this.#t("replaced",n)},identityResult:(n,r,o)=>{if(!t())return;if(r!==this.#a)return;if(n)this.#s("bound");else this.#s("refused",o??"")},error:(n)=>{if(t())this.#t("error",{error:n})},closed:(n)=>{if(!t())return;if(n==="replaced")this.#v=i=!0;this.#n=void 0,this.#o=void 0;let r=this.#h;if(this.#_(),this.#a++,this.#s("none"),r!==this.#h)return;if(this.#G&&P.has(n))this.#B(n,1);else this.#c("disconnected",n)}}}}export{A as TabMcp,m as VERSION};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=3BE1AB9A3DAE42FC64756E2164756E21
|
|
5
5
|
//# sourceMappingURL=tab-mcp-client.min.js.map
|
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
"/**\n * `TabMcp`: the eagerly loaded core (DEC-035). It holds the tool registry, the\n * events, the pairing state and the address secret; `connect()` loads the\n * connection and the MCP handler with a dynamic `import()`.\n */\n\nimport type { CallHost, ConnectionHandle, ConnectionHost } from \"./internal.ts\";\nimport type { GrantRef, SessionMessage, TabMessage } from \"./protocol.ts\";\nimport { ToolRegistry } from \"./registry.ts\";\nimport { SecretStore } from \"./secret.ts\";\nimport type {\n\tBrowserExtension,\n\tConfirmAnswer,\n\tConfirmHandler,\n\tConfirmRequest,\n\tConnectionState,\n\tConnectOptions,\n\tDialogOptions,\n\tDisconnectReason,\n\tGrant,\n\tIdentityAssertionHandler,\n\tIdentityState,\n\tPairingCode,\n\tReconnectingInfo,\n\tRegisterToolOptions,\n\tRelayClient,\n\tServeHandle,\n\tServeOptions,\n\tServerInfo,\n\tSessionInfo,\n\tTabMcpEventMap,\n\tTabMcpOptions,\n\tTool,\n\tToolCallClient,\n\tTunnelPort,\n} from \"./types.ts\";\nimport { LIBRARY_NAME, VERSION } from \"./version.ts\";\nimport type { ModelContext } from \"./webmcp.ts\";\n\n/**\n * The browser's own `ModelContext` of this document, read when a `TabMcp` is\n * made, through `Document.prototype`'s getter: never an own\n * `document.modelContext` (a polyfill such as `@mcp-b/global`, or any page\n * script; DEC-115). `undefined` without native WebMCP or a document. In the\n * core; the mirror itself is a chunk of its own (DEC-171).\n */\nfunction nativeContext(): ModelContext | undefined {\n\ttry {\n\t\treturn Object.getOwnPropertyDescriptor(\n\t\t\tDocument.prototype,\n\t\t\t\"modelContext\",\n\t\t)?.get?.call(document);\n\t} catch {\n\t\treturn undefined; // no document\n\t}\n}\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/**\n * The library's waits, in milliseconds: constants for pages (CU 17), which\n * only tests change. `reconnectDelaysMs`: before each reconnect attempt,\n * the last one repeating. `answerTimeoutMs`: for an identity assertion and\n * the relay's answer to it, and for the relay's answer to `revoke()` and\n * `signOut()`.\n */\nexport const timing: {\n\treconnectDelaysMs: number[];\n\tanswerTimeoutMs: number;\n} = {\n\treconnectDelaysMs: [5_000, 10_000, 20_000, 40_000, 60_000],\n\tanswerTimeoutMs: 15_000,\n};\n/** Reasons after which the library connects again by itself. */\nconst RECONNECT_REASONS = new Set<DisconnectReason>([\n\t\"network\",\n\t\"heartbeat\",\n\t\"shutdown\",\n]);\n\n/** A grant as the page sees it: frozen, so a page cannot change what decides Always allow. */\nfunction frozenGrant(grant: Grant): Grant {\n\treturn Object.freeze({\n\t\t...grant,\n\t\tclient: Object.freeze({ ...grant.client }),\n\t});\n}\n\n/** What the relay accepts as `hello.app.name` (protocol: session). */\nfunction isAppName(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.trim().length > 0 &&\n\t\tvalue.length <= 64 &&\n\t\t![...value].some((ch) => {\n\t\t\tconst c = ch.codePointAt(0) ?? 0;\n\t\t\treturn c < 0x20 || (c >= 0x7f && c <= 0x9f);\n\t\t})\n\t);\n}\n\n/** An app id as the relay takes it (DEC-196). */\nconst APP_ID = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;\n\n/**\n * The app id a server name gives: lower case, letters without their marks,\n * each run of anything but a-z and 0-9 as one `-`, none at either end, at\n * most 32 characters; `\"\"` when nothing is left.\n */\nexport function appIdOf(name: string): string {\n\treturn name\n\t\t.normalize(\"NFKD\")\n\t\t.replace(/\\p{M}/gu, \"\")\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\")\n\t\t.slice(0, 32)\n\t\t.replace(/-$/, \"\");\n}\n\n/** `wss://host/tab` for a relay given as `https://host`, `wss://host` or with `/tab`. */\nexport function tabUrl(relay: string): { url: string; origin: string } {\n\tlet u: URL;\n\ttry {\n\t\tu = new URL(relay);\n\t} catch {\n\t\tthrow new TypeError(`TabMcp: relay is not a URL: ${relay}`);\n\t}\n\tconst secure = u.protocol === \"https:\" || u.protocol === \"wss:\";\n\tif (!secure && u.protocol !== \"http:\" && u.protocol !== \"ws:\") {\n\t\tthrow new TypeError(\n\t\t\t`TabMcp: relay must be an https: or wss: URL: ${relay}`,\n\t\t);\n\t}\n\t// The secret travels in hello: never in clear text beyond this machine.\n\tif (!secure && !LOOPBACK.has(u.hostname)) {\n\t\tthrow new TypeError(\n\t\t\t`TabMcp: relay must use https: or wss: (http: only for localhost): ${relay}`,\n\t\t);\n\t}\n\tconst origin = `${secure ? \"https:\" : \"http:\"}//${u.host}`;\n\tconst path = u.pathname.replace(/\\/+$/, \"\");\n\tu.protocol = secure ? \"wss:\" : \"ws:\";\n\tu.pathname = path.endsWith(\"/tab\") ? path : `${path}/tab`;\n\tu.search = \"\";\n\tu.hash = \"\";\n\treturn { url: u.href, origin };\n}\n\nfunction hostOf(url: string): string {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction sessionInfo(m: SessionMessage): SessionInfo {\n\tconst info: SessionInfo = {\n\t\tsessionId: m.sessionId,\n\t\taddress: m.address,\n\t\torigin: m.origin,\n\t\tpairing: m.pairing === \"oidc\" ? \"oidc\" : \"code\",\n\t\texpiresAt: m.expiresAt,\n\t\tlimits: m.limits,\n\t};\n\tif (m.appName !== undefined) info.appName = m.appName;\n\treturn info;\n}\n\n/** What `connect()`, `showConnectDialog()` and `disconnectAll()` reject with without a relay. */\nfunction noRelay(): Promise<never> {\n\treturn Promise.reject(new TypeError(\"TabMcp: this TabMcp has no relay\"));\n}\n\n/**\n * A rejection of `disconnectAll()`: `secretChanged` says whether the apps\n * were disconnected and the secret is new (only connecting with it failed)\n * or not (the old one could not be taken back and is kept, with its grants).\n */\nfunction changed(error: unknown, secretChanged: boolean): unknown {\n\treturn Object.assign(Object(error), { secretChanged });\n}\n\n/** What a method that asks the relay rejects with while it cannot. */\nfunction notConnected(): Promise<never> {\n\treturn Promise.reject(\n\t\tnew DOMException(\"TabMcp: not connected\", \"InvalidStateError\"),\n\t);\n}\n\n/** The lazy chunk (`connection.ts`). */\ntype Lazy = typeof import(\"./connection.ts\");\n\ntype Listener<K extends keyof TabMcpEventMap> = (\n\tevent: TabMcpEventMap[K],\n) => void;\n\n/**\n * Offers a page's tools to AI apps through a tab-mcp relay (and, without\n * `relay`, only through `serve` and WebMCP).\n *\n * ```ts\n * const mcp = new TabMcp({ relay: \"https://relay.example\", server: { name: \"Calculator\", version: \"1.0.0\" } });\n * await mcp.registerTool({ name: \"add\", description: \"Add two numbers\", execute: ({ a, b }) => Number(a) + Number(b) });\n * button.onclick = () => mcp.showConnectDialog();\n * ```\n */\nexport class TabMcp extends EventTarget {\n\treadonly #registry = new ToolRegistry();\n\t/**\n\t * With `webmcp: true`: the tab-mcp browser extension while it serves this\n\t * page, with the AI apps that reach the page's tools through it (DEC-207);\n\t * `extensionchange` says when it changes. `undefined` without it, while\n\t * its AI access is off, and without WebMCP. Declared only: the mirror's\n\t * chunk defines it on the instance once it hears the extension, so that\n\t * the core carries no bytes for it (until then it is `undefined`).\n\t */\n\tdeclare readonly extension: BrowserExtension | undefined;\n\treadonly #server: ServerInfo;\n\treadonly #app: string;\n\treadonly #appName: string | undefined;\n\treadonly #onConfirm: ConfirmHandler | undefined;\n\treadonly #alwaysAllow: TabMcpOptions[\"alwaysAllow\"];\n\treadonly #ui: DialogOptions | undefined;\n\t/** `undefined` without a relay: tools only through `serve` and WebMCP. */\n\treadonly #relayUrl: string | undefined;\n\treadonly #secrets: SecretStore | undefined;\n\t/** The channel of the tabs that share the secret (DEC-095). */\n\treadonly #tabs: string | undefined;\n\t/**\n\t * The page was on when a takeover ended its session (or when a\n\t * `disconnectAll()` failed), and nothing was ended since: the next\n\t * `disconnectAll()` connects with the new secret. Only that; whether it\n\t * takes the old address back does not depend on it (DEC-136).\n\t */\n\t#stayOn = false;\n\t/** The running `disconnectAll()`: a second call returns it, `connect()` waits for it. */\n\t#renewing: Promise<void> | undefined;\n\treadonly #identityAssertion: IdentityAssertionHandler | undefined;\n\t#identity: IdentityState = \"none\";\n\t#identityMessage: string | undefined;\n\t/** Incremented per identity request, so a late answer of an older one is dropped. */\n\t#identityRound = 0;\n\t#state: ConnectionState = \"disconnected\";\n\t#session: SessionInfo | undefined;\n\t#grants: readonly Grant[] = Object.freeze([]);\n\t#pairing = false;\n\t#pairingCode: PairingCode | undefined;\n\t#pairingUntil: string | undefined;\n\t/** The last `pairing.start` went to an `oidc` session (DEC-202). */\n\t#asked = false;\n\t/** `connect()` from a click while reconnecting: that session asks again. */\n\t#clicked = false;\n\t#connection: ConnectionHandle | undefined;\n\t#connecting: Promise<SessionInfo> | undefined;\n\t/** Incremented when a connection ends or is cancelled. */\n\t#generation = 0;\n\treadonly #reconnect: boolean;\n\t#reconnecting: ReconnectingInfo | undefined;\n\t#reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\t#unwatch: (() => void) | undefined;\n\t/** The lazy chunk, once `#load()` loaded it. */\n\t#lazy: Lazy | undefined;\n\t/** The open \"Connect your AI app\" dialog: one at a time. */\n\t#connectDialog: { doc: Document; shown: Promise<void> } | undefined;\n\t/**\n\t * What a tool call needs, through the relay and WebMCP alike. The events\n\t * always, even from a connection that is no longer current: a call that\n\t * started must end, and every end has its start.\n\t */\n\treadonly #calls: CallHost = {\n\t\tregistry: this.#registry,\n\t\tconfirm: (request) => this.#confirm(request),\n\t\townConfirm: () => !!this.#onConfirm,\n\t\ttoolCallStarted: (call) => this.#emit(\"toolcall\", call),\n\t\ttoolCallEnded: (call) => this.#emit(\"toolcallend\", call),\n\t};\n\n\tconstructor(options: TabMcpOptions) {\n\t\tsuper();\n\t\tconst { server, appName } = options;\n\t\tconst relay =\n\t\t\toptions.relay === undefined ? undefined : tabUrl(options.relay);\n\t\tif (\n\t\t\ttypeof server?.name !== \"string\" ||\n\t\t\ttypeof server.version !== \"string\"\n\t\t) {\n\t\t\tthrow new TypeError(\"TabMcp: server needs a name and a version\");\n\t\t}\n\t\tif (appName !== undefined && !isAppName(appName)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"TabMcp: appName must be 1-64 characters without control characters\",\n\t\t\t);\n\t\t}\n\t\tconst app = options.app ?? appIdOf(server.name);\n\t\tif (\n\t\t\toptions.app !== undefined\n\t\t\t\t? typeof app !== \"string\" || !APP_ID.test(app)\n\t\t\t\t: relay && app === \"\"\n\t\t) {\n\t\t\tthrow new TypeError(\n\t\t\t\toptions.app !== undefined\n\t\t\t\t\t? \"TabMcp: app must be 1-32 characters of a-z, 0-9 and -, not starting or ending with -\"\n\t\t\t\t\t: \"TabMcp: server.name has no letter a-z and no digit to make the address of: set app\",\n\t\t\t);\n\t\t}\n\t\tthis.#app = app;\n\t\tthis.#relayUrl = relay?.url;\n\t\tthis.#server = { ...server };\n\t\tthis.#appName = appName;\n\t\tthis.#onConfirm = options.onConfirm;\n\t\tthis.#alwaysAllow = options.alwaysAllow;\n\t\tthis.#ui = options.ui;\n\t\tthis.#identityAssertion = options.identityAssertion;\n\t\tthis.#reconnect = options.reconnect !== false;\n\t\tif (relay !== undefined) {\n\t\t\t// One address per relay and page (server name, DEC-083).\n\t\t\tconst key =\n\t\t\t\toptions.storageKey ??\n\t\t\t\t`tab-mcp:secret:${relay.origin}:${encodeURIComponent(server.name)}`;\n\t\t\tthis.#secrets = new SecretStore(options.storage, key);\n\t\t\t// Tabs that share the secret share this channel; with `storage: null`\n\t\t\t// every tab has a secret of its own (DEC-095).\n\t\t\tthis.#tabs = options.storage === null ? undefined : `${key}#tabs`;\n\t\t}\n\t\tthis.#registry.onChange(() =>\n\t\t\tthis.#emit(\"toolschange\", { tools: this.tools }),\n\t\t);\n\t\t// Also through the browser's own WebMCP, where it has it (DEC-115):\n\t\t// consequential tools only when their registration says so. The getter\n\t\t// is read now (WM 10); the mirror loads only then (DEC-171), with the\n\t\t// handshake with the tab-mcp browser extension (DEC-207).\n\t\tconst context = options.webmcp === true ? nativeContext() : undefined;\n\t\tif (context !== undefined)\n\t\t\timport(\"./webmcp.ts\").then(\n\t\t\t\t(m) =>\n\t\t\t\t\tm.mirror(\n\t\t\t\t\t\tthis.#registry,\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t(tool, input, signal, by) =>\n\t\t\t\t\t\t\tthis.#load().then((lazy) =>\n\t\t\t\t\t\t\t\tlazy.callFromWebMcp(this.#calls, tool, input, signal, by),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tapp,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\t// Passed, not imported there: a chunk shared with the core\n\t\t\t\t\t\t// would cost the core more.\n\t\t\t\t\t\tVERSION,\n\t\t\t\t\t),\n\t\t\t\t// Like a failed registration: warned, the relay unaffected.\n\t\t\t\t(error: unknown) =>\n\t\t\t\t\tconsole.warn(\"tab-mcp: no tools are offered through WebMCP:\", error),\n\t\t\t);\n\t}\n\n\t/**\n\t * Register a tool (WebMCP shape). Allowed before and after `connect()`;\n\t * aborting `options.signal` unregisters it. Rejects with a `TypeError` for\n\t * an invalid tool and an `InvalidStateError` for a duplicate name (the\n\t * tool is registered, or refused, before it returns); await it or catch\n\t * the rejection (DEC-010).\n\t */\n\tregisterTool<Input extends object = Record<string, unknown>>(\n\t\ttool: Tool<Input>,\n\t\toptions: RegisterToolOptions = {},\n\t): Promise<void> {\n\t\ttry {\n\t\t\t// The arguments are checked against `inputSchema` before `execute` runs.\n\t\t\tthis.#registry.register(tool as unknown as Tool, options);\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\treturn Promise.resolve();\n\t}\n\n\t/** Names of the registered tools. */\n\tget tools(): readonly string[] {\n\t\treturn this.#registry.list().map((t) => t.name);\n\t}\n\n\tget state(): ConnectionState {\n\t\treturn this.#state;\n\t}\n\n\t/** The current session, while connected: its `address` is the one to give to AI apps. */\n\tget session(): SessionInfo | undefined {\n\t\treturn this.#session;\n\t}\n\n\t/** The AI apps connected to this address (frozen; a new array when they change). */\n\tget grants(): readonly Grant[] {\n\t\treturn this.#grants;\n\t}\n\n\t/**\n\t * While `state` is `reconnecting`: the next (or running) attempt and when\n\t * it starts. `undefined` otherwise.\n\t */\n\tget reconnecting(): ReconnectingInfo | undefined {\n\t\treturn this.#reconnecting;\n\t}\n\n\t/** Who the relay knows as the page's user (identity binding). */\n\tget identity(): IdentityState {\n\t\treturn this.#identity;\n\t}\n\n\t/** Why the relay refused the identity, while `identity` is `refused`. */\n\tget identityMessage(): string | undefined {\n\t\treturn this.#identityMessage;\n\t}\n\n\t/**\n\t * Ask the `identityAssertion` hook again and send the result, e.g. after\n\t * the user signed in without a page load. Resolves with the outcome, the\n\t * new `identity`: `bound` once the relay accepted it, `refused`, or `none`\n\t * when nobody is signed in or no answer came in time. Rejects with an\n\t * `InvalidStateError` while not connected, and with a `TypeError` without\n\t * the hook.\n\t */\n\trefreshIdentity(): Promise<IdentityState> {\n\t\tconst session = this.#session;\n\t\tconst ask = this.#identityAssertion;\n\t\tif (ask === undefined)\n\t\t\treturn Promise.reject(new TypeError(\"TabMcp: no identityAssertion\"));\n\t\tif (session === undefined) return notConnected();\n\t\tconst round = ++this.#identityRound;\n\t\tconst connection = this.#connection;\n\t\tthis.#setIdentity(\"pending\");\n\t\t// No answer in time, from the hook or the relay (an old relay, a lost\n\t\t// message, a hook that never settles): give up.\n\t\tconst timer = setTimeout(() => {\n\t\t\tif (round !== this.#identityRound || this.#identity !== \"pending\") return;\n\t\t\tthis.#identityRound++; // a late answer is dropped\n\t\t\tthis.#setIdentity(\"none\");\n\t\t}, timing.answerTimeoutMs);\n\t\treturn new Promise<IdentityState>((resolve) => {\n\t\t\tconst settle = (event: TabMcpEventMap[\"identitychange\"]) => {\n\t\t\t\tconst { identity } = event.detail;\n\t\t\t\tif (identity === \"pending\") return;\n\t\t\t\tthis.removeEventListener(\"identitychange\", settle);\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(identity);\n\t\t\t};\n\t\t\tthis.addEventListener(\"identitychange\", settle);\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() =>\n\t\t\t\t\task({ address: session.address, sessionId: session.sessionId }),\n\t\t\t\t)\n\t\t\t\t.then(\n\t\t\t\t\t(assertion) => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tround !== this.#identityRound ||\n\t\t\t\t\t\t\tthis.#connection !== connection\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t// Superseded (a newer request, a sign-out, a new connection): that one settles the state.\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof assertion !== \"string\" || assertion === \"\") {\n\t\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tconnection?.send({ type: \"identity\", assertion, round }) !== true\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tif (round !== this.#identityRound) return;\n\t\t\t\t\t\tthis.#emit(\"error\", {\n\t\t\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * The page's user signed out: the relay ends every AI connection of this\n\t * address at once (identity binding). Call it from the web app's logout.\n\t * `identity` goes to `none` at once. Resolves once the relay removed the\n\t * grants; rejects with an `InvalidStateError` while not connected to a\n\t * relay that pairs by sign-in (`session.pairing` is `oidc`), and with a\n\t * `NetworkError` when the session ends first. Grants that stay work only while a page signed in\n\t * as the same person is open.\n\t */\n\tsignOut(): Promise<void> {\n\t\tthis.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\treturn this.#session?.pairing === \"oidc\"\n\t\t\t? this.#ask({ type: \"identity.logout\" }, () => !this.#grants.length)\n\t\t\t: notConnected();\n\t}\n\n\t/** The pairing code to show, if the relay sent one. */\n\tget pairingCode(): PairingCode | undefined {\n\t\treturn this.#pairingCode;\n\t}\n\n\t/**\n\t * Identity binding: until when a sign-in pairs this page (ISO time, on\n\t * the page's clock: the relay's duration counted from its answer to the\n\t * last `startPairing()`, DEC-202). A reconnect the library makes by\n\t * itself does not start it anew: it is the time of the reconnect then.\n\t * `undefined` while pairing is off, until the relay answers, after the\n\t * session ended, and from relays up to 0.12.1, which do not say.\n\t */\n\tget pairingUntil(): string | undefined {\n\t\treturn this.#pairingUntil;\n\t}\n\n\t/**\n\t * Connect to the relay: loads the connection and MCP handler, opens the\n\t * WebSocket, resolves with the session. Call it from a user action (a\n\t * click): where browsers track user activation it is refused otherwise,\n\t * unless `options.resume` says the user already chose to keep AI access on.\n\t * While `reconnecting`, it makes the next attempt at once.\n\t */\n\tconnect(options: ConnectOptions = {}): Promise<SessionInfo> {\n\t\tif (this.#relayUrl === undefined) return noRelay();\n\t\tif (this.#state === \"connected\" && this.#session !== undefined) {\n\t\t\treturn Promise.resolve(this.#session);\n\t\t}\n\t\tif (this.#reconnecting !== undefined) {\n\t\t\tthis.#clicked ||= options.resume !== true;\n\t\t\treturn this.#attemptReconnect();\n\t\t}\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tconst activation = (\n\t\t\tglobalThis.navigator as\n\t\t\t\t| { userActivation?: { isActive: boolean } }\n\t\t\t\t| undefined\n\t\t)?.userActivation;\n\t\tif (\n\t\t\toptions.resume !== true &&\n\t\t\tactivation !== undefined &&\n\t\t\t!activation.isActive\n\t\t) {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew DOMException(\n\t\t\t\t\t\"connect() must be called from a user action, such as a click\",\n\t\t\t\t\t\"NotAllowedError\",\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\t// While `disconnectAll()` runs: afterwards, with the new secret.\n\t\treturn this.#renewing\n\t\t\t? this.#renewing.then(() => this.connect({ resume: true }))\n\t\t\t: this.#start();\n\t}\n\n\t/** Open the page's connection; a reconnect attempt stays `reconnecting`. */\n\t#start(): Promise<SessionInfo> {\n\t\tif (!this.#reconnecting) this.#setState(\"connecting\");\n\t\tconst connecting = this.#open(this.#generation);\n\t\tthis.#connecting = connecting;\n\t\tconnecting.then(\n\t\t\t() => {\n\t\t\t\tif (this.#connecting === connecting) this.#connecting = undefined;\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (this.#connecting !== connecting) return; // superseded\n\t\t\t\tthis.#connecting = undefined;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\t// A failed attempt: the next one is scheduled, or it stops.\n\t\t\t\tif (!this.#reconnecting) this.#setState(\"disconnected\");\n\t\t\t},\n\t\t);\n\t\treturn connecting;\n\t}\n\n\t/**\n\t * The lazy chunk (on `connect()` or the first WebMCP call). The validator\n\t * is loaded with it: it checks the schemas from now on (DEC-086).\n\t */\n\tasync #load(): Promise<Lazy> {\n\t\tconst lazy = await import(\"./connection.ts\");\n\t\tfor (const error of lazy.compileRegistry(this.#registry))\n\t\t\tthis.#emit(\"error\", { error });\n\t\tthis.#lazy = lazy;\n\t\treturn lazy;\n\t}\n\n\t/**\n\t * Open a connection. `takeBack`: the secret of an address to take back\n\t * (`hello.revokeAll`, DEC-095); that connection is never current, so its\n\t * session and events stay unseen, but `#end` closes it.\n\t */\n\tasync #open(generation: number, takeBack?: string): Promise<SessionInfo> {\n\t\tconst { openConnection, addressIdOf } = await this.#load();\n\t\tconst relayUrl = this.#relayUrl;\n\t\tif (relayUrl === undefined || this.#secrets === undefined) return noRelay();\n\t\tconst secret =\n\t\t\ttakeBack ?? this.#secrets.current() ?? this.#secrets.rotate();\n\t\tconst address = await addressIdOf(secret);\n\t\tif (generation !== this.#generation) {\n\t\t\tthrow new DOMException(\"The connection was cancelled\", \"AbortError\");\n\t\t}\n\t\tconst ref: { connection?: ConnectionHandle } = {};\n\t\tconst connection = openConnection(this.#host(ref), relayUrl, secret, {\n\t\t\taddress,\n\t\t\trevokeAll: !!takeBack,\n\t\t});\n\t\tif (!takeBack) ref.connection = connection;\n\t\tthis.#connection = connection;\n\t\treturn connection.ready;\n\t}\n\n\t/** Whether this `TabMcp` has a relay; without one, `connect()` rejects. */\n\tget hasRelay(): boolean {\n\t\treturn this.#relayUrl !== undefined;\n\t}\n\n\t/**\n\t * Serve the tools over a port, without a relay: for this site's own\n\t * assistant, e.g. a chat in an iframe whose backend calls the tools through\n\t * `createTunnelFetch` (`@ractive-ch/tab-mcp-client/tunnel`). The port\n\t * carries the relay's `http.*` messages as plain objects; a `MessagePort`\n\t * fits. Whoever holds the other end calls the tools without pairing, as\n\t * `options.client` (`kind: \"local\"`): hand it out only to a frame whose\n\t * origin you checked. Consequential tools still ask: `options.onConfirm`\n\t * for this port's calls (in the site's chat, say), else the page's\n\t * `onConfirm` or dialog. Each request may take `options.requestTimeoutMs`\n\t * (300 s). Only tools whose `callers` include `\"local\"` (by default all)\n\t * are listed and callable. Resolves once the port\n\t * is served; may be called for several ports. Rejects with a `TypeError`\n\t * for options it cannot use.\n\t */\n\tserve(port: TunnelPort, options: ServeOptions): Promise<ServeHandle> {\n\t\treturn this.#load().then((lazy) =>\n\t\t\tlazy.servePort(\n\t\t\t\t{\n\t\t\t\t\t...this.#calls,\n\t\t\t\t\tserver: this.#server,\n\t\t\t\t\terror: (error) => this.#emit(\"error\", { error }),\n\t\t\t\t},\n\t\t\t\tport,\n\t\t\t\toptions,\n\t\t\t),\n\t\t);\n\t}\n\n\t/** End the session (`bye`). Grants stay: AI apps work again after the next `connect()`. */\n\tdisconnect(): void {\n\t\tthis.#end(\"user\");\n\t}\n\n\t/**\n\t * Disconnect every AI app and start over with a new secret. The address\n\t * people add to an AI app names the app and stays the same (DEC-196);\n\t * what changes is the page behind it, so every AI app has to pair again.\n\t * If the page has a secret already, it first takes it back: it\n\t * connects with the old secret and the relay revokes every grant of it in\n\t * the same step (`hello.revokeAll`, DEC-095, DEC-136), connected or not,\n\t * taken over or not. Then it makes a new secret and connects with it if\n\t * the page was connected, connecting or reconnecting, and resolves once\n\t * that is done (the new session is `session`). Rejects, and keeps the old\n\t * secret so that a retry takes it back again, when the old secret could\n\t * not be taken back (relay unreachable, taken over again first). With a\n\t * relay, every rejection has `secretChanged`: `false` then, `true` when\n\t * only connecting with the new secret failed (without one: a\n\t * `TypeError`). Call it from a user action.\n\t */\n\tdisconnectAll(): Promise<void> {\n\t\t// Without a relay there is no secret store.\n\t\tconst secrets = this.#secrets;\n\t\tif (!secrets) return noRelay();\n\t\t// biome-ignore lint/suspicious/noAssignInExpressions: one promise per run\n\t\treturn (this.#renewing ??= this.#renew(secrets).finally(() => {\n\t\t\tthis.#renewing = undefined;\n\t\t}));\n\t}\n\n\tasync #renew(secrets: SecretStore): Promise<void> {\n\t\tconst wasOn = this.#state !== \"disconnected\" || this.#stayOn;\n\t\t// Read now, also when the page is off or was taken over (CC 4). Another\n\t\t// tab that rotated the secret since took the address it had back itself.\n\t\tconst old = secrets.current();\n\t\tthis.#end(\"disconnect_all\");\n\t\tconst generation = this.#generation;\n\t\tif (old) {\n\t\t\tthis.#setState(\"connecting\");\n\t\t\ttry {\n\t\t\t\tawait this.#open(generation, old);\n\t\t\t} catch (error) {\n\t\t\t\tif (generation === this.#generation) {\n\t\t\t\t\tthis.#setState(\"disconnected\");\n\t\t\t\t\tthis.#stayOn = wasOn; // a retry does the same\n\t\t\t\t}\n\t\t\t\tthrow changed(error, false);\n\t\t\t} finally {\n\t\t\t\t// The take-back connection, unless `#end` closed it already.\n\t\t\t\tif (generation === this.#generation) {\n\t\t\t\t\tthis.#connection?.close(\"disconnect_all\");\n\t\t\t\t\tthis.#connection = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsecrets.rotate();\n\t\t// The relay revoked them (CC 14).\n\t\tthis.#setGrants([]);\n\t\t// It was on: the user chose that already, as for a reconnect.\n\t\tif (wasOn)\n\t\t\tawait this.#start().catch((error: unknown) => {\n\t\t\t\tthrow changed(error, true);\n\t\t\t});\n\t\telse this.#setState(\"disconnected\");\n\t}\n\n\t/** Close the connection (or cancel connecting) and report it at once. */\n\t#end(reason: DisconnectReason): void {\n\t\tthis.#stopReconnecting();\n\t\tthis.#stayOn = false;\n\t\tthis.#generation++;\n\t\tconst connection = this.#connection;\n\t\tthis.#connection = undefined;\n\t\tthis.#connecting = undefined;\n\t\tconnection?.close(reason); // its callbacks are stale from here on\n\t\tif (this.#state === \"disconnected\") return;\n\t\tthis.#session = undefined;\n\t\tthis.#clearPairing();\n\t\tthis.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\t// With the reason also when it ended connecting or reconnecting: the\n\t\t// page turned it off (or disconnected all apps) all the same.\n\t\tthis.#setState(\"disconnected\", reason);\n\t}\n\n\t/**\n\t * Wait, then connect again (attempt `attempt`, from 1); `state` is\n\t * `reconnecting`, and `statechange` says so for each attempt.\n\t */\n\t#scheduleReconnect(reason: DisconnectReason, attempt: number): void {\n\t\tconst delays = timing.reconnectDelaysMs;\n\t\t// Up to 20 % either way, so that the tabs a relay restart disconnected\n\t\t// do not all come back at the same moment (CC 11).\n\t\tconst delay =\n\t\t\t(delays[Math.min(attempt, delays.length) - 1] ?? 0) *\n\t\t\t(0.8 + 0.4 * Math.random());\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = setTimeout(() => {\n\t\t\tthis.#attemptReconnect().catch(() => {}); // the next one is scheduled\n\t\t}, delay);\n\t\tthis.#watch();\n\t\tthis.#reconnecting = { reason, attempt, at: Date.now() + delay };\n\t\tthis.#setState(\"reconnecting\", attempt > 1 ? undefined : reason);\n\t}\n\n\t/** Make the next reconnect attempt now; on failure, schedule the one after. */\n\t#attemptReconnect(): Promise<SessionInfo> {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tconst attempt = this.#start();\n\t\tattempt.catch((error: unknown) => {\n\t\t\t// Read now, not when the attempt started: a listener before this may\n\t\t\t// have ended it all or started the next attempt, which then owns the\n\t\t\t// next step (CC 10).\n\t\t\tconst info = this.#reconnecting;\n\t\t\tif (info === undefined || this.#connecting !== undefined) return;\n\t\t\t// Only what may get better: an unreachable relay (network), a\n\t\t\t// heartbeat or a shutdown; a refusal stops it (DEC-082).\n\t\t\tconst reason = (error as { reason?: DisconnectReason } | null)?.reason;\n\t\t\tif (reason === undefined || RECONNECT_REASONS.has(reason)) {\n\t\t\t\tthis.#scheduleReconnect(info.reason, info.attempt + 1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A refusal stops it, and `error` says why, before `statechange`.\n\t\t\t// The state is `disconnected` already, so that a `connect()` from\n\t\t\t// the listener starts afresh (with the user-activation check).\n\t\t\tthis.#stopReconnecting();\n\t\t\tthis.#state = \"disconnected\";\n\t\t\tthis.#emit(\"error\", {\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t});\n\t\t\tif (this.#state === \"disconnected\")\n\t\t\t\tthis.#emit(\"statechange\", { state: \"disconnected\" });\n\t\t});\n\t\treturn attempt;\n\t}\n\n\t/**\n\t * Back to the front, or online again: try at once instead of waiting. The\n\t * listeners are in the lazy chunk, loaded by the connection that broke\n\t * (if loading it failed, the timer still tries).\n\t */\n\t#watch(): void {\n\t\tthis.#unwatch ??= this.#lazy?.onWake(() => {\n\t\t\t// Only while waiting: an attempt that is running is not doubled.\n\t\t\tif (this.#reconnectTimer !== undefined)\n\t\t\t\tthis.#attemptReconnect().catch(() => {});\n\t\t});\n\t}\n\n\t/** Stop reconnecting; the caller sets the state that follows. */\n\t#stopReconnecting(): void {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tthis.#unwatch?.();\n\t\tthis.#unwatch = undefined;\n\t\tthis.#reconnecting = undefined;\n\t}\n\n\t/**\n\t * The pairing dialog opened: ask the relay for codes (DEC-028). With\n\t * identity binding each call while connected starts the relay's ten\n\t * minutes for a sign-in anew (`pairingUntil`, DEC-202): call it only\n\t * when the user acts (opens the dialog, continues after the time is up).\n\t */\n\tstartPairing(): void {\n\t\tthis.#pairing = true;\n\t\t// Owed to the relay until sent: also a reconnect sends it then.\n\t\tthis.#asked = false;\n\t\tif (this.#state === \"connected\") this.#askPairing();\n\t}\n\n\t/** Send `pairing.start`; `pairingUntil` waits for the relay's answer. */\n\t#askPairing(): void {\n\t\tthis.#setPairingUntil(undefined);\n\t\tthis.#asked = this.#session?.pairing === \"oidc\";\n\t\tthis.#connection?.send({ type: \"pairing.start\" });\n\t}\n\n\t/** The pairing dialog closed: the code becomes invalid. */\n\tstopPairing(): void {\n\t\tif (!this.#pairing) return;\n\t\tthis.#pairing = false;\n\t\tif (this.#state === \"connected\")\n\t\t\tthis.#connection?.send({ type: \"pairing.stop\" });\n\t\tthis.#clearPairing();\n\t}\n\n\t/** No code, no time for a sign-in: pairing is off or the session ended. */\n\t#clearPairing(): void {\n\t\tthis.#setPairingCode(undefined);\n\t\tthis.#setPairingUntil(undefined);\n\t}\n\n\t/**\n\t * Disconnect one AI app: its tokens stop working at once. Resolves once\n\t * the relay removed the grant (at once for one that is not in `grants`,\n\t * and when the relay no longer knows it: it leaves `grants` then).\n\t * Rejects with an `InvalidStateError` while not connected (only the relay\n\t * can do it), a `NetworkError` when the session ends before the answer,\n\t * and with the relay's error when it refuses (its `code` is\n\t * `store_unavailable` when it could not save the change: try again).\n\t */\n\trevoke(grantId: string): Promise<void> {\n\t\tconst gone = () => !this.#grants.some((g) => g.grantId === grantId);\n\t\treturn gone()\n\t\t\t? Promise.resolve()\n\t\t\t: this.#ask({ type: \"grant.revoke\", grantId }, gone);\n\t}\n\n\t/**\n\t * Send `message` to the relay and resolve once `done()` holds (it is\n\t * checked on each change of the grants). Rejects with an\n\t * `InvalidStateError` when it cannot send, a `NetworkError` when the\n\t * session ends first, the relay's refusal of this message\n\t * (`store_unavailable`: it could not save the change; `unknown_id`), and a\n\t * `TimeoutError` when none of that happened within\n\t * `timing.answerTimeoutMs`.\n\t */\n\t#ask(\n\t\tmessage: TabMessage & { grantId?: string },\n\t\tdone: () => boolean,\n\t): Promise<void> {\n\t\t// With a session, the lazy chunk is loaded: the waiting is there.\n\t\treturn !this.#session || this.#connection?.send(message) !== true\n\t\t\t? notConnected()\n\t\t\t: (this.#lazy as Lazy).answer(\n\t\t\t\t\tthis,\n\t\t\t\t\tmessage,\n\t\t\t\t\tdone,\n\t\t\t\t\t() => this.#state === \"connected\",\n\t\t\t\t\ttiming.answerTimeoutMs,\n\t\t\t\t);\n\t}\n\n\t/**\n\t * Open the default \"Connect your AI app\" dialog; connects first if needed\n\t * (call it from a click). Resolves when the dialog closes. One dialog at\n\t * a time (they would share one pairing): while it is open, a call for the\n\t * same document opens no second one and resolves with it, and a call for\n\t * another document rejects with an `InvalidStateError`. Pages with their\n\t * own UI use the events and methods instead.\n\t */\n\tshowConnectDialog(options: { document?: Document } = {}): Promise<void> {\n\t\tif (this.#relayUrl === undefined) return noRelay();\n\t\tconst doc = options.document ?? globalThis.document;\n\t\tconst open = this.#connectDialog;\n\t\tif (open !== undefined) {\n\t\t\treturn open.doc === doc\n\t\t\t\t? open.shown\n\t\t\t\t: Promise.reject(\n\t\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\t\"showConnectDialog: the dialog is already open in another document\",\n\t\t\t\t\t\t\t\"InvalidStateError\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t}\n\t\tconst shown = this.#showConnectDialog(doc).finally(() => {\n\t\t\tif (this.#connectDialog?.shown === shown) this.#connectDialog = undefined;\n\t\t});\n\t\tthis.#connectDialog = { doc, shown };\n\t\treturn shown;\n\t}\n\n\tasync #showConnectDialog(doc: Document): Promise<void> {\n\t\tconst connecting = this.connect();\n\t\tconnecting.catch(() => {}); // the dialog shows the error\n\t\tconst { showConnectDialog } = await import(\"./connect.ts\");\n\t\tawait showConnectDialog(this, connecting, doc, this.#server.name, this.#ui);\n\t}\n\n\toverride addEventListener<K extends keyof TabMcpEventMap>(\n\t\ttype: K,\n\t\tlistener: Listener<K> | null,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\toverride addEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\toverride addEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void {\n\t\tsuper.addEventListener(type, listener, options);\n\t}\n\n\toverride removeEventListener<K extends keyof TabMcpEventMap>(\n\t\ttype: K,\n\t\tlistener: Listener<K> | null,\n\t\toptions?: boolean | EventListenerOptions,\n\t): void;\n\toverride removeEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | EventListenerOptions,\n\t): void;\n\toverride removeEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | EventListenerOptions,\n\t): void {\n\t\tsuper.removeEventListener(type, listener, options);\n\t}\n\n\t#emit<K extends keyof TabMcpEventMap>(\n\t\ttype: K,\n\t\tdetail: TabMcpEventMap[K][\"detail\"],\n\t): void {\n\t\tthis.dispatchEvent(new CustomEvent(type, { detail }));\n\t}\n\n\t/** A new state; `reconnecting` again means the next attempt was scheduled. */\n\t#setState(state: ConnectionState, reason?: DisconnectReason): void {\n\t\tif (this.#state === state && state !== \"reconnecting\") return;\n\t\tthis.#state = state;\n\t\tthis.#emit(\"statechange\", reason ? { state, reason } : { state });\n\t}\n\n\t#setIdentity(identity: IdentityState, message?: string): void {\n\t\tif (this.#identity === identity && message === undefined) return;\n\t\tthis.#identity = identity;\n\t\tthis.#identityMessage = identity === \"refused\" ? message : undefined;\n\t\tthis.#emit(\"identitychange\", {\n\t\t\tidentity,\n\t\t\tidentityMessage: this.#identityMessage,\n\t\t});\n\t}\n\n\t#setPairingCode(pairingCode: PairingCode | undefined): void {\n\t\tif (this.#pairingCode === undefined && pairingCode === undefined) return;\n\t\tthis.#pairingCode = pairingCode;\n\t\tthis.#emit(\"pairingcode\", { pairingCode });\n\t}\n\n\t#setPairingUntil(pairingUntil: string | undefined): void {\n\t\tif (this.#pairingUntil === pairingUntil) return;\n\t\tthis.#pairingUntil = pairingUntil;\n\t\tthis.#emit(\"pairinguntil\", { pairingUntil });\n\t}\n\n\t#setGrants(grants: readonly Grant[]): void {\n\t\tthis.#grants = Object.freeze(grants.map(frozenGrant));\n\t\tthis.#emit(\"grantschange\", { grants: this.#grants });\n\t}\n\n\t/**\n\t * A call the user allowed runs without asking, else `onConfirm` or the\n\t * dialog: decided out of the core, in the confirmation's chunk (a chunk\n\t * of its own for the allowances would cost the core more bytes, DEC-200).\n\t * If that chunk does not load, the page's own `onConfirm` asks (only its\n\t * `true` runs the call); without one the call is refused, never allowed.\n\t */\n\t#confirm(request: ConfirmRequest): Promise<ConfirmAnswer> {\n\t\tconst ask = this.#onConfirm;\n\t\treturn import(\"./confirm.ts\").then(\n\t\t\t(m) => m.confirmCall(this, request, ask),\n\t\t\t() => ask?.(request) ?? false,\n\t\t);\n\t}\n\n\t/**\n\t * For `./allowed` and the dialogs, not for pages: the tools, where the\n\t * secret is kept, and `alwaysAllow`.\n\t * @internal\n\t */\n\tget _allowed(): [\n\t\tToolRegistry,\n\t\tSecretStore | undefined,\n\t\tTabMcpOptions[\"alwaysAllow\"],\n\t] {\n\t\treturn [this.#registry, this.#secrets, this.#alwaysAllow];\n\t}\n\n\t/**\n\t * For `./react`, not for pages: the dialogs' options, whose `strings`\n\t * `ConnectButton` reads too (one table for every text, given once).\n\t * @internal\n\t */\n\tget _ui(): DialogOptions | undefined {\n\t\treturn this.#ui;\n\t}\n\n\t/**\n\t * The library's own confirmation: the dialog in the page with Don't allow\n\t * and Allow, and Always allow with `alwaysAllow` (what runs without\n\t * `onConfirm`), in `options.document` (default: the global one). An\n\t * `onConfirm` may hand some calls to it. A call the user allowed for its\n\t * AI app resolves `true` unasked. Resolves `false` where there is no\n\t * document.\n\t */\n\tconfirmInPage(\n\t\trequest: ConfirmRequest,\n\t\toptions: { document?: Document } = {},\n\t): Promise<boolean> {\n\t\tconst doc = options.document ?? globalThis.document;\n\t\tif (doc === undefined) return Promise.resolve(false); // nobody to ask: decline\n\t\treturn import(\"./confirm.ts\").then((ui) =>\n\t\t\tui.confirmInPage(this, request, doc, { ui: this.#ui }),\n\t\t);\n\t}\n\n\t/** The callbacks of one connection; once it is not current they are ignored. */\n\t#host(ref: { connection?: ConnectionHandle }): ConnectionHost {\n\t\tconst current = () =>\n\t\t\tref.connection !== undefined && this.#connection === ref.connection;\n\t\tlet replacedHere = false;\n\t\treturn {\n\t\t\t...this.#calls,\n\t\t\tserver: this.#server,\n\t\t\tapp: this.#app,\n\t\t\tappName: this.#appName,\n\t\t\ttabs: this.#tabs,\n\t\t\tlibrary: { name: LIBRARY_NAME, version: VERSION },\n\t\t\tclientFor: (grant: GrantRef): ToolCallClient => {\n\t\t\t\tconst known = this.#grants.find((g) => g.grantId === grant.grantId);\n\t\t\t\tconst client: RelayClient = {\n\t\t\t\t\tkind: \"relay\",\n\t\t\t\t\tgrantId: grant.grantId,\n\t\t\t\t\tid: grant.clientId,\n\t\t\t\t\thost: hostOf(grant.clientId),\n\t\t\t\t};\n\t\t\t\tif (known !== undefined) client.name = known.client.name;\n\t\t\t\treturn client;\n\t\t\t},\n\t\t\tsessionStarted: (m) => {\n\t\t\t\tconst session = sessionInfo(m);\n\t\t\t\tif (!current()) return session;\n\t\t\t\tthis.#session = session;\n\t\t\t\tthis.#stayOn = false;\n\t\t\t\t// A reconnect the library made by itself does not start a\n\t\t\t\t// sign-in's time anew once the user's start was sent, answered\n\t\t\t\t// or not: only the user does (DEC-202). Codes come again.\n\t\t\t\tconst ended =\n\t\t\t\t\tthis.#pairing &&\n\t\t\t\t\tthis.#reconnecting &&\n\t\t\t\t\t!this.#clicked &&\n\t\t\t\t\tthis.#asked &&\n\t\t\t\t\tsession.pairing === \"oidc\";\n\t\t\t\tthis.#clicked = false;\n\t\t\t\tthis.#stopReconnecting();\n\t\t\t\tthis.#setGrants([...m.grants]);\n\t\t\t\tif (ended) this.#setPairingUntil(new Date().toISOString());\n\t\t\t\telse if (this.#pairing) this.#askPairing();\n\t\t\t\tthis.#setState(\"connected\");\n\t\t\t\tif (session.pairing === \"oidc\" && this.#identityAssertion)\n\t\t\t\t\tvoid this.refreshIdentity();\n\t\t\t\treturn session;\n\t\t\t},\n\t\t\tpairingCode: (code) => {\n\t\t\t\tif (current() && this.#pairing) this.#setPairingCode(code);\n\t\t\t},\n\t\t\tpairingOpen: (until) => {\n\t\t\t\tif (current() && this.#pairing) this.#setPairingUntil(until);\n\t\t\t},\n\t\t\tgrantAdded: (grant) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tthis.#setGrants([\n\t\t\t\t\t...this.#grants.filter((g) => g.grantId !== grant.grantId),\n\t\t\t\t\tgrant,\n\t\t\t\t]);\n\t\t\t},\n\t\t\tgrantRemoved: (grantId) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tthis.#setGrants(this.#grants.filter((g) => g.grantId !== grantId));\n\t\t\t},\n\t\t\t// After `closed`, so no longer current: only a connection that was\n\t\t\t// current when it was replaced reports it.\n\t\t\treplaced: (detail) => {\n\t\t\t\tif (replacedHere) this.#emit(\"replaced\", detail);\n\t\t\t},\n\t\t\tidentityResult: (bound, round, message) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\t// Only the answer to the newest assertion counts: the relay echoes\n\t\t\t\t// its round, so a lost or late answer cannot pass for a newer one.\n\t\t\t\tif (round !== this.#identityRound) return;\n\t\t\t\tif (bound) this.#setIdentity(\"bound\");\n\t\t\t\telse this.#setIdentity(\"refused\", message ?? \"\");\n\t\t\t},\n\t\t\terror: (error) => {\n\t\t\t\tif (current()) this.#emit(\"error\", { error });\n\t\t\t},\n\t\t\tclosed: (reason: DisconnectReason) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tif (reason === \"replaced\") this.#stayOn = replacedHere = true;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\tthis.#session = undefined;\n\t\t\t\t// Any listener of these may end it all (`disconnect()`,\n\t\t\t\t// `disconnectAll()`): that bumps the generation.\n\t\t\t\tconst generation = this.#generation;\n\t\t\t\tthis.#clearPairing();\n\t\t\t\tthis.#identityRound++;\n\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\tif (generation !== this.#generation) return;\n\t\t\t\t// Reconnecting is decided before the page hears of it, so its\n\t\t\t\t// listener sees `reconnecting` (or calls `connect()`, which then\n\t\t\t\t// makes the first attempt at once).\n\t\t\t\tif (this.#reconnect && RECONNECT_REASONS.has(reason))\n\t\t\t\t\tthis.#scheduleReconnect(reason, 1);\n\t\t\t\telse this.#setState(\"disconnected\", reason);\n\t\t\t},\n\t\t};\n\t}\n}\n"
|
|
9
9
|
],
|
|
10
10
|
"mappings": ";AAaA,IAAM,EAAO,0BAoBb,SAAS,CAAa,CAAC,EAA0C,CAChE,OAAO,OAAO,IAAM,UAAY,IAAM,MAAQ,CAAC,MAAM,QAAQ,CAAC,EAI/D,IAAM,EAAO,kCAEP,EACL,uEAQD,SAAS,CAAU,CAClB,EACA,EACA,EAAQ,EACR,EAAM,GACC,CACP,GAAI,EAAQ,IAAM,OAAO,IAAS,UAAY,IAAS,KAAM,OAE7D,GADA,IAAQ,MAAM,QAAQ,CAAI,EACtB,CAAC,EAAK,EAAM,CAA+B,EAC/C,QAAY,EAAK,KAAU,OAAO,QAAQ,CAAI,EAC7C,GAAI,GAAO,CAAC,EAAK,KAAK,CAAG,EACxB,EAAW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=
|
|
|
225
225
|
"busy"
|
|
226
226
|
/** Allow, but no code came from the relay (`code` gave none). */
|
|
227
227
|
| "no-code";
|
|
228
|
+
/** The page a fill is for: its tab and the AI app that asks there. */
|
|
229
|
+
export interface FillContext {
|
|
230
|
+
tabId: number;
|
|
231
|
+
/** The AI app's own name (may be `""`) and the host the relay verified, as `ask` gets them. */
|
|
232
|
+
client: {
|
|
233
|
+
name: string;
|
|
234
|
+
host: string;
|
|
235
|
+
};
|
|
236
|
+
}
|
|
228
237
|
/** What `CodeFiller` needs from the extension: its parts of the fill-in. */
|
|
229
238
|
export interface FillHost {
|
|
230
239
|
/** This extension's id (`chrome.runtime.id`): only its own content script speaks. */
|
|
@@ -254,16 +263,22 @@ export interface FillHost {
|
|
|
254
263
|
host: string;
|
|
255
264
|
}, signal: AbortSignal): Promise<FillAnswer>;
|
|
256
265
|
/**
|
|
257
|
-
* The code to fill in now
|
|
258
|
-
* (`takeCode`); `undefined` if none came or
|
|
259
|
-
* went, or the fill was withdrawn as a
|
|
260
|
-
* nothing is sent if what holds for
|
|
266
|
+
* The code to fill in now on the page `context`, with pairing held on for
|
|
267
|
+
* the relay to check it (`takeCode`); `undefined` if none came or
|
|
268
|
+
* `signal` aborted (the page went, or the fill was withdrawn as a
|
|
269
|
+
* question is). Even with a code, nothing is sent if what holds for
|
|
270
|
+
* asking no longer does.
|
|
271
|
+
*/
|
|
272
|
+
code(signal: AbortSignal, context: FillContext): Promise<string | undefined>;
|
|
273
|
+
/**
|
|
274
|
+
* No fill needs pairing held on any more: a filled-in code paired its AI
|
|
275
|
+
* app, or a fill ended without sending its code (withdrawn, the page
|
|
276
|
+
* went, no code) while no other fill is under way or waits for the
|
|
277
|
+
* relay's check. It may come again with nothing held: ignore it then.
|
|
261
278
|
*/
|
|
262
|
-
code(signal: AbortSignal): Promise<string | undefined>;
|
|
263
|
-
/** A filled-in code paired its AI app: pairing need not be held for it. */
|
|
264
279
|
release(): void;
|
|
265
|
-
/**
|
|
266
|
-
failed(why: FillFailure): void;
|
|
280
|
+
/** The page `context` filled in nothing for `why`, or was not asked about: say so. */
|
|
281
|
+
failed(why: FillFailure, context: FillContext): void;
|
|
267
282
|
/** The clock (`Date.now`; a test's own). */
|
|
268
283
|
now(): number;
|
|
269
284
|
}
|
|
@@ -280,9 +295,10 @@ export interface FillHost {
|
|
|
280
295
|
* relay's `request_id`) again soon after a fill, it is the relay's answer
|
|
281
296
|
* that the code was not taken (it had just changed): filled once more with
|
|
282
297
|
* the code of then, without asking; the time after, nothing. Any other
|
|
283
|
-
* request asks.
|
|
284
|
-
*
|
|
285
|
-
*
|
|
298
|
+
* request asks. With `retry: false` that page is asked about like any
|
|
299
|
+
* other: every fill has a yes of its own. Don't allow, a timeout, the page
|
|
300
|
+
* going, AI access or the setting going off, another relay or the AI app
|
|
301
|
+
* connecting meanwhile fill nothing, and typing by hand works as before.
|
|
286
302
|
*/
|
|
287
303
|
export declare class CodeFiller {
|
|
288
304
|
#private;
|
|
@@ -290,10 +306,15 @@ export declare class CodeFiller {
|
|
|
290
306
|
* `grants`: the ids of the grants there are already, if the extension kept
|
|
291
307
|
* them between worker starts (not new when listed again); without them,
|
|
292
308
|
* the first `grantsChanged` is taken as the list there is, nothing in it
|
|
293
|
-
* new. `
|
|
309
|
+
* new. `retry`: the one more fill without asking when the same request's
|
|
310
|
+
* page comes back to the same tab soon after a fill (on unless `false`;
|
|
311
|
+
* off, that page is asked about like any other, one question per page
|
|
312
|
+
* load, and never filled without a yes). `closeAfterMs`: FILLED_CLOSE_MS
|
|
313
|
+
* unless a test's is shorter.
|
|
294
314
|
*/
|
|
295
315
|
constructor(host: FillHost, options?: {
|
|
296
316
|
grants?: Iterable<string>;
|
|
317
|
+
retry?: boolean;
|
|
297
318
|
closeAfterMs?: number;
|
|
298
319
|
});
|
|
299
320
|
/**
|
|
@@ -333,12 +354,17 @@ export declare function pairingCodes(mcp: Pick<TabMcp, "pairingCode" | "addEvent
|
|
|
333
354
|
/**
|
|
334
355
|
* The code to fill in. The current one if it has `minLeftMs` left by this
|
|
335
356
|
* clock (or an expiry that cannot be read); else the next one the relay
|
|
336
|
-
* sends, which is fresh whatever the clocks say.
|
|
337
|
-
*
|
|
338
|
-
*
|
|
339
|
-
*
|
|
340
|
-
*
|
|
341
|
-
*
|
|
357
|
+
* sends, which is fresh whatever the clocks say. The same code sent again
|
|
358
|
+
* is not the next one: the relay answers each `pairing.start` with the code
|
|
359
|
+
* it shows, so `startPairing()` with pairing on already brings back the
|
|
360
|
+
* code that is about to change; it counts only if its expiry now leaves
|
|
361
|
+
* `minLeftMs`. If no next one comes within `waitMs`, the current one after
|
|
362
|
+
* all: with this clock ahead every code would look expired, so the fill
|
|
363
|
+
* then waits the whole `waitMs` before it gets that code. The relay
|
|
364
|
+
* refuses a code that has expired; the one more fill for the same request
|
|
365
|
+
* covers that, or with `retry: false` a new question. `undefined` only
|
|
366
|
+
* without any code, or when `signal` aborts. Pairing must be on
|
|
367
|
+
* (`startPairing()`) for codes to come.
|
|
342
368
|
*/
|
|
343
369
|
export declare function takeCode(source: CodeSource, signal: AbortSignal, options: {
|
|
344
370
|
now: number;
|
package/extension.js
CHANGED
|
@@ -89,7 +89,7 @@ function helloFor(found, nonce) {
|
|
|
89
89
|
}
|
|
90
90
|
function runPairingPage(options) {
|
|
91
91
|
const flag = "__tabMcpPairingPage";
|
|
92
|
-
const scope = globalThis;
|
|
92
|
+
const scope = options.page?.document ?? globalThis;
|
|
93
93
|
if (scope[flag] === true)
|
|
94
94
|
return false;
|
|
95
95
|
scope[flag] = true;
|
|
@@ -190,9 +190,11 @@ class CodeFiller {
|
|
|
190
190
|
#filled = new Map;
|
|
191
191
|
#grants;
|
|
192
192
|
#closeAfterMs;
|
|
193
|
+
#retry;
|
|
193
194
|
constructor(host, options = {}) {
|
|
194
195
|
this.#host = host;
|
|
195
196
|
this.#grants = options.grants === undefined ? undefined : new Set(options.grants);
|
|
197
|
+
this.#retry = options.retry ?? true;
|
|
196
198
|
this.#closeAfterMs = options.closeAfterMs ?? FILLED_CLOSE_MS;
|
|
197
199
|
}
|
|
198
200
|
async page(port) {
|
|
@@ -211,14 +213,18 @@ class CodeFiller {
|
|
|
211
213
|
return;
|
|
212
214
|
}
|
|
213
215
|
const hello = parseHello(await within(port.hello, HELLO_WAIT_MS));
|
|
214
|
-
if (hello === undefined || hello.app !== host.app || port.signal.aborted || !host.enabled() || !host.aiOn()) {
|
|
216
|
+
if (hello === undefined || hello.app !== host.app || port.signal.aborted || !host.enabled() || !host.aiOn() || !isPairingSender(port.sender, host.extensionId, host.relayOrigin())) {
|
|
215
217
|
port.close();
|
|
216
218
|
return;
|
|
217
219
|
}
|
|
220
|
+
const context = {
|
|
221
|
+
tabId,
|
|
222
|
+
client: { name: hello.clientName, host: hello.clientHost }
|
|
223
|
+
};
|
|
218
224
|
const before = this.#lastFill(tabId);
|
|
219
|
-
if (before?.requestId === hello.requestId) {
|
|
225
|
+
if (this.#retry && before?.requestId === hello.requestId) {
|
|
220
226
|
if (before.count === 1)
|
|
221
|
-
await this.#fill(port,
|
|
227
|
+
await this.#fill(port, context, hello, 2);
|
|
222
228
|
else
|
|
223
229
|
port.close();
|
|
224
230
|
return;
|
|
@@ -231,27 +237,35 @@ class CodeFiller {
|
|
|
231
237
|
const signal = AbortSignal.any([port.signal, waiting.withdraw.signal]);
|
|
232
238
|
let answer;
|
|
233
239
|
try {
|
|
234
|
-
answer = await host.ask(tabId, {
|
|
240
|
+
answer = await host.ask(tabId, { ...context.client }, signal);
|
|
235
241
|
} finally {
|
|
236
242
|
this.#waiting.delete(waiting);
|
|
237
243
|
}
|
|
238
244
|
if (answer === "busy")
|
|
239
|
-
host.failed("busy");
|
|
240
|
-
if (answer !== "allow" || signal.aborted || !host.enabled() || !host.aiOn()) {
|
|
245
|
+
host.failed("busy", context);
|
|
246
|
+
if (answer !== "allow" || signal.aborted || !host.enabled() || !host.aiOn() || !isPairingSender(port.sender, host.extensionId, host.relayOrigin())) {
|
|
241
247
|
port.close();
|
|
242
248
|
return;
|
|
243
249
|
}
|
|
244
|
-
await this.#fill(port,
|
|
250
|
+
await this.#fill(port, context, hello, 1);
|
|
251
|
+
}
|
|
252
|
+
#anyFill() {
|
|
253
|
+
this.#dropStale();
|
|
254
|
+
return this.#filled.size > 0;
|
|
245
255
|
}
|
|
246
256
|
#lastFill(tabId) {
|
|
257
|
+
this.#dropStale();
|
|
258
|
+
return this.#filled.get(tabId);
|
|
259
|
+
}
|
|
260
|
+
#dropStale() {
|
|
247
261
|
const now = this.#host.now();
|
|
248
262
|
for (const [id, filled] of this.#filled)
|
|
249
263
|
if (now - filled.at > RETRY_WINDOW_MS)
|
|
250
264
|
this.#filled.delete(id);
|
|
251
|
-
return this.#filled.get(tabId);
|
|
252
265
|
}
|
|
253
|
-
async#fill(port,
|
|
266
|
+
async#fill(port, context, hello, count) {
|
|
254
267
|
const host = this.#host;
|
|
268
|
+
const { tabId } = context;
|
|
255
269
|
const before = this.#filled.get(tabId);
|
|
256
270
|
const mark = {
|
|
257
271
|
requestId: hello.requestId,
|
|
@@ -269,14 +283,17 @@ class CodeFiller {
|
|
|
269
283
|
let sent = false;
|
|
270
284
|
let keepBefore = true;
|
|
271
285
|
try {
|
|
272
|
-
const code = await host.code(signal
|
|
286
|
+
const code = await host.code(signal, {
|
|
287
|
+
tabId,
|
|
288
|
+
client: { ...context.client }
|
|
289
|
+
});
|
|
273
290
|
const off = waiting.withdraw.signal.aborted || !host.enabled() || !host.aiOn() || !isPairingSender(port.sender, host.extensionId, host.relayOrigin());
|
|
274
291
|
if (off)
|
|
275
292
|
keepBefore = false;
|
|
276
293
|
if (off || port.signal.aborted)
|
|
277
294
|
return;
|
|
278
295
|
if (code === undefined) {
|
|
279
|
-
host.failed("no-code");
|
|
296
|
+
host.failed("no-code", { tabId, client: { ...context.client } });
|
|
280
297
|
return;
|
|
281
298
|
}
|
|
282
299
|
mark.at = host.now();
|
|
@@ -293,6 +310,8 @@ class CodeFiller {
|
|
|
293
310
|
else
|
|
294
311
|
this.#filled.delete(tabId);
|
|
295
312
|
}
|
|
313
|
+
if (!this.#anyFill())
|
|
314
|
+
host.release();
|
|
296
315
|
}
|
|
297
316
|
}
|
|
298
317
|
}
|
|
@@ -318,7 +337,7 @@ class CodeFiller {
|
|
|
318
337
|
this.#filled.delete(tabId);
|
|
319
338
|
done = true;
|
|
320
339
|
}
|
|
321
|
-
if (done)
|
|
340
|
+
if (done && !this.#anyFill())
|
|
322
341
|
this.#host.release();
|
|
323
342
|
}
|
|
324
343
|
withdrawAll() {
|
|
@@ -342,8 +361,10 @@ function pairingCodes(mcp) {
|
|
|
342
361
|
}
|
|
343
362
|
function takeCode(source, signal, options) {
|
|
344
363
|
const { waitMs = CODE_WAIT_MS, minLeftMs = MIN_CODE_LEFT_MS } = options;
|
|
364
|
+
const started = Date.now();
|
|
365
|
+
const leaves = (code) => !(Date.parse(code.expiresAt) - (options.now + Date.now() - started) < minLeftMs);
|
|
345
366
|
const current = source.current();
|
|
346
|
-
if (current !== undefined &&
|
|
367
|
+
if (current !== undefined && leaves(current))
|
|
347
368
|
return Promise.resolve(current.code);
|
|
348
369
|
if (signal.aborted)
|
|
349
370
|
return Promise.resolve(undefined);
|
|
@@ -355,9 +376,9 @@ function takeCode(source, signal, options) {
|
|
|
355
376
|
resolve(code);
|
|
356
377
|
};
|
|
357
378
|
const stop = source.onChange(() => {
|
|
358
|
-
const
|
|
359
|
-
if (code !==
|
|
360
|
-
done(code);
|
|
379
|
+
const next = source.current();
|
|
380
|
+
if (next !== undefined && (next.code !== current?.code || leaves(next)))
|
|
381
|
+
done(next.code);
|
|
361
382
|
});
|
|
362
383
|
const aborted = () => done(undefined);
|
|
363
384
|
const timer = setTimeout(() => done(source.current()?.code), waitMs);
|
|
@@ -390,5 +411,5 @@ export {
|
|
|
390
411
|
takeCode
|
|
391
412
|
};
|
|
392
413
|
|
|
393
|
-
//# debugId=
|
|
414
|
+
//# debugId=61A1AFC13E8CBA8064756E2164756E21
|
|
394
415
|
//# sourceMappingURL=extension.js.map
|
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\tconst scope = globalThis as Record<string, unknown>;\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/** 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, with pairing held on for the relay to check it\n\t * (`takeCode`); `undefined` if none came or `signal` aborted (the page\n\t * went, or the fill was withdrawn as a question is). Even with a code,\n\t * nothing is sent if what holds for asking no longer does.\n\t */\n\tcode(signal: AbortSignal): Promise<string | undefined>;\n\t/** A filled-in code paired its AI app: pairing need not be held for it. */\n\trelease(): void;\n\t/** A page filled in nothing for `why`, or was not asked about: say so. */\n\tfailed(why: FillFailure): 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. Don't allow, a timeout, the page going, AI access or the\n * setting going off, another relay or the AI app connecting meanwhile fill\n * 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\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. `closeAfterMs`: FILLED_CLOSE_MS unless a test's is shorter.\n\t */\n\tconstructor(\n\t\thost: FillHost,\n\t\toptions: { grants?: Iterable<string>; closeAfterMs?: number } = {},\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.#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, and only while AI access is on: otherwise they have not asked\n\t\t// 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) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tconst before = this.#lastFill(tabId);\n\t\tif (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, tabId, 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(\n\t\t\t\ttabId,\n\t\t\t\t{ name: hello.clientName, host: hello.clientHost },\n\t\t\t\tsignal,\n\t\t\t);\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\");\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) {\n\t\t\tport.close();\n\t\t\treturn;\n\t\t}\n\t\tawait this.#fill(port, tabId, hello, 1);\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\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\treturn this.#filled.get(tabId);\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\ttabId: number,\n\t\thello: PairingHello,\n\t\tcount: number,\n\t): Promise<void> {\n\t\tconst host = this.#host;\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\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\");\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}\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\tif (done) 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. If none comes within\n * `waitMs`, the current one after all: with this clock ahead every code\n * would look expired, and the relay refuses one that is, which the one\n * more fill for the same request covers. `undefined` only without any code,\n * or when `signal` aborts. Pairing must be on (`startPairing()`) for codes\n * 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\tconst current = source.current();\n\tif (\n\t\tcurrent !== undefined &&\n\t\t!(Date.parse(current.expiresAt) - options.now < minLeftMs)\n\t)\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 code = source.current()?.code;\n\t\t\tif (code !== undefined) done(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// --- 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": ";AA6CO,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;AAAA,EACV,IACC,EAAE,YAAY,kBACd,CAAC,SAAS,EAAE,QAAQ,KACpB,CAAC,iBAAiB,KAAK,EAAE,QAAQ,KACjC,CAAC,SAAS,EAAE,MAAM,KAClB,CAAC,SAAS,EAAE,aAAa,KACzB,CAAC,SAAS,EAAE,aAAa,KACzB,EAAE,kBAAkB,MACpB,CAAC,SAAS,EAAE,YAAY,KACxB,CAAC,iBAAiB,KAAK,EAAE,YAAY,KACrC,EAAE,cAAc,SAAS,mBACzB,EAAE,cAAc,SAAS;AAAA,IAEzB;AAAA,EACD,OA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AAO,IAAI,QAAQ,CAAC,YAAY;AAAA,IAC/B,MAAM,OAAO,CAAC,SAA6B;AAAA,MAC1C,aAAa,KAAK;AAAA,MAClB,KAAK;AAAA,MACL,OAAO,oBAAoB,SAAS,OAAO;AAAA,MAC3C,QAAQ,IAAI;AAAA;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": "61A1AFC13E8CBA8064756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
package/index.js
CHANGED
|
@@ -228,7 +228,7 @@ class SecretStore {
|
|
|
228
228
|
}
|
|
229
229
|
}
|
|
230
230
|
// package.json
|
|
231
|
-
var version = "0.19.0-rc.
|
|
231
|
+
var version = "0.19.0-rc.2";
|
|
232
232
|
|
|
233
233
|
// src/version.ts
|
|
234
234
|
var LIBRARY_NAME = "@ractive-ch/tab-mcp-client";
|
|
@@ -874,5 +874,5 @@ export {
|
|
|
874
874
|
VERSION
|
|
875
875
|
};
|
|
876
876
|
|
|
877
|
-
//# debugId=
|
|
877
|
+
//# debugId=F606321EEB1E829064756E2164756E21
|
|
878
878
|
//# sourceMappingURL=index.js.map
|
package/index.js.map
CHANGED
|
@@ -8,6 +8,6 @@
|
|
|
8
8
|
"/**\n * `TabMcp`: the eagerly loaded core (DEC-035). It holds the tool registry, the\n * events, the pairing state and the address secret; `connect()` loads the\n * connection and the MCP handler with a dynamic `import()`.\n */\n\nimport type { CallHost, ConnectionHandle, ConnectionHost } from \"./internal.ts\";\nimport type { GrantRef, SessionMessage, TabMessage } from \"./protocol.ts\";\nimport { ToolRegistry } from \"./registry.ts\";\nimport { SecretStore } from \"./secret.ts\";\nimport type {\n\tBrowserExtension,\n\tConfirmAnswer,\n\tConfirmHandler,\n\tConfirmRequest,\n\tConnectionState,\n\tConnectOptions,\n\tDialogOptions,\n\tDisconnectReason,\n\tGrant,\n\tIdentityAssertionHandler,\n\tIdentityState,\n\tPairingCode,\n\tReconnectingInfo,\n\tRegisterToolOptions,\n\tRelayClient,\n\tServeHandle,\n\tServeOptions,\n\tServerInfo,\n\tSessionInfo,\n\tTabMcpEventMap,\n\tTabMcpOptions,\n\tTool,\n\tToolCallClient,\n\tTunnelPort,\n} from \"./types.ts\";\nimport { LIBRARY_NAME, VERSION } from \"./version.ts\";\nimport type { ModelContext } from \"./webmcp.ts\";\n\n/**\n * The browser's own `ModelContext` of this document, read when a `TabMcp` is\n * made, through `Document.prototype`'s getter: never an own\n * `document.modelContext` (a polyfill such as `@mcp-b/global`, or any page\n * script; DEC-115). `undefined` without native WebMCP or a document. In the\n * core; the mirror itself is a chunk of its own (DEC-171).\n */\nfunction nativeContext(): ModelContext | undefined {\n\ttry {\n\t\treturn Object.getOwnPropertyDescriptor(\n\t\t\tDocument.prototype,\n\t\t\t\"modelContext\",\n\t\t)?.get?.call(document);\n\t} catch {\n\t\treturn undefined; // no document\n\t}\n}\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/**\n * The library's waits, in milliseconds: constants for pages (CU 17), which\n * only tests change. `reconnectDelaysMs`: before each reconnect attempt,\n * the last one repeating. `answerTimeoutMs`: for an identity assertion and\n * the relay's answer to it, and for the relay's answer to `revoke()` and\n * `signOut()`.\n */\nexport const timing: {\n\treconnectDelaysMs: number[];\n\tanswerTimeoutMs: number;\n} = {\n\treconnectDelaysMs: [5_000, 10_000, 20_000, 40_000, 60_000],\n\tanswerTimeoutMs: 15_000,\n};\n/** Reasons after which the library connects again by itself. */\nconst RECONNECT_REASONS = new Set<DisconnectReason>([\n\t\"network\",\n\t\"heartbeat\",\n\t\"shutdown\",\n]);\n\n/** A grant as the page sees it: frozen, so a page cannot change what decides Always allow. */\nfunction frozenGrant(grant: Grant): Grant {\n\treturn Object.freeze({\n\t\t...grant,\n\t\tclient: Object.freeze({ ...grant.client }),\n\t});\n}\n\n/** What the relay accepts as `hello.app.name` (protocol: session). */\nfunction isAppName(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue.trim().length > 0 &&\n\t\tvalue.length <= 64 &&\n\t\t![...value].some((ch) => {\n\t\t\tconst c = ch.codePointAt(0) ?? 0;\n\t\t\treturn c < 0x20 || (c >= 0x7f && c <= 0x9f);\n\t\t})\n\t);\n}\n\n/** An app id as the relay takes it (DEC-196). */\nconst APP_ID = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;\n\n/**\n * The app id a server name gives: lower case, letters without their marks,\n * each run of anything but a-z and 0-9 as one `-`, none at either end, at\n * most 32 characters; `\"\"` when nothing is left.\n */\nexport function appIdOf(name: string): string {\n\treturn name\n\t\t.normalize(\"NFKD\")\n\t\t.replace(/\\p{M}/gu, \"\")\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\")\n\t\t.slice(0, 32)\n\t\t.replace(/-$/, \"\");\n}\n\n/** `wss://host/tab` for a relay given as `https://host`, `wss://host` or with `/tab`. */\nexport function tabUrl(relay: string): { url: string; origin: string } {\n\tlet u: URL;\n\ttry {\n\t\tu = new URL(relay);\n\t} catch {\n\t\tthrow new TypeError(`TabMcp: relay is not a URL: ${relay}`);\n\t}\n\tconst secure = u.protocol === \"https:\" || u.protocol === \"wss:\";\n\tif (!secure && u.protocol !== \"http:\" && u.protocol !== \"ws:\") {\n\t\tthrow new TypeError(\n\t\t\t`TabMcp: relay must be an https: or wss: URL: ${relay}`,\n\t\t);\n\t}\n\t// The secret travels in hello: never in clear text beyond this machine.\n\tif (!secure && !LOOPBACK.has(u.hostname)) {\n\t\tthrow new TypeError(\n\t\t\t`TabMcp: relay must use https: or wss: (http: only for localhost): ${relay}`,\n\t\t);\n\t}\n\tconst origin = `${secure ? \"https:\" : \"http:\"}//${u.host}`;\n\tconst path = u.pathname.replace(/\\/+$/, \"\");\n\tu.protocol = secure ? \"wss:\" : \"ws:\";\n\tu.pathname = path.endsWith(\"/tab\") ? path : `${path}/tab`;\n\tu.search = \"\";\n\tu.hash = \"\";\n\treturn { url: u.href, origin };\n}\n\nfunction hostOf(url: string): string {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction sessionInfo(m: SessionMessage): SessionInfo {\n\tconst info: SessionInfo = {\n\t\tsessionId: m.sessionId,\n\t\taddress: m.address,\n\t\torigin: m.origin,\n\t\tpairing: m.pairing === \"oidc\" ? \"oidc\" : \"code\",\n\t\texpiresAt: m.expiresAt,\n\t\tlimits: m.limits,\n\t};\n\tif (m.appName !== undefined) info.appName = m.appName;\n\treturn info;\n}\n\n/** What `connect()`, `showConnectDialog()` and `disconnectAll()` reject with without a relay. */\nfunction noRelay(): Promise<never> {\n\treturn Promise.reject(new TypeError(\"TabMcp: this TabMcp has no relay\"));\n}\n\n/**\n * A rejection of `disconnectAll()`: `secretChanged` says whether the apps\n * were disconnected and the secret is new (only connecting with it failed)\n * or not (the old one could not be taken back and is kept, with its grants).\n */\nfunction changed(error: unknown, secretChanged: boolean): unknown {\n\treturn Object.assign(Object(error), { secretChanged });\n}\n\n/** What a method that asks the relay rejects with while it cannot. */\nfunction notConnected(): Promise<never> {\n\treturn Promise.reject(\n\t\tnew DOMException(\"TabMcp: not connected\", \"InvalidStateError\"),\n\t);\n}\n\n/** The lazy chunk (`connection.ts`). */\ntype Lazy = typeof import(\"./connection.ts\");\n\ntype Listener<K extends keyof TabMcpEventMap> = (\n\tevent: TabMcpEventMap[K],\n) => void;\n\n/**\n * Offers a page's tools to AI apps through a tab-mcp relay (and, without\n * `relay`, only through `serve` and WebMCP).\n *\n * ```ts\n * const mcp = new TabMcp({ relay: \"https://relay.example\", server: { name: \"Calculator\", version: \"1.0.0\" } });\n * await mcp.registerTool({ name: \"add\", description: \"Add two numbers\", execute: ({ a, b }) => Number(a) + Number(b) });\n * button.onclick = () => mcp.showConnectDialog();\n * ```\n */\nexport class TabMcp extends EventTarget {\n\treadonly #registry = new ToolRegistry();\n\t/**\n\t * With `webmcp: true`: the tab-mcp browser extension while it serves this\n\t * page, with the AI apps that reach the page's tools through it (DEC-207);\n\t * `extensionchange` says when it changes. `undefined` without it, while\n\t * its AI access is off, and without WebMCP. Declared only: the mirror's\n\t * chunk defines it on the instance once it hears the extension, so that\n\t * the core carries no bytes for it (until then it is `undefined`).\n\t */\n\tdeclare readonly extension: BrowserExtension | undefined;\n\treadonly #server: ServerInfo;\n\treadonly #app: string;\n\treadonly #appName: string | undefined;\n\treadonly #onConfirm: ConfirmHandler | undefined;\n\treadonly #alwaysAllow: TabMcpOptions[\"alwaysAllow\"];\n\treadonly #ui: DialogOptions | undefined;\n\t/** `undefined` without a relay: tools only through `serve` and WebMCP. */\n\treadonly #relayUrl: string | undefined;\n\treadonly #secrets: SecretStore | undefined;\n\t/** The channel of the tabs that share the secret (DEC-095). */\n\treadonly #tabs: string | undefined;\n\t/**\n\t * The page was on when a takeover ended its session (or when a\n\t * `disconnectAll()` failed), and nothing was ended since: the next\n\t * `disconnectAll()` connects with the new secret. Only that; whether it\n\t * takes the old address back does not depend on it (DEC-136).\n\t */\n\t#stayOn = false;\n\t/** The running `disconnectAll()`: a second call returns it, `connect()` waits for it. */\n\t#renewing: Promise<void> | undefined;\n\treadonly #identityAssertion: IdentityAssertionHandler | undefined;\n\t#identity: IdentityState = \"none\";\n\t#identityMessage: string | undefined;\n\t/** Incremented per identity request, so a late answer of an older one is dropped. */\n\t#identityRound = 0;\n\t#state: ConnectionState = \"disconnected\";\n\t#session: SessionInfo | undefined;\n\t#grants: readonly Grant[] = Object.freeze([]);\n\t#pairing = false;\n\t#pairingCode: PairingCode | undefined;\n\t#pairingUntil: string | undefined;\n\t/** The last `pairing.start` went to an `oidc` session (DEC-202). */\n\t#asked = false;\n\t/** `connect()` from a click while reconnecting: that session asks again. */\n\t#clicked = false;\n\t#connection: ConnectionHandle | undefined;\n\t#connecting: Promise<SessionInfo> | undefined;\n\t/** Incremented when a connection ends or is cancelled. */\n\t#generation = 0;\n\treadonly #reconnect: boolean;\n\t#reconnecting: ReconnectingInfo | undefined;\n\t#reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\t#unwatch: (() => void) | undefined;\n\t/** The lazy chunk, once `#load()` loaded it. */\n\t#lazy: Lazy | undefined;\n\t/** The open \"Connect your AI app\" dialog: one at a time. */\n\t#connectDialog: { doc: Document; shown: Promise<void> } | undefined;\n\t/**\n\t * What a tool call needs, through the relay and WebMCP alike. The events\n\t * always, even from a connection that is no longer current: a call that\n\t * started must end, and every end has its start.\n\t */\n\treadonly #calls: CallHost = {\n\t\tregistry: this.#registry,\n\t\tconfirm: (request) => this.#confirm(request),\n\t\townConfirm: () => !!this.#onConfirm,\n\t\ttoolCallStarted: (call) => this.#emit(\"toolcall\", call),\n\t\ttoolCallEnded: (call) => this.#emit(\"toolcallend\", call),\n\t};\n\n\tconstructor(options: TabMcpOptions) {\n\t\tsuper();\n\t\tconst { server, appName } = options;\n\t\tconst relay =\n\t\t\toptions.relay === undefined ? undefined : tabUrl(options.relay);\n\t\tif (\n\t\t\ttypeof server?.name !== \"string\" ||\n\t\t\ttypeof server.version !== \"string\"\n\t\t) {\n\t\t\tthrow new TypeError(\"TabMcp: server needs a name and a version\");\n\t\t}\n\t\tif (appName !== undefined && !isAppName(appName)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"TabMcp: appName must be 1-64 characters without control characters\",\n\t\t\t);\n\t\t}\n\t\tconst app = options.app ?? appIdOf(server.name);\n\t\tif (\n\t\t\toptions.app !== undefined\n\t\t\t\t? typeof app !== \"string\" || !APP_ID.test(app)\n\t\t\t\t: relay && app === \"\"\n\t\t) {\n\t\t\tthrow new TypeError(\n\t\t\t\toptions.app !== undefined\n\t\t\t\t\t? \"TabMcp: app must be 1-32 characters of a-z, 0-9 and -, not starting or ending with -\"\n\t\t\t\t\t: \"TabMcp: server.name has no letter a-z and no digit to make the address of: set app\",\n\t\t\t);\n\t\t}\n\t\tthis.#app = app;\n\t\tthis.#relayUrl = relay?.url;\n\t\tthis.#server = { ...server };\n\t\tthis.#appName = appName;\n\t\tthis.#onConfirm = options.onConfirm;\n\t\tthis.#alwaysAllow = options.alwaysAllow;\n\t\tthis.#ui = options.ui;\n\t\tthis.#identityAssertion = options.identityAssertion;\n\t\tthis.#reconnect = options.reconnect !== false;\n\t\tif (relay !== undefined) {\n\t\t\t// One address per relay and page (server name, DEC-083).\n\t\t\tconst key =\n\t\t\t\toptions.storageKey ??\n\t\t\t\t`tab-mcp:secret:${relay.origin}:${encodeURIComponent(server.name)}`;\n\t\t\tthis.#secrets = new SecretStore(options.storage, key);\n\t\t\t// Tabs that share the secret share this channel; with `storage: null`\n\t\t\t// every tab has a secret of its own (DEC-095).\n\t\t\tthis.#tabs = options.storage === null ? undefined : `${key}#tabs`;\n\t\t}\n\t\tthis.#registry.onChange(() =>\n\t\t\tthis.#emit(\"toolschange\", { tools: this.tools }),\n\t\t);\n\t\t// Also through the browser's own WebMCP, where it has it (DEC-115):\n\t\t// consequential tools only when their registration says so. The getter\n\t\t// is read now (WM 10); the mirror loads only then (DEC-171), with the\n\t\t// handshake with the tab-mcp browser extension (DEC-207).\n\t\tconst context = options.webmcp === true ? nativeContext() : undefined;\n\t\tif (context !== undefined)\n\t\t\timport(\"./webmcp.ts\").then(\n\t\t\t\t(m) =>\n\t\t\t\t\tm.mirror(\n\t\t\t\t\t\tthis.#registry,\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t(tool, input, signal, by) =>\n\t\t\t\t\t\t\tthis.#load().then((lazy) =>\n\t\t\t\t\t\t\t\tlazy.callFromWebMcp(this.#calls, tool, input, signal, by),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tapp,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\t// Passed, not imported there: a chunk shared with the core\n\t\t\t\t\t\t// would cost the core more.\n\t\t\t\t\t\tVERSION,\n\t\t\t\t\t),\n\t\t\t\t// Like a failed registration: warned, the relay unaffected.\n\t\t\t\t(error: unknown) =>\n\t\t\t\t\tconsole.warn(\"tab-mcp: no tools are offered through WebMCP:\", error),\n\t\t\t);\n\t}\n\n\t/**\n\t * Register a tool (WebMCP shape). Allowed before and after `connect()`;\n\t * aborting `options.signal` unregisters it. Rejects with a `TypeError` for\n\t * an invalid tool and an `InvalidStateError` for a duplicate name (the\n\t * tool is registered, or refused, before it returns); await it or catch\n\t * the rejection (DEC-010).\n\t */\n\tregisterTool<Input extends object = Record<string, unknown>>(\n\t\ttool: Tool<Input>,\n\t\toptions: RegisterToolOptions = {},\n\t): Promise<void> {\n\t\ttry {\n\t\t\t// The arguments are checked against `inputSchema` before `execute` runs.\n\t\t\tthis.#registry.register(tool as unknown as Tool, options);\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t\treturn Promise.resolve();\n\t}\n\n\t/** Names of the registered tools. */\n\tget tools(): readonly string[] {\n\t\treturn this.#registry.list().map((t) => t.name);\n\t}\n\n\tget state(): ConnectionState {\n\t\treturn this.#state;\n\t}\n\n\t/** The current session, while connected: its `address` is the one to give to AI apps. */\n\tget session(): SessionInfo | undefined {\n\t\treturn this.#session;\n\t}\n\n\t/** The AI apps connected to this address (frozen; a new array when they change). */\n\tget grants(): readonly Grant[] {\n\t\treturn this.#grants;\n\t}\n\n\t/**\n\t * While `state` is `reconnecting`: the next (or running) attempt and when\n\t * it starts. `undefined` otherwise.\n\t */\n\tget reconnecting(): ReconnectingInfo | undefined {\n\t\treturn this.#reconnecting;\n\t}\n\n\t/** Who the relay knows as the page's user (identity binding). */\n\tget identity(): IdentityState {\n\t\treturn this.#identity;\n\t}\n\n\t/** Why the relay refused the identity, while `identity` is `refused`. */\n\tget identityMessage(): string | undefined {\n\t\treturn this.#identityMessage;\n\t}\n\n\t/**\n\t * Ask the `identityAssertion` hook again and send the result, e.g. after\n\t * the user signed in without a page load. Resolves with the outcome, the\n\t * new `identity`: `bound` once the relay accepted it, `refused`, or `none`\n\t * when nobody is signed in or no answer came in time. Rejects with an\n\t * `InvalidStateError` while not connected, and with a `TypeError` without\n\t * the hook.\n\t */\n\trefreshIdentity(): Promise<IdentityState> {\n\t\tconst session = this.#session;\n\t\tconst ask = this.#identityAssertion;\n\t\tif (ask === undefined)\n\t\t\treturn Promise.reject(new TypeError(\"TabMcp: no identityAssertion\"));\n\t\tif (session === undefined) return notConnected();\n\t\tconst round = ++this.#identityRound;\n\t\tconst connection = this.#connection;\n\t\tthis.#setIdentity(\"pending\");\n\t\t// No answer in time, from the hook or the relay (an old relay, a lost\n\t\t// message, a hook that never settles): give up.\n\t\tconst timer = setTimeout(() => {\n\t\t\tif (round !== this.#identityRound || this.#identity !== \"pending\") return;\n\t\t\tthis.#identityRound++; // a late answer is dropped\n\t\t\tthis.#setIdentity(\"none\");\n\t\t}, timing.answerTimeoutMs);\n\t\treturn new Promise<IdentityState>((resolve) => {\n\t\t\tconst settle = (event: TabMcpEventMap[\"identitychange\"]) => {\n\t\t\t\tconst { identity } = event.detail;\n\t\t\t\tif (identity === \"pending\") return;\n\t\t\t\tthis.removeEventListener(\"identitychange\", settle);\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(identity);\n\t\t\t};\n\t\t\tthis.addEventListener(\"identitychange\", settle);\n\t\t\tPromise.resolve()\n\t\t\t\t.then(() =>\n\t\t\t\t\task({ address: session.address, sessionId: session.sessionId }),\n\t\t\t\t)\n\t\t\t\t.then(\n\t\t\t\t\t(assertion) => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tround !== this.#identityRound ||\n\t\t\t\t\t\t\tthis.#connection !== connection\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t// Superseded (a newer request, a sign-out, a new connection): that one settles the state.\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof assertion !== \"string\" || assertion === \"\") {\n\t\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tconnection?.send({ type: \"identity\", assertion, round }) !== true\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tif (round !== this.#identityRound) return;\n\t\t\t\t\t\tthis.#emit(\"error\", {\n\t\t\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * The page's user signed out: the relay ends every AI connection of this\n\t * address at once (identity binding). Call it from the web app's logout.\n\t * `identity` goes to `none` at once. Resolves once the relay removed the\n\t * grants; rejects with an `InvalidStateError` while not connected to a\n\t * relay that pairs by sign-in (`session.pairing` is `oidc`), and with a\n\t * `NetworkError` when the session ends first. Grants that stay work only while a page signed in\n\t * as the same person is open.\n\t */\n\tsignOut(): Promise<void> {\n\t\tthis.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\treturn this.#session?.pairing === \"oidc\"\n\t\t\t? this.#ask({ type: \"identity.logout\" }, () => !this.#grants.length)\n\t\t\t: notConnected();\n\t}\n\n\t/** The pairing code to show, if the relay sent one. */\n\tget pairingCode(): PairingCode | undefined {\n\t\treturn this.#pairingCode;\n\t}\n\n\t/**\n\t * Identity binding: until when a sign-in pairs this page (ISO time, on\n\t * the page's clock: the relay's duration counted from its answer to the\n\t * last `startPairing()`, DEC-202). A reconnect the library makes by\n\t * itself does not start it anew: it is the time of the reconnect then.\n\t * `undefined` while pairing is off, until the relay answers, after the\n\t * session ended, and from relays up to 0.12.1, which do not say.\n\t */\n\tget pairingUntil(): string | undefined {\n\t\treturn this.#pairingUntil;\n\t}\n\n\t/**\n\t * Connect to the relay: loads the connection and MCP handler, opens the\n\t * WebSocket, resolves with the session. Call it from a user action (a\n\t * click): where browsers track user activation it is refused otherwise,\n\t * unless `options.resume` says the user already chose to keep AI access on.\n\t * While `reconnecting`, it makes the next attempt at once.\n\t */\n\tconnect(options: ConnectOptions = {}): Promise<SessionInfo> {\n\t\tif (this.#relayUrl === undefined) return noRelay();\n\t\tif (this.#state === \"connected\" && this.#session !== undefined) {\n\t\t\treturn Promise.resolve(this.#session);\n\t\t}\n\t\tif (this.#reconnecting !== undefined) {\n\t\t\tthis.#clicked ||= options.resume !== true;\n\t\t\treturn this.#attemptReconnect();\n\t\t}\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tconst activation = (\n\t\t\tglobalThis.navigator as\n\t\t\t\t| { userActivation?: { isActive: boolean } }\n\t\t\t\t| undefined\n\t\t)?.userActivation;\n\t\tif (\n\t\t\toptions.resume !== true &&\n\t\t\tactivation !== undefined &&\n\t\t\t!activation.isActive\n\t\t) {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew DOMException(\n\t\t\t\t\t\"connect() must be called from a user action, such as a click\",\n\t\t\t\t\t\"NotAllowedError\",\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\t// While `disconnectAll()` runs: afterwards, with the new secret.\n\t\treturn this.#renewing\n\t\t\t? this.#renewing.then(() => this.connect({ resume: true }))\n\t\t\t: this.#start();\n\t}\n\n\t/** Open the page's connection; a reconnect attempt stays `reconnecting`. */\n\t#start(): Promise<SessionInfo> {\n\t\tif (!this.#reconnecting) this.#setState(\"connecting\");\n\t\tconst connecting = this.#open(this.#generation);\n\t\tthis.#connecting = connecting;\n\t\tconnecting.then(\n\t\t\t() => {\n\t\t\t\tif (this.#connecting === connecting) this.#connecting = undefined;\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (this.#connecting !== connecting) return; // superseded\n\t\t\t\tthis.#connecting = undefined;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\t// A failed attempt: the next one is scheduled, or it stops.\n\t\t\t\tif (!this.#reconnecting) this.#setState(\"disconnected\");\n\t\t\t},\n\t\t);\n\t\treturn connecting;\n\t}\n\n\t/**\n\t * The lazy chunk (on `connect()` or the first WebMCP call). The validator\n\t * is loaded with it: it checks the schemas from now on (DEC-086).\n\t */\n\tasync #load(): Promise<Lazy> {\n\t\tconst lazy = await import(\"./connection.ts\");\n\t\tfor (const error of lazy.compileRegistry(this.#registry))\n\t\t\tthis.#emit(\"error\", { error });\n\t\tthis.#lazy = lazy;\n\t\treturn lazy;\n\t}\n\n\t/**\n\t * Open a connection. `takeBack`: the secret of an address to take back\n\t * (`hello.revokeAll`, DEC-095); that connection is never current, so its\n\t * session and events stay unseen, but `#end` closes it.\n\t */\n\tasync #open(generation: number, takeBack?: string): Promise<SessionInfo> {\n\t\tconst { openConnection, addressIdOf } = await this.#load();\n\t\tconst relayUrl = this.#relayUrl;\n\t\tif (relayUrl === undefined || this.#secrets === undefined) return noRelay();\n\t\tconst secret =\n\t\t\ttakeBack ?? this.#secrets.current() ?? this.#secrets.rotate();\n\t\tconst address = await addressIdOf(secret);\n\t\tif (generation !== this.#generation) {\n\t\t\tthrow new DOMException(\"The connection was cancelled\", \"AbortError\");\n\t\t}\n\t\tconst ref: { connection?: ConnectionHandle } = {};\n\t\tconst connection = openConnection(this.#host(ref), relayUrl, secret, {\n\t\t\taddress,\n\t\t\trevokeAll: !!takeBack,\n\t\t});\n\t\tif (!takeBack) ref.connection = connection;\n\t\tthis.#connection = connection;\n\t\treturn connection.ready;\n\t}\n\n\t/** Whether this `TabMcp` has a relay; without one, `connect()` rejects. */\n\tget hasRelay(): boolean {\n\t\treturn this.#relayUrl !== undefined;\n\t}\n\n\t/**\n\t * Serve the tools over a port, without a relay: for this site's own\n\t * assistant, e.g. a chat in an iframe whose backend calls the tools through\n\t * `createTunnelFetch` (`@ractive-ch/tab-mcp-client/tunnel`). The port\n\t * carries the relay's `http.*` messages as plain objects; a `MessagePort`\n\t * fits. Whoever holds the other end calls the tools without pairing, as\n\t * `options.client` (`kind: \"local\"`): hand it out only to a frame whose\n\t * origin you checked. Consequential tools still ask: `options.onConfirm`\n\t * for this port's calls (in the site's chat, say), else the page's\n\t * `onConfirm` or dialog. Each request may take `options.requestTimeoutMs`\n\t * (300 s). Only tools whose `callers` include `\"local\"` (by default all)\n\t * are listed and callable. Resolves once the port\n\t * is served; may be called for several ports. Rejects with a `TypeError`\n\t * for options it cannot use.\n\t */\n\tserve(port: TunnelPort, options: ServeOptions): Promise<ServeHandle> {\n\t\treturn this.#load().then((lazy) =>\n\t\t\tlazy.servePort(\n\t\t\t\t{\n\t\t\t\t\t...this.#calls,\n\t\t\t\t\tserver: this.#server,\n\t\t\t\t\terror: (error) => this.#emit(\"error\", { error }),\n\t\t\t\t},\n\t\t\t\tport,\n\t\t\t\toptions,\n\t\t\t),\n\t\t);\n\t}\n\n\t/** End the session (`bye`). Grants stay: AI apps work again after the next `connect()`. */\n\tdisconnect(): void {\n\t\tthis.#end(\"user\");\n\t}\n\n\t/**\n\t * Disconnect every AI app and start over with a new secret. The address\n\t * people add to an AI app names the app and stays the same (DEC-196);\n\t * what changes is the page behind it, so every AI app has to pair again.\n\t * If the page has a secret already, it first takes it back: it\n\t * connects with the old secret and the relay revokes every grant of it in\n\t * the same step (`hello.revokeAll`, DEC-095, DEC-136), connected or not,\n\t * taken over or not. Then it makes a new secret and connects with it if\n\t * the page was connected, connecting or reconnecting, and resolves once\n\t * that is done (the new session is `session`). Rejects, and keeps the old\n\t * secret so that a retry takes it back again, when the old secret could\n\t * not be taken back (relay unreachable, taken over again first). With a\n\t * relay, every rejection has `secretChanged`: `false` then, `true` when\n\t * only connecting with the new secret failed (without one: a\n\t * `TypeError`). Call it from a user action.\n\t */\n\tdisconnectAll(): Promise<void> {\n\t\t// Without a relay there is no secret store.\n\t\tconst secrets = this.#secrets;\n\t\tif (!secrets) return noRelay();\n\t\t// biome-ignore lint/suspicious/noAssignInExpressions: one promise per run\n\t\treturn (this.#renewing ??= this.#renew(secrets).finally(() => {\n\t\t\tthis.#renewing = undefined;\n\t\t}));\n\t}\n\n\tasync #renew(secrets: SecretStore): Promise<void> {\n\t\tconst wasOn = this.#state !== \"disconnected\" || this.#stayOn;\n\t\t// Read now, also when the page is off or was taken over (CC 4). Another\n\t\t// tab that rotated the secret since took the address it had back itself.\n\t\tconst old = secrets.current();\n\t\tthis.#end(\"disconnect_all\");\n\t\tconst generation = this.#generation;\n\t\tif (old) {\n\t\t\tthis.#setState(\"connecting\");\n\t\t\ttry {\n\t\t\t\tawait this.#open(generation, old);\n\t\t\t} catch (error) {\n\t\t\t\tif (generation === this.#generation) {\n\t\t\t\t\tthis.#setState(\"disconnected\");\n\t\t\t\t\tthis.#stayOn = wasOn; // a retry does the same\n\t\t\t\t}\n\t\t\t\tthrow changed(error, false);\n\t\t\t} finally {\n\t\t\t\t// The take-back connection, unless `#end` closed it already.\n\t\t\t\tif (generation === this.#generation) {\n\t\t\t\t\tthis.#connection?.close(\"disconnect_all\");\n\t\t\t\t\tthis.#connection = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsecrets.rotate();\n\t\t// The relay revoked them (CC 14).\n\t\tthis.#setGrants([]);\n\t\t// It was on: the user chose that already, as for a reconnect.\n\t\tif (wasOn)\n\t\t\tawait this.#start().catch((error: unknown) => {\n\t\t\t\tthrow changed(error, true);\n\t\t\t});\n\t\telse this.#setState(\"disconnected\");\n\t}\n\n\t/** Close the connection (or cancel connecting) and report it at once. */\n\t#end(reason: DisconnectReason): void {\n\t\tthis.#stopReconnecting();\n\t\tthis.#stayOn = false;\n\t\tthis.#generation++;\n\t\tconst connection = this.#connection;\n\t\tthis.#connection = undefined;\n\t\tthis.#connecting = undefined;\n\t\tconnection?.close(reason); // its callbacks are stale from here on\n\t\tif (this.#state === \"disconnected\") return;\n\t\tthis.#session = undefined;\n\t\tthis.#clearPairing();\n\t\tthis.#identityRound++;\n\t\tthis.#setIdentity(\"none\");\n\t\t// With the reason also when it ended connecting or reconnecting: the\n\t\t// page turned it off (or disconnected all apps) all the same.\n\t\tthis.#setState(\"disconnected\", reason);\n\t}\n\n\t/**\n\t * Wait, then connect again (attempt `attempt`, from 1); `state` is\n\t * `reconnecting`, and `statechange` says so for each attempt.\n\t */\n\t#scheduleReconnect(reason: DisconnectReason, attempt: number): void {\n\t\tconst delays = timing.reconnectDelaysMs;\n\t\t// Up to 20 % either way, so that the tabs a relay restart disconnected\n\t\t// do not all come back at the same moment (CC 11).\n\t\tconst delay =\n\t\t\t(delays[Math.min(attempt, delays.length) - 1] ?? 0) *\n\t\t\t(0.8 + 0.4 * Math.random());\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = setTimeout(() => {\n\t\t\tthis.#attemptReconnect().catch(() => {}); // the next one is scheduled\n\t\t}, delay);\n\t\tthis.#watch();\n\t\tthis.#reconnecting = { reason, attempt, at: Date.now() + delay };\n\t\tthis.#setState(\"reconnecting\", attempt > 1 ? undefined : reason);\n\t}\n\n\t/** Make the next reconnect attempt now; on failure, schedule the one after. */\n\t#attemptReconnect(): Promise<SessionInfo> {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tif (this.#connecting !== undefined) return this.#connecting;\n\t\tconst attempt = this.#start();\n\t\tattempt.catch((error: unknown) => {\n\t\t\t// Read now, not when the attempt started: a listener before this may\n\t\t\t// have ended it all or started the next attempt, which then owns the\n\t\t\t// next step (CC 10).\n\t\t\tconst info = this.#reconnecting;\n\t\t\tif (info === undefined || this.#connecting !== undefined) return;\n\t\t\t// Only what may get better: an unreachable relay (network), a\n\t\t\t// heartbeat or a shutdown; a refusal stops it (DEC-082).\n\t\t\tconst reason = (error as { reason?: DisconnectReason } | null)?.reason;\n\t\t\tif (reason === undefined || RECONNECT_REASONS.has(reason)) {\n\t\t\t\tthis.#scheduleReconnect(info.reason, info.attempt + 1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A refusal stops it, and `error` says why, before `statechange`.\n\t\t\t// The state is `disconnected` already, so that a `connect()` from\n\t\t\t// the listener starts afresh (with the user-activation check).\n\t\t\tthis.#stopReconnecting();\n\t\t\tthis.#state = \"disconnected\";\n\t\t\tthis.#emit(\"error\", {\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t});\n\t\t\tif (this.#state === \"disconnected\")\n\t\t\t\tthis.#emit(\"statechange\", { state: \"disconnected\" });\n\t\t});\n\t\treturn attempt;\n\t}\n\n\t/**\n\t * Back to the front, or online again: try at once instead of waiting. The\n\t * listeners are in the lazy chunk, loaded by the connection that broke\n\t * (if loading it failed, the timer still tries).\n\t */\n\t#watch(): void {\n\t\tthis.#unwatch ??= this.#lazy?.onWake(() => {\n\t\t\t// Only while waiting: an attempt that is running is not doubled.\n\t\t\tif (this.#reconnectTimer !== undefined)\n\t\t\t\tthis.#attemptReconnect().catch(() => {});\n\t\t});\n\t}\n\n\t/** Stop reconnecting; the caller sets the state that follows. */\n\t#stopReconnecting(): void {\n\t\tclearTimeout(this.#reconnectTimer);\n\t\tthis.#reconnectTimer = undefined;\n\t\tthis.#unwatch?.();\n\t\tthis.#unwatch = undefined;\n\t\tthis.#reconnecting = undefined;\n\t}\n\n\t/**\n\t * The pairing dialog opened: ask the relay for codes (DEC-028). With\n\t * identity binding each call while connected starts the relay's ten\n\t * minutes for a sign-in anew (`pairingUntil`, DEC-202): call it only\n\t * when the user acts (opens the dialog, continues after the time is up).\n\t */\n\tstartPairing(): void {\n\t\tthis.#pairing = true;\n\t\t// Owed to the relay until sent: also a reconnect sends it then.\n\t\tthis.#asked = false;\n\t\tif (this.#state === \"connected\") this.#askPairing();\n\t}\n\n\t/** Send `pairing.start`; `pairingUntil` waits for the relay's answer. */\n\t#askPairing(): void {\n\t\tthis.#setPairingUntil(undefined);\n\t\tthis.#asked = this.#session?.pairing === \"oidc\";\n\t\tthis.#connection?.send({ type: \"pairing.start\" });\n\t}\n\n\t/** The pairing dialog closed: the code becomes invalid. */\n\tstopPairing(): void {\n\t\tif (!this.#pairing) return;\n\t\tthis.#pairing = false;\n\t\tif (this.#state === \"connected\")\n\t\t\tthis.#connection?.send({ type: \"pairing.stop\" });\n\t\tthis.#clearPairing();\n\t}\n\n\t/** No code, no time for a sign-in: pairing is off or the session ended. */\n\t#clearPairing(): void {\n\t\tthis.#setPairingCode(undefined);\n\t\tthis.#setPairingUntil(undefined);\n\t}\n\n\t/**\n\t * Disconnect one AI app: its tokens stop working at once. Resolves once\n\t * the relay removed the grant (at once for one that is not in `grants`,\n\t * and when the relay no longer knows it: it leaves `grants` then).\n\t * Rejects with an `InvalidStateError` while not connected (only the relay\n\t * can do it), a `NetworkError` when the session ends before the answer,\n\t * and with the relay's error when it refuses (its `code` is\n\t * `store_unavailable` when it could not save the change: try again).\n\t */\n\trevoke(grantId: string): Promise<void> {\n\t\tconst gone = () => !this.#grants.some((g) => g.grantId === grantId);\n\t\treturn gone()\n\t\t\t? Promise.resolve()\n\t\t\t: this.#ask({ type: \"grant.revoke\", grantId }, gone);\n\t}\n\n\t/**\n\t * Send `message` to the relay and resolve once `done()` holds (it is\n\t * checked on each change of the grants). Rejects with an\n\t * `InvalidStateError` when it cannot send, a `NetworkError` when the\n\t * session ends first, the relay's refusal of this message\n\t * (`store_unavailable`: it could not save the change; `unknown_id`), and a\n\t * `TimeoutError` when none of that happened within\n\t * `timing.answerTimeoutMs`.\n\t */\n\t#ask(\n\t\tmessage: TabMessage & { grantId?: string },\n\t\tdone: () => boolean,\n\t): Promise<void> {\n\t\t// With a session, the lazy chunk is loaded: the waiting is there.\n\t\treturn !this.#session || this.#connection?.send(message) !== true\n\t\t\t? notConnected()\n\t\t\t: (this.#lazy as Lazy).answer(\n\t\t\t\t\tthis,\n\t\t\t\t\tmessage,\n\t\t\t\t\tdone,\n\t\t\t\t\t() => this.#state === \"connected\",\n\t\t\t\t\ttiming.answerTimeoutMs,\n\t\t\t\t);\n\t}\n\n\t/**\n\t * Open the default \"Connect your AI app\" dialog; connects first if needed\n\t * (call it from a click). Resolves when the dialog closes. One dialog at\n\t * a time (they would share one pairing): while it is open, a call for the\n\t * same document opens no second one and resolves with it, and a call for\n\t * another document rejects with an `InvalidStateError`. Pages with their\n\t * own UI use the events and methods instead.\n\t */\n\tshowConnectDialog(options: { document?: Document } = {}): Promise<void> {\n\t\tif (this.#relayUrl === undefined) return noRelay();\n\t\tconst doc = options.document ?? globalThis.document;\n\t\tconst open = this.#connectDialog;\n\t\tif (open !== undefined) {\n\t\t\treturn open.doc === doc\n\t\t\t\t? open.shown\n\t\t\t\t: Promise.reject(\n\t\t\t\t\t\tnew DOMException(\n\t\t\t\t\t\t\t\"showConnectDialog: the dialog is already open in another document\",\n\t\t\t\t\t\t\t\"InvalidStateError\",\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t}\n\t\tconst shown = this.#showConnectDialog(doc).finally(() => {\n\t\t\tif (this.#connectDialog?.shown === shown) this.#connectDialog = undefined;\n\t\t});\n\t\tthis.#connectDialog = { doc, shown };\n\t\treturn shown;\n\t}\n\n\tasync #showConnectDialog(doc: Document): Promise<void> {\n\t\tconst connecting = this.connect();\n\t\tconnecting.catch(() => {}); // the dialog shows the error\n\t\tconst { showConnectDialog } = await import(\"./connect.ts\");\n\t\tawait showConnectDialog(this, connecting, doc, this.#server.name, this.#ui);\n\t}\n\n\toverride addEventListener<K extends keyof TabMcpEventMap>(\n\t\ttype: K,\n\t\tlistener: Listener<K> | null,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\toverride addEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void;\n\toverride addEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | AddEventListenerOptions,\n\t): void {\n\t\tsuper.addEventListener(type, listener, options);\n\t}\n\n\toverride removeEventListener<K extends keyof TabMcpEventMap>(\n\t\ttype: K,\n\t\tlistener: Listener<K> | null,\n\t\toptions?: boolean | EventListenerOptions,\n\t): void;\n\toverride removeEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | EventListenerOptions,\n\t): void;\n\toverride removeEventListener(\n\t\ttype: string,\n\t\tlistener: EventListenerOrEventListenerObject | null,\n\t\toptions?: boolean | EventListenerOptions,\n\t): void {\n\t\tsuper.removeEventListener(type, listener, options);\n\t}\n\n\t#emit<K extends keyof TabMcpEventMap>(\n\t\ttype: K,\n\t\tdetail: TabMcpEventMap[K][\"detail\"],\n\t): void {\n\t\tthis.dispatchEvent(new CustomEvent(type, { detail }));\n\t}\n\n\t/** A new state; `reconnecting` again means the next attempt was scheduled. */\n\t#setState(state: ConnectionState, reason?: DisconnectReason): void {\n\t\tif (this.#state === state && state !== \"reconnecting\") return;\n\t\tthis.#state = state;\n\t\tthis.#emit(\"statechange\", reason ? { state, reason } : { state });\n\t}\n\n\t#setIdentity(identity: IdentityState, message?: string): void {\n\t\tif (this.#identity === identity && message === undefined) return;\n\t\tthis.#identity = identity;\n\t\tthis.#identityMessage = identity === \"refused\" ? message : undefined;\n\t\tthis.#emit(\"identitychange\", {\n\t\t\tidentity,\n\t\t\tidentityMessage: this.#identityMessage,\n\t\t});\n\t}\n\n\t#setPairingCode(pairingCode: PairingCode | undefined): void {\n\t\tif (this.#pairingCode === undefined && pairingCode === undefined) return;\n\t\tthis.#pairingCode = pairingCode;\n\t\tthis.#emit(\"pairingcode\", { pairingCode });\n\t}\n\n\t#setPairingUntil(pairingUntil: string | undefined): void {\n\t\tif (this.#pairingUntil === pairingUntil) return;\n\t\tthis.#pairingUntil = pairingUntil;\n\t\tthis.#emit(\"pairinguntil\", { pairingUntil });\n\t}\n\n\t#setGrants(grants: readonly Grant[]): void {\n\t\tthis.#grants = Object.freeze(grants.map(frozenGrant));\n\t\tthis.#emit(\"grantschange\", { grants: this.#grants });\n\t}\n\n\t/**\n\t * A call the user allowed runs without asking, else `onConfirm` or the\n\t * dialog: decided out of the core, in the confirmation's chunk (a chunk\n\t * of its own for the allowances would cost the core more bytes, DEC-200).\n\t * If that chunk does not load, the page's own `onConfirm` asks (only its\n\t * `true` runs the call); without one the call is refused, never allowed.\n\t */\n\t#confirm(request: ConfirmRequest): Promise<ConfirmAnswer> {\n\t\tconst ask = this.#onConfirm;\n\t\treturn import(\"./confirm.ts\").then(\n\t\t\t(m) => m.confirmCall(this, request, ask),\n\t\t\t() => ask?.(request) ?? false,\n\t\t);\n\t}\n\n\t/**\n\t * For `./allowed` and the dialogs, not for pages: the tools, where the\n\t * secret is kept, and `alwaysAllow`.\n\t * @internal\n\t */\n\tget _allowed(): [\n\t\tToolRegistry,\n\t\tSecretStore | undefined,\n\t\tTabMcpOptions[\"alwaysAllow\"],\n\t] {\n\t\treturn [this.#registry, this.#secrets, this.#alwaysAllow];\n\t}\n\n\t/**\n\t * For `./react`, not for pages: the dialogs' options, whose `strings`\n\t * `ConnectButton` reads too (one table for every text, given once).\n\t * @internal\n\t */\n\tget _ui(): DialogOptions | undefined {\n\t\treturn this.#ui;\n\t}\n\n\t/**\n\t * The library's own confirmation: the dialog in the page with Don't allow\n\t * and Allow, and Always allow with `alwaysAllow` (what runs without\n\t * `onConfirm`), in `options.document` (default: the global one). An\n\t * `onConfirm` may hand some calls to it. A call the user allowed for its\n\t * AI app resolves `true` unasked. Resolves `false` where there is no\n\t * document.\n\t */\n\tconfirmInPage(\n\t\trequest: ConfirmRequest,\n\t\toptions: { document?: Document } = {},\n\t): Promise<boolean> {\n\t\tconst doc = options.document ?? globalThis.document;\n\t\tif (doc === undefined) return Promise.resolve(false); // nobody to ask: decline\n\t\treturn import(\"./confirm.ts\").then((ui) =>\n\t\t\tui.confirmInPage(this, request, doc, { ui: this.#ui }),\n\t\t);\n\t}\n\n\t/** The callbacks of one connection; once it is not current they are ignored. */\n\t#host(ref: { connection?: ConnectionHandle }): ConnectionHost {\n\t\tconst current = () =>\n\t\t\tref.connection !== undefined && this.#connection === ref.connection;\n\t\tlet replacedHere = false;\n\t\treturn {\n\t\t\t...this.#calls,\n\t\t\tserver: this.#server,\n\t\t\tapp: this.#app,\n\t\t\tappName: this.#appName,\n\t\t\ttabs: this.#tabs,\n\t\t\tlibrary: { name: LIBRARY_NAME, version: VERSION },\n\t\t\tclientFor: (grant: GrantRef): ToolCallClient => {\n\t\t\t\tconst known = this.#grants.find((g) => g.grantId === grant.grantId);\n\t\t\t\tconst client: RelayClient = {\n\t\t\t\t\tkind: \"relay\",\n\t\t\t\t\tgrantId: grant.grantId,\n\t\t\t\t\tid: grant.clientId,\n\t\t\t\t\thost: hostOf(grant.clientId),\n\t\t\t\t};\n\t\t\t\tif (known !== undefined) client.name = known.client.name;\n\t\t\t\treturn client;\n\t\t\t},\n\t\t\tsessionStarted: (m) => {\n\t\t\t\tconst session = sessionInfo(m);\n\t\t\t\tif (!current()) return session;\n\t\t\t\tthis.#session = session;\n\t\t\t\tthis.#stayOn = false;\n\t\t\t\t// A reconnect the library made by itself does not start a\n\t\t\t\t// sign-in's time anew once the user's start was sent, answered\n\t\t\t\t// or not: only the user does (DEC-202). Codes come again.\n\t\t\t\tconst ended =\n\t\t\t\t\tthis.#pairing &&\n\t\t\t\t\tthis.#reconnecting &&\n\t\t\t\t\t!this.#clicked &&\n\t\t\t\t\tthis.#asked &&\n\t\t\t\t\tsession.pairing === \"oidc\";\n\t\t\t\tthis.#clicked = false;\n\t\t\t\tthis.#stopReconnecting();\n\t\t\t\tthis.#setGrants([...m.grants]);\n\t\t\t\tif (ended) this.#setPairingUntil(new Date().toISOString());\n\t\t\t\telse if (this.#pairing) this.#askPairing();\n\t\t\t\tthis.#setState(\"connected\");\n\t\t\t\tif (session.pairing === \"oidc\" && this.#identityAssertion)\n\t\t\t\t\tvoid this.refreshIdentity();\n\t\t\t\treturn session;\n\t\t\t},\n\t\t\tpairingCode: (code) => {\n\t\t\t\tif (current() && this.#pairing) this.#setPairingCode(code);\n\t\t\t},\n\t\t\tpairingOpen: (until) => {\n\t\t\t\tif (current() && this.#pairing) this.#setPairingUntil(until);\n\t\t\t},\n\t\t\tgrantAdded: (grant) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tthis.#setGrants([\n\t\t\t\t\t...this.#grants.filter((g) => g.grantId !== grant.grantId),\n\t\t\t\t\tgrant,\n\t\t\t\t]);\n\t\t\t},\n\t\t\tgrantRemoved: (grantId) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tthis.#setGrants(this.#grants.filter((g) => g.grantId !== grantId));\n\t\t\t},\n\t\t\t// After `closed`, so no longer current: only a connection that was\n\t\t\t// current when it was replaced reports it.\n\t\t\treplaced: (detail) => {\n\t\t\t\tif (replacedHere) this.#emit(\"replaced\", detail);\n\t\t\t},\n\t\t\tidentityResult: (bound, round, message) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\t// Only the answer to the newest assertion counts: the relay echoes\n\t\t\t\t// its round, so a lost or late answer cannot pass for a newer one.\n\t\t\t\tif (round !== this.#identityRound) return;\n\t\t\t\tif (bound) this.#setIdentity(\"bound\");\n\t\t\t\telse this.#setIdentity(\"refused\", message ?? \"\");\n\t\t\t},\n\t\t\terror: (error) => {\n\t\t\t\tif (current()) this.#emit(\"error\", { error });\n\t\t\t},\n\t\t\tclosed: (reason: DisconnectReason) => {\n\t\t\t\tif (!current()) return;\n\t\t\t\tif (reason === \"replaced\") this.#stayOn = replacedHere = true;\n\t\t\t\tthis.#connection = undefined;\n\t\t\t\tthis.#session = undefined;\n\t\t\t\t// Any listener of these may end it all (`disconnect()`,\n\t\t\t\t// `disconnectAll()`): that bumps the generation.\n\t\t\t\tconst generation = this.#generation;\n\t\t\t\tthis.#clearPairing();\n\t\t\t\tthis.#identityRound++;\n\t\t\t\tthis.#setIdentity(\"none\");\n\t\t\t\tif (generation !== this.#generation) return;\n\t\t\t\t// Reconnecting is decided before the page hears of it, so its\n\t\t\t\t// listener sees `reconnecting` (or calls `connect()`, which then\n\t\t\t\t// makes the first attempt at once).\n\t\t\t\tif (this.#reconnect && RECONNECT_REASONS.has(reason))\n\t\t\t\t\tthis.#scheduleReconnect(reason, 1);\n\t\t\t\telse this.#setState(\"disconnected\", reason);\n\t\t\t},\n\t\t};\n\t}\n}\n"
|
|
9
9
|
],
|
|
10
10
|
"mappings": ";AAaA,IAAM,OAAO;AAoBb,SAAS,aAAa,CAAC,GAA0C;AAAA,EAChE,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAAA;AAI/D,IAAM,OAAO;AAEb,IAAM,QACL;AAQD,SAAS,UAAU,CAClB,MACA,OACA,QAAQ,GACR,MAAM,OACC;AAAA,EACP,IAAI,QAAQ,MAAM,OAAO,SAAS,YAAY,SAAS;AAAA,IAAM;AAAA,EAC7D,QAAQ,MAAM,QAAQ,IAAI;AAAA,EAC1B,IAAI,CAAC;AAAA,IAAK,MAAM,IAA+B;AAAA,EAC/C,YAAY,KAAK,UAAU,OAAO,QAAQ,IAAI;AAAA,IAC7C,IAAI,OAAO,CAAC,KAAK,KAAK,GAAG;AAAA,MACxB,WAAW,OAAO,OAAO,QAAQ,GAAG,CAAC,OAAO,MAAM,KAAK,GAAG,CAAC;AAAA;AAI9D,SAAS,cAAc,CAAC,MAAe,SAA0B;AAAA,EAChE,IAAI,OAAgB;AAAA,EACpB,WAAW,OAAO,QAAQ,MAAM,GAAG,EAAE,MAAM,CAAC,GAAG;AAAA,IAC9C,IAAI;AAAA,IACJ,IAAI;AAAA,MACH,MAAM,mBAAmB,GAAG;AAAA,MAC3B,MAAM;AAAA,MACP;AAAA;AAAA,IAED,MAAM,IAA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