@ractive-ch/tab-mcp-client 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- var O,b,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(!b[h]&&(u=n[h])){b[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]),b||={},f(t[n],1)};k(import.meta.url,["h64fd1em","kkrmjqfh","m0e4xvcy","3reh9k1f","zrz65vva","gdj1e1wh","yjcmhpdf","q758jr4g"],[["./tab-mcp-client.min.js"],["./webmcp-kkrmjqfh.min.js"],["./connection-m0e4xvcy.min.js"],["./connect-3reh9k1f.min.js",5,6,7],["./confirm-zrz65vva.min.js",5,6,7],["./tab-mcp-client-gdj1e1wh.min.js"],["./tab-mcp-client-yjcmhpdf.min.js",5],["./tab-mcp-client-q758jr4g.min.js"]],0);
2
- var L=/^[A-Za-z0-9_.-]{1,128}$/;function g(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var D=/^(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||!D.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 _(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"||!L.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 v;try{v=JSON.parse(JSON.stringify(c))}catch{throw TypeError(`registerTool: the ${l} of ${t} must be JSON`)}let C=H(v);if(C!==void 0)throw TypeError(`registerTool: the ${l} of ${t}: ${C}`);return v},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 T{#e=new Map;#i=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={..._(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.#i.add(e),()=>this.#i.delete(e)}#y(){for(let e of[...this.#i])e()}}var z=/^[A-Za-z0-9_-]{43}$/;function G(e){return btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function J(){return G(crypto.getRandomValues(new Uint8Array(32)))}function K(e){return typeof e==="string"&&z.test(e)}function U(){try{return globalThis.localStorage??null}catch{return null}}class S{storage;key;#e;#i=!1;constructor(e,t){this.storage=e===void 0?U():e,this.key=t}current(){if(this.#i)return this.#e;let e=null;try{e=this.storage?.getItem(this.key)??null}catch{}if(K(e))return this.#e=e,e;return this.#e}rotate(){let e=J();this.#e=e,this.#i=!0;try{this.storage?.setItem(this.key,e),this.#i=!1}catch{}return e}}var I="0.23.0";var M="@ractive-ch/tab-mcp-client",m=I;function W(){try{return Object.getOwnPropertyDescriptor(Document.prototype,"modelContext")?.get?.call(document)}catch{return}}var V=new Set(["localhost","127.0.0.1","[::1]"]),q=1000,y={reconnectDelaysMs:[5000,1e4,20000,40000,60000],answerTimeoutMs:15000,siblingGraceMs:q},P=new Set(["network","heartbeat","shutdown"]);function F(e){return Object.freeze({...e,client:Object.freeze({...e.client})})}function Y(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 Z=/^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;function Q(e){return e.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,32).replace(/-$/,"")}function X(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&&!V.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 ee(e){try{return new URL(e).host}catch{return""}}function te(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 w(){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 T;#i;#m;#y;#R;#G;#b;#w;#g;#J;#v=!1;#T;#I;#S="none";#M;#c=0;#r="disconnected";#s;#l=Object.freeze([]);#f=!1;#P;#x;#A=!1;#k=!1;#n;#o;#h=0;#K;#u;#p;#L;#$;#E;#D={registry:this.#e,confirm:(e)=>this.#X(e),onConfirm:()=>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:X(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&&!Y(i))throw TypeError("TabMcp: appName must be 1-64 characters without control characters");let r=e.app??Q(t.name);if(e.app!==void 0?typeof r!=="string"||!Z.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.#i={...t},this.#y=i,this.#R=e.onConfirm,this.#G=e.alwaysAllow,this.#b=e.ui,this.#I=e.identityAssertion,this.#K=e.reconnect!==!1,n!==void 0){let s=e.storageKey??`tab-mcp:secret:${n.origin}:${encodeURIComponent(t.name)}`;this.#g=new S(e.storage,s),this.#J=e.storage===null?void 0:`${s}#tabs`}this.#e.onChange(()=>this.#t("toolschange",{tools:this.tools}));let o=e.webmcp!==!1?W():void 0;if(o!==void 0)(f("kkrmjqfh"),import("./webmcp-kkrmjqfh.min.js")).then((s)=>s.mirror(this.#e,o,(a,d,h,u)=>this.#N().then((c)=>c.callFromWebMcp(this.#D,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.#r}get session(){return this.#s}get grants(){return this.#l}get reconnecting(){return this.#u}get identity(){return this.#S}get identityMessage(){return this.#M}refreshIdentity(){let e=this.#s,t=this.#I;if(t===void 0)return Promise.reject(TypeError("TabMcp: no identityAssertion"));if(e===void 0)return E();let i=++this.#c,n=this.#n;this.#a("pending");let r=setTimeout(()=>{if(i!==this.#c||this.#S!=="pending")return;this.#c++,this.#a("none")},y.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.#c||this.#n!==n)return;if(typeof a!=="string"||a===""){this.#a("none");return}if(n?.send({type:"identity",assertion:a,round:i})!==!0)this.#a("none")},(a)=>{if(i!==this.#c)return;this.#t("error",{error:a instanceof Error?a:Error(String(a))}),this.#a("none")})})}signOut(){return this.#c++,this.#a("none"),this.#s?.pairing==="oidc"?this.#q({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 w();if(this.#r==="connected"&&this.#s!==void 0)return Promise.resolve(this.#s);if(this.#u!==void 0)return this.#k||=e.resume!==!0,this.#H();if(this.#o!==void 0)return this.#o;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.#d("connecting");let e=this.#U(this.#h);return this.#o=e,e.then(()=>{if(this.#o===e)this.#o=void 0},()=>{if(this.#o!==e)return;if(this.#o=void 0,this.#n=void 0,!this.#u)this.#d("disconnected")}),e}async#N(){let e=await (f("m0e4xvcy"),import("./connection-m0e4xvcy.min.js"));for(let t of e.compileRegistry(this.#e))this.#t("error",{error:t});return this.#$=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 w();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,siblingGraceMs:y.siblingGraceMs});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.#D,server:this.#i,error:(n)=>this.#t("error",{error:n})},e,t))}disconnect(){this.#B("user")}disconnectAll(){let e=this.#g;if(!e)return w();return this.#T??=this.#Y(e).finally(()=>{this.#T=void 0})}async#Y(e){let t=this.#r!=="disconnected"||this.#v,i=e.current();this.#B("disconnect_all");let n=this.#h;if(i){this.#d("connecting");try{await this.#U(n,i)}catch(r){if(n===this.#h)this.#d("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.#d("disconnected")}#B(e){this.#_(),this.#v=!1,this.#h++;let t=this.#n;if(this.#n=void 0,this.#o=void 0,t?.close(e),this.#r==="disconnected")return;this.#s=void 0,this.#z(),this.#c++,this.#a("none"),this.#d("disconnected",e)}#W(e,t){let i=y.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.#d("reconnecting",t>1?void 0:e)}#H(){if(clearTimeout(this.#p),this.#p=void 0,this.#o!==void 0)return this.#o;let e=this.#j();return e.catch((t)=>{let i=this.#u;if(i===void 0||this.#o!==void 0)return;let n=t?.reason;if(n===void 0||P.has(n)){this.#W(i.reason,i.attempt+1);return}if(this.#_(),this.#r="disconnected",this.#t("error",{error:t instanceof Error?t:Error(String(t))}),this.#r==="disconnected")this.#t("statechange",{state:"disconnected"})}),e}#Z(){this.#L??=this.#$?.onWake(()=>{if(this.#p!==void 0)this.#H().catch(()=>{})})}#_(){clearTimeout(this.#p),this.#p=void 0,this.#L?.(),this.#L=void 0,this.#u=void 0}startPairing(){if(this.#f=!0,this.#A=!1,this.#r==="connected")this.#V()}#V(){this.#C(void 0),this.#A=this.#s?.pairing==="oidc",this.#n?.send({type:"pairing.start"})}stopPairing(){if(!this.#f)return;if(this.#f=!1,this.#r==="connected")this.#n?.send({type:"pairing.stop"});this.#z()}#z(){this.#F(void 0),this.#C(void 0)}revoke(e){let t=()=>!this.#l.some((i)=>i.grantId===e);return t()?Promise.resolve():this.#q({type:"grant.revoke",grantId:e},t)}#q(e,t){return!this.#s||this.#n?.send(e)!==!0?E():this.#$.answer(this,e,t,()=>this.#r==="connected",y.answerTimeoutMs)}showConnectDialog(e={}){if(this.#w===void 0)return w();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("3reh9k1f"),import("./connect-3reh9k1f.min.js"));await i(this,t,e,this.#i.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}))}#d(e,t){if(this.#r===e&&e!=="reconnecting")return;this.#r=e,this.#t("statechange",t?{state:e,reason:t}:{state:e})}#a(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(F)),this.#t("grantschange",{grants:this.#l})}#X(e){let t=this.#R;return (f("zrz65vva"),import("./confirm-zrz65vva.min.js")).then((i)=>i.confirmCall(this,e,t),()=>t?.(e)??!1)}get _allowed(){return[this.#e,this.#g,this.#G]}get _ui(){return this.#b}confirmInPage(e,t={}){if(e.client.kind==="webmcp")return Promise.resolve(!0);let i=t.document??globalThis.document;if(i===void 0)return Promise.resolve(!1);return (f("zrz65vva"),import("./confirm-zrz65vva.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.#D,server:this.#i,app:this.#m,appName:this.#y,tabs:this.#J,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:ee(n.clientId)};if(r!==void 0)o.name=r.client.name;return o},sessionStarted:(n)=>{let r=te(n);if(!t())return r;this.#s=r,this.#v=!1;let o=this.#f&&this.#u&&!this.#k&&this.#A&&r.pairing==="oidc";if(this.#k=!1,this.#_(),this.#O([...n.grants]),o)this.#C(new Date().toISOString());else if(this.#f)this.#V();if(this.#d("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.#c)return;if(n)this.#a("bound");else this.#a("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.#s=void 0;let r=this.#h;if(this.#z(),this.#c++,this.#a("none"),r!==this.#h)return;if(this.#K&&P.has(n))this.#W(n,1);else this.#d("disconnected",n)}}}}export{A as TabMcp,m as VERSION};
1
+ var O,b,g,f=(e,t)=>{for(var[i,n,r]of O||[])for(var o=[e],a=globalThis,s=a.document,c,h,u,d,l;h=o.pop();)if(!b[h]&&(u=n[h])){b[h]=1;for(d=1;d<u.length;d++)o.push(r[u[d]]);if(!t&&h!==e&&(c=s&&s.head)){if(g===void 0)g=(d=s.querySelector("meta[property=csp-nonce]"))&&(d.nonce||d.getAttribute("nonce"))||"";if(l=s.createElement("link"),l.rel="modulepreload",l.crossOrigin="",g)l.nonce=g;l.href=new a.URL(u[0],i),c.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]),b||={},f(t[n],1)};k(import.meta.url,["1c7n5xsv","jtsqzqas","vxpnd3ex","3reh9k1f","zrz65vva","gdj1e1wh","yjcmhpdf","q758jr4g"],[["./tab-mcp-client.min.js"],["./webmcp-jtsqzqas.min.js"],["./connection-vxpnd3ex.min.js"],["./connect-3reh9k1f.min.js",5,6,7],["./confirm-zrz65vva.min.js",5,6,7],["./tab-mcp-client-gdj1e1wh.min.js"],["./tab-mcp-client-yjcmhpdf.min.js",5],["./tab-mcp-client-q758jr4g.min.js"]],0);
2
+ var L=/^[A-Za-z0-9_.-]{1,128}$/;function m(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var D=/^(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||!D.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 a=o.patternProperties;if(m(a))n.push(...Object.keys(a));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 a=o.slice(1);if(!(a===""||(a.startsWith("/")?N(e,a)!==void 0:t.has(a))))return`$ref ${JSON.stringify(o)} does not resolve`}return}function _(e){if(!m(e))throw TypeError("registerTool: the tool must be an object");let{name:t,title:i,description:n,inputSchema:r,outputSchema:o,execute:a,annotations:s}=e;if(typeof t!=="string"||!L.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 a!=="function")throw TypeError(`registerTool: tool ${t} needs an execute function`);let c=(d,l)=>{if(!m(d)||d.type!=="object")throw TypeError(`registerTool: the ${l} of ${t} must be a JSON Schema object with "type": "object"`);let p;try{p=JSON.parse(JSON.stringify(d))}catch{throw TypeError(`registerTool: the ${l} of ${t} must be JSON`)}let C=H(p);if(C!==void 0)throw TypeError(`registerTool: the ${l} of ${t}: ${C}`);return p},h=c(r??{type:"object"},"inputSchema");if(s!==void 0&&!m(s))throw TypeError(`registerTool: the annotations of ${t} must be an object`);let u={};for(let[d,l]of Object.entries(s??{}))if(typeof l==="boolean")u[d]=l;else if(l!==void 0&&/Hint$|^debugging$/.test(d))throw TypeError(`registerTool: ${d} of ${t} must be a boolean`);return{name:t,title:i,description:n,inputSchema:h,outputSchema:o===void 0?void 0:c(o,"outputSchema"),annotations:u,execute:a}}class T{#e=new Map;#i=new Set;#m;register(e,t={}){let{signal:i,exposedTo:n}=t,r=t.callers&&[...t.callers];if("webmcp"in t||r?.some((a)=>!/^(relay|local|webmcp)$/.test(a)))throw TypeError('registerTool: callers must be "relay", "local" or "webmcp"; option webmcp is gone');let o={..._(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.#i.add(e),()=>this.#i.delete(e)}#y(){for(let e of[...this.#i])e()}}var z=/^[A-Za-z0-9_-]{43}$/;function G(e){return btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function J(){return G(crypto.getRandomValues(new Uint8Array(32)))}function K(e){return typeof e==="string"&&z.test(e)}function U(){try{return globalThis.localStorage??null}catch{return null}}class S{storage;key;#e;#i=!1;constructor(e,t){this.storage=e===void 0?U():e,this.key=t}current(){if(this.#i)return this.#e;let e=null;try{e=this.storage?.getItem(this.key)??null}catch{}if(K(e))return this.#e=e,e;return this.#e}rotate(){let e=J();this.#e=e,this.#i=!0;try{this.storage?.setItem(this.key,e),this.#i=!1}catch{}return e}}var I="0.24.0";var M="@ractive-ch/tab-mcp-client",y=I;function W(){try{return Object.getOwnPropertyDescriptor(Document.prototype,"modelContext")?.get?.call(document)}catch{return}}var V=new Set(["localhost","127.0.0.1","[::1]"]),q=1000,w={reconnectDelaysMs:[5000,1e4,20000,40000,60000],answerTimeoutMs:15000,siblingGraceMs:q},P=new Set(["network","heartbeat","shutdown"]);function F(e){return Object.freeze({...e,client:Object.freeze({...e.client})})}function Y(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 Z=/^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;function Q(e){return e.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,32).replace(/-$/,"")}function X(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&&!V.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 ee(e){try{return new URL(e).host}catch{return""}}function te(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 v(){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 T;#i;#m;#y;#R;#G;#b;#w;#g;#J;#v=!1;#T;#I;#S="none";#M;#c=0;#r="disconnected";#s;#l=Object.freeze([]);#f=!1;#P;#x;#A=!1;#k=!1;#n;#o;#h=0;#K;#u;#p;#L;#$;#E;#D={registry:this.#e,confirm:(e)=>this.#X(e),onConfirm:()=>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:X(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&&!Y(i))throw TypeError("TabMcp: appName must be 1-64 characters without control characters");let r=e.app??Q(t.name);if(e.app!==void 0?typeof r!=="string"||!Z.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.#i={...t},this.#y=i,this.#R=e.onConfirm,this.#G=e.alwaysAllow,this.#b=e.ui,this.#I=e.identityAssertion,this.#K=e.reconnect!==!1,n!==void 0){let s=e.storageKey??`tab-mcp:secret:${n.origin}:${encodeURIComponent(t.name)}`;this.#g=new S(e.storage,s),this.#J=e.storage===null?void 0:`${s}#tabs`}if(this.#e.onChange(()=>this.#t("toolschange",{tools:this.tools})),e.webmcp===!1)return;let o=()=>{let s=W();if(s===void 0)return;globalThis.document?.removeEventListener("tab-mcp-webmcp",o),a(s)};globalThis.document?.addEventListener("tab-mcp-webmcp",o);let a=(s)=>(f("jtsqzqas"),import("./webmcp-jtsqzqas.min.js")).then((c)=>c.mirror(this.#e,s,(h,u,d,l)=>this.#N().then((p)=>p.callFromWebMcp(this.#D,h,u,d,l)),this,r,e,y),(c)=>console.warn("tab-mcp: no tools are offered through WebMCP:",c));o()}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.#r}get session(){return this.#s}get grants(){return this.#l}get reconnecting(){return this.#u}get identity(){return this.#S}get identityMessage(){return this.#M}refreshIdentity(){let e=this.#s,t=this.#I;if(t===void 0)return Promise.reject(TypeError("TabMcp: no identityAssertion"));if(e===void 0)return E();let i=++this.#c,n=this.#n;this.#a("pending");let r=setTimeout(()=>{if(i!==this.#c||this.#S!=="pending")return;this.#c++,this.#a("none")},w.answerTimeoutMs);return new Promise((o)=>{let a=(s)=>{let{identity:c}=s.detail;if(c==="pending")return;this.removeEventListener("identitychange",a),clearTimeout(r),o(c)};this.addEventListener("identitychange",a),Promise.resolve().then(()=>t({address:e.address,sessionId:e.sessionId})).then((s)=>{if(i!==this.#c||this.#n!==n)return;if(typeof s!=="string"||s===""){this.#a("none");return}if(n?.send({type:"identity",assertion:s,round:i})!==!0)this.#a("none")},(s)=>{if(i!==this.#c)return;this.#t("error",{error:s instanceof Error?s:Error(String(s))}),this.#a("none")})})}signOut(){return this.#c++,this.#a("none"),this.#s?.pairing==="oidc"?this.#q({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 v();if(this.#r==="connected"&&this.#s!==void 0)return Promise.resolve(this.#s);if(this.#u!==void 0)return this.#k||=e.resume!==!0,this.#H();if(this.#o!==void 0)return this.#o;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.#d("connecting");let e=this.#U(this.#h);return this.#o=e,e.then(()=>{if(this.#o===e)this.#o=void 0},()=>{if(this.#o!==e)return;if(this.#o=void 0,this.#n=void 0,!this.#u)this.#d("disconnected")}),e}async#N(){let e=await (f("vxpnd3ex"),import("./connection-vxpnd3ex.min.js"));for(let t of e.compileRegistry(this.#e))this.#t("error",{error:t});return this.#$=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 v();let o=t??this.#g.current()??this.#g.rotate(),a=await n(o);if(e!==this.#h)throw new DOMException("The connection was cancelled","AbortError");let s={},c=i(this.#ee(s),r,o,{address:a,revokeAll:!!t,siblingGraceMs:w.siblingGraceMs});if(!t)s.connection=c;return this.#n=c,c.ready}get hasRelay(){return this.#w!==void 0}serve(e,t){return this.#N().then((i)=>i.servePort({...this.#D,server:this.#i,error:(n)=>this.#t("error",{error:n})},e,t))}disconnect(){this.#B("user")}disconnectAll(){let e=this.#g;if(!e)return v();return this.#T??=this.#Y(e).finally(()=>{this.#T=void 0})}async#Y(e){let t=this.#r!=="disconnected"||this.#v,i=e.current();this.#B("disconnect_all");let n=this.#h;if(i){this.#d("connecting");try{await this.#U(n,i)}catch(r){if(n===this.#h)this.#d("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.#d("disconnected")}#B(e){this.#_(),this.#v=!1,this.#h++;let t=this.#n;if(this.#n=void 0,this.#o=void 0,t?.close(e),this.#r==="disconnected")return;this.#s=void 0,this.#z(),this.#c++,this.#a("none"),this.#d("disconnected",e)}#W(e,t){let i=w.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.#d("reconnecting",t>1?void 0:e)}#H(){if(clearTimeout(this.#p),this.#p=void 0,this.#o!==void 0)return this.#o;let e=this.#j();return e.catch((t)=>{let i=this.#u;if(i===void 0||this.#o!==void 0)return;let n=t?.reason;if(n===void 0||P.has(n)){this.#W(i.reason,i.attempt+1);return}if(this.#_(),this.#r="disconnected",this.#t("error",{error:t instanceof Error?t:Error(String(t))}),this.#r==="disconnected")this.#t("statechange",{state:"disconnected"})}),e}#Z(){this.#L??=this.#$?.onWake(()=>{if(this.#p!==void 0)this.#H().catch(()=>{})})}#_(){clearTimeout(this.#p),this.#p=void 0,this.#L?.(),this.#L=void 0,this.#u=void 0}startPairing(){if(this.#f=!0,this.#A=!1,this.#r==="connected")this.#V()}#V(){this.#C(void 0),this.#A=this.#s?.pairing==="oidc",this.#n?.send({type:"pairing.start"})}stopPairing(){if(!this.#f)return;if(this.#f=!1,this.#r==="connected")this.#n?.send({type:"pairing.stop"});this.#z()}#z(){this.#F(void 0),this.#C(void 0)}revoke(e){let t=()=>!this.#l.some((i)=>i.grantId===e);return t()?Promise.resolve():this.#q({type:"grant.revoke",grantId:e},t)}#q(e,t){return!this.#s||this.#n?.send(e)!==!0?E():this.#$.answer(this,e,t,()=>this.#r==="connected",w.answerTimeoutMs)}showConnectDialog(e={}){if(this.#w===void 0)return v();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("3reh9k1f"),import("./connect-3reh9k1f.min.js"));await i(this,t,e,this.#i.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}))}#d(e,t){if(this.#r===e&&e!=="reconnecting")return;this.#r=e,this.#t("statechange",t?{state:e,reason:t}:{state:e})}#a(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(F)),this.#t("grantschange",{grants:this.#l})}#X(e){let t=this.#R;return (f("zrz65vva"),import("./confirm-zrz65vva.min.js")).then((i)=>i.confirmCall(this,e,t),()=>t?.(e)??!1)}get _allowed(){return[this.#e,this.#g,this.#G]}get _ui(){return this.#b}confirmInPage(e,t={}){if(e.client.kind==="webmcp")return Promise.resolve(!0);let i=t.document??globalThis.document;if(i===void 0)return Promise.resolve(!1);return (f("zrz65vva"),import("./confirm-zrz65vva.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.#D,server:this.#i,app:this.#m,appName:this.#y,tabs:this.#J,library:{name:M,version:y},clientFor:(n)=>{let r=this.#l.find((a)=>a.grantId===n.grantId),o={kind:"relay",grantId:n.grantId,id:n.clientId,host:ee(n.clientId)};if(r!==void 0)o.name=r.client.name;return o},sessionStarted:(n)=>{let r=te(n);if(!t())return r;this.#s=r,this.#v=!1;let o=this.#f&&this.#u&&!this.#k&&this.#A&&r.pairing==="oidc";if(this.#k=!1,this.#_(),this.#O([...n.grants]),o)this.#C(new Date().toISOString());else if(this.#f)this.#V();if(this.#d("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.#c)return;if(n)this.#a("bound");else this.#a("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.#s=void 0;let r=this.#h;if(this.#z(),this.#c++,this.#a("none"),r!==this.#h)return;if(this.#K&&P.has(n))this.#W(n,1);else this.#d("disconnected",n)}}}}export{A as TabMcp,y as VERSION};
3
3
 
4
- //# debugId=35F1CD4B55C1C8BC64756E2164756E21
4
+ //# debugId=64C4A36AB2EAA10964756E2164756E21
5
5
  //# sourceMappingURL=tab-mcp-client.min.js.map
@@ -5,9 +5,9 @@
5
5
  "/**\n * The tool registry, mirroring WebMCP's `registerTool(tool, { signal })`\n * (DEC-010). Part of the eagerly loaded core.\n */\n\nimport type {\n\tJsonSchema,\n\tRegisterToolOptions,\n\tTool,\n\tToolAnnotations,\n\tToolCaller,\n} from \"./types.ts\";\n\nconst NAME = /^[A-Za-z0-9_.-]{1,128}$/;\n\n/** A validated tool as the registry keeps it. */\nexport interface RegisteredTool {\n\treadonly name: string;\n\treadonly title: string | undefined;\n\treadonly description: string;\n\treadonly inputSchema: JsonSchema;\n\treadonly outputSchema?: JsonSchema | undefined;\n\treadonly annotations: ToolAnnotations;\n\treadonly execute: Tool[\"execute\"];\n\t/**\n\t * `RegisterToolOptions.callers`, copied; `undefined`: the default, which\n\t * `toolsFor` (serve.ts, the relay and a port) and `mirror` (webmcp.ts) apply.\n\t */\n\treadonly callers?: readonly ToolCaller[] | undefined;\n\t/** `RegisterToolOptions.exposedTo`, passed on to the native registration. */\n\treadonly exposedTo?: string[] | undefined;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n\treturn typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** Keywords whose values are data, not schemas (CC 13). */\nconst DATA = /^(default|examples|const|enum)$/;\n/** Keywords whose values map names to schemas: the names are not keywords. */\nconst NAMED =\n\t/^(properties|patternProperties|\\$defs|definitions|dependentSchemas)$/;\n\n/**\n * Calls `visit` for every schema object in `node`, itself included. The\n * values of `default`, `examples`, `const` and `enum` are data and are\n * skipped. An array, or the map under `properties` and the like (`map`), is\n * not a schema itself: its values are, and its keys are names, not keywords.\n */\nfunction eachSchema(\n\tnode: unknown,\n\tvisit: (schema: Record<string, unknown>) => void,\n\tdepth = 0,\n\tmap = false,\n): void {\n\tif (depth > 64 || typeof node !== \"object\" || node === null) return;\n\tmap ||= Array.isArray(node);\n\tif (!map) visit(node as Record<string, unknown>);\n\tfor (const [key, value] of Object.entries(node))\n\t\tif (map || !DATA.test(key))\n\t\t\teachSchema(value, visit, depth + 1, !map && NAMED.test(key));\n}\n\n/** A JSON pointer (`/a/b~1c`) inside `root`, or `undefined`. */\nfunction resolvePointer(root: unknown, pointer: string): unknown {\n\tlet node: unknown = root;\n\tfor (const raw of pointer.split(\"/\").slice(1)) {\n\t\tlet key: string;\n\t\ttry {\n\t\t\tkey = decodeURIComponent(raw);\n\t\t} catch {\n\t\t\treturn undefined; // a malformed `%`\n\t\t}\n\t\tkey = key.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n\t\tif (typeof node !== \"object\" || node === null || !Object.hasOwn(node, key))\n\t\t\treturn undefined;\n\t\tnode = (node as Record<string, unknown>)[key];\n\t}\n\treturn node;\n}\n\n/**\n * What the validator (loaded only on `connect()`) would throw on later, found\n * now so that a bad schema fails registration: patterns that are not\n * regular expressions, and `$ref`s that do not resolve inside the schema.\n * Without `$id`s; once the validator is loaded, it checks too (`setCompiler`).\n * Also `x-mcp-header`, which makes the relay validate headers it does not\n * know; not supported in v1.\n */\nfunction schemaProblem(root: unknown): string | undefined {\n\tconst anchors = new Set<string>();\n\tconst refs: string[] = [];\n\tconst patterns: string[] = [];\n\tlet header = false;\n\teachSchema(root, (o) => {\n\t\tif (typeof o[\"$anchor\"] === \"string\") anchors.add(o[\"$anchor\"]);\n\t\tif (typeof o[\"$ref\"] === \"string\") refs.push(o[\"$ref\"]);\n\t\tif (typeof o[\"pattern\"] === \"string\") patterns.push(o[\"pattern\"]);\n\t\tconst pp = o[\"patternProperties\"];\n\t\tif (isPlainObject(pp)) patterns.push(...Object.keys(pp));\n\t\tif (\"x-mcp-header\" in o) header = true;\n\t});\n\tif (header) return \"x-mcp-header is not supported by tab-mcp\";\n\tfor (const p of patterns) {\n\t\ttry {\n\t\t\tnew RegExp(p, \"u\");\n\t\t} catch {\n\t\t\treturn `pattern ${JSON.stringify(p)} is not a valid regular expression`;\n\t\t}\n\t}\n\tfor (const ref of refs) {\n\t\tif (!ref.startsWith(\"#\"))\n\t\t\treturn `$ref ${JSON.stringify(ref)} points outside the schema`;\n\t\tconst target = ref.slice(1);\n\t\tconst found =\n\t\t\ttarget === \"\" ||\n\t\t\t(target.startsWith(\"/\")\n\t\t\t\t? resolvePointer(root, target) !== undefined\n\t\t\t\t: anchors.has(target));\n\t\tif (!found) return `$ref ${JSON.stringify(ref)} does not resolve`;\n\t}\n\treturn undefined;\n}\n\n/** Validate a tool; throws a `TypeError` naming the problem. */\nexport function validateTool(tool: Tool): RegisteredTool {\n\tif (!isPlainObject(tool))\n\t\tthrow new TypeError(\"registerTool: the tool must be an object\");\n\tconst {\n\t\tname,\n\t\ttitle,\n\t\tdescription,\n\t\tinputSchema,\n\t\toutputSchema,\n\t\texecute,\n\t\tannotations,\n\t} = tool;\n\tif (typeof name !== \"string\" || !NAME.test(name)) {\n\t\tthrow new TypeError(\n\t\t\t`registerTool: the name must be 1–128 characters of A–Z, a–z, 0–9, \"_\", \"-\" or \".\" (got ${JSON.stringify(name)})`,\n\t\t);\n\t}\n\tif (typeof description !== \"string\" || description.trim() === \"\") {\n\t\tthrow new TypeError(`registerTool: tool ${name} needs a description`);\n\t}\n\tif (title !== undefined && typeof title !== \"string\") {\n\t\tthrow new TypeError(`registerTool: the title of ${name} must be a string`);\n\t}\n\tif (typeof execute !== \"function\") {\n\t\tthrow new TypeError(`registerTool: tool ${name} needs an execute function`);\n\t}\n\t/**\n\t * An object schema (MCP wants `\"type\": \"object\"`), copied as JSON and\n\t * checked by `schemaProblem`: an AI app compiles the output schema too.\n\t */\n\tconst copy = (schema: unknown, what: string): JsonSchema => {\n\t\tif (!isPlainObject(schema) || schema[\"type\"] !== \"object\") {\n\t\t\tthrow new TypeError(\n\t\t\t\t`registerTool: the ${what} of ${name} must be a JSON Schema object with \"type\": \"object\"`,\n\t\t\t);\n\t\t}\n\t\tlet copied: JsonSchema;\n\t\ttry {\n\t\t\tcopied = JSON.parse(JSON.stringify(schema)) as JsonSchema;\n\t\t} catch {\n\t\t\tthrow new TypeError(`registerTool: the ${what} of ${name} must be JSON`);\n\t\t}\n\t\tconst problem = schemaProblem(copied);\n\t\tif (problem !== undefined)\n\t\t\tthrow new TypeError(`registerTool: the ${what} of ${name}: ${problem}`);\n\t\treturn copied;\n\t};\n\tconst copied = copy(inputSchema ?? { type: \"object\" }, \"inputSchema\");\n\tif (annotations !== undefined && !isPlainObject(annotations)) {\n\t\tthrow new TypeError(\n\t\t\t`registerTool: the annotations of ${name} must be an object`,\n\t\t);\n\t}\n\t// A hint that is not a boolean is refused, not dropped: a dropped\n\t// `consequentialHint: \"true\"` would run the tool without asking (CC 2).\n\t// Every key ending in `Hint`, and `debugging`, counts as a hint, also\n\t// one tab-mcp does not know (a later draft's, or a misspelt one); other\n\t// keys that are not booleans are ignored.\n\tconst hints: ToolAnnotations = {};\n\tfor (const [key, value] of Object.entries(annotations ?? {})) {\n\t\tif (typeof value === \"boolean\")\n\t\t\t(hints as Record<string, boolean>)[key] = value;\n\t\telse if (value !== undefined && /Hint$|^debugging$/.test(key))\n\t\t\tthrow new TypeError(`registerTool: ${key} of ${name} must be a boolean`);\n\t}\n\treturn {\n\t\tname,\n\t\ttitle,\n\t\tdescription,\n\t\tinputSchema: copied,\n\t\toutputSchema:\n\t\t\toutputSchema === undefined\n\t\t\t\t? undefined\n\t\t\t\t: copy(outputSchema, \"outputSchema\"),\n\t\tannotations: hints,\n\t\texecute,\n\t};\n}\n\n/** The validator's check of a schema: throws a `TypeError` naming the problem. */\nexport type SchemaCompiler = (tool: RegisteredTool) => void;\n\nexport class ToolRegistry {\n\treadonly #tools = new Map<string, RegisteredTool>();\n\treadonly #listeners = new Set<() => void>();\n\t#compile: SchemaCompiler | undefined;\n\n\t/**\n\t * Register a tool; throws `TypeError` for an invalid tool, an\n\t * `InvalidStateError` `DOMException` for a duplicate name and the abort\n\t * reason for an aborted signal (as WebMCP).\n\t */\n\tregister(tool: Tool, options: RegisterToolOptions = {}): void {\n\t\tconst { signal, exposedTo } = options;\n\t\t// A copy: the page's array may change later, what was registered does\n\t\t// not. Not a list: the spread throws a `TypeError` itself.\n\t\tconst callers = options.callers && [...options.callers];\n\t\t// The option of 0.15 and before, refused rather than ignored: an ignored\n\t\t// `webmcp: false` would put the tool into WebMCP (DEC-165).\n\t\tif (\n\t\t\t\"webmcp\" in options ||\n\t\t\tcallers?.some((c) => !/^(relay|local|webmcp)$/.test(c))\n\t\t)\n\t\t\tthrow new TypeError(\n\t\t\t\t'registerTool: callers must be \"relay\", \"local\" or \"webmcp\"; option webmcp is gone',\n\t\t\t);\n\t\tconst registered: RegisteredTool = {\n\t\t\t...validateTool(tool),\n\t\t\tcallers,\n\t\t\texposedTo,\n\t\t};\n\t\tsignal?.throwIfAborted();\n\t\tif (this.#tools.has(registered.name)) {\n\t\t\tthrow new DOMException(\n\t\t\t\t`registerTool: a tool named ${registered.name} is already registered`,\n\t\t\t\t\"InvalidStateError\",\n\t\t\t);\n\t\t}\n\t\tthis.#compile?.(registered);\n\t\tthis.#tools.set(registered.name, registered);\n\t\tsignal?.addEventListener(\"abort\", () => this.remove(registered), {\n\t\t\tonce: true,\n\t\t});\n\t\tthis.#changed();\n\t}\n\n\t/**\n\t * The validator is loaded: from now on each schema is compiled when it is\n\t * registered, and a tool it refuses is refused (DEC-086).\n\t */\n\tsetCompiler(compile: SchemaCompiler): void {\n\t\tthis.#compile ??= compile;\n\t}\n\n\t/** Unregister this tool, if it still is. */\n\tremove(tool: RegisteredTool): void {\n\t\tif (this.#tools.get(tool.name) !== tool) return;\n\t\tthis.#tools.delete(tool.name);\n\t\tthis.#changed();\n\t}\n\n\tget(name: string): RegisteredTool | undefined {\n\t\treturn this.#tools.get(name);\n\t}\n\n\t/** Tools in registration order. */\n\tlist(): RegisteredTool[] {\n\t\treturn [...this.#tools.values()];\n\t}\n\n\t/** Listen for changes; returns a function that stops listening. */\n\tonChange(listener: () => void): () => void {\n\t\tthis.#listeners.add(listener);\n\t\treturn () => this.#listeners.delete(listener);\n\t}\n\n\t#changed(): void {\n\t\tfor (const listener of [...this.#listeners]) listener();\n\t}\n}\n",
6
6
  "/**\n * The address secret (DEC-027): 32 random bytes as base64url without padding,\n * kept in `localStorage`. The relay derives the stable address from it.\n */\n\nimport type { SecretStorage } from \"./types.ts\";\n\nconst SECRET = /^[A-Za-z0-9_-]{43}$/;\n/** base64url without padding. */\nexport function base64url(bytes: Uint8Array): string {\n\treturn btoa(String.fromCharCode(...bytes))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.replace(/=+$/, \"\");\n}\n\nexport function newSecret(): string {\n\treturn base64url(crypto.getRandomValues(new Uint8Array(32)));\n}\n\nexport function isSecret(value: unknown): value is string {\n\treturn typeof value === \"string\" && SECRET.test(value);\n}\n\n/** `localStorage`, or `null` where it is missing or blocked. */\nfunction defaultStorage(): SecretStorage | null {\n\ttry {\n\t\tconst storage = (globalThis as { localStorage?: SecretStorage })\n\t\t\t.localStorage;\n\t\treturn storage ?? null;\n\t} catch {\n\t\treturn null; // SecurityError: storage blocked for this page\n\t}\n}\n\n/** Reads, creates and rotates the secret; falls back to memory without storage. */\nexport class SecretStore {\n\t/**\n\t * Where the secret is kept (`null`: memory) and under which key; the\n\t * allowed tools (`always-allowed.ts`) are kept next to it.\n\t */\n\treadonly storage: SecretStorage | null;\n\treadonly key: string;\n\t#memory: string | undefined;\n\t/**\n\t * The last rotation could not be written (quota, blocked, read-only):\n\t * memory holds the new secret for the page's lifetime and storage, which\n\t * may still hold the old one, is not read over it until a write succeeds\n\t * (code review 2026-11-22, CR-02).\n\t */\n\t#unsaved = false;\n\n\tconstructor(storage: SecretStorage | null | undefined, key: string) {\n\t\tthis.storage = storage === undefined ? defaultStorage() : storage;\n\t\tthis.key = key;\n\t}\n\n\t/**\n\t * The current secret, or `undefined` while this page has none (none made\n\t * yet); storage first, so a rotation in another tab is seen, unless the\n\t * last rotation could not be written.\n\t */\n\tcurrent(): string | undefined {\n\t\tif (this.#unsaved) return this.#memory;\n\t\tlet stored: string | null = null;\n\t\ttry {\n\t\t\tstored = this.storage?.getItem(this.key) ?? null;\n\t\t} catch {\n\t\t\t// unreadable: use a page-lifetime secret\n\t\t}\n\t\tif (isSecret(stored)) {\n\t\t\tthis.#memory = stored;\n\t\t\treturn stored;\n\t\t}\n\t\treturn this.#memory;\n\t}\n\n\t/** Make and keep a new secret (`disconnectAll()`). */\n\trotate(): string {\n\t\tconst secret = newSecret();\n\t\tthis.#memory = secret;\n\t\tthis.#unsaved = true;\n\t\ttry {\n\t\t\tthis.storage?.setItem(this.key, secret);\n\t\t\tthis.#unsaved = false;\n\t\t} catch {\n\t\t\t// quota or blocked: the secret lives as long as the page\n\t\t}\n\t\treturn secret;\n\t}\n}\n",
7
7
  "/** The library's name and version, sent in `hello`; the version is package.json's. */\nimport { version } from \"../package.json\" with { type: \"json\" };\n\nexport const LIBRARY_NAME = \"@ractive-ch/tab-mcp-client\";\nexport const VERSION: string = version;\n",
8
- "/**\n * `TabMcp`: the eagerly loaded core (DEC-035). It holds the tool registry, the\n * events, the pairing state and the address secret; `connect()` loads the\n * connection and the MCP handler with a dynamic `import()`.\n */\n\nimport type { CallHost, ConnectionHandle, ConnectionHost } from \"./internal.ts\";\nimport type { GrantRef, SessionMessage, TabMessage } from \"./protocol.ts\";\nimport { ToolRegistry } from \"./registry.ts\";\nimport { SecretStore } from \"./secret.ts\";\nimport type {\n\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 * How long a replaced tab that heard no `claimed` yet waits for one before it\n * reports `replaced`: the sibling's session and this tab's `bye` leave the\n * relay at about the same time, so the message usually comes after the `bye`.\n */\nexport const SIBLING_GRACE_MS = 1_000;\n\n/**\n * The 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()`. `siblingGraceMs`: {@link SIBLING_GRACE_MS}, passed to the\n * connection.\n */\nexport const timing: {\n\treconnectDelaysMs: number[];\n\tanswerTimeoutMs: number;\n\tsiblingGraceMs: number;\n} = {\n\treconnectDelaysMs: [5_000, 10_000, 20_000, 40_000, 60_000],\n\tanswerTimeoutMs: 15_000,\n\tsiblingGraceMs: SIBLING_GRACE_MS,\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 * Unless `webmcp: false`: 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\tonConfirm: () => 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// every tool whose `callers` do not leave \"webmcp\" out (DEC-209). 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 !== false ? 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\tsiblingGraceMs: timing.siblingGraceMs,\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. A WebMCP call resolves `true` unasked\n\t * too, without loading the dialog, as without `onConfirm` (DEC-215). Resolves `false` where there is no document.\n\t */\n\tconfirmInPage(\n\t\trequest: ConfirmRequest,\n\t\toptions: { document?: Document } = {},\n\t): Promise<boolean> {\n\t\tif (request.client.kind === \"webmcp\") return Promise.resolve(true);\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"
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 * How long a replaced tab that heard no `claimed` yet waits for one before it\n * reports `replaced`: the sibling's session and this tab's `bye` leave the\n * relay at about the same time, so the message usually comes after the `bye`.\n */\nexport const SIBLING_GRACE_MS = 1_000;\n\n/**\n * The 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()`. `siblingGraceMs`: {@link SIBLING_GRACE_MS}, passed to the\n * connection.\n */\nexport const timing: {\n\treconnectDelaysMs: number[];\n\tanswerTimeoutMs: number;\n\tsiblingGraceMs: number;\n} = {\n\treconnectDelaysMs: [5_000, 10_000, 20_000, 40_000, 60_000],\n\tanswerTimeoutMs: 15_000,\n\tsiblingGraceMs: SIBLING_GRACE_MS,\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 * Unless `webmcp: false`: 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\tonConfirm: () => 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// every tool whose `callers` do not leave \"webmcp\" out (DEC-209). 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). Without it,\n\t\t// read again when `document` hears \"tab-mcp-webmcp\" (`WEBMCP_EVENT` of\n\t\t// `./extension`, spelt out here so the core imports nothing of it): the\n\t\t// tab-mcp browser extension installed its own late, at a click on its\n\t\t// icon (DEC-223). Only the getter counts then too; the first time it\n\t\t// gives an object, the mirror starts and the listener goes.\n\t\tif (options.webmcp === false) return;\n\t\tconst look = (): void => {\n\t\t\tconst context = nativeContext();\n\t\t\tif (context === undefined) return;\n\t\t\tglobalThis.document?.removeEventListener(\"tab-mcp-webmcp\", look);\n\t\t\tmirrorIn(context);\n\t\t};\n\t\tglobalThis.document?.addEventListener(\"tab-mcp-webmcp\", look);\n\t\tconst mirrorIn = (context: ModelContext) =>\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\tlook();\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\tsiblingGraceMs: timing.siblingGraceMs,\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. A WebMCP call resolves `true` unasked\n\t * too, without loading the dialog, as without `onConfirm` (DEC-215). Resolves `false` where there is no document.\n\t */\n\tconfirmInPage(\n\t\trequest: ConfirmRequest,\n\t\toptions: { document?: Document } = {},\n\t): Promise<boolean> {\n\t\tif (request.client.kind === \"webmcp\") return Promise.resolve(true);\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
- "mappings": ";AAaA,IAAM,EAAO,0BAoBb,SAAS,CAAa,CAAC,EAA0C,CAChE,OAAO,OAAO,IAAM,UAAY,IAAM,MAAQ,CAAC,MAAM,QAAQ,CAAC,EAI/D,IAA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GAAU,KAAK,GAAiB,CAAK,GAE5D,WAAY,CAAC,IAAU,CACtB,GAAI,CAAC,EAAQ,EAAG,OAChB,KAAK,GAAW,CACf,GAAG,KAAK,GAAQ,OAAO,CAAC,IAAM,EAAE,UAAY,EAAM,OAAO,EACzD,CACD,CAAC,GAEF,aAAc,CAAC,IAAY,CAC1B,GAAI,CAAC,EAAQ,EAAG,OAChB,KAAK,GAAW,KAAK,GAAQ,OAAO,CAAC,IAAM,EAAE,UAAY,CAAO,CAAC,GAIlE,SAAU,CAAC,IAAW,CACrB,GAAI,EAAc,KAAK,GAAM,WAAY,CAAM,GAEhD,eAAgB,CAAC,EAAO,EAAO,IAAY,CAC1C,GAAI,CAAC,EAAQ,EAAG,OAGhB,GAAI,IAAU,KAAK,GAAgB,OACnC,GAAI,EAAO,KAAK,GAAa,OAAO,EACpC,KAAK,KAAK,GAAa,UAAW,GAAW,EAAE,GAEhD,MAAO,CAAC,IAAU,CACjB,GAAI,EAAQ,EAAG,KAAK,GAAM,QAAS,CAAE,OAAM,CAAC,GAE7C,OAAQ,CAAC,IAA6B,CACrC,GAAI,CAAC,EAAQ,EAAG,OAChB,GAAI,IAAW,WAAY,KAAK,GAAU,EAAe,GACzD,KAAK,GAAc,OACnB,KAAK,GAAW,OAGhB,IAAM,EAAa,KAAK,GAIxB,GAHA,KAAK,GAAc,EACnB,KAAK,KACL,KAAK,GAAa,MAAM,EACpB,IAAe,KAAK,GAAa,OAIrC,GAAI,KAAK,IAAc,EAAkB,IAAI,CAAM,EAClD,KAAK,GAAmB,EAAQ,CAAC,EAClC,KAAK,KAAK,GAAU,eAAgB,CAAM,EAE5C,EAEF",
11
+ "debugId": "64C4A36AB2EAA10964756E2164756E21",
12
12
  "names": []
13
13
  }
@@ -0,0 +1,4 @@
1
+ var m=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),y=(e)=>typeof e==="string"&&e.length<=256;function C(e){return m(e)&&y(e.name)&&y(e.host)?{name:e.name,host:e.host}:void 0}function g(e){return JSON.stringify(e,(n,o)=>m(o)?Object.fromEntries(Object.entries(o).sort(([s],[r])=>s<r?-1:s>r?1:0)):o)??""}var T=()=>performance.now();class H{#o;#n=[];#t;#e=[];constructor(e){this.#o=e,e.addEventListener("tab-mcp-extension",(n)=>this.#i(n.detail)),e.documentElement?.setAttribute("data-tab-mcp-handshake","1")}join(e){if(this.#n.push(e),this.#t!==void 0)e.set(this.#t);e.mcp.addEventListener("grantschange",()=>this.#s(e,"update")),this.#s(e,"hello")}#s(e,n){let o=this.#o.defaultView?.CustomEvent??CustomEvent;this.#o.dispatchEvent(new o("tab-mcp-page",{detail:JSON.stringify({v:1,type:n,library:e.version,app:e.app,apps:this.#n.filter((s)=>s.app===e.app).flatMap((s)=>s.mcp.grants).slice(0,64).map((s)=>({name:s.client.name,host:s.client.host}))})}))}#i(e){let n;try{n=typeof e==="string"?JSON.parse(e):void 0}catch{return}if(!m(n)||n.v!==1)return;if(n.type==="vouch"||n.type==="claim")this.#a(n);else if(n.type==="withdraw")this.#e=this.#e.filter((o)=>o.nonce!==n.nonce);else if(n.type==="hello"||n.type==="update"){let o=R(n);if(o===null)return;if(g(o)!==g(this.#t)){this.#t=o;for(let s of this.#n)s.set(o)}if(n.type==="hello")for(let s of this.#n)this.#s(s,"update")}}#a(e){let n=C(e.app),{tool:o,nonce:s}=e;if(n===void 0||typeof o!=="string"||typeof s!=="string"||!m(e.arguments))return;if(this.#r(),this.#e.some((r)=>r.nonce===s))return;for(let r of this.#n){let c=r.trust?r.registry.get(o):void 0;if(c===void 0)continue;if(this.#e.push({tool:c,args:g(e.arguments),nonce:s,app:n,at:T(),allowed:e.type==="vouch",whole:e.result==="mcp"}),this.#e.length>16)this.#e.shift();return}}#r(){let e=T();this.#e=this.#e.filter((n)=>e-n.at<=2000)}take(e,n){this.#r();let o=g(n),s=this.#e.findIndex((r)=>r.tool===e&&r.args===o);return s<0?void 0:this.#e.splice(s,1)[0]}}function R(e){if(e.on!==!0)return e.on===!1?void 0:null;let{name:n,apps:o}=e;if(!y(n)||!Array.isArray(o))return null;let s=o.slice(0,64).map(C);if(s.some((r)=>r===void 0))return null;return Object.freeze({name:n,apps:Object.freeze(s.map((r)=>Object.freeze(r))),whileInFront:e.whileInFront!==!1})}var A=new WeakMap;function M(e){let n=globalThis.document;if(n===void 0||globalThis.top!==globalThis.window)return;let o=A.get(n);if(o===void 0)o=new H(n),A.set(n,o);return o.join(e),o}var V=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"];function _(e,n,o,s,r,c,P){let w;Object.defineProperty(s,"extension",{get:()=>w,configurable:!0});let b;try{b=M({version:P,app:r,registry:e,trust:c.trustExtension!==!1,mcp:s,set:(t)=>{w=t,s.dispatchEvent(new CustomEvent("extensionchange",{detail:{extension:t}}))}})}catch(t){console.warn("tab-mcp: no handshake with the browser extension:",t)}let u=new Map,k=new Set,x=new Set,S=(t,i)=>{try{let l=c.onConfirm,h=globalThis.document?.location?.origin,d=(Array.isArray(t.exposedTo)?t.exposedTo:[]).filter((f)=>{try{return new URL(String(f)).origin!==h}catch{return!1}});if(i!==!0||d.length===0||l&&l.own!==!1||x.has(t.name))return;x.add(t.name),console.warn(`tab-mcp: ${t.name} asks before it runs, but documents of ${d.join(", ")} (its exposedTo) can call it through WebMCP without a question: the library asks no WebMCP caller. Refuse such calls in onConfirm, or leave exposedTo off.`)}catch{}},E=()=>{for(let[t,i]of u){if(e.get(t.name)===t)continue;i.abort(),u.delete(t)}for(let t of e.list()){let{annotations:i,callers:l}=t,h=i.consequentialHint??i.destructiveHint;if(u.has(t)||!(l?.includes("webmcp")??!0))continue;let d=new AbortController;u.set(t,d);let f={consequentialHint:h};for(let a of V)f[a]??=i[a];let{signal:p}=d;Promise.resolve().then(()=>p.aborted||n.registerTool({name:t.name,title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:f,execute:(a,v)=>o(t,a,v?.signal,b?.take(t,a))},{signal:p,exposedTo:t.exposedTo})).then(()=>{if(!p.aborted)S(t,h)}).catch((a)=>{if(p.aborted)return;if(k.has(t.name))return;k.add(t.name),console.warn(`tab-mcp: ${t.name} is not offered through WebMCP:`,a)})}};e.onChange(E),E()}export{_ as mirror};
2
+
3
+ //# debugId=1406A2F8B273CCE864756E2164756E21
4
+ //# sourceMappingURL=webmcp-jtsqzqas.min.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/handshake.ts", "../../src/webmcp.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * The page's side of the handshake with the tab-mcp browser extension\n * (DEC-207), in the WebMCP mirror's chunk: only a page that mirrors its\n * tools into WebMCP (unless `webmcp: false`) takes part.\n *\n * Plain DOM events on `document`, each with a JSON string as `detail`\n * (objects do not cross between a content script's world and the page's in\n * every browser): `tab-mcp-page` from the page, `tab-mcp-extension` from\n * the extension. Every message has `v: 1` and a `type`; a message of\n * another version, an unknown type or a malformed one is ignored, and so\n * are unknown fields.\n *\n * - The page announces itself (`hello`: the library's version, the app id,\n * the AI apps connected to it directly) when it starts, again (`update`)\n * when those apps change, and answers the extension's `hello` with an\n * `update`. It marks `<html data-tab-mcp-handshake>`, so that an\n * extension that starts later (its content script comes at\n * `document_idle`, or with a click) knows it may speak without having\n * heard the `hello`.\n * - The extension says what it is and which AI apps are connected to it\n * (`hello`, `update`), and, right before it runs a page tool the user\n * allowed there, `vouch`: the tool, the exact arguments, a nonce and the\n * AI app; right before one it runs without asking (read-only for it),\n * `claim` with the same fields (DEC-224); once that call ended or failed,\n * `withdraw` with the nonce, and one still unused is dropped. With\n * `result: \"mcp\"` on either, the call resolves with the whole MCP result\n * (pictures too), which the extension passes on; without it (an older\n * extension), with the value any WebMCP caller gets. A `claim` only\n * names the caller and asks for the whole result: `onConfirm` decides as\n * for any WebMCP call. It speaks only while it serves the\n * page (DEC-221): while its AI access is off the page hears nothing, as\n * without the extension, except `on: false` once if it was told \"on\".\n * - Each side cuts the other's list of AI apps to 64 and sends no more.\n *\n * No proof of who sent what: anything that could fake the extension runs in\n * the page already, where it could skip any check. A convenience between\n * two parts the user trusts, not a security boundary.\n */\n\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\nimport type { BrowserExtension, Grant } from \"./types.ts\";\n\n/** From the page to the extension. */\nexport const PAGE_EVENT = \"tab-mcp-page\";\n/** From the extension to the page. */\nexport const EXTENSION_EVENT = \"tab-mcp-extension\";\n/** On `<html>`: this page takes part (for an extension that starts later). */\nexport const MARK = \"data-tab-mcp-handshake\";\n/** A vouch is kept this long (milliseconds), then dropped unused. */\nexport const VOUCH_MS = 2_000;\n/** At most this many vouches wait; beyond, the oldest goes. */\nconst MAX_VOUCHES = 16;\n/** Texts from the extension are taken up to these lengths, apps up to this count either way. */\nconst MAX_TEXT = 256;\nconst MAX_APPS = 64;\n\n/** One `TabMcp` of the page, as the handshake sees it. */\nexport interface HandshakePage {\n\t/** The library's version. */\n\treadonly version: string;\n\treadonly app: string;\n\treadonly registry: ToolRegistry;\n\t/** Vouches are taken for its tools (`trustExtension`). */\n\treadonly trust: boolean;\n\t/** The `TabMcp`: its `grants` and `grantschange`. */\n\treadonly mcp: EventTarget & { readonly grants: readonly Grant[] };\n\t/** The extension's state changed. */\n\tset(extension: BrowserExtension | undefined): void;\n}\n\n/** The AI app a vouched call came from. */\nexport interface VouchedBy {\n\tname: string;\n\thost: string;\n}\n\n/** A call the extension announced, as its WebMCP call takes it. */\nexport interface Vouched {\n\tapp: VouchedBy;\n\t/**\n\t * The user allowed it in the extension (`vouch`): it runs without\n\t * `onConfirm`. `false` for a `claim`, a call the extension made without\n\t * asking (it took the tool for read-only): `onConfirm` decides as for\n\t * any WebMCP call.\n\t */\n\tallowed: boolean;\n\t/** The extension takes the whole MCP result (`result: \"mcp\"`, DEC-224). */\n\twhole: boolean;\n}\n\ninterface Vouch extends Vouched {\n\ttool: RegisteredTool;\n\t/** The arguments, canonical (`canonical`). */\n\targs: string;\n\tnonce: string;\n\tat: number;\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst text = (value: unknown): value is string =>\n\ttypeof value === \"string\" && value.length <= MAX_TEXT;\n\n/** An AI app as the extension names it; `undefined` if it is malformed. */\nfunction appOf(value: unknown): VouchedBy | undefined {\n\treturn isObject(value) && text(value[\"name\"]) && text(value[\"host\"])\n\t\t? { name: value[\"name\"], host: value[\"host\"] }\n\t\t: undefined;\n}\n\n/**\n * `value` as JSON with the keys of every object sorted: two argument\n * objects are equal when their canonical forms are.\n */\nexport function canonical(value: unknown): string {\n\treturn (\n\t\tJSON.stringify(value, (_key, v: unknown) =>\n\t\t\tisObject(v)\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n\t\t\t\t\t)\n\t\t\t\t: v,\n\t\t) ?? \"\"\n\t);\n}\n\n/** Monotonic milliseconds: a vouch's age must not follow the wall clock. */\nconst now = () => performance.now();\n\nclass Handshake {\n\treadonly #doc: Document;\n\treadonly #pages: HandshakePage[] = [];\n\t#extension: BrowserExtension | undefined;\n\t#vouches: Vouch[] = [];\n\n\tconstructor(doc: Document) {\n\t\tthis.#doc = doc;\n\t\tdoc.addEventListener(EXTENSION_EVENT, (event) =>\n\t\t\tthis.#heard((event as CustomEvent).detail),\n\t\t);\n\t\tdoc.documentElement?.setAttribute(MARK, \"1\");\n\t}\n\n\tjoin(page: HandshakePage): void {\n\t\tthis.#pages.push(page);\n\t\tif (this.#extension !== undefined) page.set(this.#extension);\n\t\tpage.mcp.addEventListener(\"grantschange\", () => this.#say(page, \"update\"));\n\t\tthis.#say(page, \"hello\");\n\t}\n\n\t#say(page: HandshakePage, type: \"hello\" | \"update\"): void {\n\t\t// The document's own `CustomEvent`: a document may take only events\n\t\t// of its realm.\n\t\tconst Custom = this.#doc.defaultView?.CustomEvent ?? CustomEvent;\n\t\tthis.#doc.dispatchEvent(\n\t\t\tnew Custom(PAGE_EVENT, {\n\t\t\t\tdetail: JSON.stringify({\n\t\t\t\t\tv: 1,\n\t\t\t\t\ttype,\n\t\t\t\t\tlibrary: page.version,\n\t\t\t\t\tapp: page.app,\n\t\t\t\t\t// Of every `TabMcp` of this app: the extension keeps one list\n\t\t\t\t\t// per app, and one made and dropped (React's strict mode, a\n\t\t\t\t\t// provider whose relay changed) has none. Capped as the\n\t\t\t\t\t// extension cuts what it hears: more would not be heard anyway.\n\t\t\t\t\tapps: this.#pages\n\t\t\t\t\t\t.filter((p) => p.app === page.app)\n\t\t\t\t\t\t.flatMap((p) => p.mcp.grants)\n\t\t\t\t\t\t.slice(0, MAX_APPS)\n\t\t\t\t\t\t.map((g) => ({ name: g.client.name, host: g.client.host })),\n\t\t\t\t}),\n\t\t\t}),\n\t\t);\n\t}\n\n\t#heard(detail: unknown): void {\n\t\tlet m: unknown;\n\t\ttry {\n\t\t\tm = typeof detail === \"string\" ? JSON.parse(detail) : undefined;\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (!isObject(m) || m[\"v\"] !== 1) return;\n\t\tif (m[\"type\"] === \"vouch\" || m[\"type\"] === \"claim\") this.#vouch(m);\n\t\t// The call it was for ended or never reached the page: an unused vouch\n\t\t// must not wait its 2 s for another caller.\n\t\telse if (m[\"type\"] === \"withdraw\")\n\t\t\tthis.#vouches = this.#vouches.filter((v) => v.nonce !== m[\"nonce\"]);\n\t\telse if (m[\"type\"] === \"hello\" || m[\"type\"] === \"update\") {\n\t\t\tconst extension = extensionOf(m);\n\t\t\tif (extension === null) return;\n\t\t\tif (canonical(extension) !== canonical(this.#extension)) {\n\t\t\t\tthis.#extension = extension;\n\t\t\t\tfor (const page of this.#pages) page.set(extension);\n\t\t\t}\n\t\t\tif (m[\"type\"] === \"hello\")\n\t\t\t\tfor (const page of this.#pages) this.#say(page, \"update\");\n\t\t}\n\t}\n\n\t/**\n\t * A vouch, kept for the tool registered under its name now, by a page\n\t * that takes vouches: a tool registered anew after this does not get it.\n\t */\n\t#vouch(m: Record<string, unknown>): void {\n\t\tconst app = appOf(m[\"app\"]);\n\t\tconst name = m[\"tool\"];\n\t\tconst nonce = m[\"nonce\"];\n\t\tif (\n\t\t\tapp === undefined ||\n\t\t\ttypeof name !== \"string\" ||\n\t\t\ttypeof nonce !== \"string\" ||\n\t\t\t!isObject(m[\"arguments\"])\n\t\t)\n\t\t\treturn;\n\t\tthis.#drop();\n\t\t// The same vouch heard twice counts once.\n\t\tif (this.#vouches.some((v) => v.nonce === nonce)) return;\n\t\tfor (const page of this.#pages) {\n\t\t\tconst tool = page.trust ? page.registry.get(name) : undefined;\n\t\t\tif (tool === undefined) continue;\n\t\t\tthis.#vouches.push({\n\t\t\t\ttool,\n\t\t\t\targs: canonical(m[\"arguments\"]),\n\t\t\t\tnonce,\n\t\t\t\tapp,\n\t\t\t\tat: now(),\n\t\t\t\tallowed: m[\"type\"] === \"vouch\",\n\t\t\t\twhole: m[\"result\"] === \"mcp\",\n\t\t\t});\n\t\t\tif (this.#vouches.length > MAX_VOUCHES) this.#vouches.shift();\n\t\t\treturn;\n\t\t}\n\t}\n\n\t/** Forget the vouches older than `VOUCH_MS`. */\n\t#drop(): void {\n\t\tconst t = now();\n\t\tthis.#vouches = this.#vouches.filter((v) => t - v.at <= VOUCH_MS);\n\t}\n\n\t/**\n\t * The vouch or claim for this call of `tool` with `input`, used up;\n\t * `undefined` if there is none (the call is any WebMCP call).\n\t */\n\ttake(tool: RegisteredTool, input: unknown): Vouched | undefined {\n\t\tthis.#drop();\n\t\tconst args = canonical(input);\n\t\tconst i = this.#vouches.findIndex(\n\t\t\t(v) => v.tool === tool && v.args === args,\n\t\t);\n\t\treturn i < 0 ? undefined : this.#vouches.splice(i, 1)[0];\n\t}\n}\n\n/**\n * The extension's state from its `hello` or `update`: `undefined` when it\n * does not serve the page now, `null` when the message is malformed.\n */\nfunction extensionOf(\n\tm: Record<string, unknown>,\n): BrowserExtension | undefined | null {\n\tif (m[\"on\"] !== true) return m[\"on\"] === false ? undefined : null;\n\tconst { name, apps } = m;\n\tif (!text(name) || !Array.isArray(apps)) return null;\n\tconst list = apps.slice(0, MAX_APPS).map(appOf);\n\tif (list.some((a) => a === undefined)) return null;\n\treturn Object.freeze({\n\t\tname,\n\t\tapps: Object.freeze(list.map((a) => Object.freeze(a as VouchedBy))),\n\t\twhileInFront: m[\"whileInFront\"] !== false,\n\t});\n}\n\nconst handshakes = new WeakMap<Document, Handshake>();\n\n/**\n * The handshake of the page's top-level document, which `page` joins; the\n * extension speaks only to the top frame. `undefined` in a frame or\n * without a document.\n */\nexport function joinHandshake(page: HandshakePage): Handshake | undefined {\n\tconst doc = globalThis.document;\n\tif (doc === undefined || globalThis.top !== globalThis.window)\n\t\treturn undefined;\n\tlet handshake = handshakes.get(doc);\n\tif (handshake === undefined) {\n\t\thandshake = new Handshake(doc);\n\t\thandshakes.set(doc, handshake);\n\t}\n\thandshake.join(page);\n\treturn handshake;\n}\n",
6
+ "/**\n * Mirroring the tools into the browser's own WebMCP (iteration 25, DEC-115,\n * DEC-119, DEC-143): unless `webmcp: false`, each tool that is offered there is\n * also registered with `document.modelContext.registerTool()`, under its own\n * `AbortController`, aborted when the tool leaves the registry. A chunk of\n * its own (DEC-171), loaded by a `TabMcp` whose constructor found native\n * WebMCP (`nativeContext` in the core); a call loads the connection chunk,\n * which checks and runs it. The handshake with the tab-mcp browser\n * extension (`handshake.ts`, DEC-207) is here too: only a page that mirrors\n * takes part.\n */\n\nimport {\n\ttype HandshakePage,\n\tjoinHandshake,\n\ttype Vouched,\n} from \"./handshake.ts\";\nimport type { RegisteredTool, ToolRegistry } from \"./registry.ts\";\nimport type { BrowserExtension } from \"./types.ts\";\n\n/** What the library uses of the browser's `ModelContext`. */\nexport interface ModelContext {\n\tregisterTool(\n\t\ttool: object,\n\t\toptions: { signal: AbortSignal; exposedTo: string[] | undefined },\n\t): unknown;\n}\n\n/**\n * Runs a call of a mirrored tool; `signal` is the browser's, if it gives\n * one; `by`: the tab-mcp browser extension announced it for an AI app\n * (a vouch or a claim).\n */\nexport type WebMcpCall = (\n\ttool: RegisteredTool,\n\tinput: unknown,\n\tsignal: unknown,\n\tby: Vouched | undefined,\n) => Promise<unknown>;\n\n/** The WebMCP hints; the MCP-only ones are left out. */\nconst HINTS = [\n\t\"readOnlyHint\",\n\t\"untrustedContentHint\",\n\t\"consequentialHint\",\n\t\"debugging\",\n] as const;\n\n/**\n * Mirror `registry`'s tools into `context`, now and whenever the registry\n * changes: every tool, unless its `callers` leave `\"webmcp\"` out (DEC-165,\n * DEC-209). A tool that asks is marked `consequentialHint`, so that the agent\n * asks its user; MCP's `destructiveHint` counts as `consequentialHint`\n * (DEC-143). The page's `onConfirm` decides such a call, never the library's\n * dialog (DEC-215). Every failure of the native `registerTool()`\n * stays here: warned once per name, the tool still offered through the relay.\n * The page joins the handshake with the tab-mcp browser extension: `mcp`\n * is its `TabMcp`, `app` its app id, `options` its options\n * (`trustExtension`, and `onConfirm` for the warning below), `version` the\n * library's. A tool that asks, mirrored with an `exposedTo` that names\n * other origins on a page without `onConfirm`, is warned about once per\n * name (`warnUnasked`): documents of those origins can run it, and the\n * library asks no WebMCP caller (DEC-215). The extension's state is `mcp.extension`, defined\n * here on the instance (the core only declares it, for its bytes), and\n * `extensionchange` is sent here.\n */\nexport function mirror(\n\tregistry: ToolRegistry,\n\tcontext: ModelContext,\n\tcall: WebMcpCall,\n\tmcp: HandshakePage[\"mcp\"],\n\tapp: string,\n\toptions: { trustExtension?: boolean; onConfirm?: unknown },\n\tversion: string,\n): void {\n\tlet state: BrowserExtension | undefined;\n\tObject.defineProperty(mcp, \"extension\", {\n\t\tget: () => state,\n\t\tconfigurable: true,\n\t});\n\tlet handshake: ReturnType<typeof joinHandshake>;\n\ttry {\n\t\thandshake = joinHandshake({\n\t\t\tversion,\n\t\t\tapp,\n\t\t\tregistry,\n\t\t\ttrust: options.trustExtension !== false,\n\t\t\tmcp,\n\t\t\tset: (extension) => {\n\t\t\t\tstate = extension;\n\t\t\t\tmcp.dispatchEvent(\n\t\t\t\t\tnew CustomEvent(\"extensionchange\", { detail: { extension } }),\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\t} catch (error) {\n\t\t// The tools are mirrored all the same; no call is vouched for.\n\t\tconsole.warn(\"tab-mcp: no handshake with the browser extension:\", error);\n\t}\n\tconst mirrors = new Map<RegisteredTool, AbortController>();\n\tconst warned = new Set<string>();\n\tconst unasked = new Set<string>();\n\t/**\n\t * The warning about a tool that asks with `exposedTo` (DEC-215), once its\n\t * native registration succeeded (so Chrome accepted every origin), once\n\t * per name. Decided then: a handler the page removes later is not\n\t * caught. Never throws, whatever `exposedTo` holds.\n\t */\n\tconst warnUnasked = (tool: RegisteredTool, asks: boolean | undefined) => {\n\t\ttry {\n\t\t\t// React's provider always passes a handler; `own` says whether the\n\t\t\t// page gave one.\n\t\t\tconst ask = options.onConfirm as { own?: boolean } | undefined;\n\t\t\tconst page = globalThis.document?.location?.origin;\n\t\t\tconst others = (\n\t\t\t\tArray.isArray(tool.exposedTo) ? tool.exposedTo : []\n\t\t\t).filter((entry: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn new URL(String(entry)).origin !== page;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false; // the browser refuses it anyway\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (\n\t\t\t\tasks !== true ||\n\t\t\t\tothers.length === 0 ||\n\t\t\t\t(ask && ask.own !== false) ||\n\t\t\t\tunasked.has(tool.name)\n\t\t\t)\n\t\t\t\treturn;\n\t\t\tunasked.add(tool.name);\n\t\t\tconsole.warn(\n\t\t\t\t`tab-mcp: ${tool.name} asks before it runs, but documents of ${others.join(\", \")} (its exposedTo) can call it through WebMCP without a question: the library asks no WebMCP caller. Refuse such calls in onConfirm, or leave exposedTo off.`,\n\t\t\t);\n\t\t} catch {\n\t\t\t// a warning never stops the mirror\n\t\t}\n\t};\n\tconst sync = (): void => {\n\t\tfor (const [tool, controller] of mirrors) {\n\t\t\tif (registry.get(tool.name) === tool) continue;\n\t\t\tcontroller.abort();\n\t\t\tmirrors.delete(tool);\n\t\t}\n\t\tfor (const tool of registry.list()) {\n\t\t\tconst { annotations, callers } = tool;\n\t\t\tconst consequential =\n\t\t\t\tannotations.consequentialHint ?? annotations.destructiveHint;\n\t\t\t// The one place of the rule for WebMCP (the relay and a port: `toolsFor`).\n\t\t\tif (mirrors.has(tool) || !(callers?.includes(\"webmcp\") ?? true)) continue;\n\t\t\tconst controller = new AbortController();\n\t\t\tmirrors.set(tool, controller);\n\t\t\tconst hints: Record<string, boolean | undefined> = {\n\t\t\t\tconsequentialHint: consequential,\n\t\t\t};\n\t\t\tfor (const key of HINTS) hints[key] ??= annotations[key];\n\t\t\tconst { signal } = controller;\n\t\t\tPromise.resolve()\n\t\t\t\t// Not once unmirrored: whatever the browser does with an aborted\n\t\t\t\t// signal.\n\t\t\t\t.then(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tsignal.aborted ||\n\t\t\t\t\t\tcontext.registerTool(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tname: tool.name,\n\t\t\t\t\t\t\t\t// WebIDL dictionaries: `undefined` is the same as left out.\n\t\t\t\t\t\t\t\ttitle: tool.title,\n\t\t\t\t\t\t\t\tdescription: tool.description,\n\t\t\t\t\t\t\t\tinputSchema: tool.inputSchema,\n\t\t\t\t\t\t\t\toutputSchema: tool.outputSchema,\n\t\t\t\t\t\t\t\tannotations: hints,\n\t\t\t\t\t\t\t\t// The vouch is looked up as the call arrives: it was\n\t\t\t\t\t\t\t\t// sent right before the extension made the call.\n\t\t\t\t\t\t\t\texecute: (input: unknown, options?: { signal?: unknown }) =>\n\t\t\t\t\t\t\t\t\tcall(\n\t\t\t\t\t\t\t\t\t\ttool,\n\t\t\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\t\t\toptions?.signal,\n\t\t\t\t\t\t\t\t\t\thandshake?.take(tool, input),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{ signal, exposedTo: tool.exposedTo },\n\t\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.then(() => {\n\t\t\t\t\tif (!signal.aborted) warnUnasked(tool, consequential);\n\t\t\t\t})\n\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\tif (signal.aborted) return; // unmirrored meanwhile\n\t\t\t\t\tif (warned.has(tool.name)) return;\n\t\t\t\t\twarned.add(tool.name);\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`tab-mcp: ${tool.name} is not offered through WebMCP:`,\n\t\t\t\t\t\terror,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t}\n\t};\n\tregistry.onChange(sync);\n\tsync();\n}\n"
7
+ ],
8
+ "mappings": "AAkGA,IAAM,EAAW,CAAC,IACjB,OAAO,IAAU,UAAY,IAAU,MAAQ,CAAC,MAAM,QAAQ,CAAK,EAE9D,EAAO,CAAC,IACb,OAAO,IAAU,UAAY,EAAM,QAjDnB,IAoDjB,SAAS,CAAK,CAAC,EAAuC,CACrD,OAAO,EAAS,CAAK,GAAK,EAAK,EAAM,IAAO,GAAK,EAAK,EAAM,IAAO,EAChE,CAAE,KAAM,EAAM,KAAS,KAAM,EAAM,IAAQ,EAC3C,OAOG,SAAS,CAAS,CAAC,EAAwB,CACjD,OACC,KAAK,UAAU,EAAO,CAAC,EAAM,IAC5B,EAAS,CAAC,EACP,OAAO,YACP,OAAO,QAAQ,CAAC,EAAE,KAAK,EAAE,IAAK,KAAQ,EAAI,EAAI,GAAK,EAAI,EAAI,EAAI,CAAE,CAClE,EACC,CACJ,GAAK,GAKP,IAAM,EAAM,IAAM,YAAY,IAAI,EAElC,MAAM,CAAU,CACN,GACA,GAA0B,CAAC,EACpC,GACA,GAAoB,CAAC,EAErB,WAAW,CAAC,EAAe,CAC1B,KAAK,GAAO,EACZ,EAAI,iBA7FyB,oBA6FS,CAAC,IACtC,KAAK,GAAQ,EAAsB,MAAM,CAC1C,EACA,EAA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EAAO,IAAI,EAAK,IAAI,EAAG,OAC3B,EAAO,IAAI,EAAK,IAAI,EACpB,QAAQ,KACP,YAAY,EAAK,sCACjB,CACD,EACA,IAGJ,EAAS,SAAS,CAAI,EACtB,EAAK",
9
+ "debugId": "1406A2F8B273CCE864756E2164756E21",
10
+ "names": []
11
+ }
@@ -181,6 +181,14 @@ function webMcpValue(value) {
181
181
  return value.structuredContent ?? (resultText(value, true) || "Done.");
182
182
  return value === undefined ? "Done." : value;
183
183
  }
184
+ function mcpParts(result) {
185
+ const { content, structuredContent, isError } = result;
186
+ return {
187
+ content,
188
+ ...structuredContent ? { structuredContent } : {},
189
+ ...isError ? { isError } : {}
190
+ };
191
+ }
184
192
  function thrownResult(error) {
185
193
  const message = error instanceof Error ? error.message : String(error);
186
194
  return errorResult(message || "The tool failed.");
@@ -441,8 +449,8 @@ async function decideAndRun(context, tool, raw, signal, client) {
441
449
  run.outcome = "error";
442
450
  return run;
443
451
  }
444
- async function webMcpCall(context, tool, input, signal, client) {
445
- const failed = (error) => ({ error });
452
+ async function webMcpCall(context, tool, input, signal, client, whole = false) {
453
+ const failed = (error) => whole ? errorResult(error) : { error };
446
454
  const gone = `The tool ${tool.name} is no longer available.`;
447
455
  if (context.tools.get(tool.name) !== tool)
448
456
  return failed(gone);
@@ -458,8 +466,9 @@ async function webMcpCall(context, tool, input, signal, client) {
458
466
  if (run.stop === "gone")
459
467
  return failed(gone);
460
468
  if (run.result.isError === true)
461
- return failed(resultText(run.result) || "The tool failed.");
462
- return webMcpValue(run.returned?.value);
469
+ return whole ? mcpParts(run.result) : failed(resultText(run.result) || "The tool failed.");
470
+ const value = run.returned?.value;
471
+ return whole && isCallToolResult(value) ? mcpParts(value) : webMcpValue(value);
463
472
  }
464
473
  function createMcpHandler(options) {
465
474
  const { tools, server } = options;
@@ -1234,12 +1243,16 @@ async function addressIdOf(secret, subtle = globalThis.crypto?.subtle ?? null) {
1234
1243
  // src/connection.ts
1235
1244
  function callFromWebMcp(host, tool, input, signal, by) {
1236
1245
  const context = callContext(host, "webmcp");
1237
- return by === undefined ? webMcpCall({ ...context, confirm: host.onConfirm() ?? (() => true) }, tool, input, signal, { kind: "webmcp" }) : webMcpCall({ ...context, confirm: () => true }, tool, input, signal, {
1246
+ return webMcpCall({
1247
+ ...context,
1248
+ confirm: (by?.allowed ? undefined : host.onConfirm()) ?? (() => true)
1249
+ }, tool, input, signal, by === undefined ? { kind: "webmcp" } : {
1238
1250
  kind: "webmcp",
1239
1251
  via: "tab-mcp-extension",
1240
- name: by.name,
1241
- host: by.host
1242
- });
1252
+ name: by.app.name,
1253
+ host: by.app.host,
1254
+ allowed: by.allowed
1255
+ }, by?.whole);
1243
1256
  }
1244
1257
  var CONNECT_TIMEOUT_MS = 15000;
1245
1258
  var CLOSE_REASONS = {
@@ -1590,5 +1603,5 @@ export {
1590
1603
  servePort
1591
1604
  };
1592
1605
 
1593
- //# debugId=B8DD24E28FC2D1CA64756E2164756E21
1594
- //# sourceMappingURL=connection-fnkfrvpc.js.map
1606
+ //# debugId=9BC3A4590FC3BB3C64756E2164756E21
1607
+ //# sourceMappingURL=connection-gqec88qp.js.map